summaryrefslogtreecommitdiffstats
path: root/src/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'src/plugins')
-rw-r--r--src/plugins/bearer/bearer.pro5
-rw-r--r--src/plugins/bearer/connman/connman.pro1
-rw-r--r--src/plugins/bearer/connman/qconnmanengine.cpp16
-rw-r--r--src/plugins/bearer/connman/qconnmanengine.h6
-rw-r--r--src/plugins/bearer/connman/qconnmanservice_linux.cpp14
-rw-r--r--src/plugins/bearer/corewlan/corewlan.pro2
-rw-r--r--src/plugins/bearer/corewlan/qcorewlanengine.mm68
-rw-r--r--src/plugins/bearer/generic/qgenericengine.cpp38
-rw-r--r--src/plugins/bearer/linux_common/qofonoservice_linux.cpp12
-rw-r--r--src/plugins/bearer/nativewifi/qnativewifiengine.cpp2
-rw-r--r--src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp118
-rw-r--r--src/plugins/bearer/networkmanager/qnetworkmanagerengine.h36
-rw-r--r--src/plugins/bearer/networkmanager/qnetworkmanagerservice.cpp30
-rw-r--r--src/plugins/bearer/nla/nla.pro6
-rw-r--r--src/plugins/bearer/qnetworksession_impl.cpp12
-rw-r--r--src/plugins/generic/bsdkeyboard/bsdkeyboard.json3
-rw-r--r--src/plugins/generic/bsdkeyboard/bsdkeyboard.pro16
-rw-r--r--src/plugins/generic/bsdkeyboard/main.cpp59
-rw-r--r--src/plugins/generic/bsdkeyboard/qbsdkeyboard.cpp408
-rw-r--r--src/plugins/generic/bsdkeyboard/qbsdkeyboard.h139
-rw-r--r--src/plugins/generic/bsdkeyboard/qbsdkeyboard_defaultmap.h622
-rw-r--r--src/plugins/generic/bsdmouse/bsdmouse.json3
-rw-r--r--src/plugins/generic/bsdmouse/bsdmouse.pro16
-rw-r--r--src/plugins/generic/bsdmouse/main.cpp58
-rw-r--r--src/plugins/generic/bsdmouse/qbsdmouse.cpp165
-rw-r--r--src/plugins/generic/bsdmouse/qbsdmouse.h70
-rw-r--r--src/plugins/generic/evdevkeyboard/evdevkeyboard.pro2
-rw-r--r--src/plugins/generic/evdevkeyboard/main.cpp2
-rw-r--r--src/plugins/generic/evdevmouse/evdevmouse.pro2
-rw-r--r--src/plugins/generic/evdevmouse/main.cpp2
-rw-r--r--src/plugins/generic/evdevtablet/evdevtablet.pro2
-rw-r--r--src/plugins/generic/evdevtablet/main.cpp2
-rw-r--r--src/plugins/generic/evdevtouch/evdevtouch.pro2
-rw-r--r--src/plugins/generic/evdevtouch/main.cpp2
-rw-r--r--src/plugins/generic/generic.pro15
-rw-r--r--src/plugins/generic/libinput/libinput.pro2
-rw-r--r--src/plugins/generic/libinput/main.cpp2
-rw-r--r--src/plugins/generic/tslib/main.cpp2
-rw-r--r--src/plugins/generic/tslib/tslib.pro4
-rw-r--r--src/plugins/generic/tuiotouch/qoscbundle.cpp23
-rw-r--r--src/plugins/generic/tuiotouch/qoscbundle_p.h19
-rw-r--r--src/plugins/generic/tuiotouch/qoscmessage.cpp25
-rw-r--r--src/plugins/generic/tuiotouch/qoscmessage_p.h18
-rw-r--r--src/plugins/generic/tuiotouch/qtuiocursor_p.h1
-rw-r--r--src/plugins/generic/tuiotouch/qtuiohandler.cpp277
-rw-r--r--src/plugins/generic/tuiotouch/qtuiohandler_p.h8
-rw-r--r--src/plugins/generic/tuiotouch/qtuiotoken_p.h145
-rw-r--r--src/plugins/generic/tuiotouch/tuiotouch.pro4
-rw-r--r--src/plugins/imageformats/gif/gif.pro7
-rw-r--r--src/plugins/imageformats/gif/qgifhandler.cpp1218
-rw-r--r--src/plugins/imageformats/gif/qgifhandler_p.h105
-rw-r--r--src/plugins/imageformats/ico/ico.pro7
-rw-r--r--src/plugins/imageformats/imageformats.pro7
-rw-r--r--src/plugins/imageformats/jpeg/jpeg.pro15
-rw-r--r--src/plugins/imageformats/jpeg/qjpeghandler.cpp1125
-rw-r--r--src/plugins/imageformats/jpeg/qjpeghandler_p.h (renamed from src/plugins/platforms/windows/qwindowsfontdatabase_ft.h)51
-rw-r--r--src/plugins/platforminputcontexts/compose/compose.pro13
-rw-r--r--src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp3
-rw-r--r--src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h37
-rw-r--r--src/plugins/platforminputcontexts/compose/qcomposeplatforminputcontext.cpp9
-rw-r--r--src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp8
-rw-r--r--src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h2
-rw-r--r--src/plugins/platforminputcontexts/ibus/qibustypes.cpp5
-rw-r--r--src/plugins/platforminputcontexts/platforminputcontexts.pro3
-rw-r--r--src/plugins/platforms/android/android.pro9
-rw-r--r--src/plugins/platforms/android/androidjniaccessibility.cpp2
-rw-r--r--src/plugins/platforms/android/androidjniinput.cpp34
-rw-r--r--src/plugins/platforms/android/androidjniinput.h4
-rw-r--r--src/plugins/platforms/android/androidjnimain.cpp2
-rw-r--r--src/plugins/platforms/android/qandroideventdispatcher.h2
-rw-r--r--src/plugins/platforms/android/qandroidinputcontext.cpp212
-rw-r--r--src/plugins/platforms/android/qandroidinputcontext.h14
-rw-r--r--src/plugins/platforms/android/qandroidplatformfontdatabase.h2
-rw-r--r--src/plugins/platforms/android/qandroidplatformintegration.cpp20
-rw-r--r--src/plugins/platforms/android/qandroidplatformintegration.h2
-rw-r--r--src/plugins/platforms/android/qandroidplatformopenglcontext.cpp2
-rw-r--r--src/plugins/platforms/android/qandroidplatformopenglcontext.h2
-rw-r--r--src/plugins/platforms/android/qandroidplatformopenglwindow.cpp2
-rw-r--r--src/plugins/platforms/android/qandroidplatformscreen.cpp3
-rw-r--r--src/plugins/platforms/android/qandroidplatformtheme.cpp2
-rw-r--r--src/plugins/platforms/bsdfb/bsdfb.json3
-rw-r--r--src/plugins/platforms/bsdfb/bsdfb.pro19
-rw-r--r--src/plugins/platforms/bsdfb/main.cpp60
-rw-r--r--src/plugins/platforms/bsdfb/qbsdfbintegration.cpp142
-rw-r--r--src/plugins/platforms/bsdfb/qbsdfbintegration.h81
-rw-r--r--src/plugins/platforms/bsdfb/qbsdfbscreen.cpp276
-rw-r--r--src/plugins/platforms/bsdfb/qbsdfbscreen.h74
-rw-r--r--src/plugins/platforms/cocoa/cocoa.pro7
-rw-r--r--src/plugins/platforms/cocoa/qcocoaaccessibility.mm6
-rw-r--r--src/plugins/platforms/cocoa/qcocoaaccessibilityelement.mm12
-rw-r--r--src/plugins/platforms/cocoa/qcocoaapplication.h1
-rw-r--r--src/plugins/platforms/cocoa/qcocoaapplication.mm13
-rw-r--r--src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h3
-rw-r--r--src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm25
-rw-r--r--src/plugins/platforms/cocoa/qcocoabackingstore.h24
-rw-r--r--src/plugins/platforms/cocoa/qcocoabackingstore.mm75
-rw-r--r--src/plugins/platforms/cocoa/qcocoaclipboard.h7
-rw-r--r--src/plugins/platforms/cocoa/qcocoaclipboard.mm4
-rw-r--r--src/plugins/platforms/cocoa/qcocoacolordialoghelper.mm10
-rw-r--r--src/plugins/platforms/cocoa/qcocoacursor.mm1
-rw-r--r--src/plugins/platforms/cocoa/qcocoadrag.mm3
-rw-r--r--src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm1
-rw-r--r--src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm53
-rw-r--r--src/plugins/platforms/cocoa/qcocoafontdialoghelper.mm4
-rw-r--r--src/plugins/platforms/cocoa/qcocoaglcontext.h1
-rw-r--r--src/plugins/platforms/cocoa/qcocoaglcontext.mm4
-rw-r--r--src/plugins/platforms/cocoa/qcocoahelpers.h36
-rw-r--r--src/plugins/platforms/cocoa/qcocoahelpers.mm588
-rw-r--r--src/plugins/platforms/cocoa/qcocoainputcontext.mm6
-rw-r--r--src/plugins/platforms/cocoa/qcocoaintegration.h6
-rw-r--r--src/plugins/platforms/cocoa/qcocoaintegration.mm17
-rw-r--r--src/plugins/platforms/cocoa/qcocoakeymapper.h2
-rw-r--r--src/plugins/platforms/cocoa/qcocoakeymapper.mm8
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenu.mm13
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenubar.mm7
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenuitem.h4
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenuitem.mm34
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenuloader.h8
-rw-r--r--src/plugins/platforms/cocoa/qcocoamenuloader.mm209
-rw-r--r--src/plugins/platforms/cocoa/qcocoamimetypes.mm3
-rw-r--r--src/plugins/platforms/cocoa/qcocoanativeinterface.h3
-rw-r--r--src/plugins/platforms/cocoa/qcocoanativeinterface.mm12
-rw-r--r--src/plugins/platforms/cocoa/qcocoaprintdevice.mm10
-rw-r--r--src/plugins/platforms/cocoa/qcocoaprintersupport.mm4
-rw-r--r--src/plugins/platforms/cocoa/qcocoaresources.qrc5
-rw-r--r--src/plugins/platforms/cocoa/qcocoasystemsettings.mm1
-rw-r--r--src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm98
-rw-r--r--src/plugins/platforms/cocoa/qcocoatheme.h4
-rw-r--r--src/plugins/platforms/cocoa/qcocoatheme.mm64
-rw-r--r--src/plugins/platforms/cocoa/qcocoawindow.h51
-rw-r--r--src/plugins/platforms/cocoa/qcocoawindow.mm271
-rw-r--r--src/plugins/platforms/cocoa/qmacclipboard.h4
-rw-r--r--src/plugins/platforms/cocoa/qmacclipboard.mm16
-rw-r--r--src/plugins/platforms/cocoa/qmacdefines_mac.h57
-rw-r--r--src/plugins/platforms/cocoa/qnsview.h8
-rw-r--r--src/plugins/platforms/cocoa/qnsview.mm264
-rw-r--r--src/plugins/platforms/cocoa/qnsviewaccessibility.mm4
-rw-r--r--src/plugins/platforms/cocoa/qnswindowdelegate.h2
-rw-r--r--src/plugins/platforms/cocoa/qnswindowdelegate.mm14
-rw-r--r--src/plugins/platforms/cocoa/qpaintengine_mac.mm87
-rw-r--r--src/plugins/platforms/cocoa/qprintengine_mac.mm4
-rw-r--r--src/plugins/platforms/cocoa/qprintengine_mac_p.h3
-rw-r--r--src/plugins/platforms/cocoa/qt_mac_p.h58
-rw-r--r--src/plugins/platforms/cocoa/qt_menu.nib/classes.nib59
-rw-r--r--src/plugins/platforms/cocoa/qt_menu.nib/info.nib18
-rw-r--r--src/plugins/platforms/cocoa/qt_menu.nib/keyedobjects.nibbin5560 -> 0 bytes
-rw-r--r--src/plugins/platforms/direct2d/direct2d.pro9
-rw-r--r--src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.cpp10
-rw-r--r--src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.h2
-rw-r--r--src/plugins/platforms/direct2d/qwindowsdirect2dbitmap.cpp2
-rw-r--r--src/plugins/platforms/direct2d/qwindowsdirect2dhelpers.h7
-rw-r--r--src/plugins/platforms/direct2d/qwindowsdirect2dintegration.cpp6
-rw-r--r--src/plugins/platforms/direct2d/qwindowsdirect2dpaintengine.cpp6
-rw-r--r--src/plugins/platforms/direct2d/qwindowsdirect2dwindow.cpp2
-rw-r--r--src/plugins/platforms/directfb/directfb.pro11
-rw-r--r--src/plugins/platforms/directfb/qdirectfb_egl.cpp6
-rw-r--r--src/plugins/platforms/directfb/qdirectfbbackingstore.cpp16
-rw-r--r--src/plugins/platforms/directfb/qdirectfbbackingstore.h2
-rw-r--r--src/plugins/platforms/directfb/qdirectfbintegration.cpp6
-rw-r--r--src/plugins/platforms/eglfs/api/api.pri21
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfscontext.cpp (renamed from src/plugins/platforms/eglfs/qeglfscontext.cpp)14
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfscontext_p.h (renamed from src/plugins/platforms/eglfs/qeglfscontext.h)15
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfscursor.cpp (renamed from src/plugins/platforms/eglfs/qeglfscursor.cpp)176
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfscursor_p.h (renamed from src/plugins/platforms/eglfs/qeglfscursor.h)30
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfsdeviceintegration.cpp (renamed from src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp)114
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfsdeviceintegration_p.h (renamed from src/plugins/platforms/eglfs/qeglfsdeviceintegration.h)20
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfsglobal_p.h (renamed from src/plugins/platforms/eglfs/qeglfsglobal.h)20
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfshooks.cpp (renamed from src/plugins/platforms/eglfs/qeglfshooks.cpp)16
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfshooks_p.h (renamed from src/plugins/platforms/eglfs/qeglfshooks.h)19
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfsintegration.cpp (renamed from src/plugins/platforms/eglfs/qeglfsintegration.cpp)76
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfsintegration_p.h (renamed from src/plugins/platforms/eglfs/qeglfsintegration.h)15
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfsoffscreenwindow.cpp (renamed from src/plugins/platforms/eglfs/qeglfsoffscreenwindow.cpp)6
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfsoffscreenwindow_p.h (renamed from src/plugins/platforms/eglfs/qeglfsoffscreenwindow.h)13
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfsscreen.cpp (renamed from src/plugins/platforms/eglfs/qeglfsscreen.cpp)33
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfsscreen_p.h (renamed from src/plugins/platforms/eglfs/qeglfsscreen.h)16
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfswindow.cpp (renamed from src/plugins/platforms/eglfs/qeglfswindow.cpp)19
-rw-r--r--src/plugins/platforms/eglfs/api/qeglfswindow_p.h (renamed from src/plugins/platforms/eglfs/qeglfswindow.h)19
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/deviceintegration.pro15
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/eglfs_brcm.pro4
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmintegration.h4
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmmain.cpp8
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/eglfs_kms.pro12
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.cpp6
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.h3
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmintegration.cpp6
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmmain.cpp8
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.cpp15
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.h5
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/eglfs_kms_egldevice.pro12
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.cpp33
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.h15
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp21
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h5
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicemain.cpp6
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.cpp28
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.h10
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/eglfs_kms_support.pro12
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.cpp120
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.h13
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.cpp30
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.h11
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.cpp19
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.h10
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/eglfs_mali.pro4
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.cpp2
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.h4
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmalimain.cpp8
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/eglfs_viv.pro5
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.cpp2
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.h4
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivmain.cpp8
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/eglfs_viv_wl.pro8
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.cpp2
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.h4
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlmain.cpp8
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/eglfs_x11.pro6
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11integration.h4
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11main.cpp8
-rw-r--r--src/plugins/platforms/eglfs/eglfs-plugin.pro4
-rw-r--r--src/plugins/platforms/eglfs/eglfs.pro2
-rw-r--r--src/plugins/platforms/eglfs/eglfs_device_lib.pro54
-rw-r--r--src/plugins/platforms/eglfs/eglfsdeviceintegration.pro50
-rw-r--r--src/plugins/platforms/eglfs/qeglfsmain.cpp2
-rw-r--r--src/plugins/platforms/haiku/haiku.pro4
-rw-r--r--src/plugins/platforms/haiku/qhaikuclipboard.cpp2
-rw-r--r--src/plugins/platforms/haiku/qhaikuintegration.cpp2
-rw-r--r--src/plugins/platforms/integrity/integrity.pro7
-rw-r--r--src/plugins/platforms/integrity/qintegrityfbintegration.cpp12
-rw-r--r--src/plugins/platforms/integrity/qintegrityfbscreen.cpp4
-rw-r--r--src/plugins/platforms/integrity/qintegrityfbscreen.h2
-rw-r--r--src/plugins/platforms/ios/kernel.pro34
-rw-r--r--src/plugins/platforms/ios/optional/nsphotolibrarysupport/qiosfileenginefactory.h4
-rw-r--r--src/plugins/platforms/ios/optional/optional.pro2
-rw-r--r--src/plugins/platforms/ios/plugin.mm4
-rw-r--r--src/plugins/platforms/ios/qiosbackingstore.h2
-rw-r--r--src/plugins/platforms/ios/qiosbackingstore.mm29
-rw-r--r--src/plugins/platforms/ios/qiosclipboard.h7
-rw-r--r--src/plugins/platforms/ios/qiosclipboard.mm6
-rw-r--r--src/plugins/platforms/ios/qioscontext.mm3
-rw-r--r--src/plugins/platforms/ios/qioseventdispatcher.mm2
-rw-r--r--src/plugins/platforms/ios/qiosfiledialog.h4
-rw-r--r--src/plugins/platforms/ios/qiosglobal.h11
-rw-r--r--src/plugins/platforms/ios/qiosglobal.mm26
-rw-r--r--src/plugins/platforms/ios/qiosinputcontext.h4
-rw-r--r--src/plugins/platforms/ios/qiosinputcontext.mm22
-rw-r--r--src/plugins/platforms/ios/qiosintegration.h11
-rw-r--r--src/plugins/platforms/ios/qiosintegration.mm18
-rw-r--r--src/plugins/platforms/ios/qiosmenu.h2
-rw-r--r--src/plugins/platforms/ios/qiosmenu.mm6
-rw-r--r--src/plugins/platforms/ios/qiosmessagedialog.h4
-rw-r--r--src/plugins/platforms/ios/qiosplatformaccessibility.h4
-rw-r--r--src/plugins/platforms/ios/qiosplatformaccessibility.mm6
-rw-r--r--src/plugins/platforms/ios/qiosscreen.h2
-rw-r--r--src/plugins/platforms/ios/qiosscreen.mm57
-rw-r--r--src/plugins/platforms/ios/qiostextinputoverlay.mm22
-rw-r--r--src/plugins/platforms/ios/qiostextresponder.h10
-rw-r--r--src/plugins/platforms/ios/qiostextresponder.mm17
-rw-r--r--src/plugins/platforms/ios/qiostheme.mm14
-rw-r--r--src/plugins/platforms/ios/qiosviewcontroller.h9
-rw-r--r--src/plugins/platforms/ios/qiosviewcontroller.mm74
-rw-r--r--src/plugins/platforms/ios/qioswindow.h4
-rw-r--r--src/plugins/platforms/ios/qioswindow.mm4
-rw-r--r--src/plugins/platforms/ios/quiaccessibilityelement.h3
-rw-r--r--src/plugins/platforms/ios/quiaccessibilityelement.mm6
-rw-r--r--src/plugins/platforms/ios/quiview.h8
-rw-r--r--src/plugins/platforms/ios/quiview.mm111
-rw-r--r--src/plugins/platforms/linuxfb/linuxfb.pro12
-rw-r--r--src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp36
-rw-r--r--src/plugins/platforms/linuxfb/qlinuxfbscreen.cpp12
-rw-r--r--src/plugins/platforms/linuxfb/qlinuxfbscreen.h2
-rw-r--r--src/plugins/platforms/minimal/minimal.pro9
-rw-r--r--src/plugins/platforms/minimal/qminimalintegration.cpp14
-rw-r--r--src/plugins/platforms/minimalegl/minimalegl.pro6
-rw-r--r--src/plugins/platforms/minimalegl/qminimaleglintegration.cpp6
-rw-r--r--src/plugins/platforms/minimalegl/qminimaleglscreen.cpp4
-rw-r--r--src/plugins/platforms/minimalegl/qminimaleglscreen.h2
-rw-r--r--src/plugins/platforms/mirclient/mirclient.pro10
-rw-r--r--src/plugins/platforms/mirclient/qmirclientbackingstore.cpp8
-rw-r--r--src/plugins/platforms/mirclient/qmirclientcursor.cpp2
-rw-r--r--src/plugins/platforms/mirclient/qmirclientglcontext.cpp2
-rw-r--r--src/plugins/platforms/mirclient/qmirclientinput.cpp1
-rw-r--r--src/plugins/platforms/mirclient/qmirclientintegration.cpp4
-rw-r--r--src/plugins/platforms/mirclient/qmirclientplatformservices.h4
-rw-r--r--src/plugins/platforms/mirclient/qmirclientscreen.cpp2
-rw-r--r--src/plugins/platforms/mirclient/qmirclienttheme.h2
-rw-r--r--src/plugins/platforms/offscreen/offscreen.pro9
-rw-r--r--src/plugins/platforms/offscreen/qoffscreencommon.cpp22
-rw-r--r--src/plugins/platforms/offscreen/qoffscreenintegration.cpp6
-rw-r--r--src/plugins/platforms/offscreen/qoffscreenintegration_x11.cpp2
-rw-r--r--src/plugins/platforms/openwfd/openwf.pro9
-rw-r--r--src/plugins/platforms/openwfd/qopenwfdintegration.cpp5
-rw-r--r--src/plugins/platforms/platforms.pro29
-rw-r--r--src/plugins/platforms/qnx/qnx.pro17
-rw-r--r--src/plugins/platforms/qnx/qqnxbuttoneventnotifier.cpp5
-rw-r--r--src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp12
-rw-r--r--src/plugins/platforms/qnx/qqnxintegration.cpp4
-rw-r--r--src/plugins/platforms/qnx/qqnxnavigatoreventhandler.cpp4
-rw-r--r--src/plugins/platforms/qnx/qqnxnavigatoreventnotifier.cpp3
-rw-r--r--src/plugins/platforms/qnx/qqnxnavigatorpps.cpp2
-rw-r--r--src/plugins/platforms/qnx/qqnxrasterbackingstore.cpp2
-rw-r--r--src/plugins/platforms/qnx/qqnxrasterwindow.cpp5
-rw-r--r--src/plugins/platforms/qnx/qqnxscreen.cpp21
-rw-r--r--src/plugins/platforms/qnx/qqnxscreeneventhandler.cpp2
-rw-r--r--src/plugins/platforms/qnx/qqnxvirtualkeyboardpps.cpp4
-rw-r--r--src/plugins/platforms/qnx/qqnxwindow.cpp2
-rw-r--r--src/plugins/platforms/vnc/main.cpp (renamed from src/plugins/platforms/windows/qwindowsnativeimage.h)47
-rw-r--r--src/plugins/platforms/vnc/qvnc.cpp685
-rw-r--r--src/plugins/platforms/vnc/qvnc_p.h417
-rw-r--r--src/plugins/platforms/vnc/qvncclient.cpp662
-rw-r--r--src/plugins/platforms/vnc/qvncclient.h149
-rw-r--r--src/plugins/platforms/vnc/qvncintegration.cpp148
-rw-r--r--src/plugins/platforms/vnc/qvncintegration.h (renamed from src/plugins/platforms/winrt/qwinrtfontdatabase.h)64
-rw-r--r--src/plugins/platforms/vnc/qvncscreen.cpp187
-rw-r--r--src/plugins/platforms/vnc/qvncscreen.h93
-rw-r--r--src/plugins/platforms/vnc/vnc.json3
-rw-r--r--src/plugins/platforms/vnc/vnc.pro31
-rw-r--r--src/plugins/platforms/windows/accessible/accessible.pri14
-rw-r--r--src/plugins/platforms/windows/accessible/comutils.cpp24
-rw-r--r--src/plugins/platforms/windows/accessible/iaccessible2.cpp2
-rw-r--r--src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp60
-rw-r--r--src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.cpp3
-rw-r--r--src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.h2
-rw-r--r--src/plugins/platforms/windows/qplatformfunctions_wince.h371
-rw-r--r--src/plugins/platforms/windows/qtwindows_additional.h179
-rw-r--r--src/plugins/platforms/windows/qtwindowsglobal.h23
-rw-r--r--src/plugins/platforms/windows/qwindowsbackingstore.cpp41
-rw-r--r--src/plugins/platforms/windows/qwindowsbackingstore.h4
-rw-r--r--src/plugins/platforms/windows/qwindowsclipboard.cpp5
-rw-r--r--src/plugins/platforms/windows/qwindowscontext.cpp214
-rw-r--r--src/plugins/platforms/windows/qwindowscontext.h47
-rw-r--r--src/plugins/platforms/windows/qwindowscursor.cpp70
-rw-r--r--src/plugins/platforms/windows/qwindowscursor.h2
-rw-r--r--src/plugins/platforms/windows/qwindowsdialoghelpers.cpp340
-rw-r--r--src/plugins/platforms/windows/qwindowsdialoghelpers.h2
-rw-r--r--src/plugins/platforms/windows/qwindowsdrag.cpp2
-rw-r--r--src/plugins/platforms/windows/qwindowseglcontext.cpp12
-rw-r--r--src/plugins/platforms/windows/qwindowsfontdatabase.cpp1907
-rw-r--r--src/plugins/platforms/windows/qwindowsfontdatabase.h133
-rw-r--r--src/plugins/platforms/windows/qwindowsfontdatabase_ft.cpp755
-rw-r--r--src/plugins/platforms/windows/qwindowsfontengine.cpp1381
-rw-r--r--src/plugins/platforms/windows/qwindowsfontengine.h186
-rw-r--r--src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp891
-rw-r--r--src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h138
-rw-r--r--src/plugins/platforms/windows/qwindowsglcontext.cpp10
-rw-r--r--src/plugins/platforms/windows/qwindowsglcontext.h4
-rw-r--r--src/plugins/platforms/windows/qwindowsinputcontext.cpp4
-rw-r--r--src/plugins/platforms/windows/qwindowsinputcontext.h2
-rw-r--r--src/plugins/platforms/windows/qwindowsintegration.cpp55
-rw-r--r--src/plugins/platforms/windows/qwindowsintegration.h8
-rw-r--r--src/plugins/platforms/windows/qwindowsinternalmimedata.cpp1
-rw-r--r--src/plugins/platforms/windows/qwindowsinternalmimedata.h2
-rw-r--r--src/plugins/platforms/windows/qwindowskeymapper.cpp36
-rw-r--r--src/plugins/platforms/windows/qwindowskeymapper.h2
-rw-r--r--src/plugins/platforms/windows/qwindowsmime.cpp2
-rw-r--r--src/plugins/platforms/windows/qwindowsmime.h2
-rw-r--r--src/plugins/platforms/windows/qwindowsmousehandler.cpp128
-rw-r--r--src/plugins/platforms/windows/qwindowsmousehandler.h6
-rw-r--r--src/plugins/platforms/windows/qwindowsnativeimage.cpp152
-rw-r--r--src/plugins/platforms/windows/qwindowsnativeinterface.cpp2
-rw-r--r--src/plugins/platforms/windows/qwindowsole.h2
-rw-r--r--src/plugins/platforms/windows/qwindowsopengltester.cpp36
-rw-r--r--src/plugins/platforms/windows/qwindowsscreen.cpp25
-rw-r--r--src/plugins/platforms/windows/qwindowsscreen.h3
-rw-r--r--src/plugins/platforms/windows/qwindowsservices.cpp15
-rw-r--r--src/plugins/platforms/windows/qwindowstabletsupport.h4
-rw-r--r--src/plugins/platforms/windows/qwindowstheme.cpp170
-rw-r--r--src/plugins/platforms/windows/qwindowstheme.h11
-rw-r--r--src/plugins/platforms/windows/qwindowswindow.cpp192
-rw-r--r--src/plugins/platforms/windows/qwindowswindow.h22
-rw-r--r--src/plugins/platforms/windows/windows.pri63
-rw-r--r--src/plugins/platforms/windows/windows.pro9
-rw-r--r--src/plugins/platforms/winrt/qwinrteglcontext.cpp4
-rw-r--r--src/plugins/platforms/winrt/qwinrtfontdatabase.cpp491
-rw-r--r--src/plugins/platforms/winrt/qwinrtinputcontext.cpp56
-rw-r--r--src/plugins/platforms/winrt/qwinrtinputcontext.h4
-rw-r--r--src/plugins/platforms/winrt/qwinrtintegration.cpp6
-rw-r--r--src/plugins/platforms/winrt/qwinrtscreen.cpp85
-rw-r--r--src/plugins/platforms/winrt/qwinrtscreen.h5
-rw-r--r--src/plugins/platforms/winrt/qwinrttheme.cpp11
-rw-r--r--src/plugins/platforms/winrt/qwinrttheme.h2
-rw-r--r--src/plugins/platforms/winrt/qwinrtwindow.cpp2
-rw-r--r--src/plugins/platforms/winrt/winrt.pro9
-rw-r--r--src/plugins/platforms/xcb/README10
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/gl_integrations.pro5
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/gl_integrations_plugin_base.pri33
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglcontext.h4
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglinclude.h2
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglintegration.cpp14
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglwindow.cpp4
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/xcb_egl/xcb_egl.pro5
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp2
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/xcb_glx/qxcbglxwindow.cpp2
-rw-r--r--src/plugins/platforms/xcb/gl_integrations/xcb_glx/xcb_glx.pro8
-rw-r--r--src/plugins/platforms/xcb/qxcbbackingstore.cpp19
-rw-r--r--src/plugins/platforms/xcb/qxcbbackingstore.h2
-rw-r--r--src/plugins/platforms/xcb/qxcbconnection.cpp28
-rw-r--r--src/plugins/platforms/xcb/qxcbconnection.h13
-rw-r--r--src/plugins/platforms/xcb/qxcbconnection_xi2.cpp18
-rw-r--r--src/plugins/platforms/xcb/qxcbcursor.cpp4
-rw-r--r--src/plugins/platforms/xcb/qxcbdrag.cpp32
-rw-r--r--src/plugins/platforms/xcb/qxcbdrag.h2
-rw-r--r--src/plugins/platforms/xcb/qxcbintegration.cpp13
-rw-r--r--src/plugins/platforms/xcb/qxcbkeyboard.cpp12
-rw-r--r--src/plugins/platforms/xcb/qxcbkeyboard.h6
-rw-r--r--src/plugins/platforms/xcb/qxcbmime.cpp15
-rw-r--r--src/plugins/platforms/xcb/qxcbnativeinterface.cpp8
-rw-r--r--src/plugins/platforms/xcb/qxcbnativeinterface.h2
-rw-r--r--src/plugins/platforms/xcb/qxcbscreen.cpp4
-rw-r--r--src/plugins/platforms/xcb/qxcbscreen.h2
-rw-r--r--src/plugins/platforms/xcb/qxcbsessionmanager.cpp6
-rw-r--r--src/plugins/platforms/xcb/qxcbsessionmanager.h4
-rw-r--r--src/plugins/platforms/xcb/qxcbwindow.cpp33
-rw-r--r--src/plugins/platforms/xcb/qxcbwindow.h1
-rw-r--r--src/plugins/platforms/xcb/xcb-plugin.pro4
-rw-r--r--src/plugins/platforms/xcb/xcb-static/xcb-static.pro11
-rw-r--r--src/plugins/platforms/xcb/xcb.pro3
-rw-r--r--src/plugins/platforms/xcb/xcb_qpa_lib.pro72
-rw-r--r--src/plugins/platformthemes/gtk3/gtk3.pro7
-rw-r--r--src/plugins/platformthemes/gtk3/qgtk3dialoghelpers.cpp7
-rw-r--r--src/plugins/platformthemes/gtk3/qgtk3menu.cpp489
-rw-r--r--src/plugins/platformthemes/gtk3/qgtk3menu.h162
-rw-r--r--src/plugins/platformthemes/gtk3/qgtk3theme.cpp11
-rw-r--r--src/plugins/platformthemes/gtk3/qgtk3theme.h3
-rw-r--r--src/plugins/platformthemes/platformthemes.pro3
-rw-r--r--src/plugins/plugins.pro11
-rw-r--r--src/plugins/printsupport/cups/cups.pro2
-rw-r--r--src/plugins/printsupport/cups/qppdprintdevice.cpp2
-rw-r--r--src/plugins/printsupport/printsupport.pro6
-rw-r--r--src/plugins/sqldrivers/db2/db2.pro7
-rw-r--r--src/plugins/sqldrivers/db2/main.cpp2
-rw-r--r--src/plugins/sqldrivers/db2/qsql_db2.cpp1699
-rw-r--r--src/plugins/sqldrivers/db2/qsql_db2_p.h103
-rw-r--r--src/plugins/sqldrivers/ibase/ibase.pro8
-rw-r--r--src/plugins/sqldrivers/ibase/main.cpp2
-rw-r--r--src/plugins/sqldrivers/ibase/qsql_ibase.cpp1948
-rw-r--r--src/plugins/sqldrivers/ibase/qsql_ibase_p.h114
-rw-r--r--src/plugins/sqldrivers/mysql/main.cpp2
-rw-r--r--src/plugins/sqldrivers/mysql/mysql.pro7
-rw-r--r--src/plugins/sqldrivers/mysql/qsql_mysql.cpp1678
-rw-r--r--src/plugins/sqldrivers/mysql/qsql_mysql_p.h110
-rw-r--r--src/plugins/sqldrivers/oci/main.cpp2
-rw-r--r--src/plugins/sqldrivers/oci/oci.pro9
-rw-r--r--src/plugins/sqldrivers/oci/qsql_oci.cpp2725
-rw-r--r--src/plugins/sqldrivers/oci/qsql_oci_p.h106
-rw-r--r--src/plugins/sqldrivers/odbc/main.cpp2
-rw-r--r--src/plugins/sqldrivers/odbc/odbc.pro8
-rw-r--r--src/plugins/sqldrivers/odbc/qsql_odbc.cpp2639
-rw-r--r--src/plugins/sqldrivers/odbc/qsql_odbc_p.h127
-rw-r--r--src/plugins/sqldrivers/psql/main.cpp2
-rw-r--r--src/plugins/sqldrivers/psql/psql.pro7
-rw-r--r--src/plugins/sqldrivers/psql/qsql_psql.cpp1508
-rw-r--r--src/plugins/sqldrivers/psql/qsql_psql_p.h128
-rw-r--r--src/plugins/sqldrivers/sqldrivers.pro19
-rw-r--r--src/plugins/sqldrivers/sqlite/qsql_sqlite.cpp903
-rw-r--r--src/plugins/sqldrivers/sqlite/qsql_sqlite_p.h106
-rw-r--r--src/plugins/sqldrivers/sqlite/smain.cpp2
-rw-r--r--src/plugins/sqldrivers/sqlite/sqlite.pro13
-rw-r--r--src/plugins/sqldrivers/sqlite2/qsql_sqlite2.cpp615
-rw-r--r--src/plugins/sqldrivers/sqlite2/qsql_sqlite2_p.h109
-rw-r--r--src/plugins/sqldrivers/sqlite2/smain.cpp2
-rw-r--r--src/plugins/sqldrivers/sqlite2/sqlite2.pro7
-rw-r--r--src/plugins/sqldrivers/tds/main.cpp2
-rw-r--r--src/plugins/sqldrivers/tds/qsql_tds.cpp881
-rw-r--r--src/plugins/sqldrivers/tds/qsql_tds_p.h120
-rw-r--r--src/plugins/sqldrivers/tds/tds.pro7
465 files changed, 27207 insertions, 11186 deletions
diff --git a/src/plugins/bearer/bearer.pro b/src/plugins/bearer/bearer.pro
index cc590cc545..b362722b28 100644
--- a/src/plugins/bearer/bearer.pro
+++ b/src/plugins/bearer/bearer.pro
@@ -1,4 +1,5 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += network-private
!android:linux*:qtHaveModule(dbus) {
SUBDIRS += generic
@@ -7,8 +8,8 @@ TEMPLATE = subdirs
#win32:SUBDIRS += nla
win32:SUBDIRS += generic
-win32:!wince:!winrt: SUBDIRS += nativewifi
-mac:contains(QT_CONFIG, corewlan):SUBDIRS += corewlan
+win32:!winrt: SUBDIRS += nativewifi
+darwin:qtConfig(corewlan): SUBDIRS += corewlan
mac:SUBDIRS += generic
android:SUBDIRS += android
diff --git a/src/plugins/bearer/connman/connman.pro b/src/plugins/bearer/connman/connman.pro
index 9f3fff304b..065ed11dad 100644
--- a/src/plugins/bearer/connman/connman.pro
+++ b/src/plugins/bearer/connman/connman.pro
@@ -1,7 +1,6 @@
TARGET = qconnmanbearer
QT = core network-private dbus
-CONFIG += link_pkgconfig
HEADERS += qconnmanservice_linux_p.h \
../linux_common/qofonoservice_linux_p.h \
diff --git a/src/plugins/bearer/connman/qconnmanengine.cpp b/src/plugins/bearer/connman/qconnmanengine.cpp
index 51ee51a64a..eabae5a07b 100644
--- a/src/plugins/bearer/connman/qconnmanengine.cpp
+++ b/src/plugins/bearer/connman/qconnmanengine.cpp
@@ -93,9 +93,9 @@ void QConnmanEngine::initialize()
connect(connmanManager,SIGNAL(servicesReady(QStringList)),this,SLOT(servicesReady(QStringList)));
connect(connmanManager,SIGNAL(scanFinished(bool)),this,SLOT(finishedScan(bool)));
- foreach (const QString &servPath, connmanManager->getServices()) {
+ const auto servPaths = connmanManager->getServices();
+ for (const QString &servPath : servPaths)
addServiceConfiguration(servPath);
- }
Q_EMIT updateCompleted();
}
@@ -115,9 +115,8 @@ void QConnmanEngine::changedModem()
void QConnmanEngine::servicesReady(const QStringList &list)
{
QMutexLocker locker(&mutex);
- foreach (const QString &servPath, list) {
+ for (const QString &servPath : list)
addServiceConfiguration(servPath);
- }
Q_EMIT updateCompleted();
}
@@ -329,7 +328,8 @@ QNetworkSessionPrivate *QConnmanEngine::createSessionBackend()
QNetworkConfigurationPrivatePointer QConnmanEngine::defaultConfiguration()
{
const QMutexLocker locker(&mutex);
- Q_FOREACH (const QString &servPath, connmanManager->getServices()) {
+ const auto servPaths = connmanManager->getServices();
+ for (const QString &servPath : servPaths) {
if (connmanServiceInterfaces.contains(servPath)) {
if (accessPointConfigurations.contains(servPath))
return accessPointConfigurations.value(servPath);
@@ -461,7 +461,8 @@ QNetworkConfiguration::BearerType QConnmanEngine::ofonoTechToBearerType(const QS
bool QConnmanEngine::isRoamingAllowed(const QString &context)
{
- foreach (const QString &dcPath, ofonoContextManager->contexts()) {
+ const auto dcPaths = ofonoContextManager->contexts();
+ for (const QString &dcPath : dcPaths) {
if (dcPath.contains(context.section("_",-1))) {
return ofonoContextManager->roamingAllowed();
}
@@ -557,7 +558,8 @@ bool QConnmanEngine::requiresPolling() const
void QConnmanEngine::reEvaluateCellular()
{
- Q_FOREACH (const QString &servicePath, connmanManager->getServices()) {
+ const auto servicePaths = connmanManager->getServices();
+ for (const QString &servicePath : servicePaths) {
if (servicePath.contains("cellular") && accessPointConfigurations.contains(servicePath)) {
configurationChange(connmanServiceInterfaces.value(servicePath));
}
diff --git a/src/plugins/bearer/connman/qconnmanengine.h b/src/plugins/bearer/connman/qconnmanengine.h
index 23c158ac34..c9ff17f801 100644
--- a/src/plugins/bearer/connman/qconnmanengine.h
+++ b/src/plugins/bearer/connman/qconnmanengine.h
@@ -44,9 +44,9 @@
// W A R N I N G
// -------------
//
-// This file is not part of the Qt API. It exists for the convenience
-// of the QLibrary class. This header file may change from
-// version to version without notice, or even be removed.
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
//
// We mean it.
//
diff --git a/src/plugins/bearer/connman/qconnmanservice_linux.cpp b/src/plugins/bearer/connman/qconnmanservice_linux.cpp
index 44cadc1b19..55eec57270 100644
--- a/src/plugins/bearer/connman/qconnmanservice_linux.cpp
+++ b/src/plugins/bearer/connman/qconnmanservice_linux.cpp
@@ -144,10 +144,9 @@ void QConnmanManagerInterface::servicesReply(QDBusPendingCallWatcher *call)
qDebug() << serv_reply.error().message();
} else {
servicesList.clear(); //connman list changes order
- ConnmanMap connmanobj;
- Q_FOREACH (connmanobj, serv_reply.value()) {
+ const ConnmanMapList connmanobjs = serv_reply.value();
+ for (const ConnmanMap &connmanobj : connmanobjs)
servicesList << connmanobj.objectPath.path();
- }
Q_EMIT servicesReady(servicesList);
}
call->deleteLater();
@@ -181,7 +180,7 @@ void QConnmanManagerInterface::connectNotify(const QMetaMethod &signal)
void QConnmanManagerInterface::onServicesChanged(const ConnmanMapList &changed, const QList<QDBusObjectPath> &removed)
{
servicesList.clear(); //connman list changes order
- Q_FOREACH (const ConnmanMap &connmanobj, changed) {
+ for (const ConnmanMap &connmanobj : changed) {
const QString svcPath(connmanobj.objectPath.path());
servicesList << svcPath;
}
@@ -225,7 +224,8 @@ QStringList QConnmanManagerInterface::getTechnologies()
QDBusPendingReply<ConnmanMapList> reply = call(QLatin1String("GetTechnologies"));
reply.waitForFinished();
if (!reply.isError()) {
- Q_FOREACH (const ConnmanMap &map, reply.value()) {
+ const ConnmanMapList maps = reply.value();
+ for (const ConnmanMap &map : maps) {
if (!technologiesMap.contains(map.objectPath.path())) {
technologyAdded(map.objectPath, map.propertyMap);
}
@@ -241,9 +241,9 @@ QStringList QConnmanManagerInterface::getServices()
QDBusPendingReply<ConnmanMapList> reply = call(QLatin1String("GetServices"));
reply.waitForFinished();
if (!reply.isError()) {
- Q_FOREACH (const ConnmanMap &map, reply.value()) {
+ const ConnmanMapList maps = reply.value();
+ for (const ConnmanMap &map : maps)
servicesList << map.objectPath.path();
- }
}
}
return servicesList;
diff --git a/src/plugins/bearer/corewlan/corewlan.pro b/src/plugins/bearer/corewlan/corewlan.pro
index ab0257aecd..1dc09ebdd6 100644
--- a/src/plugins/bearer/corewlan/corewlan.pro
+++ b/src/plugins/bearer/corewlan/corewlan.pro
@@ -3,7 +3,7 @@ TARGET = qcorewlanbearer
QT = core-private network-private
LIBS += -framework Foundation -framework SystemConfiguration
-contains(QT_CONFIG, corewlan) {
+qtConfig(corewlan) {
LIBS += -framework CoreWLAN -framework Security
}
diff --git a/src/plugins/bearer/corewlan/qcorewlanengine.mm b/src/plugins/bearer/corewlan/qcorewlanengine.mm
index 52e76219e6..7cf9365513 100644
--- a/src/plugins/bearer/corewlan/qcorewlanengine.mm
+++ b/src/plugins/bearer/corewlan/qcorewlanengine.mm
@@ -133,7 +133,7 @@ void networkChangeCallback(SCDynamicStoreRef/* store*/, CFArrayRef changedKeys,
{
for ( long i = 0; i < CFArrayGetCount(changedKeys); i++) {
- QString changed = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(changedKeys, i));
+ QString changed = QString::fromCFString((CFStringRef)CFArrayGetValueAtIndex(changedKeys, i));
if( changed.contains("/Network/Global/IPv4")) {
QCoreWlanEngine* wlanEngine = static_cast<QCoreWlanEngine*>(info);
wlanEngine->requestUpdate();
@@ -162,7 +162,7 @@ void QScanThread::run()
QMacAutoReleasePool pool;
QStringList found;
mutex.lock();
- CWInterface *currentInterface = [CWInterface interfaceWithName: QCFString::toNSString(interfaceName)];
+ CWInterface *currentInterface = [CWInterface interfaceWithName:interfaceName.toNSString()];
mutex.unlock();
const bool currentInterfaceServiceActive = currentInterface.serviceActive;
@@ -173,14 +173,14 @@ void QScanThread::run()
if (!err) {
for (CWNetwork *apNetwork in apSet) {
- const QString networkSsid = QCFString::toQString([apNetwork ssid]);
+ const QString networkSsid = QString::fromNSString([apNetwork ssid]);
const QString id = QString::number(qHash(QLatin1String("corewlan:") + networkSsid));
found.append(id);
QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined;
bool known = isKnownSsid(networkSsid);
if (currentInterfaceServiceActive) {
- if( networkSsid == QCFString::toQString( [currentInterface ssid])) {
+ if (networkSsid == QString::fromNSString([currentInterface ssid])) {
state = QNetworkConfiguration::Active;
}
}
@@ -223,7 +223,7 @@ void QScanThread::run()
}
if (currentInterfaceServiceActive) {
- if( networkSsid == QCFString::toQString([currentInterface ssid])) {
+ if (networkSsid == QString::fromNSString([currentInterface ssid])) {
state = QNetworkConfiguration::Active;
}
}
@@ -287,7 +287,7 @@ void QScanThread::getUserConfigurations()
NSSet *wifiInterfaces = [CWInterface interfaceNames];
for (NSString *ifName in wifiInterfaces) {
- CWInterface *wifiInterface = [CWInterface interfaceWithName: ifName];
+ CWInterface *wifiInterface = [CWInterface interfaceWithName:ifName];
NSString *nsInterfaceName = wifiInterface.ssid;
// add user configured system networks
@@ -299,10 +299,10 @@ void QScanThread::getUserConfigurations()
NSArray *thisSsidarray = [prefNetDict valueForKey:@"SSID_STR"];
for (NSString *ssidkey in thisSsidarray) {
- QString thisSsid = QCFString::toQString(ssidkey);
+ QString thisSsid = QString::fromNSString(ssidkey);
if(!userProfiles.contains(thisSsid)) {
QMap <QString,QString> map;
- map.insert(thisSsid, QCFString::toQString(nsInterfaceName));
+ map.insert(thisSsid, QString::fromNSString(nsInterfaceName));
userProfiles.insert(thisSsid, map);
}
}
@@ -315,18 +315,18 @@ void QScanThread::getUserConfigurations()
NSEnumerator *enumerator = [networkProfiles objectEnumerator];
CWNetworkProfile *wProfile;
while ((wProfile = [enumerator nextObject])) {
- QString networkName = QCFString::toQString([wProfile ssid]);
+ QString networkName = QString::fromNSString([wProfile ssid]);
if (!userProfiles.contains(networkName)) {
QMap<QString,QString> map;
- map.insert(networkName, QCFString::toQString(nsInterfaceName));
+ map.insert(networkName, QString::fromNSString(nsInterfaceName));
userProfiles.insert(networkName, map);
}
}
// 802.1X user profiles
QString userProfilePath = QDir::homePath() + "/Library/Preferences/com.apple.eap.profiles.plist";
- NSDictionary* eapDict = [[[NSDictionary alloc] initWithContentsOfFile: QCFString::toNSString(userProfilePath)] autorelease];
+ NSDictionary* eapDict = [[[NSDictionary alloc] initWithContentsOfFile:userProfilePath.toNSString()] autorelease];
if(eapDict != nil) {
NSString *profileStr= @"Profiles";
NSString *nameStr = @"UserDefinedName";
@@ -345,15 +345,15 @@ void QScanThread::getUserConfigurations()
QString ssid;
for (int i = 0; i < dictSize; i++) {
if([nameStr isEqualToString:keys[i]]) {
- networkName = QCFString::toQString(objects[i]);
+ networkName = QString::fromNSString(objects[i]);
}
if ([networkSsidStr isEqualToString:keys[i]]) {
- ssid = QCFString::toQString(objects[i]);
+ ssid = QString::fromNSString(objects[i]);
}
if (!userProfiles.contains(networkName)
&& !ssid.isEmpty()) {
QMap<QString,QString> map;
- map.insert(ssid, QCFString::toQString(nsInterfaceName));
+ map.insert(ssid, QString::fromNSString(nsInterfaceName));
userProfiles.insert(networkName, map);
}
}
@@ -476,7 +476,7 @@ void QCoreWlanEngine::connectToId(const QString &id)
QString interfaceString = getInterfaceFromId(id);
CWInterface *wifiInterface =
- [CWInterface interfaceWithName: QCFString::toNSString(interfaceString)];
+ [CWInterface interfaceWithName:interfaceString.toNSString()];
if (wifiInterface.powerOn) {
NSError *err = nil;
@@ -498,31 +498,31 @@ void QCoreWlanEngine::connectToId(const QString &id)
}
}
- NSSet *scanSet = [wifiInterface scanForNetworksWithName:QCFString::toNSString(wantedSsid) error:&err];
+ NSSet *scanSet = [wifiInterface scanForNetworksWithName:wantedSsid.toNSString() error:&err];
if(!err) {
for (CWNetwork *apNetwork in scanSet) {
- CFDataRef ssidData = (CFDataRef)[apNetwork ssidData];
+ NSData *ssidData = [apNetwork ssidData];
bool result = false;
SecIdentityRef identity = 0;
// Check first whether we require IEEE 802.1X authentication for the wanted SSID
- if (CWKeychainCopyEAPIdentity(ssidData, &identity) == errSecSuccess) {
- CFStringRef username = 0;
- CFStringRef password = 0;
- if (CWKeychainCopyEAPUsernameAndPassword(ssidData, &username, &password) == errSecSuccess) {
+ if (CWKeychainCopyWiFiEAPIdentity(kCWKeychainDomainSystem, ssidData, &identity) == errSecSuccess) {
+ NSString *username = nil;
+ NSString *password = nil;
+ if (CWKeychainFindWiFiEAPUsernameAndPassword(kCWKeychainDomainSystem, ssidData, &username, &password) == errSecSuccess) {
result = [wifiInterface associateToEnterpriseNetwork:apNetwork
identity:identity username:(NSString *)username password:(NSString *)password
error:&err];
- CFRelease(username);
- CFRelease(password);
+ [username release];
+ [password release];
}
CFRelease(identity);
} else {
- CFStringRef password = 0;
- if (CWKeychainCopyPassword(ssidData, &password) == errSecSuccess) {
+ NSString *password = nil;
+ if (CWKeychainFindWiFiPassword(kCWKeychainDomainSystem, ssidData, &password) == errSecSuccess) {
result = [wifiInterface associateToNetwork:apNetwork password:(NSString *)password error:&err];
- CFRelease(password);
+ [password release];
}
}
@@ -533,11 +533,11 @@ void QCoreWlanEngine::connectToId(const QString &id)
return;
}
} else {
- qDebug() <<"associate ERROR"<< QCFString::toQString([err localizedDescription ]);
+ qDebug() <<"associate ERROR"<< QString::fromNSString([err localizedDescription ]);
}
} //end scan network
} else {
- qDebug() <<"scan ERROR"<< QCFString::toQString([err localizedDescription ]);
+ qDebug() <<"scan ERROR"<< QString::fromNSString([err localizedDescription ]);
}
emit connectionError(id, InterfaceLookupError);
}
@@ -559,7 +559,7 @@ void QCoreWlanEngine::disconnectFromId(const QString &id)
QMacAutoReleasePool pool;
CWInterface *wifiInterface =
- [CWInterface interfaceWithName: QCFString::toNSString(interfaceString)];
+ [CWInterface interfaceWithName:interfaceString.toNSString()];
disconnectedInterfaceString = interfaceString;
[wifiInterface disassociate];
@@ -574,9 +574,9 @@ void QCoreWlanEngine::checkDisconnect()
QMacAutoReleasePool pool;
CWInterface *wifiInterface =
- [CWInterface interfaceWithName: QCFString::toNSString(disconnectedInterfaceString)];
+ [CWInterface interfaceWithName:disconnectedInterfaceString.toNSString()];
- const QString networkSsid = QCFString::toQString([wifiInterface ssid]);
+ const QString networkSsid = QString::fromNSString([wifiInterface ssid]);
if (!networkSsid.isEmpty()) {
const QString id = QString::number(qHash(QLatin1String("corewlan:") + networkSsid));
locker.unlock();
@@ -601,7 +601,7 @@ void QCoreWlanEngine::doRequestUpdate()
NSSet *wifiInterfaces = [CWInterface interfaceNames];
for (NSString *ifName in wifiInterfaces) {
- scanThread->interfaceName = QCFString::toQString(ifName);
+ scanThread->interfaceName = QString::fromNSString(ifName);
scanThread->start();
}
locker.unlock();
@@ -615,7 +615,7 @@ bool QCoreWlanEngine::isWifiReady(const QString &wifiDeviceName)
bool haswifi = false;
if(hasWifi) {
QMacAutoReleasePool pool;
- CWInterface *defaultInterface = [CWInterface interfaceWithName: QCFString::toNSString(wifiDeviceName)];
+ CWInterface *defaultInterface = [CWInterface interfaceWithName:wifiDeviceName.toNSString()];
if (defaultInterface.powerOn) {
haswifi = true;
}
@@ -843,7 +843,7 @@ quint64 QCoreWlanEngine::startTime(const QString &identifier)
bool ok = false;
for(int i = 0; i < dictSize; i++) {
if([ssidStr isEqualToString:keys[i]]) {
- const QString ident = QString::number(qHash(QLatin1String("corewlan:") + QCFString::toQString(objects[i])));
+ const QString ident = QString::number(qHash(QLatin1String("corewlan:") + QString::fromNSString(objects[i])));
if(ident == identifier) {
ok = true;
}
diff --git a/src/plugins/bearer/generic/qgenericengine.cpp b/src/plugins/bearer/generic/qgenericengine.cpp
index aa0fc6b945..02ea7abf88 100644
--- a/src/plugins/bearer/generic/qgenericengine.cpp
+++ b/src/plugins/bearer/generic/qgenericengine.cpp
@@ -50,17 +50,10 @@
#include <QtCore/qdebug.h>
#include <QtCore/private/qcoreapplication_p.h>
-#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
+#if defined(Q_OS_WIN32)
#include "../platformdefs_win.h"
#endif
-#ifdef Q_OS_WINCE
-typedef ULONG NDIS_OID, *PNDIS_OID;
-# ifndef QT_NO_WINCE_NUIOUSER
-# include <nuiouser.h>
-# endif
-#endif // Q_OS_WINCE
-
#ifdef Q_OS_WINRT
#include <qfunctions_winrt.h>
@@ -92,36 +85,22 @@ QT_BEGIN_NAMESPACE
#ifndef QT_NO_NETWORKINTERFACE
static QNetworkConfiguration::BearerType qGetInterfaceType(const QString &interface)
{
-#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
+#if defined(Q_OS_WIN32)
DWORD bytesWritten;
NDIS_MEDIUM medium;
NDIS_PHYSICAL_MEDIUM physicalMedium;
-#if defined(Q_OS_WINCE) && !defined(QT_NO_WINCE_NUIOUSER)
- NDISUIO_QUERY_OID nicGetOid;
- HANDLE handle = CreateFile((PTCHAR)NDISUIO_DEVICE_NAME, 0,
- FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
-#else
unsigned long oid;
HANDLE handle = CreateFile((TCHAR *)QString::fromLatin1("\\\\.\\%1").arg(interface).utf16(), 0,
FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
-#endif
if (handle == INVALID_HANDLE_VALUE)
return QNetworkConfiguration::BearerUnknown;
bytesWritten = 0;
-#if defined(Q_OS_WINCE) && !defined(QT_NO_WINCE_NUIOUSER)
- ZeroMemory(&nicGetOid, sizeof(NDISUIO_QUERY_OID));
- nicGetOid.Oid = OID_GEN_MEDIA_SUPPORTED;
- nicGetOid.ptcDeviceName = (PTCHAR)interface.utf16();
- bool result = DeviceIoControl(handle, IOCTL_NDISUIO_QUERY_OID_VALUE, &nicGetOid, sizeof(nicGetOid),
- &nicGetOid, sizeof(nicGetOid), &bytesWritten, 0);
-#else
oid = OID_GEN_MEDIA_SUPPORTED;
bool result = DeviceIoControl(handle, IOCTL_NDIS_QUERY_GLOBAL_STATS, &oid, sizeof(oid),
&medium, sizeof(medium), &bytesWritten, 0);
-#endif
if (!result) {
CloseHandle(handle);
return QNetworkConfiguration::BearerUnknown;
@@ -129,22 +108,9 @@ static QNetworkConfiguration::BearerType qGetInterfaceType(const QString &interf
bytesWritten = 0;
-#if defined(Q_OS_WINCE) && !defined(QT_NO_WINCE_NUIOUSER)
- medium = NDIS_MEDIUM( *(LPDWORD)nicGetOid.Data );
-
- ZeroMemory(&nicGetOid, sizeof(NDISUIO_QUERY_OID));
- nicGetOid.Oid = OID_GEN_PHYSICAL_MEDIUM;
- nicGetOid.ptcDeviceName = (PTCHAR)interface.utf16();
-
- result = DeviceIoControl(handle, IOCTL_NDISUIO_QUERY_OID_VALUE, &nicGetOid, sizeof(nicGetOid),
- &nicGetOid, sizeof(nicGetOid), &bytesWritten, 0);
-
- physicalMedium = NDIS_PHYSICAL_MEDIUM( *(LPDWORD)nicGetOid.Data );
-#else
oid = OID_GEN_PHYSICAL_MEDIUM;
result = DeviceIoControl(handle, IOCTL_NDIS_QUERY_GLOBAL_STATS, &oid, sizeof(oid),
&physicalMedium, sizeof(physicalMedium), &bytesWritten, 0);
-#endif
if (!result) {
CloseHandle(handle);
diff --git a/src/plugins/bearer/linux_common/qofonoservice_linux.cpp b/src/plugins/bearer/linux_common/qofonoservice_linux.cpp
index b0f5f29f6c..adf7feef2e 100644
--- a/src/plugins/bearer/linux_common/qofonoservice_linux.cpp
+++ b/src/plugins/bearer/linux_common/qofonoservice_linux.cpp
@@ -103,9 +103,9 @@ QStringList QOfonoManagerInterface::getModems()
QDBusPendingReply<PathPropertiesList> reply = callWithArgumentList(QDBus::Block, QLatin1String("GetModems"), argumentList);
reply.waitForFinished();
if (!reply.isError()) {
- foreach (const ObjectPathProperties &modem, reply.value()) {
+ const auto modems = reply.value();
+ for (const ObjectPathProperties &modem : modems)
modemList << modem.path.path();
- }
}
}
@@ -114,8 +114,8 @@ QStringList QOfonoManagerInterface::getModems()
QString QOfonoManagerInterface::currentModem()
{
- QStringList modems = getModems();
- foreach (const QString &modem, modems) {
+ const QStringList modems = getModems();
+ for (const QString &modem : modems) {
QOfonoModemInterface device(modem);
if (device.isPowered() && device.isOnline()
&& device.interfaces().contains(QStringLiteral("org.ofono.NetworkRegistration")))
@@ -266,9 +266,9 @@ QStringList QOfonoDataConnectionManagerInterface::contexts()
QDBusPendingReply<PathPropertiesList > reply = call(QLatin1String("GetContexts"));
reply.waitForFinished();
if (!reply.isError()) {
- foreach (const ObjectPathProperties &context, reply.value()) {
+ const auto contexts = reply.value();
+ for (const ObjectPathProperties &context : contexts)
contextList << context.path.path();
- }
}
}
return contextList;
diff --git a/src/plugins/bearer/nativewifi/qnativewifiengine.cpp b/src/plugins/bearer/nativewifi/qnativewifiengine.cpp
index 23656476bd..bb43072aba 100644
--- a/src/plugins/bearer/nativewifi/qnativewifiengine.cpp
+++ b/src/plugins/bearer/nativewifi/qnativewifiengine.cpp
@@ -459,7 +459,7 @@ void QNativeWifiEngine::disconnectFromId(const QString &id)
return;
}
- QStringList split = interface.mid(1, interface.length() - 2).split('-');
+ const QVector<QStringRef> split = interface.midRef(1, interface.length() - 2).split(QLatin1Char('-'));
GUID guid;
guid.Data1 = split.at(0).toUInt(0, 16);
diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp
index 59a6d107dc..543e66491d 100644
--- a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp
+++ b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp
@@ -127,7 +127,8 @@ void QNetworkManagerEngine::setupConfigurations()
{
QMutexLocker locker(&mutex);
// Get active connections.
- foreach (const QDBusObjectPath &acPath, managerInterface->activeConnections()) {
+ const auto acPaths = managerInterface->activeConnections();
+ for (const QDBusObjectPath &acPath : acPaths) {
if (activeConnectionsList.contains(acPath.path()))
continue;
@@ -144,8 +145,10 @@ void QNetworkManagerEngine::setupConfigurations()
connectionInterfaces.insert(activeConnection->connection().path(),device.networkInterface());
}
}
+
// Get connections.
- foreach (const QDBusObjectPath &settingsPath, systemSettings->listConnections()) {
+ const auto settingsPaths = systemSettings->listConnections();
+ for (const QDBusObjectPath &settingsPath : settingsPaths) {
locker.unlock();
if (!hasIdentifier(settingsPath.path()))
newConnection(settingsPath, systemSettings); //add system connection configs
@@ -189,21 +192,13 @@ void QNetworkManagerEngine::connectToId(const QString &id)
if (isConnectionActive(settingsPath))
return;
- QHashIterator<QString, QNetworkManagerInterfaceDevice*> i(interfaceDevices);
- while (i.hasNext()) {
- i.next();
- if (i.value()->deviceType() == DEVICE_TYPE_ETHERNET &&
- connectionType == DEVICE_TYPE_ETHERNET) {
- dbusDevicePath = i.key();
- break;
- } else if (i.value()->deviceType() == DEVICE_TYPE_WIFI &&
- connectionType == DEVICE_TYPE_WIFI) {
- dbusDevicePath = i.key();
- break;
- } else if (i.value()->deviceType() == DEVICE_TYPE_MODEM &&
- connectionType == DEVICE_TYPE_MODEM) {
- dbusDevicePath = i.key();
- break;
+ for (auto i = interfaceDevices.cbegin(), end = interfaceDevices.cend(); i != end; ++i) {
+ const auto type = i.value()->deviceType();
+ if (type == DEVICE_TYPE_ETHERNET || type == DEVICE_TYPE_WIFI || type == DEVICE_TYPE_MODEM) {
+ if (type == connectionType) {
+ dbusDevicePath = i.key();
+ break;
+ }
}
}
@@ -230,9 +225,7 @@ void QNetworkManagerEngine::disconnectFromId(const QString &id)
return;
}
- QHashIterator<QString, QNetworkManagerConnectionActive*> i(activeConnectionsList);
- while (i.hasNext()) {
- i.next();
+ for (auto i = activeConnectionsList.cbegin(), end = activeConnectionsList.cend(); i != end; ++i) {
if (id == i.value()->connection().path() && accessPointConfigurations.contains(id)) {
managerInterface->deactivateConnection(QDBusObjectPath(i.key()));
break;
@@ -243,11 +236,8 @@ void QNetworkManagerEngine::disconnectFromId(const QString &id)
void QNetworkManagerEngine::requestUpdate()
{
if (managerInterface && managerInterface->wirelessEnabled()) {
- QHashIterator<QString, QNetworkManagerInterfaceDeviceWireless *> i(wirelessDevices);
- while (i.hasNext()) {
- i.next();
- i.value()->requestScan();
- }
+ for (auto *wirelessDevice : qAsConst(wirelessDevices))
+ wirelessDevice->requestScan();
}
QMetaObject::invokeMethod(this, "updateCompleted", Qt::QueuedConnection);
}
@@ -255,20 +245,17 @@ void QNetworkManagerEngine::requestUpdate()
void QNetworkManagerEngine::interfacePropertiesChanged(const QMap<QString, QVariant> &properties)
{
QMutexLocker locker(&mutex);
- QMapIterator<QString, QVariant> i(properties);
- while (i.hasNext()) {
- i.next();
+ for (auto i = properties.cbegin(), end = properties.cend(); i != end; ++i) {
if (i.key() == QLatin1String("ActiveConnections")) {
// Active connections changed, update configurations.
- QList<QDBusObjectPath> activeConnections =
- qdbus_cast<QList<QDBusObjectPath> >(i.value().value<QDBusArgument>());
+ const auto activeConnections = qdbus_cast<QList<QDBusObjectPath> >(i.value().value<QDBusArgument>());
QStringList identifiers = accessPointConfigurations.keys();
QStringList priorActiveConnections = activeConnectionsList.keys();
- foreach (const QDBusObjectPath &acPath, activeConnections) {
+ for (const QDBusObjectPath &acPath : activeConnections) {
priorActiveConnections.removeOne(acPath.path());
QNetworkManagerConnectionActive *activeConnection =
activeConnectionsList.value(acPath.path());
@@ -399,7 +386,8 @@ void QNetworkManagerEngine::wiredCarrierChanged(bool carrier)
if (!deviceWired)
return;
QMutexLocker locker(&mutex);
- foreach (const QDBusObjectPath &settingsPath, systemSettings->listConnections()) {
+ const auto settingsPaths = systemSettings->listConnections();
+ for (const QDBusObjectPath &settingsPath : settingsPaths) {
for (int i = 0; i < connections.count(); ++i) {
QNetworkManagerSettingsConnection *connection = connections.at(i);
if (connection->getType() == DEVICE_TYPE_ETHERNET
@@ -477,12 +465,9 @@ void QNetworkManagerEngine::newConnection(const QDBusObjectPath &path,
cpPriv->state |= QNetworkConfiguration::Active;
if (deviceType == DEVICE_TYPE_ETHERNET) {
- QHashIterator<QString, QNetworkManagerInterfaceDevice*> i(interfaceDevices);
- while (i.hasNext()) {
- i.next();
- if (i.value()->deviceType() == deviceType) {
- QNetworkManagerInterfaceDeviceWired *wiredDevice
- = wiredDevices.value(i.value()->path());
+ for (const auto *interfaceDevice : interfaceDevices) {
+ if (interfaceDevice->deviceType() == deviceType) {
+ auto *wiredDevice = wiredDevices.value(interfaceDevice->path());
if (wiredDevice && wiredDevice->carrier()) {
cpPriv->state |= QNetworkConfiguration::Discovered;
}
@@ -496,14 +481,13 @@ void QNetworkManagerEngine::newConnection(const QDBusObjectPath &path,
emit configurationAdded(ptr);
}
-bool QNetworkManagerEngine::isConnectionActive(const QString &settingsPath)
+bool QNetworkManagerEngine::isConnectionActive(const QString &settingsPath) const
{
- QHashIterator<QString, QNetworkManagerConnectionActive*> i(activeConnectionsList);
- while (i.hasNext()) {
- i.next();
- if (i.value()->connection().path() == settingsPath) {
- if (i.value()->state() == NM_ACTIVE_CONNECTION_STATE_ACTIVATING
- || i.value()->state() == NM_ACTIVE_CONNECTION_STATE_ACTIVATED) {
+ for (QNetworkManagerConnectionActive *activeConnection : activeConnectionsList) {
+ if (activeConnection->connection().path() == settingsPath) {
+ const auto state = activeConnection->state();
+ if (state == NM_ACTIVE_CONNECTION_STATE_ACTIVATING
+ || state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED) {
return true;
} else {
break;
@@ -560,7 +544,8 @@ void QNetworkManagerEngine::updateConnection()
QNetworkConfigurationPrivate *cpPriv = parseConnection(settingsPath, connection->getSettings());
// Check if connection is active.
- foreach (const QDBusObjectPath &acPath, managerInterface->activeConnections()) {
+ const auto acPaths = managerInterface->activeConnections();
+ for (const QDBusObjectPath &acPath : acPaths) {
QNetworkManagerConnectionActive activeConnection(acPath.path());
if (activeConnection.connection().path() == settingsPath &&
@@ -636,7 +621,8 @@ QNetworkConfigurationPrivate *QNetworkManagerEngine::parseConnection(const QStri
if (connectionType == QLatin1String("802-3-ethernet")) {
cpPriv->bearerType = QNetworkConfiguration::BearerEthernet;
- foreach (const QDBusObjectPath &devicePath, managerInterface->getDevices()) {
+ const auto devicePaths = managerInterface->getDevices();
+ for (const QDBusObjectPath &devicePath : devicePaths) {
QNetworkManagerInterfaceDevice device(devicePath.path(),this);
if (device.deviceType() == DEVICE_TYPE_ETHERNET) {
QNetworkManagerInterfaceDeviceWired *wiredDevice = wiredDevices.value(device.path());
@@ -678,9 +664,7 @@ QNetworkConfigurationPrivate *QNetworkManagerEngine::parseConnection(const QStri
if (ofonoManager && ofonoManager->isValid()) {
const QString contextPart = connectionPath.section('/', -1);
- QHashIterator<QString, QOfonoDataConnectionManagerInterface*> i(ofonoContextManagers);
- while (i.hasNext()) {
- i.next();
+ for (auto i = ofonoContextManagers.cbegin(), end = ofonoContextManagers.cend(); i != end; ++i) {
const QString path = i.key() + QLatin1Char('/') +contextPart;
if (isActiveContext(path)) {
cpPriv->state |= QNetworkConfiguration::Active;
@@ -693,14 +677,12 @@ QNetworkConfigurationPrivate *QNetworkManagerEngine::parseConnection(const QStri
return cpPriv;
}
-bool QNetworkManagerEngine::isActiveContext(const QString &contextPath)
+bool QNetworkManagerEngine::isActiveContext(const QString &contextPath) const
{
if (ofonoManager && ofonoManager->isValid()) {
const QString contextPart = contextPath.section('/', -1);
- QHashIterator<QString, QOfonoDataConnectionManagerInterface*> i(ofonoContextManagers);
- while (i.hasNext()) {
- i.next();
- PathPropertiesList list = i.value()->contextsWithProperties();
+ for (QOfonoDataConnectionManagerInterface *iface : ofonoContextManagers) {
+ const PathPropertiesList list = iface->contextsWithProperties();
for (int i = 0; i < list.size(); ++i) {
if (list.at(i).path.path().contains(contextPart)) {
return list.at(i).properties.value(QStringLiteral("Active")).toBool();
@@ -734,9 +716,7 @@ QNetworkSession::State QNetworkManagerEngine::sessionStateForId(const QString &i
if (!ptr->isValid)
return QNetworkSession::Invalid;
- foreach (const QString &acPath, activeConnectionsList.keys()) {
- QNetworkManagerConnectionActive *activeConnection = activeConnectionsList.value(acPath);
-
+ for (QNetworkManagerConnectionActive *activeConnection : activeConnectionsList) {
const QString identifier = activeConnection->connection().path();
if (id == identifier) {
@@ -842,10 +822,7 @@ QNetworkSessionPrivate *QNetworkManagerEngine::createSessionBackend()
QNetworkConfigurationPrivatePointer QNetworkManagerEngine::defaultConfiguration()
{
- QHashIterator<QString, QNetworkManagerConnectionActive*> i(activeConnectionsList);
- while (i.hasNext()) {
- i.next();
- QNetworkManagerConnectionActive *activeConnection = i.value();
+ for (QNetworkManagerConnectionActive *activeConnection : qAsConst(activeConnectionsList)) {
if ((activeConnection->defaultRoute() || activeConnection->default6Route())) {
return accessPointConfigurations.value(activeConnection->connection().path());
}
@@ -854,12 +831,10 @@ QNetworkConfigurationPrivatePointer QNetworkManagerEngine::defaultConfiguration(
return QNetworkConfigurationPrivatePointer();
}
-QNetworkConfiguration::BearerType QNetworkManagerEngine::currentBearerType(const QString &id)
+QNetworkConfiguration::BearerType QNetworkManagerEngine::currentBearerType(const QString &id) const
{
QString contextPart = id.section('/', -1);
- QHashIterator<QString, QOfonoDataConnectionManagerInterface*> i(ofonoContextManagers);
- while (i.hasNext()) {
- i.next();
+ for (auto i = ofonoContextManagers.begin(), end = ofonoContextManagers.end(); i != end; ++i) {
QString contextPath = i.key() + QLatin1Char('/') +contextPart;
if (i.value()->contexts().contains(contextPath)) {
@@ -885,13 +860,11 @@ QNetworkConfiguration::BearerType QNetworkManagerEngine::currentBearerType(const
return QNetworkConfiguration::BearerUnknown;
}
-QString QNetworkManagerEngine::contextName(const QString &path)
+QString QNetworkManagerEngine::contextName(const QString &path) const
{
QString contextPart = path.section('/', -1);
- QHashIterator<QString, QOfonoDataConnectionManagerInterface*> i(ofonoContextManagers);
- while (i.hasNext()) {
- i.next();
- PathPropertiesList list = i.value()->contextsWithProperties();
+ for (QOfonoDataConnectionManagerInterface *iface : ofonoContextManagers) {
+ const PathPropertiesList list = iface->contextsWithProperties();
for (int i = 0; i < list.size(); ++i) {
if (list.at(i).path.path().contains(contextPart)) {
return list.at(i).properties.value(QStringLiteral("Name")).toString();
@@ -944,7 +917,8 @@ void QNetworkManagerEngine::ofonoRegistered(const QString &)
}
ofonoManager = new QOfonoManagerInterface(this);
if (ofonoManager && ofonoManager->isValid()) {
- Q_FOREACH (const QString &modem, ofonoManager->getModems()) {
+ const auto modems = ofonoManager->getModems();
+ for (const QString &modem : modems) {
QOfonoDataConnectionManagerInterface *ofonoContextManager
= new QOfonoDataConnectionManagerInterface(modem,this);
ofonoContextManagers.insert(modem, ofonoContextManager);
diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h
index 2de570b1ba..74fe24b5ab 100644
--- a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h
+++ b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.h
@@ -44,9 +44,9 @@
// W A R N I N G
// -------------
//
-// This file is not part of the Qt API. It exists for the convenience
-// of the QLibrary class. This header file may change from
-// version to version without notice, or even be removed.
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
//
// We mean it.
//
@@ -74,26 +74,26 @@ public:
bool networkManagerAvailable() const;
- QString getInterfaceFromId(const QString &id);
- bool hasIdentifier(const QString &id);
+ QString getInterfaceFromId(const QString &id) override;
+ bool hasIdentifier(const QString &id) override;
- void connectToId(const QString &id);
- void disconnectFromId(const QString &id);
+ void connectToId(const QString &id) override;
+ void disconnectFromId(const QString &id) override;
Q_INVOKABLE void initialize();
Q_INVOKABLE void requestUpdate();
- QNetworkSession::State sessionStateForId(const QString &id);
+ QNetworkSession::State sessionStateForId(const QString &id) override;
- quint64 bytesWritten(const QString &id);
- quint64 bytesReceived(const QString &id);
- quint64 startTime(const QString &id);
+ quint64 bytesWritten(const QString &id) override;
+ quint64 bytesReceived(const QString &id) override;
+ quint64 startTime(const QString &id) override;
- QNetworkConfigurationManager::Capabilities capabilities() const;
+ QNetworkConfigurationManager::Capabilities capabilities() const override;
- QNetworkSessionPrivate *createSessionBackend();
+ QNetworkSessionPrivate *createSessionBackend() override;
- QNetworkConfigurationPrivatePointer defaultConfiguration();
+ QNetworkConfigurationPrivatePointer defaultConfiguration() override;
private Q_SLOTS:
void interfacePropertiesChanged(const QMap<QString, QVariant> &properties);
@@ -133,14 +133,14 @@ private:
QOfonoManagerInterface *ofonoManager;
QHash <QString, QOfonoDataConnectionManagerInterface *> ofonoContextManagers;
- QNetworkConfiguration::BearerType currentBearerType(const QString &id);
- QString contextName(const QString &path);
+ QNetworkConfiguration::BearerType currentBearerType(const QString &id) const;
+ QString contextName(const QString &path) const;
- bool isConnectionActive(const QString &settingsPath);
+ bool isConnectionActive(const QString &settingsPath) const;
QDBusServiceWatcher *ofonoWatcher;
QDBusServiceWatcher *nmWatcher;
- bool isActiveContext(const QString &contextPath);
+ bool isActiveContext(const QString &contextPath) const;
bool nmAvailable;
void setupConfigurations();
};
diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerservice.cpp b/src/plugins/bearer/networkmanager/qnetworkmanagerservice.cpp
index c8f00118bb..3e77580015 100644
--- a/src/plugins/bearer/networkmanager/qnetworkmanagerservice.cpp
+++ b/src/plugins/bearer/networkmanager/qnetworkmanagerservice.cpp
@@ -230,9 +230,7 @@ QString QNetworkManagerInterface::version() const
void QNetworkManagerInterface::propertiesSwap(QMap<QString,QVariant> map)
{
- QMapIterator<QString, QVariant> i(map);
- while (i.hasNext()) {
- i.next();
+ for (auto i = map.cbegin(), end = map.cend(); i != end; ++i) {
propertyMap.insert(i.key(),i.value());
if (i.key() == QLatin1String("State")) {
@@ -327,11 +325,8 @@ quint32 QNetworkManagerInterfaceAccessPoint::strength() const
void QNetworkManagerInterfaceAccessPoint::propertiesSwap(QMap<QString,QVariant> map)
{
- QMapIterator<QString, QVariant> i(map);
- while (i.hasNext()) {
- i.next();
+ for (auto i = map.cbegin(), end = map.cend(); i != end; ++i)
propertyMap.insert(i.key(),i.value());
- }
}
QNetworkManagerInterfaceDevice::QNetworkManagerInterfaceDevice(const QString &deviceObjectPath, QObject *parent)
@@ -419,9 +414,7 @@ QDBusObjectPath QNetworkManagerInterfaceDevice::ip4config() const
void QNetworkManagerInterfaceDevice::propertiesSwap(QMap<QString,QVariant> map)
{
- QMapIterator<QString, QVariant> i(map);
- while (i.hasNext()) {
- i.next();
+ for (auto i = map.cbegin(), end = map.cend(); i != end; ++i) {
if (i.key() == QLatin1String("AvailableConnections")) { //Device
const QDBusArgument &dbusArgs = i.value().value<QDBusArgument>();
QDBusObjectPath path;
@@ -519,9 +512,7 @@ QStringList QNetworkManagerInterfaceDeviceWired::availableConnections()
void QNetworkManagerInterfaceDeviceWired::propertiesSwap(QMap<QString,QVariant> map)
{
- QMapIterator<QString, QVariant> i(map);
- while (i.hasNext()) {
- i.next();
+ for (auto i = map.cbegin(), end = map.cend(); i != end; ++i) {
propertyMap.insert(i.key(),i.value());
if (i.key() == QLatin1String("Carrier"))
Q_EMIT carrierChanged(i.value().toBool());
@@ -635,9 +626,7 @@ void QNetworkManagerInterfaceDeviceWireless::requestScan()
void QNetworkManagerInterfaceDeviceWireless::propertiesSwap(QMap<QString,QVariant> map)
{
- QMapIterator<QString, QVariant> i(map);
- while (i.hasNext()) {
- i.next();
+ for (auto i = map.cbegin(), end = map.cend(); i != end; ++i) {
propertyMap.insert(i.key(),i.value());
if (i.key() == QLatin1String("ActiveAccessPoint")) //DeviceWireless
Q_EMIT propertiesChanged(map);
@@ -700,11 +689,8 @@ QNetworkManagerInterfaceDeviceModem::ModemCapabilities QNetworkManagerInterfaceD
void QNetworkManagerInterfaceDeviceModem::propertiesSwap(QMap<QString,QVariant> map)
{
- QMapIterator<QString, QVariant> i(map);
- while (i.hasNext()) {
- i.next();
+ for (auto i = map.cbegin(), end = map.cend(); i != end; ++i)
propertyMap.insert(i.key(),i.value());
- }
Q_EMIT propertiesChanged(map);
}
@@ -1013,9 +999,7 @@ bool QNetworkManagerConnectionActive::default6Route() const
void QNetworkManagerConnectionActive::propertiesSwap(QMap<QString,QVariant> map)
{
- QMapIterator<QString, QVariant> i(map);
- while (i.hasNext()) {
- i.next();
+ for (auto i = map.cbegin(), end = map.cend(); i != end; ++i) {
propertyMap.insert(i.key(),i.value());
if (i.key() == QLatin1String("State")) {
quint32 state = i.value().toUInt();
diff --git a/src/plugins/bearer/nla/nla.pro b/src/plugins/bearer/nla/nla.pro
index 32ff5446e5..113d0667d2 100644
--- a/src/plugins/bearer/nla/nla.pro
+++ b/src/plugins/bearer/nla/nla.pro
@@ -2,11 +2,7 @@ TARGET = qnlabearer
QT = core core-private network network-private
-!wince* {
- LIBS += -lws2_32
-} else {
- LIBS += -lws2
-}
+LIBS += -lws2_32
HEADERS += qnlaengine.h \
../platformdefs_win.h \
diff --git a/src/plugins/bearer/qnetworksession_impl.cpp b/src/plugins/bearer/qnetworksession_impl.cpp
index a692d3c63f..5ce51670f7 100644
--- a/src/plugins/bearer/qnetworksession_impl.cpp
+++ b/src/plugins/bearer/qnetworksession_impl.cpp
@@ -54,7 +54,8 @@ static QBearerEngineImpl *getEngineFromId(const QString &id)
{
QNetworkConfigurationManagerPrivate *priv = qNetworkConfigurationManagerPrivate();
- foreach (QBearerEngine *engine, priv->engines()) {
+ const auto engines = priv->engines();
+ for (QBearerEngine *engine : engines) {
QBearerEngineImpl *engineImpl = qobject_cast<QBearerEngineImpl *>(engine);
if (engineImpl && engineImpl->hasIdentifier(id))
return engineImpl;
@@ -111,10 +112,10 @@ void QNetworkSessionPrivateImpl::syncStateWithInterface()
case QNetworkConfiguration::ServiceNetwork:
serviceConfig = publicConfig;
// Defer setting engine and signals until open().
- // fall through
+ Q_FALLTHROUGH();
case QNetworkConfiguration::UserChoice:
// Defer setting serviceConfig and activeConfig until open().
- // fall through
+ Q_FALLTHROUGH();
default:
engine = 0;
}
@@ -285,7 +286,7 @@ quint64 QNetworkSessionPrivateImpl::bytesReceived() const
quint64 QNetworkSessionPrivateImpl::activeTime() const
{
if (state == QNetworkSession::Connected && startTime != Q_UINT64_C(0))
- return QDateTime::currentDateTimeUtc().toTime_t() - startTime;
+ return QDateTime::currentSecsSinceEpoch() - startTime;
return Q_UINT64_C(0);
}
@@ -306,7 +307,8 @@ void QNetworkSessionPrivateImpl::updateStateFromServiceNetwork()
{
QNetworkSession::State oldState = state;
- foreach (const QNetworkConfiguration &config, serviceConfig.children()) {
+ const auto configs = serviceConfig.children();
+ for (const QNetworkConfiguration &config : configs) {
if ((config.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active)
continue;
diff --git a/src/plugins/generic/bsdkeyboard/bsdkeyboard.json b/src/plugins/generic/bsdkeyboard/bsdkeyboard.json
new file mode 100644
index 0000000000..46a8127c46
--- /dev/null
+++ b/src/plugins/generic/bsdkeyboard/bsdkeyboard.json
@@ -0,0 +1,3 @@
+{
+ "Keys": [ "BsdKeyboard" ]
+}
diff --git a/src/plugins/generic/bsdkeyboard/bsdkeyboard.pro b/src/plugins/generic/bsdkeyboard/bsdkeyboard.pro
new file mode 100644
index 0000000000..c14c38c839
--- /dev/null
+++ b/src/plugins/generic/bsdkeyboard/bsdkeyboard.pro
@@ -0,0 +1,16 @@
+TARGET = qbsdkeyboardplugin
+
+PLUGIN_TYPE = generic
+PLUGIN_EXTENDS = -
+PLUGIN_CLASS_NAME = QBsdKeyboardPlugin
+load(qt_plugin)
+
+QT += core gui-private
+
+HEADERS = qbsdkeyboard.h
+SOURCES = main.cpp \
+ qbsdkeyboard.cpp
+
+OTHER_FILES += \
+ qbsdkeyboard.json
+
diff --git a/src/plugins/generic/bsdkeyboard/main.cpp b/src/plugins/generic/bsdkeyboard/main.cpp
new file mode 100644
index 0000000000..f48af0ae28
--- /dev/null
+++ b/src/plugins/generic/bsdkeyboard/main.cpp
@@ -0,0 +1,59 @@
+/****************************************************************************
+**
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtGui/qgenericplugin.h>
+#include "qbsdkeyboard.h"
+
+QT_BEGIN_NAMESPACE
+
+class QBsdKeyboardPlugin : public QGenericPlugin
+{
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QGenericPluginFactoryInterface" FILE "bsdkeyboard.json")
+
+public:
+ QObject *create(const QString &key, const QString &specification) override;
+};
+
+QObject *QBsdKeyboardPlugin::create(const QString &key,
+ const QString &specification)
+{
+ if (!key.compare(QLatin1String("BsdKeyboard"), Qt::CaseInsensitive))
+ return new QBsdKeyboardHandler(key, specification);
+
+ return nullptr;
+}
+
+QT_END_NAMESPACE
+
+#include "main.moc"
diff --git a/src/plugins/generic/bsdkeyboard/qbsdkeyboard.cpp b/src/plugins/generic/bsdkeyboard/qbsdkeyboard.cpp
new file mode 100644
index 0000000000..6f34d066c6
--- /dev/null
+++ b/src/plugins/generic/bsdkeyboard/qbsdkeyboard.cpp
@@ -0,0 +1,408 @@
+/****************************************************************************
+**
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qbsdkeyboard.h"
+
+#include <QByteArray>
+#include <QFile>
+#include <QGuiApplication>
+#include <QPoint>
+#include <QSocketNotifier>
+#include <QString>
+#include <QStringList>
+
+#include <QtCore/qglobal.h>
+#include <qpa/qwindowsysteminterface.h>
+#include <private/qcore_unix_p.h>
+#include <private/qguiapplication_p.h>
+#include <private/qinputdevicemanager_p_p.h>
+
+#include <qdebug.h>
+#include <cstdio>
+
+#include <cerrno>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <termios.h>
+#include <sys/kbio.h>
+
+// #define QT_BSD_KEYBOARD_DEBUG
+
+#ifdef QT_BSD_KEYBOARD_DEBUG
+#include <qdebug.h>
+#endif
+
+QT_BEGIN_NAMESPACE
+
+enum {
+ Bsd_KeyCodeMask = 0x7f,
+ Bsd_KeyPressedMask = 0x80
+};
+
+#include "qbsdkeyboard_defaultmap.h"
+
+QBsdKeyboardHandler::QBsdKeyboardHandler(const QString &key, const QString &specification)
+{
+ Q_UNUSED(key);
+
+ setObjectName(QLatin1String("BSD Keyboard Handler"));
+
+ QByteArray device;
+ if (specification.startsWith("/dev/"))
+ device = QFile::encodeName(specification);
+
+ if (device.isEmpty()) {
+ device = QByteArrayLiteral("STDIN");
+ m_fd = fileno(stdin);
+ }
+ else {
+ m_fd = QT_OPEN(device.constData(), O_RDONLY);
+ if (!m_fd) {
+ qErrnoWarning(errno, "open(%s) failed", device.constData());
+ return;
+ }
+ m_shouldClose = true;
+ }
+
+ if (ioctl(m_fd, KDGKBMODE, &m_origKbdMode)) {
+ qErrnoWarning(errno, "ioctl(%s, KDGKBMODE) failed", device.constData());
+ revertTTYSettings();
+ return;
+ }
+
+ if (ioctl(m_fd, KDSKBMODE, K_CODE) < 0) {
+ qErrnoWarning(errno, "ioctl(%s, KDSKBMODE) failed", device.constData());
+ revertTTYSettings();
+ return;
+ }
+
+ termios kbdtty;
+ if (tcgetattr(m_fd, &kbdtty) == 0) {
+
+ m_kbdOrigTty.reset(new termios);
+ *m_kbdOrigTty = kbdtty;
+
+ kbdtty.c_iflag = IGNPAR | IGNBRK;
+ kbdtty.c_oflag = 0;
+ kbdtty.c_cflag = CREAD | CS8;
+ kbdtty.c_lflag = 0;
+ kbdtty.c_cc[VTIME] = 0;
+ kbdtty.c_cc[VMIN] = 0;
+ cfsetispeed(&kbdtty, 9600);
+ cfsetospeed(&kbdtty, 9600);
+ if (tcsetattr(m_fd, TCSANOW, &kbdtty) < 0) {
+ qErrnoWarning(errno, "tcsetattr(%s) failed", device.constData());
+
+ // TTY is still at old settings so we can
+ // dispose of original termios data
+ m_kbdOrigTty.reset();
+
+ revertTTYSettings();
+ return;
+ }
+ } else {
+ qErrnoWarning(errno, "tcgetattr(%s) failed", device.constData());
+ revertTTYSettings();
+ return;
+ }
+
+ if (fcntl(m_fd, F_SETFL, O_NONBLOCK)) {
+ qErrnoWarning(errno, "fcntl(%s, F_SETFL, O_NONBLOCK) failed", device.constData());
+ revertTTYSettings();
+ return;
+ }
+
+ resetKeymap();
+
+ m_notifier.reset(new QSocketNotifier(m_fd, QSocketNotifier::Read, this));
+ connect(m_notifier.data(), &QSocketNotifier::activated, this, &QBsdKeyboardHandler::readKeyboardData);
+ QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount(
+ QInputDeviceManager::DeviceTypeKeyboard, 1);
+}
+
+QBsdKeyboardHandler::~QBsdKeyboardHandler()
+{
+ revertTTYSettings();
+}
+
+void QBsdKeyboardHandler::revertTTYSettings()
+{
+ if (m_fd >= 0) {
+ if (m_kbdOrigTty) {
+ tcsetattr(m_fd, TCSANOW, m_kbdOrigTty.data());
+ m_kbdOrigTty.reset();
+ }
+
+ if (m_origKbdMode != Bsd_NoKeyMode) {
+ ioctl(m_fd, KDSKBMODE, m_origKbdMode);
+ m_origKbdMode = Bsd_NoKeyMode;
+ }
+
+ if (m_shouldClose)
+ close(m_fd);
+ m_fd = -1;
+ }
+}
+
+void QBsdKeyboardHandler::readKeyboardData()
+{
+
+ for (;;) {
+ uint8_t buffer[32];
+ int bytesRead = qt_safe_read(m_fd, buffer, sizeof(buffer));
+
+ if (!bytesRead) {
+ qWarning("Got EOF from the input device.");
+ return;
+ } else if (bytesRead < 0) {
+ if (errno != EINTR && errno != EAGAIN)
+ qWarning("Could not read from input device: %s", strerror(errno));
+ return;
+ }
+
+ for (int i = 0; i < bytesRead; ++i) {
+ const quint16 code = buffer[i] & Bsd_KeyCodeMask;
+ const bool pressed = (buffer[i] & Bsd_KeyPressedMask) ? false : true;
+
+ processKeycode(code, pressed, false);
+ }
+ }
+}
+
+void QBsdKeyboardHandler::processKeyEvent(int nativecode, int unicode, int qtcode,
+ Qt::KeyboardModifiers modifiers, bool isPress,
+ bool autoRepeat)
+{
+ const QString text = (unicode != 0xffff ) ? QString(unicode) : QString();
+ const QEvent::Type eventType = isPress ? QEvent::KeyPress : QEvent::KeyRelease;
+
+ QWindowSystemInterface::handleExtendedKeyEvent(0, eventType, qtcode, modifiers, nativecode, 0,
+ int(modifiers), text, autoRepeat);
+}
+
+void QBsdKeyboardHandler::processKeycode(quint16 keycode, bool pressed, bool autorepeat)
+{
+ const bool first_press = pressed && !autorepeat;
+
+ const QBsdKeyboardMap::Mapping *map_plain = nullptr;
+ const QBsdKeyboardMap::Mapping *map_withmod = nullptr;
+
+ quint8 modifiers = m_modifiers;
+
+ // get a specific and plain mapping for the keycode and the current modifiers
+ for (const QBsdKeyboardMap::Mapping &m : m_keymap) {
+ if (m.keycode == keycode) {
+ if (m.modifiers == 0)
+ map_plain = &m;
+
+ quint8 testmods = m_modifiers;
+ if (m_capsLock && (m.flags & QBsdKeyboardMap::IsLetter))
+ testmods ^= QBsdKeyboardMap::ModShift;
+ if (m.modifiers == testmods)
+ map_withmod = &m;
+ }
+ }
+
+ if (m_capsLock && map_withmod && (map_withmod->flags & QBsdKeyboardMap::IsLetter))
+ modifiers ^= QBsdKeyboardMap::ModShift;
+
+#ifdef QT_BSD_KEYBOARD_DEBUG
+ qWarning("Processing key event: keycode=%3d, modifiers=%02x pressed=%d, autorepeat=%d", \
+ keycode, modifiers, pressed ? 1 : 0, autorepeat ? 1 : 0);
+#endif
+
+ const QBsdKeyboardMap::Mapping *it = map_withmod ? map_withmod : map_plain;
+
+ if (!it) {
+#ifdef QT_BSD_KEYBOARD_DEBUG
+ // we couldn't even find a plain mapping
+ qWarning("Could not find a suitable mapping for keycode: %3d, modifiers: %02x", keycode, modifiers);
+#endif
+ return;
+ }
+
+ bool skip = false;
+ quint16 unicode = it->unicode;
+ quint32 qtcode = it->qtcode;
+
+ if ((it->flags & QBsdKeyboardMap::IsModifier) && it->special) {
+ // this is a modifier, i.e. Shift, Alt, ...
+ if (pressed)
+ m_modifiers |= quint8(it->special);
+ else
+ m_modifiers &= ~quint8(it->special);
+ } else if (qtcode >= Qt::Key_CapsLock && qtcode <= Qt::Key_ScrollLock) {
+ // (Caps|Num|Scroll)Lock
+ if (first_press) {
+ switch (qtcode) {
+ case Qt::Key_CapsLock:
+ m_capsLock = !m_capsLock;
+ switchLed(LED_CAP, m_capsLock);
+ break;
+ case Qt::Key_NumLock:
+ m_numLock = !m_numLock;
+ switchLed(LED_NUM, m_numLock);
+ break;
+ case Qt::Key_ScrollLock:
+ m_scrollLock = !m_scrollLock;
+ switchLed(LED_SCR, m_scrollLock);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ if (!skip) {
+ // a normal key was pressed
+ const int modmask = Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier
+ | Qt::MetaModifier | Qt::KeypadModifier;
+
+ // we couldn't find a specific mapping for the current modifiers,
+ // or that mapping didn't have special modifiers:
+ // so just report the plain mapping with additional modifiers.
+ if ((it == map_plain && it != map_withmod) ||
+ (map_withmod && !(map_withmod->qtcode & modmask))) {
+ qtcode |= QBsdKeyboardHandler::toQtModifiers(modifiers);
+ }
+
+#ifdef QT_BSD_KEYBOARD_DEBUG
+ qWarning("Processing: uni=%04x, qt=%08x, qtmod=%08x", unicode, qtcode & ~modmask, (qtcode & modmask));
+#endif
+ //If NumLockOff and keypad key pressed remap event sent
+ if (!m_numLock &&
+ (qtcode & Qt::KeypadModifier)) {
+ unicode = 0xffff;
+ const int oldMask = (qtcode & modmask);
+ switch (qtcode & ~modmask) {
+ case Qt::Key_7: //7 --> Home
+ qtcode = Qt::Key_Home;
+ break;
+ case Qt::Key_8: //8 --> Up
+ qtcode = Qt::Key_Up;
+ break;
+ case Qt::Key_9: //9 --> PgUp
+ qtcode = Qt::Key_PageUp;
+ break;
+ case Qt::Key_4: //4 --> Left
+ qtcode = Qt::Key_Left;
+ break;
+ case Qt::Key_5: //5 --> Clear
+ qtcode = Qt::Key_Clear;
+ break;
+ case Qt::Key_6: //6 --> right
+ qtcode = Qt::Key_Right;
+ break;
+ case Qt::Key_1: //1 --> End
+ qtcode = Qt::Key_End;
+ break;
+ case Qt::Key_2: //2 --> Down
+ qtcode = Qt::Key_Down;
+ break;
+ case Qt::Key_3: //3 --> PgDn
+ qtcode = Qt::Key_PageDown;
+ break;
+ case Qt::Key_0: //0 --> Ins
+ qtcode = Qt::Key_Insert;
+ break;
+ case Qt::Key_Period: //. --> Del
+ qtcode = Qt::Key_Delete;
+ break;
+ }
+ qtcode |= oldMask;
+ }
+
+ // send the result to the server
+ processKeyEvent(keycode, unicode, qtcode & ~modmask,
+ Qt::KeyboardModifiers(qtcode & modmask), pressed, autorepeat);
+ }
+}
+
+void QBsdKeyboardHandler::switchLed(int led, bool state)
+{
+#ifdef QT_BSD_KEYBOARD_DEBUG
+ qWarning() << "switchLed" << led << state;
+#endif
+ int leds = 0;
+ if (ioctl(m_fd, KDGETLED, &leds) < 0) {
+ qWarning("switchLed: Failed to query led states.");
+ return;
+ }
+
+ if (state)
+ leds |= led;
+ else
+ leds &= ~led;
+
+ if (ioctl(m_fd, KDSETLED, leds) < 0)
+ qWarning("switchLed: Failed to set led states.");
+}
+
+void QBsdKeyboardHandler::resetKeymap()
+{
+#ifdef QT_BSD_KEYBOARD_DEBUG
+ qWarning() << "Unload current keymap and restore built-in";
+#endif
+
+ m_keymap.clear();
+
+ const size_t mappingSize = sizeof(keymapDefault) / sizeof(keymapDefault[0]);
+ m_keymap.resize(mappingSize);
+ std::copy_n( &keymapDefault[0], mappingSize, m_keymap.begin() );
+
+ // reset state, so we could switch keymaps at runtime
+ m_modifiers = 0;
+ m_capsLock = false;
+ m_numLock = false;
+ m_scrollLock = false;
+
+ //Set locks according to keyboard leds
+ int leds = 0;
+ if (ioctl(m_fd, KDGETLED, &leds) < 0) {
+ qWarning("Failed to query led states. Settings numlock & capslock off");
+ switchLed(LED_NUM, false);
+ switchLed(LED_CAP, false);
+ switchLed(LED_SCR, false);
+ } else {
+ if ((leds & LED_CAP) > 0)
+ m_capsLock = true;
+ if ((leds & LED_NUM) > 0)
+ m_numLock = true;
+ if ((leds & LED_SCR) > 0)
+ m_scrollLock = true;
+#ifdef QT_BSD_KEYBOARD_DEBUG
+ qWarning("numlock=%d , capslock=%d, scrolllock=%d",m_numLock, m_capsLock, m_scrollLock);
+#endif
+ }
+}
diff --git a/src/plugins/generic/bsdkeyboard/qbsdkeyboard.h b/src/plugins/generic/bsdkeyboard/qbsdkeyboard.h
new file mode 100644
index 0000000000..1a7cbc1f9a
--- /dev/null
+++ b/src/plugins/generic/bsdkeyboard/qbsdkeyboard.h
@@ -0,0 +1,139 @@
+/****************************************************************************
+**
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QBSDKEYBOARD_H
+#define QBSDKEYBOARD_H
+
+#include <qobject.h>
+#include <QDataStream>
+#include <QVector>
+
+QT_BEGIN_NAMESPACE
+
+class QSocketNotifier;
+
+struct termios;
+
+enum {
+ Bsd_NoKeyMode = -1
+};
+
+namespace QBsdKeyboardMap {
+ const quint32 FileMagic = 0x514d4150; // 'QMAP'
+
+ struct Mapping {
+ quint16 keycode;
+ quint16 unicode;
+ quint32 qtcode;
+ quint8 modifiers;
+ quint8 flags;
+ quint16 special;
+
+ };
+
+ enum Flags {
+ NoFlags = 0x00,
+ IsLetter = 0x01,
+ IsModifier = 0x02
+ };
+
+ enum Modifiers {
+ ModPlain = 0x00,
+ ModShift = 0x01,
+ ModAltGr = 0x02,
+ ModControl = 0x04,
+ ModAlt = 0x08,
+ ModShiftL = 0x10,
+ ModShiftR = 0x20,
+ ModCtrlL = 0x40,
+ ModCtrlR = 0x80
+ // ModCapsShift = 0x100, // not supported!
+ };
+}
+
+inline QDataStream &operator>>(QDataStream &ds, QBsdKeyboardMap::Mapping &m)
+{
+ return ds >> m.keycode >> m.unicode >> m.qtcode >> m.modifiers >> m.flags >> m.special;
+}
+
+class QBsdKeyboardHandler : public QObject
+{
+ Q_OBJECT
+
+public:
+ QBsdKeyboardHandler(const QString &key, const QString &specification);
+ ~QBsdKeyboardHandler() override;
+
+ static Qt::KeyboardModifiers toQtModifiers(quint8 mod)
+ {
+ Qt::KeyboardModifiers qtmod = Qt::NoModifier;
+
+ if (mod & (QBsdKeyboardMap::ModShift | QBsdKeyboardMap::ModShiftL | QBsdKeyboardMap::ModShiftR))
+ qtmod |= Qt::ShiftModifier;
+ if (mod & (QBsdKeyboardMap::ModControl | QBsdKeyboardMap::ModCtrlL | QBsdKeyboardMap::ModCtrlR))
+ qtmod |= Qt::ControlModifier;
+ if (mod & QBsdKeyboardMap::ModAlt)
+ qtmod |= Qt::AltModifier;
+
+ return qtmod;
+ }
+
+protected:
+ void switchLed(int led, bool state);
+ void processKeycode(quint16 keycode, bool pressed, bool autorepeat);
+ void processKeyEvent(int nativecode, int unicode, int qtcode,
+ Qt::KeyboardModifiers modifiers, bool isPress, bool autoRepeat);
+ void revertTTYSettings();
+ void resetKeymap();
+ void readKeyboardData();
+
+private:
+ QScopedPointer<QSocketNotifier> m_notifier;
+ QScopedPointer<termios> m_kbdOrigTty;
+ int m_origKbdMode = Bsd_NoKeyMode;
+ int m_fd = -1;
+ bool m_shouldClose = false;
+ QString m_spec;
+
+ // keymap handling
+ quint8 m_modifiers = 0;
+ bool m_capsLock = false;
+ bool m_numLock = false;
+ bool m_scrollLock = false;
+
+ QVector<QBsdKeyboardMap::Mapping> m_keymap;
+};
+
+QT_END_NAMESPACE
+
+#endif // QBSDKEYBOARD_H
diff --git a/src/plugins/generic/bsdkeyboard/qbsdkeyboard_defaultmap.h b/src/plugins/generic/bsdkeyboard/qbsdkeyboard_defaultmap.h
new file mode 100644
index 0000000000..45cf5944bc
--- /dev/null
+++ b/src/plugins/generic/bsdkeyboard/qbsdkeyboard_defaultmap.h
@@ -0,0 +1,622 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QBSDKEYBOARD_DEFAULTMAP_P_H
+#define QBSDKEYBOARD_DEFAULTMAP_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qnamespace.h"
+
+// no QT_BEGIN_NAMESPACE, since we include it internally...
+using namespace QBsdKeyboardMap;
+
+#define QCTRL(x) ((x) | Qt::ControlModifier)
+#define QALT(x) ((x) | Qt::AltModifier)
+#define QKEYPAD(x) ((x) | Qt::KeypadModifier)
+
+const QBsdKeyboardMap::Mapping keymapDefault[] = {
+ { 1, 0xffff, Qt::Key_Escape, ModPlain, NoFlags, 0x0000 },
+ { 2, 0x0031, Qt::Key_1, ModPlain, NoFlags, 0x0000 },
+ { 2, 0x0021, Qt::Key_Exclam, ModShift, NoFlags, 0x0000 },
+ { 3, 0x0032, Qt::Key_2, ModPlain, NoFlags, 0x0000 },
+ { 3, 0x0040, Qt::Key_At, ModShift, NoFlags, 0x0000 },
+ { 3, 0x0040, Qt::Key_At, ModAltGr, NoFlags, 0x0000 },
+ { 4, 0x0033, Qt::Key_3, ModPlain, NoFlags, 0x0000 },
+ { 4, 0x0023, Qt::Key_NumberSign, ModShift, NoFlags, 0x0000 },
+ { 4, 0xffff, Qt::Key_Escape, ModControl, NoFlags, 0x0000 },
+ { 5, 0x0034, Qt::Key_4, ModPlain, NoFlags, 0x0000 },
+ { 5, 0x0024, Qt::Key_Dollar, ModShift, NoFlags, 0x0000 },
+ { 5, 0x0024, Qt::Key_Dollar, ModAltGr, NoFlags, 0x0000 },
+ { 5, 0x005c, QCTRL(Qt::Key_Backslash), ModControl, NoFlags, 0x0000 },
+ { 6, 0x0035, Qt::Key_5, ModPlain, NoFlags, 0x0000 },
+ { 6, 0x0025, Qt::Key_Percent, ModShift, NoFlags, 0x0000 },
+ { 6, 0x005d, QCTRL(Qt::Key_BracketRight), ModControl, NoFlags, 0x0000 },
+ { 7, 0x0036, Qt::Key_6, ModPlain, NoFlags, 0x0000 },
+ { 7, 0x005e, Qt::Key_AsciiCircum, ModShift, NoFlags, 0x0000 },
+ { 7, 0x005e, QCTRL(Qt::Key_AsciiCircum), ModControl, NoFlags, 0x0000 },
+ { 8, 0x0037, Qt::Key_7, ModPlain, NoFlags, 0x0000 },
+ { 8, 0x0026, Qt::Key_Ampersand, ModShift, NoFlags, 0x0000 },
+ { 8, 0x007b, Qt::Key_BraceLeft, ModAltGr, NoFlags, 0x0000 },
+ { 8, 0x005f, QCTRL(Qt::Key_Underscore), ModControl, NoFlags, 0x0000 },
+ { 9, 0x0038, Qt::Key_8, ModPlain, NoFlags, 0x0000 },
+ { 9, 0x002a, Qt::Key_Asterisk, ModShift, NoFlags, 0x0000 },
+ { 9, 0x005b, Qt::Key_BracketLeft, ModAltGr, NoFlags, 0x0000 },
+ { 9, 0xffff, Qt::Key_Backspace, ModControl, NoFlags, 0x0000 },
+ { 10, 0x0039, Qt::Key_9, ModPlain, NoFlags, 0x0000 },
+ { 10, 0x0028, Qt::Key_ParenLeft, ModShift, NoFlags, 0x0000 },
+ { 10, 0x005d, Qt::Key_BracketRight, ModAltGr, NoFlags, 0x0000 },
+ { 11, 0x0030, Qt::Key_0, ModPlain, NoFlags, 0x0000 },
+ { 11, 0x0029, Qt::Key_ParenRight, ModShift, NoFlags, 0x0000 },
+ { 11, 0x007d, Qt::Key_BraceRight, ModAltGr, NoFlags, 0x0000 },
+ { 12, 0x002d, Qt::Key_Minus, ModPlain, NoFlags, 0x0000 },
+ { 12, 0x005f, Qt::Key_Underscore, ModShift, NoFlags, 0x0000 },
+ { 12, 0x005c, Qt::Key_Backslash, ModAltGr, NoFlags, 0x0000 },
+ { 12, 0x005f, QCTRL(Qt::Key_Underscore), ModControl, NoFlags, 0x0000 },
+ { 12, 0x005f, QCTRL(Qt::Key_Underscore), ModShift | ModControl, NoFlags, 0x0000 },
+ { 13, 0x003d, Qt::Key_Equal, ModPlain, NoFlags, 0x0000 },
+ { 13, 0x002b, Qt::Key_Plus, ModShift, NoFlags, 0x0000 },
+ { 14, 0xffff, Qt::Key_Backspace, ModPlain, NoFlags, 0x0000 },
+ { 15, 0xffff, Qt::Key_Tab, ModPlain, NoFlags, 0x0000 },
+ { 16, 0x0071, Qt::Key_Q, ModPlain, IsLetter, 0x0000 },
+ { 16, 0x0051, Qt::Key_Q, ModShift, IsLetter, 0x0000 },
+ { 16, 0x0071, Qt::Key_Q, ModAltGr, IsLetter, 0x0000 },
+ { 16, 0x0051, Qt::Key_Q, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 16, 0x0071, QCTRL(Qt::Key_Q), ModControl, IsLetter, 0x0000 },
+ { 16, 0x0071, QCTRL(Qt::Key_Q), ModShift | ModControl, IsLetter, 0x0000 },
+ { 16, 0x0071, QCTRL(Qt::Key_Q), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 16, 0x0071, QCTRL(Qt::Key_Q), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 16, 0x0071, QALT(Qt::Key_Q), ModAlt, IsLetter, 0x0000 },
+ { 16, 0x0071, QALT(Qt::Key_Q), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 16, 0x0071, QALT(Qt::Key_Q), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 16, 0x0071, QALT(Qt::Key_Q), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 16, 0x0071, QCTRL(QALT(Qt::Key_Q)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 16, 0x0071, QCTRL(QALT(Qt::Key_Q)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 16, 0x0071, QCTRL(QALT(Qt::Key_Q)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 16, 0x0071, QCTRL(QALT(Qt::Key_Q)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 17, 0x0077, Qt::Key_W, ModPlain, IsLetter, 0x0000 },
+ { 17, 0x0057, Qt::Key_W, ModShift, IsLetter, 0x0000 },
+ { 17, 0x0077, Qt::Key_W, ModAltGr, IsLetter, 0x0000 },
+ { 17, 0x0057, Qt::Key_W, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 17, 0x0077, QCTRL(Qt::Key_W), ModControl, IsLetter, 0x0000 },
+ { 17, 0x0077, QCTRL(Qt::Key_W), ModShift | ModControl, IsLetter, 0x0000 },
+ { 17, 0x0077, QCTRL(Qt::Key_W), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 17, 0x0077, QCTRL(Qt::Key_W), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 17, 0x0077, QALT(Qt::Key_W), ModAlt, IsLetter, 0x0000 },
+ { 17, 0x0077, QALT(Qt::Key_W), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 17, 0x0077, QALT(Qt::Key_W), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 17, 0x0077, QALT(Qt::Key_W), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 17, 0x0077, QCTRL(QALT(Qt::Key_W)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 17, 0x0077, QCTRL(QALT(Qt::Key_W)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 17, 0x0077, QCTRL(QALT(Qt::Key_W)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 17, 0x0077, QCTRL(QALT(Qt::Key_W)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 18, 0x0065, Qt::Key_E, ModPlain, IsLetter, 0x0000 },
+ { 18, 0x0045, Qt::Key_E, ModShift, IsLetter, 0x0000 },
+ { 18, 0x0065, Qt::Key_E, ModAltGr, IsLetter, 0x0000 },
+ { 18, 0x0045, Qt::Key_E, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 18, 0x0065, QCTRL(Qt::Key_E), ModControl, IsLetter, 0x0000 },
+ { 18, 0x0065, QCTRL(Qt::Key_E), ModShift | ModControl, IsLetter, 0x0000 },
+ { 18, 0x0065, QCTRL(Qt::Key_E), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 18, 0x0065, QCTRL(Qt::Key_E), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 18, 0x0065, QALT(Qt::Key_E), ModAlt, IsLetter, 0x0000 },
+ { 18, 0x0065, QALT(Qt::Key_E), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 18, 0x0065, QALT(Qt::Key_E), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 18, 0x0065, QALT(Qt::Key_E), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 18, 0x0065, QCTRL(QALT(Qt::Key_E)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 18, 0x0065, QCTRL(QALT(Qt::Key_E)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 18, 0x0065, QCTRL(QALT(Qt::Key_E)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 18, 0x0065, QCTRL(QALT(Qt::Key_E)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 19, 0x0072, Qt::Key_R, ModPlain, IsLetter, 0x0000 },
+ { 19, 0x0052, Qt::Key_R, ModShift, IsLetter, 0x0000 },
+ { 19, 0x0072, Qt::Key_R, ModAltGr, IsLetter, 0x0000 },
+ { 19, 0x0052, Qt::Key_R, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 19, 0x0072, QCTRL(Qt::Key_R), ModControl, IsLetter, 0x0000 },
+ { 19, 0x0072, QCTRL(Qt::Key_R), ModShift | ModControl, IsLetter, 0x0000 },
+ { 19, 0x0072, QCTRL(Qt::Key_R), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 19, 0x0072, QCTRL(Qt::Key_R), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 19, 0x0072, QALT(Qt::Key_R), ModAlt, IsLetter, 0x0000 },
+ { 19, 0x0072, QALT(Qt::Key_R), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 19, 0x0072, QALT(Qt::Key_R), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 19, 0x0072, QALT(Qt::Key_R), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 19, 0x0072, QCTRL(QALT(Qt::Key_R)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 19, 0x0072, QCTRL(QALT(Qt::Key_R)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 19, 0x0072, QCTRL(QALT(Qt::Key_R)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 19, 0x0072, QCTRL(QALT(Qt::Key_R)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 20, 0x0074, Qt::Key_T, ModPlain, IsLetter, 0x0000 },
+ { 20, 0x0054, Qt::Key_T, ModShift, IsLetter, 0x0000 },
+ { 20, 0x0074, Qt::Key_T, ModAltGr, IsLetter, 0x0000 },
+ { 20, 0x0054, Qt::Key_T, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 20, 0x0074, QCTRL(Qt::Key_T), ModControl, IsLetter, 0x0000 },
+ { 20, 0x0074, QCTRL(Qt::Key_T), ModShift | ModControl, IsLetter, 0x0000 },
+ { 20, 0x0074, QCTRL(Qt::Key_T), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 20, 0x0074, QCTRL(Qt::Key_T), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 20, 0x0074, QALT(Qt::Key_T), ModAlt, IsLetter, 0x0000 },
+ { 20, 0x0074, QALT(Qt::Key_T), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 20, 0x0074, QALT(Qt::Key_T), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 20, 0x0074, QALT(Qt::Key_T), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 20, 0x0074, QCTRL(QALT(Qt::Key_T)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 20, 0x0074, QCTRL(QALT(Qt::Key_T)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 20, 0x0074, QCTRL(QALT(Qt::Key_T)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 20, 0x0074, QCTRL(QALT(Qt::Key_T)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 21, 0x0079, Qt::Key_Y, ModPlain, IsLetter, 0x0000 },
+ { 21, 0x0059, Qt::Key_Y, ModShift, IsLetter, 0x0000 },
+ { 21, 0x0079, Qt::Key_Y, ModAltGr, IsLetter, 0x0000 },
+ { 21, 0x0059, Qt::Key_Y, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 21, 0x0079, QCTRL(Qt::Key_Y), ModControl, IsLetter, 0x0000 },
+ { 21, 0x0079, QCTRL(Qt::Key_Y), ModShift | ModControl, IsLetter, 0x0000 },
+ { 21, 0x0079, QCTRL(Qt::Key_Y), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 21, 0x0079, QCTRL(Qt::Key_Y), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 21, 0x0079, QALT(Qt::Key_Y), ModAlt, IsLetter, 0x0000 },
+ { 21, 0x0079, QALT(Qt::Key_Y), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 21, 0x0079, QALT(Qt::Key_Y), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 21, 0x0079, QALT(Qt::Key_Y), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 21, 0x0079, QCTRL(QALT(Qt::Key_Y)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 21, 0x0079, QCTRL(QALT(Qt::Key_Y)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 21, 0x0079, QCTRL(QALT(Qt::Key_Y)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 21, 0x0079, QCTRL(QALT(Qt::Key_Y)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 22, 0x0075, Qt::Key_U, ModPlain, IsLetter, 0x0000 },
+ { 22, 0x0055, Qt::Key_U, ModShift, IsLetter, 0x0000 },
+ { 22, 0x0075, Qt::Key_U, ModAltGr, IsLetter, 0x0000 },
+ { 22, 0x0055, Qt::Key_U, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 22, 0x0075, QCTRL(Qt::Key_U), ModControl, IsLetter, 0x0000 },
+ { 22, 0x0075, QCTRL(Qt::Key_U), ModShift | ModControl, IsLetter, 0x0000 },
+ { 22, 0x0075, QCTRL(Qt::Key_U), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 22, 0x0075, QCTRL(Qt::Key_U), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 22, 0x0075, QALT(Qt::Key_U), ModAlt, IsLetter, 0x0000 },
+ { 22, 0x0075, QALT(Qt::Key_U), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 22, 0x0075, QALT(Qt::Key_U), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 22, 0x0075, QALT(Qt::Key_U), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 22, 0x0075, QCTRL(QALT(Qt::Key_U)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 22, 0x0075, QCTRL(QALT(Qt::Key_U)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 22, 0x0075, QCTRL(QALT(Qt::Key_U)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 22, 0x0075, QCTRL(QALT(Qt::Key_U)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 23, 0x0069, Qt::Key_I, ModPlain, IsLetter, 0x0000 },
+ { 23, 0x0049, Qt::Key_I, ModShift, IsLetter, 0x0000 },
+ { 23, 0x0069, Qt::Key_I, ModAltGr, IsLetter, 0x0000 },
+ { 23, 0x0049, Qt::Key_I, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 23, 0x0069, QCTRL(Qt::Key_I), ModControl, IsLetter, 0x0000 },
+ { 23, 0x0069, QCTRL(Qt::Key_I), ModShift | ModControl, IsLetter, 0x0000 },
+ { 23, 0x0069, QCTRL(Qt::Key_I), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 23, 0x0069, QCTRL(Qt::Key_I), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 23, 0x0069, QALT(Qt::Key_I), ModAlt, IsLetter, 0x0000 },
+ { 23, 0x0069, QALT(Qt::Key_I), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 23, 0x0069, QALT(Qt::Key_I), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 23, 0x0069, QALT(Qt::Key_I), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 23, 0x0069, QCTRL(QALT(Qt::Key_I)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 23, 0x0069, QCTRL(QALT(Qt::Key_I)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 23, 0x0069, QCTRL(QALT(Qt::Key_I)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 23, 0x0069, QCTRL(QALT(Qt::Key_I)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 24, 0x006f, Qt::Key_O, ModPlain, IsLetter, 0x0000 },
+ { 24, 0x004f, Qt::Key_O, ModShift, IsLetter, 0x0000 },
+ { 24, 0x006f, Qt::Key_O, ModAltGr, IsLetter, 0x0000 },
+ { 24, 0x004f, Qt::Key_O, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 24, 0x006f, QCTRL(Qt::Key_O), ModControl, IsLetter, 0x0000 },
+ { 24, 0x006f, QCTRL(Qt::Key_O), ModShift | ModControl, IsLetter, 0x0000 },
+ { 24, 0x006f, QCTRL(Qt::Key_O), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 24, 0x006f, QCTRL(Qt::Key_O), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 24, 0x006f, QALT(Qt::Key_O), ModAlt, IsLetter, 0x0000 },
+ { 24, 0x006f, QALT(Qt::Key_O), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 24, 0x006f, QALT(Qt::Key_O), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 24, 0x006f, QALT(Qt::Key_O), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 24, 0x006f, QCTRL(QALT(Qt::Key_O)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 24, 0x006f, QCTRL(QALT(Qt::Key_O)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 24, 0x006f, QCTRL(QALT(Qt::Key_O)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 24, 0x006f, QCTRL(QALT(Qt::Key_O)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 25, 0x0070, Qt::Key_P, ModPlain, IsLetter, 0x0000 },
+ { 25, 0x0050, Qt::Key_P, ModShift, IsLetter, 0x0000 },
+ { 25, 0x0070, Qt::Key_P, ModAltGr, IsLetter, 0x0000 },
+ { 25, 0x0050, Qt::Key_P, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 25, 0x0070, QCTRL(Qt::Key_P), ModControl, IsLetter, 0x0000 },
+ { 25, 0x0070, QCTRL(Qt::Key_P), ModShift | ModControl, IsLetter, 0x0000 },
+ { 25, 0x0070, QCTRL(Qt::Key_P), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 25, 0x0070, QCTRL(Qt::Key_P), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 25, 0x0070, QALT(Qt::Key_P), ModAlt, IsLetter, 0x0000 },
+ { 25, 0x0070, QALT(Qt::Key_P), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 25, 0x0070, QALT(Qt::Key_P), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 25, 0x0070, QALT(Qt::Key_P), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 25, 0x0070, QCTRL(QALT(Qt::Key_P)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 25, 0x0070, QCTRL(QALT(Qt::Key_P)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 25, 0x0070, QCTRL(QALT(Qt::Key_P)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 25, 0x0070, QCTRL(QALT(Qt::Key_P)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 26, 0x005b, Qt::Key_BracketLeft, ModPlain, NoFlags, 0x0000 },
+ { 26, 0x007b, Qt::Key_BraceLeft, ModShift, NoFlags, 0x0000 },
+ { 26, 0xffff, Qt::Key_Escape, ModControl, NoFlags, 0x0000 },
+ { 27, 0x005d, Qt::Key_BracketRight, ModPlain, NoFlags, 0x0000 },
+ { 27, 0x007d, Qt::Key_BraceRight, ModShift, NoFlags, 0x0000 },
+ { 27, 0x007e, Qt::Key_AsciiTilde, ModAltGr, NoFlags, 0x0000 },
+ { 27, 0x005d, QCTRL(Qt::Key_BracketRight), ModControl, NoFlags, 0x0000 },
+ { 28, 0xffff, Qt::Key_Return, ModPlain, NoFlags, 0x0000 },
+ { 28, 0x006d, QCTRL(QALT(Qt::Key_M)), ModAlt, NoFlags, 0x0000 },
+ { 29, 0xffff, Qt::Key_Control, ModPlain, IsModifier, ModControl },
+ { 30, 0x0061, Qt::Key_A, ModPlain, IsLetter, 0x0000 },
+ { 30, 0x0041, Qt::Key_A, ModShift, IsLetter, 0x0000 },
+ { 30, 0x0061, Qt::Key_A, ModAltGr, IsLetter, 0x0000 },
+ { 30, 0x0041, Qt::Key_A, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 30, 0x0061, QCTRL(Qt::Key_A), ModControl, IsLetter, 0x0000 },
+ { 30, 0x0061, QCTRL(Qt::Key_A), ModShift | ModControl, IsLetter, 0x0000 },
+ { 30, 0x0061, QCTRL(Qt::Key_A), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 30, 0x0061, QCTRL(Qt::Key_A), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 30, 0x0061, QALT(Qt::Key_A), ModAlt, IsLetter, 0x0000 },
+ { 30, 0x0061, QALT(Qt::Key_A), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 30, 0x0061, QALT(Qt::Key_A), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 30, 0x0061, QALT(Qt::Key_A), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 30, 0x0061, QCTRL(QALT(Qt::Key_A)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 30, 0x0061, QCTRL(QALT(Qt::Key_A)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 30, 0x0061, QCTRL(QALT(Qt::Key_A)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 30, 0x0061, QCTRL(QALT(Qt::Key_A)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 31, 0x0073, Qt::Key_S, ModPlain, IsLetter, 0x0000 },
+ { 31, 0x0053, Qt::Key_S, ModShift, IsLetter, 0x0000 },
+ { 31, 0x0073, Qt::Key_S, ModAltGr, IsLetter, 0x0000 },
+ { 31, 0x0053, Qt::Key_S, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 31, 0x0073, QCTRL(Qt::Key_S), ModControl, IsLetter, 0x0000 },
+ { 31, 0x0073, QCTRL(Qt::Key_S), ModShift | ModControl, IsLetter, 0x0000 },
+ { 31, 0x0073, QCTRL(Qt::Key_S), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 31, 0x0073, QCTRL(Qt::Key_S), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 31, 0x0073, QALT(Qt::Key_S), ModAlt, IsLetter, 0x0000 },
+ { 31, 0x0073, QALT(Qt::Key_S), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 31, 0x0073, QALT(Qt::Key_S), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 31, 0x0073, QALT(Qt::Key_S), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 31, 0x0073, QCTRL(QALT(Qt::Key_S)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 31, 0x0073, QCTRL(QALT(Qt::Key_S)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 31, 0x0073, QCTRL(QALT(Qt::Key_S)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 31, 0x0073, QCTRL(QALT(Qt::Key_S)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 32, 0x0064, Qt::Key_D, ModPlain, IsLetter, 0x0000 },
+ { 32, 0x0044, Qt::Key_D, ModShift, IsLetter, 0x0000 },
+ { 32, 0x0064, Qt::Key_D, ModAltGr, IsLetter, 0x0000 },
+ { 32, 0x0044, Qt::Key_D, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 32, 0x0064, QCTRL(Qt::Key_D), ModControl, IsLetter, 0x0000 },
+ { 32, 0x0064, QCTRL(Qt::Key_D), ModShift | ModControl, IsLetter, 0x0000 },
+ { 32, 0x0064, QCTRL(Qt::Key_D), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 32, 0x0064, QCTRL(Qt::Key_D), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 32, 0x0064, QALT(Qt::Key_D), ModAlt, IsLetter, 0x0000 },
+ { 32, 0x0064, QALT(Qt::Key_D), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 32, 0x0064, QALT(Qt::Key_D), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 32, 0x0064, QALT(Qt::Key_D), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 32, 0x0064, QCTRL(QALT(Qt::Key_D)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 32, 0x0064, QCTRL(QALT(Qt::Key_D)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 32, 0x0064, QCTRL(QALT(Qt::Key_D)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 32, 0x0064, QCTRL(QALT(Qt::Key_D)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 33, 0x0066, Qt::Key_F, ModPlain, IsLetter, 0x0000 },
+ { 33, 0x0046, Qt::Key_F, ModShift, IsLetter, 0x0000 },
+ { 33, 0x0066, Qt::Key_F, ModAltGr, IsLetter, 0x0000 },
+ { 33, 0x0046, Qt::Key_F, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 33, 0x0066, QCTRL(Qt::Key_F), ModControl, IsLetter, 0x0000 },
+ { 33, 0x0066, QCTRL(Qt::Key_F), ModShift | ModControl, IsLetter, 0x0000 },
+ { 33, 0x0066, QCTRL(Qt::Key_F), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 33, 0x0066, QCTRL(Qt::Key_F), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 33, 0x0066, QALT(Qt::Key_F), ModAlt, IsLetter, 0x0000 },
+ { 33, 0x0066, QALT(Qt::Key_F), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 33, 0x0066, QALT(Qt::Key_F), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 33, 0x0066, QALT(Qt::Key_F), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 33, 0x0066, QCTRL(QALT(Qt::Key_F)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 33, 0x0066, QCTRL(QALT(Qt::Key_F)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 33, 0x0066, QCTRL(QALT(Qt::Key_F)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 33, 0x0066, QCTRL(QALT(Qt::Key_F)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 34, 0x0067, Qt::Key_G, ModPlain, IsLetter, 0x0000 },
+ { 34, 0x0047, Qt::Key_G, ModShift, IsLetter, 0x0000 },
+ { 34, 0x0067, Qt::Key_G, ModAltGr, IsLetter, 0x0000 },
+ { 34, 0x0047, Qt::Key_G, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 34, 0x0067, QCTRL(Qt::Key_G), ModControl, IsLetter, 0x0000 },
+ { 34, 0x0067, QCTRL(Qt::Key_G), ModShift | ModControl, IsLetter, 0x0000 },
+ { 34, 0x0067, QCTRL(Qt::Key_G), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 34, 0x0067, QCTRL(Qt::Key_G), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 34, 0x0067, QALT(Qt::Key_G), ModAlt, IsLetter, 0x0000 },
+ { 34, 0x0067, QALT(Qt::Key_G), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 34, 0x0067, QALT(Qt::Key_G), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 34, 0x0067, QALT(Qt::Key_G), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 34, 0x0067, QCTRL(QALT(Qt::Key_G)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 34, 0x0067, QCTRL(QALT(Qt::Key_G)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 34, 0x0067, QCTRL(QALT(Qt::Key_G)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 34, 0x0067, QCTRL(QALT(Qt::Key_G)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 35, 0x0068, Qt::Key_H, ModPlain, IsLetter, 0x0000 },
+ { 35, 0x0048, Qt::Key_H, ModShift, IsLetter, 0x0000 },
+ { 35, 0x0068, Qt::Key_H, ModAltGr, IsLetter, 0x0000 },
+ { 35, 0x0048, Qt::Key_H, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 35, 0x0068, QCTRL(Qt::Key_H), ModControl, IsLetter, 0x0000 },
+ { 35, 0x0068, QCTRL(Qt::Key_H), ModShift | ModControl, IsLetter, 0x0000 },
+ { 35, 0x0068, QCTRL(Qt::Key_H), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 35, 0x0068, QCTRL(Qt::Key_H), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 35, 0x0068, QALT(Qt::Key_H), ModAlt, IsLetter, 0x0000 },
+ { 35, 0x0068, QALT(Qt::Key_H), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 35, 0x0068, QALT(Qt::Key_H), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 35, 0x0068, QALT(Qt::Key_H), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 35, 0x0068, QCTRL(QALT(Qt::Key_H)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 35, 0x0068, QCTRL(QALT(Qt::Key_H)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 35, 0x0068, QCTRL(QALT(Qt::Key_H)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 35, 0x0068, QCTRL(QALT(Qt::Key_H)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 36, 0x006a, Qt::Key_J, ModPlain, IsLetter, 0x0000 },
+ { 36, 0x004a, Qt::Key_J, ModShift, IsLetter, 0x0000 },
+ { 36, 0x006a, Qt::Key_J, ModAltGr, IsLetter, 0x0000 },
+ { 36, 0x004a, Qt::Key_J, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 36, 0x006a, QCTRL(Qt::Key_J), ModControl, IsLetter, 0x0000 },
+ { 36, 0x006a, QCTRL(Qt::Key_J), ModShift | ModControl, IsLetter, 0x0000 },
+ { 36, 0x006a, QCTRL(Qt::Key_J), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 36, 0x006a, QCTRL(Qt::Key_J), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 36, 0x006a, QALT(Qt::Key_J), ModAlt, IsLetter, 0x0000 },
+ { 36, 0x006a, QALT(Qt::Key_J), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 36, 0x006a, QALT(Qt::Key_J), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 36, 0x006a, QALT(Qt::Key_J), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 36, 0x006a, QCTRL(QALT(Qt::Key_J)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 36, 0x006a, QCTRL(QALT(Qt::Key_J)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 36, 0x006a, QCTRL(QALT(Qt::Key_J)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 36, 0x006a, QCTRL(QALT(Qt::Key_J)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 37, 0x006b, Qt::Key_K, ModPlain, IsLetter, 0x0000 },
+ { 37, 0x004b, Qt::Key_K, ModShift, IsLetter, 0x0000 },
+ { 37, 0x006b, Qt::Key_K, ModAltGr, IsLetter, 0x0000 },
+ { 37, 0x004b, Qt::Key_K, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 37, 0x006b, QCTRL(Qt::Key_K), ModControl, IsLetter, 0x0000 },
+ { 37, 0x006b, QCTRL(Qt::Key_K), ModShift | ModControl, IsLetter, 0x0000 },
+ { 37, 0x006b, QCTRL(Qt::Key_K), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 37, 0x006b, QCTRL(Qt::Key_K), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 37, 0x006b, QALT(Qt::Key_K), ModAlt, IsLetter, 0x0000 },
+ { 37, 0x006b, QALT(Qt::Key_K), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 37, 0x006b, QALT(Qt::Key_K), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 37, 0x006b, QALT(Qt::Key_K), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 37, 0x006b, QCTRL(QALT(Qt::Key_K)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 37, 0x006b, QCTRL(QALT(Qt::Key_K)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 37, 0x006b, QCTRL(QALT(Qt::Key_K)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 37, 0x006b, QCTRL(QALT(Qt::Key_K)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 38, 0x006c, Qt::Key_L, ModPlain, IsLetter, 0x0000 },
+ { 38, 0x004c, Qt::Key_L, ModShift, IsLetter, 0x0000 },
+ { 38, 0x006c, Qt::Key_L, ModAltGr, IsLetter, 0x0000 },
+ { 38, 0x004c, Qt::Key_L, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 38, 0x006c, QCTRL(Qt::Key_L), ModControl, IsLetter, 0x0000 },
+ { 38, 0x006c, QCTRL(Qt::Key_L), ModShift | ModControl, IsLetter, 0x0000 },
+ { 38, 0x006c, QCTRL(Qt::Key_L), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 38, 0x006c, QCTRL(Qt::Key_L), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 38, 0x006c, QALT(Qt::Key_L), ModAlt, IsLetter, 0x0000 },
+ { 38, 0x006c, QALT(Qt::Key_L), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 38, 0x006c, QALT(Qt::Key_L), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 38, 0x006c, QALT(Qt::Key_L), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 38, 0x006c, QCTRL(QALT(Qt::Key_L)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 38, 0x006c, QCTRL(QALT(Qt::Key_L)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 38, 0x006c, QCTRL(QALT(Qt::Key_L)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 38, 0x006c, QCTRL(QALT(Qt::Key_L)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 39, 0x003b, Qt::Key_Semicolon, ModPlain, NoFlags, 0x0000 },
+ { 39, 0x003a, Qt::Key_Colon, ModShift, NoFlags, 0x0000 },
+ { 40, 0x0027, Qt::Key_Apostrophe, ModPlain, NoFlags, 0x0000 },
+ { 40, 0x0022, Qt::Key_QuoteDbl, ModShift, NoFlags, 0x0000 },
+ { 40, 0x0067, QCTRL(Qt::Key_G), ModControl, NoFlags, 0x0000 },
+ { 41, 0x0060, Qt::Key_QuoteLeft, ModPlain, NoFlags, 0x0000 },
+ { 41, 0x007e, Qt::Key_AsciiTilde, ModShift, NoFlags, 0x0000 },
+ { 42, 0xffff, Qt::Key_Shift, ModPlain, IsModifier, ModShift },
+ { 43, 0x005c, Qt::Key_Backslash, ModPlain, NoFlags, 0x0000 },
+ { 43, 0x007c, Qt::Key_Bar, ModShift, NoFlags, 0x0000 },
+ { 43, 0x005c, QCTRL(Qt::Key_Backslash), ModControl, NoFlags, 0x0000 },
+ { 44, 0x007a, Qt::Key_Z, ModPlain, IsLetter, 0x0000 },
+ { 44, 0x005a, Qt::Key_Z, ModShift, IsLetter, 0x0000 },
+ { 44, 0x007a, Qt::Key_Z, ModAltGr, IsLetter, 0x0000 },
+ { 44, 0x005a, Qt::Key_Z, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 44, 0x007a, QCTRL(Qt::Key_Z), ModControl, IsLetter, 0x0000 },
+ { 44, 0x007a, QCTRL(Qt::Key_Z), ModShift | ModControl, IsLetter, 0x0000 },
+ { 44, 0x007a, QCTRL(Qt::Key_Z), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 44, 0x007a, QCTRL(Qt::Key_Z), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 44, 0x007a, QALT(Qt::Key_Z), ModAlt, IsLetter, 0x0000 },
+ { 44, 0x007a, QALT(Qt::Key_Z), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 44, 0x007a, QALT(Qt::Key_Z), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 44, 0x007a, QALT(Qt::Key_Z), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 44, 0x007a, QCTRL(QALT(Qt::Key_Z)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 44, 0x007a, QCTRL(QALT(Qt::Key_Z)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 44, 0x007a, QCTRL(QALT(Qt::Key_Z)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 44, 0x007a, QCTRL(QALT(Qt::Key_Z)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 45, 0x0078, Qt::Key_X, ModPlain, IsLetter, 0x0000 },
+ { 45, 0x0058, Qt::Key_X, ModShift, IsLetter, 0x0000 },
+ { 45, 0x0078, Qt::Key_X, ModAltGr, IsLetter, 0x0000 },
+ { 45, 0x0058, Qt::Key_X, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 45, 0x0078, QCTRL(Qt::Key_X), ModControl, IsLetter, 0x0000 },
+ { 45, 0x0078, QCTRL(Qt::Key_X), ModShift | ModControl, IsLetter, 0x0000 },
+ { 45, 0x0078, QCTRL(Qt::Key_X), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 45, 0x0078, QCTRL(Qt::Key_X), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 45, 0x0078, QALT(Qt::Key_X), ModAlt, IsLetter, 0x0000 },
+ { 45, 0x0078, QALT(Qt::Key_X), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 45, 0x0078, QALT(Qt::Key_X), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 45, 0x0078, QALT(Qt::Key_X), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 45, 0x0078, QCTRL(QALT(Qt::Key_X)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 45, 0x0078, QCTRL(QALT(Qt::Key_X)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 45, 0x0078, QCTRL(QALT(Qt::Key_X)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 45, 0x0078, QCTRL(QALT(Qt::Key_X)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 46, 0x0063, Qt::Key_C, ModPlain, IsLetter, 0x0000 },
+ { 46, 0x0043, Qt::Key_C, ModShift, IsLetter, 0x0000 },
+ { 46, 0x0063, Qt::Key_C, ModAltGr, IsLetter, 0x0000 },
+ { 46, 0x0043, Qt::Key_C, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 46, 0x0063, QCTRL(Qt::Key_C), ModControl, IsLetter, 0x0000 },
+ { 46, 0x0063, QCTRL(Qt::Key_C), ModShift | ModControl, IsLetter, 0x0000 },
+ { 46, 0x0063, QCTRL(Qt::Key_C), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 46, 0x0063, QCTRL(Qt::Key_C), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 46, 0x0063, QALT(Qt::Key_C), ModAlt, IsLetter, 0x0000 },
+ { 46, 0x0063, QALT(Qt::Key_C), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 46, 0x0063, QALT(Qt::Key_C), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 46, 0x0063, QALT(Qt::Key_C), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 46, 0x0063, QCTRL(QALT(Qt::Key_C)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 46, 0x0063, QCTRL(QALT(Qt::Key_C)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 46, 0x0063, QCTRL(QALT(Qt::Key_C)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 46, 0x0063, QCTRL(QALT(Qt::Key_C)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 47, 0x0076, Qt::Key_V, ModPlain, IsLetter, 0x0000 },
+ { 47, 0x0056, Qt::Key_V, ModShift, IsLetter, 0x0000 },
+ { 47, 0x0076, Qt::Key_V, ModAltGr, IsLetter, 0x0000 },
+ { 47, 0x0056, Qt::Key_V, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 47, 0x0076, QCTRL(Qt::Key_V), ModControl, IsLetter, 0x0000 },
+ { 47, 0x0076, QCTRL(Qt::Key_V), ModShift | ModControl, IsLetter, 0x0000 },
+ { 47, 0x0076, QCTRL(Qt::Key_V), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 47, 0x0076, QCTRL(Qt::Key_V), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 47, 0x0076, QALT(Qt::Key_V), ModAlt, IsLetter, 0x0000 },
+ { 47, 0x0076, QALT(Qt::Key_V), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 47, 0x0076, QALT(Qt::Key_V), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 47, 0x0076, QALT(Qt::Key_V), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 47, 0x0076, QCTRL(QALT(Qt::Key_V)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 47, 0x0076, QCTRL(QALT(Qt::Key_V)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 47, 0x0076, QCTRL(QALT(Qt::Key_V)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 47, 0x0076, QCTRL(QALT(Qt::Key_V)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 48, 0x0062, Qt::Key_B, ModPlain, IsLetter, 0x0000 },
+ { 48, 0x0042, Qt::Key_B, ModShift, IsLetter, 0x0000 },
+ { 48, 0x0062, Qt::Key_B, ModAltGr, IsLetter, 0x0000 },
+ { 48, 0x0042, Qt::Key_B, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 48, 0x0062, QCTRL(Qt::Key_B), ModControl, IsLetter, 0x0000 },
+ { 48, 0x0062, QCTRL(Qt::Key_B), ModShift | ModControl, IsLetter, 0x0000 },
+ { 48, 0x0062, QCTRL(Qt::Key_B), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 48, 0x0062, QCTRL(Qt::Key_B), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 48, 0x0062, QALT(Qt::Key_B), ModAlt, IsLetter, 0x0000 },
+ { 48, 0x0062, QALT(Qt::Key_B), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 48, 0x0062, QALT(Qt::Key_B), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 48, 0x0062, QALT(Qt::Key_B), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 48, 0x0062, QCTRL(QALT(Qt::Key_B)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 48, 0x0062, QCTRL(QALT(Qt::Key_B)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 48, 0x0062, QCTRL(QALT(Qt::Key_B)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 48, 0x0062, QCTRL(QALT(Qt::Key_B)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 49, 0x006e, Qt::Key_N, ModPlain, IsLetter, 0x0000 },
+ { 49, 0x004e, Qt::Key_N, ModShift, IsLetter, 0x0000 },
+ { 49, 0x006e, Qt::Key_N, ModAltGr, IsLetter, 0x0000 },
+ { 49, 0x004e, Qt::Key_N, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 49, 0x006e, QCTRL(Qt::Key_N), ModControl, IsLetter, 0x0000 },
+ { 49, 0x006e, QCTRL(Qt::Key_N), ModShift | ModControl, IsLetter, 0x0000 },
+ { 49, 0x006e, QCTRL(Qt::Key_N), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 49, 0x006e, QCTRL(Qt::Key_N), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 49, 0x006e, QALT(Qt::Key_N), ModAlt, IsLetter, 0x0000 },
+ { 49, 0x006e, QALT(Qt::Key_N), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 49, 0x006e, QALT(Qt::Key_N), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 49, 0x006e, QALT(Qt::Key_N), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 49, 0x006e, QCTRL(QALT(Qt::Key_N)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 49, 0x006e, QCTRL(QALT(Qt::Key_N)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 49, 0x006e, QCTRL(QALT(Qt::Key_N)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 49, 0x006e, QCTRL(QALT(Qt::Key_N)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 50, 0x006d, Qt::Key_M, ModPlain, IsLetter, 0x0000 },
+ { 50, 0x004d, Qt::Key_M, ModShift, IsLetter, 0x0000 },
+ { 50, 0x006d, Qt::Key_M, ModAltGr, IsLetter, 0x0000 },
+ { 50, 0x004d, Qt::Key_M, ModShift | ModAltGr, IsLetter, 0x0000 },
+ { 50, 0x006d, QCTRL(Qt::Key_M), ModControl, IsLetter, 0x0000 },
+ { 50, 0x006d, QCTRL(Qt::Key_M), ModShift | ModControl, IsLetter, 0x0000 },
+ { 50, 0x006d, QCTRL(Qt::Key_M), ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 50, 0x006d, QCTRL(Qt::Key_M), ModShift | ModAltGr | ModControl, IsLetter, 0x0000 },
+ { 50, 0x006d, QALT(Qt::Key_M), ModAlt, IsLetter, 0x0000 },
+ { 50, 0x006d, QALT(Qt::Key_M), ModShift | ModAlt, IsLetter, 0x0000 },
+ { 50, 0x006d, QALT(Qt::Key_M), ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 50, 0x006d, QALT(Qt::Key_M), ModShift | ModAltGr | ModAlt, IsLetter, 0x0000 },
+ { 50, 0x006d, QCTRL(QALT(Qt::Key_M)), ModControl | ModAlt, IsLetter, 0x0000 },
+ { 50, 0x006d, QCTRL(QALT(Qt::Key_M)), ModShift | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 50, 0x006d, QCTRL(QALT(Qt::Key_M)), ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 50, 0x006d, QCTRL(QALT(Qt::Key_M)), ModShift | ModAltGr | ModControl | ModAlt, IsLetter, 0x0000 },
+ { 51, 0x002c, Qt::Key_Comma, ModPlain, NoFlags, 0x0000 },
+ { 51, 0x003c, Qt::Key_Less, ModShift, NoFlags, 0x0000 },
+ { 52, 0x002e, Qt::Key_Period, ModPlain, NoFlags, 0x0000 },
+ { 52, 0x003e, Qt::Key_Greater, ModShift, NoFlags, 0x0000 },
+ { 52, 0xffff, Qt::Key_Multi_key, ModAltGr, NoFlags, 0x0000 },
+ { 53, 0x002f, Qt::Key_Slash, ModPlain, NoFlags, 0x0000 },
+ { 53, 0x003f, Qt::Key_Question, ModShift, NoFlags, 0x0000 },
+ { 53, 0xffff, Qt::Key_Backspace, ModControl, NoFlags, 0x0000 },
+ { 54, 0xffff, Qt::Key_Shift, ModPlain, IsModifier, ModShift },
+ { 55, 0x002a, QKEYPAD(Qt::Key_Asterisk), ModPlain, NoFlags, 0x0000 },
+ { 56, 0xffff, Qt::Key_Alt, ModPlain, IsModifier, ModAlt },
+ { 57, 0x0020, Qt::Key_Space, ModPlain, NoFlags, 0x0000 },
+ { 58, 0xffff, Qt::Key_CapsLock, ModPlain, NoFlags, 0x0000 },
+ { 59, 0xffff, Qt::Key_F1, ModPlain, NoFlags, 0x0000 },
+ { 59, 0xffff, Qt::Key_F13, ModShift, NoFlags, 0x0000 },
+ { 59, 0xffff, Qt::Key_F25, ModControl, NoFlags, 0x0000 },
+ { 60, 0xffff, Qt::Key_F2, ModPlain, NoFlags, 0x0000 },
+ { 60, 0xffff, Qt::Key_F14, ModShift, NoFlags, 0x0000 },
+ { 60, 0xffff, Qt::Key_F26, ModControl, NoFlags, 0x0000 },
+ { 61, 0xffff, Qt::Key_F3, ModPlain, NoFlags, 0x0000 },
+ { 61, 0xffff, Qt::Key_F15, ModShift, NoFlags, 0x0000 },
+ { 61, 0xffff, Qt::Key_F27, ModControl, NoFlags, 0x0000 },
+ { 62, 0xffff, Qt::Key_F4, ModPlain, NoFlags, 0x0000 },
+ { 62, 0xffff, Qt::Key_F16, ModShift, NoFlags, 0x0000 },
+ { 62, 0xffff, Qt::Key_F28, ModControl, NoFlags, 0x0000 },
+ { 63, 0xffff, Qt::Key_F5, ModPlain, NoFlags, 0x0000 },
+ { 63, 0xffff, Qt::Key_F17, ModShift, NoFlags, 0x0000 },
+ { 63, 0xffff, Qt::Key_F29, ModControl, NoFlags, 0x0000 },
+ { 64, 0xffff, Qt::Key_F6, ModPlain, NoFlags, 0x0000 },
+ { 64, 0xffff, Qt::Key_F18, ModShift, NoFlags, 0x0000 },
+ { 64, 0xffff, Qt::Key_F30, ModControl, NoFlags, 0x0000 },
+ { 65, 0xffff, Qt::Key_F7, ModPlain, NoFlags, 0x0000 },
+ { 65, 0xffff, Qt::Key_F19, ModShift, NoFlags, 0x0000 },
+ { 65, 0xffff, Qt::Key_F31, ModControl, NoFlags, 0x0000 },
+ { 66, 0xffff, Qt::Key_F8, ModPlain, NoFlags, 0x0000 },
+ { 66, 0xffff, Qt::Key_F20, ModShift, NoFlags, 0x0000 },
+ { 66, 0xffff, Qt::Key_F32, ModControl, NoFlags, 0x0000 },
+ { 67, 0xffff, Qt::Key_F9, ModPlain, NoFlags, 0x0000 },
+ { 67, 0xffff, Qt::Key_F21, ModShift, NoFlags, 0x0000 },
+ { 67, 0xffff, Qt::Key_F33, ModControl, NoFlags, 0x0000 },
+ { 68, 0xffff, Qt::Key_F10, ModPlain, NoFlags, 0x0000 },
+ { 68, 0xffff, Qt::Key_F22, ModShift, NoFlags, 0x0000 },
+ { 68, 0xffff, Qt::Key_F34, ModControl, NoFlags, 0x0000 },
+ { 69, 0xffff, Qt::Key_NumLock, ModPlain, NoFlags, 0x0000 },
+ { 70, 0xffff, Qt::Key_ScrollLock, ModPlain, NoFlags, 0x0000 },
+ { 70, 0xffff, Qt::Key_ScrollLock, ModAlt, NoFlags, 0x0000 },
+ { 71, 0x0037, QKEYPAD(Qt::Key_7), ModPlain, NoFlags, 0x0000 },
+ { 72, 0x0038, QKEYPAD(Qt::Key_8), ModPlain, NoFlags, 0x0000 },
+ { 73, 0x0039, QKEYPAD(Qt::Key_9), ModPlain, NoFlags, 0x0000 },
+ { 74, 0x002d, QKEYPAD(Qt::Key_Minus), ModPlain, NoFlags, 0x0000 },
+ { 75, 0x0034, QKEYPAD(Qt::Key_4), ModPlain, NoFlags, 0x0000 },
+ { 76, 0x0035, QKEYPAD(Qt::Key_5), ModPlain, NoFlags, 0x0000 },
+ { 77, 0x0036, QKEYPAD(Qt::Key_6), ModPlain, NoFlags, 0x0000 },
+ { 78, 0x002b, QKEYPAD(Qt::Key_Plus), ModPlain, NoFlags, 0x0000 },
+ { 79, 0x0031, QKEYPAD(Qt::Key_1), ModPlain, NoFlags, 0x0000 },
+ { 80, 0x0032, QKEYPAD(Qt::Key_2), ModPlain, NoFlags, 0x0000 },
+ { 81, 0x0033, QKEYPAD(Qt::Key_3), ModPlain, NoFlags, 0x0000 },
+ { 82, 0x0030, QKEYPAD(Qt::Key_0), ModPlain, NoFlags, 0x0000 },
+ { 83, 0x002e, QKEYPAD(Qt::Key_Period), ModPlain, NoFlags, 0x0000 },
+ { 86, 0x003c, Qt::Key_Less, ModPlain, NoFlags, 0x0000 },
+ { 86, 0x003e, Qt::Key_Greater, ModShift, NoFlags, 0x0000 },
+ { 86, 0x007c, Qt::Key_Bar, ModAltGr, NoFlags, 0x0000 },
+ { 87, 0xffff, Qt::Key_F11, ModPlain, NoFlags, 0x0000 },
+ { 87, 0xffff, Qt::Key_F23, ModShift, NoFlags, 0x0000 },
+ { 87, 0xffff, Qt::Key_F35, ModControl, NoFlags, 0x0000 },
+ { 88, 0xffff, Qt::Key_F12, ModPlain, NoFlags, 0x0000 },
+ { 88, 0xffff, Qt::Key_F24, ModShift, NoFlags, 0x0000 },
+ { 89, 0xffff, QKEYPAD(Qt::Key_Enter), ModPlain, NoFlags, 0x0000 },
+ { 90, 0xffff, Qt::Key_Control, ModPlain, IsModifier, ModControl },
+ { 91, 0x002f, QKEYPAD(Qt::Key_Slash), ModPlain, NoFlags, 0x0000 },
+ { 92, 0x005c, QCTRL(Qt::Key_Backslash), ModPlain, NoFlags, 0x0000 },
+ { 93, 0xffff, Qt::Key_AltGr, ModPlain, IsModifier, ModAltGr },
+ { 94, 0xffff, Qt::Key_Home, ModPlain, NoFlags, 0x0000 },
+ { 95, 0xffff, Qt::Key_Up, ModPlain, NoFlags, 0x0000 },
+ { 96, 0xffff, Qt::Key_PageUp, ModPlain, NoFlags, 0x0000 },
+ { 97, 0xffff, Qt::Key_Left, ModPlain, NoFlags, 0x0000 },
+ { 98, 0xffff, Qt::Key_Right, ModPlain, NoFlags, 0x0000 },
+ { 99, 0xffff, Qt::Key_End, ModPlain, NoFlags, 0x0000 },
+ { 100, 0xffff, Qt::Key_Down, ModPlain, NoFlags, 0x0000 },
+ { 101, 0xffff, Qt::Key_PageDown, ModPlain, NoFlags, 0x0000 },
+ { 102, 0xffff, Qt::Key_Insert, ModPlain, NoFlags, 0x0000 },
+ { 103, 0xffff, Qt::Key_Delete, ModPlain, NoFlags, 0x0000 },
+};
+
+#endif // QBSDKEYBOARD_DEFAULTMAP_P_H
diff --git a/src/plugins/generic/bsdmouse/bsdmouse.json b/src/plugins/generic/bsdmouse/bsdmouse.json
new file mode 100644
index 0000000000..33974a62f2
--- /dev/null
+++ b/src/plugins/generic/bsdmouse/bsdmouse.json
@@ -0,0 +1,3 @@
+{
+ "Keys": [ "BsdMouse" ]
+}
diff --git a/src/plugins/generic/bsdmouse/bsdmouse.pro b/src/plugins/generic/bsdmouse/bsdmouse.pro
new file mode 100644
index 0000000000..11949b95d5
--- /dev/null
+++ b/src/plugins/generic/bsdmouse/bsdmouse.pro
@@ -0,0 +1,16 @@
+TARGET = qbsdmouseplugin
+
+PLUGIN_TYPE = generic
+PLUGIN_EXTENDS = -
+PLUGIN_CLASS_NAME = QBsdMousePlugin
+load(qt_plugin)
+
+QT += core-private gui-private
+
+HEADERS = qbsdmouse.h
+SOURCES = main.cpp \
+ qbsdmouse.cpp
+
+OTHER_FILES += \
+ qbsdmouse.json
+
diff --git a/src/plugins/generic/bsdmouse/main.cpp b/src/plugins/generic/bsdmouse/main.cpp
new file mode 100644
index 0000000000..4abc7609c1
--- /dev/null
+++ b/src/plugins/generic/bsdmouse/main.cpp
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtGui/qgenericplugin.h>
+#include "qbsdmouse.h"
+
+QT_BEGIN_NAMESPACE
+
+class QBsdMousePlugin : public QGenericPlugin
+{
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QGenericPluginFactoryInterface" FILE "bsdmouse.json")
+
+public:
+ QObject *create(const QString &key, const QString &specification) override;
+};
+
+QObject *QBsdMousePlugin::create(const QString &key, const QString &specification)
+{
+ if (!key.compare(QLatin1String("BsdMouse"), Qt::CaseInsensitive))
+ return new QBsdMouseHandler(key, specification);
+
+ return nullptr;
+}
+
+QT_END_NAMESPACE
+
+#include "main.moc"
diff --git a/src/plugins/generic/bsdmouse/qbsdmouse.cpp b/src/plugins/generic/bsdmouse/qbsdmouse.cpp
new file mode 100644
index 0000000000..4875fd96bd
--- /dev/null
+++ b/src/plugins/generic/bsdmouse/qbsdmouse.cpp
@@ -0,0 +1,165 @@
+/****************************************************************************
+**
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qbsdmouse.h"
+
+#include <QSocketNotifier>
+#include <QStringList>
+#include <QPoint>
+#include <QGuiApplication>
+#include <qpa/qwindowsysteminterface.h>
+#include <private/qguiapplication_p.h>
+#include <private/qinputdevicemanager_p_p.h>
+
+#include <private/qcore_unix_p.h>
+#include <qdebug.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/mouse.h>
+#include <unistd.h>
+
+QT_BEGIN_NAMESPACE
+
+enum {
+ PsmLevelBasic = 0,
+ PsmLevelExtended = 1,
+ PsmLevelNative = 2
+};
+
+QBsdMouseHandler::QBsdMouseHandler(const QString &key, const QString &specification)
+{
+ Q_UNUSED(key);
+
+ setObjectName(QLatin1String("BSD Sysmouse Handler"));
+
+ QByteArray device;
+ if (specification.startsWith("/dev/"))
+ device = QFile::encodeName(specification);
+
+ if (device.isEmpty())
+ device = QByteArrayLiteral("/dev/sysmouse");
+
+ m_devFd = QT_OPEN(device.constData(), O_RDONLY);
+ if (m_devFd < 0) {
+ qErrnoWarning(errno, "open(%s) failed", device.constData());
+ return;
+ }
+
+ int level = 0;
+ if (ioctl(m_devFd, MOUSE_GETLEVEL, &level)) {
+ qErrnoWarning(errno, "ioctl(%s, MOUSE_GETLEVEL) failed", device.constData());
+ close(m_devFd);
+ m_devFd = -1;
+ return;
+ }
+
+ switch (level) {
+ case PsmLevelBasic:
+ m_packetSize = 5;
+ break;
+ case PsmLevelExtended:
+ m_packetSize = 8;
+ break;
+ default:
+ qWarning("Unsupported mouse device operation level: %d", level);
+ close(m_devFd);
+ m_devFd = -1;
+ return;
+ }
+
+ if (fcntl(m_devFd, F_SETFL, O_NONBLOCK)) {
+ qErrnoWarning(errno, "fcntl(%s, F_SETFL, O_NONBLOCK) failed", device.constData());
+ close(m_devFd);
+ m_devFd = -1;
+ return;
+ }
+
+ m_notifier.reset(new QSocketNotifier(m_devFd, QSocketNotifier::Read, this));
+ connect(m_notifier.data(), &QSocketNotifier::activated, this, &QBsdMouseHandler::readMouseData);
+ QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount(
+ QInputDeviceManager::DeviceTypePointer, 1);
+}
+
+QBsdMouseHandler::~QBsdMouseHandler()
+{
+ if (m_devFd != -1)
+ close(m_devFd);
+}
+
+void QBsdMouseHandler::readMouseData()
+{
+ if (m_devFd < 0)
+ return;
+
+ if (m_packetSize == 0)
+ return;
+
+ // packet format described in mouse(4)
+ qint8 packet[MOUSE_SYS_PACKETSIZE];
+ quint8 status = 0;
+ while (read(m_devFd, packet, m_packetSize) == m_packetSize) {
+ const qint16 relx = packet[1] + packet[3];
+ const qint16 rely = -(packet[2] + packet[4]);
+
+ m_x += relx;
+ m_y += rely;
+
+ status = packet[0] & MOUSE_SYS_STDBUTTONS;
+ }
+
+ // clamp to screen geometry
+ const QRect g = QGuiApplication::primaryScreen()->virtualGeometry();
+ if (m_x + m_xOffset < g.left())
+ m_x = g.left() - m_xOffset;
+ else if (m_x + m_xOffset > g.right())
+ m_x = g.right() - m_xOffset;
+
+ if (m_y + m_yOffset < g.top())
+ m_y = g.top() - m_yOffset;
+ else if (m_y + m_yOffset > g.bottom())
+ m_y = g.bottom() - m_yOffset;
+
+ const QPoint pos(m_x + m_xOffset, m_y + m_yOffset);
+ m_buttons = Qt::NoButton;
+ if (!(status & MOUSE_SYS_BUTTON1UP))
+ m_buttons |= Qt::LeftButton;
+ if (!(status & MOUSE_SYS_BUTTON2UP))
+ m_buttons |= Qt::MiddleButton;
+ if (!(status & MOUSE_SYS_BUTTON3UP))
+ m_buttons |= Qt::RightButton;
+
+ QWindowSystemInterface::handleMouseEvent(0, pos, pos, m_buttons);
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/generic/bsdmouse/qbsdmouse.h b/src/plugins/generic/bsdmouse/qbsdmouse.h
new file mode 100644
index 0000000000..9a4cb8dd82
--- /dev/null
+++ b/src/plugins/generic/bsdmouse/qbsdmouse.h
@@ -0,0 +1,70 @@
+/****************************************************************************
+**
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QBSDMOUSE_H
+#define QBSDMOUSE_H
+
+#include <QString>
+#include <QScopedPointer>
+#include <QSocketNotifier>
+
+#include <qobject.h>
+
+QT_BEGIN_NAMESPACE
+
+class QSocketNotifier;
+
+class QBsdMouseHandler : public QObject
+{
+ Q_OBJECT
+public:
+ QBsdMouseHandler(const QString &key, const QString &specification);
+ ~QBsdMouseHandler() override;
+
+private:
+ void readMouseData();
+
+private:
+ QScopedPointer<QSocketNotifier> m_notifier;
+ int m_devFd = -1;
+ int m_packetSize = 0;
+ int m_x = 0;
+ int m_y = 0;
+ int m_xOffset = 0;
+ int m_yOffset = 0;
+ Qt::MouseButtons m_buttons = Qt::NoButton;
+};
+
+QT_END_NAMESPACE
+
+#endif // QBSDMOUSE_H
diff --git a/src/plugins/generic/evdevkeyboard/evdevkeyboard.pro b/src/plugins/generic/evdevkeyboard/evdevkeyboard.pro
index d23ad3bad0..73fddf4d26 100644
--- a/src/plugins/generic/evdevkeyboard/evdevkeyboard.pro
+++ b/src/plugins/generic/evdevkeyboard/evdevkeyboard.pro
@@ -1,6 +1,6 @@
TARGET = qevdevkeyboardplugin
-QT += core-private platformsupport-private gui-private
+QT += core-private gui-private input_support-private
SOURCES = main.cpp
diff --git a/src/plugins/generic/evdevkeyboard/main.cpp b/src/plugins/generic/evdevkeyboard/main.cpp
index 7fd6feaecc..ef08cd56ab 100644
--- a/src/plugins/generic/evdevkeyboard/main.cpp
+++ b/src/plugins/generic/evdevkeyboard/main.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include <QtGui/qgenericplugin.h>
-#include <QtPlatformSupport/private/qevdevkeyboardmanager_p.h>
+#include <QtInputSupport/private/qevdevkeyboardmanager_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/generic/evdevmouse/evdevmouse.pro b/src/plugins/generic/evdevmouse/evdevmouse.pro
index 1a0bc08853..f3a8558ef2 100644
--- a/src/plugins/generic/evdevmouse/evdevmouse.pro
+++ b/src/plugins/generic/evdevmouse/evdevmouse.pro
@@ -1,6 +1,6 @@
TARGET = qevdevmouseplugin
-QT += core-private platformsupport-private gui-private
+QT += core-private gui-private input_support-private
SOURCES = main.cpp
diff --git a/src/plugins/generic/evdevmouse/main.cpp b/src/plugins/generic/evdevmouse/main.cpp
index 88c29366fa..86ec7cb575 100644
--- a/src/plugins/generic/evdevmouse/main.cpp
+++ b/src/plugins/generic/evdevmouse/main.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include <QtGui/qgenericplugin.h>
-#include <QtPlatformSupport/private/qevdevmousemanager_p.h>
+#include <QtInputSupport/private/qevdevmousemanager_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/generic/evdevtablet/evdevtablet.pro b/src/plugins/generic/evdevtablet/evdevtablet.pro
index aaf0ef4c67..1409cd83c9 100644
--- a/src/plugins/generic/evdevtablet/evdevtablet.pro
+++ b/src/plugins/generic/evdevtablet/evdevtablet.pro
@@ -2,7 +2,7 @@ TARGET = qevdevtabletplugin
SOURCES = main.cpp
-QT += core-private platformsupport-private gui-private
+QT += core-private gui-private input_support-private
OTHER_FILES += \
evdevtablet.json
diff --git a/src/plugins/generic/evdevtablet/main.cpp b/src/plugins/generic/evdevtablet/main.cpp
index cf8dc15c6e..0646d71146 100644
--- a/src/plugins/generic/evdevtablet/main.cpp
+++ b/src/plugins/generic/evdevtablet/main.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include <QtGui/qgenericplugin.h>
-#include <QtPlatformSupport/private/qevdevtabletmanager_p.h>
+#include <QtInputSupport/private/qevdevtabletmanager_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/generic/evdevtouch/evdevtouch.pro b/src/plugins/generic/evdevtouch/evdevtouch.pro
index 4d61db4eb0..3ca646aaca 100644
--- a/src/plugins/generic/evdevtouch/evdevtouch.pro
+++ b/src/plugins/generic/evdevtouch/evdevtouch.pro
@@ -2,7 +2,7 @@ TARGET = qevdevtouchplugin
SOURCES = main.cpp
-QT += core-private platformsupport-private gui-private
+QT += core-private gui-private input_support-private
OTHER_FILES += \
evdevtouch.json
diff --git a/src/plugins/generic/evdevtouch/main.cpp b/src/plugins/generic/evdevtouch/main.cpp
index 411bf3d7a0..aa60614936 100644
--- a/src/plugins/generic/evdevtouch/main.cpp
+++ b/src/plugins/generic/evdevtouch/main.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include <QtGui/qgenericplugin.h>
-#include <QtPlatformSupport/private/qevdevtouchmanager_p.h>
+#include <QtInputSupport/private/qevdevtouchmanager_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/generic/generic.pro b/src/plugins/generic/generic.pro
index 0c1943b7dd..996e57d015 100644
--- a/src/plugins/generic/generic.pro
+++ b/src/plugins/generic/generic.pro
@@ -1,19 +1,22 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += gui-private network-private
-load(qfeatures)
-
-contains(QT_CONFIG, evdev) {
+qtConfig(evdev) {
SUBDIRS += evdevmouse evdevtouch evdevkeyboard evdevtablet
}
-contains(QT_CONFIG, tslib) {
+qtConfig(tslib) {
SUBDIRS += tslib
}
-!contains(QT_DISABLED_FEATURES, udpsocket) {
+qtConfig(udpsocket) {
SUBDIRS += tuiotouch
}
-contains(QT_CONFIG, libinput) {
+qtConfig(libinput) {
SUBDIRS += libinput
}
+
+freebsd {
+ SUBDIRS += bsdkeyboard bsdmouse
+}
diff --git a/src/plugins/generic/libinput/libinput.pro b/src/plugins/generic/libinput/libinput.pro
index 335605d354..434bf7b945 100644
--- a/src/plugins/generic/libinput/libinput.pro
+++ b/src/plugins/generic/libinput/libinput.pro
@@ -1,6 +1,6 @@
TARGET = qlibinputplugin
-QT += core-private platformsupport-private gui-private
+QT += core-private gui-private input_support-private
SOURCES = main.cpp
diff --git a/src/plugins/generic/libinput/main.cpp b/src/plugins/generic/libinput/main.cpp
index e40fdd0097..6d1e76c0f0 100644
--- a/src/plugins/generic/libinput/main.cpp
+++ b/src/plugins/generic/libinput/main.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include <QtGui/qgenericplugin.h>
-#include <QtPlatformSupport/private/qlibinputhandler_p.h>
+#include <QtInputSupport/private/qlibinputhandler_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/generic/tslib/main.cpp b/src/plugins/generic/tslib/main.cpp
index c5e0c720fc..fb9e0c35f3 100644
--- a/src/plugins/generic/tslib/main.cpp
+++ b/src/plugins/generic/tslib/main.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include <QtGui/qgenericplugin.h>
-#include <QtPlatformSupport/private/qtslib_p.h>
+#include <QtInputSupport/private/qtslib_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/generic/tslib/tslib.pro b/src/plugins/generic/tslib/tslib.pro
index 200d231cc8..7c3a0bf607 100644
--- a/src/plugins/generic/tslib/tslib.pro
+++ b/src/plugins/generic/tslib/tslib.pro
@@ -2,9 +2,9 @@ TARGET = qtslibplugin
SOURCES = main.cpp
-QT += gui-private platformsupport-private
+QT += core-private gui-private input_support-private
-LIBS += -lts
+QMAKE_USE += tslib
OTHER_FILES += tslib.json
diff --git a/src/plugins/generic/tuiotouch/qoscbundle.cpp b/src/plugins/generic/tuiotouch/qoscbundle.cpp
index 6ddca9b09d..b84ae39aca 100644
--- a/src/plugins/generic/tuiotouch/qoscbundle.cpp
+++ b/src/plugins/generic/tuiotouch/qoscbundle.cpp
@@ -38,17 +38,20 @@
**
****************************************************************************/
+#include "qoscbundle_p.h"
+#include "qtuio_p.h"
+
#include <QtEndian>
#include <QDebug>
#include <QLoggingCategory>
-#include "qoscbundle_p.h"
-#include "qtuio_p.h"
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcTuioBundle, "qt.qpa.tuio.bundle")
+QOscBundle::QOscBundle() {}
+
// TUIO packets are transmitted using the OSC protocol, located at:
// http://opensoundcontrol.org/specification
// Snippets of this specification have been pasted into the source as a means of
@@ -172,21 +175,5 @@ QOscBundle::QOscBundle(const QByteArray &data)
}
}
-
-bool QOscBundle::isValid() const
-{
- return m_isValid;
-}
-
-QList<QOscBundle> QOscBundle::bundles() const
-{
- return m_bundles;
-}
-
-QList<QOscMessage> QOscBundle::messages() const
-{
- return m_messages;
-}
-
QT_END_NAMESPACE
diff --git a/src/plugins/generic/tuiotouch/qoscbundle_p.h b/src/plugins/generic/tuiotouch/qoscbundle_p.h
index e95a202ae7..cb3ec4d251 100644
--- a/src/plugins/generic/tuiotouch/qoscbundle_p.h
+++ b/src/plugins/generic/tuiotouch/qoscbundle_p.h
@@ -43,25 +43,32 @@
#include "qoscmessage_p.h"
+#include <QtCore/QVector>
+
QT_BEGIN_NAMESPACE
+class QByteArray;
+
class QOscBundle
{
+ QOscBundle(); // for QVector, don't use
+ friend class QVector<QOscBundle>;
public:
- QOscBundle(const QByteArray &data);
+ explicit QOscBundle(const QByteArray &data);
- bool isValid() const;
- QList<QOscBundle> bundles() const;
- QList<QOscMessage> messages() const;
+ bool isValid() const { return m_isValid; }
+ QVector<QOscBundle> bundles() const { return m_bundles; }
+ QVector<QOscMessage> messages() const { return m_messages; }
private:
bool m_isValid;
bool m_immediate;
quint32 m_timeEpoch;
quint32 m_timePico;
- QList<QOscBundle> m_bundles;
- QList<QOscMessage> m_messages;
+ QVector<QOscBundle> m_bundles;
+ QVector<QOscMessage> m_messages;
};
+Q_DECLARE_TYPEINFO(QOscBundle, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
diff --git a/src/plugins/generic/tuiotouch/qoscmessage.cpp b/src/plugins/generic/tuiotouch/qoscmessage.cpp
index 6f82cd784b..b2004903bd 100644
--- a/src/plugins/generic/tuiotouch/qoscmessage.cpp
+++ b/src/plugins/generic/tuiotouch/qoscmessage.cpp
@@ -38,19 +38,19 @@
**
****************************************************************************/
-#include <QByteArray>
+#include "qoscmessage_p.h"
+#include "qtuio_p.h"
+
#include <QDebug>
#include <QtEndian>
-#include <QVariant>
#include <QLoggingCategory>
-#include "qoscmessage_p.h"
-#include "qtuio_p.h"
-
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcTuioMessage, "qt.qpa.tuio.message")
+QOscMessage::QOscMessage() {}
+
// TUIO packets are transmitted using the OSC protocol, located at:
// http://opensoundcontrol.org/specification
// Snippets of this specification have been pasted into the source as a means of
@@ -125,20 +125,5 @@ QOscMessage::QOscMessage(const QByteArray &data)
qCDebug(lcTuioMessage) << "Message with address pattern: " << addressPattern << " arguments: " << arguments;
}
-bool QOscMessage::isValid() const
-{
- return m_isValid;
-}
-
-QByteArray QOscMessage::addressPattern() const
-{
- return m_addressPattern;
-}
-
-QList<QVariant> QOscMessage::arguments() const
-{
- return m_arguments;
-}
-
QT_END_NAMESPACE
diff --git a/src/plugins/generic/tuiotouch/qoscmessage_p.h b/src/plugins/generic/tuiotouch/qoscmessage_p.h
index 788a03e504..76d40ceb18 100644
--- a/src/plugins/generic/tuiotouch/qoscmessage_p.h
+++ b/src/plugins/generic/tuiotouch/qoscmessage_p.h
@@ -41,22 +41,32 @@
#ifndef QOSCMESSAGE_P_H
#define QOSCMESSAGE_P_H
+#include <QtCore/QByteArray>
+#include <QtCore/QVariant>
+#include <QtCore/QVector>
+#include <QtCore/QList>
+
+
QT_BEGIN_NAMESPACE
class QOscMessage
{
+ QOscMessage(); // for QVector, don't use
+ friend class QVector<QOscMessage>;
public:
- QOscMessage(const QByteArray &data);
- bool isValid() const;
+ explicit QOscMessage(const QByteArray &data);
+
+ bool isValid() const { return m_isValid; }
- QByteArray addressPattern() const;
- QList<QVariant> arguments() const;
+ QByteArray addressPattern() const { return m_addressPattern; }
+ QList<QVariant> arguments() const { return m_arguments; }
private:
bool m_isValid;
QByteArray m_addressPattern;
QList<QVariant> m_arguments;
};
+Q_DECLARE_TYPEINFO(QOscMessage, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
diff --git a/src/plugins/generic/tuiotouch/qtuiocursor_p.h b/src/plugins/generic/tuiotouch/qtuiocursor_p.h
index 2ff762b836..46134e6f3f 100644
--- a/src/plugins/generic/tuiotouch/qtuiocursor_p.h
+++ b/src/plugins/generic/tuiotouch/qtuiocursor_p.h
@@ -102,6 +102,7 @@ private:
float m_acceleration;
Qt::TouchPointState m_state;
};
+Q_DECLARE_TYPEINFO(QTuioCursor, Q_MOVABLE_TYPE); // Q_PRIMITIVE_TYPE: not possible, m_state is = 1, not 0.
QT_END_NAMESPACE
diff --git a/src/plugins/generic/tuiotouch/qtuiohandler.cpp b/src/plugins/generic/tuiotouch/qtuiohandler.cpp
index 5d34e0ea38..26b88d6d78 100644
--- a/src/plugins/generic/tuiotouch/qtuiohandler.cpp
+++ b/src/plugins/generic/tuiotouch/qtuiohandler.cpp
@@ -38,23 +38,34 @@
**
****************************************************************************/
-#include <QLoggingCategory>
-#include <QRect>
-#include <QWindow>
-#include <QGuiApplication>
-#include <QTouchDevice>
-
-#include <qpa/qwindowsysteminterface.h>
+#include "qtuiohandler_p.h"
#include "qtuiocursor_p.h"
-#include "qtuiohandler_p.h"
+#include "qtuiotoken_p.h"
#include "qoscbundle_p.h"
+#include "qoscmessage_p.h"
+
+#include <qpa/qwindowsysteminterface.h>
+
+#include <QTouchDevice>
+#include <QWindow>
+#include <QGuiApplication>
+
+#include <QLoggingCategory>
+#include <QRect>
+#include <qmath.h>
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcTuioSource, "qt.qpa.tuio.source")
Q_LOGGING_CATEGORY(lcTuioSet, "qt.qpa.tuio.set")
+// With TUIO the first application takes exclusive ownership of the "device"
+// we cannot attach more than one application to the same port anyway.
+// Forcing delivery makes it easy to use simulators in the same machine
+// and forget about headaches about unfocused TUIO windows.
+static bool forceDelivery = qEnvironmentVariableIsSet("QT_TUIOTOUCH_DELIVER_WITHOUT_FOCUS");
+
QTuioHandler::QTuioHandler(const QString &specification)
: m_device(new QTouchDevice) // not leaked, QTouchDevice cleans up registered devices itself
{
@@ -143,7 +154,7 @@ void QTuioHandler::processPackets()
// messages. The FSEQ frame ID is incremented for each delivered bundle,
// while redundant bundles can be marked using the frame sequence ID
// -1."
- QList<QOscMessage> messages;
+ QVector<QOscMessage> messages;
QOscBundle bundle(datagram);
if (bundle.isValid()) {
@@ -157,29 +168,49 @@ void QTuioHandler::processPackets()
messages.push_back(msg);
}
- foreach (const QOscMessage &message, messages) {
- if (message.addressPattern() != "/tuio/2Dcur") {
- qWarning() << "Ignoring unknown address pattern " << message.addressPattern();
- continue;
- }
-
- QList<QVariant> arguments = message.arguments();
- if (arguments.count() == 0) {
- qWarning("Ignoring TUIO message with no arguments");
- continue;
- }
-
- QByteArray messageType = arguments.at(0).toByteArray();
- if (messageType == "source") {
- process2DCurSource(message);
- } else if (messageType == "alive") {
- process2DCurAlive(message);
- } else if (messageType == "set") {
- process2DCurSet(message);
- } else if (messageType == "fseq") {
- process2DCurFseq(message);
+ for (const QOscMessage &message : messages) {
+ if (message.addressPattern() == "/tuio/2Dcur") {
+ QList<QVariant> arguments = message.arguments();
+ if (arguments.count() == 0) {
+ qWarning("Ignoring TUIO message with no arguments");
+ continue;
+ }
+
+ QByteArray messageType = arguments.at(0).toByteArray();
+ if (messageType == "source") {
+ process2DCurSource(message);
+ } else if (messageType == "alive") {
+ process2DCurAlive(message);
+ } else if (messageType == "set") {
+ process2DCurSet(message);
+ } else if (messageType == "fseq") {
+ process2DCurFseq(message);
+ } else {
+ qWarning() << "Ignoring unknown TUIO message type: " << messageType;
+ continue;
+ }
+ } else if (message.addressPattern() == "/tuio/2Dobj") {
+ QList<QVariant> arguments = message.arguments();
+ if (arguments.count() == 0) {
+ qWarning("Ignoring TUIO message with no arguments");
+ continue;
+ }
+
+ QByteArray messageType = arguments.at(0).toByteArray();
+ if (messageType == "source") {
+ process2DObjSource(message);
+ } else if (messageType == "alive") {
+ process2DObjAlive(message);
+ } else if (messageType == "set") {
+ process2DObjSet(message);
+ } else if (messageType == "fseq") {
+ process2DObjFseq(message);
+ } else {
+ qWarning() << "Ignoring unknown TUIO message type: " << messageType;
+ continue;
+ }
} else {
- qWarning() << "Ignoring unknown TUIO message type: " << messageType;
+ qWarning() << "Ignoring unknown address pattern " << message.addressPattern();
continue;
}
}
@@ -327,11 +358,6 @@ void QTuioHandler::process2DCurFseq(const QOscMessage &message)
Q_UNUSED(message); // TODO: do we need to do anything with the frame id?
QWindow *win = QGuiApplication::focusWindow();
- // With TUIO the first application takes exclusive ownership of the "device"
- // we cannot attach more than one application to the same port anyway.
- // Forcing delivery makes it easy to use simulators in the same machine
- // and forget about headaches about unfocused TUIO windows.
- static bool forceDelivery = qEnvironmentVariableIsSet("QT_TUIOTOUCH_DELIVER_WITHOUT_FOCUS");
if (!win && QGuiApplication::topLevelWindows().length() > 0 && forceDelivery)
win = QGuiApplication::topLevelWindows().at(0);
@@ -341,12 +367,12 @@ void QTuioHandler::process2DCurFseq(const QOscMessage &message)
QList<QWindowSystemInterface::TouchPoint> tpl;
tpl.reserve(m_activeCursors.size() + m_deadCursors.size());
- foreach (const QTuioCursor &tc, m_activeCursors) {
+ for (const QTuioCursor &tc : m_activeCursors) {
QWindowSystemInterface::TouchPoint tp = cursorToTouchPoint(tc, win);
tpl.append(tp);
}
- foreach (const QTuioCursor &tc, m_deadCursors) {
+ for (const QTuioCursor &tc : m_deadCursors) {
QWindowSystemInterface::TouchPoint tp = cursorToTouchPoint(tc, win);
tp.state = Qt::TouchPointReleased;
tpl.append(tp);
@@ -356,5 +382,180 @@ void QTuioHandler::process2DCurFseq(const QOscMessage &message)
m_deadCursors.clear();
}
+void QTuioHandler::process2DObjSource(const QOscMessage &message)
+{
+ QList<QVariant> arguments = message.arguments();
+ if (arguments.count() != 2) {
+ qWarning() << "Ignoring malformed TUIO source message: " << arguments.count();
+ return;
+ }
+
+ if (QMetaType::Type(arguments.at(1).type()) != QMetaType::QByteArray) {
+ qWarning("Ignoring malformed TUIO source message (bad argument type)");
+ return;
+ }
+
+ qCDebug(lcTuioSource) << "Got TUIO source message from: " << arguments.at(1).toByteArray();
+}
+
+void QTuioHandler::process2DObjAlive(const QOscMessage &message)
+{
+ QList<QVariant> arguments = message.arguments();
+
+ // delta the notified tokens that are active, against the ones we already
+ // know of.
+ //
+ // TBD: right now we're assuming one 2DObj alive message corresponds to a
+ // new data source from the input. is this correct, or do we need to store
+ // changes and only process the deltas on fseq?
+ QMap<int, QTuioToken> oldActiveTokens = m_activeTokens;
+ QMap<int, QTuioToken> newActiveTokens;
+
+ for (int i = 1; i < arguments.count(); ++i) {
+ if (QMetaType::Type(arguments.at(i).type()) != QMetaType::Int) {
+ qWarning() << "Ignoring malformed TUIO alive message (bad argument on position" << i << arguments << ')';
+ return;
+ }
+
+ int sessionId = arguments.at(i).toInt();
+ if (!oldActiveTokens.contains(sessionId)) {
+ // newly active
+ QTuioToken token(sessionId);
+ token.setState(Qt::TouchPointPressed);
+ newActiveTokens.insert(sessionId, token);
+ } else {
+ // we already know about it, remove it so it isn't marked as released
+ QTuioToken token = oldActiveTokens.value(sessionId);
+ token.setState(Qt::TouchPointStationary); // position change in SET will update if needed
+ newActiveTokens.insert(sessionId, token);
+ oldActiveTokens.remove(sessionId);
+ }
+ }
+
+ // anything left is dead now
+ QMap<int, QTuioToken>::ConstIterator it = oldActiveTokens.constBegin();
+
+ // deadTokens should be cleared from the last FSEQ now
+ m_deadTokens.reserve(oldActiveTokens.size());
+
+ // TODO: there could be an issue of resource exhaustion here if FSEQ isn't
+ // sent in a timely fashion. we should probably track message counts and
+ // force-flush if we get too many built up.
+ while (it != oldActiveTokens.constEnd()) {
+ m_deadTokens.append(it.value());
+ ++it;
+ }
+
+ m_activeTokens = newActiveTokens;
+}
+
+void QTuioHandler::process2DObjSet(const QOscMessage &message)
+{
+ QList<QVariant> arguments = message.arguments();
+ if (arguments.count() < 7) {
+ qWarning() << "Ignoring malformed TUIO set message with too few arguments: " << arguments.count();
+ return;
+ }
+
+ if (QMetaType::Type(arguments.at(1).type()) != QMetaType::Int ||
+ QMetaType::Type(arguments.at(2).type()) != QMetaType::Int ||
+ QMetaType::Type(arguments.at(3).type()) != QMetaType::Float ||
+ QMetaType::Type(arguments.at(4).type()) != QMetaType::Float ||
+ QMetaType::Type(arguments.at(5).type()) != QMetaType::Float ||
+ QMetaType::Type(arguments.at(6).type()) != QMetaType::Float ||
+ QMetaType::Type(arguments.at(7).type()) != QMetaType::Float ||
+ QMetaType::Type(arguments.at(8).type()) != QMetaType::Float ||
+ QMetaType::Type(arguments.at(9).type()) != QMetaType::Float ||
+ QMetaType::Type(arguments.at(10).type()) != QMetaType::Float) {
+ qWarning() << "Ignoring malformed TUIO set message with bad types: " << arguments;
+ return;
+ }
+
+ int id = arguments.at(1).toInt();
+ int classId = arguments.at(2).toInt();
+ float x = arguments.at(3).toFloat();
+ float y = arguments.at(4).toFloat();
+ float angle = arguments.at(5).toFloat();
+ float vx = arguments.at(6).toFloat();
+ float vy = arguments.at(7).toFloat();
+ float angularVelocity = arguments.at(8).toFloat();
+ float acceleration = arguments.at(9).toFloat();
+ float angularAcceleration = arguments.at(10).toFloat();
+
+ QMap<int, QTuioToken>::Iterator it = m_activeTokens.find(id);
+ if (it == m_activeTokens.end()) {
+ qWarning() << "Ignoring malformed TUIO set for nonexistent token " << classId;
+ return;
+ }
+
+ qCDebug(lcTuioSet) << "Processing SET for token " << classId << id << " @ " << x << y << "∡" << angle <<
+ "vel" << vx << vy << angularVelocity << "acc" << acceleration << angularAcceleration;
+ QTuioToken &tok = *it;
+ tok.setClassId(classId);
+ tok.setX(x);
+ tok.setY(y);
+ tok.setVX(vx);
+ tok.setVY(vy);
+ tok.setAcceleration(acceleration);
+ tok.setAngle(angle);
+ tok.setAngularVelocity(angularAcceleration);
+ tok.setAngularAcceleration(angularAcceleration);
+}
+
+QWindowSystemInterface::TouchPoint QTuioHandler::tokenToTouchPoint(const QTuioToken &tc, QWindow *win)
+{
+ QWindowSystemInterface::TouchPoint tp;
+ tp.id = tc.id();
+ tp.uniqueId = tc.classId(); // TODO TUIO 2.0: populate a QVariant, and register the mapping from int to arbitrary UID data
+ tp.flags = QTouchEvent::TouchPoint::Token;
+ tp.pressure = 1.0f;
+
+ tp.normalPosition = QPointF(tc.x(), tc.y());
+
+ if (!m_transform.isIdentity())
+ tp.normalPosition = m_transform.map(tp.normalPosition);
+
+ tp.state = tc.state();
+
+ // We map the token position to the size of the window.
+ QPointF relPos = QPointF(win->size().width() * tp.normalPosition.x(), win->size().height() * tp.normalPosition.y());
+ QPointF delta = relPos - relPos.toPoint();
+ tp.area.moveCenter(win->mapToGlobal(relPos.toPoint()) + delta);
+ tp.velocity = QVector2D(win->size().width() * tc.vx(), win->size().height() * tc.vy());
+ tp.rotation = tc.angle() * 180.0 / M_PI; // convert radians to degrees
+ return tp;
+}
+
+
+void QTuioHandler::process2DObjFseq(const QOscMessage &message)
+{
+ Q_UNUSED(message); // TODO: do we need to do anything with the frame id?
+
+ QWindow *win = QGuiApplication::focusWindow();
+ if (!win && QGuiApplication::topLevelWindows().length() > 0 && forceDelivery)
+ win = QGuiApplication::topLevelWindows().at(0);
+
+ if (!win)
+ return;
+
+ QList<QWindowSystemInterface::TouchPoint> tpl;
+ tpl.reserve(m_activeTokens.size() + m_deadTokens.size());
+
+ for (const QTuioToken & t : m_activeTokens) {
+ QWindowSystemInterface::TouchPoint tp = tokenToTouchPoint(t, win);
+ tpl.append(tp);
+ }
+
+ for (const QTuioToken & t : m_deadTokens) {
+ QWindowSystemInterface::TouchPoint tp = tokenToTouchPoint(t, win);
+ tp.state = Qt::TouchPointReleased;
+ tp.velocity = QVector2D();
+ tpl.append(tp);
+ }
+ QWindowSystemInterface::handleTouchEvent(win, m_device, tpl);
+
+ m_deadTokens.clear();
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/generic/tuiotouch/qtuiohandler_p.h b/src/plugins/generic/tuiotouch/qtuiohandler_p.h
index 3034872aae..2e444f2a0d 100644
--- a/src/plugins/generic/tuiotouch/qtuiohandler_p.h
+++ b/src/plugins/generic/tuiotouch/qtuiohandler_p.h
@@ -54,6 +54,7 @@ QT_BEGIN_NAMESPACE
class QTouchDevice;
class QOscMessage;
class QTuioCursor;
+class QTuioToken;
class QTuioHandler : public QObject
{
@@ -69,14 +70,21 @@ private slots:
void process2DCurAlive(const QOscMessage &message);
void process2DCurSet(const QOscMessage &message);
void process2DCurFseq(const QOscMessage &message);
+ void process2DObjSource(const QOscMessage &message);
+ void process2DObjAlive(const QOscMessage &message);
+ void process2DObjSet(const QOscMessage &message);
+ void process2DObjFseq(const QOscMessage &message);
private:
QWindowSystemInterface::TouchPoint cursorToTouchPoint(const QTuioCursor &tc, QWindow *win);
+ QWindowSystemInterface::TouchPoint tokenToTouchPoint(const QTuioToken &tc, QWindow *win);
QTouchDevice *m_device;
QUdpSocket m_socket;
QMap<int, QTuioCursor> m_activeCursors;
QVector<QTuioCursor> m_deadCursors;
+ QMap<int, QTuioToken> m_activeTokens;
+ QVector<QTuioToken> m_deadTokens;
QTransform m_transform;
};
diff --git a/src/plugins/generic/tuiotouch/qtuiotoken_p.h b/src/plugins/generic/tuiotouch/qtuiotoken_p.h
new file mode 100644
index 0000000000..b784190d53
--- /dev/null
+++ b/src/plugins/generic/tuiotouch/qtuiotoken_p.h
@@ -0,0 +1,145 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtCore module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTUIOOBJECT_P_H
+#define QTUIOOBJECT_P_H
+
+#include <Qt>
+#include <qmath.h>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \internal
+
+ A fiducial object, or token, represented by 2Dobj in TUIO 1.x and tok in TUIO 2:
+ a physical object whose position and rotation can be uniquely tracked
+ on the touchscreen surface.
+*/
+class QTuioToken
+{
+public:
+ QTuioToken(int id = -1)
+ : m_id(id)
+ , m_classId(-1)
+ , m_x(0)
+ , m_y(0)
+ , m_vx(0)
+ , m_vy(0)
+ , m_acceleration(0)
+ , m_angle(0)
+ , m_angularVelocity(0)
+ , m_angularAcceleration(0)
+ , m_state(Qt::TouchPointPressed)
+ {
+ }
+
+ int id() const { return m_id; }
+
+ int classId() const { return m_classId; }
+ void setClassId(int classId) { m_classId = classId; }
+
+ void setX(float x)
+ {
+ if (state() == Qt::TouchPointStationary &&
+ !qFuzzyCompare(m_x + 2.0, x + 2.0)) { // +2 because 1 is a valid value, and qFuzzyCompare can't cope with 0.0
+ setState(Qt::TouchPointMoved);
+ }
+ m_x = x;
+ }
+ float x() const { return m_x; }
+
+ void setY(float y)
+ {
+ if (state() == Qt::TouchPointStationary &&
+ !qFuzzyCompare(m_y + 2.0, y + 2.0)) { // +2 because 1 is a valid value, and qFuzzyCompare can't cope with 0.0
+ setState(Qt::TouchPointMoved);
+ }
+ m_y = y;
+ }
+ float y() const { return m_y; }
+
+ void setVX(float vx) { m_vx = vx; }
+ float vx() const { return m_vx; }
+
+ void setVY(float vy) { m_vy = vy; }
+ float vy() const { return m_vy; }
+
+ void setAcceleration(float acceleration) { m_acceleration = acceleration; }
+ float acceleration() const { return m_acceleration; }
+
+ float angle() const { return m_angle; }
+ void setAngle(float angle)
+ {
+ if (angle > M_PI)
+ angle = angle - M_PI * 2.0; // zero is pointing upwards, and is the default; but we want to have negative angles when rotating left
+ if (state() == Qt::TouchPointStationary &&
+ !qFuzzyCompare(m_angle + 2.0, angle + 2.0)) { // +2 because 1 is a valid value, and qFuzzyCompare can't cope with 0.0
+ setState(Qt::TouchPointMoved);
+ }
+ m_angle = angle;
+ }
+
+ float angularVelocity() const { return m_angularVelocity; }
+ void setAngularVelocity(float angularVelocity) { m_angularVelocity = angularVelocity; }
+
+ float angularAcceleration() const { return m_angularAcceleration; }
+ void setAngularAcceleration(float angularAcceleration) { m_angularAcceleration = angularAcceleration; }
+
+ void setState(const Qt::TouchPointState &state) { m_state = state; }
+ Qt::TouchPointState state() const { return m_state; }
+
+private:
+ int m_id; // sessionID, temporary object ID
+ int m_classId; // classID (e.g. marker ID)
+ float m_x;
+ float m_y;
+ float m_vx;
+ float m_vy;
+ float m_acceleration;
+ float m_angle;
+ float m_angularVelocity;
+ float m_angularAcceleration;
+ Qt::TouchPointState m_state;
+};
+Q_DECLARE_TYPEINFO(QTuioToken, Q_MOVABLE_TYPE); // Q_PRIMITIVE_TYPE: not possible: m_id, m_classId == -1
+
+QT_END_NAMESPACE
+
+#endif // QTUIOOBJECT_P_H
diff --git a/src/plugins/generic/tuiotouch/tuiotouch.pro b/src/plugins/generic/tuiotouch/tuiotouch.pro
index ae2ccde058..08f7036c92 100644
--- a/src/plugins/generic/tuiotouch/tuiotouch.pro
+++ b/src/plugins/generic/tuiotouch/tuiotouch.pro
@@ -15,11 +15,13 @@ HEADERS += \
qoscbundle_p.h \
qoscmessage_p.h \
qtuiohandler_p.h \
- qtuiocursor_p.h
+ qtuiocursor_p.h \
+ qtuiotoken_p.h
OTHER_FILES += \
tuiotouch.json
+DEFINES += QT_NO_FOREACH
PLUGIN_TYPE = generic
PLUGIN_EXTENDS = -
PLUGIN_CLASS_NAME = QTuioTouchPlugin
diff --git a/src/plugins/imageformats/gif/gif.pro b/src/plugins/imageformats/gif/gif.pro
index a361bc2532..c2625be85a 100644
--- a/src/plugins/imageformats/gif/gif.pro
+++ b/src/plugins/imageformats/gif/gif.pro
@@ -1,9 +1,8 @@
TARGET = qgif
-include(../../../gui/image/qgifhandler.pri)
-INCLUDEPATH += ../../../gui/image
-SOURCES += $$PWD/main.cpp
-HEADERS += $$PWD/main.h
+SOURCES += main.cpp qgifhandler.cpp
+HEADERS += main.h qgifhandler_p.h
+
OTHER_FILES += gif.json
PLUGIN_TYPE = imageformats
diff --git a/src/plugins/imageformats/gif/qgifhandler.cpp b/src/plugins/imageformats/gif/qgifhandler.cpp
new file mode 100644
index 0000000000..bae74bf9a1
--- /dev/null
+++ b/src/plugins/imageformats/gif/qgifhandler.cpp
@@ -0,0 +1,1218 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+** WARNING:
+** A separate license from Unisys may be required to use the gif
+** reader. See http://www.unisys.com/about__unisys/lzw/
+** for information from Unisys
+**
+****************************************************************************/
+
+#include "qgifhandler_p.h"
+
+#include <qimage.h>
+#include <qiodevice.h>
+#include <qvariant.h>
+
+QT_BEGIN_NAMESPACE
+
+#define Q_TRANSPARENT 0x00ffffff
+
+// avoid going through QImage::scanLine() which calls detach
+#define FAST_SCAN_LINE(bits, bpl, y) (bits + (y) * bpl)
+
+
+/*
+ Incremental image decoder for GIF image format.
+
+ This subclass of QImageFormat decodes GIF format images,
+ including animated GIFs. Internally in
+*/
+
+class QGIFFormat {
+public:
+ QGIFFormat();
+ ~QGIFFormat();
+
+ int decode(QImage *image, const uchar* buffer, int length,
+ int *nextFrameDelay, int *loopCount);
+ static void scan(QIODevice *device, QVector<QSize> *imageSizes, int *loopCount);
+
+ bool newFrame;
+ bool partialNewFrame;
+
+private:
+ void fillRect(QImage *image, int x, int y, int w, int h, QRgb col);
+ inline QRgb color(uchar index) const;
+
+ // GIF specific stuff
+ QRgb* globalcmap;
+ QRgb* localcmap;
+ QImage backingstore;
+ unsigned char hold[16];
+ bool gif89;
+ int count;
+ int ccount;
+ int expectcount;
+ enum State {
+ Header,
+ LogicalScreenDescriptor,
+ GlobalColorMap,
+ LocalColorMap,
+ Introducer,
+ ImageDescriptor,
+ TableImageLZWSize,
+ ImageDataBlockSize,
+ ImageDataBlock,
+ ExtensionLabel,
+ GraphicControlExtension,
+ ApplicationExtension,
+ NetscapeExtensionBlockSize,
+ NetscapeExtensionBlock,
+ SkipBlockSize,
+ SkipBlock,
+ Done,
+ Error
+ } state;
+ int gncols;
+ int lncols;
+ int ncols;
+ int lzwsize;
+ bool lcmap;
+ int swidth, sheight;
+ int width, height;
+ int left, top, right, bottom;
+ enum Disposal { NoDisposal, DoNotChange, RestoreBackground, RestoreImage };
+ Disposal disposal;
+ bool disposed;
+ int trans_index;
+ bool gcmap;
+ int bgcol;
+ int interlace;
+ int accum;
+ int bitcount;
+
+ enum { max_lzw_bits=12 }; // (poor-compiler's static const int)
+
+ int code_size, clear_code, end_code, max_code_size, max_code;
+ int firstcode, oldcode, incode;
+ short* table[2];
+ short* stack;
+ short *sp;
+ bool needfirst;
+ int x, y;
+ int frame;
+ bool out_of_bounds;
+ bool digress;
+ void nextY(unsigned char *bits, int bpl);
+ void disposePrevious(QImage *image);
+};
+
+/*!
+ Constructs a QGIFFormat.
+*/
+QGIFFormat::QGIFFormat()
+{
+ globalcmap = 0;
+ localcmap = 0;
+ lncols = 0;
+ gncols = 0;
+ disposal = NoDisposal;
+ out_of_bounds = false;
+ disposed = true;
+ frame = -1;
+ state = Header;
+ count = 0;
+ lcmap = false;
+ newFrame = false;
+ partialNewFrame = false;
+ table[0] = 0;
+ table[1] = 0;
+ stack = 0;
+}
+
+/*!
+ Destroys a QGIFFormat.
+*/
+QGIFFormat::~QGIFFormat()
+{
+ if (globalcmap) delete[] globalcmap;
+ if (localcmap) delete[] localcmap;
+ delete [] stack;
+}
+
+void QGIFFormat::disposePrevious(QImage *image)
+{
+ if (out_of_bounds) {
+ // flush anything that survived
+ // ### Changed: QRect(0, 0, swidth, sheight)
+ }
+
+ // Handle disposal of previous image before processing next one
+
+ if (disposed) return;
+
+ int l = qMin(swidth-1,left);
+ int r = qMin(swidth-1,right);
+ int t = qMin(sheight-1,top);
+ int b = qMin(sheight-1,bottom);
+
+ switch (disposal) {
+ case NoDisposal:
+ break;
+ case DoNotChange:
+ break;
+ case RestoreBackground:
+ if (trans_index>=0) {
+ // Easy: we use the transparent color
+ fillRect(image, l, t, r-l+1, b-t+1, Q_TRANSPARENT);
+ } else if (bgcol>=0) {
+ // Easy: we use the bgcol given
+ fillRect(image, l, t, r-l+1, b-t+1, color(bgcol));
+ } else {
+ // Impossible: We don't know of a bgcol - use pixel 0
+ const QRgb *bits = reinterpret_cast<const QRgb *>(image->constBits());
+ fillRect(image, l, t, r-l+1, b-t+1, bits[0]);
+ }
+ // ### Changed: QRect(l, t, r-l+1, b-t+1)
+ break;
+ case RestoreImage: {
+ if (frame >= 0) {
+ for (int ln=t; ln<=b; ln++) {
+ memcpy(image->scanLine(ln)+l,
+ backingstore.constScanLine(ln-t),
+ (r-l+1)*sizeof(QRgb));
+ }
+ // ### Changed: QRect(l, t, r-l+1, b-t+1)
+ }
+ }
+ }
+ disposal = NoDisposal; // Until an extension says otherwise.
+
+ disposed = true;
+}
+
+/*!
+ This function decodes some data into image changes.
+
+ Returns the number of bytes consumed.
+*/
+int QGIFFormat::decode(QImage *image, const uchar *buffer, int length,
+ int *nextFrameDelay, int *loopCount)
+{
+ // We are required to state that
+ // "The Graphics Interchange Format(c) is the Copyright property of
+ // CompuServe Incorporated. GIF(sm) is a Service Mark property of
+ // CompuServe Incorporated."
+
+ if (!stack) {
+ stack = new short[(1 << max_lzw_bits) * 4];
+ table[0] = &stack[(1 << max_lzw_bits) * 2];
+ table[1] = &stack[(1 << max_lzw_bits) * 3];
+ }
+
+ image->detach();
+ int bpl = image->bytesPerLine();
+ unsigned char *bits = image->bits();
+
+#define LM(l, m) (((m)<<8)|l)
+ digress = false;
+ const int initial = length;
+ while (!digress && length) {
+ length--;
+ unsigned char ch=*buffer++;
+ switch (state) {
+ case Header:
+ hold[count++]=ch;
+ if (count==6) {
+ // Header
+ gif89=(hold[3]!='8' || hold[4]!='7');
+ state=LogicalScreenDescriptor;
+ count=0;
+ }
+ break;
+ case LogicalScreenDescriptor:
+ hold[count++]=ch;
+ if (count==7) {
+ // Logical Screen Descriptor
+ swidth=LM(hold[0], hold[1]);
+ sheight=LM(hold[2], hold[3]);
+ gcmap=!!(hold[4]&0x80);
+ //UNUSED: bpchan=(((hold[4]&0x70)>>3)+1);
+ //UNUSED: gcmsortflag=!!(hold[4]&0x08);
+ gncols=2<<(hold[4]&0x7);
+ bgcol=(gcmap) ? hold[5] : -1;
+ //aspect=hold[6] ? double(hold[6]+15)/64.0 : 1.0;
+
+ trans_index = -1;
+ count=0;
+ ncols=gncols;
+ if (gcmap) {
+ ccount=0;
+ state=GlobalColorMap;
+ globalcmap = new QRgb[gncols+1]; // +1 for trans_index
+ globalcmap[gncols] = Q_TRANSPARENT;
+ } else {
+ state=Introducer;
+ }
+ }
+ break;
+ case GlobalColorMap: case LocalColorMap:
+ hold[count++]=ch;
+ if (count==3) {
+ QRgb rgb = qRgb(hold[0], hold[1], hold[2]);
+ if (state == LocalColorMap) {
+ if (ccount < lncols)
+ localcmap[ccount] = rgb;
+ } else {
+ globalcmap[ccount] = rgb;
+ }
+ if (++ccount >= ncols) {
+ if (state == LocalColorMap)
+ state=TableImageLZWSize;
+ else
+ state=Introducer;
+ }
+ count=0;
+ }
+ break;
+ case Introducer:
+ hold[count++]=ch;
+ switch (ch) {
+ case ',':
+ state=ImageDescriptor;
+ break;
+ case '!':
+ state=ExtensionLabel;
+ break;
+ case ';':
+ // ### Changed: QRect(0, 0, swidth, sheight)
+ state=Done;
+ break;
+ default:
+ digress=true;
+ // Unexpected Introducer - ignore block
+ state=Error;
+ }
+ break;
+ case ImageDescriptor:
+ hold[count++]=ch;
+ if (count==10) {
+ int newleft=LM(hold[1], hold[2]);
+ int newtop=LM(hold[3], hold[4]);
+ int newwidth=LM(hold[5], hold[6]);
+ int newheight=LM(hold[7], hold[8]);
+
+ // disbelieve ridiculous logical screen sizes,
+ // unless the image frames are also large.
+ if (swidth/10 > qMax(newwidth,200))
+ swidth = -1;
+ if (sheight/10 > qMax(newheight,200))
+ sheight = -1;
+
+ if (swidth <= 0)
+ swidth = newleft + newwidth;
+ if (sheight <= 0)
+ sheight = newtop + newheight;
+
+ QImage::Format format = trans_index >= 0 ? QImage::Format_ARGB32 : QImage::Format_RGB32;
+ if (image->isNull()) {
+ (*image) = QImage(swidth, sheight, format);
+ bpl = image->bytesPerLine();
+ bits = image->bits();
+ memset(bits, 0, image->byteCount());
+ }
+
+ // Check if the previous attempt to create the image failed. If it
+ // did then the image is broken and we should give up.
+ if (image->isNull()) {
+ state = Error;
+ return -1;
+ }
+
+ disposePrevious(image);
+ disposed = false;
+
+ left = newleft;
+ top = newtop;
+ width = newwidth;
+ height = newheight;
+
+ right=qMax(0, qMin(left+width, swidth)-1);
+ bottom=qMax(0, qMin(top+height, sheight)-1);
+ lcmap=!!(hold[9]&0x80);
+ interlace=!!(hold[9]&0x40);
+ //bool lcmsortflag=!!(hold[9]&0x20);
+ lncols=lcmap ? (2<<(hold[9]&0x7)) : 0;
+ if (lncols) {
+ if (localcmap)
+ delete [] localcmap;
+ localcmap = new QRgb[lncols+1];
+ localcmap[lncols] = Q_TRANSPARENT;
+ ncols = lncols;
+ } else {
+ ncols = gncols;
+ }
+ frame++;
+ if (frame == 0) {
+ if (left || top || width<swidth || height<sheight) {
+ // Not full-size image - erase with bg or transparent
+ if (trans_index >= 0) {
+ fillRect(image, 0, 0, swidth, sheight, color(trans_index));
+ // ### Changed: QRect(0, 0, swidth, sheight)
+ } else if (bgcol>=0) {
+ fillRect(image, 0, 0, swidth, sheight, color(bgcol));
+ // ### Changed: QRect(0, 0, swidth, sheight)
+ }
+ }
+ }
+
+ if (disposal == RestoreImage) {
+ int l = qMin(swidth-1,left);
+ int r = qMin(swidth-1,right);
+ int t = qMin(sheight-1,top);
+ int b = qMin(sheight-1,bottom);
+ int w = r-l+1;
+ int h = b-t+1;
+
+ if (backingstore.width() < w
+ || backingstore.height() < h) {
+ // We just use the backing store as a byte array
+ backingstore = QImage(qMax(backingstore.width(), w),
+ qMax(backingstore.height(), h),
+ QImage::Format_RGB32);
+ memset(backingstore.bits(), 0, backingstore.byteCount());
+ }
+ const int dest_bpl = backingstore.bytesPerLine();
+ unsigned char *dest_data = backingstore.bits();
+ for (int ln=0; ln<h; ln++) {
+ memcpy(FAST_SCAN_LINE(dest_data, dest_bpl, ln),
+ FAST_SCAN_LINE(bits, bpl, t+ln) + l, w*sizeof(QRgb));
+ }
+ }
+
+ count=0;
+ if (lcmap) {
+ ccount=0;
+ state=LocalColorMap;
+ } else {
+ state=TableImageLZWSize;
+ }
+ x = left;
+ y = top;
+ accum = 0;
+ bitcount = 0;
+ sp = stack;
+ firstcode = oldcode = 0;
+ needfirst = true;
+ out_of_bounds = left>=swidth || y>=sheight;
+ }
+ break;
+ case TableImageLZWSize: {
+ lzwsize=ch;
+ if (lzwsize > max_lzw_bits) {
+ state=Error;
+ } else {
+ code_size=lzwsize+1;
+ clear_code=1<<lzwsize;
+ end_code=clear_code+1;
+ max_code_size=2*clear_code;
+ max_code=clear_code+2;
+ int i;
+ for (i=0; i<clear_code; i++) {
+ table[0][i]=0;
+ table[1][i]=i;
+ }
+ state=ImageDataBlockSize;
+ }
+ count=0;
+ break;
+ } case ImageDataBlockSize:
+ expectcount=ch;
+ if (expectcount) {
+ state=ImageDataBlock;
+ } else {
+ state=Introducer;
+ digress = true;
+ newFrame = true;
+ }
+ break;
+ case ImageDataBlock:
+ count++;
+ accum|=(ch<<bitcount);
+ bitcount+=8;
+ while (bitcount>=code_size && state==ImageDataBlock) {
+ int code=accum&((1<<code_size)-1);
+ bitcount-=code_size;
+ accum>>=code_size;
+
+ if (code==clear_code) {
+ if (!needfirst) {
+ code_size=lzwsize+1;
+ max_code_size=2*clear_code;
+ max_code=clear_code+2;
+ }
+ needfirst=true;
+ } else if (code==end_code) {
+ bitcount = -32768;
+ // Left the block end arrive
+ } else {
+ if (needfirst) {
+ firstcode=oldcode=code;
+ if (!out_of_bounds && image->height() > y && ((frame == 0) || (firstcode != trans_index)))
+ ((QRgb*)FAST_SCAN_LINE(bits, bpl, y))[x] = color(firstcode);
+ x++;
+ if (x>=swidth) out_of_bounds = true;
+ needfirst=false;
+ if (x>=left+width) {
+ x=left;
+ out_of_bounds = left>=swidth || y>=sheight;
+ nextY(bits, bpl);
+ }
+ } else {
+ incode=code;
+ if (code>=max_code) {
+ *sp++=firstcode;
+ code=oldcode;
+ }
+ while (code>=clear_code+2) {
+ if (code >= max_code) {
+ state = Error;
+ return -1;
+ }
+ *sp++=table[1][code];
+ if (code==table[0][code]) {
+ state=Error;
+ return -1;
+ }
+ if (sp-stack>=(1<<(max_lzw_bits))*2) {
+ state=Error;
+ return -1;
+ }
+ code=table[0][code];
+ }
+ if (code < 0) {
+ state = Error;
+ return -1;
+ }
+
+ *sp++=firstcode=table[1][code];
+ code=max_code;
+ if (code<(1<<max_lzw_bits)) {
+ table[0][code]=oldcode;
+ table[1][code]=firstcode;
+ max_code++;
+ if ((max_code>=max_code_size)
+ && (max_code_size<(1<<max_lzw_bits)))
+ {
+ max_code_size*=2;
+ code_size++;
+ }
+ }
+ oldcode=incode;
+ const int h = image->height();
+ QRgb *line = 0;
+ if (!out_of_bounds && h > y)
+ line = (QRgb*)FAST_SCAN_LINE(bits, bpl, y);
+ while (sp>stack) {
+ const uchar index = *(--sp);
+ if (!out_of_bounds && h > y && ((frame == 0) || (index != trans_index))) {
+ line[x] = color(index);
+ }
+ x++;
+ if (x>=swidth) out_of_bounds = true;
+ if (x>=left+width) {
+ x=left;
+ out_of_bounds = left>=swidth || y>=sheight;
+ nextY(bits, bpl);
+ if (!out_of_bounds && h > y)
+ line = (QRgb*)FAST_SCAN_LINE(bits, bpl, y);
+ }
+ }
+ }
+ }
+ }
+ partialNewFrame = true;
+ if (count==expectcount) {
+ count=0;
+ state=ImageDataBlockSize;
+ }
+ break;
+ case ExtensionLabel:
+ switch (ch) {
+ case 0xf9:
+ state=GraphicControlExtension;
+ break;
+ case 0xff:
+ state=ApplicationExtension;
+ break;
+#if 0
+ case 0xfe:
+ state=CommentExtension;
+ break;
+ case 0x01:
+ break;
+#endif
+ default:
+ state=SkipBlockSize;
+ }
+ count=0;
+ break;
+ case ApplicationExtension:
+ if (count<11) hold[count]=ch;
+ count++;
+ if (count==hold[0]+1) {
+ if (qstrncmp((char*)(hold+1), "NETSCAPE", 8)==0) {
+ // Looping extension
+ state=NetscapeExtensionBlockSize;
+ } else {
+ state=SkipBlockSize;
+ }
+ count=0;
+ }
+ break;
+ case NetscapeExtensionBlockSize:
+ expectcount=ch;
+ count=0;
+ if (expectcount) state=NetscapeExtensionBlock;
+ else state=Introducer;
+ break;
+ case NetscapeExtensionBlock:
+ if (count<3) hold[count]=ch;
+ count++;
+ if (count==expectcount) {
+ *loopCount = hold[1]+hold[2]*256;
+ state=SkipBlockSize; // Ignore further blocks
+ }
+ break;
+ case GraphicControlExtension:
+ if (count<5) hold[count]=ch;
+ count++;
+ if (count==hold[0]+1) {
+ disposePrevious(image);
+ disposal=Disposal((hold[1]>>2)&0x7);
+ //UNUSED: waitforuser=!!((hold[1]>>1)&0x1);
+ int delay=count>3 ? LM(hold[2], hold[3]) : 1;
+ // IE and mozilla use a minimum delay of 10. With the minimum delay of 10
+ // we are compatible to them and avoid huge loads on the app and xserver.
+ *nextFrameDelay = (delay < 2 ? 10 : delay) * 10;
+
+ bool havetrans=hold[1]&0x1;
+ trans_index = havetrans ? hold[4] : -1;
+
+ count=0;
+ state=SkipBlockSize;
+ }
+ break;
+ case SkipBlockSize:
+ expectcount=ch;
+ count=0;
+ if (expectcount) state=SkipBlock;
+ else state=Introducer;
+ break;
+ case SkipBlock:
+ count++;
+ if (count==expectcount) state=SkipBlockSize;
+ break;
+ case Done:
+ digress=true;
+ /* Netscape ignores the junk, so we do too.
+ length++; // Unget
+ state=Error; // More calls to this is an error
+ */
+ break;
+ case Error:
+ return -1; // Called again after done.
+ }
+ }
+ return initial-length;
+}
+
+/*!
+ Scans through the data stream defined by \a device and returns the image
+ sizes found in the stream in the \a imageSizes vector.
+*/
+void QGIFFormat::scan(QIODevice *device, QVector<QSize> *imageSizes, int *loopCount)
+{
+ if (!device)
+ return;
+
+ qint64 oldPos = device->pos();
+ if (device->isSequential() || !device->seek(0))
+ return;
+
+ int colorCount = 0;
+ int localColorCount = 0;
+ int globalColorCount = 0;
+ int colorReadCount = 0;
+ bool localColormap = false;
+ bool globalColormap = false;
+ int count = 0;
+ int blockSize = 0;
+ int imageWidth = 0;
+ int imageHeight = 0;
+ bool done = false;
+ uchar hold[16];
+ State state = Header;
+
+ const int readBufferSize = 40960; // 40k read buffer
+ QByteArray readBuffer(device->read(readBufferSize));
+
+ if (readBuffer.isEmpty()) {
+ device->seek(oldPos);
+ return;
+ }
+
+ // This is a specialized version of the state machine from decode(),
+ // which doesn't do any image decoding or mallocing, and has an
+ // optimized way of skipping SkipBlocks, ImageDataBlocks and
+ // Global/LocalColorMaps.
+
+ while (!readBuffer.isEmpty()) {
+ int length = readBuffer.size();
+ const uchar *buffer = (const uchar *) readBuffer.constData();
+ while (!done && length) {
+ length--;
+ uchar ch = *buffer++;
+ switch (state) {
+ case Header:
+ hold[count++] = ch;
+ if (count == 6) {
+ state = LogicalScreenDescriptor;
+ count = 0;
+ }
+ break;
+ case LogicalScreenDescriptor:
+ hold[count++] = ch;
+ if (count == 7) {
+ imageWidth = LM(hold[0], hold[1]);
+ imageHeight = LM(hold[2], hold[3]);
+ globalColormap = !!(hold[4] & 0x80);
+ globalColorCount = 2 << (hold[4] & 0x7);
+ count = 0;
+ colorCount = globalColorCount;
+ if (globalColormap) {
+ int colorTableSize = 3 * globalColorCount;
+ if (length >= colorTableSize) {
+ // skip the global color table in one go
+ length -= colorTableSize;
+ buffer += colorTableSize;
+ state = Introducer;
+ } else {
+ colorReadCount = 0;
+ state = GlobalColorMap;
+ }
+ } else {
+ state=Introducer;
+ }
+ }
+ break;
+ case GlobalColorMap:
+ case LocalColorMap:
+ hold[count++] = ch;
+ if (count == 3) {
+ if (++colorReadCount >= colorCount) {
+ if (state == LocalColorMap)
+ state = TableImageLZWSize;
+ else
+ state = Introducer;
+ }
+ count = 0;
+ }
+ break;
+ case Introducer:
+ hold[count++] = ch;
+ switch (ch) {
+ case 0x2c:
+ state = ImageDescriptor;
+ break;
+ case 0x21:
+ state = ExtensionLabel;
+ break;
+ case 0x3b:
+ state = Done;
+ break;
+ default:
+ done = true;
+ state = Error;
+ }
+ break;
+ case ImageDescriptor:
+ hold[count++] = ch;
+ if (count == 10) {
+ int newLeft = LM(hold[1], hold[2]);
+ int newTop = LM(hold[3], hold[4]);
+ int newWidth = LM(hold[5], hold[6]);
+ int newHeight = LM(hold[7], hold[8]);
+
+ if (imageWidth/10 > qMax(newWidth,200))
+ imageWidth = -1;
+ if (imageHeight/10 > qMax(newHeight,200))
+ imageHeight = -1;
+
+ if (imageWidth <= 0)
+ imageWidth = newLeft + newWidth;
+ if (imageHeight <= 0)
+ imageHeight = newTop + newHeight;
+
+ *imageSizes << QSize(imageWidth, imageHeight);
+
+ localColormap = !!(hold[9] & 0x80);
+ localColorCount = localColormap ? (2 << (hold[9] & 0x7)) : 0;
+ if (localColorCount)
+ colorCount = localColorCount;
+ else
+ colorCount = globalColorCount;
+
+ count = 0;
+ if (localColormap) {
+ int colorTableSize = 3 * localColorCount;
+ if (length >= colorTableSize) {
+ // skip the local color table in one go
+ length -= colorTableSize;
+ buffer += colorTableSize;
+ state = TableImageLZWSize;
+ } else {
+ colorReadCount = 0;
+ state = LocalColorMap;
+ }
+ } else {
+ state = TableImageLZWSize;
+ }
+ }
+ break;
+ case TableImageLZWSize:
+ if (ch > max_lzw_bits)
+ state = Error;
+ else
+ state = ImageDataBlockSize;
+ count = 0;
+ break;
+ case ImageDataBlockSize:
+ blockSize = ch;
+ if (blockSize) {
+ if (length >= blockSize) {
+ // we can skip the block in one go
+ length -= blockSize;
+ buffer += blockSize;
+ count = 0;
+ } else {
+ state = ImageDataBlock;
+ }
+ } else {
+ state = Introducer;
+ }
+ break;
+ case ImageDataBlock:
+ ++count;
+ if (count == blockSize) {
+ count = 0;
+ state = ImageDataBlockSize;
+ }
+ break;
+ case ExtensionLabel:
+ switch (ch) {
+ case 0xf9:
+ state = GraphicControlExtension;
+ break;
+ case 0xff:
+ state = ApplicationExtension;
+ break;
+ default:
+ state = SkipBlockSize;
+ }
+ count = 0;
+ break;
+ case ApplicationExtension:
+ if (count < 11)
+ hold[count] = ch;
+ ++count;
+ if (count == hold[0] + 1) {
+ if (qstrncmp((char*)(hold+1), "NETSCAPE", 8) == 0)
+ state=NetscapeExtensionBlockSize;
+ else
+ state=SkipBlockSize;
+ count = 0;
+ }
+ break;
+ case GraphicControlExtension:
+ if (count < 5)
+ hold[count] = ch;
+ ++count;
+ if (count == hold[0] + 1) {
+ count = 0;
+ state = SkipBlockSize;
+ }
+ break;
+ case NetscapeExtensionBlockSize:
+ blockSize = ch;
+ count = 0;
+ if (blockSize)
+ state = NetscapeExtensionBlock;
+ else
+ state = Introducer;
+ break;
+ case NetscapeExtensionBlock:
+ if (count < 3)
+ hold[count] = ch;
+ count++;
+ if (count == blockSize) {
+ *loopCount = LM(hold[1], hold[2]);
+ state = SkipBlockSize;
+ }
+ break;
+ case SkipBlockSize:
+ blockSize = ch;
+ count = 0;
+ if (blockSize) {
+ if (length >= blockSize) {
+ // we can skip the block in one go
+ length -= blockSize;
+ buffer += blockSize;
+ } else {
+ state = SkipBlock;
+ }
+ } else {
+ state = Introducer;
+ }
+ break;
+ case SkipBlock:
+ ++count;
+ if (count == blockSize)
+ state = SkipBlockSize;
+ break;
+ case Done:
+ done = true;
+ break;
+ case Error:
+ device->seek(oldPos);
+ return;
+ }
+ }
+ readBuffer = device->read(readBufferSize);
+ }
+ device->seek(oldPos);
+ return;
+}
+
+void QGIFFormat::fillRect(QImage *image, int col, int row, int w, int h, QRgb color)
+{
+ if (w>0) {
+ for (int j=0; j<h; j++) {
+ QRgb *line = (QRgb*)image->scanLine(j+row);
+ for (int i=0; i<w; i++)
+ *(line+col+i) = color;
+ }
+ }
+}
+
+void QGIFFormat::nextY(unsigned char *bits, int bpl)
+{
+ if (out_of_bounds)
+ return;
+ int my;
+ switch (interlace) {
+ case 0: // Non-interlaced
+ // if (!out_of_bounds) {
+ // ### Changed: QRect(left, y, right - left + 1, 1);
+ // }
+ y++;
+ break;
+ case 1: {
+ int i;
+ my = qMin(7, bottom-y);
+ // Don't dup with transparency
+ if (trans_index < 0) {
+ for (i=1; i<=my; i++) {
+ memcpy(FAST_SCAN_LINE(bits, bpl, y+i)+left*sizeof(QRgb), FAST_SCAN_LINE(bits, bpl, y)+left*sizeof(QRgb),
+ (right-left+1)*sizeof(QRgb));
+ }
+ }
+
+ // if (!out_of_bounds) {
+ // ### Changed: QRect(left, y, right - left + 1, my + 1);
+ // }
+// if (!out_of_bounds)
+// qDebug("consumer->changed(QRect(%d, %d, %d, %d))", left, y, right-left+1, my+1);
+ y+=8;
+ if (y>bottom) {
+ interlace++; y=top+4;
+ if (y > bottom) { // for really broken GIFs with bottom < 5
+ interlace=2;
+ y = top + 2;
+ if (y > bottom) { // for really broken GIF with bottom < 3
+ interlace = 0;
+ y = top + 1;
+ }
+ }
+ }
+ } break;
+ case 2: {
+ int i;
+ my = qMin(3, bottom-y);
+ // Don't dup with transparency
+ if (trans_index < 0) {
+ for (i=1; i<=my; i++) {
+ memcpy(FAST_SCAN_LINE(bits, bpl, y+i)+left*sizeof(QRgb), FAST_SCAN_LINE(bits, bpl, y)+left*sizeof(QRgb),
+ (right-left+1)*sizeof(QRgb));
+ }
+ }
+
+ // if (!out_of_bounds) {
+ // ### Changed: QRect(left, y, right - left + 1, my + 1);
+ // }
+ y+=8;
+ if (y>bottom) {
+ interlace++; y=top+2;
+ // handle broken GIF with bottom < 3
+ if (y > bottom) {
+ interlace = 3;
+ y = top + 1;
+ }
+ }
+ } break;
+ case 3: {
+ int i;
+ my = qMin(1, bottom-y);
+ // Don't dup with transparency
+ if (trans_index < 0) {
+ for (i=1; i<=my; i++) {
+ memcpy(FAST_SCAN_LINE(bits, bpl, y+i)+left*sizeof(QRgb), FAST_SCAN_LINE(bits, bpl, y)+left*sizeof(QRgb),
+ (right-left+1)*sizeof(QRgb));
+ }
+ }
+ // if (!out_of_bounds) {
+ // ### Changed: QRect(left, y, right - left + 1, my + 1);
+ // }
+ y+=4;
+ if (y>bottom) { interlace++; y=top+1; }
+ } break;
+ case 4:
+ // if (!out_of_bounds) {
+ // ### Changed: QRect(left, y, right - left + 1, 1);
+ // }
+ y+=2;
+ }
+
+ // Consume bogus extra lines
+ if (y >= sheight) out_of_bounds=true; //y=bottom;
+}
+
+inline QRgb QGIFFormat::color(uchar index) const
+{
+ if (index > ncols)
+ return Q_TRANSPARENT;
+
+ QRgb *map = lcmap ? localcmap : globalcmap;
+ QRgb col = map ? map[index] : 0;
+ return index == trans_index ? col & Q_TRANSPARENT : col;
+}
+
+//-------------------------------------------------------------------------
+//-------------------------------------------------------------------------
+//-------------------------------------------------------------------------
+
+QGifHandler::QGifHandler()
+{
+ gifFormat = new QGIFFormat;
+ nextDelay = 100;
+ loopCnt = -1;
+ frameNumber = -1;
+ scanIsCached = false;
+}
+
+QGifHandler::~QGifHandler()
+{
+ delete gifFormat;
+}
+
+// Does partial decode if necessary, just to see if an image is coming
+
+bool QGifHandler::imageIsComing() const
+{
+ const int GifChunkSize = 4096;
+
+ while (!gifFormat->partialNewFrame) {
+ if (buffer.isEmpty()) {
+ buffer += device()->read(GifChunkSize);
+ if (buffer.isEmpty())
+ break;
+ }
+
+ int decoded = gifFormat->decode(&lastImage, (const uchar *)buffer.constData(), buffer.size(),
+ &nextDelay, &loopCnt);
+ if (decoded == -1)
+ break;
+ buffer.remove(0, decoded);
+ }
+ return gifFormat->partialNewFrame;
+}
+
+bool QGifHandler::canRead() const
+{
+ if (canRead(device()) || imageIsComing()) {
+ setFormat("gif");
+ return true;
+ }
+
+ return false;
+}
+
+bool QGifHandler::canRead(QIODevice *device)
+{
+ if (!device) {
+ qWarning("QGifHandler::canRead() called with no device");
+ return false;
+ }
+
+ char head[6];
+ if (device->peek(head, sizeof(head)) == sizeof(head))
+ return qstrncmp(head, "GIF87a", 6) == 0
+ || qstrncmp(head, "GIF89a", 6) == 0;
+ return false;
+}
+
+bool QGifHandler::read(QImage *image)
+{
+ const int GifChunkSize = 4096;
+
+ while (!gifFormat->newFrame) {
+ if (buffer.isEmpty()) {
+ buffer += device()->read(GifChunkSize);
+ if (buffer.isEmpty())
+ break;
+ }
+
+ int decoded = gifFormat->decode(&lastImage, (const uchar *)buffer.constData(), buffer.size(),
+ &nextDelay, &loopCnt);
+ if (decoded == -1)
+ break;
+ buffer.remove(0, decoded);
+ }
+ if (gifFormat->newFrame || (gifFormat->partialNewFrame && device()->atEnd())) {
+ *image = lastImage;
+ ++frameNumber;
+ gifFormat->newFrame = false;
+ gifFormat->partialNewFrame = false;
+ return true;
+ }
+
+ return false;
+}
+
+bool QGifHandler::write(const QImage &image)
+{
+ Q_UNUSED(image);
+ return false;
+}
+
+bool QGifHandler::supportsOption(ImageOption option) const
+{
+ if (!device() || device()->isSequential())
+ return option == Animation;
+ else
+ return option == Size
+ || option == Animation;
+}
+
+QVariant QGifHandler::option(ImageOption option) const
+{
+ if (option == Size) {
+ if (!scanIsCached) {
+ QGIFFormat::scan(device(), &imageSizes, &loopCnt);
+ scanIsCached = true;
+ }
+ // before the first frame is read, or we have an empty data stream
+ if (frameNumber == -1)
+ return (imageSizes.count() > 0) ? QVariant(imageSizes.at(0)) : QVariant();
+ // after the last frame has been read, the next size is undefined
+ if (frameNumber >= imageSizes.count() - 1)
+ return QVariant();
+ // and the last case: the size of the next frame
+ return imageSizes.at(frameNumber + 1);
+ } else if (option == Animation) {
+ return true;
+ }
+ return QVariant();
+}
+
+void QGifHandler::setOption(ImageOption option, const QVariant &value)
+{
+ Q_UNUSED(option);
+ Q_UNUSED(value);
+}
+
+int QGifHandler::nextImageDelay() const
+{
+ return nextDelay;
+}
+
+int QGifHandler::imageCount() const
+{
+ if (!scanIsCached) {
+ QGIFFormat::scan(device(), &imageSizes, &loopCnt);
+ scanIsCached = true;
+ }
+ return imageSizes.count();
+}
+
+int QGifHandler::loopCount() const
+{
+ if (!scanIsCached) {
+ QGIFFormat::scan(device(), &imageSizes, &loopCnt);
+ scanIsCached = true;
+ }
+
+ if (loopCnt == 0)
+ return -1;
+ else if (loopCnt == -1)
+ return 0;
+ else
+ return loopCnt;
+}
+
+int QGifHandler::currentImageNumber() const
+{
+ return frameNumber;
+}
+
+QByteArray QGifHandler::name() const
+{
+ return "gif";
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/imageformats/gif/qgifhandler_p.h b/src/plugins/imageformats/gif/qgifhandler_p.h
new file mode 100644
index 0000000000..bc3debe83c
--- /dev/null
+++ b/src/plugins/imageformats/gif/qgifhandler_p.h
@@ -0,0 +1,105 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+** WARNING:
+** A separate license from Unisys may be required to use the gif
+** reader. See http://www.unisys.com/about__unisys/lzw/
+** for information from Unisys
+**
+****************************************************************************/
+
+#ifndef QGIFHANDLER_P_H
+#define QGIFHANDLER_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtGui/qimageiohandler.h>
+#include <QtGui/qimage.h>
+#include <QtCore/qbytearray.h>
+
+QT_BEGIN_NAMESPACE
+
+class QGIFFormat;
+class QGifHandler : public QImageIOHandler
+{
+public:
+ QGifHandler();
+ ~QGifHandler();
+
+ bool canRead() const Q_DECL_OVERRIDE;
+ bool read(QImage *image) Q_DECL_OVERRIDE;
+ bool write(const QImage &image) Q_DECL_OVERRIDE;
+
+ QByteArray name() const Q_DECL_OVERRIDE;
+
+ static bool canRead(QIODevice *device);
+
+ QVariant option(ImageOption option) const Q_DECL_OVERRIDE;
+ void setOption(ImageOption option, const QVariant &value) Q_DECL_OVERRIDE;
+ bool supportsOption(ImageOption option) const Q_DECL_OVERRIDE;
+
+ int imageCount() const Q_DECL_OVERRIDE;
+ int loopCount() const Q_DECL_OVERRIDE;
+ int nextImageDelay() const Q_DECL_OVERRIDE;
+ int currentImageNumber() const Q_DECL_OVERRIDE;
+
+private:
+ bool imageIsComing() const;
+ QGIFFormat *gifFormat;
+ QString fileName;
+ mutable QByteArray buffer;
+ mutable QImage lastImage;
+
+ mutable int nextDelay;
+ mutable int loopCnt;
+ int frameNumber;
+ mutable QVector<QSize> imageSizes;
+ mutable bool scanIsCached;
+};
+
+QT_END_NAMESPACE
+
+#endif // QGIFHANDLER_P_H
diff --git a/src/plugins/imageformats/ico/ico.pro b/src/plugins/imageformats/ico/ico.pro
index 60afdaed70..7ca1f18cb1 100644
--- a/src/plugins/imageformats/ico/ico.pro
+++ b/src/plugins/imageformats/ico/ico.pro
@@ -1,10 +1,7 @@
TARGET = qico
-QTDIR_build:REQUIRES = "!contains(QT_CONFIG, no-ico)"
-
-HEADERS += qicohandler.h main.h
-SOURCES += main.cpp \
- qicohandler.cpp
+HEADERS += main.h qicohandler.h
+SOURCES += main.cpp qicohandler.cpp
OTHER_FILES += ico.json
PLUGIN_TYPE = imageformats
diff --git a/src/plugins/imageformats/imageformats.pro b/src/plugins/imageformats/imageformats.pro
index 2b05f2feec..9d1c0c8fdf 100644
--- a/src/plugins/imageformats/imageformats.pro
+++ b/src/plugins/imageformats/imageformats.pro
@@ -1,5 +1,6 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += gui-private
-!contains(QT_CONFIG, no-jpeg):!contains(QT_CONFIG, jpeg):SUBDIRS += jpeg
-!contains(QT_CONFIG, no-gif):!contains(QT_CONFIG, gif):SUBDIRS += gif
-!contains(QT_CONFIG, no-ico):SUBDIRS += ico
+qtConfig(ico): SUBDIRS += ico
+qtConfig(jpeg): SUBDIRS += jpeg
+qtConfig(gif): SUBDIRS += gif
diff --git a/src/plugins/imageformats/jpeg/jpeg.pro b/src/plugins/imageformats/jpeg/jpeg.pro
index 526556179c..89476e62f5 100644
--- a/src/plugins/imageformats/jpeg/jpeg.pro
+++ b/src/plugins/imageformats/jpeg/jpeg.pro
@@ -1,13 +1,16 @@
TARGET = qjpeg
-QT += core-private
+QT += core-private gui-private
-QTDIR_build:REQUIRES = "!contains(QT_CONFIG, no-jpeg)"
+SOURCES += main.cpp qjpeghandler.cpp
+HEADERS += main.h qjpeghandler_p.h
+
+qtConfig(system-jpeg) {
+ QMAKE_USE += libjpeg
+} else {
+ include($$PWD/../../../3rdparty/libjpeg.pri)
+}
-include(../../../gui/image/qjpeghandler.pri)
-INCLUDEPATH += ../../../gui/image
-SOURCES += main.cpp
-HEADERS += main.h
OTHER_FILES += jpeg.json
PLUGIN_TYPE = imageformats
diff --git a/src/plugins/imageformats/jpeg/qjpeghandler.cpp b/src/plugins/imageformats/jpeg/qjpeghandler.cpp
new file mode 100644
index 0000000000..d89b8d398b
--- /dev/null
+++ b/src/plugins/imageformats/jpeg/qjpeghandler.cpp
@@ -0,0 +1,1125 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qjpeghandler_p.h"
+
+#include <qimage.h>
+#include <qvariant.h>
+#include <qvector.h>
+#include <qbuffer.h>
+#include <qmath.h>
+#include <private/qsimd_p.h>
+#include <private/qimage_p.h> // for qt_getImageText
+
+#include <stdio.h> // jpeglib needs this to be pre-included
+#include <setjmp.h>
+
+#ifdef FAR
+#undef FAR
+#endif
+
+// including jpeglib.h seems to be a little messy
+extern "C" {
+// mingw includes rpcndr.h but does not define boolean
+#if defined(Q_OS_WIN) && defined(Q_CC_GNU)
+# if defined(__RPCNDR_H__) && !defined(boolean)
+ typedef unsigned char boolean;
+# define HAVE_BOOLEAN
+# endif
+#endif
+
+#define XMD_H // shut JPEGlib up
+#if defined(Q_OS_UNIXWARE)
+# define HAVE_BOOLEAN // libjpeg under Unixware seems to need this
+#endif
+#include <jpeglib.h>
+#ifdef const
+# undef const // remove crazy C hackery in jconfig.h
+#endif
+}
+
+QT_BEGIN_NAMESPACE
+QT_WARNING_DISABLE_GCC("-Wclobbered")
+
+Q_GUI_EXPORT void QT_FASTCALL qt_convert_rgb888_to_rgb32(quint32 *dst, const uchar *src, int len);
+typedef void (QT_FASTCALL *Rgb888ToRgb32Converter)(quint32 *dst, const uchar *src, int len);
+
+struct my_error_mgr : public jpeg_error_mgr {
+ jmp_buf setjmp_buffer;
+};
+
+extern "C" {
+
+static void my_error_exit (j_common_ptr cinfo)
+{
+ my_error_mgr* myerr = (my_error_mgr*) cinfo->err;
+ char buffer[JMSG_LENGTH_MAX];
+ (*cinfo->err->format_message)(cinfo, buffer);
+ qWarning("%s", buffer);
+ longjmp(myerr->setjmp_buffer, 1);
+}
+
+static void my_output_message(j_common_ptr cinfo)
+{
+ char buffer[JMSG_LENGTH_MAX];
+ (*cinfo->err->format_message)(cinfo, buffer);
+ qWarning("%s", buffer);
+}
+
+}
+
+
+static const int max_buf = 4096;
+
+struct my_jpeg_source_mgr : public jpeg_source_mgr {
+ // Nothing dynamic - cannot rely on destruction over longjump
+ QIODevice *device;
+ JOCTET buffer[max_buf];
+ const QBuffer *memDevice;
+
+public:
+ my_jpeg_source_mgr(QIODevice *device);
+};
+
+extern "C" {
+
+static void qt_init_source(j_decompress_ptr)
+{
+}
+
+static boolean qt_fill_input_buffer(j_decompress_ptr cinfo)
+{
+ my_jpeg_source_mgr* src = (my_jpeg_source_mgr*)cinfo->src;
+ qint64 num_read = 0;
+ if (src->memDevice) {
+ src->next_input_byte = (const JOCTET *)(src->memDevice->data().constData() + src->memDevice->pos());
+ num_read = src->memDevice->data().size() - src->memDevice->pos();
+ src->device->seek(src->memDevice->data().size());
+ } else {
+ src->next_input_byte = src->buffer;
+ num_read = src->device->read((char*)src->buffer, max_buf);
+ }
+ if (num_read <= 0) {
+ // Insert a fake EOI marker - as per jpeglib recommendation
+ src->next_input_byte = src->buffer;
+ src->buffer[0] = (JOCTET) 0xFF;
+ src->buffer[1] = (JOCTET) JPEG_EOI;
+ src->bytes_in_buffer = 2;
+ } else {
+ src->bytes_in_buffer = num_read;
+ }
+ return TRUE;
+}
+
+static void qt_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
+{
+ my_jpeg_source_mgr* src = (my_jpeg_source_mgr*)cinfo->src;
+
+ // `dumb' implementation from jpeglib
+
+ /* Just a dumb implementation for now. Could use fseek() except
+ * it doesn't work on pipes. Not clear that being smart is worth
+ * any trouble anyway --- large skips are infrequent.
+ */
+ if (num_bytes > 0) {
+ while (num_bytes > (long) src->bytes_in_buffer) { // Should not happen in case of memDevice
+ num_bytes -= (long) src->bytes_in_buffer;
+ (void) qt_fill_input_buffer(cinfo);
+ /* note we assume that qt_fill_input_buffer will never return false,
+ * so suspension need not be handled.
+ */
+ }
+ src->next_input_byte += (size_t) num_bytes;
+ src->bytes_in_buffer -= (size_t) num_bytes;
+ }
+}
+
+static void qt_term_source(j_decompress_ptr cinfo)
+{
+ my_jpeg_source_mgr* src = (my_jpeg_source_mgr*)cinfo->src;
+ if (!src->device->isSequential())
+ src->device->seek(src->device->pos() - src->bytes_in_buffer);
+}
+
+}
+
+inline my_jpeg_source_mgr::my_jpeg_source_mgr(QIODevice *device)
+{
+ jpeg_source_mgr::init_source = qt_init_source;
+ jpeg_source_mgr::fill_input_buffer = qt_fill_input_buffer;
+ jpeg_source_mgr::skip_input_data = qt_skip_input_data;
+ jpeg_source_mgr::resync_to_restart = jpeg_resync_to_restart;
+ jpeg_source_mgr::term_source = qt_term_source;
+ this->device = device;
+ memDevice = qobject_cast<QBuffer *>(device);
+ bytes_in_buffer = 0;
+ next_input_byte = buffer;
+}
+
+
+inline static bool read_jpeg_size(int &w, int &h, j_decompress_ptr cinfo)
+{
+ (void) jpeg_calc_output_dimensions(cinfo);
+
+ w = cinfo->output_width;
+ h = cinfo->output_height;
+ return true;
+}
+
+#define HIGH_QUALITY_THRESHOLD 50
+
+inline static bool read_jpeg_format(QImage::Format &format, j_decompress_ptr cinfo)
+{
+
+ bool result = true;
+ switch (cinfo->output_components) {
+ case 1:
+ format = QImage::Format_Grayscale8;
+ break;
+ case 3:
+ case 4:
+ format = QImage::Format_RGB32;
+ break;
+ default:
+ result = false;
+ break;
+ }
+ cinfo->output_scanline = cinfo->output_height;
+ return result;
+}
+
+static bool ensureValidImage(QImage *dest, struct jpeg_decompress_struct *info,
+ const QSize& size)
+{
+ QImage::Format format;
+ switch (info->output_components) {
+ case 1:
+ format = QImage::Format_Grayscale8;
+ break;
+ case 3:
+ case 4:
+ format = QImage::Format_RGB32;
+ break;
+ default:
+ return false; // unsupported format
+ }
+
+ if (dest->size() != size || dest->format() != format)
+ *dest = QImage(size, format);
+
+ return !dest->isNull();
+}
+
+static bool read_jpeg_image(QImage *outImage,
+ QSize scaledSize, QRect scaledClipRect,
+ QRect clipRect, volatile int inQuality,
+ Rgb888ToRgb32Converter converter,
+ j_decompress_ptr info, struct my_error_mgr* err )
+{
+ if (!setjmp(err->setjmp_buffer)) {
+ // -1 means default quality.
+ int quality = inQuality;
+ if (quality < 0)
+ quality = 75;
+
+ // If possible, merge the scaledClipRect into either scaledSize
+ // or clipRect to avoid doing a separate scaled clipping pass.
+ // Best results are achieved by clipping before scaling, not after.
+ if (!scaledClipRect.isEmpty()) {
+ if (scaledSize.isEmpty() && clipRect.isEmpty()) {
+ // No clipping or scaling before final clip.
+ clipRect = scaledClipRect;
+ scaledClipRect = QRect();
+ } else if (scaledSize.isEmpty()) {
+ // Clipping, but no scaling: combine the clip regions.
+ scaledClipRect.translate(clipRect.topLeft());
+ clipRect = scaledClipRect.intersected(clipRect);
+ scaledClipRect = QRect();
+ } else if (clipRect.isEmpty()) {
+ // No clipping, but scaling: if we can map back to an
+ // integer pixel boundary, then clip before scaling.
+ if ((info->image_width % scaledSize.width()) == 0 &&
+ (info->image_height % scaledSize.height()) == 0) {
+ int x = scaledClipRect.x() * info->image_width /
+ scaledSize.width();
+ int y = scaledClipRect.y() * info->image_height /
+ scaledSize.height();
+ int width = (scaledClipRect.right() + 1) *
+ info->image_width / scaledSize.width() - x;
+ int height = (scaledClipRect.bottom() + 1) *
+ info->image_height / scaledSize.height() - y;
+ clipRect = QRect(x, y, width, height);
+ scaledSize = scaledClipRect.size();
+ scaledClipRect = QRect();
+ }
+ } else {
+ // Clipping and scaling: too difficult to figure out,
+ // and not a likely use case, so do it the long way.
+ }
+ }
+
+ // Determine the scale factor to pass to libjpeg for quick downscaling.
+ if (!scaledSize.isEmpty() && info->image_width && info->image_height) {
+ if (clipRect.isEmpty()) {
+ double f = qMin(double(info->image_width) / scaledSize.width(),
+ double(info->image_height) / scaledSize.height());
+
+ // libjpeg supports M/8 scaling with M=[1,16]. All downscaling factors
+ // are a speed improvement, but upscaling during decode is slower.
+ info->scale_num = qBound(1, qCeil(8/f), 8);
+ info->scale_denom = 8;
+ } else {
+ info->scale_denom = qMin(clipRect.width() / scaledSize.width(),
+ clipRect.height() / scaledSize.height());
+
+ // Only scale by powers of two when clipping so we can
+ // keep the exact pixel boundaries
+ if (info->scale_denom < 2)
+ info->scale_denom = 1;
+ else if (info->scale_denom < 4)
+ info->scale_denom = 2;
+ else if (info->scale_denom < 8)
+ info->scale_denom = 4;
+ else
+ info->scale_denom = 8;
+ info->scale_num = 1;
+
+ // Correct the scale factor so that we clip accurately.
+ // It is recommended that the clip rectangle be aligned
+ // on an 8-pixel boundary for best performance.
+ while (info->scale_denom > 1 &&
+ ((clipRect.x() % info->scale_denom) != 0 ||
+ (clipRect.y() % info->scale_denom) != 0 ||
+ (clipRect.width() % info->scale_denom) != 0 ||
+ (clipRect.height() % info->scale_denom) != 0)) {
+ info->scale_denom /= 2;
+ }
+ }
+ }
+
+ // If high quality not required, use fast decompression
+ if( quality < HIGH_QUALITY_THRESHOLD ) {
+ info->dct_method = JDCT_IFAST;
+ info->do_fancy_upsampling = FALSE;
+ }
+
+ (void) jpeg_calc_output_dimensions(info);
+
+ // Determine the clip region to extract.
+ QRect imageRect(0, 0, info->output_width, info->output_height);
+ QRect clip;
+ if (clipRect.isEmpty()) {
+ clip = imageRect;
+ } else if (info->scale_denom == info->scale_num) {
+ clip = clipRect.intersected(imageRect);
+ } else {
+ // The scale factor was corrected above to ensure that
+ // we don't miss pixels when we scale the clip rectangle.
+ clip = QRect(clipRect.x() / int(info->scale_denom),
+ clipRect.y() / int(info->scale_denom),
+ clipRect.width() / int(info->scale_denom),
+ clipRect.height() / int(info->scale_denom));
+ clip = clip.intersected(imageRect);
+ }
+
+ // Allocate memory for the clipped QImage.
+ if (!ensureValidImage(outImage, info, clip.size()))
+ longjmp(err->setjmp_buffer, 1);
+
+ // Avoid memcpy() overhead if grayscale with no clipping.
+ bool quickGray = (info->output_components == 1 &&
+ clip == imageRect);
+ if (!quickGray) {
+ // Ask the jpeg library to allocate a temporary row.
+ // The library will automatically delete it for us later.
+ // The libjpeg docs say we should do this before calling
+ // jpeg_start_decompress(). We can't use "new" here
+ // because we are inside the setjmp() block and an error
+ // in the jpeg input stream would cause a memory leak.
+ JSAMPARRAY rows = (info->mem->alloc_sarray)
+ ((j_common_ptr)info, JPOOL_IMAGE,
+ info->output_width * info->output_components, 1);
+
+ (void) jpeg_start_decompress(info);
+
+ while (info->output_scanline < info->output_height) {
+ int y = int(info->output_scanline) - clip.y();
+ if (y >= clip.height())
+ break; // We've read the entire clip region, so abort.
+
+ (void) jpeg_read_scanlines(info, rows, 1);
+
+ if (y < 0)
+ continue; // Haven't reached the starting line yet.
+
+ if (info->output_components == 3) {
+ uchar *in = rows[0] + clip.x() * 3;
+ QRgb *out = (QRgb*)outImage->scanLine(y);
+ converter(out, in, clip.width());
+ } else if (info->out_color_space == JCS_CMYK) {
+ // Convert CMYK->RGB.
+ uchar *in = rows[0] + clip.x() * 4;
+ QRgb *out = (QRgb*)outImage->scanLine(y);
+ for (int i = 0; i < clip.width(); ++i) {
+ int k = in[3];
+ *out++ = qRgb(k * in[0] / 255, k * in[1] / 255,
+ k * in[2] / 255);
+ in += 4;
+ }
+ } else if (info->output_components == 1) {
+ // Grayscale.
+ memcpy(outImage->scanLine(y),
+ rows[0] + clip.x(), clip.width());
+ }
+ }
+ } else {
+ // Load unclipped grayscale data directly into the QImage.
+ (void) jpeg_start_decompress(info);
+ while (info->output_scanline < info->output_height) {
+ uchar *row = outImage->scanLine(info->output_scanline);
+ (void) jpeg_read_scanlines(info, &row, 1);
+ }
+ }
+
+ if (info->output_scanline == info->output_height)
+ (void) jpeg_finish_decompress(info);
+
+ if (info->density_unit == 1) {
+ outImage->setDotsPerMeterX(int(100. * info->X_density / 2.54));
+ outImage->setDotsPerMeterY(int(100. * info->Y_density / 2.54));
+ } else if (info->density_unit == 2) {
+ outImage->setDotsPerMeterX(int(100. * info->X_density));
+ outImage->setDotsPerMeterY(int(100. * info->Y_density));
+ }
+
+ if (scaledSize.isValid() && scaledSize != clip.size()) {
+ *outImage = outImage->scaled(scaledSize, Qt::IgnoreAspectRatio, quality >= HIGH_QUALITY_THRESHOLD ? Qt::SmoothTransformation : Qt::FastTransformation);
+ }
+
+ if (!scaledClipRect.isEmpty())
+ *outImage = outImage->copy(scaledClipRect);
+ return !outImage->isNull();
+ }
+ else
+ return false;
+}
+
+struct my_jpeg_destination_mgr : public jpeg_destination_mgr {
+ // Nothing dynamic - cannot rely on destruction over longjump
+ QIODevice *device;
+ JOCTET buffer[max_buf];
+
+public:
+ my_jpeg_destination_mgr(QIODevice *);
+};
+
+
+extern "C" {
+
+static void qt_init_destination(j_compress_ptr)
+{
+}
+
+static boolean qt_empty_output_buffer(j_compress_ptr cinfo)
+{
+ my_jpeg_destination_mgr* dest = (my_jpeg_destination_mgr*)cinfo->dest;
+
+ int written = dest->device->write((char*)dest->buffer, max_buf);
+ if (written == -1)
+ (*cinfo->err->error_exit)((j_common_ptr)cinfo);
+
+ dest->next_output_byte = dest->buffer;
+ dest->free_in_buffer = max_buf;
+
+ return TRUE;
+}
+
+static void qt_term_destination(j_compress_ptr cinfo)
+{
+ my_jpeg_destination_mgr* dest = (my_jpeg_destination_mgr*)cinfo->dest;
+ qint64 n = max_buf - dest->free_in_buffer;
+
+ qint64 written = dest->device->write((char*)dest->buffer, n);
+ if (written == -1)
+ (*cinfo->err->error_exit)((j_common_ptr)cinfo);
+}
+
+}
+
+inline my_jpeg_destination_mgr::my_jpeg_destination_mgr(QIODevice *device)
+{
+ jpeg_destination_mgr::init_destination = qt_init_destination;
+ jpeg_destination_mgr::empty_output_buffer = qt_empty_output_buffer;
+ jpeg_destination_mgr::term_destination = qt_term_destination;
+ this->device = device;
+ next_output_byte = buffer;
+ free_in_buffer = max_buf;
+}
+
+static inline void set_text(const QImage &image, j_compress_ptr cinfo, const QString &description)
+{
+ const QMap<QString, QString> text = qt_getImageText(image, description);
+ for (auto it = text.begin(), end = text.end(); it != end; ++it) {
+ QByteArray comment = it.key().toLatin1();
+ if (!comment.isEmpty())
+ comment += ": ";
+ comment += it.value().toLatin1();
+ if (comment.length() > 65530)
+ comment.truncate(65530);
+ jpeg_write_marker(cinfo, JPEG_COM, (const JOCTET *)comment.constData(), comment.size());
+ }
+}
+
+static bool write_jpeg_image(const QImage &image, QIODevice *device, volatile int sourceQuality, const QString &description, bool optimize, bool progressive)
+{
+ bool success = false;
+ const QVector<QRgb> cmap = image.colorTable();
+
+ if (image.format() == QImage::Format_Invalid || image.format() == QImage::Format_Alpha8)
+ return false;
+
+ struct jpeg_compress_struct cinfo;
+ JSAMPROW row_pointer[1];
+ row_pointer[0] = 0;
+
+ struct my_jpeg_destination_mgr *iod_dest = new my_jpeg_destination_mgr(device);
+ struct my_error_mgr jerr;
+
+ cinfo.err = jpeg_std_error(&jerr);
+ jerr.error_exit = my_error_exit;
+ jerr.output_message = my_output_message;
+
+ if (!setjmp(jerr.setjmp_buffer)) {
+ // WARNING:
+ // this if loop is inside a setjmp/longjmp branch
+ // do not create C++ temporaries here because the destructor may never be called
+ // if you allocate memory, make sure that you can free it (row_pointer[0])
+ jpeg_create_compress(&cinfo);
+
+ cinfo.dest = iod_dest;
+
+ cinfo.image_width = image.width();
+ cinfo.image_height = image.height();
+
+ bool gray = false;
+ switch (image.format()) {
+ case QImage::Format_Mono:
+ case QImage::Format_MonoLSB:
+ case QImage::Format_Indexed8:
+ gray = true;
+ for (int i = image.colorCount(); gray && i; i--) {
+ gray = gray & qIsGray(cmap[i-1]);
+ }
+ cinfo.input_components = gray ? 1 : 3;
+ cinfo.in_color_space = gray ? JCS_GRAYSCALE : JCS_RGB;
+ break;
+ case QImage::Format_Grayscale8:
+ gray = true;
+ cinfo.input_components = 1;
+ cinfo.in_color_space = JCS_GRAYSCALE;
+ break;
+ default:
+ cinfo.input_components = 3;
+ cinfo.in_color_space = JCS_RGB;
+ }
+
+ jpeg_set_defaults(&cinfo);
+
+ qreal diffInch = qAbs(image.dotsPerMeterX()*2.54/100. - qRound(image.dotsPerMeterX()*2.54/100.))
+ + qAbs(image.dotsPerMeterY()*2.54/100. - qRound(image.dotsPerMeterY()*2.54/100.));
+ qreal diffCm = (qAbs(image.dotsPerMeterX()/100. - qRound(image.dotsPerMeterX()/100.))
+ + qAbs(image.dotsPerMeterY()/100. - qRound(image.dotsPerMeterY()/100.)))*2.54;
+ if (diffInch < diffCm) {
+ cinfo.density_unit = 1; // dots/inch
+ cinfo.X_density = qRound(image.dotsPerMeterX()*2.54/100.);
+ cinfo.Y_density = qRound(image.dotsPerMeterY()*2.54/100.);
+ } else {
+ cinfo.density_unit = 2; // dots/cm
+ cinfo.X_density = (image.dotsPerMeterX()+50) / 100;
+ cinfo.Y_density = (image.dotsPerMeterY()+50) / 100;
+ }
+
+ if (optimize)
+ cinfo.optimize_coding = true;
+
+ if (progressive)
+ jpeg_simple_progression(&cinfo);
+
+ int quality = sourceQuality >= 0 ? qMin(int(sourceQuality),100) : 75;
+ jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
+ jpeg_start_compress(&cinfo, TRUE);
+
+ set_text(image, &cinfo, description);
+
+ row_pointer[0] = new uchar[cinfo.image_width*cinfo.input_components];
+ int w = cinfo.image_width;
+ while (cinfo.next_scanline < cinfo.image_height) {
+ uchar *row = row_pointer[0];
+ switch (image.format()) {
+ case QImage::Format_Mono:
+ case QImage::Format_MonoLSB:
+ if (gray) {
+ const uchar* data = image.constScanLine(cinfo.next_scanline);
+ if (image.format() == QImage::Format_MonoLSB) {
+ for (int i=0; i<w; i++) {
+ bool bit = !!(*(data + (i >> 3)) & (1 << (i & 7)));
+ row[i] = qRed(cmap[bit]);
+ }
+ } else {
+ for (int i=0; i<w; i++) {
+ bool bit = !!(*(data + (i >> 3)) & (1 << (7 -(i & 7))));
+ row[i] = qRed(cmap[bit]);
+ }
+ }
+ } else {
+ const uchar* data = image.constScanLine(cinfo.next_scanline);
+ if (image.format() == QImage::Format_MonoLSB) {
+ for (int i=0; i<w; i++) {
+ bool bit = !!(*(data + (i >> 3)) & (1 << (i & 7)));
+ *row++ = qRed(cmap[bit]);
+ *row++ = qGreen(cmap[bit]);
+ *row++ = qBlue(cmap[bit]);
+ }
+ } else {
+ for (int i=0; i<w; i++) {
+ bool bit = !!(*(data + (i >> 3)) & (1 << (7 -(i & 7))));
+ *row++ = qRed(cmap[bit]);
+ *row++ = qGreen(cmap[bit]);
+ *row++ = qBlue(cmap[bit]);
+ }
+ }
+ }
+ break;
+ case QImage::Format_Indexed8:
+ if (gray) {
+ const uchar* pix = image.constScanLine(cinfo.next_scanline);
+ for (int i=0; i<w; i++) {
+ *row = qRed(cmap[*pix]);
+ ++row; ++pix;
+ }
+ } else {
+ const uchar* pix = image.constScanLine(cinfo.next_scanline);
+ for (int i=0; i<w; i++) {
+ *row++ = qRed(cmap[*pix]);
+ *row++ = qGreen(cmap[*pix]);
+ *row++ = qBlue(cmap[*pix]);
+ ++pix;
+ }
+ }
+ break;
+ case QImage::Format_Grayscale8:
+ memcpy(row, image.constScanLine(cinfo.next_scanline), w);
+ break;
+ case QImage::Format_RGB888:
+ memcpy(row, image.constScanLine(cinfo.next_scanline), w * 3);
+ break;
+ case QImage::Format_RGB32:
+ case QImage::Format_ARGB32:
+ case QImage::Format_ARGB32_Premultiplied:
+ {
+ const QRgb* rgb = (const QRgb*)image.constScanLine(cinfo.next_scanline);
+ for (int i=0; i<w; i++) {
+ *row++ = qRed(*rgb);
+ *row++ = qGreen(*rgb);
+ *row++ = qBlue(*rgb);
+ ++rgb;
+ }
+ }
+ break;
+ default:
+ {
+ // (Testing shows that this way is actually faster than converting to RGB888 + memcpy)
+ QImage rowImg = image.copy(0, cinfo.next_scanline, w, 1).convertToFormat(QImage::Format_RGB32);
+ const QRgb* rgb = (const QRgb*)rowImg.constScanLine(0);
+ for (int i=0; i<w; i++) {
+ *row++ = qRed(*rgb);
+ *row++ = qGreen(*rgb);
+ *row++ = qBlue(*rgb);
+ ++rgb;
+ }
+ }
+ break;
+ }
+ jpeg_write_scanlines(&cinfo, row_pointer, 1);
+ }
+
+ jpeg_finish_compress(&cinfo);
+ jpeg_destroy_compress(&cinfo);
+ success = true;
+ } else {
+ jpeg_destroy_compress(&cinfo);
+ success = false;
+ }
+
+ delete iod_dest;
+ delete [] row_pointer[0];
+ return success;
+}
+
+class QJpegHandlerPrivate
+{
+public:
+ enum State {
+ Ready,
+ ReadHeader,
+ ReadingEnd,
+ Error
+ };
+
+ QJpegHandlerPrivate(QJpegHandler *qq)
+ : quality(75), transformation(QImageIOHandler::TransformationNone), iod_src(0),
+ rgb888ToRgb32ConverterPtr(qt_convert_rgb888_to_rgb32), state(Ready), optimize(false), progressive(false), q(qq)
+ {}
+
+ ~QJpegHandlerPrivate()
+ {
+ if(iod_src)
+ {
+ jpeg_destroy_decompress(&info);
+ delete iod_src;
+ iod_src = 0;
+ }
+ }
+
+ bool readJpegHeader(QIODevice*);
+ bool read(QImage *image);
+
+ int quality;
+ QImageIOHandler::Transformations transformation;
+ QVariant size;
+ QImage::Format format;
+ QSize scaledSize;
+ QRect scaledClipRect;
+ QRect clipRect;
+ QString description;
+ QStringList readTexts;
+
+ struct jpeg_decompress_struct info;
+ struct my_jpeg_source_mgr * iod_src;
+ struct my_error_mgr err;
+
+ Rgb888ToRgb32Converter rgb888ToRgb32ConverterPtr;
+
+ State state;
+
+ bool optimize;
+ bool progressive;
+
+ QJpegHandler *q;
+};
+
+static bool readExifHeader(QDataStream &stream)
+{
+ char prefix[6];
+ if (stream.readRawData(prefix, sizeof(prefix)) != sizeof(prefix))
+ return false;
+ static const char exifMagic[6] = {'E', 'x', 'i', 'f', 0, 0};
+ return memcmp(prefix, exifMagic, 6) == 0;
+}
+
+/*
+ * Returns -1 on error
+ * Returns 0 if no Exif orientation was found
+ * Returns 1 orientation is horizontal (normal)
+ * Returns 2 mirror horizontal
+ * Returns 3 rotate 180
+ * Returns 4 mirror vertical
+ * Returns 5 mirror horizontal and rotate 270 CCW
+ * Returns 6 rotate 90 CW
+ * Returns 7 mirror horizontal and rotate 90 CW
+ * Returns 8 rotate 270 CW
+ */
+static int getExifOrientation(QByteArray &exifData)
+{
+ QDataStream stream(&exifData, QIODevice::ReadOnly);
+
+ if (!readExifHeader(stream))
+ return -1;
+
+ quint16 val;
+ quint32 offset;
+ const qint64 headerStart = stream.device()->pos();
+
+ // read byte order marker
+ stream >> val;
+ if (val == 0x4949) // 'II' == Intel
+ stream.setByteOrder(QDataStream::LittleEndian);
+ else if (val == 0x4d4d) // 'MM' == Motorola
+ stream.setByteOrder(QDataStream::BigEndian);
+ else
+ return -1; // unknown byte order
+
+ // read size
+ stream >> val;
+ if (val != 0x2a)
+ return -1;
+
+ stream >> offset;
+
+ // read IFD
+ while (!stream.atEnd()) {
+ quint16 numEntries;
+
+ // skip offset bytes to get the next IFD
+ const qint64 bytesToSkip = offset - (stream.device()->pos() - headerStart);
+
+ if (stream.skipRawData(bytesToSkip) != bytesToSkip)
+ return -1;
+
+ stream >> numEntries;
+
+ for (; numEntries > 0; --numEntries) {
+ quint16 tag;
+ quint16 type;
+ quint32 components;
+ quint16 value;
+ quint16 dummy;
+
+ stream >> tag >> type >> components >> value >> dummy;
+ if (tag == 0x0112) { // Tag Exif.Image.Orientation
+ if (components != 1)
+ return -1;
+ if (type != 3) // we are expecting it to be an unsigned short
+ return -1;
+ if (value < 1 || value > 8) // check for valid range
+ return -1;
+
+ // It is possible to include the orientation multiple times.
+ // Right now the first value is returned.
+ return value;
+ }
+ }
+
+ // read offset to next IFD
+ stream >> offset;
+ if (offset == 0) // this is the last IFD
+ break;
+ }
+
+ // No Exif orientation was found
+ return 0;
+}
+
+static QImageIOHandler::Transformations exif2Qt(int exifOrientation)
+{
+ switch (exifOrientation) {
+ case 1: // normal
+ return QImageIOHandler::TransformationNone;
+ case 2: // mirror horizontal
+ return QImageIOHandler::TransformationMirror;
+ case 3: // rotate 180
+ return QImageIOHandler::TransformationRotate180;
+ case 4: // mirror vertical
+ return QImageIOHandler::TransformationFlip;
+ case 5: // mirror horizontal and rotate 270 CW
+ return QImageIOHandler::TransformationFlipAndRotate90;
+ case 6: // rotate 90 CW
+ return QImageIOHandler::TransformationRotate90;
+ case 7: // mirror horizontal and rotate 90 CW
+ return QImageIOHandler::TransformationMirrorAndRotate90;
+ case 8: // rotate 270 CW
+ return QImageIOHandler::TransformationRotate270;
+ }
+ qWarning("Invalid EXIF orientation");
+ return QImageIOHandler::TransformationNone;
+}
+
+/*!
+ \internal
+*/
+bool QJpegHandlerPrivate::readJpegHeader(QIODevice *device)
+{
+ if(state == Ready)
+ {
+ state = Error;
+ iod_src = new my_jpeg_source_mgr(device);
+
+ info.err = jpeg_std_error(&err);
+ err.error_exit = my_error_exit;
+ err.output_message = my_output_message;
+
+ jpeg_create_decompress(&info);
+ info.src = iod_src;
+
+ if (!setjmp(err.setjmp_buffer)) {
+ jpeg_save_markers(&info, JPEG_COM, 0xFFFF);
+ jpeg_save_markers(&info, JPEG_APP0 + 1, 0xFFFF); // Exif uses APP1 marker
+
+ (void) jpeg_read_header(&info, TRUE);
+
+ int width = 0;
+ int height = 0;
+ read_jpeg_size(width, height, &info);
+ size = QSize(width, height);
+
+ format = QImage::Format_Invalid;
+ read_jpeg_format(format, &info);
+
+ QByteArray exifData;
+
+ for (jpeg_saved_marker_ptr marker = info.marker_list; marker != NULL; marker = marker->next) {
+ if (marker->marker == JPEG_COM) {
+ QString key, value;
+ QString s = QString::fromLatin1((const char *)marker->data, marker->data_length);
+ int index = s.indexOf(QLatin1String(": "));
+ if (index == -1 || s.indexOf(QLatin1Char(' ')) < index) {
+ key = QLatin1String("Description");
+ value = s;
+ } else {
+ key = s.left(index);
+ value = s.mid(index + 2);
+ }
+ if (!description.isEmpty())
+ description += QLatin1String("\n\n");
+ description += key + QLatin1String(": ") + value.simplified();
+ readTexts.append(key);
+ readTexts.append(value);
+ } else if (marker->marker == JPEG_APP0 + 1) {
+ exifData.append((const char*)marker->data, marker->data_length);
+ }
+ }
+
+ if (!exifData.isEmpty()) {
+ // Exif data present
+ int exifOrientation = getExifOrientation(exifData);
+ if (exifOrientation > 0)
+ transformation = exif2Qt(exifOrientation);
+ }
+
+ state = ReadHeader;
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else if(state == Error)
+ return false;
+ return true;
+}
+
+bool QJpegHandlerPrivate::read(QImage *image)
+{
+ if(state == Ready)
+ readJpegHeader(q->device());
+
+ if(state == ReadHeader)
+ {
+ bool success = read_jpeg_image(image, scaledSize, scaledClipRect, clipRect, quality, rgb888ToRgb32ConverterPtr, &info, &err);
+ if (success) {
+ for (int i = 0; i < readTexts.size()-1; i+=2)
+ image->setText(readTexts.at(i), readTexts.at(i+1));
+
+ state = ReadingEnd;
+ return true;
+ }
+
+ state = Error;
+ }
+
+ return false;
+
+}
+
+Q_GUI_EXPORT void QT_FASTCALL qt_convert_rgb888_to_rgb32_neon(quint32 *dst, const uchar *src, int len);
+Q_GUI_EXPORT void QT_FASTCALL qt_convert_rgb888_to_rgb32_ssse3(quint32 *dst, const uchar *src, int len);
+extern "C" void qt_convert_rgb888_to_rgb32_mips_dspr2_asm(quint32 *dst, const uchar *src, int len);
+
+QJpegHandler::QJpegHandler()
+ : d(new QJpegHandlerPrivate(this))
+{
+#if defined(__ARM_NEON__)
+ // from qimage_neon.cpp
+ if (qCpuHasFeature(NEON))
+ d->rgb888ToRgb32ConverterPtr = qt_convert_rgb888_to_rgb32_neon;
+#endif
+
+#if defined(QT_COMPILER_SUPPORTS_SSSE3)
+ // from qimage_ssse3.cpps
+ if (qCpuHasFeature(SSSE3)) {
+ d->rgb888ToRgb32ConverterPtr = qt_convert_rgb888_to_rgb32_ssse3;
+ }
+#endif // QT_COMPILER_SUPPORTS_SSSE3
+#if defined(QT_COMPILER_SUPPORTS_MIPS_DSPR2)
+ if (qCpuHasFeature(DSPR2)) {
+ d->rgb888ToRgb32ConverterPtr = qt_convert_rgb888_to_rgb32_mips_dspr2_asm;
+ }
+#endif // QT_COMPILER_SUPPORTS_DSPR2
+}
+
+QJpegHandler::~QJpegHandler()
+{
+ delete d;
+}
+
+bool QJpegHandler::canRead() const
+{
+ if(d->state == QJpegHandlerPrivate::Ready && !canRead(device()))
+ return false;
+
+ if (d->state != QJpegHandlerPrivate::Error && d->state != QJpegHandlerPrivate::ReadingEnd) {
+ setFormat("jpeg");
+ return true;
+ }
+
+ return false;
+}
+
+bool QJpegHandler::canRead(QIODevice *device)
+{
+ if (!device) {
+ qWarning("QJpegHandler::canRead() called with no device");
+ return false;
+ }
+
+ char buffer[2];
+ if (device->peek(buffer, 2) != 2)
+ return false;
+ return uchar(buffer[0]) == 0xff && uchar(buffer[1]) == 0xd8;
+}
+
+bool QJpegHandler::read(QImage *image)
+{
+ if (!canRead())
+ return false;
+ return d->read(image);
+}
+
+extern void qt_imageTransform(QImage &src, QImageIOHandler::Transformations orient);
+
+bool QJpegHandler::write(const QImage &image)
+{
+ if (d->transformation != QImageIOHandler::TransformationNone) {
+ // We don't support writing EXIF headers so apply the transform to the data.
+ QImage img = image;
+ qt_imageTransform(img, d->transformation);
+ return write_jpeg_image(img, device(), d->quality, d->description, d->optimize, d->progressive);
+ }
+ return write_jpeg_image(image, device(), d->quality, d->description, d->optimize, d->progressive);
+}
+
+bool QJpegHandler::supportsOption(ImageOption option) const
+{
+ return option == Quality
+ || option == ScaledSize
+ || option == ScaledClipRect
+ || option == ClipRect
+ || option == Description
+ || option == Size
+ || option == ImageFormat
+ || option == OptimizedWrite
+ || option == ProgressiveScanWrite
+ || option == ImageTransformation;
+}
+
+QVariant QJpegHandler::option(ImageOption option) const
+{
+ switch(option) {
+ case Quality:
+ return d->quality;
+ case ScaledSize:
+ return d->scaledSize;
+ case ScaledClipRect:
+ return d->scaledClipRect;
+ case ClipRect:
+ return d->clipRect;
+ case Description:
+ d->readJpegHeader(device());
+ return d->description;
+ case Size:
+ d->readJpegHeader(device());
+ return d->size;
+ case ImageFormat:
+ d->readJpegHeader(device());
+ return d->format;
+ case OptimizedWrite:
+ return d->optimize;
+ case ProgressiveScanWrite:
+ return d->progressive;
+ case ImageTransformation:
+ d->readJpegHeader(device());
+ return int(d->transformation);
+ default:
+ break;
+ }
+
+ return QVariant();
+}
+
+void QJpegHandler::setOption(ImageOption option, const QVariant &value)
+{
+ switch(option) {
+ case Quality:
+ d->quality = value.toInt();
+ break;
+ case ScaledSize:
+ d->scaledSize = value.toSize();
+ break;
+ case ScaledClipRect:
+ d->scaledClipRect = value.toRect();
+ break;
+ case ClipRect:
+ d->clipRect = value.toRect();
+ break;
+ case Description:
+ d->description = value.toString();
+ break;
+ case OptimizedWrite:
+ d->optimize = value.toBool();
+ break;
+ case ProgressiveScanWrite:
+ d->progressive = value.toBool();
+ break;
+ case ImageTransformation: {
+ int transformation = value.toInt();
+ if (transformation > 0 && transformation < 8)
+ d->transformation = QImageIOHandler::Transformations(transformation);
+ }
+ default:
+ break;
+ }
+}
+
+QByteArray QJpegHandler::name() const
+{
+ return "jpeg";
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsfontdatabase_ft.h b/src/plugins/imageformats/jpeg/qjpeghandler_p.h
index 988b0012f7..534ce12115 100644
--- a/src/plugins/platforms/windows/qwindowsfontdatabase_ft.h
+++ b/src/plugins/imageformats/jpeg/qjpeghandler_p.h
@@ -37,32 +37,49 @@
**
****************************************************************************/
-#ifndef QWINDOWSFONTDATABASEFT_H
-#define QWINDOWSFONTDATABASEFT_H
+#ifndef QJPEGHANDLER_P_H
+#define QJPEGHANDLER_P_H
-#include <QtPlatformSupport/private/qbasicfontdatabase_p.h>
-#include <QtCore/QSharedPointer>
-#include "qtwindows_additional.h"
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtGui/qimageiohandler.h>
+#include <QtCore/QSize>
+#include <QtCore/QRect>
QT_BEGIN_NAMESPACE
-class QWindowsFontDatabaseFT : public QBasicFontDatabase
+class QJpegHandlerPrivate;
+class QJpegHandler : public QImageIOHandler
{
public:
- void populateFontDatabase() Q_DECL_OVERRIDE;
- void populateFamily(const QString &familyName) Q_DECL_OVERRIDE;
- QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) Q_DECL_OVERRIDE;
- QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize,
- QFont::HintingPreference hintingPreference) Q_DECL_OVERRIDE;
+ QJpegHandler();
+ ~QJpegHandler();
+
+ bool canRead() const Q_DECL_OVERRIDE;
+ bool read(QImage *image) Q_DECL_OVERRIDE;
+ bool write(const QImage &image) Q_DECL_OVERRIDE;
+
+ QByteArray name() const Q_DECL_OVERRIDE;
+
+ static bool canRead(QIODevice *device);
- QStringList fallbacksForFamily(const QString &family, QFont::Style style,
- QFont::StyleHint styleHint,
- QChar::Script script) const Q_DECL_OVERRIDE;
+ QVariant option(ImageOption option) const Q_DECL_OVERRIDE;
+ void setOption(ImageOption option, const QVariant &value) Q_DECL_OVERRIDE;
+ bool supportsOption(ImageOption option) const Q_DECL_OVERRIDE;
- QString fontDir() const Q_DECL_OVERRIDE;
- QFont defaultFont() const Q_DECL_OVERRIDE;
+private:
+ QJpegHandlerPrivate *d;
};
QT_END_NAMESPACE
-#endif // QWINDOWSFONTDATABASEFT_H
+#endif // QJPEGHANDLER_P_H
diff --git a/src/plugins/platforminputcontexts/compose/compose.pro b/src/plugins/platforminputcontexts/compose/compose.pro
index 86bdd4729b..2f53c5b416 100644
--- a/src/plugins/platforminputcontexts/compose/compose.pro
+++ b/src/plugins/platforminputcontexts/compose/compose.pro
@@ -2,8 +2,6 @@ TARGET = composeplatforminputcontextplugin
QT += core-private gui-private
-DEFINES += X11_PREFIX='\\"$$QMAKE_X11_PREFIX\\"'
-
SOURCES += $$PWD/qcomposeplatforminputcontextmain.cpp \
$$PWD/qcomposeplatforminputcontext.cpp \
$$PWD/generator/qtablegenerator.cpp \
@@ -12,15 +10,16 @@ HEADERS += $$PWD/qcomposeplatforminputcontext.h \
$$PWD/generator/qtablegenerator.h \
# libxkbcommon
-contains(QT_CONFIG, xkbcommon-qt): {
- # dont't need x11 dependency for compose key plugin
- QT_CONFIG -= use-xkbcommon-x11support
+!qtConfig(xkbcommon-system) {
include(../../../3rdparty/xkbcommon.pri)
} else {
- LIBS += $$QMAKE_LIBS_XKBCOMMON
- QMAKE_CXXFLAGS += $$QMAKE_CFLAGS_XKBCOMMON
+ QMAKE_USE += xkbcommon
}
+include($$OUT_PWD/../../../gui/qtgui-config.pri)
+
+DEFINES += X11_PREFIX='\\"$$QMAKE_X11_PREFIX\\"'
+
OTHER_FILES += $$PWD/compose.json
PLUGIN_TYPE = platforminputcontexts
diff --git a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp
index f8fe671a2b..bd25992457 100644
--- a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp
+++ b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp
@@ -255,6 +255,7 @@ void TableGenerator::initPossibleLocations()
// never meant for external software to parse compose tables directly. Best we
// can do is to hardcode search paths. To add an extra system path use
// the QTCOMPOSE environment variable
+ m_possibleLocations.reserve(7);
if (qEnvironmentVariableIsSet("QTCOMPOSE"))
m_possibleLocations.append(QString::fromLocal8Bit(qgetenv("QTCOMPOSE")));
m_possibleLocations.append(QStringLiteral("/usr/share/X11/locale"));
@@ -645,6 +646,6 @@ void TableGenerator::orderComposeTable()
// Stable-sorting to ensure that the item that appeared before the other in the
// original container will still appear first after the sort. This property is
// needed to handle the cases when user re-defines already defined key sequence
- std::stable_sort(m_composeTable.begin(), m_composeTable.end(), Compare());
+ std::stable_sort(m_composeTable.begin(), m_composeTable.end(), ByKeys());
}
diff --git a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h
index bf9f16b3e4..4f58358f4e 100644
--- a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h
+++ b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.h
@@ -45,7 +45,9 @@
#include <QtCore/QMap>
#include <QtCore/QString>
-#define QT_KEYSEQUENCE_MAX_LEN 6
+#include <algorithm>
+
+static Q_CONSTEXPR int QT_KEYSEQUENCE_MAX_LEN = 6;
//#define DEBUG_GENERATOR
@@ -65,25 +67,30 @@ Q_DECLARE_TYPEINFO(QComposeTableElement, Q_PRIMITIVE_TYPE);
QT_END_NAMESPACE
#endif
-class Compare
+struct ByKeys
{
-public:
- bool operator () (const QComposeTableElement &lhs, const uint rhs[QT_KEYSEQUENCE_MAX_LEN])
+ using uint_array = uint[QT_KEYSEQUENCE_MAX_LEN];
+ using result_type = bool;
+
+ bool operator()(const uint_array &lhs, const uint_array &rhs) const Q_DECL_NOTHROW
+ {
+ return std::lexicographical_compare(lhs, lhs + QT_KEYSEQUENCE_MAX_LEN,
+ rhs, rhs + QT_KEYSEQUENCE_MAX_LEN);
+ }
+
+ bool operator()(const uint_array &lhs, const QComposeTableElement &rhs) const Q_DECL_NOTHROW
+ {
+ return operator()(lhs, rhs.keys);
+ }
+
+ bool operator()(const QComposeTableElement &lhs, const uint_array &rhs) const Q_DECL_NOTHROW
{
- for (size_t i = 0; i < QT_KEYSEQUENCE_MAX_LEN; i++) {
- if (lhs.keys[i] != rhs[i])
- return (lhs.keys[i] < rhs[i]);
- }
- return false;
+ return operator()(lhs.keys, rhs);
}
- bool operator () (const QComposeTableElement &lhs, const QComposeTableElement &rhs)
+ bool operator()(const QComposeTableElement &lhs, const QComposeTableElement &rhs) const Q_DECL_NOTHROW
{
- for (size_t i = 0; i < QT_KEYSEQUENCE_MAX_LEN; i++) {
- if (lhs.keys[i] != rhs.keys[i])
- return (lhs.keys[i] < rhs.keys[i]);
- }
- return false;
+ return operator()(lhs.keys, rhs.keys);
}
};
diff --git a/src/plugins/platforminputcontexts/compose/qcomposeplatforminputcontext.cpp b/src/plugins/platforminputcontexts/compose/qcomposeplatforminputcontext.cpp
index 857f437661..6016d460fc 100644
--- a/src/plugins/platforminputcontexts/compose/qcomposeplatforminputcontext.cpp
+++ b/src/plugins/platforminputcontexts/compose/qcomposeplatforminputcontext.cpp
@@ -155,11 +155,8 @@ void QComposeInputContext::update(Qt::InputMethodQueries q)
static bool isDuplicate(const QComposeTableElement &lhs, const QComposeTableElement &rhs)
{
- for (size_t i = 0; i < QT_KEYSEQUENCE_MAX_LEN; i++) {
- if (lhs.keys[i] != rhs.keys[i])
- return false;
- }
- return true;
+ return std::equal(lhs.keys, lhs.keys + QT_KEYSEQUENCE_MAX_LEN,
+ QT_MAKE_CHECKED_ARRAY_ITERATOR(rhs.keys, QT_KEYSEQUENCE_MAX_LEN));
}
bool QComposeInputContext::checkComposeTable()
@@ -182,7 +179,7 @@ bool QComposeInputContext::checkComposeTable()
}
Q_ASSERT(!m_composeTable.isEmpty());
QVector<QComposeTableElement>::const_iterator it =
- std::lower_bound(m_composeTable.constBegin(), m_composeTable.constEnd(), m_composeBuffer, Compare());
+ std::lower_bound(m_composeTable.constBegin(), m_composeTable.constEnd(), m_composeBuffer, ByKeys());
// prevent dereferencing an 'end' iterator, which would result in a crash
if (it == m_composeTable.constEnd())
diff --git a/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp b/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp
index 200d5789a8..736c66ebc0 100644
--- a/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp
+++ b/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp
@@ -101,11 +101,13 @@ QIBusPlatformInputContext::QIBusPlatformInputContext ()
QString socketPath = QIBusPlatformInputContextPrivate::getSocketPath();
QFile file(socketPath);
if (file.open(QFile::ReadOnly)) {
+#ifndef QT_NO_FILESYSTEMWATCHER
// If KDE session save is used or restart ibus-daemon,
// the applications could run before ibus-daemon runs.
// We watch the getSocketPath() to get the launching ibus-daemon.
m_socketWatcher.addPath(socketPath);
connect(&m_socketWatcher, SIGNAL(fileChanged(QString)), this, SLOT(socketChanged(QString)));
+#endif
}
m_timer.setSingleShot(true);
@@ -278,7 +280,7 @@ void QIBusPlatformInputContext::updatePreeditText(const QDBusVariant &text, uint
QList<QInputMethodEvent::Attribute> attributes = t.attributes.imAttributes();
if (!t.text.isEmpty())
- attributes += QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, cursorPos, visible ? 1 : 0, QVariant());
+ attributes += QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, cursorPos, visible ? 1 : 0);
QInputMethodEvent event(t.text, attributes);
QCoreApplication::sendEvent(input, &event);
@@ -408,8 +410,10 @@ void QIBusPlatformInputContext::filterEventFinished(QDBusPendingCallWatcher *cal
&& window != NULL) {
const QPoint globalPos = window->screen()->handle()->cursor()->pos();
const QPoint pos = window->mapFromGlobal(globalPos);
+#ifndef QT_NO_CONTEXTMENU
QWindowSystemInterface::handleContextMenuEvent(window, false, pos,
globalPos, modifiers);
+#endif
}
#endif // QT_NO_CONTEXTMENU
QWindowSystemInterface::handleExtendedKeyEvent(window, time, type, qtcode, modifiers,
@@ -449,8 +453,10 @@ void QIBusPlatformInputContext::connectToBus()
d->initBus();
connectToContextSignals();
+#ifndef QT_NO_FILESYSTEMWATCHER
if (m_socketWatcher.files().size() == 0)
m_socketWatcher.addPath(QIBusPlatformInputContextPrivate::getSocketPath());
+#endif
}
void QIBusPlatformInputContext::globalEngineChanged(const QString &engine_name)
diff --git a/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h b/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h
index 4f2722480e..94fa5c3d60 100644
--- a/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h
+++ b/src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h
@@ -110,7 +110,9 @@ public Q_SLOTS:
private:
QIBusPlatformInputContextPrivate *d;
bool m_eventFilterUseSynchronousMode;
+#ifndef QT_NO_FILESYSTEMWATCHER
QFileSystemWatcher m_socketWatcher;
+#endif
QTimer m_timer;
void connectToContextSignals();
diff --git a/src/plugins/platforminputcontexts/ibus/qibustypes.cpp b/src/plugins/platforminputcontexts/ibus/qibustypes.cpp
index ac82fa3931..a2551f1320 100644
--- a/src/plugins/platforminputcontexts/ibus/qibustypes.cpp
+++ b/src/plugins/platforminputcontexts/ibus/qibustypes.cpp
@@ -73,10 +73,7 @@ void QIBusSerializable::serializeTo(QDBusArgument &argument) const
argument.beginMap(qMetaTypeId<QString>(), qMetaTypeId<QDBusVariant>());
- QHashIterator<QString, QDBusArgument> i(attachments);
- while (i.hasNext()) {
- i.next();
-
+ for (auto i = attachments.begin(), end = attachments.end(); i != end; ++i) {
argument.beginMapEntry();
argument << i.key();
diff --git a/src/plugins/platforminputcontexts/platforminputcontexts.pro b/src/plugins/platforminputcontexts/platforminputcontexts.pro
index faea54b874..ed6b1b8702 100644
--- a/src/plugins/platforminputcontexts/platforminputcontexts.pro
+++ b/src/plugins/platforminputcontexts/platforminputcontexts.pro
@@ -1,9 +1,10 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += gui-private
qtHaveModule(dbus) {
!mac:!win32:SUBDIRS += ibus
}
-contains(QT_CONFIG, xcb-plugin): SUBDIRS += compose
+qtConfig(xcb): SUBDIRS += compose
diff --git a/src/plugins/platforms/android/android.pro b/src/plugins/platforms/android/android.pro
index 045e55ec65..bd3fe5a6cc 100644
--- a/src/plugins/platforms/android/android.pro
+++ b/src/plugins/platforms/android/android.pro
@@ -6,9 +6,10 @@ DEFINES += QT_STATICPLUGIN
LIBS += -ljnigraphics -landroid
-QT += core-private gui-private platformsupport-private
-
-CONFIG += qpa/genericunixfontdatabase
+QT += \
+ core-private gui-private \
+ eventdispatcher_support-private accessibility_support-private \
+ fontdatabase_support-private egl_support-private
OTHER_FILES += $$PWD/android.json
@@ -72,7 +73,7 @@ HEADERS += $$PWD/qandroidplatformintegration.h \
$$PWD/qandroidplatformforeignwindow.h \
$$PWD/qandroideventdispatcher.h
-android-style-assets: SOURCES += $$PWD/extract.cpp
+qtConfig(android-style-assets): SOURCES += $$PWD/extract.cpp
else: SOURCES += $$PWD/extract-dummy.cpp
PLUGIN_TYPE = platforms
diff --git a/src/plugins/platforms/android/androidjniaccessibility.cpp b/src/plugins/platforms/android/androidjniaccessibility.cpp
index e8536235d7..a987092862 100644
--- a/src/plugins/platforms/android/androidjniaccessibility.cpp
+++ b/src/plugins/platforms/android/androidjniaccessibility.cpp
@@ -41,7 +41,7 @@
#include "androidjnimain.h"
#include "qandroidplatformintegration.h"
#include "qpa/qplatformaccessibility.h"
-#include <QtPlatformSupport/private/qaccessiblebridgeutils_p.h>
+#include <QtAccessibilitySupport/private/qaccessiblebridgeutils_p.h>
#include "qguiapplication.h"
#include "qwindow.h"
#include "qrect.h"
diff --git a/src/plugins/platforms/android/androidjniinput.cpp b/src/plugins/platforms/android/androidjniinput.cpp
index 5be128a0c5..5f05ab395e 100644
--- a/src/plugins/platforms/android/androidjniinput.cpp
+++ b/src/plugins/platforms/android/androidjniinput.cpp
@@ -1,7 +1,8 @@
/****************************************************************************
**
** Copyright (C) 2012 BogDan Vatra <bogdan@kde.org>
-** Contact: https://www.qt.io/licensing/
+** Copyright (C) 2016 Olivier Goffart <ogoffart@woboq.com>
+** Contact: http://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
@@ -120,6 +121,12 @@ namespace QtAndroidInput
return m_softwareKeyboardRect;
}
+ void updateHandles(int mode, QPoint cursor, QPoint anchor)
+ {
+ QJNIObjectPrivate::callStaticMethod<void>(applicationClass(), "updateHandles", "(IIIII)V",
+ mode, cursor.x(), cursor.y(), anchor.x(),
+ anchor.y());
+ }
static void mouseDown(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint x, jint y)
{
@@ -168,6 +175,10 @@ namespace QtAndroidInput
static void longPress(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint x, jint y)
{
+ QAndroidInputContext *inputContext = QAndroidInputContext::androidInputContext();
+ if (inputContext && qGuiApp)
+ QMetaObject::invokeMethod(inputContext, "longPress", Q_ARG(int, x), Q_ARG(int, y));
+
//### TODO: add proper API for Qt 5.2
static bool rightMouseFromLongPress = qEnvironmentVariableIntValue("QT_NECESSITAS_COMPATIBILITY_LONG_PRESS");
if (!rightMouseFromLongPress)
@@ -225,6 +236,12 @@ namespace QtAndroidInput
double(dw*size),
double(dh*size));
m_touchPoints.push_back(touchPoint);
+
+ if (state == Qt::TouchPointPressed) {
+ QAndroidInputContext *inputContext = QAndroidInputContext::androidInputContext();
+ if (inputContext && qGuiApp)
+ QMetaObject::invokeMethod(inputContext, "touchDown", Q_ARG(int, x), Q_ARG(int, y));
+ }
}
static void touchEnd(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint /*action*/)
@@ -786,6 +803,18 @@ namespace QtAndroidInput
#endif
}
+ static void handleLocationChanged(JNIEnv */*env*/, jobject /*thiz*/, int id, int x, int y)
+ {
+#ifdef QT_DEBUG_ANDROID_IM_PROTOCOL
+ qDebug() << "@@@ handleLocationChanged" << id << x << y;
+#endif
+ QAndroidInputContext *inputContext = QAndroidInputContext::androidInputContext();
+ if (inputContext && qGuiApp)
+ QMetaObject::invokeMethod(inputContext, "handleLocationChanged",
+ Q_ARG(int, id), Q_ARG(int, x), Q_ARG(int, y));
+
+ }
+
static JNINativeMethod methods[] = {
{"touchBegin","(I)V",(void*)touchBegin},
{"touchAdd","(IIIZIIFF)V",(void*)touchAdd},
@@ -799,7 +828,8 @@ namespace QtAndroidInput
{"keyDown", "(IIIZ)V", (void *)keyDown},
{"keyUp", "(IIIZ)V", (void *)keyUp},
{"keyboardVisibilityChanged", "(Z)V", (void *)keyboardVisibilityChanged},
- {"keyboardGeometryChanged", "(IIII)V", (void *)keyboardGeometryChanged}
+ {"keyboardGeometryChanged", "(IIII)V", (void *)keyboardGeometryChanged},
+ {"handleLocationChanged", "(III)V", (void *)handleLocationChanged}
};
bool registerNatives(JNIEnv *env)
diff --git a/src/plugins/platforms/android/androidjniinput.h b/src/plugins/platforms/android/androidjniinput.h
index 682abde098..af18a96dc1 100644
--- a/src/plugins/platforms/android/androidjniinput.h
+++ b/src/plugins/platforms/android/androidjniinput.h
@@ -39,6 +39,7 @@
#ifndef ANDROIDJNIINPUT_H
#define ANDROIDJNIINPUT_H
+
#include <jni.h>
#include <QtCore/qglobal.h>
#include <QtCore/QRect>
@@ -56,6 +57,9 @@ namespace QtAndroidInput
void updateSelection(int selStart, int selEnd, int candidatesStart, int candidatesEnd);
// Software keyboard support
+ // cursor/selection handles
+ void updateHandles(int handleCount, QPoint cursor = QPoint(), QPoint anchor = QPoint());
+
bool registerNatives(JNIEnv *env);
}
diff --git a/src/plugins/platforms/android/androidjnimain.cpp b/src/plugins/platforms/android/androidjnimain.cpp
index 2614bb52a8..df8883ab34 100644
--- a/src/plugins/platforms/android/androidjnimain.cpp
+++ b/src/plugins/platforms/android/androidjnimain.cpp
@@ -514,7 +514,7 @@ static jboolean startQtApplication(JNIEnv *env, jobject /*object*/, jstring para
if (m_applicationParams.length()) {
// Obtain a handle to the main library (the library that contains the main() function).
// This library should already be loaded, and calling dlopen() will just return a reference to it.
- m_mainLibraryHnd = dlopen(m_applicationParams.first().data(), 0);
+ m_mainLibraryHnd = dlopen(m_applicationParams.constFirst().data(), 0);
if (Q_UNLIKELY(!m_mainLibraryHnd)) {
qCritical() << "dlopen failed:" << dlerror();
return false;
diff --git a/src/plugins/platforms/android/qandroideventdispatcher.h b/src/plugins/platforms/android/qandroideventdispatcher.h
index 227027f3c3..86a7e460b3 100644
--- a/src/plugins/platforms/android/qandroideventdispatcher.h
+++ b/src/plugins/platforms/android/qandroideventdispatcher.h
@@ -42,7 +42,7 @@
#include <QtCore/QMutex>
#include <QtCore/QSemaphore>
-#include <QtPlatformSupport/private/qunixeventdispatcher_qpa_p.h>
+#include <QtEventDispatcherSupport/private/qunixeventdispatcher_qpa_p.h>
class QAndroidEventDispatcher : public QUnixEventDispatcherQPA
{
diff --git a/src/plugins/platforms/android/qandroidinputcontext.cpp b/src/plugins/platforms/android/qandroidinputcontext.cpp
index dc420775cf..2656d45d5f 100644
--- a/src/plugins/platforms/android/qandroidinputcontext.cpp
+++ b/src/plugins/platforms/android/qandroidinputcontext.cpp
@@ -2,6 +2,7 @@
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2012 BogDan Vatra <bogdan@kde.org>
+** Copyright (C) 2016 Olivier Goffart <ogoffart@woboq.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
@@ -342,9 +343,28 @@ static JNINativeMethod methods[] = {
{"updateCursorPosition", "()Z", (void *)updateCursorPosition}
};
+static QRect inputItemRectangle()
+{
+ QRectF itemRect = qGuiApp->inputMethod()->inputItemRectangle();
+ QRect rect = qGuiApp->inputMethod()->inputItemTransform().mapRect(itemRect).toRect();
+ QWindow *window = qGuiApp->focusWindow();
+ if (window)
+ rect = QRect(window->mapToGlobal(rect.topLeft()), rect.size());
+ double pixelDensity = window
+ ? QHighDpiScaling::factor(window)
+ : QHighDpiScaling::factor(QtAndroid::androidPlatformIntegration()->screen());
+ if (pixelDensity != 1.0) {
+ rect.setX(rect.x() * pixelDensity);
+ rect.setY(rect.y() * pixelDensity);
+ rect.setWidth(rect.width() * pixelDensity);
+ rect.setHeight(rect.height() * pixelDensity);
+ }
+ return rect;
+}
QAndroidInputContext::QAndroidInputContext()
- : QPlatformInputContext(), m_composingTextStart(-1), m_blockUpdateSelection(false), m_batchEditNestingLevel(0), m_focusObject(0)
+ : QPlatformInputContext(), m_composingTextStart(-1), m_blockUpdateSelection(false),
+ m_cursorHandleShown(CursorHandleNotShown), m_batchEditNestingLevel(0), m_focusObject(0)
{
jclass clazz = QJNIEnvironmentPrivate::findClass(QtNativeInputConnectionClassName);
if (Q_UNLIKELY(!clazz)) {
@@ -415,6 +435,9 @@ QAndroidInputContext::QAndroidInputContext()
qRegisterMetaType<QInputMethodEvent *>("QInputMethodEvent*");
qRegisterMetaType<QInputMethodQueryEvent *>("QInputMethodQueryEvent*");
m_androidInputContext = this;
+
+ QObject::connect(QGuiApplication::inputMethod(), &QInputMethod::cursorRectangleChanged,
+ this, &QAndroidInputContext::updateSelectionHandles);
}
QAndroidInputContext::~QAndroidInputContext()
@@ -452,6 +475,7 @@ void QAndroidInputContext::reset()
{
clear();
m_batchEditNestingLevel = 0;
+ m_cursorHandleShown = QAndroidInputContext::CursorHandleNotShown;
if (qGuiApp->focusObject()) {
QSharedPointer<QInputMethodQueryEvent> query = focusObjectInputMethodQueryThreadSafe(Qt::ImEnabled);
if (!query.isNull() && query->value(Qt::ImEnabled).toBool()) {
@@ -500,6 +524,119 @@ void QAndroidInputContext::updateCursorPosition()
}
}
+void QAndroidInputContext::updateSelectionHandles()
+{
+ auto im = qGuiApp->inputMethod();
+ if (!m_focusObject || (m_cursorHandleShown == CursorHandleNotShown)) {
+ // Hide the handles
+ QtAndroidInput::updateHandles(0);
+ return;
+ }
+ QWindow *window = qGuiApp->focusWindow();
+ double pixelDensity = window
+ ? QHighDpiScaling::factor(window)
+ : QHighDpiScaling::factor(QtAndroid::androidPlatformIntegration()->screen());
+
+ QInputMethodQueryEvent query(Qt::ImCursorPosition | Qt::ImAnchorPosition | Qt::ImEnabled);
+ QCoreApplication::sendEvent(m_focusObject, &query);
+ int cpos = query.value(Qt::ImCursorPosition).toInt();
+ int anchor = query.value(Qt::ImAnchorPosition).toInt();
+
+ if (cpos == anchor || im->anchorRectangle().isNull()) {
+ if (!query.value(Qt::ImEnabled).toBool()) {
+ QtAndroidInput::updateHandles(0);
+ return;
+ }
+
+ auto curRect = im->cursorRectangle();
+ QPoint cursorPoint(curRect.center().x(), curRect.bottom());
+ QPoint editMenuPoint(curRect.center().x(), curRect.top());
+ QtAndroidInput::updateHandles(m_cursorHandleShown, cursorPoint * pixelDensity,
+ editMenuPoint * pixelDensity);
+ return;
+ }
+
+ auto leftRect = im->cursorRectangle();
+ auto rightRect = im->anchorRectangle();
+ if (cpos > anchor)
+ std::swap(leftRect, rightRect);
+
+ QPoint leftPoint(leftRect.bottomLeft().toPoint() * pixelDensity);
+ QPoint righPoint(rightRect.bottomRight().toPoint() * pixelDensity);
+ QtAndroidInput::updateHandles(CursorHandleShowSelection, leftPoint, righPoint);
+
+ if (m_cursorHandleShown == CursorHandleShowPopup) {
+ // make sure the popup does not reappear when the selection menu closes
+ m_cursorHandleShown = QAndroidInputContext::CursorHandleNotShown;
+ }
+}
+
+/*
+ Called from Java when a cursor/selection handle was dragged to a new position
+
+ handleId of 1 means the cursor handle, 2 means the left handle, 3 means the right handle
+ */
+void QAndroidInputContext::handleLocationChanged(int handleId, int x, int y)
+{
+ auto im = qGuiApp->inputMethod();
+ auto leftRect = im->cursorRectangle();
+ // The handle is down of the cursor, but we want the position in the middle.
+ QWindow *window = qGuiApp->focusWindow();
+ double pixelDensity = window
+ ? QHighDpiScaling::factor(window)
+ : QHighDpiScaling::factor(QtAndroid::androidPlatformIntegration()->screen());
+ QPoint point(x / pixelDensity, y / pixelDensity);
+ y -= leftRect.width() / 2;
+ if (handleId == 1) {
+ setSelectionOnFocusObject(point, point);
+ return;
+ }
+
+ QInputMethodQueryEvent query(Qt::ImCursorPosition | Qt::ImAnchorPosition);
+ QCoreApplication::sendEvent(m_focusObject, &query);
+ int cpos = query.value(Qt::ImCursorPosition).toInt();
+ int anchor = query.value(Qt::ImAnchorPosition).toInt();
+
+ auto rightRect = im->anchorRectangle();
+ if (cpos > anchor)
+ std::swap(leftRect, rightRect);
+
+ if (handleId == 2) {
+ QPoint rightPoint(rightRect.center().toPoint());
+ setSelectionOnFocusObject(point, rightPoint);
+ } else if (handleId == 3) {
+ QPoint leftPoint(leftRect.center().toPoint());
+ setSelectionOnFocusObject(leftPoint, point);
+ }
+}
+
+void QAndroidInputContext::touchDown(int x, int y)
+{
+ if (m_focusObject && inputItemRectangle().contains(x, y) && !m_cursorHandleShown) {
+ // If the user touch the input rectangle, we can show the cursor handle
+ m_cursorHandleShown = QAndroidInputContext::CursorHandleShowNormal;
+ updateSelectionHandles();
+ }
+}
+
+void QAndroidInputContext::longPress(int x, int y)
+{
+ if (m_focusObject && inputItemRectangle().contains(x, y)) {
+ // Show the paste menu if there is something to paste.
+ m_cursorHandleShown = QAndroidInputContext::CursorHandleShowPopup;
+ updateSelectionHandles();
+ }
+}
+
+void QAndroidInputContext::keyDown()
+{
+ if (m_cursorHandleShown) {
+ // When the user enter text on the keyboard, we hide the cursor handle
+ m_cursorHandleShown = QAndroidInputContext::CursorHandleNotShown;
+ updateSelectionHandles();
+ }
+}
+
void QAndroidInputContext::update(Qt::InputMethodQueries queries)
{
QSharedPointer<QInputMethodQueryEvent> query = focusObjectInputMethodQueryThreadSafe(queries);
@@ -543,22 +680,11 @@ void QAndroidInputContext::showInputPanel()
m_updateCursorPosConnection = connect(qGuiApp->focusObject(), SIGNAL(cursorPositionChanged(int,int)), this, SLOT(updateCursorPosition()));
else
m_updateCursorPosConnection = connect(qGuiApp->focusObject(), SIGNAL(cursorPositionChanged()), this, SLOT(updateCursorPosition()));
- QRectF itemRect = qGuiApp->inputMethod()->inputItemRectangle();
- QRect rect = qGuiApp->inputMethod()->inputItemTransform().mapRect(itemRect).toRect();
- QWindow *window = qGuiApp->focusWindow();
- if (window)
- rect = QRect(window->mapToGlobal(rect.topLeft()), rect.size());
-
- double pixelDensity = window ? QHighDpiScaling::factor(window)
- : QHighDpiScaling::factor(QtAndroid::androidPlatformIntegration()->screen());
- QtAndroidInput::showSoftwareKeyboard(rect.left() * pixelDensity,
- rect.top() * pixelDensity,
- rect.width() * pixelDensity,
- rect.height() * pixelDensity,
+ QRect rect = inputItemRectangle();
+ QtAndroidInput::showSoftwareKeyboard(rect.left(), rect.top(), rect.width(), rect.height(),
query->value(Qt::ImHints).toUInt(),
- query->value(Qt::ImEnterKeyType).toUInt()
- );
+ query->value(Qt::ImEnterKeyType).toUInt());
}
void QAndroidInputContext::showInputPanelLater(Qt::ApplicationState state)
@@ -601,6 +727,7 @@ void QAndroidInputContext::setFocusObject(QObject *object)
reset();
}
QPlatformInputContext::setFocusObject(object);
+ updateSelectionHandles();
}
jboolean QAndroidInputContext::beginBatchEdit()
@@ -645,7 +772,7 @@ jboolean QAndroidInputContext::commitText(const QString &text, jint newCursorPos
: localPos - text.length() + newCursorPosition;
//move the cursor
attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Selection,
- newLocalPos, 0, QVariant()));
+ newLocalPos, 0));
}
}
m_blockUpdateSelection = updateSelectionWasBlocked;
@@ -691,7 +818,7 @@ jboolean QAndroidInputContext::finishComposingText()
// Moving Qt's cursor to where the preedit cursor used to be
QList<QInputMethodEvent::Attribute> attributes;
- attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Selection, localCursorPos, 0, QVariant()));
+ attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Selection, localCursorPos, 0));
QInputMethodEvent event(QString(), attributes);
event.setCommitString(m_composingText);
@@ -739,7 +866,7 @@ const QAndroidInputContext::ExtractedText &QAndroidInputContext::getExtractedTex
if (composeLength > 0) {
//Qt doesn't give us the preedit text, so we have to insert it at the correct position
int localComposePos = m_composingTextStart - blockPos;
- blockText = blockText.left(localComposePos) + m_composingText + blockText.mid(localComposePos);
+ blockText = blockText.leftRef(localComposePos) + m_composingText + blockText.midRef(localComposePos);
}
int cpos = localPos + composeLength; //actual cursor pos relative to the current block
@@ -803,9 +930,8 @@ QString QAndroidInputContext::getTextAfterCursor(jint length, jint /*flags*/)
QString QAndroidInputContext::getTextBeforeCursor(jint length, jint /*flags*/)
{
QVariant textBefore = queryFocusObjectThreadSafe(Qt::ImTextBeforeCursor, QVariant(length));
- if (textBefore.isValid()) {
- return textBefore.toString().right(length) + m_composingText;
- }
+ if (textBefore.isValid())
+ return textBefore.toString().rightRef(length) + m_composingText;
//compatibility code for old controls that do not implement the new API
QSharedPointer<QInputMethodQueryEvent> query = focusObjectInputMethodQueryThreadSafe();
@@ -819,9 +945,9 @@ QString QAndroidInputContext::getTextBeforeCursor(jint length, jint /*flags*/)
//### the preedit text does not need to be immediately before the cursor
if (cursorPos <= length)
- return text.left(cursorPos) + m_composingText;
+ return text.leftRef(cursorPos) + m_composingText;
else
- return text.mid(cursorPos - length, length) + m_composingText;
+ return text.midRef(cursorPos - length, length) + m_composingText;
}
/*
@@ -848,8 +974,7 @@ jboolean QAndroidInputContext::setComposingText(const QString &text, jint newCur
QList<QInputMethodEvent::Attribute> attributes;
attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor,
newCursorPosition,
- 1,
- QVariant()));
+ 1));
// Show compose text underlined
QTextCharFormat underlined;
underlined.setFontUnderline(true);
@@ -859,6 +984,8 @@ jboolean QAndroidInputContext::setComposingText(const QString &text, jint newCur
QInputMethodEvent event(m_composingText, attributes);
sendInputMethodEventThreadSafe(&event);
+ QMetaObject::invokeMethod(this, "keyDown");
+
updateCursorPosition();
return JNI_TRUE;
@@ -921,7 +1048,7 @@ jboolean QAndroidInputContext::setComposingRegion(jint start, jint end)
QVariant(underlined)));
// Keep the cursor position unchanged (don't move to end of preedit)
- attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, currentCursor - start, 1, QVariant()));
+ attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, currentCursor - start, 1));
QInputMethodEvent event(m_composingText, attributes);
event.setCommitString(QString(), relativeStart, length);
@@ -955,7 +1082,7 @@ jboolean QAndroidInputContext::setSelection(jint start, jint end)
// preedit cursor
int localOldPos = query->value(Qt::ImCursorPosition).toInt();
int pos = localCursorPos - localOldPos;
- attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, pos, 1, QVariant()));
+ attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, pos, 1));
//but we have to tell Qt about the compose text all over again
@@ -970,8 +1097,7 @@ jboolean QAndroidInputContext::setSelection(jint start, jint end)
// actually changing the selection
attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Selection,
localCursorPos,
- end - start,
- QVariant()));
+ end - start));
}
QInputMethodEvent event(m_composingText, attributes);
sendInputMethodEventThreadSafe(&event);
@@ -981,20 +1107,21 @@ jboolean QAndroidInputContext::setSelection(jint start, jint end)
jboolean QAndroidInputContext::selectAll()
{
-#warning TODO
- return JNI_FALSE;
+ sendShortcut(QKeySequence::SelectAll);
+ return JNI_TRUE;
}
jboolean QAndroidInputContext::cut()
{
-#warning TODO
- return JNI_FALSE;
+ m_cursorHandleShown = CursorHandleNotShown;
+ sendShortcut(QKeySequence::Cut);
+ return JNI_TRUE;
}
jboolean QAndroidInputContext::copy()
{
-#warning TODO
- return JNI_FALSE;
+ sendShortcut(QKeySequence::Copy);
+ return JNI_TRUE;
}
jboolean QAndroidInputContext::copyURL()
@@ -1005,10 +1132,21 @@ jboolean QAndroidInputContext::copyURL()
jboolean QAndroidInputContext::paste()
{
-#warning TODO
- return JNI_FALSE;
+ m_cursorHandleShown = CursorHandleNotShown;
+ sendShortcut(QKeySequence::Paste);
+ return JNI_TRUE;
}
+void QAndroidInputContext::sendShortcut(const QKeySequence &sequence)
+{
+ for (int i = 0; i < sequence.count(); ++i) {
+ const int keys = sequence[i];
+ Qt::Key key = Qt::Key(keys & ~Qt::KeyboardModifierMask);
+ Qt::KeyboardModifiers mod = Qt::KeyboardModifiers(keys & Qt::KeyboardModifierMask);
+ QGuiApplication::postEvent(m_focusObject, new QKeyEvent(QEvent::KeyPress, key, mod));
+ QGuiApplication::postEvent(m_focusObject, new QKeyEvent(QEvent::KeyRelease, key, mod));
+ }
+}
Q_INVOKABLE QVariant QAndroidInputContext::queryFocusObjectUnsafe(Qt::InputMethodQuery query, QVariant argument)
{
diff --git a/src/plugins/platforms/android/qandroidinputcontext.h b/src/plugins/platforms/android/qandroidinputcontext.h
index 5ab85dcab0..8a33ff71cc 100644
--- a/src/plugins/platforms/android/qandroidinputcontext.h
+++ b/src/plugins/platforms/android/qandroidinputcontext.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2012 BogDan Vatra <bogdan@kde.org>
+** Copyright (C) 2016 Olivier Goffart <ogoffart@woboq.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
@@ -94,6 +95,7 @@ public:
bool isComposing() const;
void clear();
void setFocusObject(QObject *object);
+ void sendShortcut(const QKeySequence &);
//---------------//
jboolean beginBatchEdit();
@@ -117,6 +119,11 @@ public:
public slots:
void updateCursorPosition();
+ void updateSelectionHandles();
+ void handleLocationChanged(int handleId, int x, int y);
+ void touchDown(int x, int y);
+ void longPress(int x, int y);
+ void keyDown();
private slots:
void showInputPanelLater(Qt::ApplicationState);
@@ -138,6 +145,13 @@ private:
int m_composingCursor;
QMetaObject::Connection m_updateCursorPosConnection;
bool m_blockUpdateSelection;
+ enum CursorHandleShowMode {
+ CursorHandleNotShown,
+ CursorHandleShowNormal = 1,
+ CursorHandleShowSelection = 2,
+ CursorHandleShowPopup = 3
+ };
+ CursorHandleShowMode m_cursorHandleShown;
int m_batchEditNestingLevel;
QObject *m_focusObject;
};
diff --git a/src/plugins/platforms/android/qandroidplatformfontdatabase.h b/src/plugins/platforms/android/qandroidplatformfontdatabase.h
index a00a3730fb..b20fd75cb2 100644
--- a/src/plugins/platforms/android/qandroidplatformfontdatabase.h
+++ b/src/plugins/platforms/android/qandroidplatformfontdatabase.h
@@ -40,7 +40,7 @@
#ifndef QANDROIDPLATFORMFONTDATABASE_H
#define QANDROIDPLATFORMFONTDATABASE_H
-#include <QtPlatformSupport/private/qbasicfontdatabase_p.h>
+#include <QtFontDatabaseSupport/private/qbasicfontdatabase_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/android/qandroidplatformintegration.cpp b/src/plugins/platforms/android/qandroidplatformintegration.cpp
index 80d7e31aa3..6669ee3176 100644
--- a/src/plugins/platforms/android/qandroidplatformintegration.cpp
+++ b/src/plugins/platforms/android/qandroidplatformintegration.cpp
@@ -46,7 +46,7 @@
#include <QThread>
#include <QOffscreenSurface>
-#include <QtPlatformSupport/private/qeglpbuffer_p.h>
+#include <QtEglSupport/private/qeglpbuffer_p.h>
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qplatformwindow.h>
#include <qpa/qplatformoffscreensurface.h>
@@ -80,6 +80,8 @@ Qt::ScreenOrientation QAndroidPlatformIntegration::m_nativeOrientation = Qt::Pri
Qt::ApplicationState QAndroidPlatformIntegration::m_defaultApplicationState = Qt::ApplicationActive;
+bool QAndroidPlatformIntegration::m_showPasswordEnabled = false;
+
void *QAndroidPlatformNativeInterface::nativeResourceForIntegration(const QByteArray &resource)
{
if (resource=="JavaVM")
@@ -191,6 +193,19 @@ QAndroidPlatformIntegration::QAndroidPlatformIntegration(const QStringList &para
}
QWindowSystemInterface::registerTouchDevice(m_touchDevice);
}
+
+ auto contentResolver = javaActivity.callObjectMethod("getContentResolver", "()Landroid/content/ContentResolver;");
+ Q_ASSERT(contentResolver.isValid());
+ QJNIObjectPrivate txtShowPassValue = QJNIObjectPrivate::callStaticObjectMethod("android/provider/Settings$System",
+ "getString",
+ "(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;",
+ contentResolver.object(),
+ QJNIObjectPrivate::getStaticObjectField("android/provider/Settings$System", "TEXT_SHOW_PASSWORD", "Ljava/lang/String;").object());
+ if (txtShowPassValue.isValid()) {
+ bool ok = false;
+ const int txtShowPass = txtShowPassValue.toString().toInt(&ok);
+ m_showPasswordEnabled = ok ? (txtShowPass == 1) : false;
+ }
}
QGuiApplicationPrivate::instance()->setApplicationState(m_defaultApplicationState);
@@ -313,6 +328,9 @@ QPlatformServices *QAndroidPlatformIntegration::services() const
QVariant QAndroidPlatformIntegration::styleHint(StyleHint hint) const
{
switch (hint) {
+ case PasswordMaskDelay:
+ // this number is from a hard-coded value in Android code (cf. PasswordTransformationMethod)
+ return m_showPasswordEnabled ? 1500 : 0;
case ShowIsMaximized:
return true;
default:
diff --git a/src/plugins/platforms/android/qandroidplatformintegration.h b/src/plugins/platforms/android/qandroidplatformintegration.h
index 1f06c23d0b..bda0bee9ad 100644
--- a/src/plugins/platforms/android/qandroidplatformintegration.h
+++ b/src/plugins/platforms/android/qandroidplatformintegration.h
@@ -143,6 +143,8 @@ private:
static Qt::ApplicationState m_defaultApplicationState;
+ static bool m_showPasswordEnabled;
+
QPlatformFontDatabase *m_androidFDB;
QAndroidPlatformNativeInterface *m_androidPlatformNativeInterface;
QAndroidPlatformServices *m_androidPlatformServices;
diff --git a/src/plugins/platforms/android/qandroidplatformopenglcontext.cpp b/src/plugins/platforms/android/qandroidplatformopenglcontext.cpp
index 80693acf88..2644fa27f6 100644
--- a/src/plugins/platforms/android/qandroidplatformopenglcontext.cpp
+++ b/src/plugins/platforms/android/qandroidplatformopenglcontext.cpp
@@ -42,7 +42,7 @@
#include "qandroidplatformopenglwindow.h"
#include "qandroidplatformintegration.h"
-#include <QtPlatformSupport/private/qeglpbuffer_p.h>
+#include <QtEglSupport/private/qeglpbuffer_p.h>
#include <QSurface>
#include <QtGui/private/qopenglcontext_p.h>
diff --git a/src/plugins/platforms/android/qandroidplatformopenglcontext.h b/src/plugins/platforms/android/qandroidplatformopenglcontext.h
index c88dbf327b..d3f6cf13a4 100644
--- a/src/plugins/platforms/android/qandroidplatformopenglcontext.h
+++ b/src/plugins/platforms/android/qandroidplatformopenglcontext.h
@@ -41,7 +41,7 @@
#ifndef QANDROIDPLATFORMOPENGLCONTEXT_H
#define QANDROIDPLATFORMOPENGLCONTEXT_H
-#include <QtPlatformSupport/private/qeglplatformcontext_p.h>
+#include <QtEglSupport/private/qeglplatformcontext_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/android/qandroidplatformopenglwindow.cpp b/src/plugins/platforms/android/qandroidplatformopenglwindow.cpp
index 7801629633..3e1cfe305d 100644
--- a/src/plugins/platforms/android/qandroidplatformopenglwindow.cpp
+++ b/src/plugins/platforms/android/qandroidplatformopenglwindow.cpp
@@ -50,7 +50,7 @@
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qplatformscreen.h>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
diff --git a/src/plugins/platforms/android/qandroidplatformscreen.cpp b/src/plugins/platforms/android/qandroidplatformscreen.cpp
index a73550606b..155d6bfb8d 100644
--- a/src/plugins/platforms/android/qandroidplatformscreen.cpp
+++ b/src/plugins/platforms/android/qandroidplatformscreen.cpp
@@ -379,9 +379,8 @@ void QAndroidPlatformScreen::doRedraw()
}
}
- foreach (const QRect &rect, visibleRegion.rects()) {
+ for (const QRect &rect : visibleRegion)
compositePainter.fillRect(rect, QColor(Qt::transparent));
- }
ret = ANativeWindow_unlockAndPost(m_nativeSurface);
if (ret >= 0)
diff --git a/src/plugins/platforms/android/qandroidplatformtheme.cpp b/src/plugins/platforms/android/qandroidplatformtheme.cpp
index 6cabdd8b3c..b891407c44 100644
--- a/src/plugins/platforms/android/qandroidplatformtheme.cpp
+++ b/src/plugins/platforms/android/qandroidplatformtheme.cpp
@@ -486,7 +486,7 @@ QVariant QAndroidPlatformTheme::themeHint(ThemeHint hint) const
if (ret > 0)
return ret;
- // fall through
+ Q_FALLTHROUGH();
}
default:
return QPlatformTheme::themeHint(hint);
diff --git a/src/plugins/platforms/bsdfb/bsdfb.json b/src/plugins/platforms/bsdfb/bsdfb.json
new file mode 100644
index 0000000000..97b3e7707e
--- /dev/null
+++ b/src/plugins/platforms/bsdfb/bsdfb.json
@@ -0,0 +1,3 @@
+{
+ "Keys": [ "bsdfb" ]
+}
diff --git a/src/plugins/platforms/bsdfb/bsdfb.pro b/src/plugins/platforms/bsdfb/bsdfb.pro
new file mode 100644
index 0000000000..770145a8ff
--- /dev/null
+++ b/src/plugins/platforms/bsdfb/bsdfb.pro
@@ -0,0 +1,19 @@
+TARGET = qbsdfb
+
+QT += \
+ core-private gui-private \
+ service_support-private eventdispatcher_support-private \
+ fontdatabase_support-private fb_support-private
+
+qtHaveModule(input_support-private): \
+ QT += input_support-private
+
+SOURCES = main.cpp qbsdfbintegration.cpp qbsdfbscreen.cpp
+HEADERS = qbsdfbintegration.h qbsdfbscreen.h
+
+OTHER_FILES += bsdfb.json
+
+PLUGIN_TYPE = platforms
+PLUGIN_CLASS_NAME = QBsdFbIntegrationPlugin
+!equals(TARGET, $$QT_DEFAULT_QPA_PLUGIN): PLUGIN_EXTENDS = -
+load(qt_plugin)
diff --git a/src/plugins/platforms/bsdfb/main.cpp b/src/plugins/platforms/bsdfb/main.cpp
new file mode 100644
index 0000000000..f4ab3dee39
--- /dev/null
+++ b/src/plugins/platforms/bsdfb/main.cpp
@@ -0,0 +1,60 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <qpa/qplatformintegrationplugin.h>
+#include "qbsdfbintegration.h"
+
+QT_BEGIN_NAMESPACE
+
+class QBsdFbIntegrationPlugin : public QPlatformIntegrationPlugin
+{
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID QPlatformIntegrationFactoryInterface_iid FILE "bsdfb.json")
+public:
+ QPlatformIntegration *create(const QString&, const QStringList&) override;
+};
+
+QPlatformIntegration* QBsdFbIntegrationPlugin::create(const QString& system, const QStringList& paramList)
+{
+ Q_UNUSED(paramList);
+ if (!system.compare(QLatin1String("bsdfb"), Qt::CaseInsensitive))
+ return new QBsdFbIntegration(paramList);
+
+ return nullptr;
+}
+
+QT_END_NAMESPACE
+
+#include "main.moc"
+
diff --git a/src/plugins/platforms/bsdfb/qbsdfbintegration.cpp b/src/plugins/platforms/bsdfb/qbsdfbintegration.cpp
new file mode 100644
index 0000000000..1fa13183f8
--- /dev/null
+++ b/src/plugins/platforms/bsdfb/qbsdfbintegration.cpp
@@ -0,0 +1,142 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qbsdfbintegration.h"
+#include "qbsdfbscreen.h"
+
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtServiceSupport/private/qgenericunixservices_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
+
+#include <QtFbSupport/private/qfbvthandler_p.h>
+#include <QtFbSupport/private/qfbbackingstore_p.h>
+#include <QtFbSupport/private/qfbwindow_p.h>
+#include <QtFbSupport/private/qfbcursor_p.h>
+
+#include <QtGui/private/qguiapplication_p.h>
+#include <qpa/qplatforminputcontext.h>
+#include <qpa/qplatforminputcontextfactory_p.h>
+
+#if QT_CONFIG(tslib)
+#include <QtInputSupport/private/qtslib_p.h>
+#endif
+
+QT_BEGIN_NAMESPACE
+
+QBsdFbIntegration::QBsdFbIntegration(const QStringList &paramList)
+{
+ m_fontDb.reset(new QGenericUnixFontDatabase);
+ m_services.reset(new QGenericUnixServices);
+ m_primaryScreen.reset(new QBsdFbScreen(paramList));
+}
+
+QBsdFbIntegration::~QBsdFbIntegration()
+{
+ destroyScreen(m_primaryScreen.take());
+}
+
+void QBsdFbIntegration::initialize()
+{
+ if (m_primaryScreen->initialize())
+ screenAdded(m_primaryScreen.data());
+ else
+ qWarning("bsdfb: Failed to initialize screen");
+
+ m_inputContext.reset(QPlatformInputContextFactory::create());
+ m_nativeInterface.reset(new QPlatformNativeInterface);
+ m_vtHandler.reset(new QFbVtHandler);
+
+ if (!qEnvironmentVariableIntValue("QT_QPA_FB_DISABLE_INPUT"))
+ createInputHandlers();
+}
+
+bool QBsdFbIntegration::hasCapability(QPlatformIntegration::Capability cap) const
+{
+ switch (cap) {
+ case ThreadedPixmaps:
+ return true;
+ case WindowManagement:
+ return false;
+ default:
+ return QPlatformIntegration::hasCapability(cap);
+ }
+}
+
+QPlatformBackingStore *QBsdFbIntegration::createPlatformBackingStore(QWindow *window) const
+{
+ return new QFbBackingStore(window);
+}
+
+QPlatformWindow *QBsdFbIntegration::createPlatformWindow(QWindow *window) const
+{
+ return new QFbWindow(window);
+}
+
+QAbstractEventDispatcher *QBsdFbIntegration::createEventDispatcher() const
+{
+ return createUnixEventDispatcher();
+}
+
+QList<QPlatformScreen *> QBsdFbIntegration::screens() const
+{
+ QList<QPlatformScreen *> list;
+ list.append(m_primaryScreen.data());
+ return list;
+}
+
+QPlatformFontDatabase *QBsdFbIntegration::fontDatabase() const
+{
+ return m_fontDb.data();
+}
+
+QPlatformServices *QBsdFbIntegration::services() const
+{
+ return m_services.data();
+}
+
+void QBsdFbIntegration::createInputHandlers()
+{
+#if QT_CONFIG(tslib)
+ const bool useTslib = qEnvironmentVariableIntValue("QT_QPA_FB_TSLIB");
+ if (useTslib)
+ new QTsLibMouseHandler(QLatin1String("TsLib"), QString());
+#endif
+}
+
+QPlatformNativeInterface *QBsdFbIntegration::nativeInterface() const
+{
+ return m_nativeInterface.data();
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/bsdfb/qbsdfbintegration.h b/src/plugins/platforms/bsdfb/qbsdfbintegration.h
new file mode 100644
index 0000000000..2be5ea260d
--- /dev/null
+++ b/src/plugins/platforms/bsdfb/qbsdfbintegration.h
@@ -0,0 +1,81 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QBSDFBINTEGRATION_H
+#define QBSDFBINTEGRATION_H
+
+#include <qpa/qplatformintegration.h>
+#include <qpa/qplatformnativeinterface.h>
+
+QT_BEGIN_NAMESPACE
+
+class QAbstractEventDispatcher;
+class QBsdFbScreen;
+class QFbVtHandler;
+
+class QBsdFbIntegration : public QPlatformIntegration, public QPlatformNativeInterface
+{
+public:
+ explicit QBsdFbIntegration(const QStringList &paramList);
+ ~QBsdFbIntegration() override;
+
+ void initialize() override;
+ bool hasCapability(QPlatformIntegration::Capability cap) const override;
+
+ QPlatformWindow *createPlatformWindow(QWindow *window) const override;
+ QPlatformBackingStore *createPlatformBackingStore(QWindow *window) const override;
+
+ QAbstractEventDispatcher *createEventDispatcher() const override;
+
+ QPlatformFontDatabase *fontDatabase() const override;
+ QPlatformServices *services() const override;
+ QPlatformInputContext *inputContext() const override { return m_inputContext.data(); }
+
+ QPlatformNativeInterface *nativeInterface() const override;
+
+ QList<QPlatformScreen *> screens() const;
+
+private:
+ void createInputHandlers();
+
+ QScopedPointer<QBsdFbScreen> m_primaryScreen;
+ QScopedPointer<QPlatformInputContext> m_inputContext;
+ QScopedPointer<QPlatformFontDatabase> m_fontDb;
+ QScopedPointer<QPlatformServices> m_services;
+ QScopedPointer<QFbVtHandler> m_vtHandler;
+ QScopedPointer<QPlatformNativeInterface> m_nativeInterface;
+};
+
+QT_END_NAMESPACE
+
+#endif // QBSDFBINTEGRATION_H
diff --git a/src/plugins/platforms/bsdfb/qbsdfbscreen.cpp b/src/plugins/platforms/bsdfb/qbsdfbscreen.cpp
new file mode 100644
index 0000000000..0ef57d37e5
--- /dev/null
+++ b/src/plugins/platforms/bsdfb/qbsdfbscreen.cpp
@@ -0,0 +1,276 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qbsdfbscreen.h"
+#include <QtFbSupport/private/qfbcursor_p.h>
+#include <QtFbSupport/private/qfbwindow_p.h>
+#include <QtCore/QRegularExpression>
+#include <QtGui/QPainter>
+
+#include <private/qcore_unix_p.h> // overrides QT_OPEN
+#include <qimage.h>
+#include <qdebug.h>
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <stdio.h>
+#include <limits.h>
+#include <signal.h>
+
+#include <sys/consio.h>
+#include <sys/fbio.h>
+
+QT_BEGIN_NAMESPACE
+
+enum {
+ DefaultDPI = 100
+};
+
+static int openFramebufferDevice(const QString &dev)
+{
+ const QByteArray devPath = QFile::encodeName(dev);
+
+ int fd = QT_OPEN(devPath.constData(), O_RDWR);
+
+ if (fd == -1)
+ fd = QT_OPEN(devPath.constData(), O_RDONLY);
+
+ return fd;
+}
+
+static QRect determineGeometry(const struct fbtype &fb, const QRect &userGeometry)
+{
+ int xoff = 0;
+ int yoff = 0;
+ int w = 0;
+ int h = 0;
+
+ if (userGeometry.isValid()) {
+ w = qMin(userGeometry.width(), fb.fb_width);
+ h = qMin(userGeometry.height(), fb.fb_height);
+
+ int xxoff = userGeometry.x(), yyoff = userGeometry.y();
+ if (xxoff != 0 || yyoff != 0) {
+ if (xxoff < 0 || xxoff + w > fb.fb_width)
+ xxoff = fb.fb_width - w;
+ if (yyoff < 0 || yyoff + h > fb.fb_height)
+ yyoff = fb.fb_height - h;
+ xoff += xxoff;
+ yoff += yyoff;
+ } else {
+ xoff += (fb.fb_width - w)/2;
+ yoff += (fb.fb_height - h)/2;
+ }
+ } else {
+ w = fb.fb_width;
+ h = fb.fb_height;
+ }
+
+ if (w == 0 || h == 0) {
+ qWarning("Unable to find screen geometry, using 320x240");
+ w = 320;
+ h = 240;
+ }
+
+ return QRect(xoff, yoff, w, h);
+}
+
+static QSizeF determinePhysicalSize(const QSize &mmSize, const QSize &res)
+{
+ int mmWidth = mmSize.width();
+ int mmHeight = mmSize.height();
+
+ if (mmWidth <= 0 && mmHeight <= 0) {
+ const int dpi = DefaultDPI;
+ mmWidth = qRound(res.width() * 25.4 / dpi);
+ mmHeight = qRound(res.height() * 25.4 / dpi);
+ } else if (mmWidth > 0 && mmHeight <= 0) {
+ mmHeight = res.height() * mmWidth/res.width();
+ } else if (mmHeight > 0 && mmWidth <= 0) {
+ mmWidth = res.width() * mmHeight/res.height();
+ }
+
+ return QSize(mmWidth, mmHeight);
+}
+
+QBsdFbScreen::QBsdFbScreen(const QStringList &args)
+ : m_arguments(args)
+{
+}
+
+QBsdFbScreen::~QBsdFbScreen()
+{
+ if (m_framebufferFd != -1) {
+ munmap(m_mmap.data - m_mmap.offset, m_mmap.size);
+ qt_safe_close(m_framebufferFd);
+ }
+}
+
+bool QBsdFbScreen::initialize()
+{
+ QRegularExpression fbRx(QLatin1String("fb=(.*)"));
+ QRegularExpression mmSizeRx(QLatin1String("mmsize=(\\d+)x(\\d+)"));
+ QRegularExpression sizeRx(QLatin1String("size=(\\d+)x(\\d+)"));
+ QRegularExpression offsetRx(QLatin1String("offset=(\\d+)x(\\d+)"));
+
+ QString fbDevice;
+ QSize userMmSize;
+ QRect userGeometry;
+
+ // Parse arguments
+ for (const QString &arg : qAsConst(m_arguments)) {
+ QRegularExpressionMatch match;
+ if (arg.contains(mmSizeRx, &match))
+ userMmSize = QSize(match.captured(1).toInt(), match.captured(2).toInt());
+ else if (arg.contains(sizeRx, &match))
+ userGeometry.setSize(QSize(match.captured(1).toInt(), match.captured(2).toInt()));
+ else if (arg.contains(offsetRx, &match))
+ userGeometry.setTopLeft(QPoint(match.captured(1).toInt(), match.captured(2).toInt()));
+ else if (arg.contains(fbRx, &match))
+ fbDevice = match.captured(1);
+ }
+
+ if (!fbDevice.isEmpty()) {
+ // Open the device
+ m_framebufferFd = openFramebufferDevice(fbDevice);
+ } else {
+ m_framebufferFd = STDIN_FILENO;
+ }
+
+ if (m_framebufferFd == -1) {
+ qErrnoWarning(errno, "Failed to open framebuffer %s", qPrintable(fbDevice));
+ return false;
+ }
+
+ struct fbtype fb;
+ if (ioctl(m_framebufferFd, FBIOGTYPE, &fb) != 0) {
+ qErrnoWarning(errno, "Error reading framebuffer information");
+ return false;
+ }
+
+ int line_length = 0;
+ if (ioctl(m_framebufferFd, FBIO_GETLINEWIDTH, &line_length) != 0) {
+ qErrnoWarning(errno, "Error reading line length information");
+ return false;
+ }
+
+ mDepth = fb.fb_depth;
+
+ m_bytesPerLine = line_length;
+ const QRect geometry = determineGeometry(fb, userGeometry);
+ mGeometry = QRect(QPoint(0, 0), geometry.size());
+ switch (mDepth) {
+ case 32:
+ mFormat = QImage::Format_RGB32;
+ break;
+ case 24:
+ mFormat = QImage::Format_RGB888;
+ break;
+ case 16:
+ // falling back
+ default:
+ mFormat = QImage::Format_RGB16;
+ break;
+ }
+ mPhysicalSize = determinePhysicalSize(userMmSize, geometry.size());
+
+ // mmap the framebuffer
+ const size_t pagemask = getpagesize() - 1;
+ m_mmap.size = (m_bytesPerLine * fb.fb_height + pagemask) & ~pagemask;
+ uchar *data = static_cast<uchar*>(mmap(nullptr, m_mmap.size, PROT_READ | PROT_WRITE, MAP_SHARED, m_framebufferFd, 0));
+ if (data == MAP_FAILED) {
+ qErrnoWarning(errno, "Failed to mmap framebuffer");
+ return false;
+ }
+
+ m_mmap.offset = geometry.y() * m_bytesPerLine + geometry.x() * mDepth / 8;
+ m_mmap.data = data + m_mmap.offset;
+
+ QFbScreen::initializeCompositor();
+ m_onscreenImage = QImage(m_mmap.data, geometry.width(), geometry.height(), m_bytesPerLine, mFormat);
+
+ mCursor = new QFbCursor(this);
+
+ return true;
+}
+
+QRegion QBsdFbScreen::doRedraw()
+{
+ const QRegion touched = QFbScreen::doRedraw();
+
+ if (touched.isEmpty())
+ return touched;
+
+ if (!m_blitter)
+ m_blitter.reset(new QPainter(&m_onscreenImage));
+
+ const auto rects = touched.rects();
+ for (const QRect &rect : rects)
+ m_blitter->drawImage(rect, *mScreenImage, rect);
+ return touched;
+}
+
+// grabWindow() grabs "from the screen" not from the backingstores.
+QPixmap QBsdFbScreen::grabWindow(WId wid, int x, int y, int width, int height) const
+{
+ if (!wid) {
+ if (width < 0)
+ width = m_onscreenImage.width() - x;
+ if (height < 0)
+ height = m_onscreenImage.height() - y;
+ return QPixmap::fromImage(m_onscreenImage).copy(x, y, width, height);
+ }
+
+ const QFbWindow *window = windowForId(wid);
+ if (window) {
+ const QRect geom = window->geometry();
+ if (width < 0)
+ width = geom.width() - x;
+ if (height < 0)
+ height = geom.height() - y;
+ QRect rect(geom.topLeft() + QPoint(x, y), QSize(width, height));
+ rect &= window->geometry();
+ return QPixmap::fromImage(m_onscreenImage).copy(rect);
+ }
+
+ return QPixmap();
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/bsdfb/qbsdfbscreen.h b/src/plugins/platforms/bsdfb/qbsdfbscreen.h
new file mode 100644
index 0000000000..3e244e3460
--- /dev/null
+++ b/src/plugins/platforms/bsdfb/qbsdfbscreen.h
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QBSDFBSCREEN_H
+#define QBSDFBSCREEN_H
+
+#include <QtFbSupport/private/qfbscreen_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QPainter;
+
+class QBsdFbScreen : public QFbScreen
+{
+ Q_OBJECT
+public:
+ explicit QBsdFbScreen(const QStringList &args);
+ ~QBsdFbScreen() override;
+
+ bool initialize();
+
+ QPixmap grabWindow(WId wid, int x, int y, int width, int height) const override;
+
+ QRegion doRedraw() override;
+
+private:
+ QStringList m_arguments;
+ int m_framebufferFd = -1;
+ QImage m_onscreenImage;
+
+ int m_bytesPerLine = -1;
+
+ struct {
+ uchar *data;
+ int offset, size;
+ } m_mmap;
+
+ QScopedPointer<QPainter> m_blitter;
+};
+
+QT_END_NAMESPACE
+
+#endif // QBSDFBSCREEN_H
diff --git a/src/plugins/platforms/cocoa/cocoa.pro b/src/plugins/platforms/cocoa/cocoa.pro
index 02d8b16110..0664841c2d 100644
--- a/src/plugins/platforms/cocoa/cocoa.pro
+++ b/src/plugins/platforms/cocoa/cocoa.pro
@@ -71,7 +71,7 @@ HEADERS += qcocoaintegration.h \
messages.h \
qcocoamimetypes.h
-contains(QT_CONFIG, opengl.*) {
+qtConfig(opengl.*) {
OBJECTIVE_SOURCES += qcocoaglcontext.mm
HEADERS += qcocoaglcontext.h
@@ -81,7 +81,10 @@ RESOURCES += qcocoaresources.qrc
LIBS += -framework AppKit -framework Carbon -framework IOKit -lcups
-QT += core-private gui-private platformsupport-private
+QT += \
+ core-private gui-private \
+ accessibility_support-private clipboard_support-private theme_support-private \
+ fontdatabase_support-private graphics_support-private cgl_support-private
qtHaveModule(widgets) {
OBJECTIVE_SOURCES += \
diff --git a/src/plugins/platforms/cocoa/qcocoaaccessibility.mm b/src/plugins/platforms/cocoa/qcocoaaccessibility.mm
index 1faa806480..b15c486e9d 100644
--- a/src/plugins/platforms/cocoa/qcocoaaccessibility.mm
+++ b/src/plugins/platforms/cocoa/qcocoaaccessibility.mm
@@ -359,7 +359,7 @@ id getValueAttribute(QAccessibleInterface *interface)
{
const QAccessible::Role qtrole = interface->role();
if (qtrole == QAccessible::StaticText) {
- return QCFString::toNSString(interface->text(QAccessible::Name));
+ return interface->text(QAccessible::Name).toNSString();
}
if (qtrole == QAccessible::EditableText) {
if (QAccessibleTextInterface *textInterface = interface->textInterface()) {
@@ -380,12 +380,12 @@ id getValueAttribute(QAccessibleInterface *interface)
// textInterface->textAfterOffset(0, QAccessible2::SentenceBoundary, &begin, &end);
text = textInterface->text(begin, end);
}
- return QCFString::toNSString(text);
+ return text.toNSString();
}
}
if (QAccessibleValueInterface *valueInterface = interface->valueInterface()) {
- return QCFString::toNSString(valueInterface->currentValue().toString());
+ return valueInterface->currentValue().toString().toNSString();
}
if (interface->state().checkable) {
diff --git a/src/plugins/platforms/cocoa/qcocoaaccessibilityelement.mm b/src/plugins/platforms/cocoa/qcocoaaccessibilityelement.mm
index 7128fb72c3..97bd402b73 100644
--- a/src/plugins/platforms/cocoa/qcocoaaccessibilityelement.mm
+++ b/src/plugins/platforms/cocoa/qcocoaaccessibilityelement.mm
@@ -41,7 +41,7 @@
#include "qcocoahelpers.h"
#include "qcocoawindow.h"
#include "private/qaccessiblecache_p.h"
-#include <QtPlatformSupport/private/qaccessiblebridgeutils_p.h>
+#include <QtAccessibilitySupport/private/qaccessiblebridgeutils_p.h>
#include <QtGui/qaccessible.h>
#import <AppKit/NSAccessibility.h>
@@ -237,7 +237,7 @@ static void convertLineOffset(QAccessibleTextInterface *text, int *line, int *of
if (QWindow *window = iface->window()) {
QCocoaWindow *win = static_cast<QCocoaWindow*>(window->handle());
- return win->qtView();
+ return qnsview_cast(win->view());
}
QAccessibleInterface *parent = iface->parent();
@@ -300,9 +300,9 @@ static void convertLineOffset(QAccessibleTextInterface *text, int *line, int *of
} else if ([attribute isEqualToString:NSAccessibilityTitleAttribute]) {
if (iface->role() == QAccessible::StaticText)
return nil;
- return QCFString::toNSString(iface->text(QAccessible::Name));
+ return iface->text(QAccessible::Name).toNSString();
} else if ([attribute isEqualToString:NSAccessibilityDescriptionAttribute]) {
- return QCFString::toNSString(iface->text(QAccessible::Description));
+ return iface->text(QAccessible::Description).toNSString();
} else if ([attribute isEqualToString:NSAccessibilityEnabledAttribute]) {
return [NSNumber numberWithBool:!iface->state().disabled];
} else if ([attribute isEqualToString:NSAccessibilityValueAttribute]) {
@@ -439,7 +439,7 @@ static void convertLineOffset(QAccessibleTextInterface *text, int *line, int *of
if ([attribute isEqualToString: NSAccessibilityAttributedStringForRangeParameterizedAttribute]) {
NSRange range = [parameter rangeValue];
QString text = iface->textInterface()->text(range.location, range.location + range.length);
- return [[NSAttributedString alloc] initWithString: text.toNSString()];
+ return [[NSAttributedString alloc] initWithString:text.toNSString()];
} else if ([attribute isEqualToString: NSAccessibilityRangeForPositionParameterizedAttribute]) {
NSPoint nsPoint = [parameter pointValue];
QPoint point(static_cast<int>(nsPoint.x), static_cast<int>(qt_mac_flipYCoordinate(nsPoint.y)));
@@ -532,7 +532,7 @@ static void convertLineOffset(QAccessibleTextInterface *text, int *line, int *of
} else {
description = qAccessibleLocalizedActionDescription(qtAction);
}
- return QCFString::toNSString(description);
+ return description.toNSString();
}
- (void)accessibilityPerformAction:(NSString *)action {
diff --git a/src/plugins/platforms/cocoa/qcocoaapplication.h b/src/plugins/platforms/cocoa/qcocoaapplication.h
index e92bef4011..7bd3c8c76c 100644
--- a/src/plugins/platforms/cocoa/qcocoaapplication.h
+++ b/src/plugins/platforms/cocoa/qcocoaapplication.h
@@ -95,7 +95,6 @@
@interface NSApplication (QT_MANGLE_NAMESPACE(QApplicationIntegration))
- (void)QT_MANGLE_NAMESPACE(qt_setDockMenu):(NSMenu *)newMenu;
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader);
- (int)QT_MANGLE_NAMESPACE(qt_validModesForFontPanel):(NSFontPanel *)fontPanel;
- (void)QT_MANGLE_NAMESPACE(qt_sendPostedMessage):(NSEvent *)event;
diff --git a/src/plugins/platforms/cocoa/qcocoaapplication.mm b/src/plugins/platforms/cocoa/qcocoaapplication.mm
index c496134606..c5ae4bc2bf 100644
--- a/src/plugins/platforms/cocoa/qcocoaapplication.mm
+++ b/src/plugins/platforms/cocoa/qcocoaapplication.mm
@@ -71,11 +71,11 @@
**
****************************************************************************/
-#include <qcocoaapplication.h>
+#include "qcocoaapplication.h"
-#include <qcocoaintrospection.h>
-#include <qcocoaapplicationdelegate.h>
-#include <qcocoahelpers.h>
+#include "qcocoaintrospection.h"
+#include "qcocoaapplicationdelegate.h"
+#include "qcocoahelpers.h"
#include <qguiapplication.h>
#include <qdebug.h>
@@ -88,11 +88,6 @@ QT_USE_NAMESPACE
[[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] setDockMenu:newMenu];
}
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)
-{
- return [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] menuLoader];
-}
-
- (int)QT_MANGLE_NAMESPACE(qt_validModesForFontPanel):(NSFontPanel *)fontPanel
{
Q_UNUSED(fontPanel);
diff --git a/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h b/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h
index 68a028ed8a..59c71017e3 100644
--- a/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h
+++ b/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.h
@@ -95,14 +95,11 @@
@interface QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) : NSObject <NSApplicationDelegate> {
bool startedQuit;
NSMenu *dockMenu;
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *qtMenuLoader;
NSObject <NSApplicationDelegate> *reflectionDelegate;
bool inLaunch;
}
+ (QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate)*)sharedDelegate;
- (void)setDockMenu:(NSMenu *)newMenu;
-- (void)setMenuLoader:(QT_MANGLE_NAMESPACE(QCocoaMenuLoader)*)menuLoader;
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)menuLoader;
- (void)setReflectionDelegate:(NSObject <NSApplicationDelegate> *)oldDelegate;
- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent;
- (void) removeAppleEventHandlers;
diff --git a/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm b/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm
index d18df35b80..da755aa189 100644
--- a/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm
+++ b/src/plugins/platforms/cocoa/qcocoaapplicationdelegate.mm
@@ -122,7 +122,6 @@ QT_END_NAMESPACE
{
sharedCocoaApplicationDelegate = nil;
[dockMenu release];
- [qtMenuLoader release];
if (reflectionDelegate) {
[[NSApplication sharedApplication] setDelegate:reflectionDelegate];
[reflectionDelegate release];
@@ -169,24 +168,12 @@ QT_END_NAMESPACE
return [[dockMenu retain] autorelease];
}
-- (void)setMenuLoader:(QCocoaMenuLoader *)menuLoader
-{
- [menuLoader retain];
- [qtMenuLoader release];
- qtMenuLoader = menuLoader;
-}
-
-- (QCocoaMenuLoader *)menuLoader
-{
- return [[qtMenuLoader retain] autorelease];
-}
-
- (BOOL) canQuit
{
[[NSApp mainMenu] cancelTracking];
bool handle_quit = true;
- NSMenuItem *quitMenuItem = [[[QCocoaApplicationDelegate sharedDelegate] menuLoader] quitMenuItem];
+ NSMenuItem *quitMenuItem = [[QT_MANGLE_NAMESPACE(QCocoaMenuLoader) sharedMenuLoader] quitMenuItem];
if (!QGuiApplicationPrivate::instance()->modalWindowList.isEmpty()
&& [quitMenuItem isEnabled]) {
int visible = 0;
@@ -309,7 +296,7 @@ QT_END_NAMESPACE
Q_UNUSED(sender);
for (NSString *fileName in filenames) {
- QString qtFileName = QCFString::toQString(fileName);
+ QString qtFileName = QString::fromNSString(fileName);
if (inLaunch) {
// We need to be careful because Cocoa will be nice enough to take
// command line arguments and send them to us as events. Given the history
@@ -437,7 +424,7 @@ QT_END_NAMESPACE
{
Q_UNUSED(replyEvent);
NSString *urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
- QWindowSystemInterface::handleFileOpenEvent(QUrl(QCFString::toQString(urlString)));
+ QWindowSystemInterface::handleFileOpenEvent(QUrl(QString::fromNSString(urlString)));
}
- (void)appleEventQuit:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
@@ -447,10 +434,4 @@ QT_END_NAMESPACE
[NSApp terminate:self];
}
-- (void)qtDispatcherToQAction:(id)sender
-{
- Q_UNUSED(sender);
- [qtMenuLoader qtDispatcherToQPAMenuItem:sender];
-}
-
@end
diff --git a/src/plugins/platforms/cocoa/qcocoabackingstore.h b/src/plugins/platforms/cocoa/qcocoabackingstore.h
index fa05626d18..5ed455fd71 100644
--- a/src/plugins/platforms/cocoa/qcocoabackingstore.h
+++ b/src/plugins/platforms/cocoa/qcocoabackingstore.h
@@ -40,36 +40,20 @@
#ifndef QBACKINGSTORE_COCOA_H
#define QBACKINGSTORE_COCOA_H
-#include <AppKit/AppKit.h>
-
-#include "qcocoawindow.h"
-#include "qnsview.h"
-
-#include <qpa/qplatformbackingstore.h>
+#include <QtGraphicsSupport/private/qrasterbackingstore_p.h>
QT_BEGIN_NAMESPACE
-class QCocoaBackingStore : public QPlatformBackingStore
+class QCocoaBackingStore : public QRasterBackingStore
{
public:
QCocoaBackingStore(QWindow *window);
~QCocoaBackingStore();
- QPaintDevice *paintDevice() Q_DECL_OVERRIDE;
- void flush(QWindow *widget, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE;
-#ifndef QT_NO_OPENGL
- QImage toImage() const Q_DECL_OVERRIDE;
-#else
- QImage toImage() const; // No QPlatformBackingStore::toImage() for NO_OPENGL builds.
-#endif
- void resize (const QSize &size, const QRegion &) Q_DECL_OVERRIDE;
- bool scroll(const QRegion &area, int dx, int dy) Q_DECL_OVERRIDE;
- void beginPaint(const QRegion &region) Q_DECL_OVERRIDE;
- qreal getBackingStoreDevicePixelRatio();
+ void flush(QWindow *, const QRegion &, const QPoint &) Q_DECL_OVERRIDE;
private:
- QImage m_qImage;
- QSize m_requestedSize;
+ QImage::Format format() const Q_DECL_OVERRIDE;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/cocoa/qcocoabackingstore.mm b/src/plugins/platforms/cocoa/qcocoabackingstore.mm
index b060d6a082..a74995319b 100644
--- a/src/plugins/platforms/cocoa/qcocoabackingstore.mm
+++ b/src/plugins/platforms/cocoa/qcocoabackingstore.mm
@@ -38,87 +38,38 @@
****************************************************************************/
#include "qcocoabackingstore.h"
-#include <QtGui/QPainter>
+
+#include "qcocoawindow.h"
#include "qcocoahelpers.h"
QT_BEGIN_NAMESPACE
QCocoaBackingStore::QCocoaBackingStore(QWindow *window)
- : QPlatformBackingStore(window)
+ : QRasterBackingStore(window)
{
}
QCocoaBackingStore::~QCocoaBackingStore()
{
if (QCocoaWindow *cocoaWindow = static_cast<QCocoaWindow *>(window()->handle()))
- [cocoaWindow->m_qtView clearBackingStore:this];
-}
-
-QPaintDevice *QCocoaBackingStore::paintDevice()
-{
- QCocoaWindow *cocoaWindow = static_cast<QCocoaWindow *>(window()->handle());
- int windowDevicePixelRatio = int(cocoaWindow->devicePixelRatio());
-
- // Receate the backing store buffer if the effective buffer size has changed,
- // either due to a window resize or devicePixelRatio change.
- QSize effectiveBufferSize = m_requestedSize * windowDevicePixelRatio;
- if (m_qImage.size() != effectiveBufferSize) {
- QImage::Format format = (window()->format().hasAlpha() || cocoaWindow->m_drawContentBorderGradient)
- ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32;
- m_qImage = QImage(effectiveBufferSize, format);
- m_qImage.setDevicePixelRatio(windowDevicePixelRatio);
- if (format == QImage::Format_ARGB32_Premultiplied)
- m_qImage.fill(Qt::transparent);
- }
- return &m_qImage;
+ [qnsview_cast(cocoaWindow->view()) clearBackingStore:this];
}
-void QCocoaBackingStore::flush(QWindow *win, const QRegion &region, const QPoint &offset)
+QImage::Format QCocoaBackingStore::format() const
{
- if (!m_qImage.isNull()) {
- if (QCocoaWindow *cocoaWindow = static_cast<QCocoaWindow *>(win->handle()))
- [cocoaWindow->m_qtView flushBackingStore:this region:region offset:offset];
- }
-}
+ if (static_cast<QCocoaWindow *>(window()->handle())->m_drawContentBorderGradient)
+ return QImage::Format_ARGB32_Premultiplied;
-QImage QCocoaBackingStore::toImage() const
-{
- return m_qImage;
+ return QRasterBackingStore::format();
}
-void QCocoaBackingStore::resize(const QSize &size, const QRegion &)
+void QCocoaBackingStore::flush(QWindow *window, const QRegion &region, const QPoint &offset)
{
- m_requestedSize = size;
-}
+ if (m_image.isNull())
+ return;
-bool QCocoaBackingStore::scroll(const QRegion &area, int dx, int dy)
-{
- extern void qt_scrollRectInImage(QImage &img, const QRect &rect, const QPoint &offset);
- const qreal devicePixelRatio = m_qImage.devicePixelRatio();
- QPoint qpoint(dx * devicePixelRatio, dy * devicePixelRatio);
- const QVector<QRect> qrects = area.rects();
- for (int i = 0; i < qrects.count(); ++i) {
- const QRect &qrect = QRect(qrects.at(i).topLeft() * devicePixelRatio, qrects.at(i).size() * devicePixelRatio);
- qt_scrollRectInImage(m_qImage, qrect, qpoint);
- }
- return true;
-}
-
-void QCocoaBackingStore::beginPaint(const QRegion &region)
-{
- if (m_qImage.hasAlphaChannel()) {
- QPainter p(&m_qImage);
- p.setCompositionMode(QPainter::CompositionMode_Source);
- const QVector<QRect> rects = region.rects();
- const QColor blank = Qt::transparent;
- for (QVector<QRect>::const_iterator it = rects.begin(), end = rects.end(); it != end; ++it)
- p.fillRect(*it, blank);
- }
-}
-
-qreal QCocoaBackingStore::getBackingStoreDevicePixelRatio()
-{
- return m_qImage.devicePixelRatio();
+ if (QCocoaWindow *cocoaWindow = static_cast<QCocoaWindow *>(window->handle()))
+ [qnsview_cast(cocoaWindow->view()) flushBackingStore:this region:region offset:offset];
}
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/cocoa/qcocoaclipboard.h b/src/plugins/platforms/cocoa/qcocoaclipboard.h
index 52fec61f39..cab2cfaa91 100644
--- a/src/plugins/platforms/cocoa/qcocoaclipboard.h
+++ b/src/plugins/platforms/cocoa/qcocoaclipboard.h
@@ -41,6 +41,9 @@
#define QCOCOACLIPBOARD_H
#include <qpa/qplatformclipboard.h>
+
+#ifndef QT_NO_CLIPBOARD
+
#include "qmacclipboard.h"
#include <QtCore/QScopedPointer>
@@ -71,4 +74,6 @@ private:
QT_END_NAMESPACE
-#endif
+#endif // QT_NO_CLIPBOARD
+
+#endif // QCOCOACLIPBOARD_H
diff --git a/src/plugins/platforms/cocoa/qcocoaclipboard.mm b/src/plugins/platforms/cocoa/qcocoaclipboard.mm
index 7209c93a94..b4745900dc 100644
--- a/src/plugins/platforms/cocoa/qcocoaclipboard.mm
+++ b/src/plugins/platforms/cocoa/qcocoaclipboard.mm
@@ -39,6 +39,8 @@
#include "qcocoaclipboard.h"
+#ifndef QT_NO_CLIPBOARD
+
QT_BEGIN_NAMESPACE
QCocoaClipboard::QCocoaClipboard()
@@ -105,3 +107,5 @@ void QCocoaClipboard::handleApplicationStateChanged(Qt::ApplicationState state)
#include "moc_qcocoaclipboard.cpp"
QT_END_NAMESPACE
+
+#endif // QT_NO_CLIPBOARD
diff --git a/src/plugins/platforms/cocoa/qcocoacolordialoghelper.mm b/src/plugins/platforms/cocoa/qcocoacolordialoghelper.mm
index f89c06fc58..7f81e313cb 100644
--- a/src/plugins/platforms/cocoa/qcocoacolordialoghelper.mm
+++ b/src/plugins/platforms/cocoa/qcocoacolordialoghelper.mm
@@ -133,7 +133,7 @@ QT_NAMESPACE_ALIAS_OBJC_CLASS(QNSColorPanelDelegate);
- (void)setDialogHelper:(QCocoaColorDialogHelper *)helper
{
mHelper = helper;
- [mColorPanel setShowsAlpha:mHelper->options()->testOption(QColorDialogOptions::ShowAlphaChannel)];
+
if (mHelper->options()->testOption(QColorDialogOptions::NoButtons)) {
[self restoreOriginalContentView];
} else if (!mStolenContentView) {
@@ -486,6 +486,14 @@ bool QCocoaColorDialogHelper::show(Qt::WindowFlags, Qt::WindowModality windowMod
{
if (windowModality == Qt::WindowModal)
windowModality = Qt::ApplicationModal;
+
+ // Workaround for Apple rdar://25792119: If you invoke
+ // -setShowsAlpha: multiple times before showing the color
+ // picker, its height grows irrevocably. Instead, only
+ // invoke it once, when we show the dialog.
+ [[NSColorPanel sharedColorPanel] setShowsAlpha:
+ options()->testOption(QColorDialogOptions::ShowAlphaChannel)];
+
sharedColorPanel()->init(this);
return sharedColorPanel()->show(windowModality, parent);
}
diff --git a/src/plugins/platforms/cocoa/qcocoacursor.mm b/src/plugins/platforms/cocoa/qcocoacursor.mm
index 4870c521c7..3df2a7c962 100644
--- a/src/plugins/platforms/cocoa/qcocoacursor.mm
+++ b/src/plugins/platforms/cocoa/qcocoacursor.mm
@@ -40,6 +40,7 @@
#include "qcocoacursor.h"
#include "qcocoawindow.h"
#include "qcocoahelpers.h"
+#include <QtGui/private/qcoregraphics_p.h>
#include <QtGui/QBitmap>
diff --git a/src/plugins/platforms/cocoa/qcocoadrag.mm b/src/plugins/platforms/cocoa/qcocoadrag.mm
index bb8d12e3ce..7d11023b78 100644
--- a/src/plugins/platforms/cocoa/qcocoadrag.mm
+++ b/src/plugins/platforms/cocoa/qcocoadrag.mm
@@ -43,6 +43,7 @@
#ifndef QT_NO_WIDGETS
#include <QtWidgets/qwidget.h>
#endif
+#include <QtGui/private/qcoregraphics_p.h>
QT_BEGIN_NAMESPACE
@@ -131,7 +132,7 @@ Qt::DropAction QCocoaDrag::drag(QDrag *o)
QPixmap pm = dragPixmap(m_drag, hotSpot);
QSize pmDeviceIndependentSize = pm.size() / pm.devicePixelRatio();
NSImage *nsimage = qt_mac_create_nsimage(pm);
- [nsimage setSize : qt_mac_toNSSize(pmDeviceIndependentSize)];
+ [nsimage setSize:pmDeviceIndependentSize.toCGSize()];
QMacPasteboard dragBoard((CFStringRef) NSDragPboard, QMacInternalPasteboardMime::MIME_DND);
m_drag->mimeData()->setData(QLatin1String("application/x-qt-mime-type-name"), QByteArray("dummy"));
diff --git a/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm b/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm
index d9c835d797..72c7856c2d 100644
--- a/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm
+++ b/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm
@@ -85,7 +85,6 @@
#include "private/qguiapplication_p.h"
#include <qdebug.h>
-#undef slots
#include <AppKit/AppKit.h>
#include <Carbon/Carbon.h>
diff --git a/src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm b/src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm
index c7191e4841..234da57f59 100644
--- a/src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm
+++ b/src/plugins/platforms/cocoa/qcocoafiledialoghelper.mm
@@ -62,6 +62,8 @@
#include <qvarlengtharray.h>
#include <stdlib.h>
#include <qabstracteventdispatcher.h>
+#include <qsysinfo.h>
+#include <qglobal.h>
#include <QDir>
#include <qpa/qplatformnativeinterface.h>
@@ -144,14 +146,14 @@ QT_NAMESPACE_ALIAS_OBJC_CLASS(QNSOpenSavePanelDelegate);
QFileInfo sel(selectFile);
if (sel.isDir() && !sel.isBundle()){
- mCurrentDir = [QCFString::toNSString(sel.absoluteFilePath()) retain];
+ mCurrentDir = [sel.absoluteFilePath().toNSString() retain];
mCurrentSelection = new QString;
} else {
- mCurrentDir = [QCFString::toNSString(sel.absolutePath()) retain];
+ mCurrentDir = [sel.absolutePath().toNSString() retain];
mCurrentSelection = new QString(sel.absoluteFilePath());
}
- [mSavePanel setTitle:QCFString::toNSString(options->windowTitle())];
+ [mSavePanel setTitle:options->windowTitle().toNSString()];
[self createPopUpButton:selectedVisualNameFilter hideDetails:options->testOption(QFileDialogOptions::HideNameFilterDetails)];
[self createTextField];
[self createAccessory];
@@ -161,6 +163,11 @@ QT_NAMESPACE_ALIAS_OBJC_CLASS(QNSOpenSavePanelDelegate);
// here to make sure it gets the correct value.
[mSavePanel setDelegate:self];
+#if QT_OSX_PLATFORM_SDK_EQUAL_OR_ABOVE(__MAC_10_11)
+ if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_11)
+ mOpenPanel.accessoryViewDisclosed = YES;
+#endif
+
if (mOptions->isLabelExplicitlySet(QFileDialogOptions::Accept))
[mSavePanel setPrompt:[self strip:options->labelText(QFileDialogOptions::Accept)]];
if (mOptions->isLabelExplicitlySet(QFileDialogOptions::FileName))
@@ -197,12 +204,12 @@ static QString strippedText(QString s)
- (NSString *)strip:(const QString &)label
{
- return QCFString::toNSString(strippedText(label));
+ return strippedText(label).toNSString();
}
- (void)closePanel
{
- *mCurrentSelection = QCFString::toQString([[mSavePanel URL] path]).normalized(QString::NormalizationForm_C);
+ *mCurrentSelection = QString::fromNSString([[mSavePanel URL] path]).normalized(QString::NormalizationForm_C);
if ([mSavePanel respondsToSelector:@selector(close)])
[mSavePanel close];
if ([mSavePanel isSheet])
@@ -213,14 +220,14 @@ static QString strippedText(QString s)
{
if (mOpenPanel){
QFileInfo info(*mCurrentSelection);
- NSString *filepath = QCFString::toNSString(info.filePath());
+ NSString *filepath = info.filePath().toNSString();
bool selectable = (mOptions->acceptMode() == QFileDialogOptions::AcceptSave)
|| [self panel:nil shouldShowFilename:filepath];
[self updateProperties];
QCocoaMenuBar::redirectKnownMenuItemsToFirstResponder();
[mOpenPanel setAllowedFileTypes:nil];
- [mSavePanel setNameFieldStringValue:selectable ? QT_PREPEND_NAMESPACE(QCFString::toNSString)(info.fileName()) : @""];
+ [mSavePanel setNameFieldStringValue:selectable ? info.fileName().toNSString() : @""];
[mOpenPanel beginWithCompletionHandler:^(NSInteger result){
mReturnCode = result;
@@ -233,12 +240,12 @@ static QString strippedText(QString s)
- (BOOL)runApplicationModalPanel
{
QFileInfo info(*mCurrentSelection);
- NSString *filepath = QCFString::toNSString(info.filePath());
+ NSString *filepath = info.filePath().toNSString();
bool selectable = (mOptions->acceptMode() == QFileDialogOptions::AcceptSave)
|| [self panel:nil shouldShowFilename:filepath];
[mSavePanel setDirectoryURL: [NSURL fileURLWithPath:mCurrentDir]];
- [mSavePanel setNameFieldStringValue:selectable ? QCFString::toNSString(info.fileName()) : @""];
+ [mSavePanel setNameFieldStringValue:selectable ? info.fileName().toNSString() : @""];
// Call processEvents in case the event dispatcher has been interrupted, and needs to do
// cleanup of modal sessions. Do this before showing the native dialog, otherwise it will
@@ -264,7 +271,7 @@ static QString strippedText(QString s)
- (void)showWindowModalSheet:(QWindow *)parent
{
QFileInfo info(*mCurrentSelection);
- NSString *filepath = QCFString::toNSString(info.filePath());
+ NSString *filepath = info.filePath().toNSString();
bool selectable = (mOptions->acceptMode() == QFileDialogOptions::AcceptSave)
|| [self panel:nil shouldShowFilename:filepath];
@@ -272,7 +279,7 @@ static QString strippedText(QString s)
QCocoaMenuBar::redirectKnownMenuItemsToFirstResponder();
[mSavePanel setDirectoryURL: [NSURL fileURLWithPath:mCurrentDir]];
- [mSavePanel setNameFieldStringValue:selectable ? QCFString::toNSString(info.fileName()) : @""];
+ [mSavePanel setNameFieldStringValue:selectable ? info.fileName().toNSString() : @""];
NSWindow *nsparent = static_cast<NSWindow *>(qGuiApp->platformNativeInterface()->nativeResourceForWindow("nswindow", parent));
[mSavePanel beginSheetModalForWindow:nsparent completionHandler:^(NSInteger result){
@@ -319,7 +326,7 @@ static QString strippedText(QString s)
}
}
- QString qtFileName = QFileInfo(QCFString::toQString(filename)).fileName();
+ QString qtFileName = QFileInfo(QString::fromNSString(filename)).fileName();
// No filter means accept everything
bool nameMatches = mSelectedNameFilter->isEmpty();
// Check if the current file name filter accepts the file:
@@ -371,7 +378,7 @@ static QString strippedText(QString s)
if (filters.size() > 0){
for (int i=0; i<filters.size(); ++i) {
QString filter = hideDetails ? [self removeExtensions:filters.at(i)] : filters.at(i);
- [mPopUpButton addItemWithTitle:QCFString::toNSString(filter)];
+ [mPopUpButton addItemWithTitle:filter.toNSString()];
}
[mPopUpButton selectItemAtIndex:0];
[mSavePanel setAccessoryView:mAccessoryView];
@@ -405,13 +412,13 @@ static QString strippedText(QString s)
QList<QUrl> result;
NSArray* array = [mOpenPanel URLs];
for (NSUInteger i=0; i<[array count]; ++i) {
- QString path = QCFString::toQString([[array objectAtIndex:i] path]).normalized(QString::NormalizationForm_C);
+ QString path = QString::fromNSString([[array objectAtIndex:i] path]).normalized(QString::NormalizationForm_C);
result << QUrl::fromLocalFile(path);
}
return result;
} else {
QList<QUrl> result;
- QString filename = QCFString::toQString([[mSavePanel URL] path]).normalized(QString::NormalizationForm_C);
+ QString filename = QString::fromNSString([[mSavePanel URL] path]).normalized(QString::NormalizationForm_C);
result << QUrl::fromLocalFile(filename.remove(QLatin1String("___qt_very_unlikely_prefix_")));
return result;
}
@@ -434,8 +441,8 @@ static QString strippedText(QString s)
[mSavePanel setCanCreateDirectories:!(mOptions->testOption(QFileDialogOptions::ReadOnly))];
[mOpenPanel setAllowsMultipleSelection:(fileMode == QFileDialogOptions::ExistingFiles)];
[mOpenPanel setResolvesAliases:!(mOptions->testOption(QFileDialogOptions::DontResolveSymlinks))];
- [mOpenPanel setTitle:QCFString::toNSString(mOptions->windowTitle())];
- [mSavePanel setTitle:QCFString::toNSString(mOptions->windowTitle())];
+ [mOpenPanel setTitle:mOptions->windowTitle().toNSString()];
+ [mSavePanel setTitle:mOptions->windowTitle().toNSString()];
[mPopUpButton setHidden:chooseDirsOnly]; // TODO hide the whole sunken pane instead?
QStringList ext = [self acceptableExtensionsForSave];
@@ -454,7 +461,7 @@ static QString strippedText(QString s)
{
Q_UNUSED(sender);
if (mHelper && [mSavePanel isVisible]) {
- QString selection = QCFString::toQString([[mSavePanel URL] path]);
+ QString selection = QString::fromNSString([[mSavePanel URL] path]);
if (selection != mCurrentSelection) {
*mCurrentSelection = selection;
mHelper->QNSOpenSavePanelDelegate_selectionChanged(selection);
@@ -472,7 +479,7 @@ static QString strippedText(QString s)
[mCurrentDir release];
mCurrentDir = [path retain];
- mHelper->QNSOpenSavePanelDelegate_directoryEntered(QCFString::toQString(mCurrentDir));
+ mHelper->QNSOpenSavePanelDelegate_directoryEntered(QString::fromNSString(mCurrentDir));
}
/*
@@ -535,7 +542,7 @@ static QString strippedText(QString s)
(filterToUse == -1 && currentFilter.startsWith(selectedFilter)))
filterToUse = i;
QString filter = hideDetails ? [self removeExtensions:currentFilter] : currentFilter;
- [mPopUpButton addItemWithTitle:QCFString::toNSString(filter)];
+ [mPopUpButton addItemWithTitle:filter.toNSString()];
}
if (filterToUse != -1)
[mPopUpButton selectItemAtIndex:filterToUse];
@@ -607,7 +614,7 @@ void QCocoaFileDialogHelper::QNSOpenSavePanelDelegate_filterSelected(int menuInd
void QCocoaFileDialogHelper::setDirectory(const QUrl &directory)
{
if (mDelegate)
- [mDelegate->mSavePanel setDirectoryURL:[NSURL fileURLWithPath:QCFString::toNSString(directory.toLocalFile())]];
+ [mDelegate->mSavePanel setDirectoryURL:[NSURL fileURLWithPath:directory.toLocalFile().toNSString()]];
else
mDir = directory;
}
@@ -615,7 +622,7 @@ void QCocoaFileDialogHelper::setDirectory(const QUrl &directory)
QUrl QCocoaFileDialogHelper::directory() const
{
if (mDelegate) {
- QString path = QCFString::toQString([[mDelegate->mSavePanel directoryURL] path]).normalized(QString::NormalizationForm_C);
+ QString path = QString::fromNSString([[mDelegate->mSavePanel directoryURL] path]).normalized(QString::NormalizationForm_C);
return QUrl::fromLocalFile(path);
}
return mDir;
@@ -644,7 +651,7 @@ void QCocoaFileDialogHelper::setFilter()
if (!mDelegate)
return;
const SharedPointerFileDialogOptions &opts = options();
- [mDelegate->mSavePanel setTitle:QCFString::toNSString(opts->windowTitle())];
+ [mDelegate->mSavePanel setTitle:opts->windowTitle().toNSString()];
if (opts->isLabelExplicitlySet(QFileDialogOptions::Accept))
[mDelegate->mSavePanel setPrompt:[mDelegate strip:opts->labelText(QFileDialogOptions::Accept)]];
if (opts->isLabelExplicitlySet(QFileDialogOptions::FileName))
diff --git a/src/plugins/platforms/cocoa/qcocoafontdialoghelper.mm b/src/plugins/platforms/cocoa/qcocoafontdialoghelper.mm
index 32c4077961..791839d6ea 100644
--- a/src/plugins/platforms/cocoa/qcocoafontdialoghelper.mm
+++ b/src/plugins/platforms/cocoa/qcocoafontdialoghelper.mm
@@ -163,7 +163,7 @@ QT_NAMESPACE_ALIAS_OBJC_CLASS(QNSFontPanelDelegate);
{
mHelper = helper;
- [mFontPanel setTitle:QCFString::toNSString(helper->options()->windowTitle())];
+ [mFontPanel setTitle:helper->options()->windowTitle().toNSString()];
if (mHelper->options()->testOption(QFontDialogOptions::NoButtons)) {
[self restoreOriginalContentView];
@@ -447,7 +447,7 @@ public:
}
QFontInfo fontInfo(font);
- nsFont = [mgr fontWithFamily:QCFString::toNSString(fontInfo.family())
+ nsFont = [mgr fontWithFamily:fontInfo.family().toNSString()
traits:mask
weight:weight
size:fontInfo.pointSize()];
diff --git a/src/plugins/platforms/cocoa/qcocoaglcontext.h b/src/plugins/platforms/cocoa/qcocoaglcontext.h
index 5bee708b76..1a66cec0e3 100644
--- a/src/plugins/platforms/cocoa/qcocoaglcontext.h
+++ b/src/plugins/platforms/cocoa/qcocoaglcontext.h
@@ -45,7 +45,6 @@
#include <QtGui/QOpenGLContext>
#include <QtGui/QWindow>
-#undef slots
#include <AppKit/AppKit.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/cocoa/qcocoaglcontext.mm b/src/plugins/platforms/cocoa/qcocoaglcontext.mm
index ccb11f80f1..a7cc19b3bf 100644
--- a/src/plugins/platforms/cocoa/qcocoaglcontext.mm
+++ b/src/plugins/platforms/cocoa/qcocoaglcontext.mm
@@ -42,7 +42,7 @@
#include "qcocoahelpers.h"
#include <qdebug.h>
#include <QtCore/private/qcore_mac_p.h>
-#include <QtPlatformSupport/private/cglconvenience_p.h>
+#include <QtCglSupport/private/cglconvenience_p.h>
#include <QtPlatformHeaders/qcocoanativecontext.h>
#include <dlfcn.h>
@@ -255,7 +255,7 @@ void QCocoaGLContext::setActiveWindow(QWindow *window)
QCocoaWindow *cocoaWindow = static_cast<QCocoaWindow *>(window->handle());
cocoaWindow->setCurrentContext(this);
- [(QNSView *) cocoaWindow->contentView() setQCocoaGLContext:this];
+ [(QNSView *) cocoaWindow->view() setQCocoaGLContext:this];
}
void QCocoaGLContext::updateSurfaceFormat()
diff --git a/src/plugins/platforms/cocoa/qcocoahelpers.h b/src/plugins/platforms/cocoa/qcocoahelpers.h
index ec2f7f8cf1..1b038a6b5e 100644
--- a/src/plugins/platforms/cocoa/qcocoahelpers.h
+++ b/src/plugins/platforms/cocoa/qcocoahelpers.h
@@ -55,6 +55,8 @@
#include <QtGui/qpalette.h>
#include <QtGui/qscreen.h>
+Q_FORWARD_DECLARE_OBJC_CLASS(QT_MANGLE_NAMESPACE(QNSView));
+
QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(lcQpaCocoaWindow)
@@ -69,39 +71,15 @@ void *qt_mac_QStringListToNSMutableArrayVoid(const QStringList &list);
inline NSMutableArray *qt_mac_QStringListToNSMutableArray(const QStringList &qstrlist)
{ return reinterpret_cast<NSMutableArray *>(qt_mac_QStringListToNSMutableArrayVoid(qstrlist)); }
-NSImage *qt_mac_cgimage_to_nsimage(CGImageRef iamge);
-NSImage *qt_mac_create_nsimage(const QPixmap &pm);
-NSImage *qt_mac_create_nsimage(const QIcon &icon);
-CGImageRef qt_mac_toCGImage(const QImage &qImage);
-CGImageRef qt_mac_toCGImageMask(const QImage &qImage);
-QImage qt_mac_toQImage(CGImageRef image);
-QPixmap qt_mac_toQPixmap(const NSImage *image, const QSizeF &size);
-
-NSSize qt_mac_toNSSize(const QSize &qtSize);
-NSRect qt_mac_toNSRect(const QRect &rect);
-QRect qt_mac_toQRect(const NSRect &rect);
-
-QColor qt_mac_toQColor(const NSColor *color);
-QColor qt_mac_toQColor(CGColorRef color);
-
-QBrush qt_mac_toQBrush(CGColorRef color);
-QBrush qt_mac_toQBrush(const NSColor *color, QPalette::ColorGroup colorGroup = QPalette::Normal);
-
-// Creates a mutable shape, it's the caller's responsibility to release.
-HIMutableShapeRef qt_mac_QRegionToHIMutableShape(const QRegion &region);
-
-OSStatus qt_mac_drawCGImage(CGContextRef inContext, const CGRect *inBounds, CGImageRef inImage);
-
NSDragOperation qt_mac_mapDropAction(Qt::DropAction action);
NSDragOperation qt_mac_mapDropActions(Qt::DropActions actions);
Qt::DropAction qt_mac_mapNSDragOperation(NSDragOperation nsActions);
Qt::DropActions qt_mac_mapNSDragOperations(NSDragOperation nsActions);
+QT_MANGLE_NAMESPACE(QNSView) *qnsview_cast(NSView *view);
+
// Misc
void qt_mac_transformProccessToForegroundApplication();
-CGColorSpaceRef qt_mac_genericColorSpace();
-CGColorSpaceRef qt_mac_displayColorSpace(const QWidget *widget);
-CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice);
QString qt_mac_applicationName();
int qt_mac_flipYCoordinate(int y);
@@ -114,10 +92,6 @@ NSRect qt_mac_flipRect(const QRect &rect);
Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum);
-bool qt_mac_execute_apple_script(const char *script, long script_len, AEDesc *ret);
-bool qt_mac_execute_apple_script(const char *script, AEDesc *ret);
-bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret);
-
// strip out '&' characters, and convert "&&" to a single '&', in menu
// text - since menu text is sometimes decorated with these for Windows
// accelerators.
@@ -151,8 +125,6 @@ public:
}
};
-CGContextRef qt_mac_cg_context(QPaintDevice *pdev);
-
template<typename T>
T qt_mac_resolveOption(const T &fallback, const QByteArray &environment)
{
diff --git a/src/plugins/platforms/cocoa/qcocoahelpers.mm b/src/plugins/platforms/cocoa/qcocoahelpers.mm
index 606b2e7032..c57567bdd6 100644
--- a/src/plugins/platforms/cocoa/qcocoahelpers.mm
+++ b/src/plugins/platforms/cocoa/qcocoahelpers.mm
@@ -40,13 +40,14 @@
#include <qpa/qplatformtheme.h>
#include "qcocoahelpers.h"
-
+#include "qnsview.h"
#include <QtCore>
#include <QtGui>
#include <qpa/qplatformscreen.h>
#include <private/qguiapplication_p.h>
#include <private/qwindow_p.h>
+#include <QtGui/private/qcoregraphics_p.h>
#ifndef QT_NO_WIDGETS
#include <QtWidgets/QWidget>
@@ -56,25 +57,6 @@
#include <Carbon/Carbon.h>
-@interface NSGraphicsContext (QtAdditions)
-
-+ (NSGraphicsContext *)qt_graphicsContextWithCGContext:(CGContextRef)graphicsPort flipped:(BOOL)initialFlippedState;
-
-@end
-
-@implementation NSGraphicsContext (QtAdditions)
-
-+ (NSGraphicsContext *)qt_graphicsContextWithCGContext:(CGContextRef)graphicsPort flipped:(BOOL)initialFlippedState
-{
-#if QT_MAC_PLATFORM_SDK_EQUAL_OR_ABOVE(__MAC_10_10, __IPHONE_NA)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_10)
- return [self graphicsContextWithCGContext:graphicsPort flipped:initialFlippedState];
-#endif
- return [self graphicsContextWithGraphicsPort:graphicsPort flipped:initialFlippedState];
-}
-
-@end
-
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcQpaCocoaWindow, "qt.qpa.cocoa.window");
@@ -88,7 +70,7 @@ QStringList qt_mac_NSArrayToQStringList(void *nsarray)
QStringList result;
NSArray *array = static_cast<NSArray *>(nsarray);
for (NSUInteger i=0; i<[array count]; ++i)
- result << QCFString::toQString([array objectAtIndex:i]);
+ result << QString::fromNSString([array objectAtIndex:i]);
return result;
}
@@ -101,291 +83,6 @@ void *qt_mac_QStringListToNSMutableArrayVoid(const QStringList &list)
return result;
}
-static void qt_mac_deleteImage(void *image, const void *, size_t)
-{
- delete static_cast<QImage *>(image);
-}
-
-// Creates a CGDataProvider with the data from the given image.
-// The data provider retains a copy of the image.
-CGDataProviderRef qt_mac_CGDataProvider(const QImage &image)
-{
- return CGDataProviderCreateWithData(new QImage(image), image.bits(),
- image.byteCount(), qt_mac_deleteImage);
-}
-
-CGImageRef qt_mac_toCGImage(const QImage &inImage)
-{
- if (inImage.isNull())
- return 0;
-
- QImage image = inImage;
-
- uint cgflags = kCGImageAlphaNone;
- switch (image.format()) {
- case QImage::Format_ARGB32:
- cgflags = kCGImageAlphaFirst | kCGBitmapByteOrder32Host;
- break;
- case QImage::Format_RGB32:
- cgflags = kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host;
- break;
- case QImage::Format_RGB888:
- cgflags = kCGImageAlphaNone | kCGBitmapByteOrder32Big;
- break;
- case QImage::Format_RGBA8888_Premultiplied:
- cgflags = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;
- break;
- case QImage::Format_RGBA8888:
- cgflags = kCGImageAlphaLast | kCGBitmapByteOrder32Big;
- break;
- case QImage::Format_RGBX8888:
- cgflags = kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Big;
- break;
- default:
- // Everything not recognized explicitly is converted to ARGB32_Premultiplied.
- image = inImage.convertToFormat(QImage::Format_ARGB32_Premultiplied);
- // no break;
- case QImage::Format_ARGB32_Premultiplied:
- cgflags = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host;
- break;
- }
-
- QCFType<CGDataProviderRef> dataProvider = qt_mac_CGDataProvider(image);
- return CGImageCreate(image.width(), image.height(), 8, 32,
- image.bytesPerLine(),
- qt_mac_genericColorSpace(),
- cgflags, dataProvider, 0, false, kCGRenderingIntentDefault);
-}
-
-CGImageRef qt_mac_toCGImageMask(const QImage &image)
-{
- QCFType<CGDataProviderRef> dataProvider = qt_mac_CGDataProvider(image);
- return CGImageMaskCreate(image.width(), image.height(), 8, image.depth(),
- image.bytesPerLine(), dataProvider, NULL, false);
-}
-
-NSImage *qt_mac_cgimage_to_nsimage(CGImageRef image)
-{
- NSImage *newImage = [[NSImage alloc] initWithCGImage:image size:NSZeroSize];
- return newImage;
-}
-
-NSImage *qt_mac_create_nsimage(const QPixmap &pm)
-{
- if (pm.isNull())
- return 0;
- QImage image = pm.toImage();
- CGImageRef cgImage = qt_mac_toCGImage(image);
- NSImage *nsImage = qt_mac_cgimage_to_nsimage(cgImage);
- CGImageRelease(cgImage);
- return nsImage;
-}
-
-NSImage *qt_mac_create_nsimage(const QIcon &icon)
-{
- if (icon.isNull())
- return nil;
-
- NSImage *nsImage = [[NSImage alloc] init];
- foreach (QSize size, icon.availableSizes()) {
- QPixmap pm = icon.pixmap(size);
- QImage image = pm.toImage();
- CGImageRef cgImage = qt_mac_toCGImage(image);
- NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
- [nsImage addRepresentation:imageRep];
- [imageRep release];
- CGImageRelease(cgImage);
- }
- return nsImage;
-}
-
-HIMutableShapeRef qt_mac_QRegionToHIMutableShape(const QRegion &region)
-{
- HIMutableShapeRef shape = HIShapeCreateMutable();
- QVector<QRect> rects = region.rects();
- if (!rects.isEmpty()) {
- int n = rects.count();
- const QRect *qt_r = rects.constData();
- while (n--) {
- CGRect cgRect = CGRectMake(qt_r->x(), qt_r->y(), qt_r->width(), qt_r->height());
- HIShapeUnionWithRect(shape, &cgRect);
- ++qt_r;
- }
- }
- return shape;
-}
-
-NSSize qt_mac_toNSSize(const QSize &qtSize)
-{
- return NSMakeSize(qtSize.width(), qtSize.height());
-}
-
-NSRect qt_mac_toNSRect(const QRect &rect)
-{
- return NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height());
-}
-
-QRect qt_mac_toQRect(const NSRect &rect)
-{
- return QRect(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
-}
-
-QColor qt_mac_toQColor(const NSColor *color)
-{
- QColor qtColor;
- NSString *colorSpace = [color colorSpaceName];
- if (colorSpace == NSDeviceCMYKColorSpace) {
- CGFloat cyan, magenta, yellow, black, alpha;
- [color getCyan:&cyan magenta:&magenta yellow:&yellow black:&black alpha:&alpha];
- qtColor.setCmykF(cyan, magenta, yellow, black, alpha);
- } else {
- NSColor *tmpColor;
- tmpColor = [color colorUsingColorSpaceName:NSDeviceRGBColorSpace];
- CGFloat red, green, blue, alpha;
- [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
- qtColor.setRgbF(red, green, blue, alpha);
- }
- return qtColor;
-}
-
-QColor qt_mac_toQColor(CGColorRef color)
-{
- QColor qtColor;
- CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color));
- const CGFloat *components = CGColorGetComponents(color);
- if (model == kCGColorSpaceModelRGB) {
- qtColor.setRgbF(components[0], components[1], components[2], components[3]);
- } else if (model == kCGColorSpaceModelCMYK) {
- qtColor.setCmykF(components[0], components[1], components[2], components[3]);
- } else if (model == kCGColorSpaceModelMonochrome) {
- qtColor.setRgbF(components[0], components[0], components[0], components[1]);
- } else {
- // Colorspace we can't deal with.
- qWarning("Qt: qt_mac_toQColor: cannot convert from colorspace model: %d", model);
- Q_ASSERT(false);
- }
- return qtColor;
-}
-
-QBrush qt_mac_toQBrush(CGColorRef color)
-{
- QBrush qtBrush;
- CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color));
- if (model == kCGColorSpaceModelPattern) {
- // Colorspace we can't deal with; the color is drawn directly using a callback.
- qWarning("Qt: qt_mac_toQBrush: cannot convert from colorspace model: %d", model);
- Q_ASSERT(false);
- } else {
- qtBrush.setStyle(Qt::SolidPattern);
- qtBrush.setColor(qt_mac_toQColor(color));
- }
- return qtBrush;
-}
-
-static bool qt_mac_isSystemColorOrInstance(const NSColor *color, NSString *colorNameComponent, NSString *className)
-{
- // We specifically do not want isKindOfClass: here
- if ([color.className isEqualToString:className]) // NSPatternColorSpace
- return true;
- if ([color.catalogNameComponent isEqualToString:@"System"] &&
- [color.colorNameComponent isEqualToString:colorNameComponent] &&
- [color.colorSpaceName isEqualToString:NSNamedColorSpace])
- return true;
- return false;
-}
-
-QBrush qt_mac_toQBrush(const NSColor *color, QPalette::ColorGroup colorGroup)
-{
- QBrush qtBrush;
-
- // QTBUG-49773: This calls NSDrawMenuItemBackground to render a 1 by n gradient; could use HITheme
- if ([color.className isEqualToString:@"NSMenuItemHighlightColor"]) {
- qWarning("Qt: qt_mac_toQBrush: cannot convert from NSMenuItemHighlightColor");
- return qtBrush;
- }
-
- // Not a catalog color or a manifestation of System.windowBackgroundColor;
- // only retrieved from NSWindow.backgroundColor directly
- if ([color.className isEqualToString:@"NSMetalPatternColor"]) {
- // NSTexturedBackgroundWindowMask, could theoretically handle this without private API by
- // creating a window with the appropriate properties and then calling NSWindow.backgroundColor.patternImage,
- // which returns a texture sized 1 by (window height, including frame), backed by a CGPattern
- // which follows the window key state... probably need to allow QBrush to store a function pointer
- // like CGPattern does
- qWarning("Qt: qt_mac_toQBrush: cannot convert from NSMetalPatternColor");
- return qtBrush;
- }
-
- // No public API to get these colors/stops;
- // both accurately obtained through runtime object inspection on OS X 10.11
- // (the NSColor object has NSGradient i-vars for both color groups)
- if (qt_mac_isSystemColorOrInstance(color, @"_sourceListBackgroundColor", @"NSSourceListBackgroundColor")) {
- QLinearGradient gradient;
- if (colorGroup == QPalette::Active) {
- gradient.setColorAt(0, QColor(233, 237, 242));
- gradient.setColorAt(0.5, QColor(225, 229, 235));
- gradient.setColorAt(1, QColor(209, 216, 224));
- } else {
- gradient.setColorAt(0, QColor(248, 248, 248));
- gradient.setColorAt(0.5, QColor(240, 240, 240));
- gradient.setColorAt(1, QColor(235, 235, 235));
- }
- return QBrush(gradient);
- }
-
- // A couple colors are special... they are actually instances of NSGradientPatternColor, which
- // override set/setFill/setStroke to instead initialize an internal color
- // ([NSColor colorWithCalibratedWhite:0.909804 alpha:1.000000]) while still returning the
- // ruled lines pattern image (from OS X 10.4) to the user from -[NSColor patternImage]
- // (and providing no public API to get the underlying color without this insanity)
- if (qt_mac_isSystemColorOrInstance(color, @"controlColor", @"NSGradientPatternColor") ||
- qt_mac_isSystemColorOrInstance(color, @"windowBackgroundColor", @"NSGradientPatternColor")) {
- static QColor newColor;
- if (!newColor.isValid()) {
-#if QT_MAC_PLATFORM_SDK_EQUAL_OR_ABOVE(__MAC_10_8, __IPHONE_NA)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_8) {
- newColor = qt_mac_toQColor(color.CGColor);
- } else
-#endif
- {
- NSBitmapImageRep *offscreenRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
- pixelsWide:1
- pixelsHigh:1
- bitsPerSample:8
- samplesPerPixel:4
- hasAlpha:YES
- isPlanar:NO
- colorSpaceName:NSDeviceRGBColorSpace
- bytesPerRow:4
- bitsPerPixel:32];
- [NSGraphicsContext saveGraphicsState];
- [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep]];
- NSEraseRect(NSMakeRect(0, 0, 1, 1));
- [color drawSwatchInRect:NSMakeRect(0, 0, 1, 1)];
- [NSGraphicsContext restoreGraphicsState];
- NSUInteger pixel[4];
- [offscreenRep getPixel:pixel atX:0 y:0];
- [offscreenRep release];
- newColor = QColor(pixel[0], pixel[1], pixel[2], pixel[3]);
- }
- }
-
- qtBrush.setStyle(Qt::SolidPattern);
- qtBrush.setColor(newColor);
- return qtBrush;
- }
-
- if (NSColor *patternColor = [color colorUsingColorSpaceName:NSPatternColorSpace]) {
- NSImage *patternImage = patternColor.patternImage;
- const QSizeF sz(patternImage.size.width, patternImage.size.height);
- qtBrush.setTexture(qt_mac_toQPixmap(patternImage, sz)); // QTBUG-49774
- } else {
- qtBrush.setStyle(Qt::SolidPattern);
- qtBrush.setColor(qt_mac_toQColor(color));
- }
- return qtBrush;
-}
-
struct dndenum_mapper
{
NSDragOperation mac_code;
@@ -446,7 +143,30 @@ Qt::DropActions qt_mac_mapNSDragOperations(NSDragOperation nsActions)
return actions;
}
+/*!
+ Returns the view cast to a QNSview if possible.
+
+ If the view is not a QNSView, nil is returned, which is safe to
+ send messages to, effectivly making [qnsview_cast(view) message]
+ a no-op.
+ For extra verbosity and clearer code, please consider checking
+ that window()->type() != Qt::ForeignWindow before using this cast.
+
+ Do not use this method soley to check for foreign windows, as
+ that will make the code harder to read for people not working
+ primarily on macOS, who do not know the difference between the
+ NSView and QNSView cases.
+*/
+QNSView *qnsview_cast(NSView *view)
+{
+ if (![view isKindOfClass:[QNSView class]]) {
+ qCWarning(lcQpaCocoaWindow) << "NSView is not QNSView, consider checking for Qt::ForeignWindow";
+ return nil;
+ }
+
+ return static_cast<QNSView *>(view);
+}
//
// Misc
@@ -464,7 +184,7 @@ void qt_mac_transformProccessToForegroundApplication()
// Officially it's supposed to be a string, a boolean makes sense, so we'll check.
// A number less so, but OK.
if (valueType == CFStringGetTypeID())
- forceTransform = !(QCFString::toQString(static_cast<CFStringRef>(value)).toInt());
+ forceTransform = !(QString::fromCFString(static_cast<CFStringRef>(value)).toInt());
else if (valueType == CFBooleanGetTypeID())
forceTransform = !CFBooleanGetValue(static_cast<CFBooleanRef>(value));
else if (valueType == CFNumberGetTypeID()) {
@@ -482,7 +202,7 @@ void qt_mac_transformProccessToForegroundApplication()
if (valueType == CFBooleanGetTypeID())
forceTransform = !CFBooleanGetValue(static_cast<CFBooleanRef>(value));
else if (valueType == CFStringGetTypeID())
- forceTransform = !(QCFString::toQString(static_cast<CFStringRef>(value)).toInt());
+ forceTransform = !(QString::fromCFString(static_cast<CFStringRef>(value)).toInt());
else if (valueType == CFNumberGetTypeID()) {
int valueAsInt;
CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberIntType, &valueAsInt);
@@ -495,104 +215,13 @@ void qt_mac_transformProccessToForegroundApplication()
[[NSApplication sharedApplication] setActivationPolicy:NSApplicationActivationPolicyRegular];
}
}
-static CGColorSpaceRef m_genericColorSpace = 0;
-static QHash<CGDirectDisplayID, CGColorSpaceRef> m_displayColorSpaceHash;
-static bool m_postRoutineRegistered = false;
-
-CGColorSpaceRef qt_mac_genericColorSpace()
-{
-#if 0
- if (!m_genericColorSpace) {
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
- m_genericColorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
- } else
- {
- m_genericColorSpace = CGColorSpaceCreateDeviceRGB();
- }
- if (!m_postRoutineRegistered) {
- m_postRoutineRegistered = true;
- qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
- }
- }
- return m_genericColorSpace;
-#else
- // Just return the main display colorspace for the moment.
- return qt_mac_displayColorSpace(0);
-#endif
-}
-
-/*
- Ideally, we should pass the widget in here, and use CGGetDisplaysWithRect() etc.
- to support multiple displays correctly.
-*/
-CGColorSpaceRef qt_mac_displayColorSpace(const QWidget *widget)
-{
- CGColorSpaceRef colorSpace;
-
- CGDirectDisplayID displayID;
- if (widget == 0) {
- displayID = CGMainDisplayID();
- } else {
- displayID = CGMainDisplayID();
- /*
- ### get correct display
- const QRect &qrect = widget->window()->geometry();
- CGRect rect = CGRectMake(qrect.x(), qrect.y(), qrect.width(), qrect.height());
- CGDisplayCount throwAway;
- CGDisplayErr dErr = CGGetDisplaysWithRect(rect, 1, &displayID, &throwAway);
- if (dErr != kCGErrorSuccess)
- return macDisplayColorSpace(0); // fall back on main display
- */
- }
- if ((colorSpace = m_displayColorSpaceHash.value(displayID)))
- return colorSpace;
-
- colorSpace = CGDisplayCopyColorSpace(displayID);
- if (colorSpace == 0)
- colorSpace = CGColorSpaceCreateDeviceRGB();
-
- m_displayColorSpaceHash.insert(displayID, colorSpace);
- if (!m_postRoutineRegistered) {
- m_postRoutineRegistered = true;
- void qt_mac_cleanUpMacColorSpaces();
- qAddPostRoutine(qt_mac_cleanUpMacColorSpaces);
- }
- return colorSpace;
-}
-
-void qt_mac_cleanUpMacColorSpaces()
-{
- if (m_genericColorSpace) {
- CFRelease(m_genericColorSpace);
- m_genericColorSpace = 0;
- }
- QHash<CGDirectDisplayID, CGColorSpaceRef>::const_iterator it = m_displayColorSpaceHash.constBegin();
- while (it != m_displayColorSpaceHash.constEnd()) {
- if (it.value())
- CFRelease(it.value());
- ++it;
- }
- m_displayColorSpaceHash.clear();
-}
-
-CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice)
-{
-#ifdef QT_NO_WIDGETS
- Q_UNUSED(paintDevice)
- return qt_mac_displayColorSpace(0);
-#else
- bool isWidget = (paintDevice->devType() == QInternal::Widget);
- return qt_mac_displayColorSpace(isWidget ? static_cast<const QWidget *>(paintDevice): 0);
-#endif
-
-}
QString qt_mac_applicationName()
{
QString appName;
CFTypeRef string = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), CFSTR("CFBundleName"));
if (string)
- appName = QCFString::toQString(static_cast<CFStringRef>(string));
+ appName = QString::fromCFString(static_cast<CFStringRef>(string));
if (appName.isEmpty()) {
QString arg0 = QGuiApplicationPrivate::instance()->appName();
@@ -650,28 +279,6 @@ NSRect qt_mac_flipRect(const QRect &rect)
return NSMakeRect(rect.x(), flippedY, rect.width(), rect.height());
}
-OSStatus qt_mac_drawCGImage(CGContextRef inContext, const CGRect *inBounds, CGImageRef inImage)
-{
- // Verbatim copy if HIViewDrawCGImage (as shown on Carbon-Dev)
- OSStatus err = noErr;
-
- require_action(inContext != NULL, InvalidContext, err = paramErr);
- require_action(inBounds != NULL, InvalidBounds, err = paramErr);
- require_action(inImage != NULL, InvalidImage, err = paramErr);
-
- CGContextSaveGState( inContext );
- CGContextTranslateCTM (inContext, 0, inBounds->origin.y + CGRectGetMaxY(*inBounds));
- CGContextScaleCTM(inContext, 1, -1);
-
- CGContextDrawImage(inContext, *inBounds, inImage);
-
- CGContextRestoreGState(inContext);
-InvalidImage:
-InvalidBounds:
-InvalidContext:
- return err;
-}
-
Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum)
{
if (buttonNum == 0)
@@ -687,146 +294,9 @@ Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum)
return Qt::NoButton;
}
-bool qt_mac_execute_apple_script(const char *script, long script_len, AEDesc *ret) {
- OSStatus err;
- AEDesc scriptTextDesc;
- ComponentInstance theComponent = 0;
- OSAID scriptID = kOSANullScript, resultID = kOSANullScript;
-
- // set up locals to a known state
- AECreateDesc(typeNull, 0, 0, &scriptTextDesc);
- scriptID = kOSANullScript;
- resultID = kOSANullScript;
-
- // open the scripting component
- theComponent = OpenDefaultComponent(kOSAComponentType, typeAppleScript);
- if (!theComponent) {
- err = paramErr;
- goto bail;
- }
-
- // put the script text into an aedesc
- err = AECreateDesc(typeUTF8Text, script, script_len, &scriptTextDesc);
- if (err != noErr)
- goto bail;
-
- // compile the script
- err = OSACompile(theComponent, &scriptTextDesc, kOSAModeNull, &scriptID);
- if (err != noErr)
- goto bail;
-
- // run the script
- err = OSAExecute(theComponent, scriptID, kOSANullScript, kOSAModeNull, &resultID);
-
- // collect the results - if any
- if (ret) {
- AECreateDesc(typeNull, 0, 0, ret);
- if (err == errOSAScriptError)
- OSAScriptError(theComponent, kOSAErrorMessage, typeChar, ret);
- else if (err == noErr && resultID != kOSANullScript)
- OSADisplay(theComponent, resultID, typeChar, kOSAModeNull, ret);
- }
-bail:
- AEDisposeDesc(&scriptTextDesc);
- if (scriptID != kOSANullScript)
- OSADispose(theComponent, scriptID);
- if (resultID != kOSANullScript)
- OSADispose(theComponent, resultID);
- if (theComponent)
- CloseComponent(theComponent);
- return err == noErr;
-}
-
-bool qt_mac_execute_apple_script(const char *script, AEDesc *ret)
-{
- return qt_mac_execute_apple_script(script, qstrlen(script), ret);
-}
-
-bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret)
-{
- const QByteArray l = script.toUtf8(); return qt_mac_execute_apple_script(l.constData(), l.size(), ret);
-}
-
QString qt_mac_removeAmpersandEscapes(QString s)
{
return QPlatformTheme::removeMnemonics(s).trimmed();
}
-/*! \internal
-
- Returns the CoreGraphics CGContextRef of the paint device. 0 is
- returned if it can't be obtained. It is the caller's responsibility to
- CGContextRelease the context when finished using it.
-
- \warning This function is only available on \macos.
- \warning This function is duplicated in qmacstyle_mac.mm
- */
-CGContextRef qt_mac_cg_context(QPaintDevice *pdev)
-{
- // In Qt 5, QWidget and QPixmap (and QImage) paint devices are all QImages under the hood.
- QImage *image = 0;
- if (pdev->devType() == QInternal::Image) {
- image = static_cast<QImage *>(pdev);
- } else if (pdev->devType() == QInternal::Pixmap) {
-
- const QPixmap *pm = static_cast<const QPixmap*>(pdev);
- QPlatformPixmap *data = const_cast<QPixmap *>(pm)->data_ptr().data();
- if (data && data->classId() == QPlatformPixmap::RasterClass) {
- image = data->buffer();
- } else {
- qDebug("qt_mac_cg_context: Unsupported pixmap class");
- }
- } else if (pdev->devType() == QInternal::Widget) {
- // TODO test: image = static_cast<QImage *>(static_cast<const QWidget *>(pdev)->backingStore()->paintDevice());
- qDebug("qt_mac_cg_context: not implemented: Widget class");
- }
-
- if (!image)
- return 0; // Context type not supported.
-
- CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pdev);
- uint flags = kCGImageAlphaPremultipliedFirst;
- flags |= kCGBitmapByteOrder32Host;
- CGContextRef ret = 0;
- ret = CGBitmapContextCreate(image->bits(), image->width(), image->height(),
- 8, image->bytesPerLine(), colorspace, flags);
- CGContextTranslateCTM(ret, 0, image->height());
- CGContextScaleCTM(ret, 1, -1);
- return ret;
-}
-
-QPixmap qt_mac_toQPixmap(const NSImage *image, const QSizeF &size)
-{
- const NSSize pixmapSize = NSMakeSize(size.width(), size.height());
- QPixmap pixmap(pixmapSize.width, pixmapSize.height);
- pixmap.fill(Qt::transparent);
- [image setSize:pixmapSize];
- const NSRect iconRect = NSMakeRect(0, 0, pixmapSize.width, pixmapSize.height);
- QMacCGContext ctx(&pixmap);
- if (!ctx)
- return QPixmap();
- NSGraphicsContext *gc = [NSGraphicsContext qt_graphicsContextWithCGContext:ctx flipped:YES];
- if (!gc)
- return QPixmap();
- [NSGraphicsContext saveGraphicsState];
- [NSGraphicsContext setCurrentContext:gc];
- [image drawInRect:iconRect fromRect:iconRect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES hints:nil];
- [NSGraphicsContext restoreGraphicsState];
- return pixmap;
-}
-
-QImage qt_mac_toQImage(CGImageRef image)
-{
- const size_t w = CGImageGetWidth(image),
- h = CGImageGetHeight(image);
- QImage ret(w, h, QImage::Format_ARGB32_Premultiplied);
- ret.fill(Qt::transparent);
- CGRect rect = CGRectMake(0, 0, w, h);
- CGContextRef ctx = qt_mac_cg_context(&ret);
- qt_mac_drawCGImage(ctx, &rect, image);
- CGContextRelease(ctx);
- return ret;
-}
-
-
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/cocoa/qcocoainputcontext.mm b/src/plugins/platforms/cocoa/qcocoainputcontext.mm
index 04d6d6b806..9e3d747cd7 100644
--- a/src/plugins/platforms/cocoa/qcocoainputcontext.mm
+++ b/src/plugins/platforms/cocoa/qcocoainputcontext.mm
@@ -41,6 +41,7 @@
#include "qcocoainputcontext.h"
#include "qcocoanativeinterface.h"
#include "qcocoawindow.h"
+#include "qcocoahelpers.h"
#include <Carbon/Carbon.h>
@@ -102,7 +103,8 @@ void QCocoaInputContext::reset()
if (!mWindow)
return;
- QNSView *view = static_cast<QCocoaWindow *>(mWindow->handle())->qtView();
+ QCocoaWindow *window = static_cast<QCocoaWindow *>(mWindow->handle());
+ QNSView *view = qnsview_cast(window->view());
if (!view)
return;
@@ -131,7 +133,7 @@ void QCocoaInputContext::updateLocale()
CFArrayRef languages = (CFArrayRef) TISGetInputSourceProperty(source, kTISPropertyInputSourceLanguages);
if (CFArrayGetCount(languages) > 0) {
CFStringRef langRef = (CFStringRef)CFArrayGetValueAtIndex(languages, 0);
- QString name = QCFString::toQString(langRef);
+ QString name = QString::fromCFString(langRef);
QLocale locale(name);
if (m_locale != locale) {
m_locale = locale;
diff --git a/src/plugins/platforms/cocoa/qcocoaintegration.h b/src/plugins/platforms/cocoa/qcocoaintegration.h
index 9b0b5959a4..32f6fe0af1 100644
--- a/src/plugins/platforms/cocoa/qcocoaintegration.h
+++ b/src/plugins/platforms/cocoa/qcocoaintegration.h
@@ -54,7 +54,7 @@
#include <QtCore/QScopedPointer>
#include <qpa/qplatformintegration.h>
-#include <QtPlatformSupport/private/qcoretextfontdatabase_p.h>
+#include <QtFontDatabaseSupport/private/qcoretextfontdatabase_p.h>
QT_BEGIN_NAMESPACE
@@ -130,7 +130,9 @@ public:
#ifndef QT_NO_ACCESSIBILITY
QCocoaAccessibility *accessibility() const Q_DECL_OVERRIDE;
#endif
+#ifndef QT_NO_CLIPBOARD
QCocoaClipboard *clipboard() const Q_DECL_OVERRIDE;
+#endif
QCocoaDrag *drag() const Q_DECL_OVERRIDE;
QStringList themeNames() const Q_DECL_OVERRIDE;
@@ -169,7 +171,9 @@ private:
#endif
QScopedPointer<QPlatformTheme> mPlatformTheme;
QList<QCocoaScreen *> mScreens;
+#ifndef QT_NO_CLIPBOARD
QCocoaClipboard *mCocoaClipboard;
+#endif
QScopedPointer<QCocoaDrag> mCocoaDrag;
QScopedPointer<QCocoaNativeInterface> mNativeInterface;
QScopedPointer<QCocoaServices> mServices;
diff --git a/src/plugins/platforms/cocoa/qcocoaintegration.mm b/src/plugins/platforms/cocoa/qcocoaintegration.mm
index e481cede17..92fffb4d15 100644
--- a/src/plugins/platforms/cocoa/qcocoaintegration.mm
+++ b/src/plugins/platforms/cocoa/qcocoaintegration.mm
@@ -58,6 +58,8 @@
#include <qpa/qplatforminputcontextfactory_p.h>
#include <QtCore/qcoreapplication.h>
+#include <QtGui/private/qcoregraphics_p.h>
+
#include <IOKit/graphics/IOGraphicsLib.h>
static void initResources()
@@ -199,8 +201,6 @@ QWindow *QCocoaScreen::topLevelAt(const QPoint &point) const
return window;
}
-extern CGContextRef qt_mac_cg_context(const QPaintDevice *pdev);
-
QPixmap QCocoaScreen::grabWindow(WId window, int x, int y, int width, int height) const
{
// TODO window should be handled
@@ -251,9 +251,8 @@ QPixmap QCocoaScreen::grabWindow(WId window, int x, int y, int width, int height
QPixmap pix(w, h);
pix.fill(Qt::transparent);
CGRect rect = CGRectMake(0, 0, w, h);
- CGContextRef ctx = qt_mac_cg_context(&pix);
+ QMacCGContext ctx(&pix);
qt_mac_drawCGImage(ctx, &rect, image);
- CGContextRelease(ctx);
QPainter painter(&windowPixmap);
painter.drawPixmap(0, 0, pix);
@@ -283,7 +282,9 @@ QCocoaIntegration::QCocoaIntegration(const QStringList &paramList)
#ifndef QT_NO_ACCESSIBILITY
, mAccessibility(new QCocoaAccessibility)
#endif
+#ifndef QT_NO_CLIPBOARD
, mCocoaClipboard(new QCocoaClipboard)
+#endif
, mCocoaDrag(new QCocoaDrag)
, mNativeInterface(new QCocoaNativeInterface)
, mServices(new QCocoaServices)
@@ -329,10 +330,8 @@ QCocoaIntegration::QCocoaIntegration(const QStringList &paramList)
[cocoaApplication setDelegate:newDelegate];
// Load the application menu. This menu contains Preferences, Hide, Quit.
- QCocoaMenuLoader *qtMenuLoader = [[QCocoaMenuLoader alloc] init];
- qt_mac_loadMenuNib(qtMenuLoader);
+ QCocoaMenuLoader *qtMenuLoader = [QCocoaMenuLoader sharedMenuLoader];
[cocoaApplication setMenu:[qtMenuLoader menu]];
- [newDelegate setMenuLoader:qtMenuLoader];
}
// The presentation options such as whether or not the dock and/or menu bar is
@@ -366,11 +365,13 @@ QCocoaIntegration::~QCocoaIntegration()
[[NSApplication sharedApplication] setDelegate: 0];
}
+#ifndef QT_NO_CLIPBOARD
// Delete the clipboard integration and destroy mime type converters.
// Deleting the clipboard integration flushes promised pastes using
// the mime converters - the ordering here is important.
delete mCocoaClipboard;
QMacInternalPasteboardMime::destroyMimeTypes();
+#endif
// Delete screens in reverse order to avoid crash in case of multiple screens
while (!mScreens.isEmpty()) {
@@ -531,10 +532,12 @@ QCocoaAccessibility *QCocoaIntegration::accessibility() const
}
#endif
+#ifndef QT_NO_CLIPBOARD
QCocoaClipboard *QCocoaIntegration::clipboard() const
{
return mCocoaClipboard;
}
+#endif
QCocoaDrag *QCocoaIntegration::drag() const
{
diff --git a/src/plugins/platforms/cocoa/qcocoakeymapper.h b/src/plugins/platforms/cocoa/qcocoakeymapper.h
index 93ebc5b9dc..4ba615efeb 100644
--- a/src/plugins/platforms/cocoa/qcocoakeymapper.h
+++ b/src/plugins/platforms/cocoa/qcocoakeymapper.h
@@ -40,7 +40,7 @@
#ifndef QCOCOAKEYMAPPER_H
#define QCOCOAKEYMAPPER_H
-#include <qcocoahelpers.h>
+#include "qcocoahelpers.h"
#include <AppKit/AppKit.h>
#include <Carbon/Carbon.h>
diff --git a/src/plugins/platforms/cocoa/qcocoakeymapper.mm b/src/plugins/platforms/cocoa/qcocoakeymapper.mm
index 250f3f3bf7..e7952ae1f6 100644
--- a/src/plugins/platforms/cocoa/qcocoakeymapper.mm
+++ b/src/plugins/platforms/cocoa/qcocoakeymapper.mm
@@ -251,16 +251,20 @@ static qt_mac_enum_mapper qt_mac_private_unicode[] = {
{ 0xF72B, QT_MAC_MAP_ENUM(Qt::Key_End) }, //NSEndFunctionKey
{ 0xF72C, QT_MAC_MAP_ENUM(Qt::Key_PageUp) }, //NSPageUpFunctionKey
{ 0xF72D, QT_MAC_MAP_ENUM(Qt::Key_PageDown) }, //NSPageDownFunctionKey
+ { 0xF72E, QT_MAC_MAP_ENUM(Qt::Key_Print) }, //NSPrintScreenFunctionKey
{ 0xF72F, QT_MAC_MAP_ENUM(Qt::Key_ScrollLock) }, //NSScrollLockFunctionKey
{ 0xF730, QT_MAC_MAP_ENUM(Qt::Key_Pause) }, //NSPauseFunctionKey
{ 0xF731, QT_MAC_MAP_ENUM(Qt::Key_SysReq) }, //NSSysReqFunctionKey
{ 0xF735, QT_MAC_MAP_ENUM(Qt::Key_Menu) }, //NSMenuFunctionKey
- { 0xF738, QT_MAC_MAP_ENUM(Qt::Key_Print) }, //NSPrintFunctionKey
+ { 0xF738, QT_MAC_MAP_ENUM(Qt::Key_Printer) }, //NSPrintFunctionKey
{ 0xF73A, QT_MAC_MAP_ENUM(Qt::Key_Clear) }, //NSClearDisplayFunctionKey
{ 0xF73D, QT_MAC_MAP_ENUM(Qt::Key_Insert) }, //NSInsertCharFunctionKey
{ 0xF73E, QT_MAC_MAP_ENUM(Qt::Key_Delete) }, //NSDeleteCharFunctionKey
{ 0xF741, QT_MAC_MAP_ENUM(Qt::Key_Select) }, //NSSelectFunctionKey
{ 0xF742, QT_MAC_MAP_ENUM(Qt::Key_Execute) }, //NSExecuteFunctionKey
+ { 0xF743, QT_MAC_MAP_ENUM(Qt::Key_Undo) }, //NSUndoFunctionKey
+ { 0xF744, QT_MAC_MAP_ENUM(Qt::Key_Redo) }, //NSRedoFunctionKey
+ { 0xF745, QT_MAC_MAP_ENUM(Qt::Key_Find) }, //NSFindFunctionKey
{ 0xF746, QT_MAC_MAP_ENUM(Qt::Key_Help) }, //NSHelpFunctionKey
{ 0xF747, QT_MAC_MAP_ENUM(Qt::Key_Mode_switch) }, //NSModeSwitchFunctionKey
{ 0, QT_MAC_MAP_ENUM(0) }
@@ -384,7 +388,7 @@ bool QCocoaKeyMapper::updateKeyboard()
iso639Code = static_cast<CFStringRef>(CFArrayGetValueAtIndex(array, 0)); // Actually a RFC3066bis, but it's close enough
if (iso639Code) {
- keyboardInputLocale = QLocale(QCFString::toQString(iso639Code));
+ keyboardInputLocale = QLocale(QString::fromCFString(iso639Code));
keyboardInputDirection = keyboardInputLocale.textDirection();
} else {
keyboardInputLocale = QLocale::c();
diff --git a/src/plugins/platforms/cocoa/qcocoamenu.mm b/src/plugins/platforms/cocoa/qcocoamenu.mm
index 40d593cf0f..566363e01f 100644
--- a/src/plugins/platforms/cocoa/qcocoamenu.mm
+++ b/src/plugins/platforms/cocoa/qcocoamenu.mm
@@ -74,11 +74,6 @@ NSString *qt_mac_removePrivateUnicode(NSString* string)
return string;
}
-static inline QCocoaMenuLoader *getMenuLoader()
-{
- return [NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)];
-}
-
QT_END_NAMESPACE
@interface QT_MANGLE_NAMESPACE(QCocoaMenuDelegate) : NSObject <NSMenuDelegate> {
@@ -290,7 +285,7 @@ void QCocoaMenu::setText(const QString &text)
{
QMacAutoReleasePool pool;
QString stripped = qt_mac_removeAmpersandEscapes(text);
- [m_nativeMenu setTitle:QCFString::toNSString(stripped)];
+ [m_nativeMenu setTitle:stripped.toNSString()];
}
void QCocoaMenu::setMinimumWidth(int width)
@@ -301,7 +296,7 @@ void QCocoaMenu::setMinimumWidth(int width)
void QCocoaMenu::setFont(const QFont &font)
{
if (font.resolve()) {
- NSFont *customMenuFont = [NSFont fontWithName:QCFString::toNSString(font.family())
+ NSFont *customMenuFont = [NSFont fontWithName:font.family().toNSString()
size:font.pointSize()];
m_nativeMenu.font = customMenuFont;
}
@@ -414,7 +409,7 @@ void QCocoaMenu::syncMenuItem(QPlatformMenuItem *menuItem)
}
bool wasMerged = cocoaItem->isMerged();
- NSMenu *oldMenu = wasMerged ? [getMenuLoader() applicationMenu] : m_nativeMenu;
+ NSMenu *oldMenu = wasMerged ? [[QCocoaMenuLoader sharedMenuLoader] applicationMenu] : m_nativeMenu;
NSMenuItem *oldItem = [oldMenu itemWithTag:(NSInteger) cocoaItem];
if (cocoaItem->sync() != oldItem) {
@@ -500,7 +495,7 @@ void QCocoaMenu::showPopup(const QWindow *parentWindow, const QRect &targetRect,
QPoint pos = QPoint(targetRect.left(), targetRect.top() + targetRect.height());
QCocoaWindow *cocoaWindow = parentWindow ? static_cast<QCocoaWindow *>(parentWindow->handle()) : 0;
- NSView *view = cocoaWindow ? cocoaWindow->contentView() : nil;
+ NSView *view = cocoaWindow ? cocoaWindow->view() : nil;
NSMenuItem *nsItem = item ? ((QCocoaMenuItem *)item)->nsItem() : nil;
QScreen *screen = 0;
diff --git a/src/plugins/platforms/cocoa/qcocoamenubar.mm b/src/plugins/platforms/cocoa/qcocoamenubar.mm
index c6e9bd6373..a95ffc2f9f 100644
--- a/src/plugins/platforms/cocoa/qcocoamenubar.mm
+++ b/src/plugins/platforms/cocoa/qcocoamenubar.mm
@@ -52,11 +52,6 @@ QT_BEGIN_NAMESPACE
static QList<QCocoaMenuBar*> static_menubars;
-static inline QCocoaMenuLoader *getMenuLoader()
-{
- return [NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)];
-}
-
QCocoaMenuBar::QCocoaMenuBar() :
m_window(0)
{
@@ -356,7 +351,7 @@ void QCocoaMenuBar::updateMenuBarImmediately()
menu->propagateEnabledState(!disableForModal);
}
- QCocoaMenuLoader *loader = getMenuLoader();
+ QCocoaMenuLoader *loader = [QCocoaMenuLoader sharedMenuLoader];
[loader ensureAppMenuInMenu:mb->nsMenu()];
NSMutableSet *mergedItems = [[NSMutableSet setWithCapacity:0] retain];
diff --git a/src/plugins/platforms/cocoa/qcocoamenuitem.h b/src/plugins/platforms/cocoa/qcocoamenuitem.h
index d63f21f598..23f788687c 100644
--- a/src/plugins/platforms/cocoa/qcocoamenuitem.h
+++ b/src/plugins/platforms/cocoa/qcocoamenuitem.h
@@ -90,7 +90,9 @@ public:
void setIsSeparator(bool isSeparator) Q_DECL_OVERRIDE;
void setFont(const QFont &font) Q_DECL_OVERRIDE;
void setRole(MenuRole role) Q_DECL_OVERRIDE;
+#ifndef QT_NO_SHORTCUT
void setShortcut(const QKeySequence& shortcut) Q_DECL_OVERRIDE;
+#endif
void setCheckable(bool checkable) Q_DECL_OVERRIDE { Q_UNUSED(checkable) }
void setChecked(bool isChecked) Q_DECL_OVERRIDE;
void setEnabled(bool isEnabled) Q_DECL_OVERRIDE;
@@ -124,7 +126,9 @@ private:
QFont m_font;
MenuRole m_role;
MenuRole m_detectedRole;
+#ifndef QT_NO_SHORTCUT
QKeySequence m_shortcut;
+#endif
quintptr m_tag;
int m_iconSize;
bool m_textSynced:1;
diff --git a/src/plugins/platforms/cocoa/qcocoamenuitem.mm b/src/plugins/platforms/cocoa/qcocoamenuitem.mm
index 3979d7169a..b8a64641a8 100644
--- a/src/plugins/platforms/cocoa/qcocoamenuitem.mm
+++ b/src/plugins/platforms/cocoa/qcocoamenuitem.mm
@@ -48,17 +48,12 @@
#include "qt_mac_p.h"
#include "qcocoaapplication.h" // for custom application category
#include "qcocoamenuloader.h"
+#include <QtGui/private/qcoregraphics_p.h>
#include <QtCore/QDebug>
QT_BEGIN_NAMESPACE
-static inline QCocoaMenuLoader *getMenuLoader()
-{
- return [NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)];
-}
-
-
static quint32 constructModifierMask(quint32 accel_key)
{
quint32 ret = 0;
@@ -74,6 +69,7 @@ static quint32 constructModifierMask(quint32 accel_key)
return ret;
}
+#ifndef QT_NO_SHORTCUT
// return an autoreleased string given a QKeySequence (currently only looks at the first one).
NSString *keySequenceToKeyEqivalent(const QKeySequence &accel)
{
@@ -92,6 +88,7 @@ NSUInteger keySequenceModifierMask(const QKeySequence &accel)
{
return constructModifierMask(accel[0]);
}
+#endif
QCocoaMenuItem::QCocoaMenuItem() :
m_native(NULL),
@@ -189,10 +186,12 @@ void QCocoaMenuItem::setRole(MenuRole role)
m_role = role;
}
+#ifndef QT_NO_SHORTCUT
void QCocoaMenuItem::setShortcut(const QKeySequence& shortcut)
{
m_shortcut = shortcut;
}
+#endif
void QCocoaMenuItem::setChecked(bool isChecked)
{
@@ -234,7 +233,7 @@ NSMenuItem *QCocoaMenuItem::sync()
if ((m_role != NoRole && !m_textSynced) || m_merged) {
NSMenuItem *mergeItem = nil;
- QCocoaMenuLoader *loader = getMenuLoader();
+ QCocoaMenuLoader *loader = [QCocoaMenuLoader sharedMenuLoader];
switch (m_role) {
case ApplicationSpecificRole:
mergeItem = [loader appSpecificMenuItem:reinterpret_cast<NSInteger>(this)];
@@ -310,7 +309,7 @@ NSMenuItem *QCocoaMenuItem::sync()
}
if (!m_native) {
- m_native = [[NSMenuItem alloc] initWithTitle:QCFString::toNSString(m_text)
+ m_native = [[NSMenuItem alloc] initWithTitle:m_text.toNSString()
action:nil
keyEquivalent:@""];
[m_native setTag:reinterpret_cast<NSInteger>(this)];
@@ -320,36 +319,41 @@ NSMenuItem *QCocoaMenuItem::sync()
[m_native setView:m_itemView];
QString text = mergeText();
+#ifndef QT_NO_SHORTCUT
QKeySequence accel = mergeAccel();
// Show multiple key sequences as part of the menu text.
if (accel.count() > 1)
text += QLatin1String(" (") + accel.toString(QKeySequence::NativeText) + QLatin1String(")");
+#endif
QString finalString = QPlatformTheme::removeMnemonics(text);
bool useAttributedTitle = false;
// Cocoa Font and title
if (m_font.resolve()) {
- NSFont *customMenuFont = [NSFont fontWithName:QCFString::toNSString(m_font.family())
+ NSFont *customMenuFont = [NSFont fontWithName:m_font.family().toNSString()
size:m_font.pointSize()];
if (customMenuFont) {
NSArray *keys = [NSArray arrayWithObjects:NSFontAttributeName, nil];
NSArray *objects = [NSArray arrayWithObjects:customMenuFont, nil];
NSDictionary *attributes = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
- NSAttributedString *str = [[[NSAttributedString alloc] initWithString:QCFString::toNSString(finalString)
+ NSAttributedString *str = [[[NSAttributedString alloc] initWithString:finalString.toNSString()
attributes:attributes] autorelease];
[m_native setAttributedTitle: str];
useAttributedTitle = true;
}
}
if (!useAttributedTitle) {
- [m_native setTitle: QCFString::toNSString(finalString)];
+ [m_native setTitle:finalString.toNSString()];
}
+#ifndef QT_NO_SHORTCUT
if (accel.count() == 1) {
[m_native setKeyEquivalent:keySequenceToKeyEqivalent(accel)];
[m_native setKeyEquivalentModifierMask:keySequenceModifierMask(accel)];
- } else {
+ } else
+#endif
+ {
[m_native setKeyEquivalent:@""];
[m_native setKeyEquivalentModifierMask:NSCommandKeyMask];
}
@@ -372,7 +376,7 @@ QT_END_NAMESPACE
QString QCocoaMenuItem::mergeText()
{
- QCocoaMenuLoader *loader = getMenuLoader();
+ QCocoaMenuLoader *loader = [QCocoaMenuLoader sharedMenuLoader];
if (m_native == [loader aboutMenuItem]) {
return qt_mac_applicationmenu_string(6).arg(qt_mac_applicationName());
} else if (m_native== [loader aboutQtMenuItem]) {
@@ -390,9 +394,10 @@ QString QCocoaMenuItem::mergeText()
return m_text;
}
+#ifndef QT_NO_SHORTCUT
QKeySequence QCocoaMenuItem::mergeAccel()
{
- QCocoaMenuLoader *loader = getMenuLoader();
+ QCocoaMenuLoader *loader = [QCocoaMenuLoader sharedMenuLoader];
if (m_native == [loader preferencesMenuItem])
return QKeySequence(QKeySequence::Preferences);
else if (m_native == [loader quitMenuItem])
@@ -402,6 +407,7 @@ QKeySequence QCocoaMenuItem::mergeAccel()
return m_shortcut;
}
+#endif
void QCocoaMenuItem::syncMerged()
{
diff --git a/src/plugins/platforms/cocoa/qcocoamenuloader.h b/src/plugins/platforms/cocoa/qcocoamenuloader.h
index 6f58b2f24c..95f347646c 100644
--- a/src/plugins/platforms/cocoa/qcocoamenuloader.h
+++ b/src/plugins/platforms/cocoa/qcocoamenuloader.h
@@ -68,6 +68,8 @@
NSMenuItem *hideAllOthersItem;
NSMenuItem *showAllItem;
}
++ (instancetype)sharedMenuLoader;
+- (instancetype)init;
- (void)ensureAppMenuInMenu:(NSMenu *)menu;
- (void)removeActionsFromAppMenu;
- (NSMenu *)applicationMenu;
@@ -92,10 +94,4 @@
QT_NAMESPACE_ALIAS_OBJC_CLASS(QCocoaMenuLoader);
-QT_BEGIN_NAMESPACE
-
-void qt_mac_loadMenuNib(QCocoaMenuLoader *qtMenuLoader);
-
-QT_END_NAMESPACE
-
#endif // QCOCOAMENULOADER_P_H
diff --git a/src/plugins/platforms/cocoa/qcocoamenuloader.mm b/src/plugins/platforms/cocoa/qcocoamenuloader.mm
index e440a9080c..01a3c04afb 100644
--- a/src/plugins/platforms/cocoa/qcocoamenuloader.mm
+++ b/src/plugins/platforms/cocoa/qcocoamenuloader.mm
@@ -55,86 +55,127 @@
QT_FORWARD_DECLARE_CLASS(QCFString)
QT_FORWARD_DECLARE_CLASS(QString)
+@implementation QCocoaMenuLoader
-QT_BEGIN_NAMESPACE
-
-/*
- Loads and instantiates the main app menu from the menu nib file(s).
-
- The main app menu contains the Quit, Hide About, Preferences entries, and
- The reason for having the nib file is that those can not be created
- programmatically. To ease deployment the nib files are stored in Qt resources
- and written to QDir::temp() before loading. (Earlier Qt versions used
- to require having the nib file in the Qt GUI framework.)
-*/
-void qt_mac_loadMenuNib(QCocoaMenuLoader *qtMenuLoader)
++ (instancetype)sharedMenuLoader
{
- // Create qt_menu.nib dir in temp.
- QDir temp = QDir::temp();
- temp.mkdir("qt_menu.nib");
- QString nibDir = temp.canonicalPath() + QLatin1String("/") + QLatin1String("qt_menu.nib/");
- if (!QDir(nibDir).exists()) {
- qWarning("qt_mac_loadMenuNib: could not create nib directory in temp");
- return;
- }
-
- // Copy nib files from resources to temp.
- QDir nibResource(":/qt-project.org/mac/qt_menu.nib/");
- if (!nibResource.exists()) {
- qWarning("qt_mac_loadMenuNib: could not load nib from resources");
- return;
- }
- foreach (const QFileInfo &file, nibResource.entryInfoList()) {
- QFileInfo destinationFile(nibDir + QLatin1String("/") + file.fileName());
- if (destinationFile.exists() && destinationFile.size() != file.size())
- QFile::remove(destinationFile.absoluteFilePath());
+ static QCocoaMenuLoader *shared = nil;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ shared = [[self alloc] init];
+ });
+ return shared;
+}
- QFile::copy(file.absoluteFilePath(), destinationFile.absoluteFilePath());
+- (instancetype)init
+{
+ if ((self = [super init])) {
+ NSString *appName = qt_mac_applicationName().toNSString();
+
+ // Menubar as menu. Title as set in the NIB file
+ theMenu = [[NSMenu alloc] initWithTitle:@"Main Menu"];
+
+ // Application menu. Since 10.6, the first menu
+ // is always identified as the application menu.
+ NSMenuItem *appItem = [[[NSMenuItem alloc] init] autorelease];
+ appItem.title = appName;
+ [theMenu addItem:appItem];
+ appMenu = [[NSMenu alloc] initWithTitle:appName];
+ appItem.submenu = appMenu;
+
+ // About Application
+ aboutItem = [[NSMenuItem alloc] initWithTitle:[@"About " stringByAppendingString:appName]
+ action:@selector(orderFrontStandardAboutPanel:)
+ keyEquivalent:@""];
+ aboutItem.target = self;
+ // Disable until a QAction is associated
+ aboutItem.enabled = NO;
+ aboutItem.hidden = YES;
+ [appMenu addItem:aboutItem];
+
+ // About Qt (shameless self-promotion)
+ aboutQtItem = [[NSMenuItem alloc] init];
+ aboutQtItem.title = @"About Qt";
+ // Disable until a QAction is associated
+ aboutQtItem.enabled = NO;
+ aboutQtItem.hidden = YES;
+ [appMenu addItem:aboutQtItem];
+
+ [appMenu addItem:[NSMenuItem separatorItem]];
+
+ // Preferences
+ preferencesItem = [[NSMenuItem alloc] initWithTitle:@"Preferences…"
+ action:@selector(qtDispatcherToQPAMenuItem:)
+ keyEquivalent:@","];
+ preferencesItem.target = self;
+ // Disable until a QAction is associated
+ preferencesItem.enabled = NO;
+ preferencesItem.hidden = YES;
+ [appMenu addItem:preferencesItem];
+
+ [appMenu addItem:[NSMenuItem separatorItem]];
+
+ // Services item and menu
+ servicesItem = [[NSMenuItem alloc] init];
+ servicesItem.title = @"Services";
+ NSMenu *servicesMenu = [[[NSMenu alloc] initWithTitle:@"Services"] autorelease];
+ servicesItem.submenu = servicesMenu;
+ [NSApplication sharedApplication].servicesMenu = servicesMenu;
+ [appMenu addItem:servicesItem];
+
+ [appMenu addItem:[NSMenuItem separatorItem]];
+
+ // Hide Application
+ hideItem = [[NSMenuItem alloc] initWithTitle:[@"Hide " stringByAppendingString:appName]
+ action:@selector(hide:)
+ keyEquivalent:@"h"];
+ hideItem.target = self;
+ [appMenu addItem:hideItem];
+
+ // Hide Others
+ hideAllOthersItem = [[NSMenuItem alloc] initWithTitle:@"Hide Others"
+ action:@selector(hideOtherApplications:)
+ keyEquivalent:@"h"];
+ hideAllOthersItem.target = self;
+ hideAllOthersItem.keyEquivalentModifierMask = NSCommandKeyMask | NSAlternateKeyMask;
+ [appMenu addItem:hideAllOthersItem];
+
+ // Show All
+ showAllItem = [[NSMenuItem alloc] initWithTitle:@"Show All"
+ action:@selector(unhideAllApplications:)
+ keyEquivalent:@""];
+ showAllItem.target = self;
+ [appMenu addItem:showAllItem];
+
+ [appMenu addItem:[NSMenuItem separatorItem]];
+
+ // Quit Application
+ quitItem = [[NSMenuItem alloc] initWithTitle:[@"Quit " stringByAppendingString:appName]
+ action:@selector(terminate:)
+ keyEquivalent:@"q"];
+ quitItem.target = self;
+ [appMenu addItem:quitItem];
}
- // Load and instantiate nib file from temp
- NSURL *nibUrl = [NSURL fileURLWithPath : QCFString::toNSString(nibDir)];
- NSNib *nib = [[NSNib alloc] initWithContentsOfURL : nibUrl];
- [nib autorelease];
- if(!nib) {
- qWarning("qt_mac_loadMenuNib: could not load nib from temp");
- return;
- }
- bool ok = [nib instantiateNibWithOwner : qtMenuLoader topLevelObjects : nil];
- if (!ok) {
- qWarning("qt_mac_loadMenuNib: could not instantiate nib");
- }
+ return self;
}
-QT_END_NAMESPACE
+- (void)dealloc
+{
+ [theMenu release];
+ [appMenu release];
+ [aboutItem release];
+ [aboutQtItem release];
+ [preferencesItem release];
+ [servicesItem release];
+ [hideItem release];
+ [hideAllOthersItem release];
+ [showAllItem release];
+ [quitItem release];
-@implementation QCocoaMenuLoader
+ [lastAppSpecificItem release];
-- (void)awakeFromNib
-{
- servicesItem = [[appMenu itemWithTitle:@"Services"] retain];
- hideAllOthersItem = [[appMenu itemWithTitle:@"Hide Others"] retain];
- showAllItem = [[appMenu itemWithTitle:@"Show All"] retain];
-
- // Get the names in the nib to match the app name set by Qt.
- const NSString *appName = qt_mac_applicationName().toNSString();
- [quitItem setTitle:[[quitItem title] stringByReplacingOccurrencesOfString:@"NewApplication"
- withString:const_cast<NSString *>(appName)]];
- [hideItem setTitle:[[hideItem title] stringByReplacingOccurrencesOfString:@"NewApplication"
- withString:const_cast<NSString *>(appName)]];
- [aboutItem setTitle:[[aboutItem title] stringByReplacingOccurrencesOfString:@"NewApplication"
- withString:const_cast<NSString *>(appName)]];
- // Disable the items that don't do anything. If someone associates a QAction with them
- // They should get synced back in.
- [preferencesItem setEnabled:NO];
- [preferencesItem setHidden:YES];
-
- // should set this in the NIB
- [preferencesItem setTarget: self];
- [preferencesItem setAction: @selector(qtDispatcherToQPAMenuItem:)];
-
- [aboutItem setEnabled:NO];
- [aboutItem setHidden:YES];
+ [super dealloc];
}
- (void)ensureAppMenuInMenu:(NSMenu *)menu
@@ -179,18 +220,6 @@ QT_END_NAMESPACE
[item setTag:0];
}
-- (void)dealloc
-{
- [servicesItem release];
- [hideAllOthersItem release];
- [showAllItem release];
-
- [lastAppSpecificItem release];
- [theMenu release];
- [appMenu release];
- [super dealloc];
-}
-
- (NSMenu *)menu
{
return [[theMenu retain] autorelease];
@@ -285,13 +314,13 @@ QT_END_NAMESPACE
{
#ifndef QT_NO_TRANSLATION
- [servicesItem setTitle: QCFString::toNSString(qt_mac_applicationmenu_string(0))];
- [hideItem setTitle: QCFString::toNSString(qt_mac_applicationmenu_string(1).arg(qt_mac_applicationName()))];
- [hideAllOthersItem setTitle: QCFString::toNSString(qt_mac_applicationmenu_string(2))];
- [showAllItem setTitle: QCFString::toNSString(qt_mac_applicationmenu_string(3))];
- [preferencesItem setTitle: QCFString::toNSString(qt_mac_applicationmenu_string(4))];
- [quitItem setTitle: QCFString::toNSString(qt_mac_applicationmenu_string(5).arg(qt_mac_applicationName()))];
- [aboutItem setTitle: QCFString::toNSString(qt_mac_applicationmenu_string(6).arg(qt_mac_applicationName()))];
+ [servicesItem setTitle:qt_mac_applicationmenu_string(0).toNSString()];
+ [hideItem setTitle:qt_mac_applicationmenu_string(1).arg(qt_mac_applicationName()).toNSString()];
+ [hideAllOthersItem setTitle:qt_mac_applicationmenu_string(2).toNSString()];
+ [showAllItem setTitle:qt_mac_applicationmenu_string(3).toNSString()];
+ [preferencesItem setTitle:qt_mac_applicationmenu_string(4).toNSString()];
+ [quitItem setTitle:qt_mac_applicationmenu_string(5).arg(qt_mac_applicationName()).toNSString()];
+ [aboutItem setTitle:qt_mac_applicationmenu_string(6).arg(qt_mac_applicationName()).toNSString()];
#endif
}
diff --git a/src/plugins/platforms/cocoa/qcocoamimetypes.mm b/src/plugins/platforms/cocoa/qcocoamimetypes.mm
index e7a3aab845..093f86da6e 100644
--- a/src/plugins/platforms/cocoa/qcocoamimetypes.mm
+++ b/src/plugins/platforms/cocoa/qcocoamimetypes.mm
@@ -38,8 +38,9 @@
****************************************************************************/
#include "qcocoamimetypes.h"
-#include <QtPlatformSupport/private/qmacmime_p.h>
+#include <QtClipboardSupport/private/qmacmime_p.h>
#include "qcocoahelpers.h"
+#include <QtGui/private/qcoregraphics_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/cocoa/qcocoanativeinterface.h b/src/plugins/platforms/cocoa/qcocoanativeinterface.h
index b06fff1375..26fbe3e4bc 100644
--- a/src/plugins/platforms/cocoa/qcocoanativeinterface.h
+++ b/src/plugins/platforms/cocoa/qcocoanativeinterface.h
@@ -122,9 +122,6 @@ private:
static CGImageRef qImageToCGImage(const QImage &image);
static QImage cgImageToQImage(CGImageRef image);
- // Embedding NSViews as child QWindows
- static void setWindowContentView(QPlatformWindow *window, void *nsViewContentView);
-
// Set a QWindow as a "guest" (subwindow) of a non-QWindow
static void setEmbeddedInForeignView(QPlatformWindow *window, bool embedded);
diff --git a/src/plugins/platforms/cocoa/qcocoanativeinterface.mm b/src/plugins/platforms/cocoa/qcocoanativeinterface.mm
index a327750ffd..972230349b 100644
--- a/src/plugins/platforms/cocoa/qcocoanativeinterface.mm
+++ b/src/plugins/platforms/cocoa/qcocoanativeinterface.mm
@@ -65,6 +65,8 @@
#include <qpa/qplatformprintersupport.h>
#endif
+#include <QtGui/private/qcoregraphics_p.h>
+
#include <QtPlatformHeaders/qcocoawindowfunctions.h>
#include <AppKit/AppKit.h>
@@ -95,7 +97,7 @@ void *QCocoaNativeInterface::nativeResourceForWindow(const QByteArray &resourceS
return 0;
if (resourceString == "nsview") {
- return static_cast<QCocoaWindow *>(window->handle())->m_contentView;
+ return static_cast<QCocoaWindow *>(window->handle())->m_view;
#ifndef QT_NO_OPENGL
} else if (resourceString == "nsopenglcontext") {
return static_cast<QCocoaWindow *>(window->handle())->currentContext()->nsOpenGLContext();
@@ -124,8 +126,6 @@ QPlatformNativeInterface::NativeResourceForIntegrationFunction QCocoaNativeInter
return NativeResourceForIntegrationFunction(QCocoaNativeInterface::qImageToCGImage);
if (resource.toLower() == "cgimagetoqimage")
return NativeResourceForIntegrationFunction(QCocoaNativeInterface::cgImageToQImage);
- if (resource.toLower() == "setwindowcontentview")
- return NativeResourceForIntegrationFunction(QCocoaNativeInterface::setWindowContentView);
if (resource.toLower() == "registertouchwindow")
return NativeResourceForIntegrationFunction(QCocoaNativeInterface::registerTouchWindow);
if (resource.toLower() == "setembeddedinforeignview")
@@ -282,12 +282,6 @@ QImage QCocoaNativeInterface::cgImageToQImage(CGImageRef image)
return qt_mac_toQImage(image);
}
-void QCocoaNativeInterface::setWindowContentView(QPlatformWindow *window, void *contentView)
-{
- QCocoaWindow *cocoaPlatformWindow = static_cast<QCocoaWindow *>(window);
- cocoaPlatformWindow->setContentView(reinterpret_cast<NSView *>(contentView));
-}
-
void QCocoaNativeInterface::setEmbeddedInForeignView(QPlatformWindow *window, bool embedded)
{
QCocoaWindow *cocoaPlatformWindow = static_cast<QCocoaWindow *>(window);
diff --git a/src/plugins/platforms/cocoa/qcocoaprintdevice.mm b/src/plugins/platforms/cocoa/qcocoaprintdevice.mm
index d5fd523a37..39fcf285ed 100644
--- a/src/plugins/platforms/cocoa/qcocoaprintdevice.mm
+++ b/src/plugins/platforms/cocoa/qcocoaprintdevice.mm
@@ -71,13 +71,13 @@ QCocoaPrintDevice::QCocoaPrintDevice(const QString &id)
m_ppd(0)
{
if (!id.isEmpty()) {
- m_printer = PMPrinterCreateFromPrinterID(QCFString::toCFStringRef(id));
+ m_printer = PMPrinterCreateFromPrinterID(id.toCFString());
if (m_printer) {
- m_name = QCFString::toQString(PMPrinterGetName(m_printer));
- m_location = QCFString::toQString(PMPrinterGetLocation(m_printer));
+ m_name = QString::fromCFString(PMPrinterGetName(m_printer));
+ m_location = QString::fromCFString(PMPrinterGetLocation(m_printer));
CFStringRef cfMakeAndModel;
if (PMPrinterGetMakeAndModelName(m_printer, &cfMakeAndModel) == noErr)
- m_makeAndModel = QCFString::toQString(cfMakeAndModel);
+ m_makeAndModel = QString::fromCFString(cfMakeAndModel);
Boolean isRemote;
if (PMPrinterIsRemote(m_printer, &isRemote) == noErr)
m_isRemote = isRemote;
@@ -420,7 +420,7 @@ void QCocoaPrintDevice::loadMimeTypes() const
int count = CFArrayGetCount(mimeTypes);
for (int i = 0; i < count; ++i) {
CFStringRef mimeName = static_cast<CFStringRef>(const_cast<void *>(CFArrayGetValueAtIndex(mimeTypes, i)));
- QMimeType mimeType = db.mimeTypeForName(QCFString::toQString(mimeName));
+ QMimeType mimeType = db.mimeTypeForName(QString::fromCFString(mimeName));
if (mimeType.isValid())
m_mimeTypes.append(mimeType);
}
diff --git a/src/plugins/platforms/cocoa/qcocoaprintersupport.mm b/src/plugins/platforms/cocoa/qcocoaprintersupport.mm
index f8fc23f681..c2f7d5b022 100644
--- a/src/plugins/platforms/cocoa/qcocoaprintersupport.mm
+++ b/src/plugins/platforms/cocoa/qcocoaprintersupport.mm
@@ -82,7 +82,7 @@ QStringList QCocoaPrinterSupport::availablePrintDeviceIds() const
CFIndex count = CFArrayGetCount(printerList);
for (CFIndex i = 0; i < count; ++i) {
PMPrinter printer = static_cast<PMPrinter>(const_cast<void *>(CFArrayGetValueAtIndex(printerList, i)));
- list.append(QCFString::toQString(PMPrinterGetID(printer)));
+ list.append(QString::fromCFString(PMPrinterGetID(printer)));
}
}
return list;
@@ -96,7 +96,7 @@ QString QCocoaPrinterSupport::defaultPrintDeviceId() const
for (CFIndex i = 0; i < count; ++i) {
PMPrinter printer = static_cast<PMPrinter>(const_cast<void *>(CFArrayGetValueAtIndex(printerList, i)));
if (PMPrinterIsDefault(printer))
- return QCFString::toQString(PMPrinterGetID(printer));
+ return QString::fromCFString(PMPrinterGetID(printer));
}
}
return QString();
diff --git a/src/plugins/platforms/cocoa/qcocoaresources.qrc b/src/plugins/platforms/cocoa/qcocoaresources.qrc
index 9e0640db7d..4255bfba9d 100644
--- a/src/plugins/platforms/cocoa/qcocoaresources.qrc
+++ b/src/plugins/platforms/cocoa/qcocoaresources.qrc
@@ -9,9 +9,4 @@
<qresource prefix="/qt-project.org/mac/style">
<file>images/leopard-unified-toolbar-on.png</file>
</qresource>
-<qresource prefix="/qt-project.org/mac/">
-<file>qt_menu.nib/classes.nib</file>
-<file>qt_menu.nib/info.nib</file>
-<file>qt_menu.nib/keyedobjects.nib</file>
-</qresource>
</RCC>
diff --git a/src/plugins/platforms/cocoa/qcocoasystemsettings.mm b/src/plugins/platforms/cocoa/qcocoasystemsettings.mm
index be5fa61b8b..9ddad7fc7a 100644
--- a/src/plugins/platforms/cocoa/qcocoasystemsettings.mm
+++ b/src/plugins/platforms/cocoa/qcocoasystemsettings.mm
@@ -43,6 +43,7 @@
#include <QtCore/private/qcore_mac_p.h>
#include <QtGui/qfont.h>
+#include <QtGui/private/qcoregraphics_p.h>
#include <Carbon/Carbon.h>
diff --git a/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm b/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm
index 0cbdc5d9c8..6af22facf9 100644
--- a/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm
+++ b/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm
@@ -75,6 +75,9 @@
#define QT_MAC_SYSTEMTRAY_USE_GROWL
#include "qcocoasystemtrayicon.h"
+
+#ifndef QT_NO_SYSTEMTRAYICON
+
#include <qtemporaryfile.h>
#include <qimagewriter.h>
#include <qdebug.h>
@@ -83,6 +86,7 @@
#include "qt_mac_p.h"
#include "qcocoahelpers.h"
+#include <QtGui/private/qcoregraphics_p.h>
#import <AppKit/AppKit.h>
@@ -91,11 +95,8 @@ QT_USE_NAMESPACE
@class QT_MANGLE_NAMESPACE(QNSMenu);
@class QT_MANGLE_NAMESPACE(QNSImageView);
-@interface QT_MANGLE_NAMESPACE(QNSStatusItem) : NSObject
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
- <NSUserNotificationCenterDelegate>
-#endif
- {
+@interface QT_MANGLE_NAMESPACE(QNSStatusItem) : NSObject <NSUserNotificationCenterDelegate>
+{
@public
QCocoaSystemTrayIcon *systray;
NSStatusItem *item;
@@ -109,11 +110,8 @@ QT_USE_NAMESPACE
-(QRectF)geometry;
- (void)triggerSelector:(id)sender button:(Qt::MouseButton)mouseButton;
- (void)doubleClickSelector:(id)sender;
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification;
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification;
-#endif
@end
@interface QT_MANGLE_NAMESPACE(QNSImageView) : NSImageView {
@@ -142,19 +140,11 @@ class QSystemTrayIconSys
public:
QSystemTrayIconSys(QCocoaSystemTrayIcon *sys) {
item = [[QNSStatusItem alloc] initWithSysTray:sys];
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_8) {
- [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:item];
- }
-#endif
+ [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:item];
}
~QSystemTrayIconSys() {
[[[item item] view] setHidden: YES];
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_8) {
- [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:nil];
- }
-#endif
+ [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:nil];
[item release];
}
QNSStatusItem *item;
@@ -280,7 +270,7 @@ void QCocoaSystemTrayIcon::updateToolTip(const QString &toolTip)
{
if (!m_sys)
return;
- [[[m_sys->item item] view] setToolTip:QCFString::toNSString(toolTip)];
+ [[[m_sys->item item] view] setToolTip:toolTip.toNSString()];
}
bool QCocoaSystemTrayIcon::isSystemTrayAvailable() const
@@ -296,71 +286,15 @@ bool QCocoaSystemTrayIcon::supportsMessages() const
void QCocoaSystemTrayIcon::showMessage(const QString &title, const QString &message,
const QIcon& icon, MessageIcon, int)
{
+ Q_UNUSED(icon);
if (!m_sys)
return;
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_8) {
- NSUserNotification *notification = [[NSUserNotification alloc] init];
- notification.title = [NSString stringWithUTF8String:title.toUtf8().data()];
- notification.informativeText = [NSString stringWithUTF8String:message.toUtf8().data()];
-
- [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
+ NSUserNotification *notification = [[NSUserNotification alloc] init];
+ notification.title = [NSString stringWithUTF8String:title.toUtf8().data()];
+ notification.informativeText = [NSString stringWithUTF8String:message.toUtf8().data()];
- return;
- }
-#endif
-
-#ifdef QT_MAC_SYSTEMTRAY_USE_GROWL
- // Make sure that we have Growl installed on the machine we are running on.
- QCFType<CFURLRef> cfurl;
- OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator,
- CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
- if (status == kLSApplicationNotFoundErr)
- return;
- QCFType<CFBundleRef> bundle = CFBundleCreate(0, cfurl);
-
- if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"),
- kCFCompareCaseInsensitive | kCFCompareBackwards) != kCFCompareEqualTo)
- return;
- QPixmap notificationIconPixmap = icon.pixmap(32, 32);
- QTemporaryFile notificationIconFile;
- QString notificationType(QLatin1String("Notification")), notificationIcon, notificationApp(qt_mac_applicationName());
- if (notificationApp.isEmpty())
- notificationApp = QLatin1String("Application");
- if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
- QImageWriter writer(&notificationIconFile, "PNG");
- if (writer.write(notificationIconPixmap.toImage()))
- notificationIcon = QLatin1String("image from location \"file://") + notificationIconFile.fileName() + QLatin1String("\"");
- }
- const QString script(QLatin1String(
- "tell application \"System Events\"\n"
- "set isRunning to (count of (every process whose bundle identifier is \"com.Growl.GrowlHelperApp\")) > 0\n"
- "end tell\n"
- "if isRunning\n"
- "tell application id \"com.Growl.GrowlHelperApp\"\n"
- "-- Make a list of all the notification types (all)\n"
- "set the allNotificationsList to {\"") + notificationType + QLatin1String("\"}\n"
-
- "-- Make a list of the notifications (enabled)\n"
- "set the enabledNotificationsList to {\"") + notificationType + QLatin1String("\"}\n"
-
- "-- Register our script with growl.\n"
- "register as application \"") + notificationApp + QLatin1String("\" all notifications allNotificationsList default notifications enabledNotificationsList\n"
-
- "-- Send a Notification...\n") +
- QLatin1String("notify with name \"") + notificationType +
- QLatin1String("\" title \"") + title +
- QLatin1String("\" description \"") + message +
- QLatin1String("\" application name \"") + notificationApp +
- QLatin1String("\" ") + notificationIcon +
- QLatin1String("\nend tell\nend if"));
- qt_mac_execute_apple_script(script, 0);
-#else
- Q_UNUSED(icon);
- Q_UNUSED(title);
- Q_UNUSED(message);
-#endif
+ [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
}
QT_END_NAMESPACE
@@ -499,7 +433,6 @@ QT_END_NAMESPACE
emit systray->activated(QPlatformSystemTrayIcon::DoubleClick);
}
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification {
Q_UNUSED(center);
Q_UNUSED(notification);
@@ -511,7 +444,6 @@ QT_END_NAMESPACE
Q_UNUSED(notification);
emit systray->messageClicked();
}
-#endif
@end
@@ -536,3 +468,5 @@ private:
return qmenu;
}
@end
+
+#endif // QT_NO_SYSTEMTRAYICON
diff --git a/src/plugins/platforms/cocoa/qcocoatheme.h b/src/plugins/platforms/cocoa/qcocoatheme.h
index 282e527b0b..d47e620fbb 100644
--- a/src/plugins/platforms/cocoa/qcocoatheme.h
+++ b/src/plugins/platforms/cocoa/qcocoatheme.h
@@ -70,9 +70,7 @@ public:
const QPalette *palette(Palette type = SystemPalette) const Q_DECL_OVERRIDE;
const QFont *font(Font type = SystemFont) const Q_DECL_OVERRIDE;
QPixmap standardPixmap(StandardPixmap sp, const QSizeF &size) const Q_DECL_OVERRIDE;
- QPixmap fileIconPixmap(const QFileInfo &fileInfo,
- const QSizeF &size,
- QPlatformTheme::IconOptions options = 0) const Q_DECL_OVERRIDE;
+ QIcon fileIcon(const QFileInfo &fileInfo, QPlatformTheme::IconOptions options = 0) const override;
QVariant themeHint(ThemeHint hint) const Q_DECL_OVERRIDE;
QString standardButtonText(int button) const Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/cocoa/qcocoatheme.mm b/src/plugins/platforms/cocoa/qcocoatheme.mm
index 831f1cfcf4..4d74c11581 100644
--- a/src/plugins/platforms/cocoa/qcocoatheme.mm
+++ b/src/plugins/platforms/cocoa/qcocoatheme.mm
@@ -56,8 +56,10 @@
#include <QtCore/qfileinfo.h>
#include <QtGui/private/qguiapplication_p.h>
+#include <QtGui/private/qcoregraphics_p.h>
#include <QtGui/qpainter.h>
-#include <QtPlatformSupport/private/qcoretextfontdatabase_p.h>
+#include <QtFontDatabaseSupport/private/qcoretextfontdatabase_p.h>
+#include <QtThemeSupport/private/qabstractfileiconengine_p.h>
#include <qpa/qplatformintegration.h>
#include <qpa/qplatformnativeinterface.h>
@@ -136,8 +138,10 @@ bool QCocoaTheme::usePlatformNativeDialog(DialogType dialogType) const
QPlatformDialogHelper * QCocoaTheme::createPlatformDialogHelper(DialogType dialogType) const
{
switch (dialogType) {
+#ifndef QT_NO_FILEDIALOG
case QPlatformTheme::FileDialog:
return new QCocoaFileDialogHelper();
+#endif
#ifndef QT_NO_COLORDIALOG
case QPlatformTheme::ColorDialog:
return new QCocoaColorDialogHelper();
@@ -194,7 +198,7 @@ QPixmap qt_mac_convert_iconref(const IconRef icon, int width, int height)
CGRect rect = CGRectMake(0, 0, width, height);
- CGContextRef ctx = qt_mac_cg_context(&ret);
+ QMacCGContext ctx(&ret);
CGAffineTransform old_xform = CGContextGetCTM(ctx);
CGContextConcatCTM(ctx, CGAffineTransformInvert(old_xform));
CGContextConcatCTM(ctx, CGAffineTransformIdentity);
@@ -202,7 +206,6 @@ QPixmap qt_mac_convert_iconref(const IconRef icon, int width, int height)
::RGBColor b;
b.blue = b.green = b.red = 255*255;
PlotIconRefInContext(ctx, &rect, kAlignNone, kTransformNone, &b, kPlotIconRefNormalFlags, icon);
- CGContextRelease(ctx);
return ret;
}
@@ -274,16 +277,42 @@ QPixmap QCocoaTheme::standardPixmap(StandardPixmap sp, const QSizeF &size) const
return QPlatformTheme::standardPixmap(sp, size);
}
-QPixmap QCocoaTheme::fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &size,
- QPlatformTheme::IconOptions iconOptions) const
+class QCocoaFileIconEngine : public QAbstractFileIconEngine
{
- Q_UNUSED(iconOptions);
- QMacAutoReleasePool pool;
+public:
+ explicit QCocoaFileIconEngine(const QFileInfo &info,
+ QPlatformTheme::IconOptions opts) :
+ QAbstractFileIconEngine(info, opts) {}
+
+ static QList<QSize> availableIconSizes()
+ {
+ const qreal devicePixelRatio = qGuiApp->devicePixelRatio();
+ const int sizes[] = {
+ qRound(16 * devicePixelRatio), qRound(32 * devicePixelRatio),
+ qRound(64 * devicePixelRatio), qRound(128 * devicePixelRatio),
+ qRound(256 * devicePixelRatio)
+ };
+ return QAbstractFileIconEngine::toSizeList(sizes, sizes + sizeof(sizes) / sizeof(sizes[0]));
+ }
+
+ QList<QSize> availableSizes(QIcon::Mode = QIcon::Normal, QIcon::State = QIcon::Off) const override
+ { return QCocoaFileIconEngine::availableIconSizes(); }
+
+protected:
+ QPixmap filePixmap(const QSize &size, QIcon::Mode, QIcon::State) override
+ {
+ QMacAutoReleasePool pool;
- NSImage *iconImage = [[NSWorkspace sharedWorkspace] iconForFile:QCFString::toNSString(fileInfo.canonicalFilePath())];
- if (!iconImage)
- return QPixmap();
- return qt_mac_toQPixmap(iconImage, size);
+ NSImage *iconImage = [[NSWorkspace sharedWorkspace] iconForFile:fileInfo().canonicalFilePath().toNSString()];
+ if (!iconImage)
+ return QPixmap();
+ return qt_mac_toQPixmap(iconImage, size);
+ }
+};
+
+QIcon QCocoaTheme::fileIcon(const QFileInfo &fileInfo, QPlatformTheme::IconOptions iconOptions) const
+{
+ return QIcon(new QCocoaFileIconEngine(fileInfo, iconOptions));
}
QVariant QCocoaTheme::themeHint(ThemeHint hint) const
@@ -298,17 +327,12 @@ QVariant QCocoaTheme::themeHint(ThemeHint hint) const
case TabFocusBehavior:
return QVariant([[NSApplication sharedApplication] isFullKeyboardAccessEnabled] ?
int(Qt::TabFocusAllControls) : int(Qt::TabFocusTextControls | Qt::TabFocusListControls));
- case IconPixmapSizes: {
- qreal devicePixelRatio = qGuiApp->devicePixelRatio();
- QList<int> sizes;
- sizes << 16 * devicePixelRatio
- << 32 * devicePixelRatio
- << 64 * devicePixelRatio
- << 128 * devicePixelRatio;
- return QVariant::fromValue(sizes);
- }
+ case IconPixmapSizes:
+ return QVariant::fromValue(QCocoaFileIconEngine::availableIconSizes());
case QPlatformTheme::PasswordMaskCharacter:
return QVariant(QChar(kBulletUnicode));
+ case QPlatformTheme::UiEffects:
+ return QVariant(int(HoverEffect));
default:
break;
}
diff --git a/src/plugins/platforms/cocoa/qcocoawindow.h b/src/plugins/platforms/cocoa/qcocoawindow.h
index 849ed858d1..16639fd8b1 100644
--- a/src/plugins/platforms/cocoa/qcocoawindow.h
+++ b/src/plugins/platforms/cocoa/qcocoawindow.h
@@ -54,32 +54,6 @@
QT_FORWARD_DECLARE_CLASS(QCocoaWindow)
-QT_BEGIN_NAMESPACE
-
-class QCocoaWindowPointer
-{
-public:
- void assign(QCocoaWindow *w);
- void clear();
-
- QCocoaWindow *data() const
- { return watcher.isNull() ? Q_NULLPTR : window; }
- bool isNull() const
- { return watcher.isNull(); }
- operator QCocoaWindow*() const
- { return data(); }
- QCocoaWindow *operator->() const
- { return data(); }
- QCocoaWindow &operator*() const
- { return *data(); }
-
-private:
- QPointer<QObject> watcher;
- QCocoaWindow *window;
-};
-
-QT_END_NAMESPACE
-
@class QT_MANGLE_NAMESPACE(QNSWindowHelper);
@protocol QNSWindowProtocol
@@ -96,13 +70,13 @@ typedef NSWindow<QNSWindowProtocol> QCocoaNSWindow;
@interface QT_MANGLE_NAMESPACE(QNSWindowHelper) : NSObject
{
QCocoaNSWindow *_window;
- QCocoaWindowPointer _platformWindow;
+ QPointer<QCocoaWindow> _platformWindow;
BOOL _grabbingMouse;
BOOL _releaseOnMouseUp;
}
@property (nonatomic, readonly) QCocoaNSWindow *window;
-@property (nonatomic, readonly) QCocoaWindowPointer platformWindow;
+@property (nonatomic, readonly) QCocoaWindow *platformWindow;
@property (nonatomic) BOOL grabbingMouse;
@property (nonatomic) BOOL releaseOnMouseUp;
@@ -169,8 +143,9 @@ QT_BEGIN_NAMESPACE
class QCocoaMenuBar;
-class QCocoaWindow : public QPlatformWindow
+class QCocoaWindow : public QObject, public QPlatformWindow
{
+ Q_OBJECT
public:
QCocoaWindow(QWindow *tlw);
~QCocoaWindow();
@@ -207,9 +182,7 @@ public:
WId winId() const Q_DECL_OVERRIDE;
void setParent(const QPlatformWindow *window) Q_DECL_OVERRIDE;
- NSView *contentView() const;
- void setContentView(NSView *contentView);
- QNSView *qtView() const;
+ NSView *view() const;
NSWindow *nativeWindow() const;
void setEmbeddedInForeignView(bool subwindow);
@@ -219,6 +192,7 @@ public:
void windowDidResize();
void windowDidEndLiveResize();
bool windowShouldClose();
+ void windowWillClose();
bool windowIsPopupType(Qt::WindowType type = Qt::Widget) const;
void setSynchedWindowStateFromWindow();
@@ -277,6 +251,7 @@ protected:
void syncWindowState(Qt::WindowState newState);
void reinsertChildWindow(QCocoaWindow *child);
void removeChildWindow(QCocoaWindow *child);
+ bool isNativeWindowTypeInconsistent();
// private:
public: // for QNSView
@@ -285,14 +260,13 @@ public: // for QNSView
void removeMonitor();
- NSView *m_contentView;
- QNSView *m_qtView;
+ NSView *m_view;
QCocoaNSWindow *m_nsWindow;
- QCocoaWindowPointer m_forwardWindow;
+ QPointer<QCocoaWindow> m_forwardWindow;
// TODO merge to one variable if possible
- bool m_contentViewIsEmbedded; // true if the m_contentView is actually embedded in a "foreign" NSView hiearchy
- bool m_contentViewIsToBeEmbedded; // true if the m_contentView is intended to be embedded in a "foreign" NSView hiearchy
+ bool m_viewIsEmbedded; // true if the m_view is actually embedded in a "foreign" NSView hiearchy
+ bool m_viewIsToBeEmbedded; // true if the m_view is intended to be embedded in a "foreign" NSView hiearchy
QCocoaWindow *m_parentCocoaWindow;
bool m_isNSWindowChild; // this window is a non-top level QWindow with a NSWindow.
@@ -351,9 +325,6 @@ public: // for QNSView
QHash<quintptr, BorderRange> m_contentBorderAreas; // identifer -> uppper/lower
QHash<quintptr, bool> m_enabledContentBorderAreas; // identifer -> enabled state (true/false)
- // This object is tracked by QCocoaWindowPointer,
- // preventing the use of dangling pointers.
- QObject sentinel;
bool m_hasWindowFilePath;
};
diff --git a/src/plugins/platforms/cocoa/qcocoawindow.mm b/src/plugins/platforms/cocoa/qcocoawindow.mm
index b3cbf9f599..602da0a175 100644
--- a/src/plugins/platforms/cocoa/qcocoawindow.mm
+++ b/src/plugins/platforms/cocoa/qcocoawindow.mm
@@ -52,6 +52,7 @@
#include <private/qwindow_p.h>
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qplatformscreen.h>
+#include <QtGui/private/qcoregraphics_p.h>
#include <AppKit/AppKit.h>
@@ -78,19 +79,31 @@ static bool isMouseEvent(NSEvent *ev)
}
}
+static void qt_closePopups()
+{
+ while (QCocoaWindow *popup = QCocoaIntegration::instance()->popPopupWindow()) {
+ QWindowSystemInterface::handleCloseEvent(popup->window());
+ QWindowSystemInterface::flushWindowSystemEvents();
+ }
+}
+
@implementation QNSWindowHelper
@synthesize window = _window;
-@synthesize platformWindow = _platformWindow;
@synthesize grabbingMouse = _grabbingMouse;
@synthesize releaseOnMouseUp = _releaseOnMouseUp;
+- (QCocoaWindow *)platformWindow
+{
+ return _platformWindow.data();
+}
+
- (id)initWithNSWindow:(QCocoaNSWindow *)window platformWindow:(QCocoaWindow *)platformWindow
{
self = [super init];
if (self) {
_window = window;
- _platformWindow.assign(platformWindow);
+ _platformWindow = platformWindow;
_window.delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:_platformWindow];
@@ -109,7 +122,7 @@ static bool isMouseEvent(NSEvent *ev)
QCocoaWindow *pw = self.platformWindow;
if (pw && pw->m_forwardWindow) {
if (theEvent.type == NSLeftMouseUp || theEvent.type == NSLeftMouseDragged) {
- QNSView *forwardView = pw->m_qtView;
+ QNSView *forwardView = qnsview_cast(pw->view());
if (theEvent.type == NSLeftMouseUp) {
[forwardView mouseUp:theEvent];
pw->m_forwardWindow.clear();
@@ -150,18 +163,14 @@ static bool isMouseEvent(NSEvent *ev)
NSPoint loc = [theEvent locationInWindow];
NSRect windowFrame = [self.window convertRectFromScreen:[self.window frame]];
NSRect contentFrame = [[self.window contentView] frame];
- if (NSMouseInRect(loc, windowFrame, NO) &&
- !NSMouseInRect(loc, contentFrame, NO))
- {
- QNSView *contentView = pw->m_qtView;
- [contentView handleFrameStrutMouseEvent: theEvent];
- }
+ if (NSMouseInRect(loc, windowFrame, NO) && !NSMouseInRect(loc, contentFrame, NO))
+ [qnsview_cast(pw->view()) handleFrameStrutMouseEvent:theEvent];
}
}
- (void)detachFromPlatformWindow
{
- self.platformWindow.clear();
+ _platformWindow.clear();
[self.window.delegate release];
self.window.delegate = nil;
}
@@ -182,7 +191,7 @@ static bool isMouseEvent(NSEvent *ev)
- (void)dealloc
{
_window = nil;
- self.platformWindow.clear();
+ _platformWindow.clear();
[super dealloc];
}
@@ -334,27 +343,14 @@ static bool isMouseEvent(NSEvent *ev)
@end
-void QCocoaWindowPointer::assign(QCocoaWindow *w)
-{
- window = w;
- watcher = &w->sentinel;
-}
-
-void QCocoaWindowPointer::clear()
-{
- window = Q_NULLPTR;
- watcher.clear();
-}
-
const int QCocoaWindow::NoAlertRequest = -1;
QCocoaWindow::QCocoaWindow(QWindow *tlw)
: QPlatformWindow(tlw)
- , m_contentView(nil)
- , m_qtView(nil)
+ , m_view(nil)
, m_nsWindow(0)
- , m_contentViewIsEmbedded(false)
- , m_contentViewIsToBeEmbedded(false)
+ , m_viewIsEmbedded(false)
+ , m_viewIsToBeEmbedded(false)
, m_parentCocoaWindow(0)
, m_isNSWindowChild(false)
, m_effectivelyMaximized(false)
@@ -391,11 +387,9 @@ QCocoaWindow::QCocoaWindow(QWindow *tlw)
QMacAutoReleasePool pool;
if (tlw->type() == Qt::ForeignWindow) {
- NSView *foreignView = (NSView *)WId(tlw->property("_q_foreignWinId").value<WId>());
- setContentView(foreignView);
+ m_view = (NSView *)WId(tlw->property("_q_foreignWinId").value<WId>());
} else {
- m_qtView = [[QNSView alloc] initWithQWindow:tlw platformWindow:this];
- m_contentView = m_qtView;
+ m_view = [[QNSView alloc] initWithCocoaWindow:this];
// Enable high-dpi OpenGL for retina displays. Enabling has the side
// effect that Cocoa will start calling glViewport(0, 0, width, height),
// overriding any glViewport calls in application code. This is usually not a
@@ -404,14 +398,14 @@ QCocoaWindow::QCocoaWindow(QWindow *tlw)
if (tlw->supportsOpenGL()) {
BOOL enable = qt_mac_resolveOption(YES, tlw, "_q_mac_wantsBestResolutionOpenGLSurface",
"QT_MAC_WANTS_BEST_RESOLUTION_OPENGL_SURFACE");
- [m_contentView setWantsBestResolutionOpenGLSurface:enable];
+ [m_view setWantsBestResolutionOpenGLSurface:enable];
}
BOOL enable = qt_mac_resolveOption(NO, tlw, "_q_mac_wantsLayer",
"QT_MAC_WANTS_LAYER");
- [m_contentView setWantsLayer:enable];
+ [m_view setWantsLayer:enable];
}
setGeometry(tlw->geometry());
- recreateWindow(parent());
+ recreateWindow(QPlatformWindow::parent());
tlw->setGeometry(geometry());
if (tlw->isTopLevel())
setWindowIcon(tlw->icon());
@@ -429,25 +423,16 @@ QCocoaWindow::~QCocoaWindow()
if (m_isNSWindowChild) {
if (m_parentCocoaWindow)
m_parentCocoaWindow->removeChildWindow(this);
- } else if ([m_contentView superview]) {
- [m_contentView removeFromSuperview];
+ } else if ([m_view superview]) {
+ [m_view removeFromSuperview];
}
removeMonitor();
// Make sure to disconnect observer in all case if view is valid
// to avoid notifications received when deleting when using Qt::AA_NativeWindows attribute
- if (m_qtView) {
- [[NSNotificationCenter defaultCenter] removeObserver:m_qtView];
- }
-
- // The QNSView object may outlive the corresponding QCocoaWindow object,
- // for example during app shutdown when the QNSView is embedded in a
- // foregin NSView hiearchy. Clear the pointers to the QWindow/QCocoaWindow
- // here to make sure QNSView does not dereference stale pointers.
- if (m_qtView) {
- [m_qtView clearQWindowPointers];
- }
+ if (window()->type() != Qt::ForeignWindow)
+ [[NSNotificationCenter defaultCenter] removeObserver:m_view];
// While it is unlikely that this window will be in the popup stack
// during deletetion we clear any pointers here to make sure.
@@ -460,7 +445,7 @@ QCocoaWindow::~QCocoaWindow()
child->m_parentCocoaWindow = 0;
}
- [m_contentView release];
+ [m_view release];
[m_nsWindow release];
[m_windowCursor release];
}
@@ -501,12 +486,12 @@ QRect QCocoaWindow::geometry() const
// QWindows that are embedded in a NSView hiearchy may be considered
// top-level from Qt's point of view but are not from Cocoa's point
// of view. Embedded QWindows get global (screen) geometry.
- if (m_contentViewIsEmbedded) {
- NSPoint windowPoint = [m_contentView convertPoint:NSMakePoint(0, 0) toView:nil];
- NSRect screenRect = [[m_contentView window] convertRectToScreen:NSMakeRect(windowPoint.x, windowPoint.y, 1, 1)];
+ if (m_viewIsEmbedded) {
+ NSPoint windowPoint = [m_view convertPoint:NSMakePoint(0, 0) toView:nil];
+ NSRect screenRect = [[m_view window] convertRectToScreen:NSMakeRect(windowPoint.x, windowPoint.y, 1, 1)];
NSPoint screenPoint = screenRect.origin;
QPoint position = qt_mac_flipPoint(screenPoint).toPoint();
- QSize size = qt_mac_toQRect([m_contentView bounds]).size();
+ QSize size = QRectF::fromCGRect([m_view bounds]).toRect().size();
return QRect(position, size);
}
@@ -518,9 +503,9 @@ void QCocoaWindow::setCocoaGeometry(const QRect &rect)
qCDebug(lcQpaCocoaWindow) << "QCocoaWindow::setCocoaGeometry" << window() << rect;
QMacAutoReleasePool pool;
- if (m_contentViewIsEmbedded) {
- if (m_qtView) {
- [m_qtView setFrame:NSMakeRect(0, 0, rect.width(), rect.height())];
+ if (m_viewIsEmbedded) {
+ if (window()->type() != Qt::ForeignWindow) {
+ [m_view setFrame:NSMakeRect(0, 0, rect.width(), rect.height())];
} else {
QPlatformWindow::setGeometry(rect);
}
@@ -540,10 +525,10 @@ void QCocoaWindow::setCocoaGeometry(const QRect &rect)
NSRect bounds = qt_mac_flipRect(rect);
[m_nsWindow setFrame:[m_nsWindow frameRectForContentRect:bounds] display:YES animate:NO];
} else {
- [m_contentView setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
+ [m_view setFrame:NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
}
- if (!m_qtView)
+ if (window()->type() == Qt::ForeignWindow)
QPlatformWindow::setGeometry(rect);
// will call QPlatformWindow::setGeometry(rect) during resize confirmation (see qnsview.mm)
@@ -568,7 +553,7 @@ void QCocoaWindow::clipWindow(const NSRect &clipRect)
// Clipping top/left offsets the content. Move it back.
NSPoint contentViewOffset = NSMakePoint(qMax(CGFloat(0), NSMinX(clippedWindowRect) - NSMinX(windowFrame)),
qMax(CGFloat(0), NSMaxY(windowFrame) - NSMaxY(clippedWindowRect)));
- [m_contentView setBoundsOrigin:contentViewOffset];
+ [m_view setBoundsOrigin:contentViewOffset];
}
if (NSIsEmptyRect(clippedWindowRect)) {
@@ -653,8 +638,8 @@ void QCocoaWindow::setVisible(bool visible)
if (visible) {
// We need to recreate if the modality has changed as the style mask will need updating
- if (m_windowModality != window()->modality())
- recreateWindow(parent());
+ if (m_windowModality != window()->modality() || isNativeWindowTypeInconsistent())
+ recreateWindow(QPlatformWindow::parent());
// Register popup windows. The Cocoa platform plugin will forward mouse events
// to them and close them when needed.
@@ -739,8 +724,8 @@ void QCocoaWindow::setVisible(bool visible)
// In some cases, e.g. QDockWidget, the content view is hidden before moving to its own
// Cocoa window, and then shown again. Therefore, we test for the view being hidden even
// if it's attached to an NSWindow.
- if ([m_contentView isHidden])
- [m_contentView setHidden:NO];
+ if ([m_view isHidden])
+ [m_view setHidden:NO];
} else {
// qDebug() << "close" << this;
#ifndef QT_NO_OPENGL
@@ -773,7 +758,7 @@ void QCocoaWindow::setVisible(bool visible)
[mainWindow makeKeyWindow];
}
} else {
- [m_contentView setHidden:YES];
+ [m_view setHidden:YES];
}
removeMonitor();
@@ -938,7 +923,7 @@ void QCocoaWindow::setWindowTitle(const QString &title)
if (!m_nsWindow)
return;
- CFStringRef windowTitle = QCFString::toCFStringRef(title);
+ CFStringRef windowTitle = title.toCFString();
[m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
CFRelease(windowTitle);
}
@@ -950,7 +935,7 @@ void QCocoaWindow::setWindowFilePath(const QString &filePath)
return;
QFileInfo fi(filePath);
- [m_nsWindow setRepresentedFilename: fi.exists() ? QCFString::toNSString(filePath) : @""];
+ [m_nsWindow setRepresentedFilename:fi.exists() ? filePath.toNSString() : @""];
m_hasWindowFilePath = fi.exists();
}
@@ -962,7 +947,7 @@ void QCocoaWindow::setWindowIcon(const QIcon &icon)
if (iconButton == nil) {
if (icon.isNull())
return;
- NSString *title = QCFString::toNSString(window()->title());
+ NSString *title = window()->title().toNSString();
[m_nsWindow setRepresentedURL:[NSURL fileURLWithPath:title]];
iconButton = [m_nsWindow standardWindowButton:NSWindowDocumentIconButton];
}
@@ -1025,9 +1010,7 @@ void QCocoaWindow::raise()
}
static bool raiseProcess = qt_mac_resolveOption(true, "QT_MAC_SET_RAISE_PROCESS");
if (raiseProcess) {
- ProcessSerialNumber psn;
- GetCurrentProcess(&psn);
- SetFrontProcessWithOptions(&psn, kSetFrontProcessFrontWindowOnly);
+ [NSApp activateIgnoringOtherApps:YES];
}
}
}
@@ -1075,9 +1058,9 @@ bool QCocoaWindow::isOpaque() const
// When ordering below the window must be tranclucent.
static GLint openglSourfaceOrder = qt_mac_resolveOption(1, "QT_MAC_OPENGL_SURFACE_ORDER");
- bool translucent = (window()->format().alphaBufferSize() > 0
+ bool translucent = window()->format().alphaBufferSize() > 0
|| window()->opacity() < 1
- || (m_qtView && [m_qtView hasMask]))
+ || [qnsview_cast(m_view) hasMask]
|| (surface()->supportsOpenGL() && openglSourfaceOrder == -1);
return !translucent;
}
@@ -1109,11 +1092,10 @@ void QCocoaWindow::propagateSizeHints()
// sizeIncrement is observed to take values of (-1, -1) and (0, 0) for windows that should be
// resizable and that have no specific size increment set. Cocoa expects (1.0, 1.0) in this case.
- const QSize sizeIncrement = windowSizeIncrement();
- if (!sizeIncrement.isEmpty())
- [m_nsWindow setResizeIncrements : qt_mac_toNSSize(sizeIncrement)];
- else
- [m_nsWindow setResizeIncrements : NSMakeSize(1.0, 1.0)];
+ QSize sizeIncrement = windowSizeIncrement();
+ if (sizeIncrement.isEmpty())
+ sizeIncrement = QSize(1, 1);
+ [m_nsWindow setResizeIncrements:sizeIncrement.toCGSize()];
QRect rect = geometry();
QSize baseSize = windowBaseSize();
@@ -1137,8 +1119,8 @@ void QCocoaWindow::setMask(const QRegion &region)
if (m_nsWindow)
[m_nsWindow setBackgroundColor:[NSColor clearColor]];
- [m_qtView setMaskRegion:&region];
- [m_nsWindow setOpaque: isOpaque()];
+ [qnsview_cast(m_view) setMaskRegion:&region];
+ [m_nsWindow setOpaque:isOpaque()];
}
bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
@@ -1167,7 +1149,7 @@ bool QCocoaWindow::setMouseGrabEnabled(bool grab)
WId QCocoaWindow::winId() const
{
- return WId(m_contentView);
+ return WId(m_view);
}
void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
@@ -1175,38 +1157,16 @@ void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
qCDebug(lcQpaCocoaWindow) << "QCocoaWindow::setParent" << window() << (parentWindow ? parentWindow->window() : 0);
// recreate the window for compatibility
- bool unhideAfterRecreate = parentWindow && !m_contentViewIsToBeEmbedded && ![m_contentView isHidden];
+ bool unhideAfterRecreate = parentWindow && !m_viewIsToBeEmbedded && ![m_view isHidden];
recreateWindow(parentWindow);
if (unhideAfterRecreate)
- [m_contentView setHidden:NO];
+ [m_view setHidden:NO];
setCocoaGeometry(geometry());
}
-NSView *QCocoaWindow::contentView() const
-{
- return m_contentView;
-}
-
-void QCocoaWindow::setContentView(NSView *contentView)
+NSView *QCocoaWindow::view() const
{
- // Remove and release the previous content view
- if (m_nsWindow)
- [m_nsWindow setContentView:nil];
- else
- [m_contentView removeFromSuperview];
-
- [m_contentView release];
-
- // Insert and retain the new content view
- [contentView retain];
- m_contentView = contentView;
- m_qtView = 0; // The new content view is not a QNSView.
- recreateWindow(parent()); // Adds the content view to parent NSView
-}
-
-QNSView *QCocoaWindow::qtView() const
-{
- return m_qtView;
+ return m_view;
}
NSWindow *QCocoaWindow::nativeWindow() const
@@ -1216,7 +1176,7 @@ NSWindow *QCocoaWindow::nativeWindow() const
void QCocoaWindow::setEmbeddedInForeignView(bool embedded)
{
- m_contentViewIsToBeEmbedded = embedded;
+ m_viewIsToBeEmbedded = embedded;
// Release any previosly created NSWindow.
[m_nsWindow closeAndRelease];
m_nsWindow = 0;
@@ -1225,10 +1185,7 @@ void QCocoaWindow::setEmbeddedInForeignView(bool embedded)
void QCocoaWindow::windowWillMove()
{
// Close any open popups on window move
- while (QCocoaWindow *popup = QCocoaIntegration::instance()->popPopupWindow()) {
- QWindowSystemInterface::handleCloseEvent(popup->window());
- QWindowSystemInterface::flushWindowSystemEvents();
- }
+ qt_closePopups();
}
void QCocoaWindow::windowDidMove()
@@ -1236,7 +1193,7 @@ void QCocoaWindow::windowDidMove()
if (m_isNSWindowChild)
return;
- [m_qtView updateGeometry];
+ [qnsview_cast(m_view) updateGeometry];
}
void QCocoaWindow::windowDidResize()
@@ -1248,14 +1205,14 @@ void QCocoaWindow::windowDidResize()
return;
clipChildWindows();
- [m_qtView updateGeometry];
+ [qnsview_cast(m_view) updateGeometry];
}
void QCocoaWindow::windowDidEndLiveResize()
{
if (m_synchedWindowState == Qt::WindowMaximized && ![m_nsWindow isZoomed]) {
m_effectivelyMaximized = false;
- [m_qtView notifyWindowStateChanged:Qt::WindowNoState];
+ [qnsview_cast(m_view) notifyWindowStateChanged:Qt::WindowNoState];
}
}
@@ -1272,6 +1229,13 @@ bool QCocoaWindow::windowShouldClose()
return accepted;
}
+void QCocoaWindow::windowWillClose()
+{
+ // Close any open popups on window closing.
+ if (window() && !windowIsPopupType(window()->type()))
+ qt_closePopups();
+}
+
void QCocoaWindow::setSynchedWindowStateFromWindow()
{
if (QWindow *w = window())
@@ -1324,8 +1288,8 @@ void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
bool usesNSPanel = [m_nsWindow isKindOfClass:[QNSPanel class]];
// No child QNSWindow should notify its QNSView
- if (m_nsWindow && m_qtView && m_parentCocoaWindow && !oldParentCocoaWindow)
- [[NSNotificationCenter defaultCenter] removeObserver:m_qtView
+ if (m_nsWindow && (window()->type() != Qt::ForeignWindow) && m_parentCocoaWindow && !oldParentCocoaWindow)
+ [[NSNotificationCenter defaultCenter] removeObserver:m_view
name:nil object:m_nsWindow];
// Remove current window (if any)
@@ -1343,8 +1307,8 @@ void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
// Only non-child QNSWindows should notify their QNSViews
// (but don't register more than once).
- if (m_qtView && (noPreviousWindow || (wasNSWindowChild && !m_isNSWindowChild)))
- [[NSNotificationCenter defaultCenter] addObserver:m_qtView
+ if ((window()->type() != Qt::ForeignWindow) && (noPreviousWindow || (wasNSWindowChild && !m_isNSWindowChild)))
+ [[NSNotificationCenter defaultCenter] addObserver:m_view
selector:@selector(windowNotification:)
name:nil // Get all notifications
object:m_nsWindow];
@@ -1352,13 +1316,13 @@ void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
if (oldParentCocoaWindow) {
if (!m_isNSWindowChild || oldParentCocoaWindow != m_parentCocoaWindow)
oldParentCocoaWindow->removeChildWindow(this);
- m_forwardWindow.assign(oldParentCocoaWindow);
+ m_forwardWindow = oldParentCocoaWindow;
}
setNSWindow(m_nsWindow);
}
- if (m_contentViewIsToBeEmbedded) {
+ if (m_viewIsToBeEmbedded) {
// An embedded window doesn't have its own NSWindow.
} else if (!parentWindow) {
// QPlatformWindow subclasses must sync up with QWindow on creation:
@@ -1388,18 +1352,18 @@ void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
}
} else {
// Child windows have no NSWindow, link the NSViews instead.
- if ([m_contentView superview])
- [m_contentView removeFromSuperview];
+ if ([m_view superview])
+ [m_view removeFromSuperview];
- [m_parentCocoaWindow->m_contentView addSubview : m_contentView];
+ [m_parentCocoaWindow->m_view addSubview:m_view];
QRect rect = windowGeometry();
// Prevent setting a (0,0) window size; causes opengl context
// "Invalid Drawable" warnings.
if (rect.isNull())
rect.setSize(QSize(1, 1));
NSRect frame = NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height());
- [m_contentView setFrame:frame];
- [m_contentView setHidden: YES];
+ [m_view setFrame:frame];
+ [m_view setHidden:!window()->isVisible()];
}
m_nsWindow.ignoresMouseEvents =
@@ -1430,9 +1394,9 @@ void QCocoaWindow::reinsertChildWindow(QCocoaWindow *child)
void QCocoaWindow::requestActivateWindow()
{
- NSWindow *window = [m_contentView window];
- [ window makeFirstResponder : m_contentView ];
- [ window makeKeyWindow ];
+ NSWindow *window = [m_view window];
+ [window makeFirstResponder:m_view];
+ [window makeKeyWindow];
}
bool QCocoaWindow::shouldUseNSPanel()
@@ -1517,14 +1481,14 @@ QCocoaNSWindow * QCocoaWindow::createNSWindow()
void QCocoaWindow::setNSWindow(QCocoaNSWindow *window)
{
- if (window.contentView != m_contentView) {
- [m_contentView setPostsFrameChangedNotifications: NO];
- [m_contentView retain];
- if (m_contentView.superview) // m_contentView comes from another NSWindow
- [m_contentView removeFromSuperview];
- [window setContentView:m_contentView];
- [m_contentView release];
- [m_contentView setPostsFrameChangedNotifications: YES];
+ if (window.contentView != m_view) {
+ [m_view setPostsFrameChangedNotifications:NO];
+ [m_view retain];
+ if (m_view.superview) // m_view comes from another NSWindow
+ [m_view removeFromSuperview];
+ [window setContentView:m_view];
+ [m_view release];
+ [m_view setPostsFrameChangedNotifications:YES];
}
}
@@ -1534,6 +1498,17 @@ void QCocoaWindow::removeChildWindow(QCocoaWindow *child)
[m_nsWindow removeChildWindow:child->m_nsWindow];
}
+bool QCocoaWindow::isNativeWindowTypeInconsistent()
+{
+ if (!m_nsWindow)
+ return false;
+
+ const bool isPanel = [m_nsWindow isKindOfClass:[QNSPanel class]];
+ const bool usePanel = shouldUseNSPanel();
+
+ return isPanel != usePanel;
+}
+
void QCocoaWindow::removeMonitor()
{
if (!monitor)
@@ -1571,7 +1546,7 @@ void QCocoaWindow::syncWindowState(Qt::WindowState newState)
return;
// if content view width or height is 0 then the window animations will crash so
// do nothing except set the new state
- NSRect contentRect = [contentView() frame];
+ NSRect contentRect = m_view.frame;
if (contentRect.size.width <= 0 || contentRect.size.height <= 0) {
qWarning("invalid window content view size, check your window geometry");
m_synchedWindowState = newState;
@@ -1671,9 +1646,9 @@ NSCursor *QCocoaWindow::effectiveWindowCursor() const
if (m_windowCursor)
return m_windowCursor;
- if (!parent())
+ if (!QPlatformWindow::parent())
return nil;
- return static_cast<QCocoaWindow *>(parent())->effectiveWindowCursor();
+ return static_cast<QCocoaWindow *>(QPlatformWindow::parent())->effectiveWindowCursor();
}
// Applies the cursor as returned by effectiveWindowCursor(), handles
@@ -1696,7 +1671,7 @@ void QCocoaWindow::setWindowCursor(NSCursor *cursor)
return;
// Setting a cursor in a foregin view is not supported.
- if (!m_qtView)
+ if (window()->type() == Qt::ForeignWindow)
return;
[m_windowCursor release];
@@ -1714,9 +1689,9 @@ void QCocoaWindow::registerTouch(bool enable)
{
m_registerTouchCount += enable ? 1 : -1;
if (enable && m_registerTouchCount == 1)
- [m_contentView setAcceptsTouchEvents:YES];
+ [m_view setAcceptsTouchEvents:YES];
else if (m_registerTouchCount == 0)
- [m_contentView setAcceptsTouchEvents:NO];
+ [m_view setAcceptsTouchEvents:NO];
}
void QCocoaWindow::setContentBorderThickness(int topThickness, int bottomThickness)
@@ -1816,7 +1791,7 @@ qreal QCocoaWindow::devicePixelRatio() const
// methods such as [NSWindow backingScaleFacor] might not give the correct
// result, for example if setWantsBestResolutionOpenGLSurface is not set or
// or ignored by the OpenGL driver.
- NSSize backingSize = [m_contentView convertSizeToBacking:NSMakeSize(1.0, 1.0)];
+ NSSize backingSize = [m_view convertSizeToBacking:NSMakeSize(1.0, 1.0)];
return backingSize.height;
}
@@ -1826,8 +1801,8 @@ bool QCocoaWindow::isWindowExposable()
{
QSize size = geometry().size();
bool validGeometry = (size.width() > 0 && size.height() > 0);
- bool validScreen = ([[m_contentView window] screen] != 0);
- bool nonHiddenSuperView = ![[m_contentView superview] isHidden];
+ bool validScreen = ([[m_view window] screen] != 0);
+ bool nonHiddenSuperView = ![[m_view superview] isHidden];
return (validGeometry && validScreen && nonHiddenSuperView);
}
@@ -1939,11 +1914,11 @@ QPoint QCocoaWindow::bottomLeftClippedByNSWindowOffsetStatic(QWindow *window)
QPoint QCocoaWindow::bottomLeftClippedByNSWindowOffset() const
{
- if (!m_contentView)
+ if (!m_view)
return QPoint();
- const NSPoint origin = [m_contentView isFlipped] ? NSMakePoint(0, [m_contentView frame].size.height)
+ const NSPoint origin = [m_view isFlipped] ? NSMakePoint(0, [m_view frame].size.height)
: NSMakePoint(0, 0);
- const NSRect visibleRect = [m_contentView visibleRect];
+ const NSRect visibleRect = [m_view visibleRect];
return QPoint(visibleRect.origin.x, -visibleRect.origin.y + (origin.y - visibleRect.size.height));
}
@@ -1963,3 +1938,5 @@ void QCocoaWindow::setFrameStrutEventsEnabled(bool enabled)
{
m_frameStrutEventsEnabled = enabled;
}
+
+#include "moc_qcocoawindow.cpp"
diff --git a/src/plugins/platforms/cocoa/qmacclipboard.h b/src/plugins/platforms/cocoa/qmacclipboard.h
index a3abacf849..1d229a55d2 100644
--- a/src/plugins/platforms/cocoa/qmacclipboard.h
+++ b/src/plugins/platforms/cocoa/qmacclipboard.h
@@ -41,9 +41,7 @@
#define QMACCLIPBOARD_H
#include <QtGui>
-#include <QtPlatformSupport/private/qmacmime_p.h>
-
-#undef slots
+#include <QtClipboardSupport/private/qmacmime_p.h>
#import <AppKit/AppKit.h>
diff --git a/src/plugins/platforms/cocoa/qmacclipboard.mm b/src/plugins/platforms/cocoa/qmacclipboard.mm
index 721b0fb4d1..e09bb1e362 100644
--- a/src/plugins/platforms/cocoa/qmacclipboard.mm
+++ b/src/plugins/platforms/cocoa/qmacclipboard.mm
@@ -113,7 +113,7 @@ QMacPasteboard::QMacPasteboard(CFStringRef name, uchar mt)
if (err == noErr) {
PasteboardSetPromiseKeeper(paste, promiseKeeper, this);
} else {
- qDebug("PasteBoard: Error creating pasteboard: %s [%d]", QCFString::toQString(name).toLatin1().constData(), (int)err);
+ qDebug("PasteBoard: Error creating pasteboard: %s [%d]", QString::fromCFString(name).toLatin1().constData(), (int)err);
}
resolvingBeforeDestruction = false;
}
@@ -139,7 +139,7 @@ OSStatus QMacPasteboard::promiseKeeper(PasteboardRef paste, PasteboardItemID id,
const long promise_id = (long)id;
// Find the kept promise
- const QString flavorAsQString = QCFString::toQString(flavor);
+ const QString flavorAsQString = QString::fromCFString(flavor);
QMacPasteboard::Promise promise;
for (int i = 0; i < qpaste->promises.size(); i++){
QMacPasteboard::Promise tmp = qpaste->promises[i];
@@ -380,7 +380,7 @@ QMacPasteboard::formats() const
const int type_count = CFArrayGetCount(types);
for (int i = 0; i < type_count; ++i) {
- const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
+ const QString flavor = QString::fromCFString((CFStringRef)CFArrayGetValueAtIndex(types, i));
#ifdef DEBUG_PASTEBOARD
qDebug(" -%s", qPrintable(QString(flavor)));
#endif
@@ -423,7 +423,7 @@ QMacPasteboard::hasFormat(const QString &format) const
const int type_count = CFArrayGetCount(types);
for (int i = 0; i < type_count; ++i) {
- const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
+ const QString flavor = QString::fromCFString((CFStringRef)CFArrayGetValueAtIndex(types, i));
#ifdef DEBUG_PASTEBOARD
qDebug(" -%s [0x%x]", qPrintable(QString(flavor)), mime_type);
#endif
@@ -487,13 +487,13 @@ QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const
const int type_count = CFArrayGetCount(types);
for (int i = 0; i < type_count; ++i) {
CFStringRef flavor = static_cast<CFStringRef>(CFArrayGetValueAtIndex(types, i));
- if (c_flavor == QCFString::toQString(flavor)) {
+ if (c_flavor == QString::fromCFString(flavor)) {
QCFType<CFDataRef> macBuffer;
if (PasteboardCopyItemFlavorData(paste, id, flavor, &macBuffer) == noErr) {
QByteArray buffer((const char *)CFDataGetBytePtr(macBuffer), CFDataGetLength(macBuffer));
if (!buffer.isEmpty()) {
#ifdef DEBUG_PASTEBOARD
- qDebug(" - %s [%s] (%s)", qPrintable(format), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
+ qDebug(" - %s [%s] (%s)", qPrintable(format), qPrintable(QString::fromNSString(flavor)), qPrintable(c->convertorName()));
#endif
buffer.detach(); //detach since we release the macBuffer
retList.append(buffer);
@@ -502,7 +502,7 @@ QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const
}
} else {
#ifdef DEBUG_PASTEBOARD
- qDebug(" - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
+ qDebug(" - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QString::fromNSString(flavor)), qPrintable(c->convertorName()));
#endif
}
}
@@ -565,7 +565,7 @@ QString qt_mac_get_pasteboardString(PasteboardRef paste)
if (pb) {
NSString *text = [pb stringForType:NSStringPboardType];
if (text)
- return QCFString::toQString(text);
+ return QString::fromNSString(text);
}
return QString();
}
diff --git a/src/plugins/platforms/cocoa/qmacdefines_mac.h b/src/plugins/platforms/cocoa/qmacdefines_mac.h
index e27f805fca..9e229b8dcb 100644
--- a/src/plugins/platforms/cocoa/qmacdefines_mac.h
+++ b/src/plugins/platforms/cocoa/qmacdefines_mac.h
@@ -93,42 +93,31 @@ typedef signed int OSStatus;
typedef signed long OSStatus;
#endif
+typedef struct OpaqueEventHandlerCallRef * EventHandlerCallRef;
+typedef struct OpaqueEventRef * EventRef;
+typedef struct OpaqueMenuRef * MenuRef;
+typedef struct OpaquePasteboardRef* PasteboardRef;
+typedef struct OpaqueRgnHandle * RgnHandle;
+typedef const struct __HIShape *HIShapeRef;
+typedef struct __HIShape *HIMutableShapeRef;
+typedef struct CGRect CGRect;
+typedef struct CGImage *CGImageRef;
+typedef struct CGContext *CGContextRef;
+typedef struct GDevice * GDPtr;
+typedef GDPtr * GDHandle;
+typedef struct OpaqueIconRef * IconRef;
+
#ifdef __OBJC__
-# ifdef slots
-# define old_slots slots
-# undef slots
-# endif
-#include <AppKit/AppKit.h>
-# ifdef old_slots
-# undef slots
-# define slots
-# undef old_slots
-# endif
+typedef NSWindow* OSWindowRef;
+typedef NSView *OSViewRef;
+typedef NSMenu *OSMenuRef;
+typedef NSEvent *OSEventRef;
+#else
+typedef void *OSWindowRef;
+typedef void *OSViewRef;
+typedef void *OSMenuRef;
+typedef void *OSEventRef;
#endif
- typedef struct OpaqueEventHandlerCallRef * EventHandlerCallRef;
- typedef struct OpaqueEventRef * EventRef;
- typedef struct OpaqueMenuRef * MenuRef;
- typedef struct OpaquePasteboardRef* PasteboardRef;
- typedef struct OpaqueRgnHandle * RgnHandle;
- typedef const struct __HIShape *HIShapeRef;
- typedef struct __HIShape *HIMutableShapeRef;
- typedef struct CGRect CGRect;
- typedef struct CGImage *CGImageRef;
- typedef struct CGContext *CGContextRef;
- typedef struct GDevice * GDPtr;
- typedef GDPtr * GDHandle;
- typedef struct OpaqueIconRef * IconRef;
-# ifdef __OBJC__
- typedef NSWindow* OSWindowRef;
- typedef NSView *OSViewRef;
- typedef NSMenu *OSMenuRef;
- typedef NSEvent *OSEventRef;
-# else
- typedef void *OSWindowRef;
- typedef void *OSViewRef;
- typedef void *OSMenuRef;
- typedef void *OSEventRef;
-# endif
typedef PasteboardRef OSPasteboardRef;
typedef struct AEDesc AEDescList;
diff --git a/src/plugins/platforms/cocoa/qnsview.h b/src/plugins/platforms/cocoa/qnsview.h
index c30ace35b4..f226547b90 100644
--- a/src/plugins/platforms/cocoa/qnsview.h
+++ b/src/plugins/platforms/cocoa/qnsview.h
@@ -64,8 +64,7 @@ Q_FORWARD_DECLARE_OBJC_CLASS(QT_MANGLE_NAMESPACE(QNSViewMouseMoveHelper));
CGImageRef m_maskImage;
uchar *m_maskData;
bool m_shouldInvalidateWindowShadow;
- QPointer<QWindow> m_window;
- QCocoaWindow *m_platformWindow;
+ QPointer<QCocoaWindow> m_platformWindow;
NSTrackingArea *m_trackingArea;
Qt::MouseButtons m_buttons;
Qt::MouseButtons m_acceptedMouseDowns;
@@ -85,15 +84,13 @@ Q_FORWARD_DECLARE_OBJC_CLASS(QT_MANGLE_NAMESPACE(QNSViewMouseMoveHelper));
bool m_resendKeyEvent;
bool m_scrolling;
bool m_updatingDrag;
- bool m_exposedOnMoveToWindow;
NSEvent *m_currentlyInterpretedKeyEvent;
bool m_isMenuView;
QSet<quint32> m_acceptedKeyDowns;
}
- (id)init;
-- (id)initWithQWindow:(QWindow *)window platformWindow:(QCocoaWindow *) platformWindow;
-- (void) clearQWindowPointers;
+- (id)initWithCocoaWindow:(QCocoaWindow *)platformWindow;
#ifndef QT_NO_OPENGL
- (void)setQCocoaGLContext:(QCocoaGLContext *)context;
#endif
@@ -102,6 +99,7 @@ Q_FORWARD_DECLARE_OBJC_CLASS(QT_MANGLE_NAMESPACE(QNSViewMouseMoveHelper));
- (void)setMaskRegion:(const QRegion *)region;
- (void)invalidateWindowShadowIfNeeded;
- (void)drawRect:(NSRect)dirtyRect;
+- (void)drawBackingStoreUsingCoreGraphics:(NSRect)dirtyRect;
- (void)updateGeometry;
- (void)notifyWindowStateChanged:(Qt::WindowState)newState;
- (void)windowNotification : (NSNotification *) windowNotification;
diff --git a/src/plugins/platforms/cocoa/qnsview.mm b/src/plugins/platforms/cocoa/qnsview.mm
index ba86b39e5b..a63bc4d570 100644
--- a/src/plugins/platforms/cocoa/qnsview.mm
+++ b/src/plugins/platforms/cocoa/qnsview.mm
@@ -39,8 +39,6 @@
#include <QtCore/qglobal.h>
-#include <dlfcn.h>
-
#include "qnsview.h"
#include "qcocoawindow.h"
#include "qcocoahelpers.h"
@@ -54,6 +52,7 @@
#include <QtCore/QDebug>
#include <QtCore/qsysinfo.h>
#include <private/qguiapplication_p.h>
+#include <private/qcoregraphics_p.h>
#include "qcocoabackingstore.h"
#ifndef QT_NO_OPENGL
#include "qcocoaglcontext.h"
@@ -72,9 +71,6 @@ Q_LOGGING_CATEGORY(lcQpaTablet, "qt.qpa.input.tablet")
static QTouchDevice *touchDevice = 0;
-// ### HACK Remove once 10.8 is unsupported
-static NSString *_q_NSWindowDidChangeOcclusionStateNotification = nil;
-
static bool _q_dontOverrideCtrlLMB = false;
@interface NSEvent (Qt_Compile_Leopard_DeviceDelta)
@@ -130,14 +126,15 @@ static bool _q_dontOverrideCtrlLMB = false;
@end
+// Private interface
+@interface QT_MANGLE_NAMESPACE(QNSView) ()
+- (BOOL)isTransparentForUserInput;
+@end
+
@implementation QT_MANGLE_NAMESPACE(QNSView)
+ (void)initialize
{
- NSString **notificationNameVar = (NSString **)dlsym(RTLD_NEXT, "NSWindowDidChangeOcclusionStateNotification");
- if (notificationNameVar)
- _q_NSWindowDidChangeOcclusionStateNotification = *notificationNameVar;
-
_q_dontOverrideCtrlLMB = qt_mac_resolveOption(false, "QT_MAC_DONT_OVERRIDE_CTRL_LMB");
}
@@ -148,7 +145,6 @@ static bool _q_dontOverrideCtrlLMB = false;
m_backingStore = 0;
m_maskImage = 0;
m_shouldInvalidateWindowShadow = false;
- m_window = 0;
m_buttons = Qt::NoButton;
m_acceptedMouseDowns = Qt::NoButton;
m_frameStrutButtons = Qt::NoButton;
@@ -185,7 +181,6 @@ static bool _q_dontOverrideCtrlLMB = false;
CGImageRelease(m_maskImage);
[m_trackingArea release];
m_maskImage = 0;
- m_window = 0;
m_subscribesForGlobalFrameNotifications = false;
[m_inputSource release];
[[NSNotificationCenter defaultCenter] removeObserver:self];
@@ -196,13 +191,12 @@ static bool _q_dontOverrideCtrlLMB = false;
[super dealloc];
}
-- (id)initWithQWindow:(QWindow *)window platformWindow:(QCocoaWindow *) platformWindow
+- (id)initWithCocoaWindow:(QCocoaWindow *)platformWindow
{
self = [self init];
if (!self)
return 0;
- m_window = window;
m_platformWindow = platformWindow;
m_sendKeyEvent = false;
m_trackingArea = nil;
@@ -237,12 +231,6 @@ static bool _q_dontOverrideCtrlLMB = false;
return self;
}
-- (void) clearQWindowPointers
-{
- m_window = 0;
- m_platformWindow = 0;
-}
-
#ifndef QT_NO_OPENGL
- (void) setQCocoaGLContext:(QCocoaGLContext *)context
{
@@ -275,40 +263,28 @@ static bool _q_dontOverrideCtrlLMB = false;
- (void)viewDidMoveToSuperview
{
- if (!(m_platformWindow->m_contentViewIsToBeEmbedded))
+ if (!(m_platformWindow->m_viewIsToBeEmbedded))
return;
if ([self superview]) {
- m_platformWindow->m_contentViewIsEmbedded = true;
- QWindowSystemInterface::handleGeometryChange(m_window, m_platformWindow->geometry());
+ m_platformWindow->m_viewIsEmbedded = true;
+ QWindowSystemInterface::handleGeometryChange(m_platformWindow->window(), m_platformWindow->geometry());
m_platformWindow->updateExposedGeometry();
QWindowSystemInterface::flushWindowSystemEvents();
} else {
- m_platformWindow->m_contentViewIsEmbedded = false;
+ m_platformWindow->m_viewIsEmbedded = false;
}
}
- (void)viewDidMoveToWindow
{
m_backingStore = Q_NULLPTR;
- m_isMenuView = [self.window.className isEqualToString:@"NSCarbonMenuWindow"];
- if (self.window) {
- // This is the case of QWidgetAction's generated QWidget inserted in an NSMenu.
- // 10.9 and newer get the NSWindowDidChangeOcclusionStateNotification
- if (!_q_NSWindowDidChangeOcclusionStateNotification && m_isMenuView) {
- m_exposedOnMoveToWindow = true;
- m_platformWindow->exposeWindow();
- }
- } else if (m_exposedOnMoveToWindow) {
- m_exposedOnMoveToWindow = false;
- m_platformWindow->obscureWindow();
- }
}
- (void)viewWillMoveToWindow:(NSWindow *)newWindow
{
// ### Merge "normal" window code path with this one for 5.1.
- if (!(m_window->type() & Qt::SubWindow))
+ if (!(m_platformWindow->window()->type() & Qt::SubWindow))
return;
if (newWindow) {
@@ -323,11 +299,11 @@ static bool _q_dontOverrideCtrlLMB = false;
- (QWindow *)topLevelWindow
{
- QWindow *focusWindow = m_window;
+ QWindow *focusWindow = m_platformWindow->window();
// For widgets we need to do a bit of trickery as the window
// to activate is the window of the top-level widget.
- if (qstrcmp(m_window->metaObject()->className(), "QWidgetWindow") == 0) {
+ if (qstrcmp(focusWindow->metaObject()->className(), "QWidgetWindow") == 0) {
while (focusWindow->parent()) {
focusWindow = focusWindow->parent();
}
@@ -343,9 +319,9 @@ static bool _q_dontOverrideCtrlLMB = false;
if (m_platformWindow->m_isNSWindowChild) {
return;
#if 0
- //geometry = qt_mac_toQRect([self frame]);
+ //geometry = QRectF::fromCGRect([self frame]).toRect();
qDebug() << "nsview updateGeometry" << m_platformWindow->window();
- QRect screenRect = qt_mac_toQRect([m_platformWindow->m_nsWindow convertRectToScreen:[self frame]]);
+ QRect screenRect = QRectF::fromCGRect([m_platformWindow->m_nsWindow convertRectToScreen:[self frame]]).toRect();
qDebug() << "screenRect" << screenRect;
screenRect.moveTop(qt_mac_flipYCoordinate(screenRect.y() + screenRect.height()));
@@ -358,12 +334,12 @@ static bool _q_dontOverrideCtrlLMB = false;
NSRect rect = [self frame];
NSRect windowRect = [[self window] frame];
geometry = QRect(windowRect.origin.x, qt_mac_flipYCoordinate(windowRect.origin.y + rect.size.height), rect.size.width, rect.size.height);
- } else if (m_platformWindow->m_contentViewIsToBeEmbedded) {
+ } else if (m_platformWindow->m_viewIsToBeEmbedded) {
// embedded child window, use the frame rect ### merge with case below
- geometry = qt_mac_toQRect([self bounds]);
+ geometry = QRectF::fromCGRect([self bounds]).toRect();
} else {
// child window, use the frame rect
- geometry = qt_mac_toQRect([self frame]);
+ geometry = QRectF::fromCGRect([self frame]).toRect();
}
if (m_platformWindow->m_nsWindow && geometry == m_platformWindow->geometry())
@@ -377,7 +353,7 @@ static bool _q_dontOverrideCtrlLMB = false;
if (m_platformWindow->m_inSetStyleMask && !self.window)
return;
- qCDebug(lcQpaCocoaWindow) << "[QNSView udpateGeometry:]" << m_window
+ qCDebug(lcQpaCocoaWindow) << "[QNSView udpateGeometry:]" << m_platformWindow->window()
<< "current" << m_platformWindow->geometry() << "new" << geometry;
// Call setGeometry on QPlatformWindow. (not on QCocoaWindow,
@@ -388,12 +364,12 @@ static bool _q_dontOverrideCtrlLMB = false;
// Don't send the geometry change if the QWindow is designated to be
// embedded in a foreign view hiearchy but has not actually been
// embedded yet - it's too early.
- if (m_platformWindow->m_contentViewIsToBeEmbedded && !m_platformWindow->m_contentViewIsEmbedded)
+ if (m_platformWindow->m_viewIsToBeEmbedded && !m_platformWindow->m_viewIsEmbedded)
return;
// Send a geometry change event to Qt, if it's ready to handle events
if (!m_platformWindow->m_inConstructor) {
- QWindowSystemInterface::handleGeometryChange(m_window, geometry);
+ QWindowSystemInterface::handleGeometryChange(m_platformWindow->window(), geometry);
m_platformWindow->updateExposedGeometry();
// Guard against processing window system events during QWindow::setGeometry
// calles, which Qt and Qt applications do not excpect.
@@ -412,7 +388,7 @@ static bool _q_dontOverrideCtrlLMB = false;
// So we should say that it is maximized because it actually is.
if (newState == Qt::WindowNoState && m_platformWindow->m_effectivelyMaximized)
newState = Qt::WindowMaximized;
- QWindowSystemInterface::handleWindowStateChanged(m_window, newState);
+ QWindowSystemInterface::handleWindowStateChanged(m_platformWindow->window(), newState);
// We want to read the window state back from the window,
// but the event we just sent may be asynchronous.
QWindowSystemInterface::flushWindowSystemEvents();
@@ -421,18 +397,18 @@ static bool _q_dontOverrideCtrlLMB = false;
- (void)windowNotification : (NSNotification *) windowNotification
{
- //qDebug() << "windowNotification" << QCFString::toQString([windowNotification name]);
+ //qDebug() << "windowNotification" << QString::fromNSString([windowNotification name]);
NSString *notificationName = [windowNotification name];
if (notificationName == NSWindowDidBecomeKeyNotification) {
if (!m_platformWindow->windowIsPopupType() && !m_isMenuView)
- QWindowSystemInterface::handleWindowActivated(m_window);
+ QWindowSystemInterface::handleWindowActivated(m_platformWindow->window());
} else if (notificationName == NSWindowDidResignKeyNotification) {
// key window will be non-nil if another window became key... do not
// set the active window to zero here, the new key window's
// NSWindowDidBecomeKeyNotification hander will change the active window
NSWindow *keyWindow = [NSApp keyWindow];
- if (!keyWindow) {
+ if (!keyWindow || keyWindow == windowNotification.object) {
// no new key window, go ahead and set the active window to zero
if (!m_platformWindow->windowIsPopupType() && !m_isMenuView)
QWindowSystemInterface::handleWindowActivated(0);
@@ -446,14 +422,7 @@ static bool _q_dontOverrideCtrlLMB = false;
m_platformWindow->obscureWindow();
} else if ([notificationName isEqualToString: @"NSWindowDidOrderOnScreenAndFinishAnimatingNotification"]) {
m_platformWindow->exposeWindow();
- } else if (_q_NSWindowDidChangeOcclusionStateNotification
- && [notificationName isEqualToString:_q_NSWindowDidChangeOcclusionStateNotification]) {
-#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_9
-// ### HACK Remove the enum declaration, the warning disabling and the cast further down once 10.8 is unsupported
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_CLANG("-Wobjc-method-access")
- enum { NSWindowOcclusionStateVisible = 1UL << 1 };
-#endif
+ } else if ([notificationName isEqualToString:NSWindowDidChangeOcclusionStateNotification]) {
// Several unit tests expect paint and/or expose events for windows that are
// sometimes (unpredictably) occluded and some unit tests depend on QWindow::isExposed -
// don't send Expose/Obscure events when running under QTestLib.
@@ -466,16 +435,13 @@ QT_WARNING_DISABLE_CLANG("-Wobjc-method-access")
m_platformWindow->obscureWindow();
}
}
-#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_9
-QT_WARNING_POP
-#endif
} else if (notificationName == NSWindowDidChangeScreenNotification) {
- if (m_window) {
+ if (m_platformWindow->window()) {
NSUInteger screenIndex = [[NSScreen screens] indexOfObject:self.window.screen];
if (screenIndex != NSNotFound) {
QCocoaScreen *cocoaScreen = QCocoaIntegration::instance()->screenAtIndex(screenIndex);
if (cocoaScreen)
- QWindowSystemInterface::handleWindowScreenChanged(m_window, cocoaScreen->screen());
+ QWindowSystemInterface::handleWindowScreenChanged(m_platformWindow->window(), cocoaScreen->screen());
m_platformWindow->updateExposedGeometry();
}
}
@@ -522,11 +488,11 @@ QT_WARNING_POP
- (void) flushBackingStore:(QCocoaBackingStore *)backingStore region:(const QRegion &)region offset:(QPoint)offset
{
- qCDebug(lcQpaCocoaWindow) << "[QNSView flushBackingStore:]" << m_window << region.rectCount() << region.boundingRect() << offset;
+ qCDebug(lcQpaCocoaWindow) << "[QNSView flushBackingStore:]" << m_platformWindow->window() << region.rectCount() << region.boundingRect() << offset;
m_backingStore = backingStore;
- m_backingStoreOffset = offset * m_backingStore->getBackingStoreDevicePixelRatio();
- foreach (QRect rect, region.rects())
+ m_backingStoreOffset = offset * m_backingStore->paintDevice()->devicePixelRatio();
+ for (const QRect &rect : region)
[self setNeedsDisplayInRect:NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
}
@@ -587,7 +553,7 @@ QT_WARNING_POP
- (void) drawRect:(NSRect)dirtyRect
{
- qCDebug(lcQpaCocoaWindow) << "[QNSView drawRect:]" << m_window << qt_mac_toQRect(dirtyRect);
+ qCDebug(lcQpaCocoaWindow) << "[QNSView drawRect:]" << m_platformWindow->window() << QRectF::fromCGRect(dirtyRect);
#ifndef QT_NO_OPENGL
if (m_glContext && m_shouldSetGLContextinDrawRect) {
@@ -599,6 +565,18 @@ QT_WARNING_POP
if (m_platformWindow->m_drawContentBorderGradient)
NSDrawWindowBackground(dirtyRect);
+ if (m_backingStore)
+ [self drawBackingStoreUsingCoreGraphics:dirtyRect];
+
+ [self invalidateWindowShadowIfNeeded];
+}
+
+// Draws the backing store content to the QNSView using Core Graphics.
+// This function assumes that the QNSView is in a configuration that
+// supports Core Graphics, such as "classic" mode or layer mode with
+// the default layer.
+- (void)drawBackingStoreUsingCoreGraphics:(NSRect)dirtyRect
+{
if (!m_backingStore)
return;
@@ -607,7 +585,7 @@ QT_WARNING_POP
// The backing store source rect will be larger on retina displays.
// Scale dirtyRect by the device pixel ratio:
- const qreal devicePixelRatio = m_backingStore->getBackingStoreDevicePixelRatio();
+ const qreal devicePixelRatio = m_backingStore->paintDevice()->devicePixelRatio();
CGRect dirtyBackingRect = CGRectMake(dirtyRect.origin.x * devicePixelRatio,
dirtyRect.origin.y * devicePixelRatio,
dirtyRect.size.width * devicePixelRatio,
@@ -653,8 +631,6 @@ QT_WARNING_POP
CGImageRelease(cleanImg);
CGImageRelease(subMask);
CGImageRelease(bsCGImage);
-
- [self invalidateWindowShadowIfNeeded];
}
- (BOOL) isFlipped
@@ -662,11 +638,17 @@ QT_WARNING_POP
return YES;
}
+- (BOOL)isTransparentForUserInput
+{
+ return m_platformWindow->window() &&
+ m_platformWindow->window()->flags() & Qt::WindowTransparentForInput;
+}
+
- (BOOL)becomeFirstResponder
{
- if (!m_window || !m_platformWindow)
+ if (!m_platformWindow)
return NO;
- if (m_window->flags() & Qt::WindowTransparentForInput)
+ if ([self isTransparentForUserInput])
return NO;
if (!m_platformWindow->windowIsPopupType() && !m_isMenuView)
QWindowSystemInterface::handleWindowActivated([self topLevelWindow]);
@@ -675,15 +657,15 @@ QT_WARNING_POP
- (BOOL)acceptsFirstResponder
{
- if (!m_window || !m_platformWindow)
+ if (!m_platformWindow)
return NO;
if (m_isMenuView)
return NO;
if (m_platformWindow->shouldRefuseKeyWindowAndFirstResponder())
return NO;
- if (m_window->flags() & Qt::WindowTransparentForInput)
+ if ([self isTransparentForUserInput])
return NO;
- if ((m_window->flags() & Qt::ToolTip) == Qt::ToolTip)
+ if ((m_platformWindow->window()->flags() & Qt::ToolTip) == Qt::ToolTip)
return NO;
return YES;
}
@@ -691,9 +673,9 @@ QT_WARNING_POP
- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
{
Q_UNUSED(theEvent)
- if (!m_window || !m_platformWindow)
+ if (!m_platformWindow)
return NO;
- if (m_window->flags() & Qt::WindowTransparentForInput)
+ if ([self isTransparentForUserInput])
return NO;
return YES;
}
@@ -702,7 +684,7 @@ QT_WARNING_POP
{
NSView *candidate = [super hitTest:aPoint];
if (candidate == self) {
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput))
+ if ([self isTransparentForUserInput])
return nil;
}
return candidate;
@@ -769,7 +751,7 @@ QT_WARNING_POP
QNSView *targetView = self;
if (m_platformWindow && m_platformWindow->m_forwardWindow) {
if (theEvent.type == NSLeftMouseDragged || theEvent.type == NSLeftMouseUp)
- targetView = m_platformWindow->m_forwardWindow->m_qtView;
+ targetView = qnsview_cast(m_platformWindow->m_forwardWindow->view());
else
m_platformWindow->m_forwardWindow.clear();
}
@@ -779,7 +761,7 @@ QT_WARNING_POP
// Tooltips must be transparent for mouse events
// The bug reference is QTBUG-46379
if (!popup->m_windowFlags.testFlag(Qt::ToolTip)) {
- if (QNSView *popupView = popup->qtView())
+ if (QNSView *popupView = qnsview_cast(popup->view()))
targetView = popupView;
}
}
@@ -791,7 +773,7 @@ QT_WARNING_POP
nativeDrag->setLastMouseEvent(theEvent, self);
Qt::KeyboardModifiers keyboardModifiers = [QNSView convertKeyModifiers:[theEvent modifierFlags]];
- QWindowSystemInterface::handleMouseEvent(targetView->m_window, timestamp, qtWindowPoint, qtScreenPoint,
+ QWindowSystemInterface::handleMouseEvent(targetView->m_platformWindow->window(), timestamp, qtWindowPoint, qtScreenPoint,
m_buttons, keyboardModifiers, Qt::MouseEventNotSynthesized);
}
@@ -845,12 +827,12 @@ QT_WARNING_POP
QPoint qtScreenPoint = QPoint(screenPoint.x, qt_mac_flipYCoordinate(screenPoint.y));
ulong timestamp = [theEvent timestamp] * 1000;
- QWindowSystemInterface::handleFrameStrutMouseEvent(m_window, timestamp, qtWindowPoint, qtScreenPoint, m_frameStrutButtons);
+ QWindowSystemInterface::handleFrameStrutMouseEvent(m_platformWindow->window(), timestamp, qtWindowPoint, qtScreenPoint, m_frameStrutButtons);
}
- (bool)handleMouseDownEvent:(NSEvent *)theEvent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput))
+ if ([self isTransparentForUserInput])
return false;
Qt::MouseButton button = cocoaButton2QtButton([theEvent buttonNumber]);
@@ -882,7 +864,7 @@ QT_WARNING_POP
- (bool)handleMouseDraggedEvent:(NSEvent *)theEvent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput))
+ if ([self isTransparentForUserInput])
return false;
Qt::MouseButton button = cocoaButton2QtButton([theEvent buttonNumber]);
@@ -898,7 +880,7 @@ QT_WARNING_POP
- (bool)handleMouseUpEvent:(NSEvent *)theEvent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput))
+ if ([self isTransparentForUserInput])
return false;
Qt::MouseButton button = cocoaButton2QtButton([theEvent buttonNumber]);
@@ -921,7 +903,7 @@ QT_WARNING_POP
- (void)mouseDown:(NSEvent *)theEvent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput) )
+ if ([self isTransparentForUserInput])
return [super mouseDown:theEvent];
m_sendUpAsRightButton = false;
@@ -1079,7 +1061,7 @@ QT_WARNING_POP
- (void)mouseMovedImpl:(NSEvent *)theEvent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput) )
+ if ([self isTransparentForUserInput])
return;
QPointF windowPoint;
@@ -1101,7 +1083,7 @@ QT_WARNING_POP
// Cocoa keeps firing mouse move events for obscured parent views. Qt should not
// send those events so filter them out here.
- if (childWindow != m_window)
+ if (childWindow != m_platformWindow->window())
return;
[self handleMouseEvent: theEvent];
@@ -1112,7 +1094,7 @@ QT_WARNING_POP
Q_UNUSED(theEvent)
m_platformWindow->m_windowUnderMouse = true;
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput) )
+ if ([self isTransparentForUserInput])
return;
// Top-level windows generate enter events for sub-windows.
@@ -1131,7 +1113,7 @@ QT_WARNING_POP
Q_UNUSED(theEvent);
m_platformWindow->m_windowUnderMouse = false;
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput) )
+ if ([self isTransparentForUserInput])
return;
// Top-level windows generate leave events for sub-windows.
@@ -1207,16 +1189,16 @@ Q_GLOBAL_STATIC(QCocoaTabletDeviceDataHash, tabletDeviceDataHash)
windowPoint.x(), windowPoint.y(), screenPoint.x(), screenPoint.y(),
static_cast<uint>(buttons), pressure, xTilt, yTilt, rotation);
- QWindowSystemInterface::handleTabletEvent(m_window, timestamp, windowPoint, screenPoint,
+ QWindowSystemInterface::handleTabletEvent(m_platformWindow->window(), timestamp, windowPoint, screenPoint,
deviceData.device, deviceData.pointerType, buttons, pressure, xTilt, yTilt,
tangentialPressure, rotation, z, deviceData.uid,
keyboardModifiers);
return true;
}
-- (void)tabletPoint: (NSEvent *)theEvent
+- (void)tabletPoint:(NSEvent *)theEvent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput) )
+ if ([self isTransparentForUserInput])
return [super tabletPoint:theEvent];
[self handleTabletEvent: theEvent];
@@ -1262,9 +1244,9 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
return device;
}
-- (void)tabletProximity: (NSEvent *)theEvent
+- (void)tabletProximity:(NSEvent *)theEvent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput) )
+ if ([self isTransparentForUserInput])
return [super tabletProximity:theEvent];
ulong timestamp = [theEvent timestamp] * 1000;
@@ -1311,11 +1293,11 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
}
}
-- (bool) shouldSendSingleTouch
+- (bool)shouldSendSingleTouch
{
// QtWidgets expects single-point touch events, QtDeclarative does not.
// Until there is an API we solve this by looking at the window class type.
- return m_window->inherits("QWidgetWindow");
+ return m_platformWindow->window()->inherits("QWidgetWindow");
}
- (void)touchesBeganWithEvent:(NSEvent *)event
@@ -1323,7 +1305,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
const NSTimeInterval timestamp = [event timestamp];
const QList<QWindowSystemInterface::TouchPoint> points = QCocoaTouch::getCurrentTouchPointList(event, [self shouldSendSingleTouch]);
qCDebug(lcQpaTouch) << "touchesBeganWithEvent" << points;
- QWindowSystemInterface::handleTouchEvent(m_window, timestamp * 1000, touchDevice, points);
+ QWindowSystemInterface::handleTouchEvent(m_platformWindow->window(), timestamp * 1000, touchDevice, points);
}
- (void)touchesMovedWithEvent:(NSEvent *)event
@@ -1331,7 +1313,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
const NSTimeInterval timestamp = [event timestamp];
const QList<QWindowSystemInterface::TouchPoint> points = QCocoaTouch::getCurrentTouchPointList(event, [self shouldSendSingleTouch]);
qCDebug(lcQpaTouch) << "touchesMovedWithEvent" << points;
- QWindowSystemInterface::handleTouchEvent(m_window, timestamp * 1000, touchDevice, points);
+ QWindowSystemInterface::handleTouchEvent(m_platformWindow->window(), timestamp * 1000, touchDevice, points);
}
- (void)touchesEndedWithEvent:(NSEvent *)event
@@ -1339,7 +1321,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
const NSTimeInterval timestamp = [event timestamp];
const QList<QWindowSystemInterface::TouchPoint> points = QCocoaTouch::getCurrentTouchPointList(event, [self shouldSendSingleTouch]);
qCDebug(lcQpaTouch) << "touchesEndedWithEvent" << points;
- QWindowSystemInterface::handleTouchEvent(m_window, timestamp * 1000, touchDevice, points);
+ QWindowSystemInterface::handleTouchEvent(m_platformWindow->window(), timestamp * 1000, touchDevice, points);
}
- (void)touchesCancelledWithEvent:(NSEvent *)event
@@ -1347,7 +1329,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
const NSTimeInterval timestamp = [event timestamp];
const QList<QWindowSystemInterface::TouchPoint> points = QCocoaTouch::getCurrentTouchPointList(event, [self shouldSendSingleTouch]);
qCDebug(lcQpaTouch) << "touchesCancelledWithEvent" << points;
- QWindowSystemInterface::handleTouchEvent(m_window, timestamp * 1000, touchDevice, points);
+ QWindowSystemInterface::handleTouchEvent(m_platformWindow->window(), timestamp * 1000, touchDevice, points);
}
#ifndef QT_NO_GESTURES
@@ -1379,11 +1361,10 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
QPointF windowPoint;
QPointF screenPoint;
[self convertFromScreen:[self screenMousePoint:event] toWindowPoint:&windowPoint andScreenPoint:&screenPoint];
- QWindowSystemInterface::handleGestureEventWithRealValue(m_window, timestamp, Qt::ZoomNativeGesture,
+ QWindowSystemInterface::handleGestureEventWithRealValue(m_platformWindow->window(), timestamp, Qt::ZoomNativeGesture,
[event magnification], windowPoint, screenPoint);
}
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
- (void)smartMagnifyWithEvent:(NSEvent *)event
{
static bool zoomIn = true;
@@ -1392,11 +1373,10 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
QPointF windowPoint;
QPointF screenPoint;
[self convertFromScreen:[self screenMousePoint:event] toWindowPoint:&windowPoint andScreenPoint:&screenPoint];
- QWindowSystemInterface::handleGestureEventWithRealValue(m_window, timestamp, Qt::SmartZoomNativeGesture,
+ QWindowSystemInterface::handleGestureEventWithRealValue(m_platformWindow->window(), timestamp, Qt::SmartZoomNativeGesture,
zoomIn ? 1.0f : 0.0f, windowPoint, screenPoint);
zoomIn = !zoomIn;
}
-#endif
- (void)rotateWithEvent:(NSEvent *)event
{
@@ -1407,7 +1387,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
QPointF windowPoint;
QPointF screenPoint;
[self convertFromScreen:[self screenMousePoint:event] toWindowPoint:&windowPoint andScreenPoint:&screenPoint];
- QWindowSystemInterface::handleGestureEventWithRealValue(m_window, timestamp, Qt::RotateNativeGesture,
+ QWindowSystemInterface::handleGestureEventWithRealValue(m_platformWindow->window(), timestamp, Qt::RotateNativeGesture,
-[event rotation], windowPoint, screenPoint);
}
@@ -1429,7 +1409,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
else if ([event deltaY] == -1)
angle = 270.0f;
- QWindowSystemInterface::handleGestureEventWithRealValue(m_window, timestamp, Qt::SwipeNativeGesture,
+ QWindowSystemInterface::handleGestureEventWithRealValue(m_platformWindow->window(), timestamp, Qt::SwipeNativeGesture,
angle, windowPoint, screenPoint);
}
@@ -1440,7 +1420,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
QPointF screenPoint;
[self convertFromScreen:[self screenMousePoint:event] toWindowPoint:&windowPoint andScreenPoint:&screenPoint];
qCDebug(lcQpaGestures) << "beginGestureWithEvent @" << windowPoint;
- QWindowSystemInterface::handleGestureEvent(m_window, timestamp, Qt::BeginNativeGesture,
+ QWindowSystemInterface::handleGestureEvent(m_platformWindow->window(), timestamp, Qt::BeginNativeGesture,
windowPoint, screenPoint);
}
@@ -1451,7 +1431,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
QPointF windowPoint;
QPointF screenPoint;
[self convertFromScreen:[self screenMousePoint:event] toWindowPoint:&windowPoint andScreenPoint:&screenPoint];
- QWindowSystemInterface::handleGestureEvent(m_window, timestamp, Qt::EndNativeGesture,
+ QWindowSystemInterface::handleGestureEvent(m_platformWindow->window(), timestamp, Qt::EndNativeGesture,
windowPoint, screenPoint);
}
#endif // QT_NO_GESTURES
@@ -1459,7 +1439,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
#ifndef QT_NO_WHEELEVENT
- (void)scrollWheel:(NSEvent *)theEvent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput) )
+ if ([self isTransparentForUserInput])
return [super scrollWheel:theEvent];
QPoint angleDelta;
@@ -1512,16 +1492,12 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
NSEventPhase phase = [theEvent phase];
Qt::ScrollPhase ph = Qt::ScrollUpdate;
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
- if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_8) {
- // On 10.8 and above, MayBegin is likely to happen. We treat it the same as an actual begin.
- if (phase == NSEventPhaseMayBegin) {
- m_scrolling = true;
- ph = Qt::ScrollBegin;
- }
- }
-#endif
- if (phase == NSEventPhaseBegan) {
+
+ // MayBegin is likely to happen. We treat it the same as an actual begin.
+ if (phase == NSEventPhaseMayBegin) {
+ m_scrolling = true;
+ ph = Qt::ScrollBegin;
+ } else if (phase == NSEventPhaseBegan) {
// If MayBegin did not happen, Began is the actual beginning.
if (!m_scrolling)
ph = Qt::ScrollBegin;
@@ -1536,7 +1512,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
// "isInverted": natural OS X scrolling, inverted from the Qt/other platform/Jens perspective.
bool isInverted = [theEvent isDirectionInvertedFromDevice];
- QWindowSystemInterface::handleWheelEvent(m_window, qt_timestamp, qt_windowPoint, qt_screenPoint, pixelDelta, angleDelta, currentWheelModifiers, ph, source, isInverted);
+ QWindowSystemInterface::handleWheelEvent(m_platformWindow->window(), qt_timestamp, qt_windowPoint, qt_screenPoint, pixelDelta, angleDelta, currentWheelModifiers, ph, source, isInverted);
}
#endif //QT_NO_WHEELEVENT
@@ -1595,7 +1571,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
// ignore text for the U+F700-U+F8FF range. This is used by Cocoa when
// delivering function keys (e.g. arrow keys, backspace, F1-F35, etc.)
if (!(modifiers & (Qt::ControlModifier | Qt::MetaModifier)) && (ch.unicode() < 0xf700 || ch.unicode() > 0xf8ff))
- text = QCFString::toQString(characters);
+ text = QString::fromNSString(characters);
QWindow *window = [self topLevelWindow];
@@ -1644,7 +1620,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
- (void)keyDown:(NSEvent *)nsevent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput) )
+ if ([self isTransparentForUserInput])
return [super keyDown:nsevent];
const bool accepted = [self handleKeyEvent:nsevent eventType:int(QEvent::KeyPress)];
@@ -1666,7 +1642,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
- (void)keyUp:(NSEvent *)nsevent
{
- if (m_window && (m_window->flags() & Qt::WindowTransparentForInput) )
+ if ([self isTransparentForUserInput])
return [super keyUp:nsevent];
const bool keyUpAccepted = [self handleKeyEvent:nsevent eventType:int(QEvent::KeyRelease)];
@@ -1727,7 +1703,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
if ((delta & mac_mask) == 0u)
continue;
- QWindowSystemInterface::handleKeyEvent(m_window,
+ QWindowSystemInterface::handleKeyEvent(m_platformWindow->window(),
timestamp,
(lastKnownModifiers & mac_mask) ? QEvent::KeyRelease : QEvent::KeyPress,
modifier_key_symbols[i].qt_code,
@@ -1758,9 +1734,9 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
QString commitString;
if ([aString length]) {
if ([aString isKindOfClass:[NSAttributedString class]]) {
- commitString = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string]));
+ commitString = QString::fromCFString(reinterpret_cast<CFStringRef>([aString string]));
} else {
- commitString = QCFString::toQString(reinterpret_cast<CFStringRef>(aString));
+ commitString = QString::fromCFString(reinterpret_cast<CFStringRef>(aString));
};
}
QObject *fo = QGuiApplication::focusObject();
@@ -1790,7 +1766,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
if ([aString isKindOfClass:[NSAttributedString class]]) {
// Preedit string has attribution
- preeditString = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string]));
+ preeditString = QString::fromCFString(reinterpret_cast<CFStringRef>([aString string]));
int composingLength = preeditString.length();
int index = 0;
// Create attributes for individual sections of preedit text
@@ -1819,7 +1795,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
}
} else {
// No attributes specified, take only the preedit text.
- preeditString = QCFString::toQString(reinterpret_cast<CFStringRef>(aString));
+ preeditString = QString::fromCFString(reinterpret_cast<CFStringRef>(aString));
}
if (attrs.isEmpty()) {
@@ -1938,12 +1914,12 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
if (!queryEvent.value(Qt::ImEnabled).toBool())
return NSZeroRect;
- if (!m_window)
+ if (!m_platformWindow->window())
return NSZeroRect;
// The returned rect is always based on the internal cursor.
QRect mr = qApp->inputMethod()->cursorRectangle().toRect();
- QPoint mp = m_window->mapToGlobal(mr.bottomLeft());
+ QPoint mp = m_platformWindow->window()->mapToGlobal(mr.bottomLeft());
NSRect rect;
rect.origin.x = mp.x();
@@ -1960,9 +1936,9 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
return NSNotFound;
}
-- (NSArray*) validAttributesForMarkedText
+- (NSArray*)validAttributesForMarkedText
{
- if (m_window != QGuiApplication::focusWindow())
+ if (m_platformWindow->window() != QGuiApplication::focusWindow())
return nil;
QObject *fo = QGuiApplication::focusObject();
@@ -2000,7 +1976,7 @@ static QTabletEvent::TabletDevice wacomTabletDevice(NSEvent *theEvent)
NSMultipleTextSelectionPboardType, mimeTypeGeneric, nil];
// Add custom types supported by the application.
for (int i = 0; i < customTypes.size(); i++) {
- [supportedTypes addObject:QCFString::toNSString(customTypes[i])];
+ [supportedTypes addObject:customTypes[i].toNSString()];
}
[self registerForDraggedTypes:supportedTypes];
}
@@ -2137,7 +2113,7 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin
QPoint qt_windowPoint(windowPoint.x, windowPoint.y);
Qt::DropActions qtAllowed = qt_mac_mapNSDragOperations([sender draggingSourceOperationMask]);
- QWindow *target = findEventTargetWindow(m_window);
+ QWindow *target = findEventTargetWindow(m_platformWindow->window());
if (!target)
return NSDragOperationNone;
@@ -2148,11 +2124,11 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin
QCocoaDrag* nativeDrag = QCocoaIntegration::instance()->drag();
if (nativeDrag->currentDrag()) {
// The drag was started from within the application
- response = QWindowSystemInterface::handleDrag(target, nativeDrag->platformDropData(), mapWindowCoordinates(m_window, target, qt_windowPoint), qtAllowed);
+ response = QWindowSystemInterface::handleDrag(target, nativeDrag->platformDropData(), mapWindowCoordinates(m_platformWindow->window(), target, qt_windowPoint), qtAllowed);
[self updateCursorFromDragResponse:response drag:nativeDrag];
} else {
QCocoaDropData mimeData([sender draggingPasteboard]);
- response = QWindowSystemInterface::handleDrag(target, &mimeData, mapWindowCoordinates(m_window, target, qt_windowPoint), qtAllowed);
+ response = QWindowSystemInterface::handleDrag(target, &mimeData, mapWindowCoordinates(m_platformWindow->window(), target, qt_windowPoint), qtAllowed);
}
return qt_mac_mapDropAction(response.acceptedAction());
@@ -2160,7 +2136,7 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin
- (void)draggingExited:(id <NSDraggingInfo>)sender
{
- QWindow *target = findEventTargetWindow(m_window);
+ QWindow *target = findEventTargetWindow(m_platformWindow->window());
if (!target)
return;
@@ -2168,13 +2144,13 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin
QPoint qt_windowPoint(windowPoint.x, windowPoint.y);
// Send 0 mime data to indicate drag exit
- QWindowSystemInterface::handleDrag(target, 0, mapWindowCoordinates(m_window, target, qt_windowPoint), Qt::IgnoreAction);
+ QWindowSystemInterface::handleDrag(target, 0, mapWindowCoordinates(m_platformWindow->window(), target, qt_windowPoint), Qt::IgnoreAction);
}
// called on drop, send the drop to Qt and return if it was accepted.
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
- QWindow *target = findEventTargetWindow(m_window);
+ QWindow *target = findEventTargetWindow(m_platformWindow->window());
if (!target)
return false;
@@ -2186,10 +2162,10 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin
QCocoaDrag* nativeDrag = QCocoaIntegration::instance()->drag();
if (nativeDrag->currentDrag()) {
// The drag was started from within the application
- response = QWindowSystemInterface::handleDrop(target, nativeDrag->platformDropData(), mapWindowCoordinates(m_window, target, qt_windowPoint), qtAllowed);
+ response = QWindowSystemInterface::handleDrop(target, nativeDrag->platformDropData(), mapWindowCoordinates(m_platformWindow->window(), target, qt_windowPoint), qtAllowed);
} else {
QCocoaDropData mimeData([sender draggingPasteboard]);
- response = QWindowSystemInterface::handleDrop(target, &mimeData, mapWindowCoordinates(m_window, target, qt_windowPoint), qtAllowed);
+ response = QWindowSystemInterface::handleDrop(target, &mimeData, mapWindowCoordinates(m_platformWindow->window(), target, qt_windowPoint), qtAllowed);
}
if (response.isAccepted()) {
QCocoaDrag* nativeDrag = QCocoaIntegration::instance()->drag();
@@ -2204,7 +2180,7 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin
{
Q_UNUSED(session);
Q_UNUSED(operation);
- QWindow *target = findEventTargetWindow(m_window);
+ QWindow *target = findEventTargetWindow(m_platformWindow->window());
if (!target)
return;
@@ -2221,7 +2197,7 @@ static QPoint mapWindowCoordinates(QWindow *source, QWindow *target, QPoint poin
QPoint qtScreenPoint = QPoint(screenPoint.x, qt_mac_flipYCoordinate(screenPoint.y));
- QWindowSystemInterface::handleMouseEvent(target, mapWindowCoordinates(m_window, target, qtWindowPoint), qtScreenPoint, m_buttons);
+ QWindowSystemInterface::handleMouseEvent(target, mapWindowCoordinates(m_platformWindow->window(), target, qtWindowPoint), qtScreenPoint, m_buttons);
}
@end
diff --git a/src/plugins/platforms/cocoa/qnsviewaccessibility.mm b/src/plugins/platforms/cocoa/qnsviewaccessibility.mm
index bfb4ba8124..73e1f41dd5 100644
--- a/src/plugins/platforms/cocoa/qnsviewaccessibility.mm
+++ b/src/plugins/platforms/cocoa/qnsviewaccessibility.mm
@@ -53,10 +53,10 @@
@implementation QNSView (QNSViewAccessibility)
- (id)childAccessibleElement {
- if (!m_window->accessibleRoot())
+ if (!m_platformWindow->window()->accessibleRoot())
return nil;
- QAccessible::Id childId = QAccessible::uniqueId(m_window->accessibleRoot());
+ QAccessible::Id childId = QAccessible::uniqueId(m_platformWindow->window()->accessibleRoot());
return [QMacAccessibilityElement elementWithId: childId];
}
diff --git a/src/plugins/platforms/cocoa/qnswindowdelegate.h b/src/plugins/platforms/cocoa/qnswindowdelegate.h
index 5cb4b2aca2..f29aa97b68 100644
--- a/src/plugins/platforms/cocoa/qnswindowdelegate.h
+++ b/src/plugins/platforms/cocoa/qnswindowdelegate.h
@@ -57,6 +57,8 @@
- (void)windowWillMove:(NSNotification *)notification;
- (BOOL)windowShouldClose:(NSNotification *)notification;
- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame;
+- (void)windowWillClose:(NSNotification *)notification;
+
- (BOOL)window:(NSWindow *)window shouldPopUpDocumentPathMenu:(NSMenu *)menu;
- (BOOL)window:(NSWindow *)window shouldDragDocumentWithEvent:(NSEvent *)event from:(NSPoint)dragImageLocation withPasteboard:(NSPasteboard *)pasteboard;
@end
diff --git a/src/plugins/platforms/cocoa/qnswindowdelegate.mm b/src/plugins/platforms/cocoa/qnswindowdelegate.mm
index 320a7890bf..7f988ac963 100644
--- a/src/plugins/platforms/cocoa/qnswindowdelegate.mm
+++ b/src/plugins/platforms/cocoa/qnswindowdelegate.mm
@@ -38,6 +38,7 @@
****************************************************************************/
#include "qnswindowdelegate.h"
+#include "qcocoahelpers.h"
#include <QDebug>
#include <qpa/qwindowsysteminterface.h>
@@ -60,7 +61,7 @@
if (m_cocoaWindow->m_windowUnderMouse) {
QPointF windowPoint;
QPointF screenPoint;
- [m_cocoaWindow->m_qtView convertFromScreen:[NSEvent mouseLocation] toWindowPoint:&windowPoint andScreenPoint:&screenPoint];
+ [qnsview_cast(m_cocoaWindow->view()) convertFromScreen:[NSEvent mouseLocation] toWindowPoint:&windowPoint andScreenPoint:&screenPoint];
QWindowSystemInterface::handleEnterEvent(m_cocoaWindow->m_enterLeaveTargetWindow, windowPoint, screenPoint);
}
}
@@ -110,11 +111,18 @@
- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame
{
Q_UNUSED(newFrame);
- if (m_cocoaWindow && m_cocoaWindow->m_qtView)
- [m_cocoaWindow->m_qtView notifyWindowWillZoom:![window isZoomed]];
+ if (m_cocoaWindow && m_cocoaWindow->window()->type() != Qt::ForeignWindow)
+ [qnsview_cast(m_cocoaWindow->view()) notifyWindowWillZoom:![window isZoomed]];
return YES;
}
+- (void)windowWillClose:(NSNotification *)notification
+{
+ Q_UNUSED(notification);
+ if (m_cocoaWindow)
+ m_cocoaWindow->windowWillClose();
+}
+
- (BOOL)window:(NSWindow *)window shouldPopUpDocumentPathMenu:(NSMenu *)menu
{
Q_UNUSED(window);
diff --git a/src/plugins/platforms/cocoa/qpaintengine_mac.mm b/src/plugins/platforms/cocoa/qpaintengine_mac.mm
index 395c25c915..7e241e3ae6 100644
--- a/src/plugins/platforms/cocoa/qpaintengine_mac.mm
+++ b/src/plugins/platforms/cocoa/qpaintengine_mac.mm
@@ -63,6 +63,7 @@
#include <private/qpainter_p.h>
#include <private/qpainterpath_p.h>
#include <private/qtextengine_p.h>
+#include <private/qcoregraphics_p.h>
#include "qcocoahelpers.h"
@@ -74,87 +75,6 @@ QT_BEGIN_NAMESPACE
QCoreGraphicsPaintEngine utility functions
*****************************************************************************/
-static void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform)
-{
- CGAffineTransform old_xform = CGAffineTransformIdentity;
- if (orig_xform) { //setup xforms
- old_xform = CGContextGetCTM(hd);
- CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
- CGContextConcatCTM(hd, *orig_xform);
- }
-
- //do the clipping
- CGContextBeginPath(hd);
- if (rgn.isEmpty()) {
- CGContextAddRect(hd, CGRectMake(0, 0, 0, 0));
- } else {
- QVector<QRect> rects = rgn.rects();
- const int count = rects.size();
- for (int i = 0; i < count; i++) {
- const QRect &r = rects[i];
- CGRect mac_r = CGRectMake(r.x(), r.y(), r.width(), r.height());
- CGContextAddRect(hd, mac_r);
- }
- }
- CGContextClip(hd);
-
- if (orig_xform) {//reset xforms
- CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
- CGContextConcatCTM(hd, old_xform);
- }
-}
-
-// Implemented for qt_mac_p.h
-QMacCGContext::QMacCGContext(QPainter *p)
-{
- QPaintEngine *pe = p->paintEngine();
-#ifndef QT_NO_PRINTER
- if (pe->type() == QPaintEngine::MacPrinter)
- pe = static_cast<QMacPrintEngine*>(pe)->paintEngine();
-#endif
- pe->syncState();
- context = 0;
- if (pe->type() == QPaintEngine::CoreGraphics)
- context = static_cast<QCoreGraphicsPaintEngine*>(pe)->handle();
-
- int devType = p->device()->devType();
- if (pe->type() == QPaintEngine::Raster
- && (devType == QInternal::Widget || devType == QInternal::Pixmap || devType == QInternal::Image)) {
-
- CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pe->paintDevice());
- uint flags = kCGImageAlphaPremultipliedFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
- flags |= kCGBitmapByteOrder32Host;
-#endif
- const QImage *image = (const QImage *) pe->paintDevice();
-
- context = CGBitmapContextCreate((void *) image->bits(), image->width(), image->height(),
- 8, image->bytesPerLine(), colorspace, flags);
-
- CGContextTranslateCTM(context, 0, image->height());
- CGContextScaleCTM(context, 1, -1);
-
- if (devType == QInternal::Widget) {
- QRegion clip = p->paintEngine()->systemClip();
- QTransform native = p->deviceTransform();
-
- if (p->hasClipping()) {
- QRegion r = p->clipRegion();
- r.translate(native.dx(), native.dy());
- if (clip.isEmpty())
- clip = r;
- else
- clip &= r;
- }
- qt_mac_clip_cg(context, clip, 0);
-
- CGContextTranslateCTM(context, native.dx(), native.dy());
- }
- } else {
- CGContextRetain(context);
- }
-}
-
void qt_mac_cgimage_data_free(void *, const void *memoryToFree, size_t)
{
free(const_cast<void *>(memoryToFree));
@@ -456,7 +376,7 @@ static void qt_mac_draw_pattern(void *info, CGContextRef c)
const QColor c0(0, 0, 0, 0), c1(255, 255, 255, 255);
QPixmap pm(w*QMACPATTERN_MASK_MULTIPLIER, h*QMACPATTERN_MASK_MULTIPLIER);
pm.fill(c0);
- CGContextRef pm_ctx = qt_mac_cg_context(&pm);
+ QMacCGContext pm_ctx(&pm);
CGContextSetFillColorWithColor(c, cgColorForQColor(c1, pat->pdev));
CGRect rect = CGRectMake(0, 0, w, h);
for (int x = 0; x < QMACPATTERN_MASK_MULTIPLIER; ++x) {
@@ -546,7 +466,8 @@ QCoreGraphicsPaintEngine::begin(QPaintDevice *pdev)
d->cosmeticPenSize = 1;
d->current.clipEnabled = false;
d->pixelSize = QPoint(1,1);
- d->hd = qt_mac_cg_context(pdev);
+ QMacCGContext ctx(pdev);
+ d->hd = CGContextRetain(ctx);
if (d->hd) {
d->saveGraphicsState();
d->orig_xform = CGContextGetCTM(d->hd);
diff --git a/src/plugins/platforms/cocoa/qprintengine_mac.mm b/src/plugins/platforms/cocoa/qprintengine_mac.mm
index 3d0c91c36c..8098c5e829 100644
--- a/src/plugins/platforms/cocoa/qprintengine_mac.mm
+++ b/src/plugins/platforms/cocoa/qprintengine_mac.mm
@@ -200,7 +200,7 @@ int QMacPrintEngine::metric(QPaintDevice::PaintDeviceMetric m) const
val = (int)resolution.vRes;
break;
}
- //otherwise fall through
+ Q_FALLTHROUGH();
}
case QPaintDevice::PdmDpiY:
val = (int)d->resolution.vRes;
@@ -673,7 +673,7 @@ QVariant QMacPrintEngine::property(PrintEnginePropertyKey key) const
case PPK_DocumentName: {
CFStringRef name;
PMPrintSettingsGetJobName(d->settings(), &name);
- ret = QCFString::toQString(name);
+ ret = QString::fromCFString(name);
break;
}
case PPK_Duplex: {
diff --git a/src/plugins/platforms/cocoa/qprintengine_mac_p.h b/src/plugins/platforms/cocoa/qprintengine_mac_p.h
index e3cad3fd57..ee98275b63 100644
--- a/src/plugins/platforms/cocoa/qprintengine_mac_p.h
+++ b/src/plugins/platforms/cocoa/qprintengine_mac_p.h
@@ -149,6 +149,9 @@ public:
PMPageFormat format() const { return static_cast<PMPageFormat>([printInfo PMPageFormat]); }
PMPrintSession session() const { return static_cast<PMPrintSession>([printInfo PMPrintSession]); }
PMPrintSettings settings() const { return static_cast<PMPrintSettings>([printInfo PMPrintSettings]); }
+
+ QPaintEngine *aggregateEngine() Q_DECL_OVERRIDE { return paintEngine; }
+ Qt::HANDLE nativeHandle() Q_DECL_OVERRIDE { return q_func()->handle(); }
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/cocoa/qt_mac_p.h b/src/plugins/platforms/cocoa/qt_mac_p.h
index 03eae1b2e7..fdcf3bcdd3 100644
--- a/src/plugins/platforms/cocoa/qt_mac_p.h
+++ b/src/plugins/platforms/cocoa/qt_mac_p.h
@@ -51,13 +51,13 @@
// We mean it.
//
-#include "qmacdefines_mac.h"
-
#ifdef __OBJC__
#include <AppKit/AppKit.h>
#include <objc/runtime.h>
#endif
+#include "qmacdefines_mac.h"
+
#include <CoreServices/CoreServices.h>
#include "QtCore/qglobal.h"
@@ -90,60 +90,6 @@ public:
}
};
-class Q_WIDGETS_EXPORT QMacWindowChangeEvent
-{
-private:
- static QList<QMacWindowChangeEvent*> *change_events;
-public:
- QMacWindowChangeEvent() {
- }
- virtual ~QMacWindowChangeEvent() {
- }
- static inline void exec(bool ) {
- }
-protected:
- virtual void windowChanged() = 0;
- virtual void flushWindowChanged() = 0;
-};
-
-class QMacCGContext
-{
- CGContextRef context;
-public:
- QMacCGContext(QPainter *p); //qpaintengine_mac.mm
- inline QMacCGContext() { context = 0; }
- inline QMacCGContext(QPaintDevice *pdev) {
- extern CGContextRef qt_mac_cg_context(QPaintDevice *);
- context = qt_mac_cg_context(pdev);
- }
- inline QMacCGContext(CGContextRef cg, bool takeOwnership=false) {
- context = cg;
- if(!takeOwnership)
- CGContextRetain(context);
- }
- inline QMacCGContext(const QMacCGContext &copy) : context(0) { *this = copy; }
- inline ~QMacCGContext() {
- if(context)
- CGContextRelease(context);
- }
- inline bool isNull() const { return context; }
- inline operator CGContextRef() { return context; }
- inline QMacCGContext &operator=(const QMacCGContext &copy) {
- if(context)
- CGContextRelease(context);
- context = copy.context;
- CGContextRetain(context);
- return *this;
- }
- inline QMacCGContext &operator=(CGContextRef cg) {
- if(context)
- CGContextRelease(context);
- context = cg;
- CGContextRetain(context); //we do not take ownership
- return *this;
- }
-};
-
class QMacInternalPasteboardMime;
class QMimeData;
diff --git a/src/plugins/platforms/cocoa/qt_menu.nib/classes.nib b/src/plugins/platforms/cocoa/qt_menu.nib/classes.nib
deleted file mode 100644
index 78941153c2..0000000000
--- a/src/plugins/platforms/cocoa/qt_menu.nib/classes.nib
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>IBClasses</key>
- <array>
- <dict>
- <key>ACTIONS</key>
- <dict>
- <key>hide</key>
- <string>id</string>
- <key>hideOtherApplications</key>
- <string>id</string>
- <key>orderFrontStandardAboutPanel</key>
- <string>id</string>
- <key>qtDispatcherToQPAMenuItem</key>
- <string>id</string>
- <key>terminate</key>
- <string>id</string>
- <key>unhideAllApplications</key>
- <string>id</string>
- </dict>
- <key>CLASS</key>
- <string>QCocoaMenuLoader</string>
- <key>LANGUAGE</key>
- <string>ObjC</string>
- <key>OUTLETS</key>
- <dict>
- <key>aboutItem</key>
- <string>NSMenuItem</string>
- <key>aboutQtItem</key>
- <string>NSMenuItem</string>
- <key>appMenu</key>
- <string>NSMenu</string>
- <key>hideItem</key>
- <string>NSMenuItem</string>
- <key>preferencesItem</key>
- <string>NSMenuItem</string>
- <key>quitItem</key>
- <string>NSMenuItem</string>
- <key>theMenu</key>
- <string>NSMenu</string>
- </dict>
- <key>SUPERCLASS</key>
- <string>NSResponder</string>
- </dict>
- <dict>
- <key>CLASS</key>
- <string>FirstResponder</string>
- <key>LANGUAGE</key>
- <string>ObjC</string>
- <key>SUPERCLASS</key>
- <string>NSObject</string>
- </dict>
- </array>
- <key>IBVersion</key>
- <string>1</string>
-</dict>
-</plist>
diff --git a/src/plugins/platforms/cocoa/qt_menu.nib/info.nib b/src/plugins/platforms/cocoa/qt_menu.nib/info.nib
deleted file mode 100644
index 02e5cca562..0000000000
--- a/src/plugins/platforms/cocoa/qt_menu.nib/info.nib
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>IBFramework Version</key>
- <string>672</string>
- <key>IBOldestOS</key>
- <integer>5</integer>
- <key>IBOpenObjects</key>
- <array>
- <integer>57</integer>
- </array>
- <key>IBSystem Version</key>
- <string>9L31a</string>
- <key>targetFramework</key>
- <string>IBCocoaFramework</string>
-</dict>
-</plist>
diff --git a/src/plugins/platforms/cocoa/qt_menu.nib/keyedobjects.nib b/src/plugins/platforms/cocoa/qt_menu.nib/keyedobjects.nib
deleted file mode 100644
index 67207ca628..0000000000
--- a/src/plugins/platforms/cocoa/qt_menu.nib/keyedobjects.nib
+++ /dev/null
Binary files differ
diff --git a/src/plugins/platforms/direct2d/direct2d.pro b/src/plugins/platforms/direct2d/direct2d.pro
index 005a4da6db..224f122fc4 100644
--- a/src/plugins/platforms/direct2d/direct2d.pro
+++ b/src/plugins/platforms/direct2d/direct2d.pro
@@ -1,10 +1,11 @@
TARGET = qdirect2d
-QT *= core-private
-QT *= gui-private
-QT *= platformsupport-private
+QT += \
+ core-private gui-private \
+ eventdispatcher_support-private accessibility_support-private \
+ fontdatabase_support-private theme_support-private
-LIBS *= -ld2d1 -ld3d11 -ldwrite -lVersion -lgdi32
+LIBS += -ldwmapi -ld2d1 -ld3d11 -ldwrite -lVersion -lgdi32
include(../windows/windows.pri)
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.cpp b/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.cpp
index 97eadb207b..38f2352934 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.cpp
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.cpp
@@ -95,7 +95,7 @@ void QWindowsDirect2DBackingStore::beginPaint(const QRegion &region)
painter.setCompositionMode(QPainter::CompositionMode_Source);
- foreach (const QRect &r, region.rects())
+ for (const QRect &r : region)
painter.fillRect(r, clear);
}
@@ -127,10 +127,14 @@ void QWindowsDirect2DBackingStore::resize(const QSize &size, const QRegion &regi
QPixmap *newPixmap = nativeWindow(window())->pixmap();
if (!old.isNull()) {
- foreach (const QRect &rect, region.rects()) {
+ for (const QRect &rect : region)
platformPixmap(newPixmap)->copy(old.handle(), rect);
- }
}
}
+QImage QWindowsDirect2DBackingStore::toImage() const
+{
+ return nativeWindow(window())->pixmap()->toImage();
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.h b/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.h
index 9d754866cc..670c4e9840 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.h
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.h
@@ -60,6 +60,8 @@ public:
QPaintDevice *paintDevice() Q_DECL_OVERRIDE;
void flush(QWindow *targetWindow, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE;
void resize(const QSize &size, const QRegion &staticContents) Q_DECL_OVERRIDE;
+
+ QImage toImage() const override;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dbitmap.cpp b/src/plugins/platforms/direct2d/qwindowsdirect2dbitmap.cpp
index 2d107a6e27..b5065ba380 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dbitmap.cpp
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dbitmap.cpp
@@ -80,7 +80,7 @@ public:
bitmap.Reset();
D2D1_SIZE_U size = {
- width, height
+ UINT32(width), UINT32(height)
};
HRESULT hr = deviceContext->get()->CreateBitmap(size, data, pitch,
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dhelpers.h b/src/plugins/platforms/direct2d/qwindowsdirect2dhelpers.h
index 97715ad050..34225bba9a 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dhelpers.h
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dhelpers.h
@@ -46,6 +46,13 @@
#include <QtGui/QColor>
#include <QtGui/QTransform>
+#ifdef Q_CC_MINGW
+# include <qt_windows.h>
+# include <d2d1.h>
+# include <d2d1helper.h>
+# include <d2dbasetypes.h>
+# include <d2d1_1.h>
+#endif // Q_CC_MINGW
#include <d2d1_1helper.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dintegration.cpp b/src/plugins/platforms/direct2d/qwindowsdirect2dintegration.cpp
index deabe98fbe..da4a4e6ce6 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dintegration.cpp
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dintegration.cpp
@@ -50,7 +50,9 @@
#include <QtCore/QCoreApplication>
#include <QtGui/private/qpixmap_raster_p.h>
#include <QtGui/qpa/qwindowsysteminterface.h>
-#include <QtPlatformSupport/private/qwindowsguieventdispatcher_p.h>
+#include <QtEventDispatcherSupport/private/qwindowsguieventdispatcher_p.h>
+
+#include <QVarLengthArray>
QT_BEGIN_NAMESPACE
@@ -106,7 +108,7 @@ public:
if (_tcscat_s(filename, bufSize, __TEXT("\\d2d1.dll")) == 0) {
DWORD versionInfoSize = GetFileVersionInfoSize(filename, NULL);
if (versionInfoSize) {
- QVector<BYTE> info(versionInfoSize);
+ QVarLengthArray<BYTE> info(versionInfoSize);
if (GetFileVersionInfo(filename, NULL, versionInfoSize, info.data())) {
UINT size;
DWORD *fi;
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dpaintengine.cpp b/src/plugins/platforms/direct2d/qwindowsdirect2dpaintengine.cpp
index 730d5de450..69d2e12778 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dpaintengine.cpp
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dpaintengine.cpp
@@ -45,8 +45,8 @@
#include "qwindowsdirect2dbitmap.h"
#include "qwindowsdirect2ddevicecontext.h"
-#include "qwindowsfontengine.h"
-#include "qwindowsfontdatabase.h"
+#include <QtFontDatabaseSupport/private/qwindowsfontdatabase_p.h>
+#include <QtFontDatabaseSupport/private/qwindowsfontengine_p.h>
#include "qwindowsintegration.h"
#include <QtCore/QtMath>
@@ -563,7 +563,7 @@ public:
if (newPen.widthF() <= 1.0)
props.startCap = props.endCap = props.dashCap = D2D1_CAP_STYLE_FLAT;
- // fall through
+ Q_FALLTHROUGH();
default:
props.dashStyle = D2D1_DASH_STYLE_CUSTOM;
break;
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dwindow.cpp b/src/plugins/platforms/direct2d/qwindowsdirect2dwindow.cpp
index 4e677166b2..c750b02078 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dwindow.cpp
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dwindow.cpp
@@ -122,7 +122,7 @@ void QWindowsDirect2DWindow::flush(QWindowsDirect2DBitmap *bitmap, const QRegion
QRegion clipped = region;
clipped &= QRect(QPoint(), size);
- foreach (const QRect &rect, clipped.rects()) {
+ for (const QRect &rect : clipped) {
QRectF rectF(rect);
dc->DrawBitmap(bitmap->bitmap(),
to_d2d_rect_f(rectF),
diff --git a/src/plugins/platforms/directfb/directfb.pro b/src/plugins/platforms/directfb/directfb.pro
index 5c81e0283a..4e95aebe35 100644
--- a/src/plugins/platforms/directfb/directfb.pro
+++ b/src/plugins/platforms/directfb/directfb.pro
@@ -1,9 +1,11 @@
TARGET = qdirectfb
-QT += core-private gui-private platformsupport-private
+QT += \
+ core-private gui-private \
+ eventdispatcher_support-private service_support-private \
+ fontdatabase_support-private egl_support-private
-LIBS += $$QMAKE_LIBS_DIRECTFB
-QMAKE_CXXFLAGS += $$QMAKE_CFLAGS_DIRECTFB
+QMAKE_USE += directfb
SOURCES = main.cpp \
qdirectfbintegration.cpp \
@@ -42,9 +44,6 @@ contains(QT_CONFIG, directfb_egl) {
SOURCES += qdirectfbeglhooks_stub.cpp
}
-
-CONFIG += qpa/genericunixfontdatabase
-
OTHER_FILES += directfb.json
PLUGIN_TYPE = platforms
diff --git a/src/plugins/platforms/directfb/qdirectfb_egl.cpp b/src/plugins/platforms/directfb/qdirectfb_egl.cpp
index 2a04c0bba3..dad553c890 100644
--- a/src/plugins/platforms/directfb/qdirectfb_egl.cpp
+++ b/src/plugins/platforms/directfb/qdirectfb_egl.cpp
@@ -46,10 +46,10 @@
#include <qpa/qplatformopenglcontext.h>
#include <QtGui/QScreen>
-#include <QtPlatformSupport/private/qeglplatformcontext_p.h>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglplatformcontext_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
-#include <QtPlatformSupport/private/qt_egl_p.h>
+#include <QtEglSupport/private/qt_egl_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/directfb/qdirectfbbackingstore.cpp b/src/plugins/platforms/directfb/qdirectfbbackingstore.cpp
index 0bcf93aa3d..8d5e1e50c4 100644
--- a/src/plugins/platforms/directfb/qdirectfbbackingstore.cpp
+++ b/src/plugins/platforms/directfb/qdirectfbbackingstore.cpp
@@ -70,9 +70,7 @@ void QDirectFbBackingStore::flush(QWindow *, const QRegion &region, const QPoint
{
m_pmdata->blittable()->unlock();
- QVector<QRect> rects = region.rects();
- for (int i = 0 ; i < rects.size(); i++) {
- const QRect rect = rects.at(i);
+ for (const QRect &rect : region) {
DFBRegion dfbReg(rect.x() + offset.x(),rect.y() + offset.y(),rect.right() + offset.x(),rect.bottom() + offset.y());
m_dfbSurface->Flip(m_dfbSurface.data(), &dfbReg, DFBSurfaceFlipFlags(DSFLIP_BLIT|DSFLIP_ONSYNC));
}
@@ -108,13 +106,15 @@ bool QDirectFbBackingStore::scroll(const QRegion &area, int dx, int dy)
if (area.rectCount() == 1) {
scrollSurface(m_dfbSurface.data(), area.boundingRect(), dx, dy);
} else {
- const QVector<QRect> rects = area.rects();
- const int n = rects.size();
- for (int i=0; i<n; ++i) {
- scrollSurface(m_dfbSurface.data(), rects.at(i), dx, dy);
- }
+ for (const QRect &rect : area)
+ scrollSurface(m_dfbSurface.data(), rect, dx, dy);
}
return true;
}
+QImage QDirectFbBackingStore::toImage() const
+{
+ return m_pixmap.data()->toImage();
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/directfb/qdirectfbbackingstore.h b/src/plugins/platforms/directfb/qdirectfbbackingstore.h
index 33ab1c111d..af1ce92e64 100644
--- a/src/plugins/platforms/directfb/qdirectfbbackingstore.h
+++ b/src/plugins/platforms/directfb/qdirectfbbackingstore.h
@@ -59,6 +59,8 @@ public:
void resize (const QSize &size, const QRegion &staticContents);
bool scroll(const QRegion &area, int dx, int dy);
+ QImage toImage() const override;
+
private:
void lockSurfaceToImage();
diff --git a/src/plugins/platforms/directfb/qdirectfbintegration.cpp b/src/plugins/platforms/directfb/qdirectfbintegration.cpp
index 506432f886..cdf340da7a 100644
--- a/src/plugins/platforms/directfb/qdirectfbintegration.cpp
+++ b/src/plugins/platforms/directfb/qdirectfbintegration.cpp
@@ -44,9 +44,9 @@
#include "qdirectfbcursor.h"
#include "qdirectfbwindow.h"
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
-#include <QtPlatformSupport/private/qgenericunixservices_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtServiceSupport/private/qgenericunixservices_p.h>
#include <QtGui/private/qpixmap_blitter_p.h>
#include <QtGui/private/qpixmap_raster_p.h>
diff --git a/src/plugins/platforms/eglfs/api/api.pri b/src/plugins/platforms/eglfs/api/api.pri
new file mode 100644
index 0000000000..0ea65bd1ff
--- /dev/null
+++ b/src/plugins/platforms/eglfs/api/api.pri
@@ -0,0 +1,21 @@
+
+SOURCES += $$PWD/qeglfswindow.cpp \
+ $$PWD/qeglfsscreen.cpp \
+ $$PWD/qeglfscursor.cpp \
+ $$PWD/qeglfshooks.cpp \
+ $$PWD/qeglfsdeviceintegration.cpp \
+ $$PWD/qeglfsintegration.cpp \
+ $$PWD/qeglfscontext.cpp \
+ $$PWD/qeglfsoffscreenwindow.cpp
+
+HEADERS += $$PWD/qeglfswindow_p.h \
+ $$PWD/qeglfsscreen_p.h \
+ $$PWD/qeglfscursor_p.h \
+ $$PWD/qeglfshooks_p.h \
+ $$PWD/qeglfsdeviceintegration_p.h \
+ $$PWD/qeglfsintegration_p.h \
+ $$PWD/qeglfscontext_p.h \
+ $$PWD/qeglfsoffscreenwindow_p.h \
+ $$PWD/qeglfsglobal_p.h
+
+INCLUDEPATH += $$PWD
diff --git a/src/plugins/platforms/eglfs/qeglfscontext.cpp b/src/plugins/platforms/eglfs/api/qeglfscontext.cpp
index 6acb362bf0..c5cef34d8e 100644
--- a/src/plugins/platforms/eglfs/qeglfscontext.cpp
+++ b/src/plugins/platforms/eglfs/api/qeglfscontext.cpp
@@ -37,15 +37,15 @@
**
****************************************************************************/
-#include "qeglfsglobal.h"
+#include "qeglfsglobal_p.h"
#include <QtGui/QSurface>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-#include <QtPlatformSupport/private/qeglpbuffer_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglpbuffer_p.h>
-#include "qeglfscontext.h"
-#include "qeglfswindow.h"
-#include "qeglfshooks.h"
-#include "qeglfscursor.h"
+#include "qeglfscontext_p.h"
+#include "qeglfswindow_p.h"
+#include "qeglfshooks_p.h"
+#include "qeglfscursor_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfscontext.h b/src/plugins/platforms/eglfs/api/qeglfscontext_p.h
index 91c5a7910b..ab5bf99c3c 100644
--- a/src/plugins/platforms/eglfs/qeglfscontext.h
+++ b/src/plugins/platforms/eglfs/api/qeglfscontext_p.h
@@ -40,8 +40,19 @@
#ifndef QEGLFSCONTEXT_H
#define QEGLFSCONTEXT_H
-#include "qeglfsglobal.h"
-#include <QtPlatformSupport/private/qeglplatformcontext_p.h>
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qeglfsglobal_p.h"
+#include <QtEglSupport/private/qeglplatformcontext_p.h>
#include <QtCore/QVariant>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfscursor.cpp b/src/plugins/platforms/eglfs/api/qeglfscursor.cpp
index 6c8c35b1dc..2b54251a06 100644
--- a/src/plugins/platforms/eglfs/qeglfscursor.cpp
+++ b/src/plugins/platforms/eglfs/api/qeglfscursor.cpp
@@ -37,9 +37,9 @@
**
****************************************************************************/
-#include "qeglfscursor.h"
-#include "qeglfsintegration.h"
-#include "qeglfsscreen.h"
+#include "qeglfscursor_p.h"
+#include "qeglfsintegration_p.h"
+#include "qeglfsscreen_p.h"
#include <qpa/qwindowsysteminterface.h>
#include <QtGui/QOpenGLContext>
@@ -59,12 +59,11 @@
QT_BEGIN_NAMESPACE
QEglFSCursor::QEglFSCursor(QPlatformScreen *screen)
- : m_visible(true),
- m_screen(static_cast<QEglFSScreen *>(screen)),
- m_program(0),
- m_textureEntry(0),
- m_deviceListener(0),
- m_updateRequested(false)
+ : m_visible(true),
+ m_screen(static_cast<QEglFSScreen *>(screen)),
+ m_activeScreen(nullptr),
+ m_deviceListener(0),
+ m_updateRequested(false)
{
QByteArray hideCursorVal = qgetenv("QT_QPA_EGLFS_HIDECURSOR");
if (!hideCursorVal.isEmpty())
@@ -72,6 +71,10 @@ QEglFSCursor::QEglFSCursor(QPlatformScreen *screen)
if (!m_visible)
return;
+ int rotation = qEnvironmentVariableIntValue("QT_QPA_EGLFS_ROTATION");
+ if (rotation)
+ m_rotationMatrix.rotate(rotation, 0, 0, 1);
+
// Try to load the cursor atlas. If this fails, m_visible is set to false and
// paintOnScreen() and setCurrentCursor() become no-ops.
initCursorAtlas();
@@ -112,15 +115,14 @@ void QEglFSCursorDeviceListener::onDeviceListChanged(QInputDeviceManager::Device
void QEglFSCursor::resetResources()
{
- if (QOpenGLContext::currentContext()) {
- delete m_program;
- glDeleteTextures(1, &m_cursor.customCursorTexture);
- glDeleteTextures(1, &m_cursorAtlas.texture);
+ if (QOpenGLContext *ctx = QOpenGLContext::currentContext()) {
+ GraphicsContextData &gfx(m_gfx[ctx]);
+ delete gfx.program;
+ glDeleteTextures(1, &gfx.customCursorTexture);
+ glDeleteTextures(1, &gfx.atlasTexture);
+ gfx = GraphicsContextData();
}
- m_program = 0;
- m_cursor.customCursorTexture = 0;
m_cursor.customCursorPending = !m_cursor.customCursorImage.isNull();
- m_cursorAtlas.texture = 0;
}
void QEglFSCursor::createShaderPrograms()
@@ -129,9 +131,10 @@ void QEglFSCursor::createShaderPrograms()
"attribute highp vec2 vertexCoordEntry;\n"
"attribute highp vec2 textureCoordEntry;\n"
"varying highp vec2 textureCoord;\n"
+ "uniform highp mat4 mat;\n"
"void main() {\n"
" textureCoord = textureCoordEntry;\n"
- " gl_Position = vec4(vertexCoordEntry, 1.0, 1.0);\n"
+ " gl_Position = mat * vec4(vertexCoordEntry, 1.0, 1.0);\n"
"}\n";
static const char *textureFragmentProgram =
@@ -141,14 +144,16 @@ void QEglFSCursor::createShaderPrograms()
" gl_FragColor = texture2D(texture, textureCoord).bgra;\n"
"}\n";
- m_program = new QOpenGLShaderProgram;
- m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, textureVertexProgram);
- m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, textureFragmentProgram);
- m_program->bindAttributeLocation("vertexCoordEntry", 0);
- m_program->bindAttributeLocation("textureCoordEntry", 1);
- m_program->link();
+ GraphicsContextData &gfx(m_gfx[QOpenGLContext::currentContext()]);
+ gfx.program = new QOpenGLShaderProgram;
+ gfx.program->addShaderFromSourceCode(QOpenGLShader::Vertex, textureVertexProgram);
+ gfx.program->addShaderFromSourceCode(QOpenGLShader::Fragment, textureFragmentProgram);
+ gfx.program->bindAttributeLocation("vertexCoordEntry", 0);
+ gfx.program->bindAttributeLocation("textureCoordEntry", 1);
+ gfx.program->link();
- m_textureEntry = m_program->uniformLocation("texture");
+ gfx.textureEntry = gfx.program->uniformLocation("texture");
+ gfx.matEntry = gfx.program->uniformLocation("mat");
}
void QEglFSCursor::createCursorTexture(uint *texture, const QImage &image)
@@ -208,7 +213,7 @@ void QEglFSCursor::changeCursor(QCursor *cursor, QWindow *window)
Q_UNUSED(window);
const QRect oldCursorRect = cursorRect();
if (setCurrentCursor(cursor))
- update(oldCursorRect | cursorRect());
+ update(oldCursorRect | cursorRect(), false);
}
bool QEglFSCursor::setCurrentCursor(QCursor *cursor)
@@ -232,16 +237,17 @@ bool QEglFSCursor::setCurrentCursor(QCursor *cursor)
hs * (m_cursor.shape / m_cursorAtlas.cursorsPerRow),
ws, hs);
m_cursor.hotSpot = m_cursorAtlas.hotSpots[m_cursor.shape];
- m_cursor.texture = m_cursorAtlas.texture;
+ m_cursor.useCustomCursor = false;
m_cursor.size = QSize(m_cursorAtlas.cursorWidth, m_cursorAtlas.cursorHeight);
} else {
QImage image = cursor->pixmap().toImage();
m_cursor.textureRect = QRectF(0, 0, 1, 1);
m_cursor.hotSpot = cursor->hotSpot();
- m_cursor.texture = 0; // will get updated in the next render()
+ m_cursor.useCustomCursor = false; // will get updated in the next render()
m_cursor.size = image.size();
m_cursor.customCursorImage = image;
m_cursor.customCursorPending = true;
+ m_cursor.customCursorKey = m_cursor.customCursorImage.cacheKey();
}
return true;
@@ -251,17 +257,20 @@ bool QEglFSCursor::setCurrentCursor(QCursor *cursor)
class CursorUpdateEvent : public QEvent
{
public:
- CursorUpdateEvent(const QPoint &pos, const QRegion &rgn)
+ CursorUpdateEvent(const QPoint &pos, const QRect &rect, bool allScreens)
: QEvent(QEvent::Type(QEvent::User + 1)),
m_pos(pos),
- m_region(rgn)
+ m_rect(rect),
+ m_allScreens(allScreens)
{ }
QPoint pos() const { return m_pos; }
- QRegion region() const { return m_region; }
+ QRegion rect() const { return m_rect; }
+ bool allScreens() const { return m_allScreens; }
private:
QPoint m_pos;
- QRegion m_region;
+ QRect m_rect;
+ bool m_allScreens;
};
bool QEglFSCursor::event(QEvent *e)
@@ -269,21 +278,30 @@ bool QEglFSCursor::event(QEvent *e)
if (e->type() == QEvent::User + 1) {
CursorUpdateEvent *ev = static_cast<CursorUpdateEvent *>(e);
m_updateRequested = false;
- QWindowSystemInterface::handleExposeEvent(m_screen->topLevelAt(ev->pos()), ev->region());
- QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
+ if (!ev->allScreens()) {
+ QWindow *w = m_screen->topLevelAt(ev->pos()); // works for the entire virtual desktop, no need to loop
+ if (w) {
+ QWindowSystemInterface::handleExposeEvent(w, ev->rect());
+ QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
+ }
+ } else {
+ for (QWindow *w : qGuiApp->topLevelWindows())
+ QWindowSystemInterface::handleExposeEvent(w, w->geometry());
+ QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
+ }
return true;
}
return QPlatformCursor::event(e);
}
-void QEglFSCursor::update(const QRegion &rgn)
+void QEglFSCursor::update(const QRect &rect, bool allScreens)
{
if (!m_updateRequested) {
// Must not flush the window system events directly from here since we are likely to
// be a called directly from QGuiApplication's processMouseEvents. Flushing events
// could cause reentering by dispatching more queued mouse events.
m_updateRequested = true;
- QCoreApplication::postEvent(this, new CursorUpdateEvent(m_cursor.pos, rgn));
+ QCoreApplication::postEvent(this, new CursorUpdateEvent(m_cursor.pos, rect, allScreens));
}
}
@@ -302,8 +320,9 @@ void QEglFSCursor::setPos(const QPoint &pos)
QGuiApplicationPrivate::inputDeviceManager()->setCursorPos(pos);
const QRect oldCursorRect = cursorRect();
m_cursor.pos = pos;
- update(oldCursorRect | cursorRect());
- m_screen->handleCursorMove(m_cursor.pos);
+ update(oldCursorRect | cursorRect(), false);
+ for (QPlatformScreen *screen : m_screen->virtualSiblings())
+ static_cast<QEglFSScreen *>(screen)->handleCursorMove(m_cursor.pos);
}
void QEglFSCursor::pointerEvent(const QMouseEvent &event)
@@ -312,8 +331,9 @@ void QEglFSCursor::pointerEvent(const QMouseEvent &event)
return;
const QRect oldCursorRect = cursorRect();
m_cursor.pos = event.screenPos().toPoint();
- update(oldCursorRect | cursorRect());
- m_screen->handleCursorMove(m_cursor.pos);
+ update(oldCursorRect | cursorRect(), false);
+ for (QPlatformScreen *screen : m_screen->virtualSiblings())
+ static_cast<QEglFSScreen *>(screen)->handleCursorMove(m_cursor.pos);
}
void QEglFSCursor::paintOnScreen()
@@ -321,15 +341,37 @@ void QEglFSCursor::paintOnScreen()
if (!m_visible)
return;
- const QRectF cr = cursorRect();
- const QRect screenRect(m_screen->geometry());
- const GLfloat x1 = 2 * (cr.left() / screenRect.width()) - 1;
- const GLfloat x2 = 2 * (cr.right() / screenRect.width()) - 1;
- const GLfloat y1 = 1 - (cr.top() / screenRect.height()) * 2;
- const GLfloat y2 = 1 - (cr.bottom() / screenRect.height()) * 2;
- QRectF r(QPointF(x1, y1), QPointF(x2, y2));
+ // cr must be a QRectF, otherwise cr.right() and bottom() would be off by
+ // one in the calculations below.
+ QRectF cr = cursorRect(); // hotspot included
+
+ // Support virtual desktop too. Backends with multi-screen support (e.g. all
+ // variants of KMS/DRM) will enable this by default. In this case all
+ // screens are siblings of each other. When not enabled, the sibling list
+ // only contains m_screen itself.
+ for (QPlatformScreen *screen : m_screen->virtualSiblings()) {
+ if (screen->geometry().contains(cr.topLeft().toPoint() + m_cursor.hotSpot)
+ && QOpenGLContext::currentContext()->screen() == screen->screen())
+ {
+ cr.translate(-screen->geometry().topLeft());
+ const QSize screenSize = screen->geometry().size();
+ const GLfloat x1 = 2 * (cr.left() / GLfloat(screenSize.width())) - 1;
+ const GLfloat x2 = 2 * (cr.right() / GLfloat(screenSize.width())) - 1;
+ const GLfloat y1 = 1 - (cr.top() / GLfloat(screenSize.height())) * 2;
+ const GLfloat y2 = 1 - (cr.bottom() / GLfloat(screenSize.height())) * 2;
+ QRectF r(QPointF(x1, y1), QPointF(x2, y2));
+
+ draw(r);
+
+ if (screen != m_activeScreen) {
+ m_activeScreen = screen;
+ // Do not want a leftover cursor on the screen the cursor just left.
+ update(cursorRect(), true);
+ }
- draw(r);
+ break;
+ }
+ }
}
// In order to prevent breaking code doing custom OpenGL rendering while
@@ -431,30 +473,33 @@ void QEglFSCursor::draw(const QRectF &r)
{
StateSaver stateSaver;
- if (!m_program) {
+ GraphicsContextData &gfx(m_gfx[QOpenGLContext::currentContext()]);
+ if (!gfx.program) {
// one time initialization
initializeOpenGLFunctions();
createShaderPrograms();
- if (!m_cursorAtlas.texture) {
- createCursorTexture(&m_cursorAtlas.texture, m_cursorAtlas.image);
+ if (!gfx.atlasTexture) {
+ createCursorTexture(&gfx.atlasTexture, m_cursorAtlas.image);
if (m_cursor.shape != Qt::BitmapCursor)
- m_cursor.texture = m_cursorAtlas.texture;
+ m_cursor.useCustomCursor = false;
}
}
- if (m_cursor.shape == Qt::BitmapCursor && m_cursor.customCursorPending) {
+ if (m_cursor.shape == Qt::BitmapCursor && (m_cursor.customCursorPending || m_cursor.customCursorKey != gfx.customCursorKey)) {
// upload the custom cursor
- createCursorTexture(&m_cursor.customCursorTexture, m_cursor.customCursorImage);
- m_cursor.texture = m_cursor.customCursorTexture;
+ createCursorTexture(&gfx.customCursorTexture, m_cursor.customCursorImage);
+ m_cursor.useCustomCursor = true;
m_cursor.customCursorPending = false;
+ gfx.customCursorKey = m_cursor.customCursorKey;
}
- Q_ASSERT(m_cursor.texture);
+ GLuint cursorTexture = !m_cursor.useCustomCursor ? gfx.atlasTexture : gfx.customCursorTexture;
+ Q_ASSERT(cursorTexture);
- m_program->bind();
+ gfx.program->bind();
const GLfloat x1 = r.left();
const GLfloat x2 = r.right();
@@ -479,19 +524,20 @@ void QEglFSCursor::draw(const QRectF &r)
};
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, m_cursor.texture);
+ glBindTexture(GL_TEXTURE_2D, cursorTexture);
if (stateSaver.vaoHelper->isValid())
stateSaver.vaoHelper->glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
- m_program->enableAttributeArray(0);
- m_program->enableAttributeArray(1);
- m_program->setAttributeArray(0, cursorCoordinates, 2);
- m_program->setAttributeArray(1, textureCoordinates, 2);
+ gfx.program->enableAttributeArray(0);
+ gfx.program->enableAttributeArray(1);
+ gfx.program->setAttributeArray(0, cursorCoordinates, 2);
+ gfx.program->setAttributeArray(1, textureCoordinates, 2);
- m_program->setUniformValue(m_textureEntry, 0);
+ gfx.program->setUniformValue(gfx.textureEntry, 0);
+ gfx.program->setUniformValue(gfx.matEntry, m_rotationMatrix);
glDisable(GL_CULL_FACE);
glFrontFace(GL_CCW);
@@ -501,9 +547,9 @@ void QEglFSCursor::draw(const QRectF &r)
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
- m_program->disableAttributeArray(0);
- m_program->disableAttributeArray(1);
- m_program->release();
+ gfx.program->disableAttributeArray(0);
+ gfx.program->disableAttributeArray(1);
+ gfx.program->release();
}
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfscursor.h b/src/plugins/platforms/eglfs/api/qeglfscursor_p.h
index bb30d53d6c..bf6dbc8a21 100644
--- a/src/plugins/platforms/eglfs/qeglfscursor.h
+++ b/src/plugins/platforms/eglfs/api/qeglfscursor_p.h
@@ -51,9 +51,10 @@
// We mean it.
//
-#include "qeglfsglobal.h"
+#include "qeglfsglobal_p.h"
#include <qpa/qplatformcursor.h>
#include <qpa/qplatformscreen.h>
+#include <QtGui/QMatrix4x4>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/private/qinputdevicemanager_p.h>
@@ -104,30 +105,29 @@ private:
bool setCurrentCursor(QCursor *cursor);
#endif
void draw(const QRectF &rect);
- void update(const QRegion &region);
+ void update(const QRect &rect, bool allScreens);
void createShaderPrograms();
void createCursorTexture(uint *texture, const QImage &image);
void initCursorAtlas();
// current cursor information
struct Cursor {
- Cursor() : texture(0), shape(Qt::BlankCursor), customCursorTexture(0), customCursorPending(false) { }
- uint texture; // a texture from 'image' or the atlas
+ Cursor() : shape(Qt::BlankCursor), customCursorPending(false), customCursorKey(0), useCustomCursor(false) { }
Qt::CursorShape shape;
QRectF textureRect; // normalized rect inside texture
QSize size; // size of the cursor
QPoint hotSpot;
QImage customCursorImage;
QPoint pos; // current cursor position
- uint customCursorTexture;
bool customCursorPending;
+ qint64 customCursorKey;
+ bool useCustomCursor;
} m_cursor;
// cursor atlas information
struct CursorAtlas {
- CursorAtlas() : cursorsPerRow(0), texture(0), cursorWidth(0), cursorHeight(0) { }
+ CursorAtlas() : cursorsPerRow(0), cursorWidth(0), cursorHeight(0) { }
int cursorsPerRow;
- uint texture;
int width, height; // width and height of the atlas
int cursorWidth, cursorHeight; // width and height of cursors inside the atlas
QList<QPoint> hotSpots;
@@ -136,10 +136,22 @@ private:
bool m_visible;
QEglFSScreen *m_screen;
- QOpenGLShaderProgram *m_program;
- int m_textureEntry;
+ QPlatformScreen *m_activeScreen;
QEglFSCursorDeviceListener *m_deviceListener;
bool m_updateRequested;
+ QMatrix4x4 m_rotationMatrix;
+
+ struct GraphicsContextData {
+ GraphicsContextData() : program(nullptr), textureEntry(0), matEntry(0),
+ customCursorTexture(0), atlasTexture(0), customCursorKey(0) { }
+ QOpenGLShaderProgram *program;
+ int textureEntry;
+ int matEntry;
+ uint customCursorTexture;
+ uint atlasTexture;
+ qint64 customCursorKey;
+ };
+ QHash<QOpenGLContext *, GraphicsContextData> m_gfx;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp b/src/plugins/platforms/eglfs/api/qeglfsdeviceintegration.cpp
index fc41dc5643..3e1e93f1e4 100644
--- a/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp
+++ b/src/plugins/platforms/eglfs/api/qeglfsdeviceintegration.cpp
@@ -37,11 +37,14 @@
**
****************************************************************************/
-#include "qeglfsdeviceintegration.h"
-#include "qeglfsintegration.h"
-#include "qeglfscursor.h"
-#include "qeglfswindow.h"
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
+#include "qeglfsdeviceintegration_p.h"
+#include "qeglfsintegration_p.h"
+#include "qeglfscursor_p.h"
+#include "qeglfswindow_p.h"
+#include "qeglfsscreen_p.h"
+#include "qeglfshooks_p.h"
+
+#include <QtEglSupport/private/qeglconvenience_p.h>
#include <QGuiApplication>
#include <private/qguiapplication_p.h>
#include <QScreen>
@@ -64,14 +67,15 @@ QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(qLcEglDevDebug, "qt.qpa.egldeviceintegration")
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
- (QEGLDeviceIntegrationFactoryInterface_iid, QLatin1String("/egldeviceintegrations"), Qt::CaseInsensitive))
+ (QEglFSDeviceIntegrationFactoryInterface_iid, QLatin1String("/egldeviceintegrations"), Qt::CaseInsensitive))
#ifndef QT_NO_LIBRARY
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, directLoader,
- (QEGLDeviceIntegrationFactoryInterface_iid, QLatin1String(""), Qt::CaseInsensitive))
+ (QEglFSDeviceIntegrationFactoryInterface_iid, QLatin1String(""), Qt::CaseInsensitive))
+
#endif // QT_NO_LIBRARY
-QStringList QEGLDeviceIntegrationFactory::keys(const QString &pluginPath)
+QStringList QEglFSDeviceIntegrationFactory::keys(const QString &pluginPath)
{
QStringList list;
#ifndef QT_NO_LIBRARY
@@ -95,19 +99,19 @@ QStringList QEGLDeviceIntegrationFactory::keys(const QString &pluginPath)
return list;
}
-QEGLDeviceIntegration *QEGLDeviceIntegrationFactory::create(const QString &key, const QString &pluginPath)
+QEglFSDeviceIntegration *QEglFSDeviceIntegrationFactory::create(const QString &key, const QString &pluginPath)
{
- QEGLDeviceIntegration *integration = Q_NULLPTR;
+ QEglFSDeviceIntegration *integration = Q_NULLPTR;
#ifndef QT_NO_LIBRARY
if (!pluginPath.isEmpty()) {
QCoreApplication::addLibraryPath(pluginPath);
- integration = qLoadPlugin<QEGLDeviceIntegration, QEGLDeviceIntegrationPlugin>(directLoader(), key);
+ integration = qLoadPlugin<QEglFSDeviceIntegration, QEglFSDeviceIntegrationPlugin>(directLoader(), key);
}
#else
Q_UNUSED(pluginPath);
#endif
if (!integration)
- integration = qLoadPlugin<QEGLDeviceIntegration, QEGLDeviceIntegrationPlugin>(loader(), key);
+ integration = qLoadPlugin<QEglFSDeviceIntegration, QEglFSDeviceIntegrationPlugin>(loader(), key);
if (integration)
qCDebug(qLcEglDevDebug) << "Using EGL device integration" << key;
else
@@ -118,7 +122,7 @@ QEGLDeviceIntegration *QEGLDeviceIntegrationFactory::create(const QString &key,
static int framebuffer = -1;
-QByteArray QEGLDeviceIntegration::fbDeviceName() const
+QByteArray QEglFSDeviceIntegration::fbDeviceName() const
{
#ifdef Q_OS_LINUX
QByteArray fbDev = qgetenv("QT_QPA_EGLFS_FB");
@@ -131,7 +135,7 @@ QByteArray QEGLDeviceIntegration::fbDeviceName() const
#endif
}
-int QEGLDeviceIntegration::framebufferIndex() const
+int QEglFSDeviceIntegration::framebufferIndex() const
{
int fbIndex = 0;
#ifndef QT_NO_REGULAREXPRESSION
@@ -143,7 +147,7 @@ int QEGLDeviceIntegration::framebufferIndex() const
return fbIndex;
}
-void QEGLDeviceIntegration::platformInit()
+void QEglFSDeviceIntegration::platformInit()
{
#ifdef Q_OS_LINUX
QByteArray fbDev = fbDeviceName();
@@ -161,7 +165,7 @@ void QEGLDeviceIntegration::platformInit()
#endif
}
-void QEGLDeviceIntegration::platformDestroy()
+void QEglFSDeviceIntegration::platformDestroy()
{
#ifdef Q_OS_LINUX
if (framebuffer != -1)
@@ -169,46 +173,46 @@ void QEGLDeviceIntegration::platformDestroy()
#endif
}
-EGLNativeDisplayType QEGLDeviceIntegration::platformDisplay() const
+EGLNativeDisplayType QEglFSDeviceIntegration::platformDisplay() const
{
return EGL_DEFAULT_DISPLAY;
}
-EGLDisplay QEGLDeviceIntegration::createDisplay(EGLNativeDisplayType nativeDisplay)
+EGLDisplay QEglFSDeviceIntegration::createDisplay(EGLNativeDisplayType nativeDisplay)
{
return eglGetDisplay(nativeDisplay);
}
-bool QEGLDeviceIntegration::usesDefaultScreen()
+bool QEglFSDeviceIntegration::usesDefaultScreen()
{
return true;
}
-void QEGLDeviceIntegration::screenInit()
+void QEglFSDeviceIntegration::screenInit()
{
// Nothing to do here. Called only when usesDefaultScreen is false.
}
-void QEGLDeviceIntegration::screenDestroy()
+void QEglFSDeviceIntegration::screenDestroy()
{
QGuiApplication *app = qGuiApp;
QEglFSIntegration *platformIntegration = static_cast<QEglFSIntegration *>(
QGuiApplicationPrivate::platformIntegration());
while (!app->screens().isEmpty())
- platformIntegration->removeScreen(app->screens().last()->handle());
+ platformIntegration->removeScreen(app->screens().constLast()->handle());
}
-QSizeF QEGLDeviceIntegration::physicalScreenSize() const
+QSizeF QEglFSDeviceIntegration::physicalScreenSize() const
{
return q_physicalScreenSizeFromFb(framebuffer, screenSize());
}
-QSize QEGLDeviceIntegration::screenSize() const
+QSize QEglFSDeviceIntegration::screenSize() const
{
return q_screenSizeFromFb(framebuffer);
}
-QDpi QEGLDeviceIntegration::logicalDpi() const
+QDpi QEglFSDeviceIntegration::logicalDpi() const
{
const QSizeF ps = physicalScreenSize();
const QSize s = screenSize();
@@ -220,42 +224,42 @@ QDpi QEGLDeviceIntegration::logicalDpi() const
return QDpi(100, 100);
}
-qreal QEGLDeviceIntegration::pixelDensity() const
+qreal QEglFSDeviceIntegration::pixelDensity() const
{
return qRound(logicalDpi().first / qreal(100));
}
-Qt::ScreenOrientation QEGLDeviceIntegration::nativeOrientation() const
+Qt::ScreenOrientation QEglFSDeviceIntegration::nativeOrientation() const
{
return Qt::PrimaryOrientation;
}
-Qt::ScreenOrientation QEGLDeviceIntegration::orientation() const
+Qt::ScreenOrientation QEglFSDeviceIntegration::orientation() const
{
return Qt::PrimaryOrientation;
}
-int QEGLDeviceIntegration::screenDepth() const
+int QEglFSDeviceIntegration::screenDepth() const
{
return q_screenDepthFromFb(framebuffer);
}
-QImage::Format QEGLDeviceIntegration::screenFormat() const
+QImage::Format QEglFSDeviceIntegration::screenFormat() const
{
return screenDepth() == 16 ? QImage::Format_RGB16 : QImage::Format_RGB32;
}
-qreal QEGLDeviceIntegration::refreshRate() const
+qreal QEglFSDeviceIntegration::refreshRate() const
{
return q_refreshRateFromFb(framebuffer);
}
-EGLint QEGLDeviceIntegration::surfaceType() const
+EGLint QEglFSDeviceIntegration::surfaceType() const
{
return EGL_WINDOW_BIT;
}
-QSurfaceFormat QEGLDeviceIntegration::surfaceFormatFor(const QSurfaceFormat &inputFormat) const
+QSurfaceFormat QEglFSDeviceIntegration::surfaceFormatFor(const QSurfaceFormat &inputFormat) const
{
QSurfaceFormat format = inputFormat;
@@ -269,17 +273,17 @@ QSurfaceFormat QEGLDeviceIntegration::surfaceFormatFor(const QSurfaceFormat &inp
return format;
}
-bool QEGLDeviceIntegration::filterConfig(EGLDisplay, EGLConfig) const
+bool QEglFSDeviceIntegration::filterConfig(EGLDisplay, EGLConfig) const
{
return true;
}
-QEglFSWindow *QEGLDeviceIntegration::createWindow(QWindow *window) const
+QEglFSWindow *QEglFSDeviceIntegration::createWindow(QWindow *window) const
{
return new QEglFSWindow(window);
}
-EGLNativeWindowType QEGLDeviceIntegration::createNativeWindow(QPlatformWindow *platformWindow,
+EGLNativeWindowType QEglFSDeviceIntegration::createNativeWindow(QPlatformWindow *platformWindow,
const QSize &size,
const QSurfaceFormat &format)
{
@@ -289,29 +293,29 @@ EGLNativeWindowType QEGLDeviceIntegration::createNativeWindow(QPlatformWindow *p
return 0;
}
-EGLNativeWindowType QEGLDeviceIntegration::createNativeOffscreenWindow(const QSurfaceFormat &format)
+EGLNativeWindowType QEglFSDeviceIntegration::createNativeOffscreenWindow(const QSurfaceFormat &format)
{
Q_UNUSED(format);
return 0;
}
-void QEGLDeviceIntegration::destroyNativeWindow(EGLNativeWindowType window)
+void QEglFSDeviceIntegration::destroyNativeWindow(EGLNativeWindowType window)
{
Q_UNUSED(window);
}
-bool QEGLDeviceIntegration::hasCapability(QPlatformIntegration::Capability cap) const
+bool QEglFSDeviceIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
Q_UNUSED(cap);
return false;
}
-QPlatformCursor *QEGLDeviceIntegration::createCursor(QPlatformScreen *screen) const
+QPlatformCursor *QEglFSDeviceIntegration::createCursor(QPlatformScreen *screen) const
{
- return new QEglFSCursor(screen);
+ return new QEglFSCursor(static_cast<QEglFSScreen *>(screen));
}
-void QEGLDeviceIntegration::waitForVSync(QPlatformSurface *surface) const
+void QEglFSDeviceIntegration::waitForVSync(QPlatformSurface *surface) const
{
Q_UNUSED(surface);
@@ -325,24 +329,42 @@ void QEGLDeviceIntegration::waitForVSync(QPlatformSurface *surface) const
#endif
}
-void QEGLDeviceIntegration::presentBuffer(QPlatformSurface *surface)
+void QEglFSDeviceIntegration::presentBuffer(QPlatformSurface *surface)
{
Q_UNUSED(surface);
}
-bool QEGLDeviceIntegration::supportsPBuffers() const
+bool QEglFSDeviceIntegration::supportsPBuffers() const
{
return true;
}
-bool QEGLDeviceIntegration::supportsSurfacelessContexts() const
+bool QEglFSDeviceIntegration::supportsSurfacelessContexts() const
{
return true;
}
-void *QEGLDeviceIntegration::wlDisplay() const
+void *QEglFSDeviceIntegration::wlDisplay() const
{
return Q_NULLPTR;
}
+EGLConfig QEglFSDeviceIntegration::chooseConfig(EGLDisplay display, const QSurfaceFormat &format)
+{
+ class Chooser : public QEglConfigChooser {
+ public:
+ Chooser(EGLDisplay display)
+ : QEglConfigChooser(display) { }
+ bool filterConfig(EGLConfig config) const Q_DECL_OVERRIDE {
+ return qt_egl_device_integration()->filterConfig(display(), config)
+ && QEglConfigChooser::filterConfig(config);
+ }
+ };
+
+ Chooser chooser(display);
+ chooser.setSurfaceType(qt_egl_device_integration()->surfaceType());
+ chooser.setSurfaceFormat(format);
+ return chooser.chooseConfig();
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfsdeviceintegration.h b/src/plugins/platforms/eglfs/api/qeglfsdeviceintegration_p.h
index f1a5bde331..4335554912 100644
--- a/src/plugins/platforms/eglfs/qeglfsdeviceintegration.h
+++ b/src/plugins/platforms/eglfs/api/qeglfsdeviceintegration_p.h
@@ -51,7 +51,7 @@
// We mean it.
//
-#include "qeglfsglobal.h"
+#include "qeglfsglobal_p.h"
#include <qpa/qplatformintegration.h>
#include <qpa/qplatformscreen.h>
#include <QtCore/QString>
@@ -63,12 +63,12 @@ QT_BEGIN_NAMESPACE
class QPlatformSurface;
class QEglFSWindow;
-#define QEGLDeviceIntegrationFactoryInterface_iid "org.qt-project.qt.qpa.egl.QEGLDeviceIntegrationFactoryInterface.5.5"
+#define QEglFSDeviceIntegrationFactoryInterface_iid "org.qt-project.qt.qpa.egl.QEglFSDeviceIntegrationFactoryInterface.5.5"
-class Q_EGLFS_EXPORT QEGLDeviceIntegration
+class Q_EGLFS_EXPORT QEglFSDeviceIntegration
{
public:
- virtual ~QEGLDeviceIntegration() { }
+ virtual ~QEglFSDeviceIntegration() { }
virtual void platformInit();
virtual void platformDestroy();
@@ -105,25 +105,27 @@ public:
virtual bool supportsSurfacelessContexts() const;
virtual void *wlDisplay() const;
+
+ static EGLConfig chooseConfig(EGLDisplay display, const QSurfaceFormat &format);
};
-class Q_EGLFS_EXPORT QEGLDeviceIntegrationPlugin : public QObject
+class Q_EGLFS_EXPORT QEglFSDeviceIntegrationPlugin : public QObject
{
Q_OBJECT
public:
- virtual QEGLDeviceIntegration *create() = 0;
+ virtual QEglFSDeviceIntegration *create() = 0;
// the pattern expected by qLoadPlugin calls for a QString argument.
// we don't need it, so don't bother subclasses with it:
- QEGLDeviceIntegration *create(const QString &) { return create(); }
+ QEglFSDeviceIntegration *create(const QString &) { return create(); }
};
-class Q_EGLFS_EXPORT QEGLDeviceIntegrationFactory
+class Q_EGLFS_EXPORT QEglFSDeviceIntegrationFactory
{
public:
static QStringList keys(const QString &pluginPath = QString());
- static QEGLDeviceIntegration *create(const QString &name, const QString &platformPluginPath = QString());
+ static QEglFSDeviceIntegration *create(const QString &name, const QString &platformPluginPath = QString());
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfsglobal.h b/src/plugins/platforms/eglfs/api/qeglfsglobal_p.h
index 309655e86c..8d76ff5ee0 100644
--- a/src/plugins/platforms/eglfs/qeglfsglobal.h
+++ b/src/plugins/platforms/eglfs/api/qeglfsglobal_p.h
@@ -40,7 +40,22 @@
#ifndef QEGLFSGLOBAL_H
#define QEGLFSGLOBAL_H
-#include <qglobal.h>
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtCore/qglobal.h>
+
+#include <QtEglSupport/private/qt_egl_p.h>
+
+QT_BEGIN_NAMESPACE
#ifdef QT_BUILD_EGL_DEVICE_LIB
#define Q_EGLFS_EXPORT Q_DECL_EXPORT
@@ -48,7 +63,6 @@
#define Q_EGLFS_EXPORT Q_DECL_IMPORT
#endif
-#include <QtPlatformSupport/private/qt_egl_p.h>
#undef Status
#undef None
#undef Bool
@@ -61,4 +75,6 @@
#undef Expose
#undef Unsorted
+QT_END_NAMESPACE
+
#endif
diff --git a/src/plugins/platforms/eglfs/qeglfshooks.cpp b/src/plugins/platforms/eglfs/api/qeglfshooks.cpp
index 7345cfd1f1..d8332a94cb 100644
--- a/src/plugins/platforms/eglfs/qeglfshooks.cpp
+++ b/src/plugins/platforms/eglfs/api/qeglfshooks.cpp
@@ -37,7 +37,7 @@
**
****************************************************************************/
-#include "qeglfshooks.h"
+#include "qeglfshooks_p.h"
#include <QLoggingCategory>
QT_BEGIN_NAMESPACE
@@ -46,7 +46,7 @@ Q_DECLARE_LOGGING_CATEGORY(qLcEglDevDebug)
#ifdef EGLFS_PLATFORM_HOOKS
-QEGLDeviceIntegration *qt_egl_device_integration()
+QEglFSDeviceIntegration *qt_egl_device_integration()
{
extern QEglFSHooks *platformHooks;
return platformHooks;
@@ -59,9 +59,9 @@ class DeviceIntegration
public:
DeviceIntegration();
~DeviceIntegration() { delete m_integration; }
- QEGLDeviceIntegration *integration() { return m_integration; }
+ QEglFSDeviceIntegration *integration() { return m_integration; }
private:
- QEGLDeviceIntegration *m_integration;
+ QEglFSDeviceIntegration *m_integration;
};
Q_GLOBAL_STATIC(DeviceIntegration, deviceIntegration)
@@ -69,7 +69,7 @@ Q_GLOBAL_STATIC(DeviceIntegration, deviceIntegration)
DeviceIntegration::DeviceIntegration()
: m_integration(nullptr)
{
- QStringList pluginKeys = QEGLDeviceIntegrationFactory::keys();
+ QStringList pluginKeys = QEglFSDeviceIntegrationFactory::keys();
if (!pluginKeys.isEmpty()) {
// Some built-in logic: Prioritize either X11 or KMS/DRM.
if (qEnvironmentVariableIsSet("DISPLAY")) {
@@ -114,7 +114,7 @@ DeviceIntegration::DeviceIntegration()
while (!m_integration && !pluginKeys.isEmpty()) {
QString key = pluginKeys.takeFirst();
qCDebug(qLcEglDevDebug) << "Trying to load device EGL integration" << key;
- m_integration = QEGLDeviceIntegrationFactory::create(key);
+ m_integration = QEglFSDeviceIntegrationFactory::create(key);
}
}
}
@@ -123,11 +123,11 @@ DeviceIntegration::DeviceIntegration()
// Use a default, non-specialized device integration when no plugin is available.
// For some systems this is sufficient.
qCDebug(qLcEglDevDebug) << "Using base device integration";
- m_integration = new QEGLDeviceIntegration;
+ m_integration = new QEglFSDeviceIntegration;
}
}
-QEGLDeviceIntegration *qt_egl_device_integration()
+QEglFSDeviceIntegration *qt_egl_device_integration()
{
return deviceIntegration()->integration();
}
diff --git a/src/plugins/platforms/eglfs/qeglfshooks.h b/src/plugins/platforms/eglfs/api/qeglfshooks_p.h
index cc6c325b58..4c3149c7c9 100644
--- a/src/plugins/platforms/eglfs/qeglfshooks.h
+++ b/src/plugins/platforms/eglfs/api/qeglfshooks_p.h
@@ -40,16 +40,27 @@
#ifndef QEGLFSHOOKS_H
#define QEGLFSHOOKS_H
-#include "qeglfsglobal.h"
-#include "qeglfsdeviceintegration.h"
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qeglfsglobal_p.h"
+#include "qeglfsdeviceintegration_p.h"
QT_BEGIN_NAMESPACE
-class QEglFSHooks : public QEGLDeviceIntegration
+class QEglFSHooks : public QEglFSDeviceIntegration
{
};
-Q_EGLFS_EXPORT QEGLDeviceIntegration *qt_egl_device_integration();
+Q_EGLFS_EXPORT QEglFSDeviceIntegration *qt_egl_device_integration();
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfsintegration.cpp b/src/plugins/platforms/eglfs/api/qeglfsintegration.cpp
index a4263c490e..7c88c73cc2 100644
--- a/src/plugins/platforms/eglfs/qeglfsintegration.cpp
+++ b/src/plugins/platforms/eglfs/api/qeglfsintegration.cpp
@@ -49,39 +49,39 @@
#include <QtCore/QLoggingCategory>
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qplatforminputcontextfactory_p.h>
-#include <private/qgenericunixthemes_p.h>
-#include "qeglfsintegration.h"
-#include "qeglfswindow.h"
-#include "qeglfshooks.h"
-#include "qeglfscontext.h"
-#include "qeglfsoffscreenwindow.h"
-#include "qeglfscursor.h"
+#include "qeglfsintegration_p.h"
+#include "qeglfswindow_p.h"
+#include "qeglfshooks_p.h"
+#include "qeglfscontext_p.h"
+#include "qeglfsoffscreenwindow_p.h"
+#include "qeglfscursor_p.h"
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-#include <QtPlatformSupport/private/qeglplatformcontext_p.h>
-#include <QtPlatformSupport/private/qeglpbuffer_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglplatformcontext_p.h>
+#include <QtEglSupport/private/qeglpbuffer_p.h>
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qgenericunixservices_p.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
-#include <QtPlatformSupport/private/qfbvthandler_p.h>
-#include <QtPlatformSupport/private/qopenglcompositorbackingstore_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtServiceSupport/private/qgenericunixservices_p.h>
+#include <QtThemeSupport/private/qgenericunixthemes_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtFbSupport/private/qfbvthandler_p.h>
+#include <QtPlatformCompositorSupport/private/qopenglcompositorbackingstore_p.h>
#include <QtPlatformHeaders/QEGLNativeContext>
-#ifndef QT_NO_LIBINPUT
-#include <QtPlatformSupport/private/qlibinputhandler_p.h>
+#if QT_CONFIG(libinput)
+#include <QtInputSupport/private/qlibinputhandler_p.h>
#endif
-#if !defined(QT_NO_EVDEV) && !defined(Q_OS_ANDROID)
-#include <QtPlatformSupport/private/qevdevmousemanager_p.h>
-#include <QtPlatformSupport/private/qevdevkeyboardmanager_p.h>
-#include <QtPlatformSupport/private/qevdevtouchmanager_p.h>
+#if QT_CONFIG(evdev)
+#include <QtInputSupport/private/qevdevmousemanager_p.h>
+#include <QtInputSupport/private/qevdevkeyboardmanager_p.h>
+#include <QtInputSupport/private/qevdevtouchmanager_p.h>
#endif
-#if !defined(QT_NO_TSLIB) && !defined(Q_OS_ANDROID)
-#include <QtPlatformSupport/private/qtslib_p.h>
+#if QT_CONFIG(tslib)
+#include <QtInputSupport/private/qtslib_p.h>
#endif
#include <QtPlatformHeaders/qeglfsfunctions.h>
@@ -205,7 +205,7 @@ QPlatformOpenGLContext *QEglFSIntegration::createPlatformOpenGLContext(QOpenGLCo
QEglFSContext *ctx;
QSurfaceFormat adjustedFormat = qt_egl_device_integration()->surfaceFormatFor(context->format());
if (nativeHandle.isNull()) {
- EGLConfig config = QEglFSIntegration::chooseConfig(dpy, adjustedFormat);
+ EGLConfig config = QEglFSDeviceIntegration::chooseConfig(dpy, adjustedFormat);
ctx = new QEglFSContext(adjustedFormat, share, dpy, &config, QVariant());
} else {
ctx = new QEglFSContext(adjustedFormat, share, dpy, 0, nativeHandle);
@@ -386,7 +386,7 @@ QPlatformNativeInterface::NativeResourceForContextFunction QEglFSIntegration::na
QFunctionPointer QEglFSIntegration::platformFunction(const QByteArray &function) const
{
-#if !defined(QT_NO_EVDEV) && !defined(Q_OS_ANDROID)
+#if QT_CONFIG(evdev)
if (function == QEglFSFunctions::loadKeymapTypeIdentifier())
return QFunctionPointer(loadKeymapStatic);
#else
@@ -398,7 +398,7 @@ QFunctionPointer QEglFSIntegration::platformFunction(const QByteArray &function)
void QEglFSIntegration::loadKeymapStatic(const QString &filename)
{
-#if !defined(QT_NO_EVDEV) && !defined(Q_OS_ANDROID)
+#if QT_CONFIG(evdev)
QEglFSIntegration *self = static_cast<QEglFSIntegration *>(QGuiApplicationPrivate::platformIntegration());
if (self->m_kbdMgr)
self->m_kbdMgr->loadKeymap(filename);
@@ -411,7 +411,7 @@ void QEglFSIntegration::loadKeymapStatic(const QString &filename)
void QEglFSIntegration::createInputHandlers()
{
-#ifndef QT_NO_LIBINPUT
+#if QT_CONFIG(libinput)
if (!qEnvironmentVariableIntValue("QT_QPA_EGLFS_NO_LIBINPUT")) {
new QLibInputHandler(QLatin1String("libinput"), QString());
return;
@@ -419,13 +419,13 @@ void QEglFSIntegration::createInputHandlers()
#endif
bool useTslib = false;
-#ifndef QT_NO_TSLIB
+#if QT_CONFIG(tslib)
useTslib = qEnvironmentVariableIntValue("QT_QPA_EGLFS_TSLIB");
if (useTslib)
new QTsLibMouseHandler(QLatin1String("TsLib"), QString() /* spec */);
#endif
-#if !defined(QT_NO_EVDEV) && !defined(Q_OS_ANDROID)
+#if QT_CONFIG(evdev)
m_kbdMgr = new QEvdevKeyboardManager(QLatin1String("EvdevKeyboard"), QString() /* spec */, this);
new QEvdevMouseManager(QLatin1String("EvdevMouse"), QString() /* spec */, this);
if (!useTslib)
@@ -438,22 +438,4 @@ EGLNativeDisplayType QEglFSIntegration::nativeDisplay() const
return qt_egl_device_integration()->platformDisplay();
}
-EGLConfig QEglFSIntegration::chooseConfig(EGLDisplay display, const QSurfaceFormat &format)
-{
- class Chooser : public QEglConfigChooser {
- public:
- Chooser(EGLDisplay display)
- : QEglConfigChooser(display) { }
- bool filterConfig(EGLConfig config) const Q_DECL_OVERRIDE {
- return qt_egl_device_integration()->filterConfig(display(), config)
- && QEglConfigChooser::filterConfig(config);
- }
- };
-
- Chooser chooser(display);
- chooser.setSurfaceType(qt_egl_device_integration()->surfaceType());
- chooser.setSurfaceFormat(format);
- return chooser.chooseConfig();
-}
-
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfsintegration.h b/src/plugins/platforms/eglfs/api/qeglfsintegration_p.h
index 678452a8db..1a3a44d441 100644
--- a/src/plugins/platforms/eglfs/qeglfsintegration.h
+++ b/src/plugins/platforms/eglfs/api/qeglfsintegration_p.h
@@ -40,7 +40,18 @@
#ifndef QEGLFSINTEGRATION_H
#define QEGLFSINTEGRATION_H
-#include "qeglfsglobal.h"
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qeglfsglobal_p.h"
#include <QtCore/QVariant>
#include <qpa/qplatformintegration.h>
#include <qpa/qplatformnativeinterface.h>
@@ -92,8 +103,6 @@ public:
void addScreen(QPlatformScreen *screen);
void removeScreen(QPlatformScreen *screen);
- static EGLConfig chooseConfig(EGLDisplay display, const QSurfaceFormat &format);
-
private:
EGLNativeDisplayType nativeDisplay() const;
void createInputHandlers();
diff --git a/src/plugins/platforms/eglfs/qeglfsoffscreenwindow.cpp b/src/plugins/platforms/eglfs/api/qeglfsoffscreenwindow.cpp
index 11b101970b..864271cd3a 100644
--- a/src/plugins/platforms/eglfs/qeglfsoffscreenwindow.cpp
+++ b/src/plugins/platforms/eglfs/api/qeglfsoffscreenwindow.cpp
@@ -37,10 +37,10 @@
**
****************************************************************************/
-#include "qeglfsoffscreenwindow.h"
-#include "qeglfshooks.h"
+#include "qeglfsoffscreenwindow_p.h"
+#include "qeglfshooks_p.h"
#include <QtGui/QOffscreenSurface>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfsoffscreenwindow.h b/src/plugins/platforms/eglfs/api/qeglfsoffscreenwindow_p.h
index 673fa0d729..ec483c64e2 100644
--- a/src/plugins/platforms/eglfs/qeglfsoffscreenwindow.h
+++ b/src/plugins/platforms/eglfs/api/qeglfsoffscreenwindow_p.h
@@ -40,7 +40,18 @@
#ifndef QEGLFSOFFSCREENWINDOW_H
#define QEGLFSOFFSCREENWINDOW_H
-#include "qeglfsglobal.h"
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qeglfsglobal_p.h"
#include <qpa/qplatformoffscreensurface.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/qeglfsscreen.cpp b/src/plugins/platforms/eglfs/api/qeglfsscreen.cpp
index a1ab854db1..5613179041 100644
--- a/src/plugins/platforms/eglfs/qeglfsscreen.cpp
+++ b/src/plugins/platforms/eglfs/api/qeglfsscreen.cpp
@@ -41,11 +41,11 @@
#include <QtGui/qwindow.h>
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qplatformcursor.h>
-#include <QtPlatformSupport/private/qopenglcompositor_p.h>
+#include <QtPlatformCompositorSupport/private/qopenglcompositor_p.h>
-#include "qeglfsscreen.h"
-#include "qeglfswindow.h"
-#include "qeglfshooks.h"
+#include "qeglfsscreen_p.h"
+#include "qeglfswindow_p.h"
+#include "qeglfshooks_p.h"
QT_BEGIN_NAMESPACE
@@ -65,6 +65,31 @@ QEglFSScreen::~QEglFSScreen()
QRect QEglFSScreen::geometry() const
{
+ QRect r = rawGeometry();
+
+ static int rotation = qEnvironmentVariableIntValue("QT_QPA_EGLFS_ROTATION");
+ switch (rotation) {
+ case 0:
+ case 180:
+ case -180:
+ break;
+ case 90:
+ case -90: {
+ int h = r.height();
+ r.setHeight(r.width());
+ r.setWidth(h);
+ break;
+ }
+ default:
+ qWarning("Invalid rotation %d specified in QT_QPA_EGLFS_ROTATION", rotation);
+ break;
+ }
+
+ return r;
+}
+
+QRect QEglFSScreen::rawGeometry() const
+{
return QRect(QPoint(0, 0), qt_egl_device_integration()->screenSize());
}
diff --git a/src/plugins/platforms/eglfs/qeglfsscreen.h b/src/plugins/platforms/eglfs/api/qeglfsscreen_p.h
index 57d68ca572..131e619e06 100644
--- a/src/plugins/platforms/eglfs/qeglfsscreen.h
+++ b/src/plugins/platforms/eglfs/api/qeglfsscreen_p.h
@@ -40,9 +40,22 @@
#ifndef QEGLFSSCREEN_H
#define QEGLFSSCREEN_H
-#include "qeglfsglobal.h"
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qeglfsglobal_p.h"
#include <QtCore/QPointer>
+#include <qpa/qplatformscreen.h>
+
QT_BEGIN_NAMESPACE
class QEglFSWindow;
@@ -55,6 +68,7 @@ public:
~QEglFSScreen();
QRect geometry() const Q_DECL_OVERRIDE;
+ virtual QRect rawGeometry() const;
int depth() const Q_DECL_OVERRIDE;
QImage::Format format() const Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/eglfs/qeglfswindow.cpp b/src/plugins/platforms/eglfs/api/qeglfswindow.cpp
index 556d3942cd..e79b377d40 100644
--- a/src/plugins/platforms/eglfs/qeglfswindow.cpp
+++ b/src/plugins/platforms/eglfs/api/qeglfswindow.cpp
@@ -43,12 +43,13 @@
#include <private/qguiapplication_p.h>
#include <QtGui/private/qopenglcontext_p.h>
#include <QtGui/QOpenGLContext>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-#include <QtPlatformSupport/private/qopenglcompositorbackingstore_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
+#include <QtPlatformCompositorSupport/private/qopenglcompositorbackingstore_p.h>
-#include "qeglfswindow.h"
-#include "qeglfscursor.h"
-#include "qeglfshooks.h"
+#include "qeglfswindow_p.h"
+#include "qeglfscursor_p.h"
+#include "qeglfshooks_p.h"
+#include "qeglfsdeviceintegration_p.h"
QT_BEGIN_NAMESPACE
@@ -141,7 +142,8 @@ void QEglFSWindow::create()
context->setScreen(window()->screen());
if (Q_UNLIKELY(!context->create()))
qFatal("EGLFS: Failed to create compositing context");
- compositor->setTarget(context, window());
+ compositor->setTarget(context, window(), screen->rawGeometry());
+ compositor->setRotation(qEnvironmentVariableIntValue("QT_QPA_EGLFS_ROTATION"));
// If there is a "root" window into which raster and QOpenGLWidget content is
// composited, all other contexts must share with its context.
if (!qt_gl_global_share_context()) {
@@ -186,9 +188,10 @@ void QEglFSWindow::resetSurface()
EGLDisplay display = screen()->display();
QSurfaceFormat platformFormat = qt_egl_device_integration()->surfaceFormatFor(window()->requestedFormat());
- m_config = QEglFSIntegration::chooseConfig(display, platformFormat);
+ m_config = QEglFSDeviceIntegration::chooseConfig(display, platformFormat);
m_format = q_glFormatFromConfig(display, m_config, platformFormat);
- m_window = qt_egl_device_integration()->createNativeWindow(this, screen()->geometry().size(), m_format);
+ const QSize surfaceSize = screen()->rawGeometry().size();
+ m_window = qt_egl_device_integration()->createNativeWindow(this, surfaceSize, m_format);
m_surface = eglCreateWindowSurface(display, m_config, m_window, NULL);
}
diff --git a/src/plugins/platforms/eglfs/qeglfswindow.h b/src/plugins/platforms/eglfs/api/qeglfswindow_p.h
index d607c8bd62..0889f27ae3 100644
--- a/src/plugins/platforms/eglfs/qeglfswindow.h
+++ b/src/plugins/platforms/eglfs/api/qeglfswindow_p.h
@@ -40,12 +40,23 @@
#ifndef QEGLFSWINDOW_H
#define QEGLFSWINDOW_H
-#include "qeglfsglobal.h"
-#include "qeglfsintegration.h"
-#include "qeglfsscreen.h"
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qeglfsglobal_p.h"
+#include "qeglfsintegration_p.h"
+#include "qeglfsscreen_p.h"
#include <qpa/qplatformwindow.h>
-#include <QtPlatformSupport/private/qopenglcompositor_p.h>
+#include <QtPlatformCompositorSupport/private/qopenglcompositor_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/deviceintegration.pro b/src/plugins/platforms/eglfs/deviceintegration/deviceintegration.pro
index 769c248d0d..d86a67b4f4 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/deviceintegration.pro
+++ b/src/plugins/platforms/eglfs/deviceintegration/deviceintegration.pro
@@ -1,12 +1,13 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += gui-private
-contains(QT_CONFIG, egl_x11): SUBDIRS += eglfs_x11
-contains(QT_CONFIG, eglfs_gbm): SUBDIRS += eglfs_kms_support eglfs_kms
-contains(QT_CONFIG, eglfs_egldevice): SUBDIRS += eglfs_kms_support eglfs_kms_egldevice
-contains(QT_CONFIG, eglfs_brcm): SUBDIRS += eglfs_brcm
-contains(QT_CONFIG, eglfs_mali): SUBDIRS += eglfs_mali
-contains(QT_CONFIG, eglfs_viv): SUBDIRS += eglfs_viv
-contains(QT_CONFIG, eglfs_viv_wl): SUBDIRS += eglfs_viv_wl
+qtConfig(egl_x11): SUBDIRS += eglfs_x11
+qtConfig(eglfs_gbm): SUBDIRS += eglfs_kms_support eglfs_kms
+qtConfig(eglfs_egldevice): SUBDIRS += eglfs_kms_support eglfs_kms_egldevice
+qtConfig(eglfs_brcm): SUBDIRS += eglfs_brcm
+qtConfig(eglfs_mali): SUBDIRS += eglfs_mali
+qtConfig(eglfs_viv): SUBDIRS += eglfs_viv
+qtConfig(eglfs_viv_wl): SUBDIRS += eglfs_viv_wl
eglfs_kms_egldevice.depends = eglfs_kms_support
eglfs_kms.depends = eglfs_kms_support
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/eglfs_brcm.pro b/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/eglfs_brcm.pro
index 2b710ac24c..fee67da2de 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/eglfs_brcm.pro
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/eglfs_brcm.pro
@@ -1,8 +1,8 @@
TARGET = qeglfs-brcm-integration
-QT += core-private gui-private platformsupport-private eglfs_device_lib-private
+QT += core-private gui-private eglfsdeviceintegration-private
-INCLUDEPATH += $$PWD/../..
+INCLUDEPATH += $$PWD/../../api
CONFIG += egl
LIBS += -lbcm_host
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmintegration.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmintegration.h
index 8f78b51190..5af628dedd 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmintegration.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmintegration.h
@@ -40,11 +40,11 @@
#ifndef QEGLFSBRCMINTEGRATION_H
#define QEGLFSBRCMINTEGRATION_H
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
QT_BEGIN_NAMESPACE
-class QEglFSBrcmIntegration : public QEGLDeviceIntegration
+class QEglFSBrcmIntegration : public QEglFSDeviceIntegration
{
public:
void platformInit() Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmmain.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmmain.cpp
index 0bd54ba239..80d7631931 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmmain.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_brcm/qeglfsbrcmmain.cpp
@@ -37,18 +37,18 @@
**
****************************************************************************/
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
#include "qeglfsbrcmintegration.h"
QT_BEGIN_NAMESPACE
-class QEglFSBrcmIntegrationPlugin : public QEGLDeviceIntegrationPlugin
+class QEglFSBrcmIntegrationPlugin : public QEglFSDeviceIntegrationPlugin
{
Q_OBJECT
- Q_PLUGIN_METADATA(IID QEGLDeviceIntegrationFactoryInterface_iid FILE "eglfs_brcm.json")
+ Q_PLUGIN_METADATA(IID QEglFSDeviceIntegrationFactoryInterface_iid FILE "eglfs_brcm.json")
public:
- QEGLDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSBrcmIntegration; }
+ QEglFSDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSBrcmIntegration; }
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/eglfs_kms.pro b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/eglfs_kms.pro
index b1791240ab..255db824b7 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/eglfs_kms.pro
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/eglfs_kms.pro
@@ -4,20 +4,14 @@ PLUGIN_TYPE = egldeviceintegrations
PLUGIN_CLASS_NAME = QEglFSKmsGbmIntegrationPlugin
load(qt_plugin)
-QT += core-private gui-private platformsupport-private eglfs_device_lib-private eglfs_kms_support-private
+QT += core-private gui-private eglfsdeviceintegration-private eglfs_kms_support-private
-INCLUDEPATH += $$PWD/../.. $$PWD/../eglfs_kms_support
+INCLUDEPATH += $$PWD/../../api $$PWD/../eglfs_kms_support
# Avoid X11 header collision, use generic EGL native types
DEFINES += QT_EGL_NO_X11
-CONFIG += link_pkgconfig
-!contains(QT_CONFIG, no-pkg-config) {
- PKGCONFIG += libdrm gbm
-} else {
- LIBS += -ldrm -lgbm
-}
-
+QMAKE_USE += gbm drm
CONFIG += egl
QMAKE_LFLAGS += $$QMAKE_LFLAGS_NOUNDEF
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.cpp
index 278752bddf..3a220ec942 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.cpp
@@ -42,7 +42,7 @@
#include "qeglfskmsgbmdevice.h"
#include "qeglfskmsgbmscreen.h"
-#include "qeglfsintegration.h"
+#include "qeglfsintegration_p.h"
#include <QtCore/QLoggingCategory>
#include <QtCore/private/qcore_unix_p.h>
@@ -142,10 +142,10 @@ void QEglFSKmsGbmDevice::handleDrmEvent()
drmHandleEvent(fd(), &drmEvent);
}
-QEglFSKmsScreen *QEglFSKmsGbmDevice::createScreen(QEglFSKmsIntegration *integration, QEglFSKmsDevice *device, QEglFSKmsOutput output, QPoint position)
+QEglFSKmsScreen *QEglFSKmsGbmDevice::createScreen(QEglFSKmsIntegration *integration, QEglFSKmsDevice *device, QEglFSKmsOutput output)
{
static bool firstScreen = true;
- QEglFSKmsGbmScreen *screen = new QEglFSKmsGbmScreen(integration, device, output, position);
+ QEglFSKmsGbmScreen *screen = new QEglFSKmsGbmScreen(integration, device, output);
if (firstScreen && integration->hwCursor()) {
m_globalCursor = new QEglFSKmsGbmCursor(screen);
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.h
index 6a45f9ffa0..7c0af84422 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmdevice.h
@@ -68,8 +68,7 @@ public:
virtual QEglFSKmsScreen *createScreen(QEglFSKmsIntegration *integration,
QEglFSKmsDevice *device,
- QEglFSKmsOutput output,
- QPoint position) Q_DECL_OVERRIDE;
+ QEglFSKmsOutput output) Q_DECL_OVERRIDE;
private:
Q_DISABLE_COPY(QEglFSKmsGbmDevice)
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmintegration.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmintegration.cpp
index 1c0a8e1b5f..38419a55c8 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmintegration.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmintegration.cpp
@@ -43,9 +43,9 @@
#include "qeglfskmsgbmdevice.h"
#include "qeglfskmsgbmscreen.h"
#include "qeglfskmsgbmcursor.h"
-#include "qeglfscursor.h"
+#include "private/qeglfscursor_p.h"
-#include <QtPlatformSupport/private/qdevicediscovery_p.h>
+#include <QtDeviceDiscoverySupport/private/qdevicediscovery_p.h>
#include <QtCore/QLoggingCategory>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
@@ -126,7 +126,7 @@ QEglFSKmsDevice *QEglFSKmsGbmIntegration::createDevice(const QString &devicePath
} else {
QDeviceDiscovery *d = QDeviceDiscovery::create(QDeviceDiscovery::Device_VideoMask);
- QStringList devices = d->scanConnectedDevices();
+ const QStringList devices = d->scanConnectedDevices();
qCDebug(qLcEglfsKmsDebug) << "Found the following video devices:" << devices;
d->deleteLater();
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmmain.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmmain.cpp
index 8e8779ca10..f34e4859c6 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmmain.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmmain.cpp
@@ -38,18 +38,18 @@
**
****************************************************************************/
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
#include "qeglfskmsgbmintegration.h"
QT_BEGIN_NAMESPACE
-class QEglFSKmsGbmIntegrationPlugin : public QEGLDeviceIntegrationPlugin
+class QEglFSKmsGbmIntegrationPlugin : public QEglFSDeviceIntegrationPlugin
{
Q_OBJECT
- Q_PLUGIN_METADATA(IID QEGLDeviceIntegrationFactoryInterface_iid FILE "eglfs_kms.json")
+ Q_PLUGIN_METADATA(IID QEglFSDeviceIntegrationFactoryInterface_iid FILE "eglfs_kms.json")
public:
- QEGLDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSKmsGbmIntegration; }
+ QEglFSDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSKmsGbmIntegration; }
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.cpp
index 7a17b60a5e..bed775ff81 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.cpp
@@ -42,12 +42,12 @@
#include "qeglfskmsgbmscreen.h"
#include "qeglfskmsgbmdevice.h"
#include "qeglfskmsgbmcursor.h"
-#include "qeglfsintegration.h"
+#include "qeglfsintegration_p.h"
#include <QtCore/QLoggingCategory>
#include <QtGui/private/qguiapplication_p.h>
-#include <QtPlatformSupport/private/qfbvthandler_p.h>
+#include <QtFbSupport/private/qfbvthandler_p.h>
QT_BEGIN_NAMESPACE
@@ -93,10 +93,9 @@ QEglFSKmsGbmScreen::FrameBuffer *QEglFSKmsGbmScreen::framebufferForBufferObject(
}
QEglFSKmsGbmScreen::QEglFSKmsGbmScreen(QEglFSKmsIntegration *integration,
- QEglFSKmsDevice *device,
- QEglFSKmsOutput output,
- QPoint position)
- : QEglFSKmsScreen(integration, device, output, position)
+ QEglFSKmsDevice *device,
+ QEglFSKmsOutput output)
+ : QEglFSKmsScreen(integration, device, output)
, m_gbm_surface(Q_NULLPTR)
, m_gbm_bo_current(Q_NULLPTR)
, m_gbm_bo_next(Q_NULLPTR)
@@ -130,8 +129,8 @@ gbm_surface *QEglFSKmsGbmScreen::createSurface()
if (!m_gbm_surface) {
qCDebug(qLcEglfsKmsDebug) << "Creating window for screen" << name();
m_gbm_surface = gbm_surface_create(static_cast<QEglFSKmsGbmDevice *>(device())->gbmDevice(),
- geometry().width(),
- geometry().height(),
+ rawGeometry().width(),
+ rawGeometry().height(),
GBM_FORMAT_XRGB8888,
GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);
}
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.h
index 3381bbfdbb..d7ad348291 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms/qeglfskmsgbmscreen.h
@@ -55,9 +55,8 @@ class QEglFSKmsGbmScreen : public QEglFSKmsScreen
{
public:
QEglFSKmsGbmScreen(QEglFSKmsIntegration *integration,
- QEglFSKmsDevice *device,
- QEglFSKmsOutput output,
- QPoint position);
+ QEglFSKmsDevice *device,
+ QEglFSKmsOutput output);
~QEglFSKmsGbmScreen();
QPlatformCursor *cursor() const Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/eglfs_kms_egldevice.pro b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/eglfs_kms_egldevice.pro
index e2263f6cbf..a625021aba 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/eglfs_kms_egldevice.pro
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/eglfs_kms_egldevice.pro
@@ -1,19 +1,13 @@
TARGET = qeglfs-kms-egldevice-integration
-QT += core-private gui-private platformsupport-private eglfs_device_lib-private eglfs_kms_support-private
+QT += core-private gui-private eglfsdeviceintegration-private eglfs_kms_support-private
-INCLUDEPATH += $$PWD/../.. $$PWD/../eglfs_kms_support
+INCLUDEPATH += $$PWD/../../api $$PWD/../eglfs_kms_support
# Avoid X11 header collision, use generic EGL native types
DEFINES += QT_EGL_NO_X11
-CONFIG += link_pkgconfig
-!contains(QT_CONFIG, no-pkg-config) {
- PKGCONFIG += libdrm
-} else {
- LIBS += -ldrm
-}
-
+QMAKE_USE += drm
CONFIG += egl
QMAKE_LFLAGS += $$QMAKE_LFLAGS_NOUNDEF
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.cpp
index f6e86bf0bc..60989e2bd0 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.cpp
@@ -40,11 +40,15 @@
#include "qeglfskmsegldevice.h"
#include "qeglfskmsegldevicescreen.h"
#include "qeglfskmsegldeviceintegration.h"
+#include "private/qeglfscursor_p.h"
#include <QtCore/private/qcore_unix_p.h>
+QT_BEGIN_NAMESPACE
+
QEglFSKmsEglDevice::QEglFSKmsEglDevice(QEglFSKmsIntegration *integration, const QString &path)
- : QEglFSKmsDevice(integration, path)
+ : QEglFSKmsDevice(integration, path),
+ m_globalCursor(nullptr)
{
}
@@ -52,6 +56,8 @@ bool QEglFSKmsEglDevice::open()
{
Q_ASSERT(fd() == -1);
+ qCDebug(qLcEglfsKmsDebug, "Opening DRM device %s", qPrintable(devicePath()));
+
int fd = drmOpen(devicePath().toLocal8Bit().constData(), Q_NULLPTR);
if (Q_UNLIKELY(fd < 0))
qFatal("Could not open DRM device");
@@ -63,6 +69,8 @@ bool QEglFSKmsEglDevice::open()
void QEglFSKmsEglDevice::close()
{
+ qCDebug(qLcEglfsKmsDebug, "Closing DRM device");
+
if (qt_safe_close(fd()) == -1)
qErrnoWarning("Could not close DRM device");
@@ -74,7 +82,26 @@ EGLNativeDisplayType QEglFSKmsEglDevice::nativeDisplay() const
return reinterpret_cast<EGLNativeDisplayType>(static_cast<QEglFSKmsEglDeviceIntegration *>(m_integration)->eglDevice());
}
-QEglFSKmsScreen *QEglFSKmsEglDevice::createScreen(QEglFSKmsIntegration *integration, QEglFSKmsDevice *device, QEglFSKmsOutput output, QPoint position)
+QEglFSKmsScreen *QEglFSKmsEglDevice::createScreen(QEglFSKmsIntegration *integration, QEglFSKmsDevice *device,
+ QEglFSKmsOutput output)
{
- return new QEglFSKmsEglDeviceScreen(integration, device, output, position);
+ QEglFSKmsScreen *screen = new QEglFSKmsEglDeviceScreen(integration, device, output);
+
+ if (!m_globalCursor && !integration->separateScreens()) {
+ qCDebug(qLcEglfsKmsDebug, "Creating new global mouse cursor");
+ m_globalCursor = new QEglFSCursor(screen);
+ }
+
+ return screen;
}
+
+void QEglFSKmsEglDevice::destroyGlobalCursor()
+{
+ if (m_globalCursor) {
+ qCDebug(qLcEglfsKmsDebug, "Destroying global mouse cursor");
+ delete m_globalCursor;
+ m_globalCursor = nullptr;
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.h
index b1c98f3fe6..8c8f79f70c 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevice.h
@@ -42,6 +42,10 @@
#include <qeglfskmsdevice.h>
+QT_BEGIN_NAMESPACE
+
+class QPlatformCursor;
+
class QEglFSKmsEglDevice: public QEglFSKmsDevice
{
public:
@@ -54,8 +58,15 @@ public:
virtual QEglFSKmsScreen *createScreen(QEglFSKmsIntegration *integration,
QEglFSKmsDevice *device,
- QEglFSKmsOutput output,
- QPoint position) Q_DECL_OVERRIDE;
+ QEglFSKmsOutput output) Q_DECL_OVERRIDE;
+
+ QPlatformCursor *globalCursor() { return m_globalCursor; }
+ void destroyGlobalCursor();
+
+private:
+ QPlatformCursor *m_globalCursor;
};
+QT_END_NAMESPACE
+
#endif // QEGLFSKMSEGLDEVICE_H
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp
index 838569d5c6..d0c9c9565e 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp
@@ -39,8 +39,9 @@
****************************************************************************/
#include "qeglfskmsegldeviceintegration.h"
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-#include "qeglfswindow.h"
+#include <QtEglSupport/private/qeglconvenience_p.h>
+#include "private/qeglfswindow_p.h"
+#include "private/qeglfscursor_p.h"
#include "qeglfskmsegldevice.h"
#include "qeglfskmsscreen.h"
#include <QLoggingCategory>
@@ -189,12 +190,12 @@ void QEglJetsonTK1Window::resetSurface()
if (!m_integration->m_funcs->stream_consumer_output(display, m_egl_stream, layer))
qWarning("resetSurface: Unable to connect stream");
- m_config = QEglFSIntegration::chooseConfig(display, m_integration->surfaceFormatFor(window()->requestedFormat()));
+ m_config = QEglFSDeviceIntegration::chooseConfig(display, m_integration->surfaceFormatFor(window()->requestedFormat()));
m_format = q_glFormatFromConfig(display, m_config);
qCDebug(qLcEglfsKmsDebug) << "Stream producer format is" << m_format;
- const int w = cur_screen->geometry().width();
- const int h = cur_screen->geometry().height();
+ const int w = cur_screen->rawGeometry().width();
+ const int h = cur_screen->rawGeometry().height();
qCDebug(qLcEglfsKmsDebug, "Creating stream producer surface of size %dx%d", w, h);
const EGLint stream_producer_attribs[] = {
@@ -222,11 +223,6 @@ QEglFSWindow *QEglFSKmsEglDeviceIntegration::createWindow(QWindow *window) const
return eglWindow;
}
-bool QEglFSKmsEglDeviceIntegration::separateScreens() const
-{
- return true;
-}
-
QEglFSKmsDevice *QEglFSKmsEglDeviceIntegration::createDevice(const QString &devicePath)
{
Q_UNUSED(devicePath)
@@ -263,4 +259,9 @@ bool QEglFSKmsEglDeviceIntegration::query_egl_device()
return true;
}
+QPlatformCursor *QEglFSKmsEglDeviceIntegration::createCursor(QPlatformScreen *screen) const
+{
+ return separateScreens() ? new QEglFSCursor(screen) : nullptr;
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h
index f04c42267a..cddfdbd5c6 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h
@@ -46,7 +46,7 @@
#include <xf86drm.h>
#include <xf86drmMode.h>
-#include <QtPlatformSupport/private/qeglstreamconvenience_p.h>
+#include <QtEglSupport/private/qeglstreamconvenience_p.h>
QT_BEGIN_NAMESPACE
@@ -61,12 +61,11 @@ public:
bool supportsPBuffers() const Q_DECL_OVERRIDE;
QEglFSWindow *createWindow(QWindow *window) const Q_DECL_OVERRIDE;
- virtual bool separateScreens() const Q_DECL_OVERRIDE;
-
EGLDeviceEXT eglDevice() const { return m_egl_device; }
protected:
QEglFSKmsDevice *createDevice(const QString &devicePath) Q_DECL_OVERRIDE;
+ QPlatformCursor *createCursor(QPlatformScreen *screen) const Q_DECL_OVERRIDE;
private:
bool setup_kms();
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicemain.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicemain.cpp
index 63571f796f..42fec073f1 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicemain.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicemain.cpp
@@ -41,13 +41,13 @@
QT_BEGIN_NAMESPACE
-class QEglFSKmsEglDeviceIntegrationPlugin : public QEGLDeviceIntegrationPlugin
+class QEglFSKmsEglDeviceIntegrationPlugin : public QEglFSDeviceIntegrationPlugin
{
Q_OBJECT
- Q_PLUGIN_METADATA(IID QEGLDeviceIntegrationFactoryInterface_iid FILE "eglfs_kms_egldevice.json")
+ Q_PLUGIN_METADATA(IID QEglFSDeviceIntegrationFactoryInterface_iid FILE "eglfs_kms_egldevice.json")
public:
- QEGLDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSKmsEglDeviceIntegration; }
+ QEglFSDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSKmsEglDeviceIntegration; }
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.cpp
index da1b577801..1f672afeb4 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.cpp
@@ -39,10 +39,30 @@
#include "qeglfskmsegldevicescreen.h"
#include "qeglfskmsegldevice.h"
+#include <QGuiApplication>
-QEglFSKmsEglDeviceScreen::QEglFSKmsEglDeviceScreen(QEglFSKmsIntegration *integration, QEglFSKmsDevice *device, QEglFSKmsOutput output, QPoint position)
- : QEglFSKmsScreen(integration, device, output, position)
+QT_BEGIN_NAMESPACE
+
+QEglFSKmsEglDeviceScreen::QEglFSKmsEglDeviceScreen(QEglFSKmsIntegration *integration, QEglFSKmsDevice *device, QEglFSKmsOutput output)
+ : QEglFSKmsScreen(integration, device, output)
+{
+}
+
+QEglFSKmsEglDeviceScreen::~QEglFSKmsEglDeviceScreen()
{
+ const int remainingScreenCount = qGuiApp->screens().count();
+ qCDebug(qLcEglfsKmsDebug, "Screen dtor. Remaining screens: %d", remainingScreenCount);
+ if (!remainingScreenCount && !m_integration->separateScreens())
+ static_cast<QEglFSKmsEglDevice *>(device())->destroyGlobalCursor();
+}
+
+QPlatformCursor *QEglFSKmsEglDeviceScreen::cursor() const
+{
+ // The base class creates a cursor via integration->createCursor()
+ // in its ctor. With separateScreens just use that. Otherwise
+ // there's a virtual desktop and the device has a global cursor
+ // and the base class has no dedicated cursor at all.
+ return m_integration->separateScreens() ? QEglFSScreen::cursor() : static_cast<QEglFSKmsEglDevice *>(device())->globalCursor();
}
void QEglFSKmsEglDeviceScreen::waitForFlip()
@@ -68,7 +88,7 @@ void QEglFSKmsEglDeviceScreen::waitForFlip()
qCDebug(qLcEglfsKmsDebug, "Setting mode");
int ret = drmModeSetCrtc(device()->fd(), output().crtc_id,
- -1, 0, 0,
+ uint32_t(-1), 0, 0,
&output().connector_id, 1,
&output().modes[output().mode]);
if (ret)
@@ -76,3 +96,5 @@ void QEglFSKmsEglDeviceScreen::waitForFlip()
}
}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.h
index 0cd46e9f9d..c57f52c6b7 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldevicescreen.h
@@ -42,15 +42,21 @@
#include <qeglfskmsscreen.h>
+QT_BEGIN_NAMESPACE
+
class QEglFSKmsEglDeviceScreen : public QEglFSKmsScreen
{
public:
QEglFSKmsEglDeviceScreen(QEglFSKmsIntegration *integration,
QEglFSKmsDevice *device,
- QEglFSKmsOutput output,
- QPoint position);
+ QEglFSKmsOutput output);
+ ~QEglFSKmsEglDeviceScreen();
+
+ QPlatformCursor *cursor() const Q_DECL_OVERRIDE;
void waitForFlip() Q_DECL_OVERRIDE;
};
+QT_END_NAMESPACE
+
#endif // QEGLFSKMSEGLDEVICESCREEN_H
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/eglfs_kms_support.pro b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/eglfs_kms_support.pro
index 32f15f33fb..487edb569e 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/eglfs_kms_support.pro
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/eglfs_kms_support.pro
@@ -2,20 +2,14 @@ TARGET = QtEglFsKmsSupport
CONFIG += no_module_headers internal_module
load(qt_module)
-QT += core-private gui-private platformsupport-private eglfs_device_lib-private
+QT += core-private gui-private eglfsdeviceintegration-private
-INCLUDEPATH += $$PWD/../..
+INCLUDEPATH += $$PWD/../../api
# Avoid X11 header collision, use generic EGL native types
DEFINES += QT_EGL_NO_X11
-CONFIG += link_pkgconfig
-!contains(QT_CONFIG, no-pkg-config) {
- PKGCONFIG += libdrm
-} else {
- LIBS += -ldrm
-}
-
+QMAKE_USE += drm
CONFIG += egl
QMAKE_LFLAGS += $$QMAKE_LFLAGS_NOUNDEF
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.cpp
index f4ffee569d..f6b58d1ba6 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.cpp
@@ -42,7 +42,7 @@
#include "qeglfskmsdevice.h"
#include "qeglfskmsscreen.h"
-#include "qeglfsintegration.h"
+#include "qeglfsintegration_p.h"
#include <QtCore/QLoggingCategory>
#include <QtCore/private/qcore_unix_p.h>
@@ -86,7 +86,7 @@ int QEglFSKmsDevice::crtcForConnector(drmModeResPtr resources, drmModeConnectorP
return -1;
}
-static const char * const connector_type_names[] = {
+static const char * const connector_type_names[] = { // must match DRM_MODE_CONNECTOR_*
"None",
"VGA",
"DVI",
@@ -102,6 +102,8 @@ static const char * const connector_type_names[] = {
"HDMI",
"TV",
"eDP",
+ "Virtual",
+ "DSI"
};
static QByteArray nameForConnector(const drmModeConnectorPtr connector)
@@ -159,7 +161,9 @@ static bool parseModeline(const QByteArray &text, drmModeModeInfoPtr mode)
return true;
}
-QEglFSKmsScreen *QEglFSKmsDevice::screenForConnector(drmModeResPtr resources, drmModeConnectorPtr connector, QPoint pos)
+QEglFSKmsScreen *QEglFSKmsDevice::createScreenForConnector(drmModeResPtr resources,
+ drmModeConnectorPtr connector,
+ VirtualDesktopInfo *vinfo)
{
const QByteArray connectorName = nameForConnector(connector);
@@ -173,8 +177,11 @@ QEglFSKmsScreen *QEglFSKmsDevice::screenForConnector(drmModeResPtr resources, dr
QSize configurationSize;
drmModeModeInfo configurationModeline;
- const QByteArray mode = m_integration->outputSettings().value(QString::fromUtf8(connectorName))
- .value(QStringLiteral("mode"), QStringLiteral("preferred")).toByteArray().toLower();
+ auto userConfig = m_integration->outputSettings();
+ auto userConnectorConfig = userConfig.value(QString::fromUtf8(connectorName));
+ // default to the preferred mode unless overridden in the config
+ const QByteArray mode = userConnectorConfig.value(QStringLiteral("mode"), QStringLiteral("preferred"))
+ .toByteArray().toLower();
if (mode == "off") {
configuration = OutputConfigOff;
} else if (mode == "preferred") {
@@ -189,6 +196,16 @@ QEglFSKmsScreen *QEglFSKmsDevice::screenForConnector(drmModeResPtr resources, dr
qWarning("Invalid mode \"%s\" for output %s", mode.constData(), connectorName.constData());
configuration = OutputConfigPreferred;
}
+ if (vinfo) {
+ *vinfo = VirtualDesktopInfo();
+ vinfo->virtualIndex = userConnectorConfig.value(QStringLiteral("virtualIndex"), INT_MAX).toInt();
+ if (userConnectorConfig.contains(QStringLiteral("virtualPos"))) {
+ const QByteArray vpos = userConnectorConfig.value(QStringLiteral("virtualPos")).toByteArray();
+ const QByteArrayList vposComp = vpos.split(',');
+ if (vposComp.count() == 2)
+ vinfo->virtualPos = QPoint(vposComp[0].trimmed().toInt(), vposComp[1].trimmed().toInt());
+ }
+ }
const uint32_t crtc_id = resources->crtcs[crtc];
@@ -287,18 +304,26 @@ QEglFSKmsScreen *QEglFSKmsDevice::screenForConnector(drmModeResPtr resources, dr
qCDebug(qLcEglfsKmsDebug) << "Selected mode" << selected_mode << ":" << width << "x" << height
<< '@' << refresh << "hz for output" << connectorName;
}
+
+ // physical size from connector < config values < env vars
static const int width = qEnvironmentVariableIntValue("QT_QPA_EGLFS_PHYSICAL_WIDTH");
static const int height = qEnvironmentVariableIntValue("QT_QPA_EGLFS_PHYSICAL_HEIGHT");
- QSizeF size(width, height);
- if (size.isEmpty()) {
- size.setWidth(connector->mmWidth);
- size.setHeight(connector->mmHeight);
+ QSizeF physSize(width, height);
+ if (physSize.isEmpty()) {
+ physSize = QSize(userConnectorConfig.value(QStringLiteral("physicalWidth")).toInt(),
+ userConnectorConfig.value(QStringLiteral("physicalHeight")).toInt());
+ if (physSize.isEmpty()) {
+ physSize.setWidth(connector->mmWidth);
+ physSize.setHeight(connector->mmHeight);
+ }
}
+ qCDebug(qLcEglfsKmsDebug) << "Physical size is" << physSize << "mm" << "for output" << connectorName;
+
QEglFSKmsOutput output = {
QString::fromUtf8(connectorName),
connector->connector_id,
crtc_id,
- size,
+ physSize,
selected_mode,
false,
drmModeGetCrtc(m_dri_fd, crtc_id),
@@ -310,7 +335,7 @@ QEglFSKmsScreen *QEglFSKmsDevice::screenForConnector(drmModeResPtr resources, dr
m_crtc_allocator |= (1 << output.crtc_id);
m_connector_allocator |= (1 << output.connector_id);
- return createScreen(m_integration, this, output, pos);
+ return createScreen(m_integration, this, output);
}
drmModePropertyPtr QEglFSKmsDevice::connectorProperty(drmModeConnectorPtr connector, const QByteArray &name)
@@ -342,6 +367,28 @@ QEglFSKmsDevice::~QEglFSKmsDevice()
{
}
+struct OrderedScreen
+{
+ OrderedScreen() : screen(nullptr) { }
+ OrderedScreen(QEglFSKmsScreen *screen, const QEglFSKmsDevice::VirtualDesktopInfo &vinfo)
+ : screen(screen), vinfo(vinfo) { }
+ QEglFSKmsScreen *screen;
+ QEglFSKmsDevice::VirtualDesktopInfo vinfo;
+};
+
+QDebug operator<<(QDebug dbg, const OrderedScreen &s)
+{
+ QDebugStateSaver saver(dbg);
+ dbg.nospace() << "OrderedScreen(" << s.screen << " : " << s.vinfo.virtualIndex
+ << " / " << s.vinfo.virtualPos << ")";
+ return dbg;
+}
+
+static bool orderedScreenLessThan(const OrderedScreen &a, const OrderedScreen &b)
+{
+ return a.vinfo.virtualIndex < b.vinfo.virtualIndex;
+}
+
void QEglFSKmsDevice::createScreens()
{
drmModeResPtr resources = drmModeGetResources(m_dri_fd);
@@ -350,32 +397,53 @@ void QEglFSKmsDevice::createScreens()
return;
}
- QEglFSKmsScreen *primaryScreen = Q_NULLPTR;
- QList<QPlatformScreen *> siblings;
- QPoint pos(0, 0);
- QEglFSIntegration *integration = static_cast<QEglFSIntegration *>(QGuiApplicationPrivate::platformIntegration());
+ QVector<OrderedScreen> screens;
for (int i = 0; i < resources->count_connectors; i++) {
drmModeConnectorPtr connector = drmModeGetConnector(m_dri_fd, resources->connectors[i]);
if (!connector)
continue;
- QEglFSKmsScreen *screen = screenForConnector(resources, connector, pos);
- if (screen) {
- integration->addScreen(screen);
- pos.rx() += screen->geometry().width();
- siblings << screen;
-
- if (!primaryScreen)
- primaryScreen = screen;
- }
+ VirtualDesktopInfo vinfo;
+ QEglFSKmsScreen *screen = createScreenForConnector(resources, connector, &vinfo);
+ if (screen)
+ screens.append(OrderedScreen(screen, vinfo));
drmModeFreeConnector(connector);
}
drmModeFreeResources(resources);
+ // Use stable sort to preserve the original order for outputs with unspecified indices.
+ std::stable_sort(screens.begin(), screens.end(), orderedScreenLessThan);
+ qCDebug(qLcEglfsKmsDebug) << "Sorted screen list:" << screens;
+
+ QPoint pos(0, 0);
+ QList<QPlatformScreen *> siblings;
+ QEglFSIntegration *qpaIntegration = static_cast<QEglFSIntegration *>(QGuiApplicationPrivate::platformIntegration());
+
+ for (const OrderedScreen &orderedScreen : screens) {
+ QEglFSKmsScreen *s = orderedScreen.screen;
+ // set up a horizontal or vertical virtual desktop
+ if (orderedScreen.vinfo.virtualPos.isNull()) {
+ s->setVirtualPosition(pos);
+ if (m_integration->virtualDesktopLayout() == QEglFSKmsIntegration::VirtualDesktopLayoutVertical)
+ pos.ry() += s->geometry().height();
+ else
+ pos.rx() += s->geometry().width();
+ } else {
+ s->setVirtualPosition(orderedScreen.vinfo.virtualPos);
+ }
+ qCDebug(qLcEglfsKmsDebug) << "Adding screen" << s << "to QPA with geometry" << s->geometry();
+ // The order in qguiapp's screens list will match the order set by
+ // virtualIndex. This is not only handy but also required since for instance
+ // evdevtouch relies on it when performing touch device - screen mapping.
+ qpaIntegration->addScreen(s);
+ siblings << s;
+ }
+
if (!m_integration->separateScreens()) {
+ // enable the virtual desktop
Q_FOREACH (QPlatformScreen *screen, siblings)
static_cast<QEglFSKmsScreen *>(screen)->setVirtualSiblings(siblings);
}
@@ -391,9 +459,9 @@ QString QEglFSKmsDevice::devicePath() const
return m_path;
}
-QEglFSKmsScreen *QEglFSKmsDevice::createScreen(QEglFSKmsIntegration *integration, QEglFSKmsDevice *device, QEglFSKmsOutput output, QPoint position)
+QEglFSKmsScreen *QEglFSKmsDevice::createScreen(QEglFSKmsIntegration *integration, QEglFSKmsDevice *device, QEglFSKmsOutput output)
{
- return new QEglFSKmsScreen(integration, device, output, position);
+ return new QEglFSKmsScreen(integration, device, output);
}
void QEglFSKmsDevice::setFd(int fd)
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.h
index 041c063695..3e7ac7e3f0 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsdevice.h
@@ -53,6 +53,12 @@ QT_BEGIN_NAMESPACE
class Q_EGLFS_EXPORT QEglFSKmsDevice
{
public:
+ struct VirtualDesktopInfo {
+ VirtualDesktopInfo() : virtualIndex(0) { }
+ int virtualIndex;
+ QPoint virtualPos;
+ };
+
QEglFSKmsDevice(QEglFSKmsIntegration *integration, const QString &path);
virtual ~QEglFSKmsDevice();
@@ -68,8 +74,7 @@ public:
protected:
virtual QEglFSKmsScreen *createScreen(QEglFSKmsIntegration *integration,
QEglFSKmsDevice *device,
- QEglFSKmsOutput output,
- QPoint position);
+ QEglFSKmsOutput output);
void setFd(int fd);
QEglFSKmsIntegration *m_integration;
@@ -80,7 +85,9 @@ protected:
quint32 m_connector_allocator;
int crtcForConnector(drmModeResPtr resources, drmModeConnectorPtr connector);
- QEglFSKmsScreen *screenForConnector(drmModeResPtr resources, drmModeConnectorPtr connector, QPoint pos);
+ QEglFSKmsScreen *createScreenForConnector(drmModeResPtr resources,
+ drmModeConnectorPtr connector,
+ VirtualDesktopInfo *vinfo);
drmModePropertyPtr connectorProperty(drmModeConnectorPtr connector, const QByteArray &name);
static void pageFlipHandler(int fd,
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.cpp
index 07ea7d4439..5368a6d031 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.cpp
@@ -42,15 +42,12 @@
#include "qeglfskmsintegration.h"
#include "qeglfskmsdevice.h"
#include "qeglfskmsscreen.h"
-#include "qeglfswindow.h"
-#include "qeglfscursor.h"
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
+#include <QtCore/QFile>
#include <QtGui/qpa/qplatformwindow.h>
-#include <QtGui/qpa/qplatformcursor.h>
#include <QtGui/QScreen>
#include <xf86drm.h>
@@ -65,6 +62,7 @@ QEglFSKmsIntegration::QEglFSKmsIntegration()
, m_hwCursor(false)
, m_pbuffers(false)
, m_separateScreens(false)
+ , m_virtualDesktopLayout(VirtualDesktopLayoutHorizontal)
{}
void QEglFSKmsIntegration::platformInit()
@@ -149,6 +147,11 @@ bool QEglFSKmsIntegration::separateScreens() const
return m_separateScreens;
}
+QEglFSKmsIntegration::VirtualDesktopLayout QEglFSKmsIntegration::virtualDesktopLayout() const
+{
+ return m_virtualDesktopLayout;
+}
+
QMap<QString, QVariantMap> QEglFSKmsIntegration::outputSettings() const
{
return m_outputSettings;
@@ -169,15 +172,15 @@ void QEglFSKmsIntegration::loadConfig()
QFile file(QString::fromUtf8(json));
if (!file.open(QFile::ReadOnly)) {
- qCDebug(qLcEglfsKmsDebug) << "Could not open config file"
- << json << "for reading";
+ qCWarning(qLcEglfsKmsDebug) << "Could not open config file"
+ << json << "for reading";
return;
}
const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
if (!doc.isObject()) {
- qCDebug(qLcEglfsKmsDebug) << "Invalid config file" << json
- << "- no top-level JSON object";
+ qCWarning(qLcEglfsKmsDebug) << "Invalid config file" << json
+ << "- no top-level JSON object";
return;
}
@@ -188,6 +191,16 @@ void QEglFSKmsIntegration::loadConfig()
m_devicePath = object.value(QLatin1String("device")).toString();
m_separateScreens = object.value(QLatin1String("separateScreens")).toBool(m_separateScreens);
+ const QString vdOriString = object.value(QLatin1String("virtualDesktopLayout")).toString();
+ if (!vdOriString.isEmpty()) {
+ if (vdOriString == QLatin1String("horizontal"))
+ m_virtualDesktopLayout = VirtualDesktopLayoutHorizontal;
+ else if (vdOriString == QLatin1String("vertical"))
+ m_virtualDesktopLayout = VirtualDesktopLayoutVertical;
+ else
+ qCWarning(qLcEglfsKmsDebug) << "Unknown virtualDesktopOrientation value" << vdOriString;
+ }
+
const QJsonArray outputs = object.value(QLatin1String("outputs")).toArray();
for (int i = 0; i < outputs.size(); i++) {
const QVariantMap outputSettings = outputs.at(i).toObject().toVariantMap();
@@ -207,6 +220,7 @@ void QEglFSKmsIntegration::loadConfig()
<< "\thwcursor:" << m_hwCursor << "\n"
<< "\tpbuffers:" << m_pbuffers << "\n"
<< "\tseparateScreens:" << m_separateScreens << "\n"
+ << "\tvirtualDesktopLayout:" << m_virtualDesktopLayout << "\n"
<< "\toutputs:" << m_outputSettings;
}
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.h
index 34ac5385a5..ba49945715 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsintegration.h
@@ -42,7 +42,7 @@
#ifndef QEGLFSKMSINTEGRATION_H
#define QEGLFSKMSINTEGRATION_H
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
#include <QtCore/QMap>
#include <QtCore/QVariant>
#include <QtCore/QLoggingCategory>
@@ -53,9 +53,14 @@ class QEglFSKmsDevice;
Q_EGLFS_EXPORT Q_DECLARE_LOGGING_CATEGORY(qLcEglfsKmsDebug)
-class Q_EGLFS_EXPORT QEglFSKmsIntegration : public QEGLDeviceIntegration
+class Q_EGLFS_EXPORT QEglFSKmsIntegration : public QEglFSDeviceIntegration
{
public:
+ enum VirtualDesktopLayout {
+ VirtualDesktopLayoutHorizontal,
+ VirtualDesktopLayoutVertical
+ };
+
QEglFSKmsIntegration();
void platformInit() Q_DECL_OVERRIDE;
@@ -70,6 +75,7 @@ public:
virtual bool hwCursor() const;
virtual bool separateScreens() const;
+ virtual VirtualDesktopLayout virtualDesktopLayout() const;
QMap<QString, QVariantMap> outputSettings() const;
QEglFSKmsDevice *device() const;
@@ -83,6 +89,7 @@ protected:
bool m_hwCursor;
bool m_pbuffers;
bool m_separateScreens;
+ VirtualDesktopLayout m_virtualDesktopLayout;
QString m_devicePath;
QMap<QString, QVariantMap> m_outputSettings;
};
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.cpp
index e6b256f6b2..4021609407 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.cpp
@@ -41,12 +41,12 @@
#include "qeglfskmsscreen.h"
#include "qeglfskmsdevice.h"
-#include "qeglfsintegration.h"
+#include "qeglfsintegration_p.h"
#include <QtCore/QLoggingCategory>
#include <QtGui/private/qguiapplication_p.h>
-#include <QtPlatformSupport/private/qfbvthandler_p.h>
+#include <QtFbSupport/private/qfbvthandler_p.h>
QT_BEGIN_NAMESPACE
@@ -71,17 +71,15 @@ private:
QEglFSKmsScreen::QEglFSKmsScreen(QEglFSKmsIntegration *integration,
QEglFSKmsDevice *device,
- QEglFSKmsOutput output,
- QPoint position)
+ QEglFSKmsOutput output)
: QEglFSScreen(eglGetDisplay(device->nativeDisplay()))
, m_integration(integration)
, m_device(device)
, m_output(output)
- , m_pos(position)
, m_powerState(PowerStateOn)
, m_interruptHandler(new QEglFSKmsInterruptHandler(this))
{
- m_siblings << this;
+ m_siblings << this; // gets overridden by QEglFSKmsDevice later if !separateScreens
}
QEglFSKmsScreen::~QEglFSKmsScreen()
@@ -98,7 +96,14 @@ QEglFSKmsScreen::~QEglFSKmsScreen()
delete m_interruptHandler;
}
-QRect QEglFSKmsScreen::geometry() const
+void QEglFSKmsScreen::setVirtualPosition(const QPoint &pos)
+{
+ m_pos = pos;
+}
+
+// Reimplement rawGeometry(), not geometry(). The base class implementation of
+// geometry() calls rawGeometry() and may apply additional transforms.
+QRect QEglFSKmsScreen::rawGeometry() const
{
const int mode = m_output.mode;
return QRect(m_pos.x(), m_pos.y(),
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.h
index aa698e1b5d..2b6a0ffe6c 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_support/qeglfskmsscreen.h
@@ -43,7 +43,7 @@
#define QEGLFSKMSSCREEN_H
#include "qeglfskmsintegration.h"
-#include "qeglfsscreen.h"
+#include "private/qeglfsscreen_p.h"
#include <QtCore/QList>
#include <QtCore/QMutex>
@@ -74,11 +74,13 @@ class Q_EGLFS_EXPORT QEglFSKmsScreen : public QEglFSScreen
public:
QEglFSKmsScreen(QEglFSKmsIntegration *integration,
QEglFSKmsDevice *device,
- QEglFSKmsOutput output,
- QPoint position);
+ QEglFSKmsOutput output);
~QEglFSKmsScreen();
- QRect geometry() const Q_DECL_OVERRIDE;
+ void setVirtualPosition(const QPoint &pos);
+
+ QRect rawGeometry() const Q_DECL_OVERRIDE;
+
int depth() const Q_DECL_OVERRIDE;
QImage::Format format() const Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/eglfs_mali.pro b/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/eglfs_mali.pro
index 3e486bd1bd..5e6f636e2b 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/eglfs_mali.pro
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/eglfs_mali.pro
@@ -1,11 +1,11 @@
TARGET = qeglfs-mali-integration
-QT += core-private gui-private platformsupport-private eglfs_device_lib-private
+QT += core-private gui-private eglfsdeviceintegration-private
# Avoid X11 header collision, use generic EGL native types
DEFINES += QT_EGL_NO_X11
-INCLUDEPATH += $$PWD/../..
+INCLUDEPATH += $$PWD/../../api
CONFIG += egl
QMAKE_LFLAGS += $$QMAKE_LFLAGS_NOUNDEF
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.cpp
index ffdb7a686b..cd468c989f 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.cpp
@@ -56,7 +56,7 @@ struct fbdev_window {
void QEglFSMaliIntegration::platformInit()
{
// Keep the non-overridden base class functions based on fb0 working.
- QEGLDeviceIntegration::platformInit();
+ QEglFSDeviceIntegration::platformInit();
int fd = qt_safe_open("/dev/fb0", O_RDWR, 0);
if (fd == -1)
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.h
index 35a2c64951..56883a3676 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmaliintegration.h
@@ -40,11 +40,11 @@
#ifndef QEGLFSMALIINTEGRATION_H
#define QEGLFSMALIINTEGRATION_H
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
QT_BEGIN_NAMESPACE
-class QEglFSMaliIntegration : public QEGLDeviceIntegration
+class QEglFSMaliIntegration : public QEglFSDeviceIntegration
{
public:
void platformInit() Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmalimain.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmalimain.cpp
index 0754e1af5b..a3c804f54d 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmalimain.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_mali/qeglfsmalimain.cpp
@@ -37,18 +37,18 @@
**
****************************************************************************/
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
#include "qeglfsmaliintegration.h"
QT_BEGIN_NAMESPACE
-class QEglFSMaliIntegrationPlugin : public QEGLDeviceIntegrationPlugin
+class QEglFSMaliIntegrationPlugin : public QEglFSDeviceIntegrationPlugin
{
Q_OBJECT
- Q_PLUGIN_METADATA(IID QEGLDeviceIntegrationFactoryInterface_iid FILE "eglfs_mali.json")
+ Q_PLUGIN_METADATA(IID QEglFSDeviceIntegrationFactoryInterface_iid FILE "eglfs_mali.json")
public:
- QEGLDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSMaliIntegration; }
+ QEglFSDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSMaliIntegration; }
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/eglfs_viv.pro b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/eglfs_viv.pro
index 6fac2f529a..f9cce8d48b 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/eglfs_viv.pro
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/eglfs_viv.pro
@@ -1,11 +1,10 @@
TARGET = qeglfs-viv-integration
-QT += core-private gui-private platformsupport-private eglfs_device_lib-private
+QT += core-private gui-private eglfsdeviceintegration-private
-INCLUDEPATH += $$PWD/../..
+INCLUDEPATH += $$PWD/../../api
CONFIG += egl
DEFINES += LINUX=1 EGL_API_FB=1
-LIBS += -lGAL
QMAKE_LFLAGS += $$QMAKE_LFLAGS_NOUNDEF
SOURCES += $$PWD/qeglfsvivmain.cpp \
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.cpp
index ca97f6c8f9..f2fcc0d3ff 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.cpp
@@ -49,7 +49,7 @@ QT_BEGIN_NAMESPACE
void QEglFSVivIntegration::platformInit()
{
- QEGLDeviceIntegration::platformInit();
+ QEglFSDeviceIntegration::platformInit();
int width, height;
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.h
index 4a8cd5c385..2e98c2b4b1 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivintegration.h
@@ -40,11 +40,11 @@
#ifndef QEGLFSVIVINTEGRATION_H
#define QEGLFSVIVINTEGRATION_H
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
QT_BEGIN_NAMESPACE
-class QEglFSVivIntegration : public QEGLDeviceIntegration
+class QEglFSVivIntegration : public QEglFSDeviceIntegration
{
public:
void platformInit() Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivmain.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivmain.cpp
index d1c9fb4086..ebe2091b1e 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivmain.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv/qeglfsvivmain.cpp
@@ -37,18 +37,18 @@
**
****************************************************************************/
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
#include "qeglfsvivintegration.h"
QT_BEGIN_NAMESPACE
-class QEglFSVivIntegrationPlugin : public QEGLDeviceIntegrationPlugin
+class QEglFSVivIntegrationPlugin : public QEglFSDeviceIntegrationPlugin
{
Q_OBJECT
- Q_PLUGIN_METADATA(IID QEGLDeviceIntegrationFactoryInterface_iid FILE "eglfs_viv.json")
+ Q_PLUGIN_METADATA(IID QEglFSDeviceIntegrationFactoryInterface_iid FILE "eglfs_viv.json")
public:
- QEGLDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSVivIntegration; }
+ QEglFSDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSVivIntegration; }
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/eglfs_viv_wl.pro b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/eglfs_viv_wl.pro
index 44f75c40e0..065a103376 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/eglfs_viv_wl.pro
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/eglfs_viv_wl.pro
@@ -1,11 +1,10 @@
TARGET = qeglfs-viv-wl-integration
-QT += core-private gui-private platformsupport-private eglfs_device_lib-private
+QT += core-private gui-private eglfsdeviceintegration-private
-INCLUDEPATH += $$PWD/../..
+INCLUDEPATH += $$PWD/../../api
CONFIG += egl
DEFINES += LINUX=1 EGL_API_FB=1
-LIBS += -lGAL
QMAKE_LFLAGS += $$QMAKE_LFLAGS_NOUNDEF
SOURCES += $$PWD/qeglfsvivwlmain.cpp \
@@ -15,8 +14,7 @@ HEADERS += $$PWD/qeglfsvivwlintegration.h
OTHER_FILES += $$PWD/eglfs_viv_wl.json
-CONFIG += link_pkgconfig
-PKGCONFIG_PRIVATE += wayland-server
+QMAKE_USE_PRIVATE += wayland_server
PLUGIN_TYPE = egldeviceintegrations
PLUGIN_CLASS_NAME = QEglFSVivWaylandIntegrationPlugin
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.cpp
index 5c113456e4..61e2f17766 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.cpp
@@ -47,7 +47,7 @@ QT_BEGIN_NAMESPACE
void QEglFSVivWaylandIntegration::platformInit()
{
- QEGLDeviceIntegration::platformInit();
+ QEglFSDeviceIntegration::platformInit();
int width, height;
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.h
index 40eacc8f2f..9abbe817a6 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.h
@@ -40,12 +40,12 @@
#ifndef QEGLFSVIVINTEGRATION_H
#define QEGLFSVIVINTEGRATION_H
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
struct wl_display;
QT_BEGIN_NAMESPACE
-class QEglFSVivWaylandIntegration : public QEGLDeviceIntegration
+class QEglFSVivWaylandIntegration : public QEglFSDeviceIntegration
{
public:
void platformInit() Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlmain.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlmain.cpp
index 02ef9c566c..3b26feda07 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlmain.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlmain.cpp
@@ -37,18 +37,18 @@
**
****************************************************************************/
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
#include "qeglfsvivwlintegration.h"
QT_BEGIN_NAMESPACE
-class QEglFSVivWaylandIntegrationPlugin : public QEGLDeviceIntegrationPlugin
+class QEglFSVivWaylandIntegrationPlugin : public QEglFSDeviceIntegrationPlugin
{
Q_OBJECT
- Q_PLUGIN_METADATA(IID QEGLDeviceIntegrationFactoryInterface_iid FILE "eglfs_viv_wl.json")
+ Q_PLUGIN_METADATA(IID QEglFSDeviceIntegrationFactoryInterface_iid FILE "eglfs_viv_wl.json")
public:
- QEGLDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSVivWaylandIntegration; }
+ QEglFSDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSVivWaylandIntegration; }
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/eglfs_x11.pro b/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/eglfs_x11.pro
index 1948d73750..391f63615b 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/eglfs_x11.pro
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/eglfs_x11.pro
@@ -1,14 +1,14 @@
TARGET = qeglfs-x11-integration
-QT += core-private gui-private platformsupport-private eglfs_device_lib-private
+QT += core-private gui-private eglfsdeviceintegration-private
# Avoid X11 header collision, use generic EGL native types
DEFINES += QT_EGL_NO_X11
-INCLUDEPATH += $$PWD/../..
+INCLUDEPATH += $$PWD/../../api
CONFIG += egl
-LIBS += -lX11 -lX11-xcb -lxcb
+QMAKE_USE += xcb_xlib
QMAKE_LFLAGS += $$QMAKE_LFLAGS_NOUNDEF
SOURCES += $$PWD/qeglfsx11main.cpp \
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11integration.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11integration.h
index a3d0b01baf..c0f0ee5f22 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11integration.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11integration.h
@@ -40,7 +40,7 @@
#ifndef QEGLFSX11INTEGRATION_H
#define QEGLFSX11INTEGRATION_H
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qplatformwindow.h>
@@ -64,7 +64,7 @@ namespace Atoms {
class EventReader;
-class QEglFSX11Integration : public QEGLDeviceIntegration
+class QEglFSX11Integration : public QEglFSDeviceIntegration
{
public:
QEglFSX11Integration() : m_connection(0), m_window(0), m_eventReader(0) {}
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11main.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11main.cpp
index 314a85694b..c15e05b657 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11main.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_x11/qeglfsx11main.cpp
@@ -37,18 +37,18 @@
**
****************************************************************************/
-#include "qeglfsdeviceintegration.h"
+#include "private/qeglfsdeviceintegration_p.h"
#include "qeglfsx11integration.h"
QT_BEGIN_NAMESPACE
-class QEglFSX11IntegrationPlugin : public QEGLDeviceIntegrationPlugin
+class QEglFSX11IntegrationPlugin : public QEglFSDeviceIntegrationPlugin
{
Q_OBJECT
- Q_PLUGIN_METADATA(IID QEGLDeviceIntegrationFactoryInterface_iid FILE "eglfs_x11.json")
+ Q_PLUGIN_METADATA(IID QEglFSDeviceIntegrationFactoryInterface_iid FILE "eglfs_x11.json")
public:
- QEGLDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSX11Integration; }
+ QEglFSDeviceIntegration *create() Q_DECL_OVERRIDE { return new QEglFSX11Integration; }
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/eglfs/eglfs-plugin.pro b/src/plugins/platforms/eglfs/eglfs-plugin.pro
index a628cdccd9..cf4863975a 100644
--- a/src/plugins/platforms/eglfs/eglfs-plugin.pro
+++ b/src/plugins/platforms/eglfs/eglfs-plugin.pro
@@ -1,11 +1,13 @@
TARGET = qeglfs
-QT += platformsupport-private eglfs_device_lib-private
+QT += eglfsdeviceintegration-private
SOURCES += $$PWD/qeglfsmain.cpp
OTHER_FILES += $$PWD/eglfs.json
+INCLUDEPATH += $$PWD/api
+
PLUGIN_TYPE = platforms
PLUGIN_CLASS_NAME = QEglFSIntegrationPlugin
!equals(TARGET, $$QT_DEFAULT_QPA_PLUGIN): PLUGIN_EXTENDS = -
diff --git a/src/plugins/platforms/eglfs/eglfs.pro b/src/plugins/platforms/eglfs/eglfs.pro
index 03c96ca1d9..d91ffd60a1 100644
--- a/src/plugins/platforms/eglfs/eglfs.pro
+++ b/src/plugins/platforms/eglfs/eglfs.pro
@@ -1,6 +1,6 @@
TEMPLATE = subdirs
CONFIG += ordered
-SUBDIRS += eglfs_device_lib.pro
+SUBDIRS += eglfsdeviceintegration.pro
SUBDIRS += eglfs-plugin.pro
SUBDIRS += deviceintegration
diff --git a/src/plugins/platforms/eglfs/eglfs_device_lib.pro b/src/plugins/platforms/eglfs/eglfs_device_lib.pro
deleted file mode 100644
index 974b85b1dd..0000000000
--- a/src/plugins/platforms/eglfs/eglfs_device_lib.pro
+++ /dev/null
@@ -1,54 +0,0 @@
-# The device integration plugin base class has to live in a shared library,
-# placing it into a static lib like platformsupport is not sufficient since we
-# have to keep the QObject magic like qobject_cast working.
-# Hence this header-less, private-only module.
-
-TARGET = QtEglDeviceIntegration
-CONFIG += no_module_headers internal_module
-
-QT += core-private gui-private platformsupport-private
-LIBS += $$QMAKE_LIBS_DYNLOAD
-
-# Avoid X11 header collision, use generic EGL native types
-DEFINES += QT_EGL_NO_X11
-
-DEFINES += QT_BUILD_EGL_DEVICE_LIB
-
-SOURCES += $$PWD/qeglfsintegration.cpp \
- $$PWD/qeglfswindow.cpp \
- $$PWD/qeglfsscreen.cpp \
- $$PWD/qeglfscursor.cpp \
- $$PWD/qeglfshooks.cpp \
- $$PWD/qeglfscontext.cpp \
- $$PWD/qeglfsoffscreenwindow.cpp \
- $$PWD/qeglfsdeviceintegration.cpp
-
-HEADERS += $$PWD/qeglfsintegration.h \
- $$PWD/qeglfswindow.h \
- $$PWD/qeglfsscreen.h \
- $$PWD/qeglfscursor.h \
- $$PWD/qeglfshooks.h \
- $$PWD/qeglfscontext.h \
- $$PWD/qeglfsoffscreenwindow.h \
- $$PWD/qeglfsdeviceintegration.h
-
-QMAKE_LFLAGS += $$QMAKE_LFLAGS_NOUNDEF
-
-INCLUDEPATH += $$PWD
-
-!isEmpty(EGLFS_PLATFORM_HOOKS_SOURCES) {
- HEADERS += $$EGLFS_PLATFORM_HOOKS_HEADERS
- SOURCES += $$EGLFS_PLATFORM_HOOKS_SOURCES
- LIBS += $$EGLFS_PLATFORM_HOOKS_LIBS
- DEFINES += EGLFS_PLATFORM_HOOKS
-}
-
-!isEmpty(EGLFS_DEVICE_INTEGRATION) {
- DEFINES += EGLFS_PREFERRED_PLUGIN=$$EGLFS_DEVICE_INTEGRATION
-}
-
-CONFIG += egl qpa/genericunixfontdatabase
-
-!contains(DEFINES, QT_NO_CURSOR): RESOURCES += $$PWD/cursor.qrc
-
-load(qt_module)
diff --git a/src/plugins/platforms/eglfs/eglfsdeviceintegration.pro b/src/plugins/platforms/eglfs/eglfsdeviceintegration.pro
new file mode 100644
index 0000000000..35af3615bd
--- /dev/null
+++ b/src/plugins/platforms/eglfs/eglfsdeviceintegration.pro
@@ -0,0 +1,50 @@
+# The device integration plugin base class has to live in a shared library,
+# placing it into a static lib like platformsupport is not sufficient since we
+# have to keep the QObject magic like qobject_cast working.
+# Hence this private-only module.
+# By having _p headers, it also enables developing out-of-tree integration plugins.
+
+TARGET = QtEglFSDeviceIntegration
+CONFIG += internal_module
+MODULE = eglfsdeviceintegration
+
+QT += \
+ core-private gui-private \
+ devicediscovery_support-private eventdispatcher_support-private \
+ service_support-private theme_support-private fontdatabase_support-private \
+ fb_support-private egl_support-private platformcompositor_support-private
+
+qtHaveModule(input_support-private): \
+ QT += input_support-private
+
+LIBS += $$QMAKE_LIBS_DYNLOAD
+
+# Avoid X11 header collision, use generic EGL native types
+DEFINES += QT_EGL_NO_X11
+
+DEFINES += QT_BUILD_EGL_DEVICE_LIB
+
+include($$PWD/api/api.pri)
+
+QMAKE_LFLAGS += $$QMAKE_LFLAGS_NOUNDEF
+
+!isEmpty(EGLFS_PLATFORM_HOOKS_SOURCES) {
+ HEADERS += $$EGLFS_PLATFORM_HOOKS_HEADERS
+ SOURCES += $$EGLFS_PLATFORM_HOOKS_SOURCES
+ LIBS += $$EGLFS_PLATFORM_HOOKS_LIBS
+ DEFINES += EGLFS_PLATFORM_HOOKS
+}
+
+!isEmpty(EGLFS_DEVICE_INTEGRATION) {
+ DEFINES += EGLFS_PREFERRED_PLUGIN=$$EGLFS_DEVICE_INTEGRATION
+}
+
+CONFIG += egl
+
+# Prevent gold linker from crashing.
+# This started happening when QtPlatformSupport was modularized.
+use_gold_linker: CONFIG += no_linker_version_script
+
+!contains(DEFINES, QT_NO_CURSOR): RESOURCES += $$PWD/cursor.qrc
+
+load(qt_module)
diff --git a/src/plugins/platforms/eglfs/qeglfsmain.cpp b/src/plugins/platforms/eglfs/qeglfsmain.cpp
index 50279ad110..2885d397c6 100644
--- a/src/plugins/platforms/eglfs/qeglfsmain.cpp
+++ b/src/plugins/platforms/eglfs/qeglfsmain.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include <qpa/qplatformintegrationplugin.h>
-#include "qeglfsintegration.h"
+#include "qeglfsintegration_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/haiku/haiku.pro b/src/plugins/platforms/haiku/haiku.pro
index ea5bb632db..fd1f47b963 100644
--- a/src/plugins/platforms/haiku/haiku.pro
+++ b/src/plugins/platforms/haiku/haiku.pro
@@ -1,6 +1,6 @@
TARGET = qhaiku
-QT += platformsupport-private core-private gui-private
+QT += core-private gui-private eventdistpatcher_support-private
SOURCES = \
main.cpp \
@@ -36,8 +36,6 @@ LIBS += -lbe
OTHER_FILES += haiku.json
-include (../../../platformsupport/fontdatabases/fontdatabases.pri)
-
PLUGIN_TYPE = platforms
PLUGIN_CLASS_NAME = QHaikuIntegrationPlugin
load(qt_plugin)
diff --git a/src/plugins/platforms/haiku/qhaikuclipboard.cpp b/src/plugins/platforms/haiku/qhaikuclipboard.cpp
index 0194a0415a..774da4432a 100644
--- a/src/plugins/platforms/haiku/qhaikuclipboard.cpp
+++ b/src/plugins/platforms/haiku/qhaikuclipboard.cpp
@@ -91,7 +91,7 @@ QMimeData *QHaikuClipboard::mimeData(QClipboard::Mode mode)
const status_t status = clipboard->FindData(name, B_MIME_TYPE, &data, &dataLen);
if (dataLen && (status == B_OK)) {
- const QString format = QString::fromLatin1(name);
+ const QLatin1String format(name);
if (format == QLatin1String("text/plain")) {
m_systemMimeData->setText(QString::fromLocal8Bit(reinterpret_cast<const char*>(data), dataLen));
} else if (format == QLatin1String("text/html")) {
diff --git a/src/plugins/platforms/haiku/qhaikuintegration.cpp b/src/plugins/platforms/haiku/qhaikuintegration.cpp
index d239380866..d46d77ff18 100644
--- a/src/plugins/platforms/haiku/qhaikuintegration.cpp
+++ b/src/plugins/platforms/haiku/qhaikuintegration.cpp
@@ -49,7 +49,7 @@
#include <QCoreApplication>
#include <QFileInfo>
#include <qpa/qplatformwindow.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
#include <Application.h>
diff --git a/src/plugins/platforms/integrity/integrity.pro b/src/plugins/platforms/integrity/integrity.pro
index 07dbf4093d..0fb256793d 100644
--- a/src/plugins/platforms/integrity/integrity.pro
+++ b/src/plugins/platforms/integrity/integrity.pro
@@ -1,6 +1,9 @@
TARGET = integrityfb
-QT += core-private gui-private platformsupport-private
+QT += \
+ core-private gui-private \
+ eventdispatcher_support-private service_support-private \
+ fontdatabase_support-private fb_support-private
SOURCES = \
main.cpp \
@@ -13,8 +16,6 @@ HEADERS = \
qintegrityfbscreen.h \
qintegrityhidmanager.h
-CONFIG += qpa/genericunixfontdatabase
-
OTHER_FILES += integrity.json
PLUGIN_TYPE = platforms
diff --git a/src/plugins/platforms/integrity/qintegrityfbintegration.cpp b/src/plugins/platforms/integrity/qintegrityfbintegration.cpp
index 5332718c5e..a88c85e30d 100644
--- a/src/plugins/platforms/integrity/qintegrityfbintegration.cpp
+++ b/src/plugins/platforms/integrity/qintegrityfbintegration.cpp
@@ -35,13 +35,13 @@
#include "qintegrityfbscreen.h"
#include "qintegrityhidmanager.h"
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qgenericunixservices_p.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtServiceSupport/private/qgenericunixservices_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
-#include <QtPlatformSupport/private/qfbbackingstore_p.h>
-#include <QtPlatformSupport/private/qfbwindow_p.h>
-#include <QtPlatformSupport/private/qfbcursor_p.h>
+#include <QtFbSupport/private/qfbbackingstore_p.h>
+#include <QtFbSupport/private/qfbwindow_p.h>
+#include <QtFbSupport/private/qfbcursor_p.h>
#include <QtGui/private/qguiapplication_p.h>
#include <qpa/qplatforminputcontextfactory_p.h>
diff --git a/src/plugins/platforms/integrity/qintegrityfbscreen.cpp b/src/plugins/platforms/integrity/qintegrityfbscreen.cpp
index e043da7786..256cc117a2 100644
--- a/src/plugins/platforms/integrity/qintegrityfbscreen.cpp
+++ b/src/plugins/platforms/integrity/qintegrityfbscreen.cpp
@@ -32,8 +32,8 @@
****************************************************************************/
#include "qintegrityfbscreen.h"
-#include <QtPlatformSupport/private/qfbcursor_p.h>
-#include <QtPlatformSupport/private/qfbwindow_p.h>
+#include <QtFbSupport/private/qfbcursor_p.h>
+#include <QtFbSupport/private/qfbwindow_p.h>
#include <QtCore/QRegularExpression>
#include <QtGui/QPainter>
diff --git a/src/plugins/platforms/integrity/qintegrityfbscreen.h b/src/plugins/platforms/integrity/qintegrityfbscreen.h
index 2a83f3426f..5b4d900a4b 100644
--- a/src/plugins/platforms/integrity/qintegrityfbscreen.h
+++ b/src/plugins/platforms/integrity/qintegrityfbscreen.h
@@ -34,7 +34,7 @@
#ifndef QINTEGRITYFBSCREEN_H
#define QINTEGRITYFBSCREEN_H
-#include <QtPlatformSupport/private/qfbscreen_p.h>
+#include <QtFbSupport/private/qfbscreen_p.h>
#include <device/fbdriver.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/ios/kernel.pro b/src/plugins/platforms/ios/kernel.pro
index 955f8d9642..caafe89730 100644
--- a/src/plugins/platforms/ios/kernel.pro
+++ b/src/plugins/platforms/ios/kernel.pro
@@ -1,6 +1,9 @@
TARGET = qios
-QT += core-private gui-private platformsupport-private
+QT += \
+ core-private gui-private \
+ clipboard_support-private fontdatabase_support-private graphics_support-private
+
LIBS += -framework Foundation -framework UIKit -framework QuartzCore -framework AudioToolbox
OBJECTIVE_SOURCES = \
@@ -19,14 +22,9 @@ OBJECTIVE_SOURCES = \
qiosglobal.mm \
qiosservices.mm \
quiview.mm \
- qiosclipboard.mm \
quiaccessibilityelement.mm \
qiosplatformaccessibility.mm \
- qiostextresponder.mm \
- qiosmenu.mm \
- qiosfiledialog.mm \
- qiosmessagedialog.mm \
- qiostextinputoverlay.mm
+ qiostextresponder.mm
HEADERS = \
qiosintegration.h \
@@ -43,15 +41,25 @@ HEADERS = \
qiosglobal.h \
qiosservices.h \
quiview.h \
- qiosclipboard.h \
quiaccessibilityelement.h \
qiosplatformaccessibility.h \
- qiostextresponder.h \
- qiosmenu.h \
- qiosfiledialog.h \
- qiosmessagedialog.h \
- qiostextinputoverlay.h
+ qiostextresponder.h
+!tvos {
+ LIBS += -framework AssetsLibrary
+ OBJECTIVE_SOURCES += \
+ qiosclipboard.mm \
+ qiosmenu.mm \
+ qiosfiledialog.mm \
+ qiosmessagedialog.mm \
+ qiostextinputoverlay.mm
+ HEADERS += \
+ qiosclipboard.h \
+ qiosmenu.h \
+ qiosfiledialog.h \
+ qiosmessagedialog.h \
+ qiostextinputoverlay.h
+}
OTHER_FILES = \
quiview_textinput.mm \
diff --git a/src/plugins/platforms/ios/optional/nsphotolibrarysupport/qiosfileenginefactory.h b/src/plugins/platforms/ios/optional/nsphotolibrarysupport/qiosfileenginefactory.h
index 0397b20dfa..b143357aa5 100644
--- a/src/plugins/platforms/ios/optional/nsphotolibrarysupport/qiosfileenginefactory.h
+++ b/src/plugins/platforms/ios/optional/nsphotolibrarysupport/qiosfileenginefactory.h
@@ -53,8 +53,12 @@ public:
{
static QLatin1String assetsScheme("assets-library:");
+#ifndef Q_OS_TVOS
if (fileName.toLower().startsWith(assetsScheme))
return new QIOSFileEngineAssetsLibrary(fileName);
+#else
+ Q_UNUSED(fileName);
+#endif
return 0;
}
diff --git a/src/plugins/platforms/ios/optional/optional.pro b/src/plugins/platforms/ios/optional/optional.pro
index 5e3421a025..6b4ae1ef5e 100644
--- a/src/plugins/platforms/ios/optional/optional.pro
+++ b/src/plugins/platforms/ios/optional/optional.pro
@@ -1,2 +1,2 @@
TEMPLATE = subdirs
-SUBDIRS = nsphotolibrarysupport
+ios: SUBDIRS = nsphotolibrarysupport
diff --git a/src/plugins/platforms/ios/plugin.mm b/src/plugins/platforms/ios/plugin.mm
index b854dfdaa0..83760f2f39 100644
--- a/src/plugins/platforms/ios/plugin.mm
+++ b/src/plugins/platforms/ios/plugin.mm
@@ -54,8 +54,10 @@ class QIOSIntegrationPlugin : public QPlatformIntegrationPlugin
QPlatformIntegration * QIOSIntegrationPlugin::create(const QString& system, const QStringList& paramList)
{
Q_UNUSED(paramList);
- if (!system.compare(QLatin1String("ios"), Qt::CaseInsensitive))
+ if (!system.compare(QLatin1String("ios"), Qt::CaseInsensitive)
+ || !system.compare(QLatin1String("tvos"), Qt::CaseInsensitive)) {
return new QIOSIntegration;
+ }
return 0;
}
diff --git a/src/plugins/platforms/ios/qiosbackingstore.h b/src/plugins/platforms/ios/qiosbackingstore.h
index 5c37be5d38..1c072c0935 100644
--- a/src/plugins/platforms/ios/qiosbackingstore.h
+++ b/src/plugins/platforms/ios/qiosbackingstore.h
@@ -42,7 +42,7 @@
#include <qpa/qplatformbackingstore.h>
-#include <QtPlatformSupport/private/qrasterbackingstore_p.h>
+#include <QtGraphicsSupport/private/qrasterbackingstore_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/ios/qiosbackingstore.mm b/src/plugins/platforms/ios/qiosbackingstore.mm
index fb0c9805f9..076e34c1a5 100644
--- a/src/plugins/platforms/ios/qiosbackingstore.mm
+++ b/src/plugins/platforms/ios/qiosbackingstore.mm
@@ -49,6 +49,8 @@
#include <QtDebug>
+QT_BEGIN_NAMESPACE
+
class QIOSPaintDevice : public QOpenGLPaintDevice
{
public:
@@ -64,6 +66,33 @@ void QIOSPaintDevice::ensureActiveTarget()
m_backingStore->makeCurrent();
}
+/*!
+ \class QIOSBackingStore
+
+ \brief The QPlatformBackingStore on iOS.
+
+ QBackingStore enables the use of QPainter to paint on a QWindow, as opposed
+ to rendering to a QWindow through the use of OpenGL with QOpenGLContext.
+
+ Historically, the iOS port initially implemented the backing store by using
+ an QOpenGLPaintDevice as its paint device, triggering the use of the OpenGL
+ paint engine for QPainter based drawing. This was due to raster drawing
+ operations being too slow when not being NEON-optimized, and got the port
+ up and running quickly.
+
+ As of 3e892e4a97, released in Qt 5.7, the backing store now uses a QImage,
+ for its paint device, giving normal raster-based QPainter operations, and
+ enabling features such as antialiased drawing.
+
+ To account for regressions in performance, the old code path is still
+ available by setting the surface type of the QWindow to OpenGLSurface.
+ This surface type is normally used when rendering though QOpenGLContext,
+ but will in the case of QIOSBackingStore trigger the old OpenGL based
+ painter.
+
+ This fallback path is not too intrusive, as the QImage based path still
+ uses OpenGL to composite the image at flush() time using composeAndFlush.
+*/
QIOSBackingStore::QIOSBackingStore(QWindow *window)
: QRasterBackingStore(window)
, m_context(new QOpenGLContext)
diff --git a/src/plugins/platforms/ios/qiosclipboard.h b/src/plugins/platforms/ios/qiosclipboard.h
index b9ba4a2669..f3ccfcace0 100644
--- a/src/plugins/platforms/ios/qiosclipboard.h
+++ b/src/plugins/platforms/ios/qiosclipboard.h
@@ -40,10 +40,13 @@
#ifndef QIOSCLIPBOARD_H
#define QIOSCLIPBOARD_H
+#include <qpa/qplatformclipboard.h>
+
+#ifndef QT_NO_CLIPBOARD
+
#import <UIKit/UIKit.h>
#include <QMimeData>
-#include <qpa/qplatformclipboard.h>
@class QUIClipboard;
@@ -67,4 +70,6 @@ private:
QT_END_NAMESPACE
+#endif // QT_NO_CLIPBOARD
+
#endif // QIOSCLIPBOARD_H
diff --git a/src/plugins/platforms/ios/qiosclipboard.mm b/src/plugins/platforms/ios/qiosclipboard.mm
index fb75cc793c..ef3b453bbf 100644
--- a/src/plugins/platforms/ios/qiosclipboard.mm
+++ b/src/plugins/platforms/ios/qiosclipboard.mm
@@ -39,7 +39,9 @@
#include "qiosclipboard.h"
-#include <QtPlatformSupport/private/qmacmime_p.h>
+#ifndef QT_NO_CLIPBOARD
+
+#include <QtClipboardSupport/private/qmacmime_p.h>
#include <QtCore/QMimeData>
#include <QtGui/QGuiApplication>
@@ -247,3 +249,5 @@ bool QIOSClipboard::ownsMode(QClipboard::Mode mode) const
}
QT_END_NAMESPACE
+
+#endif // QT_NO_CLIPBOARD
diff --git a/src/plugins/platforms/ios/qioscontext.mm b/src/plugins/platforms/ios/qioscontext.mm
index 50374dc951..2d5286e971 100644
--- a/src/plugins/platforms/ios/qioscontext.mm
+++ b/src/plugins/platforms/ios/qioscontext.mm
@@ -48,6 +48,8 @@
#import <OpenGLES/ES2/glext.h>
#import <QuartzCore/CAEAGLLayer.h>
+QT_BEGIN_NAMESPACE
+
Q_LOGGING_CATEGORY(lcQpaGLContext, "qt.qpa.glcontext");
QIOSContext::QIOSContext(QOpenGLContext *context)
@@ -314,3 +316,4 @@ bool QIOSContext::isSharing() const
#include "moc_qioscontext.cpp"
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/ios/qioseventdispatcher.mm b/src/plugins/platforms/ios/qioseventdispatcher.mm
index 8d82364cc0..f49f81912e 100644
--- a/src/plugins/platforms/ios/qioseventdispatcher.mm
+++ b/src/plugins/platforms/ios/qioseventdispatcher.mm
@@ -493,7 +493,7 @@ void QIOSEventDispatcher::handleRunLoopExit(CFRunLoopActivity activity)
Q_UNUSED(activity);
Q_ASSERT(activity == kCFRunLoopExit);
- if (m_processEventLevel == 1 && !QThreadData::current()->eventLoops.top()->isRunning()) {
+ if (m_processEventLevel == 1 && !currentEventLoop()->isRunning()) {
qEventDispatcherDebug() << "Root runloop level exited";
interruptEventLoopExec();
}
diff --git a/src/plugins/platforms/ios/qiosfiledialog.h b/src/plugins/platforms/ios/qiosfiledialog.h
index 937b56e2f6..0b56bd20bf 100644
--- a/src/plugins/platforms/ios/qiosfiledialog.h
+++ b/src/plugins/platforms/ios/qiosfiledialog.h
@@ -43,10 +43,10 @@
#include <QtCore/qeventloop.h>
#include <qpa/qplatformdialoghelper.h>
-QT_BEGIN_NAMESPACE
-
Q_FORWARD_DECLARE_OBJC_CLASS(UIViewController);
+QT_BEGIN_NAMESPACE
+
class QIOSFileDialog : public QPlatformFileDialogHelper
{
public:
diff --git a/src/plugins/platforms/ios/qiosglobal.h b/src/plugins/platforms/ios/qiosglobal.h
index 0fe81ceb91..f74e3004cc 100644
--- a/src/plugins/platforms/ios/qiosglobal.h
+++ b/src/plugins/platforms/ios/qiosglobal.h
@@ -61,13 +61,10 @@ class QPlatformScreen;
bool isQtApplication();
-CGRect toCGRect(const QRectF &rect);
-QRectF fromCGRect(const CGRect &rect);
-CGPoint toCGPoint(const QPointF &point);
-QPointF fromCGPoint(const CGPoint &point);
-
+#ifndef Q_OS_TVOS
Qt::ScreenOrientation toQtScreenOrientation(UIDeviceOrientation uiDeviceOrientation);
UIDeviceOrientation fromQtScreenOrientation(Qt::ScreenOrientation qtOrientation);
+#endif
int infoPlistValue(NSString* key, int defaultValue);
@@ -77,6 +74,8 @@ QT_END_NAMESPACE
+ (id)currentFirstResponder;
@end
+QT_BEGIN_NAMESPACE
+
class FirstResponderCandidate : public QScopedValueRollback<UIResponder *>
{
public:
@@ -87,4 +86,6 @@ private:
static UIResponder *s_firstResponderCandidate;
};
+QT_END_NAMESPACE
+
#endif // QIOSGLOBAL_H
diff --git a/src/plugins/platforms/ios/qiosglobal.mm b/src/plugins/platforms/ios/qiosglobal.mm
index c2f3d6b9e1..1482ffc7af 100644
--- a/src/plugins/platforms/ios/qiosglobal.mm
+++ b/src/plugins/platforms/ios/qiosglobal.mm
@@ -58,26 +58,7 @@ bool isQtApplication()
return isQt;
}
-CGRect toCGRect(const QRectF &rect)
-{
- return CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
-}
-
-QRectF fromCGRect(const CGRect &rect)
-{
- return QRectF(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
-}
-
-CGPoint toCGPoint(const QPointF &point)
-{
- return CGPointMake(point.x(), point.y());
-}
-
-QPointF fromCGPoint(const CGPoint &point)
-{
- return QPointF(point.x, point.y);
-}
-
+#ifndef Q_OS_TVOS
Qt::ScreenOrientation toQtScreenOrientation(UIDeviceOrientation uiDeviceOrientation)
{
Qt::ScreenOrientation qtOrientation;
@@ -124,6 +105,7 @@ UIDeviceOrientation fromQtScreenOrientation(Qt::ScreenOrientation qtOrientation)
}
return uiOrientation;
}
+#endif
int infoPlistValue(NSString* key, int defaultValue)
{
@@ -132,6 +114,8 @@ int infoPlistValue(NSString* key, int defaultValue)
return value ? [value intValue] : defaultValue;
}
+QT_END_NAMESPACE
+
// -------------------------------------------------------------------------
@interface QtFirstResponderEvent : UIEvent
@@ -182,6 +166,8 @@ int infoPlistValue(NSString* key, int defaultValue)
}
@end
+QT_BEGIN_NAMESPACE
+
FirstResponderCandidate::FirstResponderCandidate(UIResponder *responder)
: QScopedValueRollback<UIResponder *>(s_firstResponderCandidate, responder)
{
diff --git a/src/plugins/platforms/ios/qiosinputcontext.h b/src/plugins/platforms/ios/qiosinputcontext.h
index ffb21d6afe..966d1a7e80 100644
--- a/src/plugins/platforms/ios/qiosinputcontext.h
+++ b/src/plugins/platforms/ios/qiosinputcontext.h
@@ -52,13 +52,13 @@ const char kImePlatformDataInputAccessoryView[] = "inputAccessoryView";
const char kImePlatformDataHideShortcutsBar[] = "hideShortcutsBar";
const char kImePlatformDataReturnKeyType[] = "returnKeyType";
-QT_BEGIN_NAMESPACE
-
@class QIOSLocaleListener;
@class QIOSKeyboardListener;
@class QIOSTextInputResponder;
@protocol KeyboardState;
+QT_BEGIN_NAMESPACE
+
struct KeyboardState
{
KeyboardState() :
diff --git a/src/plugins/platforms/ios/qiosinputcontext.mm b/src/plugins/platforms/ios/qiosinputcontext.mm
index ef93d68cf0..68088540c6 100644
--- a/src/plugins/platforms/ios/qiosinputcontext.mm
+++ b/src/plugins/platforms/ios/qiosinputcontext.mm
@@ -97,14 +97,14 @@ static QUIView *focusView()
@interface QIOSKeyboardListener : UIGestureRecognizer <UIGestureRecognizerDelegate> {
@private
- QIOSInputContext *m_context;
+ QT_PREPEND_NAMESPACE(QIOSInputContext) *m_context;
}
@property BOOL hasDeferredScrollToCursor;
@end
@implementation QIOSKeyboardListener
-- (id)initWithQIOSInputContext:(QIOSInputContext *)context
+- (id)initWithQIOSInputContext:(QT_PREPEND_NAMESPACE(QIOSInputContext) *)context
{
if (self = [super initWithTarget:self action:@selector(gestureStateChanged:)]) {
@@ -117,6 +117,7 @@ static QUIView *focusView()
self.cancelsTouchesInView = NO;
self.delaysTouchesEnded = NO;
+#ifndef Q_OS_TVOS
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
@@ -134,6 +135,7 @@ static QUIView *focusView()
[notificationCenter addObserver:self
selector:@selector(keyboardDidChangeFrame:)
name:UIKeyboardDidChangeFrameNotification object:nil];
+#endif
}
return self;
@@ -289,6 +291,8 @@ static QUIView *focusView()
// -------------------------------------------------------------------------
+QT_BEGIN_NAMESPACE
+
Qt::InputMethodQueries ImeState::update(Qt::InputMethodQueries properties)
{
if (!properties)
@@ -377,6 +381,9 @@ void QIOSInputContext::clearCurrentFocusObject()
void QIOSInputContext::updateKeyboardState(NSNotification *notification)
{
+#ifdef Q_OS_TVOS
+ Q_UNUSED(notification);
+#else
static CGRect currentKeyboardRect = CGRectZero;
KeyboardState previousState = m_keyboardState;
@@ -412,7 +419,7 @@ void QIOSInputContext::updateKeyboardState(NSNotification *notification)
m_keyboardState.animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
m_keyboardState.keyboardAnimating = m_keyboardState.animationDuration > 0 && !atEndOfKeyboardTransition;
- qImDebug() << qPrintable(QString::fromNSString(notification.name)) << "from" << fromCGRect(frameBegin) << "to" << fromCGRect(frameEnd)
+ qImDebug() << qPrintable(QString::fromNSString(notification.name)) << "from" << QRectF::fromCGRect(frameBegin) << "to" << QRectF::fromCGRect(frameEnd)
<< "(curve =" << m_keyboardState.animationCurve << "duration =" << m_keyboardState.animationDuration << "s)";
} else {
qImDebug("No notification to update keyboard state based on, just updating keyboard rect");
@@ -421,7 +428,7 @@ void QIOSInputContext::updateKeyboardState(NSNotification *notification)
if (!focusView() || CGRectIsEmpty(currentKeyboardRect))
m_keyboardState.keyboardRect = QRectF();
else // QInputmethod::keyboardRectangle() is documented to be in window coordinates.
- m_keyboardState.keyboardRect = fromCGRect([focusView() convertRect:currentKeyboardRect fromView:nil]);
+ m_keyboardState.keyboardRect = QRectF::fromCGRect([focusView() convertRect:currentKeyboardRect fromView:nil]);
// Emit for all changed properties
if (m_keyboardState.keyboardVisible != previousState.keyboardVisible)
@@ -430,6 +437,7 @@ void QIOSInputContext::updateKeyboardState(NSNotification *notification)
emitAnimatingChanged();
if (m_keyboardState.keyboardRect != previousState.keyboardRect)
emitKeyboardRectChanged();
+#endif
}
bool QIOSInputContext::isInputPanelVisible() const
@@ -549,7 +557,11 @@ void QIOSInputContext::scroll(int y)
if (keyboardScrollIsActive && !originalWindowLevels.contains(window))
originalWindowLevels.insert(window, window.windowLevel);
+#ifndef Q_OS_TVOS
UIWindowLevel windowLevelAdjustment = keyboardScrollIsActive ? UIWindowLevelStatusBar : 0;
+#else
+ UIWindowLevel windowLevelAdjustment = 0;
+#endif
window.windowLevel = originalWindowLevels.value(window) + windowLevelAdjustment;
if (!keyboardScrollIsActive)
@@ -703,3 +715,5 @@ QLocale QIOSInputContext::locale() const
{
return QLocale(QString::fromNSString([[NSLocale currentLocale] objectForKey:NSLocaleIdentifier]));
}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/ios/qiosintegration.h b/src/plugins/platforms/ios/qiosintegration.h
index 35f12bcb56..54c1a1dcb7 100644
--- a/src/plugins/platforms/ios/qiosintegration.h
+++ b/src/plugins/platforms/ios/qiosintegration.h
@@ -47,7 +47,9 @@
#include <QtCore/private/qfactoryloader_p.h>
#include "qiosapplicationstate.h"
+#ifndef Q_OS_TVOS
#include "qiostextinputoverlay.h"
+#endif
QT_BEGIN_NAMESPACE
@@ -71,7 +73,9 @@ public:
QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const Q_DECL_OVERRIDE;
QPlatformFontDatabase *fontDatabase() const Q_DECL_OVERRIDE;
+#ifndef QT_NO_CLIPBOARD
QPlatformClipboard *clipboard() const Q_DECL_OVERRIDE;
+#endif
QPlatformInputContext *inputContext() const Q_DECL_OVERRIDE;
QPlatformServices *services() const Q_DECL_OVERRIDE;
@@ -84,7 +88,9 @@ public:
QPlatformNativeInterface *nativeInterface() const Q_DECL_OVERRIDE;
QTouchDevice *touchDevice();
+#ifndef QT_NO_ACCESSIBILITY
QPlatformAccessibility *accessibility() const Q_DECL_OVERRIDE;
+#endif
// Called from Objective-C class QIOSScreenTracker, which can't be friended
void addScreen(QPlatformScreen *screen) { screenAdded(screen); }
@@ -105,14 +111,18 @@ public:
private:
QPlatformFontDatabase *m_fontDatabase;
+#ifndef Q_OS_TVOS
QPlatformClipboard *m_clipboard;
+#endif
QPlatformInputContext *m_inputContext;
QTouchDevice *m_touchDevice;
QIOSApplicationState m_applicationState;
QIOSServices *m_platformServices;
mutable QPlatformAccessibility *m_accessibility;
QFactoryLoader *m_optionalPlugins;
+#ifndef Q_OS_TVOS
QIOSTextInputOverlay m_textInputOverlay;
+#endif
bool m_debugWindowManagement;
};
@@ -120,4 +130,3 @@ private:
QT_END_NAMESPACE
#endif
-
diff --git a/src/plugins/platforms/ios/qiosintegration.mm b/src/plugins/platforms/ios/qiosintegration.mm
index a9435ef15a..e5b4d6da85 100644
--- a/src/plugins/platforms/ios/qiosintegration.mm
+++ b/src/plugins/platforms/ios/qiosintegration.mm
@@ -45,7 +45,9 @@
#include "qiosscreen.h"
#include "qiosplatformaccessibility.h"
#include "qioscontext.h"
+#ifndef Q_OS_TVOS
#include "qiosclipboard.h"
+#endif
#include "qiosinputcontext.h"
#include "qiostheme.h"
#include "qiosservices.h"
@@ -56,8 +58,8 @@
#include <qoffscreensurface.h>
#include <qpa/qplatformoffscreensurface.h>
-#include <QtPlatformSupport/private/qcoretextfontdatabase_p.h>
-#include <QtPlatformSupport/private/qmacmime_p.h>
+#include <QtFontDatabaseSupport/private/qcoretextfontdatabase_p.h>
+#include <QtClipboardSupport/private/qmacmime_p.h>
#include <QDir>
#import <AudioToolbox/AudioServices.h>
@@ -73,7 +75,9 @@ QIOSIntegration *QIOSIntegration::instance()
QIOSIntegration::QIOSIntegration()
: m_fontDatabase(new QCoreTextFontDatabase)
+#if !defined(Q_OS_TVOS) && !defined(QT_NO_CLIPBOARD)
, m_clipboard(new QIOSClipboard)
+#endif
, m_inputContext(0)
, m_platformServices(new QIOSServices)
, m_accessibility(0)
@@ -132,8 +136,10 @@ QIOSIntegration::~QIOSIntegration()
delete m_fontDatabase;
m_fontDatabase = 0;
+#if !defined(Q_OS_TVOS) && !defined(QT_NO_CLIPBOARD)
delete m_clipboard;
m_clipboard = 0;
+#endif
QMacInternalPasteboardMime::destroyMimeTypes();
delete m_inputContext;
@@ -223,10 +229,16 @@ QPlatformFontDatabase * QIOSIntegration::fontDatabase() const
return m_fontDatabase;
}
+#ifndef QT_NO_CLIPBOARD
QPlatformClipboard *QIOSIntegration::clipboard() const
{
+#ifndef Q_OS_TVOS
return m_clipboard;
+#else
+ return QPlatformIntegration::clipboard();
+#endif
}
+#endif
QPlatformInputContext *QIOSIntegration::inputContext() const
{
@@ -274,12 +286,14 @@ QTouchDevice *QIOSIntegration::touchDevice()
return m_touchDevice;
}
+#ifndef QT_NO_ACCESSIBILITY
QPlatformAccessibility *QIOSIntegration::accessibility() const
{
if (!m_accessibility)
m_accessibility = new QIOSPlatformAccessibility;
return m_accessibility;
}
+#endif
QPlatformNativeInterface *QIOSIntegration::nativeInterface() const
{
diff --git a/src/plugins/platforms/ios/qiosmenu.h b/src/plugins/platforms/ios/qiosmenu.h
index dab5720d48..b7371a5f49 100644
--- a/src/plugins/platforms/ios/qiosmenu.h
+++ b/src/plugins/platforms/ios/qiosmenu.h
@@ -68,7 +68,9 @@ public:
void setRole(MenuRole role) Q_DECL_OVERRIDE;
void setCheckable(bool) Q_DECL_OVERRIDE {}
void setChecked(bool) Q_DECL_OVERRIDE {}
+#ifndef QT_NO_SHORTCUT
void setShortcut(const QKeySequence&) Q_DECL_OVERRIDE;
+#endif
void setEnabled(bool enabled) Q_DECL_OVERRIDE;
void setIconSize(int) Q_DECL_OVERRIDE {}
diff --git a/src/plugins/platforms/ios/qiosmenu.mm b/src/plugins/platforms/ios/qiosmenu.mm
index 24d8559cc8..01cb3badea 100644
--- a/src/plugins/platforms/ios/qiosmenu.mm
+++ b/src/plugins/platforms/ios/qiosmenu.mm
@@ -304,10 +304,12 @@ void QIOSMenuItem::setRole(QPlatformMenuItem::MenuRole role)
m_role = role;
}
+#ifndef QT_NO_SHORTCUT
void QIOSMenuItem::setShortcut(const QKeySequence &sequence)
{
m_shortcut = sequence;
}
+#endif
void QIOSMenuItem::setEnabled(bool enabled)
{
@@ -551,6 +553,7 @@ QIOSMenuItemList QIOSMenu::filterFirstResponderActions(const QIOSMenuItemList &m
for (int i = 0; i < menuItems.count(); ++i) {
QIOSMenuItem *menuItem = menuItems.at(i);
+#ifndef QT_NO_SHORTCUT
QKeySequence shortcut = menuItem->m_shortcut;
if ((shortcut == QKeySequence::Cut && [responder canPerformAction:@selector(cut:) withSender:nil])
|| (shortcut == QKeySequence::Copy && [responder canPerformAction:@selector(copy:) withSender:nil])
@@ -564,6 +567,7 @@ QIOSMenuItemList QIOSMenu::filterFirstResponderActions(const QIOSMenuItemList &m
|| (shortcut == QKeySequence::Underline && [responder canPerformAction:@selector(toggleUnderline:) withSender:nil])) {
continue;
}
+#endif
filteredMenuItems.append(menuItem);
}
return filteredMenuItems;
@@ -574,7 +578,7 @@ void QIOSMenu::repositionMenu()
switch (m_effectiveMenuType) {
case EditMenu: {
UIView *view = reinterpret_cast<UIView *>(m_parentWindow->winId());
- [[UIMenuController sharedMenuController] setTargetRect:toCGRect(m_targetRect) inView:view];
+ [[UIMenuController sharedMenuController] setTargetRect:m_targetRect.toCGRect() inView:view];
[[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
break; }
default:
diff --git a/src/plugins/platforms/ios/qiosmessagedialog.h b/src/plugins/platforms/ios/qiosmessagedialog.h
index 971c8d8b4d..e67e10a5e1 100644
--- a/src/plugins/platforms/ios/qiosmessagedialog.h
+++ b/src/plugins/platforms/ios/qiosmessagedialog.h
@@ -43,11 +43,11 @@
#include <QtCore/qeventloop.h>
#include <qpa/qplatformdialoghelper.h>
-QT_BEGIN_NAMESPACE
-
Q_FORWARD_DECLARE_OBJC_CLASS(UIAlertController);
Q_FORWARD_DECLARE_OBJC_CLASS(UIAlertAction);
+QT_BEGIN_NAMESPACE
+
class QIOSMessageDialog : public QPlatformMessageDialogHelper
{
public:
diff --git a/src/plugins/platforms/ios/qiosplatformaccessibility.h b/src/plugins/platforms/ios/qiosplatformaccessibility.h
index 2374457591..989eaa4fb8 100644
--- a/src/plugins/platforms/ios/qiosplatformaccessibility.h
+++ b/src/plugins/platforms/ios/qiosplatformaccessibility.h
@@ -42,6 +42,8 @@
#include <qpa/qplatformaccessibility.h>
+#ifndef QT_NO_ACCESSIBILITY
+
QT_BEGIN_NAMESPACE
class QIOSPlatformAccessibility: public QPlatformAccessibility
@@ -56,3 +58,5 @@ public:
QT_END_NAMESPACE
#endif
+
+#endif
diff --git a/src/plugins/platforms/ios/qiosplatformaccessibility.mm b/src/plugins/platforms/ios/qiosplatformaccessibility.mm
index 2ebe23c939..aef4216e03 100644
--- a/src/plugins/platforms/ios/qiosplatformaccessibility.mm
+++ b/src/plugins/platforms/ios/qiosplatformaccessibility.mm
@@ -39,6 +39,8 @@
#include "qiosplatformaccessibility.h"
+#ifndef QT_NO_ACCESSIBILITY
+
#include <QtGui/QtGui>
#include "qioswindow.h"
@@ -63,7 +65,7 @@ void invalidateCache(QAccessibleInterface *iface)
// when items get added or removed from the screen
foreach (QWindow *win, QGuiApplication::topLevelWindows()) {
if (win && win->handle()) {
- QIOSWindow *window = static_cast<QIOSWindow*>(win->handle());
+ QT_PREPEND_NAMESPACE(QIOSWindow) *window = static_cast<QT_PREPEND_NAMESPACE(QIOSWindow) *>(win->handle());
window->clearAccessibleCache();
}
}
@@ -85,3 +87,5 @@ void QIOSPlatformAccessibility::notifyAccessibilityUpdate(QAccessibleEvent *even
break;
}
}
+
+#endif
diff --git a/src/plugins/platforms/ios/qiosscreen.h b/src/plugins/platforms/ios/qiosscreen.h
index cc83e7f3d2..9fcce42825 100644
--- a/src/plugins/platforms/ios/qiosscreen.h
+++ b/src/plugins/platforms/ios/qiosscreen.h
@@ -68,6 +68,8 @@ public:
Qt::ScreenOrientation orientation() const Q_DECL_OVERRIDE;
void setOrientationUpdateMask(Qt::ScreenOrientations mask) Q_DECL_OVERRIDE;
+ QPixmap grabWindow(WId window, int x, int y, int width, int height) const override;
+
UIScreen *uiScreen() const;
UIWindow *uiWindow() const;
diff --git a/src/plugins/platforms/ios/qiosscreen.mm b/src/plugins/platforms/ios/qiosscreen.mm
index dc14698146..c518f9111d 100644
--- a/src/plugins/platforms/ios/qiosscreen.mm
+++ b/src/plugins/platforms/ios/qiosscreen.mm
@@ -47,6 +47,7 @@
#include "quiview.h"
#include <QtGui/private/qwindow_p.h>
+#include <private/qcoregraphics_p.h>
#include <sys/sysctl.h>
@@ -143,21 +144,25 @@ static QIOSScreen* qtPlatformScreenFor(UIScreen *uiScreen)
self = [super init];
if (self) {
m_screen = screen;
+#ifndef Q_OS_TVOS
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(orientationChanged:)
name:@"UIDeviceOrientationDidChangeNotification" object:nil];
+#endif
}
return self;
}
- (void)dealloc
{
+#ifndef Q_OS_TVOS
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:@"UIDeviceOrientationDidChangeNotification" object:nil];
+#endif
[super dealloc];
}
@@ -171,6 +176,8 @@ static QIOSScreen* qtPlatformScreenFor(UIScreen *uiScreen)
// -------------------------------------------------------------------------
+QT_BEGIN_NAMESPACE
+
/*!
Returns the model identifier of the device.
@@ -256,9 +263,14 @@ void QIOSScreen::updateProperties()
QRect previousGeometry = m_geometry;
QRect previousAvailableGeometry = m_availableGeometry;
- m_geometry = fromCGRect(m_uiScreen.bounds).toRect();
- m_availableGeometry = fromCGRect(m_uiScreen.applicationFrame).toRect();
+ m_geometry = QRectF::fromCGRect(m_uiScreen.bounds).toRect();
+#ifdef Q_OS_TVOS
+ m_availableGeometry = m_geometry;
+#else
+ m_availableGeometry = QRectF::fromCGRect(m_uiScreen.applicationFrame).toRect();
+#endif
+#ifndef Q_OS_TVOS
if (m_uiScreen == [UIScreen mainScreen]) {
Qt::ScreenOrientation statusBarOrientation = toQtScreenOrientation(UIDeviceOrientation([UIApplication sharedApplication].statusBarOrientation));
@@ -286,6 +298,7 @@ void QIOSScreen::updateProperties()
m_availableGeometry = transform.mapRect(m_availableGeometry);
}
}
+#endif
if (m_geometry != previousGeometry) {
QRectF physicalGeometry;
@@ -298,7 +311,7 @@ void QIOSScreen::updateProperties()
// before being output on the physical display. We have to take this into account when
// computing the physical size. Note that unlike the native bounds, the physical size
// follows the primary orientation of the screen.
- physicalGeometry = mapBetween(nativeOrientation(), primaryOrientation, fromCGRect(m_uiScreen.nativeBounds).toRect());
+ physicalGeometry = mapBetween(nativeOrientation(), primaryOrientation, QRectF::fromCGRect(m_uiScreen.nativeBounds).toRect());
} else {
physicalGeometry = QRectF(0, 0, m_geometry.width() * devicePixelRatio(), m_geometry.height() * devicePixelRatio());
}
@@ -393,7 +406,7 @@ qreal QIOSScreen::devicePixelRatio() const
Qt::ScreenOrientation QIOSScreen::nativeOrientation() const
{
CGRect nativeBounds =
-#if QT_IOS_PLATFORM_SDK_EQUAL_OR_ABOVE(__IPHONE_8_0)
+#if !defined(Q_OS_TVOS) && QT_IOS_PLATFORM_SDK_EQUAL_OR_ABOVE(__IPHONE_8_0)
QSysInfo::MacintoshVersion >= QSysInfo::MV_IOS_8_0 ? m_uiScreen.nativeBounds :
#endif
m_uiScreen.bounds;
@@ -406,6 +419,9 @@ Qt::ScreenOrientation QIOSScreen::nativeOrientation() const
Qt::ScreenOrientation QIOSScreen::orientation() const
{
+#ifdef Q_OS_TVOS
+ return Qt::PrimaryOrientation;
+#else
// Auxiliary screens are always the same orientation as their primary orientation
if (m_uiScreen != [UIScreen mainScreen])
return Qt::PrimaryOrientation;
@@ -430,6 +446,7 @@ Qt::ScreenOrientation QIOSScreen::orientation() const
}
return toQtScreenOrientation(deviceOrientation);
+#endif
}
void QIOSScreen::setOrientationUpdateMask(Qt::ScreenOrientations mask)
@@ -443,6 +460,38 @@ void QIOSScreen::setOrientationUpdateMask(Qt::ScreenOrientations mask)
}
}
+QPixmap QIOSScreen::grabWindow(WId window, int x, int y, int width, int height) const
+{
+ if (window && ![reinterpret_cast<id>(window) isKindOfClass:[UIView class]])
+ return QPixmap();
+
+ UIView *view = window ? reinterpret_cast<UIView *>(window) : m_uiWindow;
+
+ if (width < 0)
+ width = qMax(view.bounds.size.width - x, CGFloat(0));
+ if (height < 0)
+ height = qMax(view.bounds.size.height - y, CGFloat(0));
+
+ CGRect captureRect = [m_uiWindow convertRect:CGRectMake(x, y, width, height) fromView:view];
+ captureRect = CGRectIntersection(captureRect, m_uiWindow.bounds);
+
+ UIGraphicsBeginImageContextWithOptions(captureRect.size, NO, 0.0);
+ CGContextRef context = UIGraphicsGetCurrentContext();
+ CGContextTranslateCTM(context, -captureRect.origin.x, -captureRect.origin.y);
+
+ // Draws the complete view hierarchy of m_uiWindow into the given rect, which
+ // needs to be the same aspect ratio as the m_uiWindow's size. Since we've
+ // translated the graphics context, and are potentially drawing into a smaller
+ // context than the full window, the resulting image will be a subsection of the
+ // full screen.
+ [m_uiWindow drawViewHierarchyInRect:m_uiWindow.bounds afterScreenUpdates:NO];
+
+ UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
+ UIGraphicsEndImageContext();
+
+ return QPixmap::fromImage(qt_mac_toQImage(screenshot.CGImage));
+}
+
UIScreen *QIOSScreen::uiScreen() const
{
return m_uiScreen;
diff --git a/src/plugins/platforms/ios/qiostextinputoverlay.mm b/src/plugins/platforms/ios/qiostextinputoverlay.mm
index 54c2e98d71..238d7addf6 100644
--- a/src/plugins/platforms/ios/qiostextinputoverlay.mm
+++ b/src/plugins/platforms/ios/qiostextinputoverlay.mm
@@ -136,7 +136,7 @@ static void executeBlockWithoutAnimation(Block block)
// first responder, which is normally QIOSTextResponder.
QRectF cr = qApp->inputMethod()->cursorRectangle();
QRectF ar = qApp->inputMethod()->anchorRectangle();
- CGRect targetRect = toCGRect(cr.united(ar));
+ CGRect targetRect = cr.united(ar).toCGRect();
UIView *focusView = reinterpret_cast<UIView *>(qApp->focusWindow()->winId());
[[UIMenuController sharedMenuController] setTargetRect:targetRect inView:focusView];
[[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
@@ -500,12 +500,12 @@ static void executeBlockWithoutAnimation(Block block)
QGuiApplication::styleHints()->setCursorFlashTime(0);
if (!_loupeLayer)
[self createLoupe];
- [self updateFocalPoint:fromCGPoint(_lastTouchPoint)];
+ [self updateFocalPoint:QPointF::fromCGPoint(_lastTouchPoint)];
_loupeLayer.visible = YES;
break;
case UIGestureRecognizerStateChanged:
// Tell the sub class to move the loupe to the correct position
- [self updateFocalPoint:fromCGPoint(_lastTouchPoint)];
+ [self updateFocalPoint:QPointF::fromCGPoint(_lastTouchPoint)];
break;
case UIGestureRecognizerStateEnded:
// Restore cursor blinking, and hide the loupe
@@ -530,12 +530,12 @@ static void executeBlockWithoutAnimation(Block block)
- (QPointF)focalPoint
{
- return fromCGPoint([_loupeLayer.targetView convertPoint:_loupeLayer.focalPoint toView:_focusView]);
+ return QPointF::fromCGPoint([_loupeLayer.targetView convertPoint:_loupeLayer.focalPoint toView:_focusView]);
}
- (void)setFocalPoint:(QPointF)point
{
- _loupeLayer.focalPoint = [_loupeLayer.targetView convertPoint:toCGPoint(point) fromView:_focusView];
+ _loupeLayer.focalPoint = [_loupeLayer.targetView convertPoint:point.toCGPoint() fromView:_focusView];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
@@ -552,7 +552,7 @@ static void executeBlockWithoutAnimation(Block block)
// If the touch point is accepted by the sub class (e.g touch on cursor), we start a
// press'n'hold timer that eventually will move the state to UIGestureRecognizerStateBegan.
- if ([self acceptTouchesBegan:fromCGPoint(_firstTouchPoint)])
+ if ([self acceptTouchesBegan:QPointF::fromCGPoint(_firstTouchPoint)])
_triggerStateBeganTimer.start();
else
self.state = UIGestureRecognizerStateFailed;
@@ -860,8 +860,8 @@ static void executeBlockWithoutAnimation(Block block)
// Adjust handles and input rect to match the new selection
QRectF inputRect = QGuiApplication::inputMethod()->inputItemClipRectangle();
- CGRect cursorRect = toCGRect(QGuiApplication::inputMethod()->cursorRectangle());
- CGRect anchorRect = toCGRect(QGuiApplication::inputMethod()->anchorRectangle());
+ CGRect cursorRect = QGuiApplication::inputMethod()->cursorRectangle().toCGRect();
+ CGRect anchorRect = QGuiApplication::inputMethod()->anchorRectangle().toCGRect();
if (!_multiLine) {
// Resize the layer a bit bigger to ensure that the handles are
@@ -870,7 +870,7 @@ static void executeBlockWithoutAnimation(Block block)
inputRect.adjust(-margin / 2, -margin, margin / 2, margin);
}
- executeBlockWithoutAnimation(^{ _clipRectLayer.frame = toCGRect(inputRect); });
+ executeBlockWithoutAnimation(^{ _clipRectLayer.frame = inputRect.toCGRect(); });
_cursorLayer.cursorRectangle = [self.focusView.layer convertRect:cursorRect toLayer:_clipRectLayer];
_anchorLayer.cursorRectangle = [self.focusView.layer convertRect:anchorRect toLayer:_clipRectLayer];
_cursorLayer.visible = YES;
@@ -938,7 +938,7 @@ static void executeBlockWithoutAnimation(Block block)
}
QRectF inputRect = QGuiApplication::inputMethod()->inputItemClipRectangle();
- QPointF touchPos = fromCGPoint([static_cast<UITouch *>([touches anyObject]) locationInView:_focusView]);
+ QPointF touchPos = QPointF::fromCGPoint([static_cast<UITouch *>([touches anyObject]) locationInView:_focusView]);
if (!inputRect.contains(touchPos))
self.state = UIGestureRecognizerStateFailed;
@@ -947,7 +947,7 @@ static void executeBlockWithoutAnimation(Block block)
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
- QPointF touchPos = fromCGPoint([static_cast<UITouch *>([touches anyObject]) locationInView:_focusView]);
+ QPointF touchPos = QPointF::fromCGPoint([static_cast<UITouch *>([touches anyObject]) locationInView:_focusView]);
const QTransform mapToLocal = QGuiApplication::inputMethod()->inputItemTransform().inverted();
int cursorPosOnRelease = QInputMethod::queryFocusObject(Qt::ImCursorPosition, touchPos * mapToLocal).toInt();
diff --git a/src/plugins/platforms/ios/qiostextresponder.h b/src/plugins/platforms/ios/qiostextresponder.h
index f7450df4c8..77be2cf2fe 100644
--- a/src/plugins/platforms/ios/qiostextresponder.h
+++ b/src/plugins/platforms/ios/qiostextresponder.h
@@ -42,19 +42,23 @@
#include <QtCore/qstring.h>
#include <QtGui/qevent.h>
+QT_BEGIN_NAMESPACE
+
class QIOSInputContext;
+QT_END_NAMESPACE
+
@interface QIOSTextInputResponder : UIResponder <UITextInputTraits, UIKeyInput, UITextInput>
{
@private
- QIOSInputContext *m_inputContext;
- QInputMethodQueryEvent *m_configuredImeState;
+ QT_PREPEND_NAMESPACE(QIOSInputContext) *m_inputContext;
+ QT_PREPEND_NAMESPACE(QInputMethodQueryEvent) *m_configuredImeState;
QString m_markedText;
BOOL m_inSendEventToFocusObject;
BOOL m_inSelectionChange;
}
-- (id)initWithInputContext:(QIOSInputContext *)context;
+- (id)initWithInputContext:(QT_PREPEND_NAMESPACE(QIOSInputContext) *)context;
- (BOOL)needsKeyboardReconfigure:(Qt::InputMethodQueries)updatedProperties;
- (void)notifyInputDelegate:(Qt::InputMethodQueries)updatedProperties;
diff --git a/src/plugins/platforms/ios/qiostextresponder.mm b/src/plugins/platforms/ios/qiostextresponder.mm
index 009f3f8a20..eab6792266 100644
--- a/src/plugins/platforms/ios/qiostextresponder.mm
+++ b/src/plugins/platforms/ios/qiostextresponder.mm
@@ -163,7 +163,7 @@
@implementation QIOSTextInputResponder
-- (id)initWithInputContext:(QIOSInputContext *)inputContext
+- (id)initWithInputContext:(QT_PREPEND_NAMESPACE(QIOSInputContext) *)inputContext
{
if (!(self = [self init]))
return self;
@@ -236,6 +236,8 @@
self.inputView = [[[WrapperView alloc] initWithView:inputView] autorelease];
if (UIView *accessoryView = static_cast<UIView *>(platformData.value(kImePlatformDataInputAccessoryView).value<void *>()))
self.inputAccessoryView = [[[WrapperView alloc] initWithView:accessoryView] autorelease];
+
+#ifndef Q_OS_TVOS
if (QSysInfo::MacintoshVersion >= QSysInfo::MV_IOS_9_0) {
if (platformData.value(kImePlatformDataHideShortcutsBar).toBool()) {
// According to the docs, leadingBarButtonGroups/trailingBarButtonGroups should be set to nil to hide the shortcuts bar.
@@ -247,6 +249,7 @@
self.inputAssistantItem.trailingBarButtonGroups = @[trailing];
}
}
+#endif
self.undoManager.groupsByEvent = NO;
[self rebuildUndoStack];
@@ -691,11 +694,7 @@
if (markedTextFormat.isEmpty()) {
// There seems to be no way to query how the preedit text
// should be drawn. So we need to hard-code the color.
- QSysInfo::MacVersion iosVersion = QSysInfo::MacintoshVersion;
- if (iosVersion < QSysInfo::MV_IOS_7_0)
- markedTextFormat.setBackground(QColor(235, 239, 247));
- else
- markedTextFormat.setBackground(QColor(206, 221, 238));
+ markedTextFormat.setBackground(QColor(206, 221, 238));
}
QList<QInputMethodEvent::Attribute> attrs;
@@ -823,7 +822,7 @@
[self sendEventToFocusObject:e];
}
- return toCGRect(startRect.united(endRect));
+ return startRect.united(endRect).toCGRect();
}
- (NSArray *)selectionRectsForRange:(UITextRange *)range
@@ -841,7 +840,7 @@
// Assume for now that position is always the same as
// cursor index until a better API is in place:
QRectF cursorRect = qApp->inputMethod()->cursorRectangle();
- return toCGRect(cursorRect);
+ return cursorRect.toCGRect();
}
- (void)replaceRange:(UITextRange *)range withText:(NSString *)text
@@ -908,6 +907,7 @@
// text instead of just guessing...
}
+#ifndef Q_OS_TVOS
- (NSDictionary *)textStylingAtPosition:(UITextPosition *)position inDirection:(UITextStorageDirection)direction
{
Q_UNUSED(position);
@@ -927,6 +927,7 @@
return [NSDictionary dictionary];
return [NSDictionary dictionaryWithObject:uifont forKey:NSFontAttributeName];
}
+#endif
- (NSDictionary *)markedTextStyle
{
diff --git a/src/plugins/platforms/ios/qiostheme.mm b/src/plugins/platforms/ios/qiostheme.mm
index 486c146af9..91980d3f35 100644
--- a/src/plugins/platforms/ios/qiostheme.mm
+++ b/src/plugins/platforms/ios/qiostheme.mm
@@ -44,16 +44,18 @@
#include <QtGui/QFont>
-#include <QtPlatformSupport/private/qcoretextfontdatabase_p.h>
+#include <QtFontDatabaseSupport/private/qcoretextfontdatabase_p.h>
#include <QtGui/private/qguiapplication_p.h>
#include <qpa/qplatformintegration.h>
#include <UIKit/UIFont.h>
#include <UIKit/UIInterface.h>
+#ifndef Q_OS_TVOS
#include "qiosmenu.h"
#include "qiosfiledialog.h"
#include "qiosmessagedialog.h"
+#endif
QT_BEGIN_NAMESPACE
@@ -80,12 +82,20 @@ const QPalette *QIOSTheme::palette(QPlatformTheme::Palette type) const
QPlatformMenuItem* QIOSTheme::createPlatformMenuItem() const
{
+#ifdef Q_OS_TVOS
+ return 0;
+#else
return new QIOSMenuItem();
+#endif
}
QPlatformMenu* QIOSTheme::createPlatformMenu() const
{
+#ifdef Q_OS_TVOS
+ return 0;
+#else
return new QIOSMenu();
+#endif
}
bool QIOSTheme::usePlatformNativeDialog(QPlatformTheme::DialogType type) const
@@ -102,12 +112,14 @@ bool QIOSTheme::usePlatformNativeDialog(QPlatformTheme::DialogType type) const
QPlatformDialogHelper *QIOSTheme::createPlatformDialogHelper(QPlatformTheme::DialogType type) const
{
switch (type) {
+#ifndef Q_OS_TVOS
case FileDialog:
return new QIOSFileDialog();
break;
case MessageDialog:
return new QIOSMessageDialog();
break;
+#endif
default:
return 0;
}
diff --git a/src/plugins/platforms/ios/qiosviewcontroller.h b/src/plugins/platforms/ios/qiosviewcontroller.h
index e97aeb32ed..07d5535e1a 100644
--- a/src/plugins/platforms/ios/qiosviewcontroller.h
+++ b/src/plugins/platforms/ios/qiosviewcontroller.h
@@ -38,20 +38,27 @@
****************************************************************************/
#import <UIKit/UIKit.h>
+#include <QtCore/QtGlobal>
+
+QT_BEGIN_NAMESPACE
class QIOSScreen;
+QT_END_NAMESPACE
+
@interface QIOSViewController : UIViewController
-- (id)initWithQIOSScreen:(QIOSScreen *)screen;
+- (id)initWithQIOSScreen:(QT_PREPEND_NAMESPACE(QIOSScreen) *)screen;
- (void)updateProperties;
+#ifndef Q_OS_TVOS
@property (nonatomic, assign) UIInterfaceOrientation lockedOrientation;
// UIViewController
@property (nonatomic, assign) BOOL prefersStatusBarHidden;
@property (nonatomic, assign) UIStatusBarAnimation preferredStatusBarUpdateAnimation;
@property (nonatomic, assign) UIStatusBarStyle preferredStatusBarStyle;
+#endif
@end
diff --git a/src/plugins/platforms/ios/qiosviewcontroller.mm b/src/plugins/platforms/ios/qiosviewcontroller.mm
index fd88664d15..c47b6d68b1 100644
--- a/src/plugins/platforms/ios/qiosviewcontroller.mm
+++ b/src/plugins/platforms/ios/qiosviewcontroller.mm
@@ -37,6 +37,7 @@
**
****************************************************************************/
+#include "qiosglobal.h"
#import "qiosviewcontroller.h"
#include <QtCore/qscopedvaluerollback.h>
@@ -57,7 +58,7 @@
@interface QIOSViewController () {
@public
- QPointer<QIOSScreen> m_screen;
+ QPointer<QT_PREPEND_NAMESPACE(QIOSScreen)> m_screen;
BOOL m_updatingProperties;
QMetaObject::Connection m_focusWindowChangeConnection;
}
@@ -125,7 +126,7 @@
{
Q_UNUSED(subview);
- QIOSScreen *screen = self.qtViewController->m_screen;
+ QT_PREPEND_NAMESPACE(QIOSScreen) *screen = self.qtViewController->m_screen;
// The 'window' property of our view is not valid until the window
// has been shown, so we have to access it through the QIOSScreen.
@@ -228,42 +229,27 @@
@implementation QIOSViewController
+#ifndef Q_OS_TVOS
@synthesize prefersStatusBarHidden;
@synthesize preferredStatusBarUpdateAnimation;
@synthesize preferredStatusBarStyle;
+#endif
-- (id)initWithQIOSScreen:(QIOSScreen *)screen
+- (id)initWithQIOSScreen:(QT_PREPEND_NAMESPACE(QIOSScreen) *)screen
{
if (self = [self init]) {
m_screen = screen;
-#if QT_IOS_DEPLOYMENT_TARGET_BELOW(__IPHONE_7_0)
- QSysInfo::MacVersion iosVersion = QSysInfo::MacintoshVersion;
-
- // We prefer to keep the root viewcontroller in fullscreen layout, so that
- // we don't have to compensate for the viewcontroller position. This also
- // gives us the same behavior on iOS 5/6 as on iOS 7, where full screen layout
- // is the only way.
- if (iosVersion < QSysInfo::MV_IOS_7_0)
- self.wantsFullScreenLayout = YES;
-
- // Use translucent statusbar by default on iOS6 iPhones (unless the user changed
- // the default in the Info.plist), so that windows placed under the stausbar are
- // still visible, just like on iOS7.
- if (screen->uiScreen() == [UIScreen mainScreen]
- && iosVersion >= QSysInfo::MV_IOS_6_0 && iosVersion < QSysInfo::MV_IOS_7_0
- && [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone
- && [UIApplication sharedApplication].statusBarStyle == UIStatusBarStyleDefault)
- [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
-#endif
- self.lockedOrientation = UIInterfaceOrientationUnknown;
self.changingOrientation = NO;
+#ifndef Q_OS_TVOS
+ self.lockedOrientation = UIInterfaceOrientationUnknown;
// Status bar may be initially hidden at startup through Info.plist
self.prefersStatusBarHidden = infoPlistValue(@"UIStatusBarHidden", false);
self.preferredStatusBarUpdateAnimation = UIStatusBarAnimationNone;
self.preferredStatusBarStyle = UIStatusBarStyle(infoPlistValue(@"UIStatusBarStyle", UIStatusBarStyleDefault));
+#endif
m_focusWindowChangeConnection = QObject::connect(qApp, &QGuiApplication::focusWindowChanged, [self]() {
[self updateProperties];
@@ -288,6 +274,7 @@
{
[super viewDidLoad];
+#ifndef Q_OS_TVOS
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(willChangeStatusBarFrame:)
name:UIApplicationWillChangeStatusBarFrameNotification
@@ -296,6 +283,7 @@
[center addObserver:self selector:@selector(didChangeStatusBarOrientation:)
name:UIApplicationDidChangeStatusBarOrientationNotification
object:[UIApplication sharedApplication]];
+#endif
}
- (void)viewDidUnload
@@ -308,10 +296,13 @@
- (BOOL)shouldAutorotate
{
+#ifndef Q_OS_TVOS
return m_screen && m_screen->uiScreen() == [UIScreen mainScreen] && !self.lockedOrientation;
+#else
+ return NO;
+#endif
}
-#if QT_IOS_PLATFORM_SDK_EQUAL_OR_ABOVE(__IPHONE_6_0)
- (NSUInteger)supportedInterfaceOrientations
{
// As documented by Apple in the iOS 6.0 release notes, setStatusBarOrientation:animated:
@@ -322,15 +313,6 @@
// supportedInterfaceOrientations says, which states that the method should not return 0.
return [self shouldAutorotate] ? UIInterfaceOrientationMaskAll : 0;
}
-#endif
-
-#if QT_IOS_DEPLOYMENT_TARGET_BELOW(__IPHONE_6_0)
-- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
-{
- Q_UNUSED(interfaceOrientation);
- return [self shouldAutorotate];
-}
-#endif
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration
{
@@ -439,6 +421,7 @@
// All decisions are based on the the top level window
focusWindow = qt_window_private(focusWindow)->topLevelWindow();
+#ifndef Q_OS_TVOS
UIApplication *uiApplication = [UIApplication sharedApplication];
// -------------- Status bar style and visbility ---------------
@@ -447,30 +430,16 @@
if (focusWindow->flags() & Qt::MaximizeUsingFullscreenGeometryHint)
self.preferredStatusBarStyle = UIStatusBarStyleDefault;
else
- self.preferredStatusBarStyle = QSysInfo::MacintoshVersion >= QSysInfo::MV_IOS_7_0 ?
- UIStatusBarStyleLightContent : UIStatusBarStyleBlackTranslucent;
-
- if (self.preferredStatusBarStyle != oldStatusBarStyle) {
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_IOS_7_0)
- [self setNeedsStatusBarAppearanceUpdate];
- else
- [uiApplication setStatusBarStyle:self.preferredStatusBarStyle];
- }
+ self.preferredStatusBarStyle = UIStatusBarStyleLightContent;
+
+ if (self.preferredStatusBarStyle != oldStatusBarStyle)
+ [self setNeedsStatusBarAppearanceUpdate];
bool currentStatusBarVisibility = self.prefersStatusBarHidden;
self.prefersStatusBarHidden = focusWindow->windowState() == Qt::WindowFullScreen;
if (self.prefersStatusBarHidden != currentStatusBarVisibility) {
-#if QT_IOS_PLATFORM_SDK_EQUAL_OR_ABOVE(__IPHONE_7_0)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_IOS_7_0) {
- [self setNeedsStatusBarAppearanceUpdate];
- } else
-#endif
- {
- [uiApplication setStatusBarHidden:self.prefersStatusBarHidden
- withAnimation:self.preferredStatusBarUpdateAnimation];
- }
-
+ [self setNeedsStatusBarAppearanceUpdate];
[self.view setNeedsLayout];
}
@@ -516,6 +485,7 @@
[UIViewController attemptRotationToDeviceOrientation];
}
}
+#endif
}
@end
diff --git a/src/plugins/platforms/ios/qioswindow.h b/src/plugins/platforms/ios/qioswindow.h
index afc2f0f89d..81fad420f6 100644
--- a/src/plugins/platforms/ios/qioswindow.h
+++ b/src/plugins/platforms/ios/qioswindow.h
@@ -48,10 +48,10 @@
class QIOSContext;
class QIOSWindow;
-QT_BEGIN_NAMESPACE
-
@class QUIView;
+QT_BEGIN_NAMESPACE
+
class QIOSWindow : public QObject, public QPlatformWindow
{
Q_OBJECT
diff --git a/src/plugins/platforms/ios/qioswindow.mm b/src/plugins/platforms/ios/qioswindow.mm
index 8099d13147..8ff0dfbd5f 100644
--- a/src/plugins/platforms/ios/qioswindow.mm
+++ b/src/plugins/platforms/ios/qioswindow.mm
@@ -54,6 +54,8 @@
#include <QtDebug>
+QT_BEGIN_NAMESPACE
+
QIOSWindow::QIOSWindow(QWindow *window)
: QPlatformWindow(window)
, m_view([[QUIView alloc] initWithQIOSWindow:this])
@@ -211,7 +213,7 @@ void QIOSWindow::applyGeometry(const QRect &rect)
// The baseclass takes care of persisting this for us.
QPlatformWindow::setGeometry(rect);
- m_view.frame = toCGRect(rect);
+ m_view.frame = rect.toCGRect();
// iOS will automatically trigger -[layoutSubviews:] for resize,
// but not for move, so we force it just in case.
diff --git a/src/plugins/platforms/ios/quiaccessibilityelement.h b/src/plugins/platforms/ios/quiaccessibilityelement.h
index 1a9ae2a1a7..03abf5407e 100644
--- a/src/plugins/platforms/ios/quiaccessibilityelement.h
+++ b/src/plugins/platforms/ios/quiaccessibilityelement.h
@@ -43,6 +43,8 @@
#import <UIKit/UIKit.h>
#import <QtGui/QtGui>
+#ifndef QT_NO_ACCESSIBILITY
+
@interface QMacAccessibilityElement : UIAccessibilityElement
{}
@@ -54,3 +56,4 @@
@end
#endif
+#endif
diff --git a/src/plugins/platforms/ios/quiaccessibilityelement.mm b/src/plugins/platforms/ios/quiaccessibilityelement.mm
index 39a879fc23..a26ba61b3c 100644
--- a/src/plugins/platforms/ios/quiaccessibilityelement.mm
+++ b/src/plugins/platforms/ios/quiaccessibilityelement.mm
@@ -39,6 +39,8 @@
#include "quiaccessibilityelement.h"
+#ifndef QT_NO_ACCESSIBILITY
+
#include "private/qaccessiblecache_p.h"
@implementation QMacAccessibilityElement
@@ -61,7 +63,7 @@
QAccessibleCache *cache = QAccessibleCache::instance();
- QMacAccessibilityElement *element = cache->elementForId(anId);
+ QT_MANGLE_NAMESPACE(QMacAccessibilityElement) *element = cache->elementForId(anId);
if (!element) {
Q_ASSERT(QAccessible::accessibleInterface(anId));
element = [[self alloc] initWithId:anId withAccessibilityContainer: view];
@@ -221,3 +223,5 @@
}
@end
+
+#endif
diff --git a/src/plugins/platforms/ios/quiview.h b/src/plugins/platforms/ios/quiview.h
index fdaae943d8..1500f0b41c 100644
--- a/src/plugins/platforms/ios/quiview.h
+++ b/src/plugins/platforms/ios/quiview.h
@@ -44,14 +44,18 @@
#include <qpa/qwindowsysteminterface.h>
+QT_BEGIN_NAMESPACE
+
class QIOSWindow;
+QT_END_NAMESPACE
+
@class QIOSViewController;
@interface QUIView : UIView
{
@public
- QIOSWindow *m_qioswindow;
+ QT_PREPEND_NAMESPACE(QIOSWindow) *m_qioswindow;
@private
QHash<UITouch *, QWindowSystemInterface::TouchPoint> m_activeTouches;
int m_nextTouchId;
@@ -60,7 +64,7 @@ class QIOSWindow;
NSMutableArray *m_accessibleElements;
};
-- (id)initWithQIOSWindow:(QIOSWindow *)window;
+- (id)initWithQIOSWindow:(QT_PREPEND_NAMESPACE(QIOSWindow) *)window;
- (void)sendUpdatedExposeEvent;
- (BOOL)isActiveWindow;
@end
diff --git a/src/plugins/platforms/ios/quiview.mm b/src/plugins/platforms/ios/quiview.mm
index 9c7acc9278..2a1444e9e5 100644
--- a/src/plugins/platforms/ios/quiview.mm
+++ b/src/plugins/platforms/ios/quiview.mm
@@ -44,10 +44,13 @@
#include "qiosviewcontroller.h"
#include "qiostextresponder.h"
#include "qioswindow.h"
+#ifndef Q_OS_TVOS
#include "qiosmenu.h"
+#endif
#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/private/qwindow_p.h>
+#include <qpa/qwindowsysteminterface_p.h>
@implementation QUIView
@@ -56,9 +59,9 @@
return [CAEAGLLayer class];
}
-- (id)initWithQIOSWindow:(QIOSWindow *)window
+- (id)initWithQIOSWindow:(QT_PREPEND_NAMESPACE(QIOSWindow) *)window
{
- if (self = [self initWithFrame:toCGRect(window->geometry())])
+ if (self = [self initWithFrame:window->geometry().toCGRect()])
m_qioswindow = window;
m_accessibleElements = [[NSMutableArray alloc] init];
@@ -78,7 +81,9 @@
if (isQtApplication())
self.hidden = YES;
+#ifndef Q_OS_TVOS
self.multipleTouchEnabled = YES;
+#endif
if (QIOSIntegration::instance()->debugWindowManagement()) {
static CGFloat hue = 0.0;
@@ -149,7 +154,7 @@
// from what we end up with after applying window constraints.
QRect requestedGeometry = m_qioswindow->geometry();
- QRect actualGeometry = fromCGRect(self.frame).toRect();
+ QRect actualGeometry = QRectF::fromCGRect(self.frame).toRect();
// Persist the actual/new geometry so that QWindow::geometry() can
// be queried on the resize event.
@@ -159,8 +164,7 @@
requestedGeometry : qt_window_private(m_qioswindow->window())->geometry;
QWindow *window = m_qioswindow->window();
- QWindowSystemInterface::handleGeometryChange(window, actualGeometry, previousGeometry);
- QWindowSystemInterface::flushWindowSystemEvents(window->inherits("QWidgetWindow") ? QEventLoop::ExcludeUserInputEvents : QEventLoop::AllEvents);
+ QWindowSystemInterface::handleGeometryChange<QWindowSystemInterface::SynchronousDelivery>(window, actualGeometry, previousGeometry);
if (actualGeometry.size() != previousGeometry.size()) {
// Trigger expose event on resize
@@ -184,7 +188,7 @@
QRegion region;
if (m_qioswindow->isExposed()) {
- QSize bounds = fromCGRect(self.layer.bounds).toRect().size();
+ QSize bounds = QRectF::fromCGRect(self.layer.bounds).toRect().size();
Q_ASSERT(m_qioswindow->geometry().size() == bounds);
Q_ASSERT(self.hidden == !m_qioswindow->window()->isVisible());
@@ -192,8 +196,7 @@
region = QRect(QPoint(), bounds);
}
- QWindowSystemInterface::handleExposeEvent(m_qioswindow->window(), region);
- QWindowSystemInterface::flushWindowSystemEvents();
+ QWindowSystemInterface::handleExposeEvent<QWindowSystemInterface::SynchronousDelivery>(m_qioswindow->window(), region);
}
// -------------------------------------------------------------------------
@@ -218,13 +221,10 @@
qImDebug() << m_qioswindow->window() << "became first responder";
- if (qGuiApp->focusWindow() != m_qioswindow->window()) {
- QWindowSystemInterface::handleWindowActivated(m_qioswindow->window());
- QWindowSystemInterface::flushWindowSystemEvents();
- } else {
- qImDebug() << m_qioswindow->window()
- << "already active, not sending window activation";
- }
+ if (qGuiApp->focusWindow() != m_qioswindow->window())
+ QWindowSystemInterface::handleWindowActivated<QWindowSystemInterface::SynchronousDelivery>(m_qioswindow->window());
+ else
+ qImDebug() << m_qioswindow->window() << "already active, not sending window activation";
return YES;
}
@@ -259,10 +259,8 @@
qImDebug() << m_qioswindow->window() << "resigned first responder";
UIResponder *newResponder = FirstResponderCandidate::currentCandidate();
- if ([self responderShouldTriggerWindowDeactivation:newResponder]) {
- QWindowSystemInterface::handleWindowActivated(0);
- QWindowSystemInterface::flushWindowSystemEvents();
- }
+ if ([self responderShouldTriggerWindowDeactivation:newResponder])
+ QWindowSystemInterface::handleWindowActivated<QWindowSystemInterface::SynchronousDelivery>(0);
return YES;
}
@@ -324,7 +322,8 @@
// Touch positions are expected to be in QScreen global coordinates, and
// as we already have the QWindow positioned at the right place, we can
// just map from the local view position to global coordinates.
- QPoint localViewPosition = fromCGPoint([uiTouch locationInView:self]).toPoint();
+ // tvOS: all touches start at the center of the screen and move from there.
+ QPoint localViewPosition = QPointF::fromCGPoint([uiTouch locationInView:self]).toPoint();
QPoint globalScreenPosition = m_qioswindow->mapToGlobal(localViewPosition);
touchPoint.area = QRectF(globalScreenPosition, QSize(0, 0));
@@ -351,10 +350,8 @@
- (void)sendTouchEventWithTimestamp:(ulong)timeStamp
{
- // Send touch event synchronously
QIOSIntegration *iosIntegration = QIOSIntegration::instance();
- QWindowSystemInterface::handleTouchEvent(m_qioswindow->window(), timeStamp, iosIntegration->touchDevice(), m_activeTouches.values());
- QWindowSystemInterface::flushWindowSystemEvents();
+ QWindowSystemInterface::handleTouchEvent<QWindowSystemInterface::SynchronousDelivery>(m_qioswindow->window(), timeStamp, iosIntegration->touchDevice(), m_activeTouches.values());
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
@@ -432,22 +429,80 @@
NSTimeInterval timestamp = event ? event.timestamp : [[NSProcessInfo processInfo] systemUptime];
- // Send cancel touch event synchronously
QIOSIntegration *iosIntegration = static_cast<QIOSIntegration *>(QGuiApplicationPrivate::platformIntegration());
- QWindowSystemInterface::handleTouchCancelEvent(m_qioswindow->window(), ulong(timestamp * 1000), iosIntegration->touchDevice());
- QWindowSystemInterface::flushWindowSystemEvents();
+ QWindowSystemInterface::handleTouchCancelEvent<QWindowSystemInterface::SynchronousDelivery>(m_qioswindow->window(), ulong(timestamp * 1000), iosIntegration->touchDevice());
+}
+
+- (int)mapPressTypeToKey:(UIPress*)press
+{
+ switch (press.type) {
+ case UIPressTypeUpArrow: return Qt::Key_Up;
+ case UIPressTypeDownArrow: return Qt::Key_Down;
+ case UIPressTypeLeftArrow: return Qt::Key_Left;
+ case UIPressTypeRightArrow: return Qt::Key_Right;
+ case UIPressTypeSelect: return Qt::Key_Select;
+ case UIPressTypeMenu: return Qt::Key_Menu;
+ case UIPressTypePlayPause: return Qt::Key_MediaTogglePlayPause;
+ }
+ return Qt::Key_unknown;
+}
+
+- (bool)processPresses:(NSSet *)presses withType:(QEvent::Type)type {
+ // Presses on Menu button will generate a Menu key event. By default, not handling
+ // this event will cause the application to return to Headboard (tvOS launcher).
+ // When handling the event (for example, as a back button), both press and
+ // release events must be handled accordingly.
+
+ bool handled = false;
+ for (UIPress* press in presses) {
+ int key = [self mapPressTypeToKey:press];
+ if (key == Qt::Key_unknown)
+ continue;
+ if (QWindowSystemInterface::handleKeyEvent<QWindowSystemInterface::SynchronousDelivery>(m_qioswindow->window(), type, key, Qt::NoModifier))
+ handled = true;
+ }
+
+ return handled;
+}
+
+- (void)pressesBegan:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event
+{
+ if (![self processPresses:presses withType:QEvent::KeyPress])
+ [super pressesBegan:presses withEvent:event];
+}
+
+- (void)pressesChanged:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event
+{
+ if (![self processPresses:presses withType:QEvent::KeyPress])
+ [super pressesChanged:presses withEvent:event];
+}
+
+- (void)pressesEnded:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event
+{
+ if (![self processPresses:presses withType:QEvent::KeyRelease])
+ [super pressesEnded:presses withEvent:event];
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
+#ifndef Q_OS_TVOS
// Check first if QIOSMenu should handle the action before continuing up the responder chain
return [QIOSMenu::menuActionTarget() targetForAction:action withSender:sender] != 0;
+#else
+ Q_UNUSED(action)
+ Q_UNUSED(sender)
+ return false;
+#endif
}
- (id)forwardingTargetForSelector:(SEL)selector
{
Q_UNUSED(selector)
+#ifndef Q_OS_TVOS
return QIOSMenu::menuActionTarget();
+#else
+ return nil;
+#endif
}
@end
@@ -457,7 +512,7 @@
- (QWindow *)qwindow
{
if ([self isKindOfClass:[QUIView class]]) {
- if (QIOSWindow *w = static_cast<QUIView *>(self)->m_qioswindow)
+ if (QT_PREPEND_NAMESPACE(QIOSWindow) *w = static_cast<QUIView *>(self)->m_qioswindow)
return w->window();
}
return nil;
@@ -484,5 +539,7 @@
@end
+#ifndef QT_NO_ACCESSIBILITY
// Include category as an alternative to using -ObjC (Apple QA1490)
#include "quiview_accessibility.mm"
+#endif
diff --git a/src/plugins/platforms/linuxfb/linuxfb.pro b/src/plugins/platforms/linuxfb/linuxfb.pro
index b5de192346..e2fa31211d 100644
--- a/src/plugins/platforms/linuxfb/linuxfb.pro
+++ b/src/plugins/platforms/linuxfb/linuxfb.pro
@@ -1,12 +1,18 @@
TARGET = qlinuxfb
-QT += core-private gui-private platformsupport-private
+DEFINES += QT_NO_FOREACH
+
+QT += \
+ core-private gui-private \
+ service_support-private eventdispatcher_support-private \
+ fontdatabase_support-private fb_support-private
+
+qtHaveModule(input_support-private): \
+ QT += input_support-private
SOURCES = main.cpp qlinuxfbintegration.cpp qlinuxfbscreen.cpp
HEADERS = qlinuxfbintegration.h qlinuxfbscreen.h
-CONFIG += qpa/genericunixfontdatabase
-
OTHER_FILES += linuxfb.json
PLUGIN_TYPE = platforms
diff --git a/src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp b/src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp
index 2037f29a5a..c1c235588e 100644
--- a/src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp
+++ b/src/plugins/platforms/linuxfb/qlinuxfbintegration.cpp
@@ -40,30 +40,30 @@
#include "qlinuxfbintegration.h"
#include "qlinuxfbscreen.h"
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qgenericunixservices_p.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtServiceSupport/private/qgenericunixservices_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
-#include <QtPlatformSupport/private/qfbvthandler_p.h>
-#include <QtPlatformSupport/private/qfbbackingstore_p.h>
-#include <QtPlatformSupport/private/qfbwindow_p.h>
-#include <QtPlatformSupport/private/qfbcursor_p.h>
+#include <QtFbSupport/private/qfbvthandler_p.h>
+#include <QtFbSupport/private/qfbbackingstore_p.h>
+#include <QtFbSupport/private/qfbwindow_p.h>
+#include <QtFbSupport/private/qfbcursor_p.h>
#include <QtGui/private/qguiapplication_p.h>
#include <qpa/qplatforminputcontextfactory_p.h>
-#ifndef QT_NO_LIBINPUT
-#include <QtPlatformSupport/private/qlibinputhandler_p.h>
+#if QT_CONFIG(libinput)
+#include <QtInputSupport/private/qlibinputhandler_p.h>
#endif
-#if !defined(QT_NO_EVDEV) && !defined(Q_OS_ANDROID)
-#include <QtPlatformSupport/private/qevdevmousemanager_p.h>
-#include <QtPlatformSupport/private/qevdevkeyboardmanager_p.h>
-#include <QtPlatformSupport/private/qevdevtouchmanager_p.h>
+#if QT_CONFIG(evdev) && !defined(Q_OS_ANDROID)
+#include <QtInputSupport/private/qevdevmousemanager_p.h>
+#include <QtInputSupport/private/qevdevkeyboardmanager_p.h>
+#include <QtInputSupport/private/qevdevtouchmanager_p.h>
#endif
-#if !defined(QT_NO_TSLIB) && !defined(Q_OS_ANDROID)
-#include <QtPlatformSupport/private/qtslib_p.h>
+#if QT_CONFIG(tslib) && !defined(Q_OS_ANDROID)
+#include <QtInputSupport/private/qtslib_p.h>
#endif
QT_BEGIN_NAMESPACE
@@ -140,7 +140,7 @@ QPlatformServices *QLinuxFbIntegration::services() const
void QLinuxFbIntegration::createInputHandlers()
{
-#ifndef QT_NO_LIBINPUT
+#if QT_CONFIG(libinput)
if (!qEnvironmentVariableIntValue("QT_QPA_FB_NO_LIBINPUT")) {
new QLibInputHandler(QLatin1String("libinput"), QString());
return;
@@ -148,13 +148,13 @@ void QLinuxFbIntegration::createInputHandlers()
#endif
bool useTslib = false;
-#ifndef QT_NO_TSLIB
+#if QT_CONFIG(tslib)
useTslib = qEnvironmentVariableIntValue("QT_QPA_FB_TSLIB");
if (useTslib)
new QTsLibMouseHandler(QLatin1String("TsLib"), QString());
#endif
-#if !defined(QT_NO_EVDEV) && !defined(Q_OS_ANDROID)
+#if QT_CONFIG(evdev) && !defined(Q_OS_ANDROID)
new QEvdevKeyboardManager(QLatin1String("EvdevKeyboard"), QString(), this);
new QEvdevMouseManager(QLatin1String("EvdevMouse"), QString(), this);
if (!useTslib)
diff --git a/src/plugins/platforms/linuxfb/qlinuxfbscreen.cpp b/src/plugins/platforms/linuxfb/qlinuxfbscreen.cpp
index 1fd2b84e37..246c959fd3 100644
--- a/src/plugins/platforms/linuxfb/qlinuxfbscreen.cpp
+++ b/src/plugins/platforms/linuxfb/qlinuxfbscreen.cpp
@@ -38,8 +38,8 @@
****************************************************************************/
#include "qlinuxfbscreen.h"
-#include <QtPlatformSupport/private/qfbcursor_p.h>
-#include <QtPlatformSupport/private/qfbwindow_p.h>
+#include <QtFbSupport/private/qfbcursor_p.h>
+#include <QtFbSupport/private/qfbwindow_p.h>
#include <QtCore/QFile>
#include <QtCore/QRegularExpression>
#include <QtGui/QPainter>
@@ -320,7 +320,7 @@ bool QLinuxFbScreen::initialize()
bool doSwitchToGraphicsMode = true;
// Parse arguments
- foreach (const QString &arg, mArgs) {
+ for (const QString &arg : qAsConst(mArgs)) {
QRegularExpressionMatch match;
if (arg == QLatin1String("nographicsmodeswitch"))
doSwitchToGraphicsMode = false;
@@ -412,11 +412,9 @@ QRegion QLinuxFbScreen::doRedraw()
if (!mBlitter)
mBlitter = new QPainter(&mFbScreenImage);
- const QVector<QRect> rects = touched.rects();
mBlitter->setCompositionMode(QPainter::CompositionMode_Source);
-
- for (int i = 0; i < rects.size(); ++i)
- mBlitter->drawImage(rects[i], *mScreenImage, rects[i]);
+ for (const QRect &rect : touched)
+ mBlitter->drawImage(rect, *mScreenImage, rect);
return touched;
}
diff --git a/src/plugins/platforms/linuxfb/qlinuxfbscreen.h b/src/plugins/platforms/linuxfb/qlinuxfbscreen.h
index ada9c4d830..1e98191569 100644
--- a/src/plugins/platforms/linuxfb/qlinuxfbscreen.h
+++ b/src/plugins/platforms/linuxfb/qlinuxfbscreen.h
@@ -40,7 +40,7 @@
#ifndef QLINUXFBSCREEN_H
#define QLINUXFBSCREEN_H
-#include <QtPlatformSupport/private/qfbscreen_p.h>
+#include <QtFbSupport/private/qfbscreen_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/minimal/minimal.pro b/src/plugins/platforms/minimal/minimal.pro
index 3aca27b555..8cfb68824e 100644
--- a/src/plugins/platforms/minimal/minimal.pro
+++ b/src/plugins/platforms/minimal/minimal.pro
@@ -1,6 +1,10 @@
TARGET = qminimal
-QT += core-private gui-private platformsupport-private
+QT += \
+ core-private gui-private \
+ eventdispatcher_support-private fontdatabase_support-private
+
+DEFINES += QT_NO_FOREACH
SOURCES = main.cpp \
qminimalintegration.cpp \
@@ -10,9 +14,6 @@ HEADERS = qminimalintegration.h \
OTHER_FILES += minimal.json
-CONFIG += qpa/genericunixfontdatabase
-win32|darwin: DEFINES += QT_NO_FONTCONFIG
-
PLUGIN_TYPE = platforms
PLUGIN_CLASS_NAME = QMinimalIntegrationPlugin
!equals(TARGET, $$QT_DEFAULT_QPA_PLUGIN): PLUGIN_EXTENDS = -
diff --git a/src/plugins/platforms/minimal/qminimalintegration.cpp b/src/plugins/platforms/minimal/qminimalintegration.cpp
index 7224f4114c..03c72502cb 100644
--- a/src/plugins/platforms/minimal/qminimalintegration.cpp
+++ b/src/plugins/platforms/minimal/qminimalintegration.cpp
@@ -45,15 +45,15 @@
#include <qpa/qplatformwindow.h>
#if defined(Q_OS_WIN)
-#include <QtPlatformSupport/private/qbasicfontdatabase_p.h>
-#elif defined(QT_NO_FONTCONFIG)
-#include <qpa/qplatformfontdatabase.h>
+#include <QtFontDatabaseSupport/private/qbasicfontdatabase_p.h>
+#elif QT_CONFIG(fontconfig)
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
#else
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
+#include <qpa/qplatformfontdatabase.h>
#endif
#if !defined(Q_OS_WIN)
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
#elif defined(Q_OS_WINRT)
#include <QtCore/private/qeventdispatcher_winrt_p.h>
#else
@@ -67,7 +67,7 @@ static const char debugBackingStoreEnvironmentVariable[] = "QT_DEBUG_BACKINGSTOR
static inline unsigned parseOptions(const QStringList &paramList)
{
unsigned options = 0;
- foreach (const QString &param, paramList) {
+ for (const QString &param : paramList) {
if (param == QLatin1String("enable_fonts"))
options |= QMinimalIntegration::EnableFonts;
}
@@ -118,7 +118,7 @@ public:
QPlatformFontDatabase *QMinimalIntegration::fontDatabase() const
{
if (m_options & EnableFonts) {
-#ifndef QT_NO_FONTCONFIG
+#if QT_CONFIG(fontconfig)
if (!m_fontDatabase)
m_fontDatabase = new QGenericUnixFontDatabase;
#else
diff --git a/src/plugins/platforms/minimalegl/minimalegl.pro b/src/plugins/platforms/minimalegl/minimalegl.pro
index b8a91729fd..88466e7f36 100644
--- a/src/plugins/platforms/minimalegl/minimalegl.pro
+++ b/src/plugins/platforms/minimalegl/minimalegl.pro
@@ -1,6 +1,8 @@
TARGET = qminimalegl
-QT += core-private gui-private platformsupport-private
+QT += \
+ core-private gui-private \
+ eventdispatcher_support-private fontdatabase_support-private egl_support-private
#DEFINES += QEGL_EXTRA_DEBUG
@@ -20,7 +22,7 @@ HEADERS = qminimaleglintegration.h \
qminimaleglbackingstore.h \
qminimaleglscreen.h
-CONFIG += egl qpa/genericunixfontdatabase
+CONFIG += egl
OTHER_FILES += \
minimalegl.json
diff --git a/src/plugins/platforms/minimalegl/qminimaleglintegration.cpp b/src/plugins/platforms/minimalegl/qminimaleglintegration.cpp
index 06008e00d8..c564e1e431 100644
--- a/src/plugins/platforms/minimalegl/qminimaleglintegration.cpp
+++ b/src/plugins/platforms/minimalegl/qminimaleglintegration.cpp
@@ -42,15 +42,15 @@
#include "qminimaleglwindow.h"
#include "qminimaleglbackingstore.h"
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
#if defined(Q_OS_UNIX)
-# include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+# include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
#elif defined(Q_OS_WINRT)
# include <QtCore/private/qeventdispatcher_winrt_p.h>
# include <QtGui/qpa/qwindowsysteminterface.h>
#elif defined(Q_OS_WIN)
-# include <QtPlatformSupport/private/qwindowsguieventdispatcher_p.h>
+# include <QtEventDispatcherSupport/private/qwindowsguieventdispatcher_p.h>
#endif
#include <qpa/qplatformwindow.h>
diff --git a/src/plugins/platforms/minimalegl/qminimaleglscreen.cpp b/src/plugins/platforms/minimalegl/qminimaleglscreen.cpp
index e8a9641224..d3d091fab7 100644
--- a/src/plugins/platforms/minimalegl/qminimaleglscreen.cpp
+++ b/src/plugins/platforms/minimalegl/qminimaleglscreen.cpp
@@ -40,8 +40,8 @@
#include "qminimaleglscreen.h"
#include "qminimaleglwindow.h"
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-#include <QtPlatformSupport/private/qeglplatformcontext_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglplatformcontext_p.h>
#ifdef Q_OPENKODE
#include <KD/kd.h>
diff --git a/src/plugins/platforms/minimalegl/qminimaleglscreen.h b/src/plugins/platforms/minimalegl/qminimaleglscreen.h
index 4b53bbd39a..ba605835a8 100644
--- a/src/plugins/platforms/minimalegl/qminimaleglscreen.h
+++ b/src/plugins/platforms/minimalegl/qminimaleglscreen.h
@@ -44,7 +44,7 @@
#include <QtCore/QTextStream>
-#include <QtPlatformSupport/private/qt_egl_p.h>
+#include <QtEglSupport/private/qt_egl_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/mirclient/mirclient.pro b/src/plugins/platforms/mirclient/mirclient.pro
index d5d35f1632..0ba63601a9 100644
--- a/src/plugins/platforms/mirclient/mirclient.pro
+++ b/src/plugins/platforms/mirclient/mirclient.pro
@@ -1,16 +1,16 @@
TARGET = qmirclient
-QT += core-private gui-private platformsupport-private dbus
-
-CONFIG += qpa/genericunixfontdatabase
+QT += \
+ core-private gui-private dbus \
+ theme_support-private eventdispatcher_support-private \
+ fontdatabase_support-private egl_support-private
DEFINES += MESA_EGL_NO_X11_HEADERS
# CONFIG += c++11 # only enables C++0x
QMAKE_CXXFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden -std=c++11 -Werror -Wall
QMAKE_LFLAGS += -std=c++11 -Wl,-no-undefined
-CONFIG += link_pkgconfig
-PKGCONFIG += egl mirclient ubuntu-platform-api
+QMAKE_USE_PRIVATE += mirclient
SOURCES = \
qmirclientbackingstore.cpp \
diff --git a/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp b/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp
index 465ad355b9..a4bb8864ab 100644
--- a/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp
@@ -43,7 +43,7 @@
#include <QtGui/QOpenGLContext>
#include <QtGui/QOpenGLTexture>
#include <QtGui/QMatrix4x4>
-#include <QtGui/private/qopengltextureblitter_p.h>
+#include <QtGui/qopengltextureblitter.h>
#include <QtGui/qopenglfunctions.h>
QMirClientBackingStore::QMirClientBackingStore(QWindow* window)
@@ -76,7 +76,7 @@ void QMirClientBackingStore::flush(QWindow* window, const QRegion& region, const
mBlitter->create();
mBlitter->bind();
- mBlitter->setSwizzleRB(true);
+ mBlitter->setRedBlueSwizzle(true);
mBlitter->blit(mTexture->textureId(), QMatrix4x4(), QOpenGLTextureBlitter::OriginTopLeft);
mBlitter->release();
@@ -100,7 +100,7 @@ void QMirClientBackingStore::updateTexture()
QRegion fixed;
QRect imageRect = mImage.rect();
- Q_FOREACH (const QRect &rect, mDirty.rects()) {
+ for (const QRect &rect : mDirty) {
// intersect with image rect to be sure
QRect r = imageRect & rect;
@@ -113,7 +113,7 @@ void QMirClientBackingStore::updateTexture()
fixed |= r;
}
- Q_FOREACH (const QRect &rect, fixed.rects()) {
+ for (const QRect &rect : fixed) {
// if the sub-rect is full-width we can pass the image data directly to
// OpenGL instead of copying, since there is no gap between scanlines
if (rect.width() == imageRect.width()) {
diff --git a/src/plugins/platforms/mirclient/qmirclientcursor.cpp b/src/plugins/platforms/mirclient/qmirclientcursor.cpp
index 83ea116c11..a0da3fdd77 100644
--- a/src/plugins/platforms/mirclient/qmirclientcursor.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientcursor.cpp
@@ -167,7 +167,7 @@ void QMirClientCursor::configureMirCursorWithPixmapQCursor(MirSurface *surface,
QImage image = cursor.pixmap().toImage();
if (image.format() != QImage::Format_ARGB32) {
- image.convertToFormat(QImage::Format_ARGB32);
+ image = image.convertToFormat(QImage::Format_ARGB32);
}
MirBufferStream *bufferStream = mir_connection_create_buffer_stream_sync(mConnection,
diff --git a/src/plugins/platforms/mirclient/qmirclientglcontext.cpp b/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
index 4092669cfc..38eb0a4609 100644
--- a/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
@@ -41,7 +41,7 @@
#include "qmirclientglcontext.h"
#include "qmirclientwindow.h"
#include "qmirclientlogging.h"
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
#include <QtGui/private/qopenglcontext_p.h>
#include <dlfcn.h>
diff --git a/src/plugins/platforms/mirclient/qmirclientinput.cpp b/src/plugins/platforms/mirclient/qmirclientinput.cpp
index 4817185d41..b3b21ae0e3 100644
--- a/src/plugins/platforms/mirclient/qmirclientinput.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientinput.cpp
@@ -347,6 +347,7 @@ void QMirClientInput::dispatchTouchEvent(QMirClientWindow *window, const MirInpu
// TODO: Is it worth setting the Qt::TouchPointStationary ones? Currently they are left
// as Qt::TouchPointMoved
const unsigned int kPointerCount = mir_touch_event_point_count(tev);
+ touchPoints.reserve(int(kPointerCount));
for (unsigned int i = 0; i < kPointerCount; ++i) {
QWindowSystemInterface::TouchPoint touchPoint;
diff --git a/src/plugins/platforms/mirclient/qmirclientintegration.cpp b/src/plugins/platforms/mirclient/qmirclientintegration.cpp
index cfbcdc937e..2c8740f070 100644
--- a/src/plugins/platforms/mirclient/qmirclientintegration.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientintegration.cpp
@@ -56,8 +56,8 @@
#include <qpa/qplatformnativeinterface.h>
#include <qpa/qplatforminputcontextfactory_p.h>
#include <qpa/qplatforminputcontext.h>
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
#include <QOpenGLContext>
// platform-api
diff --git a/src/plugins/platforms/mirclient/qmirclientplatformservices.h b/src/plugins/platforms/mirclient/qmirclientplatformservices.h
index 46cf4300f8..a1cd5758ca 100644
--- a/src/plugins/platforms/mirclient/qmirclientplatformservices.h
+++ b/src/plugins/platforms/mirclient/qmirclientplatformservices.h
@@ -42,8 +42,8 @@
#define QMIRCLIENTPLATFORMSERVICES_H
#include <qpa/qplatformservices.h>
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
class QMirClientPlatformServices : public QPlatformServices {
public:
diff --git a/src/plugins/platforms/mirclient/qmirclientscreen.cpp b/src/plugins/platforms/mirclient/qmirclientscreen.cpp
index ca0c3e4733..0a2253e9e2 100644
--- a/src/plugins/platforms/mirclient/qmirclientscreen.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientscreen.cpp
@@ -51,7 +51,7 @@
#include <QScreen>
#include <QThread>
#include <qpa/qwindowsysteminterface.h>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
#include <memory>
diff --git a/src/plugins/platforms/mirclient/qmirclienttheme.h b/src/plugins/platforms/mirclient/qmirclienttheme.h
index 19728741e3..4bab1d0ee0 100644
--- a/src/plugins/platforms/mirclient/qmirclienttheme.h
+++ b/src/plugins/platforms/mirclient/qmirclienttheme.h
@@ -41,7 +41,7 @@
#ifndef QMIRCLIENTTHEME_H
#define QMIRCLIENTTHEME_H
-#include <QtPlatformSupport/private/qgenericunixthemes_p.h>
+#include <QtThemeSupport/private/qgenericunixthemes_p.h>
class QMirClientTheme : public QGenericUnixTheme
{
diff --git a/src/plugins/platforms/offscreen/offscreen.pro b/src/plugins/platforms/offscreen/offscreen.pro
index 999550a7e1..6652cefd86 100644
--- a/src/plugins/platforms/offscreen/offscreen.pro
+++ b/src/plugins/platforms/offscreen/offscreen.pro
@@ -1,6 +1,10 @@
TARGET = qoffscreen
-QT += core-private gui-private platformsupport-private
+QT += \
+ core-private gui-private \
+ eventdispatcher_support-private fontdatabase_support-private
+
+DEFINES += QT_NO_FOREACH
SOURCES = main.cpp \
qoffscreenintegration.cpp \
@@ -13,9 +17,10 @@ HEADERS = qoffscreenintegration.h \
OTHER_FILES += offscreen.json
-contains(QT_CONFIG, xlib):contains(QT_CONFIG, opengl):!contains(QT_CONFIG, opengles2) {
+qtConfig(xlib):qtConfig(opengl):!qtConfig(opengles2) {
SOURCES += qoffscreenintegration_x11.cpp
HEADERS += qoffscreenintegration_x11.h
+ QT += glx_support-private
system(echo "Using X11 offscreen integration with GLX")
} else {
SOURCES += qoffscreenintegration_dummy.cpp
diff --git a/src/plugins/platforms/offscreen/qoffscreencommon.cpp b/src/plugins/platforms/offscreen/qoffscreencommon.cpp
index ed1a81c2b3..85422071aa 100644
--- a/src/plugins/platforms/offscreen/qoffscreencommon.cpp
+++ b/src/plugins/platforms/offscreen/qoffscreencommon.cpp
@@ -59,9 +59,9 @@ public:
void setPos(const QPoint &pos) Q_DECL_OVERRIDE
{
m_pos = pos;
- QWindowList wl = QGuiApplication::topLevelWindows();
+ const QWindowList wl = QGuiApplication::topLevelWindows();
QWindow *containing = 0;
- foreach (QWindow *w, wl) {
+ for (QWindow *w : wl) {
if (w->type() != Qt::Desktop && w->isExposed() && w->geometry().contains(pos)) {
containing = w;
break;
@@ -104,9 +104,9 @@ QPixmap QOffscreenScreen::grabWindow(WId id, int x, int y, int width, int height
QOffscreenWindow *window = QOffscreenWindow::windowForWinId(id);
if (!window || window->window()->type() == Qt::Desktop) {
- QWindowList wl = QGuiApplication::topLevelWindows();
+ const QWindowList wl = QGuiApplication::topLevelWindows();
QWindow *containing = 0;
- foreach (QWindow *w, wl) {
+ for (QWindow *w : wl) {
if (w->type() != Qt::Desktop && w->isExposed() && w->geometry().contains(rect)) {
containing = w;
break;
@@ -179,9 +179,8 @@ bool QOffscreenBackingStore::scroll(const QRegion &area, int dx, int dy)
if (m_image.isNull())
return false;
- const QVector<QRect> rects = area.rects();
- for (int i = 0; i < rects.size(); ++i)
- qt_scrollRectInImage(m_image, rects.at(i), QPoint(dx, dy));
+ for (const QRect &rect : area)
+ qt_scrollRectInImage(m_image, rect, QPoint(dx, dy));
return true;
}
@@ -213,11 +212,10 @@ QOffscreenBackingStore *QOffscreenBackingStore::backingStoreForWinId(WId id)
void QOffscreenBackingStore::clearHash()
{
- QList<WId> ids = m_windowAreaHash.keys();
- foreach (WId id, ids) {
- QHash<WId, QOffscreenBackingStore *>::iterator it = m_backingStoreForWinIdHash.find(id);
- if (it.value() == this)
- m_backingStoreForWinIdHash.remove(id);
+ for (auto it = m_windowAreaHash.cbegin(), end = m_windowAreaHash.cend(); it != end; ++it) {
+ const auto it2 = qAsConst(m_backingStoreForWinIdHash).find(it.key());
+ if (it2.value() == this)
+ m_backingStoreForWinIdHash.erase(it2);
}
m_windowAreaHash.clear();
}
diff --git a/src/plugins/platforms/offscreen/qoffscreenintegration.cpp b/src/plugins/platforms/offscreen/qoffscreenintegration.cpp
index 4c3d62a53b..56e6075cb2 100644
--- a/src/plugins/platforms/offscreen/qoffscreenintegration.cpp
+++ b/src/plugins/platforms/offscreen/qoffscreenintegration.cpp
@@ -42,14 +42,14 @@
#include "qoffscreencommon.h"
#if defined(Q_OS_UNIX)
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
#if defined(Q_OS_MAC)
#include <qpa/qplatformfontdatabase.h>
#else
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
#endif
#elif defined(Q_OS_WIN)
-#include <QtPlatformSupport/private/qbasicfontdatabase_p.h>
+#include <QtFontDatabaseSupport/private/qbasicfontdatabase_p.h>
#ifndef Q_OS_WINRT
#include <QtCore/private/qeventdispatcher_win_p.h>
#else
diff --git a/src/plugins/platforms/offscreen/qoffscreenintegration_x11.cpp b/src/plugins/platforms/offscreen/qoffscreenintegration_x11.cpp
index 2187eceed4..b46d94dfd3 100644
--- a/src/plugins/platforms/offscreen/qoffscreenintegration_x11.cpp
+++ b/src/plugins/platforms/offscreen/qoffscreenintegration_x11.cpp
@@ -45,7 +45,7 @@
#include <X11/Xlib.h>
#include <GL/glx.h>
-#include <QtPlatformSupport/private/qglxconvenience_p.h>
+#include <QtGlxSupport/private/qglxconvenience_p.h>
#include <qpa/qplatformsurface.h>
#include <qsurface.h>
diff --git a/src/plugins/platforms/openwfd/openwf.pro b/src/plugins/platforms/openwfd/openwf.pro
index 152e4f57d7..6012731b65 100644
--- a/src/plugins/platforms/openwfd/openwf.pro
+++ b/src/plugins/platforms/openwfd/openwf.pro
@@ -1,8 +1,8 @@
TARGET = qopenwf
-QT += core-private gui-private platformsupport-private
-
-CONFIG += qpa/genericunixfontdatabase
+QT += \
+ core-private gui-private \
+ eventdispatcher_support-private fontdatabase_support-private
HEADERS += \
qopenwfddevice.h \
@@ -31,7 +31,8 @@ SOURCES += \
qopenwfdportmode.cpp \
qopenwfdwindow.cpp
-LIBS += -lWFD -lgbm -lGLESv2 -lEGL
+LIBS += -lWFD
+QMAKE_USE += gbm opengl_es2 egl
PLUGIN_TYPE = platforms
PLUGIN_CLASS_NAME = QOpenWFDIntegrationPlugin
diff --git a/src/plugins/platforms/openwfd/qopenwfdintegration.cpp b/src/plugins/platforms/openwfd/qopenwfdintegration.cpp
index 71e2b381fc..4850ca2e45 100644
--- a/src/plugins/platforms/openwfd/qopenwfdintegration.cpp
+++ b/src/plugins/platforms/openwfd/qopenwfdintegration.cpp
@@ -51,8 +51,8 @@
#include <QtGui/QOpenGLContext>
#include <QtGui/QScreen>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
#include <stdio.h>
@@ -68,6 +68,7 @@ QOpenWFDIntegration::QOpenWFDIntegration()
int actualNumberOfDevices = wfdEnumerateDevices(devices,numberOfDevices,0);
Q_ASSERT(actualNumberOfDevices == numberOfDevices);
+ mDevices.reserve(actualNumberOfDevices);
for (int i = 0; i < actualNumberOfDevices; i++) {
mDevices.append(new QOpenWFDDevice(this,devices[i]));
}
diff --git a/src/plugins/platforms/platforms.pro b/src/plugins/platforms/platforms.pro
index a5b64636af..2a6e059243 100644
--- a/src/plugins/platforms/platforms.pro
+++ b/src/plugins/platforms/platforms.pro
@@ -1,24 +1,23 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += gui-private
android: SUBDIRS += android
!android: SUBDIRS += minimal
-!android:if(!win32|contains(QT_CONFIG, freetype)): SUBDIRS += offscreen
+!android:qtConfig(freetype): SUBDIRS += offscreen
-contains(QT_CONFIG, xcb) {
+qtConfig(xcb) {
SUBDIRS += xcb
}
-mac {
- ios: SUBDIRS += ios
- else: SUBDIRS += cocoa
-}
+uikit:!watchos: SUBDIRS += ios
+osx: SUBDIRS += cocoa
win32:!winrt: SUBDIRS += windows
winrt: SUBDIRS += winrt
-contains(QT_CONFIG, direct2d) {
+qtConfig(direct2d) {
SUBDIRS += direct2d
}
@@ -26,21 +25,27 @@ qnx {
SUBDIRS += qnx
}
-contains(QT_CONFIG, eglfs) {
+qtConfig(eglfs) {
SUBDIRS += eglfs
SUBDIRS += minimalegl
}
-contains(QT_CONFIG, directfb) {
+qtConfig(directfb) {
SUBDIRS += directfb
}
-contains(QT_CONFIG, linuxfb): SUBDIRS += linuxfb
+qtConfig(linuxfb): SUBDIRS += linuxfb
+
+unix:!android:!darwin: SUBDIRS += vnc
+
+freebsd {
+ SUBDIRS += bsdfb
+}
haiku {
SUBDIRS += haiku
}
-contains(QT_CONFIG, mirclient): SUBDIRS += mirclient
+qtConfig(mirclient): SUBDIRS += mirclient
-contains(QT_CONFIG, integrityfb): SUBDIRS += integrity
+qtConfig(integrityfb): SUBDIRS += integrity
diff --git a/src/plugins/platforms/qnx/qnx.pro b/src/plugins/platforms/qnx/qnx.pro
index 5a0f4f5c98..9da3d6811b 100644
--- a/src/plugins/platforms/qnx/qnx.pro
+++ b/src/plugins/platforms/qnx/qnx.pro
@@ -1,6 +1,8 @@
TARGET = qqnx
-QT += platformsupport-private core-private gui-private
+QT += \
+ core-private gui-private \
+ fontdatabase_support-private eventdispatcher_support-private egl_support-private
# Uncomment this to build with support for IMF once it becomes available in the BBNDK
#CONFIG += qqnx_imf
@@ -75,14 +77,14 @@ CONFIG(qqnx_screeneventthread) {
LIBS += -lscreen
-contains(QT_CONFIG, opengles2) {
+qtConfig(opengles2) {
SOURCES += qqnxglcontext.cpp \
qqnxeglwindow.cpp
HEADERS += qqnxglcontext.h \
qqnxeglwindow.h
- LIBS += -lEGL
+ QMAKE_USE += egl
}
CONFIG(qqnx_pps) {
@@ -100,7 +102,7 @@ CONFIG(qqnx_pps) {
qqnxnavigatoreventnotifier.h \
qqnxvirtualkeyboardpps.h
- LIBS += -lpps
+ QMAKE_USE += pps
!contains(DEFINES, QT_NO_CLIPBOARD): LIBS += -lclipboard
CONFIG(qqnx_imf) {
@@ -116,16 +118,11 @@ CONFIG(qqnx_pps) {
lgmon {
DEFINES += QQNX_LGMON
SOURCES += qqnxlgmon.cpp
- LIBS += -llgmon
+ QMAKE_USE += lgmon
}
OTHER_FILES += qnx.json
-QMAKE_CXXFLAGS += -I./private
-
-include (../../../platformsupport/eglconvenience/eglconvenience.pri)
-include (../../../platformsupport/fontdatabases/fontdatabases.pri)
-
PLUGIN_TYPE = platforms
PLUGIN_CLASS_NAME = QQnxIntegrationPlugin
!equals(TARGET, $$QT_DEFAULT_QPA_PLUGIN): PLUGIN_EXTENDS = -
diff --git a/src/plugins/platforms/qnx/qqnxbuttoneventnotifier.cpp b/src/plugins/platforms/qnx/qqnxbuttoneventnotifier.cpp
index a08ac2b839..a6236f2376 100644
--- a/src/plugins/platforms/qnx/qqnxbuttoneventnotifier.cpp
+++ b/src/plugins/platforms/qnx/qqnxbuttoneventnotifier.cpp
@@ -67,6 +67,7 @@ QQnxButtonEventNotifier::QQnxButtonEventNotifier(QObject *parent)
// fetch the new button ids
int enumeratorIndex = QQnxButtonEventNotifier::staticMetaObject.indexOfEnumerator(QByteArrayLiteral("ButtonId"));
QMetaEnum enumerator = QQnxButtonEventNotifier::staticMetaObject.enumerator(enumeratorIndex);
+ m_buttonKeys.reserve(ButtonCount - bid_minus);
for (int buttonId = bid_minus; buttonId < ButtonCount; ++buttonId) {
m_buttonKeys.append(enumerator.valueToKey(buttonId));
m_state[buttonId] = ButtonUp;
@@ -97,7 +98,7 @@ void QQnxButtonEventNotifier::start()
m_readNotifier = new QSocketNotifier(m_fd, QSocketNotifier::Read);
QObject::connect(m_readNotifier, SIGNAL(activated(int)), this, SLOT(updateButtonStates()));
- qButtonDebug() << "successfully connected to Navigator. fd =" << m_fd;
+ qButtonDebug("successfully connected to Navigator. fd = %d", m_fd);
}
void QQnxButtonEventNotifier::updateButtonStates()
@@ -121,7 +122,7 @@ void QQnxButtonEventNotifier::updateButtonStates()
// Ensure data is null terminated
buffer[bytes] = '\0';
- qButtonDebug() << "received PPS message:\n" << buffer;
+ qButtonDebug("received PPS message:\n%s", buffer);
// Process received message
QByteArray ppsData = QByteArray::fromRawData(buffer, bytes);
diff --git a/src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp b/src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp
index 79ff74b113..ce3a445d7c 100644
--- a/src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp
+++ b/src/plugins/platforms/qnx/qqnxinputcontext_imf.cpp
@@ -721,7 +721,7 @@ void QQnxInputContext::update(Qt::InputMethodQueries queries)
initEvent(&caretEvent.event, sInputSession, EVENT_CARET, CARET_POS_CHANGED, sizeof(caretEvent));
caretEvent.old_pos = lastCaret;
caretEvent.new_pos = m_caretPosition;
- qInputContextDebug() << "ictrl_dispatch_event caret changed" << lastCaret << m_caretPosition;
+ qInputContextDebug("ictrl_dispatch_event caret changed %d %d", lastCaret, m_caretPosition);
p_ictrl_dispatch_event(&caretEvent.event);
}
}
@@ -914,7 +914,7 @@ bool QQnxInputContext::handleKeyboardEvent(int flags, int sym, int mod, int scan
navigation_event_t navEvent;
initEvent(&navEvent.event, sInputSession, EVENT_NAVIGATION, key, sizeof(navEvent));
navEvent.magnitude = 1;
- qInputContextDebug() << "ictrl_dispatch_even navigation" << key;
+ qInputContextDebug("ictrl_dispatch_even navigation %d", key);
p_ictrl_dispatch_event(&navEvent.event);
}
} else {
@@ -927,7 +927,7 @@ bool QQnxInputContext::handleKeyboardEvent(int flags, int sym, int mod, int scan
keyEvent.sequence_id = sequenceId;
p_ictrl_dispatch_event(&keyEvent.event);
- qInputContextDebug() << "ictrl_dispatch_even key" << key;
+ qInputContextDebug("ictrl_dispatch_even key %d", key);
}
return true;
@@ -943,7 +943,7 @@ void QQnxInputContext::updateCursorPosition()
QCoreApplication::sendEvent(input, &query);
m_caretPosition = query.value(Qt::ImCursorPosition).toInt();
- qInputContextDebug() << m_caretPosition;
+ qInputContextDebug("%d", m_caretPosition);
}
void QQnxInputContext::endComposition()
@@ -1116,7 +1116,7 @@ int32_t QQnxInputContext::processEvent(event_t *event)
int flags = KEY_SYM_VALID | KEY_CAP_VALID;
if (event->event_id == IMF_KEY_DOWN)
flags |= KEY_DOWN;
- qInputContextDebug() << "EVENT_KEY" << flags << keySym;
+ qInputContextDebug("EVENT_KEY %d %d", flags, keySym);
QQnxScreenEventHandler::injectKeyboardEvent(flags, keySym, modifiers, 0, keyCap);
result = 0;
break;
@@ -1156,7 +1156,7 @@ int32_t QQnxInputContext::onCommitText(spannable_string_t *text, int32_t new_cur
int32_t QQnxInputContext::onDeleteSurroundingText(int32_t left_length, int32_t right_length)
{
- qInputContextDebug() << "L:" << left_length << " R:" << right_length;
+ qInputContextDebug("L: %d R: %d", int(left_length), int(right_length));
QObject *input = qGuiApp->focusObject();
if (!input)
diff --git a/src/plugins/platforms/qnx/qqnxintegration.cpp b/src/plugins/platforms/qnx/qqnxintegration.cpp
index e06d9a25c4..7229d7d2a8 100644
--- a/src/plugins/platforms/qnx/qqnxintegration.cpp
+++ b/src/plugins/platforms/qnx/qqnxintegration.cpp
@@ -453,11 +453,11 @@ void QQnxIntegration::createDisplays()
Q_SCREEN_CHECKERROR(result, "Failed to query display attachment");
if (!isAttached) {
- qIntegrationDebug() << "Skipping non-attached display" << i;
+ qIntegrationDebug("Skipping non-attached display %d", i);
continue;
}
- qIntegrationDebug() << "Creating screen for display" << i;
+ qIntegrationDebug("Creating screen for display %d", i);
createDisplay(displays[i], /*isPrimary=*/false);
} // of displays iteration
}
diff --git a/src/plugins/platforms/qnx/qqnxnavigatoreventhandler.cpp b/src/plugins/platforms/qnx/qqnxnavigatoreventhandler.cpp
index 4955938a3a..0e16764b79 100644
--- a/src/plugins/platforms/qnx/qqnxnavigatoreventhandler.cpp
+++ b/src/plugins/platforms/qnx/qqnxnavigatoreventhandler.cpp
@@ -63,14 +63,14 @@ bool QQnxNavigatorEventHandler::handleOrientationCheck(int angle)
{
// reply to navigator that (any) orientation is acceptable
// TODO: check if top window flags prohibit orientation change
- qNavigatorEventHandlerDebug() << "angle=" << angle;
+ qNavigatorEventHandlerDebug("angle=%d", angle);
return true;
}
void QQnxNavigatorEventHandler::handleOrientationChange(int angle)
{
// update screen geometry and reply to navigator that we're ready
- qNavigatorEventHandlerDebug() << "angle=" << angle;
+ qNavigatorEventHandlerDebug("angle=%d", angle);
emit rotationChanged(angle);
}
diff --git a/src/plugins/platforms/qnx/qqnxnavigatoreventnotifier.cpp b/src/plugins/platforms/qnx/qqnxnavigatoreventnotifier.cpp
index 9ccda2d94a..1f630863b7 100644
--- a/src/plugins/platforms/qnx/qqnxnavigatoreventnotifier.cpp
+++ b/src/plugins/platforms/qnx/qqnxnavigatoreventnotifier.cpp
@@ -91,8 +91,7 @@ void QQnxNavigatorEventNotifier::start()
errno = 0;
m_fd = open(navigatorControlPath, O_RDWR);
if (m_fd == -1) {
- qNavigatorEventNotifierDebug() << "failed to open navigator pps:"
- << strerror(errno);
+ qNavigatorEventNotifierDebug("failed to open navigator pps: %s", strerror(errno));
return;
}
diff --git a/src/plugins/platforms/qnx/qqnxnavigatorpps.cpp b/src/plugins/platforms/qnx/qqnxnavigatorpps.cpp
index fd1bbc4a85..d5234ca92f 100644
--- a/src/plugins/platforms/qnx/qqnxnavigatorpps.cpp
+++ b/src/plugins/platforms/qnx/qqnxnavigatorpps.cpp
@@ -79,7 +79,7 @@ bool QQnxNavigatorPps::openPpsConnection()
return false;
}
- qNavigatorDebug() << "successfully connected to Navigator. fd=" << m_fd;
+ qNavigatorDebug("successfully connected to Navigator. fd=%d", m_fd);
return true;
}
diff --git a/src/plugins/platforms/qnx/qqnxrasterbackingstore.cpp b/src/plugins/platforms/qnx/qqnxrasterbackingstore.cpp
index c9a89def41..a758bdf7f4 100644
--- a/src/plugins/platforms/qnx/qqnxrasterbackingstore.cpp
+++ b/src/plugins/platforms/qnx/qqnxrasterbackingstore.cpp
@@ -139,7 +139,7 @@ void QQnxRasterBackingStore::beginPaint(const QRegion &region)
platformWindow()->adjustBufferSize();
if (window()->requestedFormat().alphaBufferSize() > 0) {
- foreach (const QRect &r, region.rects()) {
+ for (const QRect &r : region) {
// Clear transparent regions
const int bg[] = {
SCREEN_BLIT_COLOR, 0x00000000,
diff --git a/src/plugins/platforms/qnx/qqnxrasterwindow.cpp b/src/plugins/platforms/qnx/qqnxrasterwindow.cpp
index 3ac3d23c88..7f11de228e 100644
--- a/src/plugins/platforms/qnx/qqnxrasterwindow.cpp
+++ b/src/plugins/platforms/qnx/qqnxrasterwindow.cpp
@@ -215,10 +215,9 @@ void QQnxRasterWindow::blitPreviousToCurrent(const QRegion &region, int dx, int
QQnxBuffer &previousBuffer = m_buffers[m_previousBufferIndex];
// Break down region into non-overlapping rectangles
- const QVector<QRect> rects = region.rects();
- for (int i = rects.size() - 1; i >= 0; i--) {
+ for (auto rit = region.rbegin(), rend = region.rend(); rit != rend; ++rit) {
// Clip rectangle to bounds of target
- const QRect rect = rects[i].intersected(currentBuffer.rect());
+ const QRect rect = rit->intersected(currentBuffer.rect());
if (rect.isEmpty())
continue;
diff --git a/src/plugins/platforms/qnx/qqnxscreen.cpp b/src/plugins/platforms/qnx/qqnxscreen.cpp
index 16ddcd784b..46df500330 100644
--- a/src/plugins/platforms/qnx/qqnxscreen.cpp
+++ b/src/plugins/platforms/qnx/qqnxscreen.cpp
@@ -90,7 +90,7 @@ static QSize determineScreenSize(screen_display_t display, bool primaryScreen) {
const QString envPhySizeStr = qgetenv("QQNX_PHYSICAL_SCREEN_SIZE");
if (!envPhySizeStr.isEmpty()) {
- const QStringList envPhySizeStrList = envPhySizeStr.split(QLatin1Char(','));
+ const auto envPhySizeStrList = envPhySizeStr.splitRef(QLatin1Char(','));
const int envWidth = envPhySizeStrList.size() == 2 ? envPhySizeStrList[0].toInt() : -1;
const int envHeight = envPhySizeStrList.size() == 2 ? envPhySizeStrList[1].toInt() : -1;
@@ -340,11 +340,12 @@ qreal QQnxScreen::refreshRate() const
qWarning("QQnxScreen: Failed to query screen mode. Using default value of 60Hz");
return 60.0;
}
- qScreenDebug() << "screen mode:" << endl
- << " width =" << displayMode.width << endl
- << " height =" << displayMode.height << endl
- << " refresh =" << displayMode.refresh << endl
- << " interlaced =" << displayMode.interlaced;
+ qScreenDebug("screen mode:\n"
+ " width = %u\n"
+ " height = %u\n"
+ " refresh = %u\n"
+ " interlaced = %u",
+ uint(displayMode.width), uint(displayMode.height), uint(displayMode.refresh), uint(displayMode.interlaced));
return static_cast<qreal>(displayMode.refresh);
}
@@ -384,10 +385,8 @@ Qt::ScreenOrientation QQnxScreen::orientation() const
QWindow *QQnxScreen::topLevelAt(const QPoint &point) const
{
- QListIterator<QQnxWindow*> it(m_childWindows);
- it.toBack();
- while (it.hasPrevious()) {
- QWindow *win = it.previous()->window();
+ for (auto it = m_childWindows.rbegin(), end = m_childWindows.rend(); it != end; ++it) {
+ QWindow *win = (*it)->window();
if (win->geometry().contains(point))
return win;
}
@@ -404,7 +403,7 @@ static bool isOrthogonal(int angle1, int angle2)
void QQnxScreen::setRotation(int rotation)
{
- qScreenDebug() << "orientation =" << rotation;
+ qScreenDebug("orientation = %d", rotation);
// Check if rotation changed
// We only want to rotate if we are the primary screen
if (m_currentRotation != rotation && isPrimaryScreen()) {
diff --git a/src/plugins/platforms/qnx/qqnxscreeneventhandler.cpp b/src/plugins/platforms/qnx/qqnxscreeneventhandler.cpp
index f7a87b6073..beda6e1a49 100644
--- a/src/plugins/platforms/qnx/qqnxscreeneventhandler.cpp
+++ b/src/plugins/platforms/qnx/qqnxscreeneventhandler.cpp
@@ -147,7 +147,7 @@ bool QQnxScreenEventHandler::handleEvent(screen_event_t event, int qnxType)
default:
// event ignored
- qScreenEventDebug() << "unknown event" << qnxType;
+ qScreenEventDebug("unknown event %d", qnxType);
return false;
}
diff --git a/src/plugins/platforms/qnx/qqnxvirtualkeyboardpps.cpp b/src/plugins/platforms/qnx/qqnxvirtualkeyboardpps.cpp
index 1174dc6ab3..025c03c058 100644
--- a/src/plugins/platforms/qnx/qqnxvirtualkeyboardpps.cpp
+++ b/src/plugins/platforms/qnx/qqnxvirtualkeyboardpps.cpp
@@ -164,7 +164,7 @@ void QQnxVirtualKeyboardPps::ppsDataReady()
{
ssize_t nread = qt_safe_read(m_fd, m_buffer, ms_bufferSize - 1);
- qVirtualKeyboardDebug() << "keyboardMessage size: " << nread;
+ qVirtualKeyboardDebug("keyboardMessage size: %zd", nread);
if (nread < 0){
connect(); // reconnect
return;
@@ -230,7 +230,7 @@ void QQnxVirtualKeyboardPps::handleKeyboardInfoMessage()
}
setHeight(newHeight);
- qVirtualKeyboardDebug() << "size=" << newHeight;
+ qVirtualKeyboardDebug("size=%d", newHeight);
}
bool QQnxVirtualKeyboardPps::showKeyboard()
diff --git a/src/plugins/platforms/qnx/qqnxwindow.cpp b/src/plugins/platforms/qnx/qqnxwindow.cpp
index 7b3a5ec70c..6fd0191e43 100644
--- a/src/plugins/platforms/qnx/qqnxwindow.cpp
+++ b/src/plugins/platforms/qnx/qqnxwindow.cpp
@@ -569,7 +569,7 @@ void QQnxWindow::requestActivateWindow()
for (int i = 1; i < windowList.size(); ++i)
windowList.at(i-1)->setFocus(windowList.at(i)->nativeHandle());
- windowList.last()->setFocus(windowList.last()->nativeHandle());
+ windowList.last()->setFocus(windowList.constLast()->nativeHandle());
}
screen_flush_context(m_screenContext, 0);
diff --git a/src/plugins/platforms/windows/qwindowsnativeimage.h b/src/plugins/platforms/vnc/main.cpp
index c96ca7937a..6ee8bf1ec6 100644
--- a/src/plugins/platforms/windows/qwindowsnativeimage.h
+++ b/src/plugins/platforms/vnc/main.cpp
@@ -3,7 +3,7 @@
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -37,42 +37,29 @@
**
****************************************************************************/
-#ifndef QWINDOWSNATIVEIMAGE_H
-#define QWINDOWSNATIVEIMAGE_H
-
-#include "qtwindows_additional.h"
-
-#include <QtGui/QImage>
+#include <qpa/qplatformintegrationplugin.h>
+#include "qvncintegration.h"
+#include "qvnc_p.h"
QT_BEGIN_NAMESPACE
-class QWindowsNativeImage
+class QVncIntegrationPlugin : public QPlatformIntegrationPlugin
{
- Q_DISABLE_COPY(QWindowsNativeImage)
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID QPlatformIntegrationFactoryInterface_iid FILE "vnc.json")
public:
- QWindowsNativeImage(int width, int height,
- QImage::Format format);
-
- ~QWindowsNativeImage();
-
- inline int width() const { return m_image.width(); }
- inline int height() const { return m_image.height(); }
-
- QImage &image() { return m_image; }
- const QImage &image() const { return m_image; }
-
- HDC hdc() const { return m_hdc; }
+ QPlatformIntegration *create(const QString&, const QStringList&) Q_DECL_OVERRIDE;
+};
- static QImage::Format systemFormat();
+QPlatformIntegration* QVncIntegrationPlugin::create(const QString& system, const QStringList& paramList)
+{
+ if (!system.compare(QLatin1String("vnc"), Qt::CaseInsensitive))
+ return new QVncIntegration(paramList);
-private:
- const HDC m_hdc;
- QImage m_image;
-
- HBITMAP m_bitmap;
- HBITMAP m_null_bitmap;
-};
+ return 0;
+}
QT_END_NAMESPACE
-#endif // QWINDOWSNATIVEIMAGE_H
+#include "main.moc"
+
diff --git a/src/plugins/platforms/vnc/qvnc.cpp b/src/plugins/platforms/vnc/qvnc.cpp
new file mode 100644
index 0000000000..a45bb1c19c
--- /dev/null
+++ b/src/plugins/platforms/vnc/qvnc.cpp
@@ -0,0 +1,685 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+#include "qvnc_p.h"
+#include "qvncscreen.h"
+#include "qvncclient.h"
+#include "QtNetwork/qtcpserver.h"
+#include "QtNetwork/qtcpsocket.h"
+#include <qendian.h>
+#include <qthread.h>
+
+#include <QtGui/qguiapplication.h>
+#include <QtGui/QWindow>
+
+#ifdef Q_OS_WIN
+#include <Winsock2.h>
+#else
+#include <arpa/inet.h>
+#endif
+
+#include <QtCore/QDebug>
+
+QT_BEGIN_NAMESPACE
+
+Q_LOGGING_CATEGORY(lcVnc, "qt.qpa.vnc");
+
+QVncDirtyMap::QVncDirtyMap(QVncScreen *screen)
+ : screen(screen), bytesPerPixel(0), numDirty(0)
+{
+ bytesPerPixel = (screen->depth() + 7) / 8;
+ bufferWidth = screen->geometry().width();
+ bufferHeight = screen->geometry().height();
+ bufferStride = bufferWidth * bytesPerPixel;
+ buffer = new uchar[bufferHeight * bufferStride];
+
+ mapWidth = (bufferWidth + MAP_TILE_SIZE - 1) / MAP_TILE_SIZE;
+ mapHeight = (bufferHeight + MAP_TILE_SIZE - 1) / MAP_TILE_SIZE;
+ numTiles = mapWidth * mapHeight;
+ map = new uchar[numTiles];
+}
+
+QVncDirtyMap::~QVncDirtyMap()
+{
+ delete[] map;
+ delete[] buffer;
+}
+
+void QVncDirtyMap::reset()
+{
+ memset(map, 1, numTiles);
+ memset(buffer, 0, bufferHeight * bufferStride);
+ numDirty = numTiles;
+}
+
+inline bool QVncDirtyMap::dirty(int x, int y) const
+{
+ return map[y * mapWidth + x];
+}
+
+inline void QVncDirtyMap::setClean(int x, int y)
+{
+ map[y * mapWidth + x] = 0;
+ --numDirty;
+}
+
+template <class T>
+void QVncDirtyMapOptimized<T>::setDirty(int tileX, int tileY, bool force)
+{
+ static bool alwaysForce = qEnvironmentVariableIsSet("QT_VNC_NO_COMPAREBUFFER");
+ if (alwaysForce)
+ force = true;
+
+ bool changed = false;
+
+ if (!force) {
+ const int lstep = bufferStride;
+ const int startX = tileX * MAP_TILE_SIZE;
+ const int startY = tileY * MAP_TILE_SIZE;
+ const uchar *scrn = screen->image()->constBits()
+ + startY * lstep + startX * bytesPerPixel;
+ uchar *old = buffer + startY * bufferStride + startX * sizeof(T);
+
+ const int tileHeight = (startY + MAP_TILE_SIZE > bufferHeight ?
+ bufferHeight - startY : MAP_TILE_SIZE);
+ const int tileWidth = (startX + MAP_TILE_SIZE > bufferWidth ?
+ bufferWidth - startX : MAP_TILE_SIZE);
+ const bool doInlines = (tileWidth == MAP_TILE_SIZE);
+
+ int y = tileHeight;
+
+ if (doInlines) { // hw: memcmp/memcpy is inlined when using constants
+ while (y) {
+ if (memcmp(old, scrn, sizeof(T) * MAP_TILE_SIZE)) {
+ changed = true;
+ break;
+ }
+ scrn += lstep;
+ old += bufferStride;
+ --y;
+ }
+
+ while (y) {
+ memcpy(old, scrn, sizeof(T) * MAP_TILE_SIZE);
+ scrn += lstep;
+ old += bufferStride;
+ --y;
+ }
+ } else {
+ while (y) {
+ if (memcmp(old, scrn, sizeof(T) * tileWidth)) {
+ changed = true;
+ break;
+ }
+ scrn += lstep;
+ old += bufferStride;
+ --y;
+ }
+
+ while (y) {
+ memcpy(old, scrn, sizeof(T) * tileWidth);
+ scrn += lstep;
+ old += bufferStride;
+ --y;
+ }
+ }
+ }
+
+ const int mapIndex = tileY * mapWidth + tileX;
+ if ((force || changed) && !map[mapIndex]) {
+ map[mapIndex] = 1;
+ ++numDirty;
+ }
+}
+
+template class QVncDirtyMapOptimized<unsigned char>;
+template class QVncDirtyMapOptimized<unsigned short>;
+template class QVncDirtyMapOptimized<unsigned int>;
+
+static const struct {
+ int keysym;
+ int keycode;
+} keyMap[] = {
+ { 0xff08, Qt::Key_Backspace },
+ { 0xff09, Qt::Key_Tab },
+ { 0xff0d, Qt::Key_Return },
+ { 0xff1b, Qt::Key_Escape },
+ { 0xff63, Qt::Key_Insert },
+ { 0xffff, Qt::Key_Delete },
+ { 0xff50, Qt::Key_Home },
+ { 0xff57, Qt::Key_End },
+ { 0xff55, Qt::Key_PageUp },
+ { 0xff56, Qt::Key_PageDown },
+ { 0xff51, Qt::Key_Left },
+ { 0xff52, Qt::Key_Up },
+ { 0xff53, Qt::Key_Right },
+ { 0xff54, Qt::Key_Down },
+ { 0xffbe, Qt::Key_F1 },
+ { 0xffbf, Qt::Key_F2 },
+ { 0xffc0, Qt::Key_F3 },
+ { 0xffc1, Qt::Key_F4 },
+ { 0xffc2, Qt::Key_F5 },
+ { 0xffc3, Qt::Key_F6 },
+ { 0xffc4, Qt::Key_F7 },
+ { 0xffc5, Qt::Key_F8 },
+ { 0xffc6, Qt::Key_F9 },
+ { 0xffc7, Qt::Key_F10 },
+ { 0xffc8, Qt::Key_F11 },
+ { 0xffc9, Qt::Key_F12 },
+ { 0xffe1, Qt::Key_Shift },
+ { 0xffe2, Qt::Key_Shift },
+ { 0xffe3, Qt::Key_Control },
+ { 0xffe4, Qt::Key_Control },
+ { 0xffe7, Qt::Key_Meta },
+ { 0xffe8, Qt::Key_Meta },
+ { 0xffe9, Qt::Key_Alt },
+ { 0xffea, Qt::Key_Alt },
+
+ { 0xffb0, Qt::Key_0 },
+ { 0xffb1, Qt::Key_1 },
+ { 0xffb2, Qt::Key_2 },
+ { 0xffb3, Qt::Key_3 },
+ { 0xffb4, Qt::Key_4 },
+ { 0xffb5, Qt::Key_5 },
+ { 0xffb6, Qt::Key_6 },
+ { 0xffb7, Qt::Key_7 },
+ { 0xffb8, Qt::Key_8 },
+ { 0xffb9, Qt::Key_9 },
+
+ { 0xff8d, Qt::Key_Return },
+ { 0xffaa, Qt::Key_Asterisk },
+ { 0xffab, Qt::Key_Plus },
+ { 0xffad, Qt::Key_Minus },
+ { 0xffae, Qt::Key_Period },
+ { 0xffaf, Qt::Key_Slash },
+
+ { 0xff95, Qt::Key_Home },
+ { 0xff96, Qt::Key_Left },
+ { 0xff97, Qt::Key_Up },
+ { 0xff98, Qt::Key_Right },
+ { 0xff99, Qt::Key_Down },
+ { 0xff9a, Qt::Key_PageUp },
+ { 0xff9b, Qt::Key_PageDown },
+ { 0xff9c, Qt::Key_End },
+ { 0xff9e, Qt::Key_Insert },
+ { 0xff9f, Qt::Key_Delete },
+
+ { 0, 0 }
+};
+
+void QRfbRect::read(QTcpSocket *s)
+{
+ quint16 buf[4];
+ s->read((char*)buf, 8);
+ x = ntohs(buf[0]);
+ y = ntohs(buf[1]);
+ w = ntohs(buf[2]);
+ h = ntohs(buf[3]);
+}
+
+void QRfbRect::write(QTcpSocket *s) const
+{
+ quint16 buf[4];
+ buf[0] = htons(x);
+ buf[1] = htons(y);
+ buf[2] = htons(w);
+ buf[3] = htons(h);
+ s->write((char*)buf, 8);
+}
+
+void QRfbPixelFormat::read(QTcpSocket *s)
+{
+ char buf[16];
+ s->read(buf, 16);
+ bitsPerPixel = buf[0];
+ depth = buf[1];
+ bigEndian = buf[2];
+ trueColor = buf[3];
+
+ quint16 a = ntohs(*(quint16 *)(buf + 4));
+ redBits = 0;
+ while (a) { a >>= 1; redBits++; }
+
+ a = ntohs(*(quint16 *)(buf + 6));
+ greenBits = 0;
+ while (a) { a >>= 1; greenBits++; }
+
+ a = ntohs(*(quint16 *)(buf + 8));
+ blueBits = 0;
+ while (a) { a >>= 1; blueBits++; }
+
+ redShift = buf[10];
+ greenShift = buf[11];
+ blueShift = buf[12];
+}
+
+void QRfbPixelFormat::write(QTcpSocket *s)
+{
+ char buf[16];
+ buf[0] = bitsPerPixel;
+ buf[1] = depth;
+ buf[2] = bigEndian;
+ buf[3] = trueColor;
+
+ quint16 a = 0;
+ for (int i = 0; i < redBits; i++) a = (a << 1) | 1;
+ *(quint16 *)(buf + 4) = htons(a);
+
+ a = 0;
+ for (int i = 0; i < greenBits; i++) a = (a << 1) | 1;
+ *(quint16 *)(buf + 6) = htons(a);
+
+ a = 0;
+ for (int i = 0; i < blueBits; i++) a = (a << 1) | 1;
+ *(quint16 *)(buf + 8) = htons(a);
+
+ buf[10] = redShift;
+ buf[11] = greenShift;
+ buf[12] = blueShift;
+ s->write(buf, 16);
+}
+
+
+void QRfbServerInit::setName(const char *n)
+{
+ delete[] name;
+ name = new char [strlen(n) + 1];
+ strcpy(name, n);
+}
+
+void QRfbServerInit::read(QTcpSocket *s)
+{
+ s->read((char *)&width, 2);
+ width = ntohs(width);
+ s->read((char *)&height, 2);
+ height = ntohs(height);
+ format.read(s);
+
+ quint32 len;
+ s->read((char *)&len, 4);
+ len = ntohl(len);
+
+ name = new char [len + 1];
+ s->read(name, len);
+ name[len] = '\0';
+}
+
+void QRfbServerInit::write(QTcpSocket *s)
+{
+ quint16 t = htons(width);
+ s->write((char *)&t, 2);
+ t = htons(height);
+ s->write((char *)&t, 2);
+ format.write(s);
+ quint32 len = strlen(name);
+ len = htonl(len);
+ s->write((char *)&len, 4);
+ s->write(name, strlen(name));
+}
+
+bool QRfbSetEncodings::read(QTcpSocket *s)
+{
+ if (s->bytesAvailable() < 3)
+ return false;
+
+ char tmp;
+ s->read(&tmp, 1); // padding
+ s->read((char *)&count, 2);
+ count = ntohs(count);
+
+ return true;
+}
+
+bool QRfbFrameBufferUpdateRequest::read(QTcpSocket *s)
+{
+ if (s->bytesAvailable() < 9)
+ return false;
+
+ s->read(&incremental, 1);
+ rect.read(s);
+
+ return true;
+}
+
+bool QRfbKeyEvent::read(QTcpSocket *s)
+{
+ if (s->bytesAvailable() < 7)
+ return false;
+
+ s->read(&down, 1);
+ quint16 tmp;
+ s->read((char *)&tmp, 2); // padding
+
+ quint32 key;
+ s->read((char *)&key, 4);
+ key = ntohl(key);
+
+ unicode = 0;
+ keycode = 0;
+ int i = 0;
+ while (keyMap[i].keysym && !keycode) {
+ if (keyMap[i].keysym == (int)key)
+ keycode = keyMap[i].keycode;
+ i++;
+ }
+
+ if (keycode >= ' ' && keycode <= '~')
+ unicode = keycode;
+
+ if (!keycode) {
+ if (key <= 0xff) {
+ unicode = key;
+ if (key >= 'a' && key <= 'z')
+ keycode = Qt::Key_A + key - 'a';
+ else if (key >= ' ' && key <= '~')
+ keycode = Qt::Key_Space + key - ' ';
+ }
+ }
+
+ return true;
+}
+
+bool QRfbPointerEvent::read(QTcpSocket *s)
+{
+ if (s->bytesAvailable() < 5)
+ return false;
+
+ char buttonMask;
+ s->read(&buttonMask, 1);
+ buttons = Qt::NoButton;
+ if (buttonMask & 1)
+ buttons |= Qt::LeftButton;
+ if (buttonMask & 2)
+ buttons |= Qt::MidButton;
+ if (buttonMask & 4)
+ buttons |= Qt::RightButton;
+
+ quint16 tmp;
+ s->read((char *)&tmp, 2);
+ x = ntohs(tmp);
+ s->read((char *)&tmp, 2);
+ y = ntohs(tmp);
+
+ return true;
+}
+
+bool QRfbClientCutText::read(QTcpSocket *s)
+{
+ if (s->bytesAvailable() < 7)
+ return false;
+
+ char tmp[3];
+ s->read(tmp, 3); // padding
+ s->read((char *)&length, 4);
+ length = ntohl(length);
+
+ return true;
+}
+
+void QRfbRawEncoder::write()
+{
+// QVncDirtyMap *map = server->dirtyMap();
+ QTcpSocket *socket = client->clientSocket();
+
+ const int bytesPerPixel = client->clientBytesPerPixel();
+
+ // create a region from the dirty rects and send the region's merged rects.
+ // ### use the tile map again
+ QRegion rgn = client->dirtyRegion();
+ qCDebug(lcVnc) << "QRfbRawEncoder::write()" << rgn;
+// if (map) {
+// for (int y = 0; y < map->mapHeight; ++y) {
+// for (int x = 0; x < map->mapWidth; ++x) {
+// if (!map->dirty(x, y))
+// continue;
+// rgn += QRect(x * MAP_TILE_SIZE, y * MAP_TILE_SIZE,
+// MAP_TILE_SIZE, MAP_TILE_SIZE);
+// map->setClean(x, y);
+// }
+// }
+
+// rgn &= QRect(0, 0, server->screen()->geometry().width(),
+// server->screen()->geometry().height());
+// }
+ const QVector<QRect> rects = rgn.rects();
+
+ {
+ const char tmp[2] = { 0, 0 }; // msg type, padding
+ socket->write(tmp, sizeof(tmp));
+ }
+
+ {
+ const quint16 count = htons(rects.size());
+ socket->write((char *)&count, sizeof(count));
+ }
+
+ if (rects.size() <= 0)
+ return;
+
+ const QImage screenImage = client->server()->screenImage();
+
+ for (const QRect &tileRect: rects) {
+ const QRfbRect rect(tileRect.x(), tileRect.y(),
+ tileRect.width(), tileRect.height());
+ rect.write(socket);
+
+ const quint32 encoding = htonl(0); // raw encoding
+ socket->write((char *)&encoding, sizeof(encoding));
+
+ int linestep = screenImage.bytesPerLine();
+ const uchar *screendata = screenImage.scanLine(rect.y)
+ + rect.x * screenImage.depth() / 8;
+
+ if (client->doPixelConversion()) {
+ const int bufferSize = rect.w * rect.h * bytesPerPixel;
+ if (bufferSize > buffer.size())
+ buffer.resize(bufferSize);
+
+ // convert pixels
+ char *b = buffer.data();
+ const int bstep = rect.w * bytesPerPixel;
+ for (int i = 0; i < rect.h; ++i) {
+ client->convertPixels(b, (const char*)screendata, rect.w);
+ screendata += linestep;
+ b += bstep;
+ }
+ socket->write(buffer.constData(), bufferSize);
+ } else {
+ for (int i = 0; i < rect.h; ++i) {
+ socket->write((const char*)screendata, rect.w * bytesPerPixel);
+ screendata += linestep;
+ }
+ }
+ if (socket->state() == QAbstractSocket::UnconnectedState)
+ break;
+ }
+ socket->flush();
+}
+
+QVncClientCursor::QVncClientCursor()
+{
+#ifndef QT_NO_CURSOR
+ QWindow *w = QGuiApplication::focusWindow();
+ QCursor c = w ? w->cursor() : QCursor(Qt::ArrowCursor);
+ changeCursor(&c, 0);
+#endif
+}
+
+QVncClientCursor::~QVncClientCursor()
+{
+}
+
+void QVncClientCursor::write(QVncClient *client) const
+{
+ QTcpSocket *socket = client->clientSocket();
+
+ // FramebufferUpdate header
+ {
+ const quint16 tmp[6] = { htons(0),
+ htons(1),
+ htons(hotspot.x()), htons(hotspot.y()),
+ htons(cursor.width()),
+ htons(cursor.height()) };
+ socket->write((char*)tmp, sizeof(tmp));
+
+ const qint32 encoding = qToBigEndian(-239);
+ socket->write((char*)(&encoding), sizeof(encoding));
+ }
+
+ if (cursor.isNull())
+ return;
+
+ // write pixels
+ Q_ASSERT(cursor.hasAlphaChannel());
+ const QImage img = cursor.convertToFormat(client->server()->screen()->format());
+ const int n = client->clientBytesPerPixel() * img.width();
+ char *buffer = new char[n];
+ for (int i = 0; i < img.height(); ++i) {
+ client->convertPixels(buffer, (const char*)img.scanLine(i), img.width());
+ socket->write(buffer, n);
+ }
+ delete[] buffer;
+
+ // write mask
+ const QImage bitmap = cursor.createAlphaMask().convertToFormat(QImage::Format_Mono);
+ Q_ASSERT(bitmap.depth() == 1);
+ Q_ASSERT(bitmap.size() == img.size());
+ const int width = (bitmap.width() + 7) / 8;
+ for (int i = 0; i < bitmap.height(); ++i)
+ socket->write((const char*)bitmap.scanLine(i), width);
+}
+
+void QVncClientCursor::changeCursor(QCursor *widgetCursor, QWindow *window)
+{
+ Q_UNUSED(window);
+#ifndef QT_NO_CURSOR
+ const Qt::CursorShape shape = widgetCursor ? widgetCursor->shape() : Qt::ArrowCursor;
+
+ if (shape == Qt::BitmapCursor) {
+ // application supplied cursor
+ hotspot = widgetCursor->hotSpot();
+ cursor = widgetCursor->pixmap().toImage();
+ } else {
+ // system cursor
+ QPlatformCursorImage platformImage(0, 0, 0, 0, 0, 0);
+ platformImage.set(shape);
+ cursor = *platformImage.image();
+ hotspot = platformImage.hotspot();
+ }
+#else // !QT_NO_CURSOR
+ Q_UNUSED(widgetCursor);
+#endif
+ for (auto client : clients)
+ client->setDirtyCursor();
+}
+
+void QVncClientCursor::addClient(QVncClient *client)
+{
+ if (!clients.contains(client))
+ clients.append(client);
+}
+
+uint QVncClientCursor::removeClient(QVncClient *client)
+{
+ clients.removeOne(client);
+ return clients.count();
+}
+
+QVncServer::QVncServer(QVncScreen *screen, quint16 port)
+ : qvnc_screen(screen)
+ , m_port(port)
+{
+ QMetaObject::invokeMethod(this, "init", Qt::QueuedConnection);
+}
+
+void QVncServer::init()
+{
+ serverSocket = new QTcpServer(this);
+ if (!serverSocket->listen(QHostAddress::Any, m_port))
+ qWarning() << "QVncServer could not connect:" << serverSocket->errorString();
+ else
+ qWarning("QVncServer created on port %d", m_port);
+
+ connect(serverSocket, SIGNAL(newConnection()), this, SLOT(newConnection()));
+
+}
+
+QVncServer::~QVncServer()
+{
+ for (auto client : clients) {
+ delete client;
+ }
+}
+
+void QVncServer::setDirty()
+{
+ for (auto client : clients) {
+ client->setDirty(qvnc_screen->dirtyRegion);
+ }
+ qvnc_screen->clearDirty();
+}
+
+
+void QVncServer::newConnection()
+{
+ auto clientSocket = serverSocket->nextPendingConnection();
+ clients.append(new QVncClient(clientSocket, this));
+
+ dirtyMap()->reset();
+
+ qCDebug(lcVnc) << "new Connection from: " << clientSocket->localAddress();
+
+ qvnc_screen->setPowerState(QPlatformScreen::PowerStateOn);
+}
+
+void QVncServer::discardClient(QVncClient *client)
+{
+ clients.removeOne(client);
+ client->deleteLater();
+ if (clients.isEmpty()) {
+ qvnc_screen->disableClientCursor(client);
+ qvnc_screen->setPowerState(QPlatformScreen::PowerStateOff);
+ }
+}
+
+inline QImage QVncServer::screenImage() const
+{
+ return *qvnc_screen->image();
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/vnc/qvnc_p.h b/src/plugins/platforms/vnc/qvnc_p.h
new file mode 100644
index 0000000000..1c44cd1569
--- /dev/null
+++ b/src/plugins/platforms/vnc/qvnc_p.h
@@ -0,0 +1,417 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QVNC_P_H
+#define QVNC_P_H
+
+#include "qvncscreen.h"
+
+#include <QtCore/QLoggingCategory>
+#include <QtCore/qbytearray.h>
+#include <QtCore/qvarlengtharray.h>
+#include <qpa/qplatformcursor.h>
+
+QT_BEGIN_NAMESPACE
+
+Q_DECLARE_LOGGING_CATEGORY(lcVnc)
+
+class QTcpSocket;
+class QTcpServer;
+
+class QVncScreen;
+class QVncServer;
+class QVncClientCursor;
+class QVncClient;
+
+// This fits with the VNC hextile messages
+#define MAP_TILE_SIZE 16
+
+class QVncDirtyMap
+{
+public:
+ QVncDirtyMap(QVncScreen *screen);
+ virtual ~QVncDirtyMap();
+
+ void reset();
+ bool dirty(int x, int y) const;
+ virtual void setDirty(int x, int y, bool force = false) = 0;
+ void setClean(int x, int y);
+
+ QVncScreen *screen;
+ int bytesPerPixel;
+ int numDirty;
+ int mapWidth;
+ int mapHeight;
+
+protected:
+ uchar *map;
+ uchar *buffer;
+ int bufferWidth;
+ int bufferHeight;
+ int bufferStride;
+ int numTiles;
+};
+
+template <class T>
+class QVncDirtyMapOptimized : public QVncDirtyMap
+{
+public:
+ QVncDirtyMapOptimized(QVncScreen *screen) : QVncDirtyMap(screen) {}
+ ~QVncDirtyMapOptimized() {}
+
+ void setDirty(int x, int y, bool force = false);
+};
+
+
+class QRfbRect
+{
+public:
+ QRfbRect() {}
+ QRfbRect(quint16 _x, quint16 _y, quint16 _w, quint16 _h) {
+ x = _x; y = _y; w = _w; h = _h;
+ }
+
+ void read(QTcpSocket *s);
+ void write(QTcpSocket *s) const;
+
+ quint16 x;
+ quint16 y;
+ quint16 w;
+ quint16 h;
+};
+
+class QRfbPixelFormat
+{
+public:
+ static int size() { return 16; }
+
+ void read(QTcpSocket *s);
+ void write(QTcpSocket *s);
+
+ int bitsPerPixel;
+ int depth;
+ bool bigEndian;
+ bool trueColor;
+ int redBits;
+ int greenBits;
+ int blueBits;
+ int redShift;
+ int greenShift;
+ int blueShift;
+};
+
+class QRfbServerInit
+{
+public:
+ QRfbServerInit() { name = 0; }
+ ~QRfbServerInit() { delete[] name; }
+
+ int size() const { return QRfbPixelFormat::size() + 8 + strlen(name); }
+ void setName(const char *n);
+
+ void read(QTcpSocket *s);
+ void write(QTcpSocket *s);
+
+ quint16 width;
+ quint16 height;
+ QRfbPixelFormat format;
+ char *name;
+};
+
+class QRfbSetEncodings
+{
+public:
+ bool read(QTcpSocket *s);
+
+ quint16 count;
+};
+
+class QRfbFrameBufferUpdateRequest
+{
+public:
+ bool read(QTcpSocket *s);
+
+ char incremental;
+ QRfbRect rect;
+};
+
+class QRfbKeyEvent
+{
+public:
+ bool read(QTcpSocket *s);
+
+ char down;
+ int keycode;
+ int unicode;
+};
+
+class QRfbPointerEvent
+{
+public:
+ bool read(QTcpSocket *s);
+
+ Qt::MouseButtons buttons;
+ quint16 x;
+ quint16 y;
+};
+
+class QRfbClientCutText
+{
+public:
+ bool read(QTcpSocket *s);
+
+ quint32 length;
+};
+
+class QRfbEncoder
+{
+public:
+ QRfbEncoder(QVncClient *s) : client(s) {}
+ virtual ~QRfbEncoder() {}
+
+ virtual void write() = 0;
+
+protected:
+ QVncClient *client;
+};
+
+class QRfbRawEncoder : public QRfbEncoder
+{
+public:
+ QRfbRawEncoder(QVncClient *s) : QRfbEncoder(s) {}
+
+ void write();
+
+private:
+ QByteArray buffer;
+};
+
+template <class SRC> class QRfbHextileEncoder;
+
+template <class SRC>
+class QRfbSingleColorHextile
+{
+public:
+ QRfbSingleColorHextile(QRfbHextileEncoder<SRC> *e) : encoder(e) {}
+ bool read(const uchar *data, int width, int height, int stride);
+ void write(QTcpSocket *socket) const;
+
+private:
+ QRfbHextileEncoder<SRC> *encoder;
+};
+
+template <class SRC>
+class QRfbDualColorHextile
+{
+public:
+ QRfbDualColorHextile(QRfbHextileEncoder<SRC> *e) : encoder(e) {}
+ bool read(const uchar *data, int width, int height, int stride);
+ void write(QTcpSocket *socket) const;
+
+private:
+ struct Rect {
+ quint8 xy;
+ quint8 wh;
+ } Q_PACKED rects[8 * 16];
+
+ quint8 numRects;
+ QRfbHextileEncoder<SRC> *encoder;
+
+private:
+ inline int lastx() const { return rectx(numRects); }
+ inline int lasty() const { return recty(numRects); }
+ inline int rectx(int r) const { return rects[r].xy >> 4; }
+ inline int recty(int r) const { return rects[r].xy & 0x0f; }
+ inline int width(int r) const { return (rects[r].wh >> 4) + 1; }
+ inline int height(int r) const { return (rects[r].wh & 0x0f) + 1; }
+
+ inline void setX(int r, int x) {
+ rects[r].xy = (x << 4) | (rects[r].xy & 0x0f);
+ }
+ inline void setY(int r, int y) {
+ rects[r].xy = (rects[r].xy & 0xf0) | y;
+ }
+ inline void setWidth(int r, int width) {
+ rects[r].wh = ((width - 1) << 4) | (rects[r].wh & 0x0f);
+ }
+ inline void setHeight(int r, int height) {
+ rects[r].wh = (rects[r].wh & 0xf0) | (height - 1);
+ }
+
+ inline void setWidth(int width) { setWidth(numRects, width); }
+ inline void setHeight(int height) { setHeight(numRects, height); }
+ inline void setX(int x) { setX(numRects, x); }
+ inline void setY(int y) { setY(numRects, y); }
+ void next();
+};
+
+template <class SRC>
+class QRfbMultiColorHextile
+{
+public:
+ QRfbMultiColorHextile(QRfbHextileEncoder<SRC> *e) : encoder(e) {}
+ bool read(const uchar *data, int width, int height, int stride);
+ void write(QTcpSocket *socket) const;
+
+private:
+ inline quint8* rect(int r) {
+ return rects.data() + r * (bpp + 2);
+ }
+ inline const quint8* rect(int r) const {
+ return rects.constData() + r * (bpp + 2);
+ }
+ inline void setX(int r, int x) {
+ quint8 *ptr = rect(r) + bpp;
+ *ptr = (x << 4) | (*ptr & 0x0f);
+ }
+ inline void setY(int r, int y) {
+ quint8 *ptr = rect(r) + bpp;
+ *ptr = (*ptr & 0xf0) | y;
+ }
+ void setColor(SRC color);
+ inline int rectx(int r) const {
+ const quint8 *ptr = rect(r) + bpp;
+ return *ptr >> 4;
+ }
+ inline int recty(int r) const {
+ const quint8 *ptr = rect(r) + bpp;
+ return *ptr & 0x0f;
+ }
+ inline void setWidth(int r, int width) {
+ quint8 *ptr = rect(r) + bpp + 1;
+ *ptr = ((width - 1) << 4) | (*ptr & 0x0f);
+ }
+ inline void setHeight(int r, int height) {
+ quint8 *ptr = rect(r) + bpp + 1;
+ *ptr = (*ptr & 0xf0) | (height - 1);
+ }
+
+ bool beginRect();
+ void endRect();
+
+ static const int maxRectsSize = 16 * 16;
+ QVarLengthArray<quint8, maxRectsSize> rects;
+
+ quint8 bpp;
+ quint8 numRects;
+ QRfbHextileEncoder<SRC> *encoder;
+};
+
+template <class SRC>
+class QRfbHextileEncoder : public QRfbEncoder
+{
+public:
+ QRfbHextileEncoder(QVncServer *s);
+ void write();
+
+private:
+ enum SubEncoding {
+ Raw = 1,
+ BackgroundSpecified = 2,
+ ForegroundSpecified = 4,
+ AnySubrects = 8,
+ SubrectsColoured = 16
+ };
+
+ QByteArray buffer;
+ QRfbSingleColorHextile<SRC> singleColorHextile;
+ QRfbDualColorHextile<SRC> dualColorHextile;
+ QRfbMultiColorHextile<SRC> multiColorHextile;
+
+ SRC bg;
+ SRC fg;
+ bool newBg;
+ bool newFg;
+
+ friend class QRfbSingleColorHextile<SRC>;
+ friend class QRfbDualColorHextile<SRC>;
+ friend class QRfbMultiColorHextile<SRC>;
+};
+
+class QVncClientCursor : public QPlatformCursor
+{
+public:
+ QVncClientCursor();
+ ~QVncClientCursor();
+
+ void write(QVncClient *client) const;
+
+ void changeCursor(QCursor *widgetCursor, QWindow *window);
+
+ void addClient(QVncClient *client);
+ uint removeClient(QVncClient *client);
+
+ QImage cursor;
+ QPoint hotspot;
+ QVector<QVncClient *> clients;
+};
+
+
+class QVncServer : public QObject
+{
+ Q_OBJECT
+public:
+ QVncServer(QVncScreen *screen, quint16 port = 5900);
+ ~QVncServer();
+
+ enum ServerMsg { FramebufferUpdate = 0,
+ SetColourMapEntries = 1 };
+
+ void setDirty();
+
+
+ inline QVncScreen* screen() const { return qvnc_screen; }
+ inline QVncDirtyMap* dirtyMap() const { return qvnc_screen->dirty; }
+ QImage screenImage() const;
+ void discardClient(QVncClient *client);
+
+private slots:
+ void newConnection();
+ void init();
+
+private:
+ QTcpServer *serverSocket;
+ QVector<QVncClient*> clients;
+ QVncScreen *qvnc_screen;
+ quint16 m_port;
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/plugins/platforms/vnc/qvncclient.cpp b/src/plugins/platforms/vnc/qvncclient.cpp
new file mode 100644
index 0000000000..dae3e83f37
--- /dev/null
+++ b/src/plugins/platforms/vnc/qvncclient.cpp
@@ -0,0 +1,662 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qvncclient.h"
+#include "qvnc_p.h"
+
+#include <QtNetwork/QTcpSocket>
+#include <QtCore/QCoreApplication>
+
+#include <qpa/qwindowsysteminterface.h>
+#include <QtGui/qguiapplication.h>
+
+#ifdef Q_OS_WIN
+#include <Winsock2.h>
+#else
+#include <arpa/inet.h>
+#endif
+
+QT_BEGIN_NAMESPACE
+
+QVncClient::QVncClient(QTcpSocket *clientSocket, QVncServer *server)
+ : QObject(server)
+ , m_server(server)
+ , m_clientSocket(clientSocket)
+ , m_encoder(nullptr)
+ , m_msgType(0)
+ , m_handleMsg(false)
+ , m_encodingsPending(0)
+ , m_cutTextPending(0)
+ , m_supportHextile(false)
+ , m_wantUpdate(false)
+ , m_keymod(0)
+ , m_dirtyCursor(false)
+ , m_updatePending(false)
+ , m_protocolVersion(V3_3)
+{
+ connect(m_clientSocket,SIGNAL(readyRead()),this,SLOT(readClient()));
+ connect(m_clientSocket,SIGNAL(disconnected()),this,SLOT(discardClient()));
+
+ // send protocol version
+ const char *proto = "RFB 003.003\n";
+ m_clientSocket->write(proto, 12);
+ m_state = Protocol;
+}
+
+QVncClient::~QVncClient()
+{
+ delete m_encoder;
+}
+
+QTcpSocket *QVncClient::clientSocket() const
+{
+ return m_clientSocket;
+}
+
+void QVncClient::setDirty(const QRegion &region)
+{
+ m_dirtyRegion += region;
+ if (m_state == Connected &&
+ ((m_server->dirtyMap()->numDirty > 0) || m_dirtyCursor)) {
+ scheduleUpdate();
+ }
+}
+
+void QVncClient::convertPixels(char *dst, const char *src, int count) const
+{
+ const int screendepth = m_server->screen()->depth();
+
+ // cutoffs
+#if Q_BYTE_ORDER == Q_BIG_ENDIAN
+ if (!m_swapBytes)
+#endif
+ if (m_sameEndian) {
+ if (screendepth == m_pixelFormat.bitsPerPixel) { // memcpy cutoffs
+
+ switch (screendepth) {
+ case 32:
+ memcpy(dst, src, count * sizeof(quint32));
+ return;
+ case 16:
+ if (m_pixelFormat.redBits == 5
+ && m_pixelFormat.greenBits == 6
+ && m_pixelFormat.blueBits == 5)
+ {
+ memcpy(dst, src, count * sizeof(quint16));
+ return;
+ }
+ }
+ }
+ }
+
+ const int bytesPerPixel = (m_pixelFormat.bitsPerPixel + 7) / 8;
+
+ for (int i = 0; i < count; ++i) {
+ int r, g, b;
+
+ switch (screendepth) {
+ case 8: {
+ QRgb rgb = m_server->screen()->image()->colorTable()[int(*src)];
+ r = qRed(rgb);
+ g = qGreen(rgb);
+ b = qBlue(rgb);
+ src++;
+ break;
+ }
+ case 16: {
+ quint16 p = *reinterpret_cast<const quint16*>(src);
+#if Q_BYTE_ORDER == Q_BIG_ENDIAN
+ if (swapBytes)
+ p = ((p & 0xff) << 8) | ((p & 0xff00) >> 8);
+#endif
+ r = (p >> 11) & 0x1f;
+ g = (p >> 5) & 0x3f;
+ b = p & 0x1f;
+ r <<= 3;
+ g <<= 2;
+ b <<= 3;
+ src += sizeof(quint16);
+ break;
+ }
+ case 32: {
+ quint32 p = *reinterpret_cast<const quint32*>(src);
+ r = (p >> 16) & 0xff;
+ g = (p >> 8) & 0xff;
+ b = p & 0xff;
+ src += sizeof(quint32);
+ break;
+ }
+ default: {
+ r = g = b = 0;
+ qWarning("QVNCServer: don't support %dbpp display", screendepth);
+ return;
+ }
+ }
+
+#if Q_BYTE_ORDER == Q_BIG_ENDIAN
+ if (m_swapBytes)
+ qSwap(r, b);
+#endif
+
+ r >>= (8 - m_pixelFormat.redBits);
+ g >>= (8 - m_pixelFormat.greenBits);
+ b >>= (8 - m_pixelFormat.blueBits);
+
+ int pixel = (r << m_pixelFormat.redShift) |
+ (g << m_pixelFormat.greenShift) |
+ (b << m_pixelFormat.blueShift);
+
+ if (m_sameEndian || m_pixelFormat.bitsPerPixel == 8) {
+ memcpy(dst, &pixel, bytesPerPixel);
+ dst += bytesPerPixel;
+ continue;
+ }
+
+
+ if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
+ switch (m_pixelFormat.bitsPerPixel) {
+ case 16:
+ pixel = (((pixel & 0x0000ff00) << 8) |
+ ((pixel & 0x000000ff) << 24));
+ break;
+ case 32:
+ pixel = (((pixel & 0xff000000) >> 24) |
+ ((pixel & 0x00ff0000) >> 8) |
+ ((pixel & 0x0000ff00) << 8) |
+ ((pixel & 0x000000ff) << 24));
+ break;
+ default:
+ qWarning("Cannot handle %d bpp client", m_pixelFormat.bitsPerPixel);
+ }
+ } else { // QSysInfo::ByteOrder == QSysInfo::LittleEndian
+ switch (m_pixelFormat.bitsPerPixel) {
+ case 16:
+ pixel = (((pixel & 0xff000000) >> 8) |
+ ((pixel & 0x00ff0000) << 8));
+ break;
+ case 32:
+ pixel = (((pixel & 0xff000000) >> 24) |
+ ((pixel & 0x00ff0000) >> 8) |
+ ((pixel & 0x0000ff00) << 8) |
+ ((pixel & 0x000000ff) << 24));
+ break;
+ default:
+ qWarning("Cannot handle %d bpp client",
+ m_pixelFormat.bitsPerPixel);
+ break;
+ }
+ }
+ memcpy(dst, &pixel, bytesPerPixel);
+ dst += bytesPerPixel;
+ }
+}
+
+void QVncClient::readClient()
+{
+ qCDebug(lcVnc) << "readClient" << m_state;
+ switch (m_state) {
+ case Disconnected:
+
+ break;
+ case Protocol:
+ if (m_clientSocket->bytesAvailable() >= 12) {
+ char proto[13];
+ m_clientSocket->read(proto, 12);
+ proto[12] = '\0';
+ qCDebug(lcVnc, "Client protocol version %s", proto);
+ if (!strcmp(proto, "RFB 003.008\n")) {
+ m_protocolVersion = V3_8;
+ } else if (!strcmp(proto, "RFB 003.007\n")) {
+ m_protocolVersion = V3_7;
+ } else {
+ m_protocolVersion = V3_3;
+ }
+
+ if (m_protocolVersion == V3_3) {
+ // No authentication
+ quint32 auth = htonl(1);
+ m_clientSocket->write((char *) &auth, sizeof(auth));
+ m_state = Init;
+ }
+ }
+ break;
+ case Authentication:
+
+ break;
+ case Init:
+ if (m_clientSocket->bytesAvailable() >= 1) {
+ quint8 shared;
+ m_clientSocket->read((char *) &shared, 1);
+
+ // Server Init msg
+ QRfbServerInit sim;
+ QRfbPixelFormat &format = sim.format;
+ switch (m_server->screen()->depth()) {
+ case 32:
+ format.bitsPerPixel = 32;
+ format.depth = 32;
+ format.bigEndian = 0;
+ format.trueColor = true;
+ format.redBits = 8;
+ format.greenBits = 8;
+ format.blueBits = 8;
+ format.redShift = 16;
+ format.greenShift = 8;
+ format.blueShift = 0;
+ break;
+
+ case 24:
+ format.bitsPerPixel = 24;
+ format.depth = 24;
+ format.bigEndian = 0;
+ format.trueColor = true;
+ format.redBits = 8;
+ format.greenBits = 8;
+ format.blueBits = 8;
+ format.redShift = 16;
+ format.greenShift = 8;
+ format.blueShift = 0;
+ break;
+
+ case 18:
+ format.bitsPerPixel = 24;
+ format.depth = 18;
+ format.bigEndian = 0;
+ format.trueColor = true;
+ format.redBits = 6;
+ format.greenBits = 6;
+ format.blueBits = 6;
+ format.redShift = 12;
+ format.greenShift = 6;
+ format.blueShift = 0;
+ break;
+
+ case 16:
+ format.bitsPerPixel = 16;
+ format.depth = 16;
+ format.bigEndian = 0;
+ format.trueColor = true;
+ format.redBits = 5;
+ format.greenBits = 6;
+ format.blueBits = 5;
+ format.redShift = 11;
+ format.greenShift = 5;
+ format.blueShift = 0;
+ break;
+
+ case 15:
+ format.bitsPerPixel = 16;
+ format.depth = 15;
+ format.bigEndian = 0;
+ format.trueColor = true;
+ format.redBits = 5;
+ format.greenBits = 5;
+ format.blueBits = 5;
+ format.redShift = 10;
+ format.greenShift = 5;
+ format.blueShift = 0;
+ break;
+
+ case 12:
+ format.bitsPerPixel = 16;
+ format.depth = 12;
+ format.bigEndian = 0;
+ format.trueColor = true;
+ format.redBits = 4;
+ format.greenBits = 4;
+ format.blueBits = 4;
+ format.redShift = 8;
+ format.greenShift = 4;
+ format.blueShift = 0;
+ break;
+
+ case 8:
+ case 4:
+ format.bitsPerPixel = 8;
+ format.depth = 8;
+ format.bigEndian = 0;
+ format.trueColor = false;
+ format.redBits = 0;
+ format.greenBits = 0;
+ format.blueBits = 0;
+ format.redShift = 0;
+ format.greenShift = 0;
+ format.blueShift = 0;
+ break;
+
+ default:
+ qWarning("QVNC cannot drive depth %d", m_server->screen()->depth());
+ discardClient();
+ return;
+ }
+ sim.width = m_server->screen()->geometry().width();
+ sim.height = m_server->screen()->geometry().height();
+ sim.setName("Qt for Embedded Linux VNC Server");
+ sim.write(m_clientSocket);
+ m_state = Connected;
+ }
+ break;
+
+ case Connected:
+ do {
+ if (!m_handleMsg) {
+ m_clientSocket->read((char *)&m_msgType, 1);
+ m_handleMsg = true;
+ }
+ if (m_handleMsg) {
+ switch (m_msgType ) {
+ case SetPixelFormat:
+ setPixelFormat();
+ break;
+ case FixColourMapEntries:
+ qWarning("Not supported: FixColourMapEntries");
+ m_handleMsg = false;
+ break;
+ case SetEncodings:
+ setEncodings();
+ break;
+ case FramebufferUpdateRequest:
+ frameBufferUpdateRequest();
+ break;
+ case KeyEvent:
+ keyEvent();
+ break;
+ case PointerEvent:
+ pointerEvent();
+ break;
+ case ClientCutText:
+ clientCutText();
+ break;
+ default:
+ qWarning("Unknown message type: %d", (int)m_msgType);
+ m_handleMsg = false;
+ }
+ }
+ } while (!m_handleMsg && m_clientSocket->bytesAvailable());
+ break;
+ default:
+ break;
+ }
+}
+
+void QVncClient::discardClient()
+{
+ m_state = Disconnected;
+ m_server->discardClient(this);
+}
+
+void QVncClient::checkUpdate()
+{
+ if (!m_wantUpdate)
+ return;
+
+ if (m_dirtyCursor) {
+ m_server->screen()->clientCursor->write(this);
+ m_dirtyCursor = false;
+ m_wantUpdate = false;
+ return;
+ }
+
+ if (!m_dirtyRegion.isEmpty()) {
+ if (m_encoder)
+ m_encoder->write();
+ m_wantUpdate = false;
+ m_dirtyRegion = QRegion();
+ }
+}
+
+void QVncClient::scheduleUpdate()
+{
+ if (!m_updatePending) {
+ m_updatePending = true;
+ QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
+ }
+}
+
+bool QVncClient::event(QEvent *event)
+{
+ if (event->type() == QEvent::UpdateRequest) {
+ m_updatePending = false;
+ checkUpdate();
+ return true;
+ }
+ return QObject::event(event);
+}
+
+void QVncClient::setPixelFormat()
+{
+ if (m_clientSocket->bytesAvailable() >= 19) {
+ char buf[3];
+ m_clientSocket->read(buf, 3); // just padding
+ m_pixelFormat.read(m_clientSocket);
+ qCDebug(lcVnc, "Want format: %d %d %d %d %d %d %d %d %d %d",
+ int(m_pixelFormat.bitsPerPixel),
+ int(m_pixelFormat.depth),
+ int(m_pixelFormat.bigEndian),
+ int(m_pixelFormat.trueColor),
+ int(m_pixelFormat.redBits),
+ int(m_pixelFormat.greenBits),
+ int(m_pixelFormat.blueBits),
+ int(m_pixelFormat.redShift),
+ int(m_pixelFormat.greenShift),
+ int(m_pixelFormat.blueShift));
+ if (!m_pixelFormat.trueColor) {
+ qWarning("Can only handle true color clients");
+ discardClient();
+ }
+ m_handleMsg = false;
+ m_sameEndian = (QSysInfo::ByteOrder == QSysInfo::BigEndian) == !!m_pixelFormat.bigEndian;
+ m_needConversion = pixelConversionNeeded();
+#if Q_BYTE_ORDER == Q_BIG_ENDIAN
+ m_swapBytes = qvnc_screen->swapBytes();
+#endif
+ }
+}
+
+void QVncClient::setEncodings()
+{
+ QRfbSetEncodings enc;
+
+ if (!m_encodingsPending && enc.read(m_clientSocket)) {
+ m_encodingsPending = enc.count;
+ if (!m_encodingsPending)
+ m_handleMsg = false;
+ }
+
+ if (m_encoder) {
+ delete m_encoder;
+ m_encoder = nullptr;
+ }
+
+ enum Encodings {
+ Raw = 0,
+ CopyRect = 1,
+ RRE = 2,
+ CoRRE = 4,
+ Hextile = 5,
+ ZRLE = 16,
+ Cursor = -239,
+ DesktopSize = -223
+ };
+
+ if (m_encodingsPending && (unsigned)m_clientSocket->bytesAvailable() >=
+ m_encodingsPending * sizeof(quint32)) {
+ for (int i = 0; i < m_encodingsPending; ++i) {
+ qint32 enc;
+ m_clientSocket->read((char *)&enc, sizeof(qint32));
+ enc = ntohl(enc);
+ qCDebug(lcVnc, "QVncServer::setEncodings: %d", enc);
+ switch (enc) {
+ case Raw:
+ if (!m_encoder) {
+ m_encoder = new QRfbRawEncoder(this);
+ qCDebug(lcVnc, "QVncServer::setEncodings: using raw");
+ }
+ break;
+ case CopyRect:
+ m_supportCopyRect = true;
+ break;
+ case RRE:
+ m_supportRRE = true;
+ break;
+ case CoRRE:
+ m_supportCoRRE = true;
+ break;
+ case Hextile:
+ m_supportHextile = true;
+ if (m_encoder)
+ break;
+ break;
+ case ZRLE:
+ m_supportZRLE = true;
+ break;
+ case Cursor:
+ m_supportCursor = true;
+ m_server->screen()->enableClientCursor(this);
+ break;
+ case DesktopSize:
+ m_supportDesktopSize = true;
+ break;
+ default:
+ break;
+ }
+ }
+ m_handleMsg = false;
+ m_encodingsPending = 0;
+ }
+
+ if (!m_encoder) {
+ m_encoder = new QRfbRawEncoder(this);
+ qCDebug(lcVnc, "QVncServer::setEncodings: fallback using raw");
+ }
+}
+
+void QVncClient::frameBufferUpdateRequest()
+{
+ qCDebug(lcVnc) << "FramebufferUpdateRequest";
+ QRfbFrameBufferUpdateRequest ev;
+
+ if (ev.read(m_clientSocket)) {
+ if (!ev.incremental) {
+ QRect r(ev.rect.x, ev.rect.y, ev.rect.w, ev.rect.h);
+ r.translate(m_server->screen()->geometry().topLeft());
+ setDirty(r);
+ }
+ m_wantUpdate = true;
+ checkUpdate();
+ m_handleMsg = false;
+ }
+}
+
+void QVncClient::pointerEvent()
+{
+ QRfbPointerEvent ev;
+ if (ev.read(m_clientSocket)) {
+ const QPoint pos = m_server->screen()->geometry().topLeft() + QPoint(ev.x, ev.y);
+ QWindowSystemInterface::handleMouseEvent(0, pos, pos, ev.buttons, QGuiApplication::keyboardModifiers());
+ m_handleMsg = false;
+ }
+}
+
+void QVncClient::keyEvent()
+{
+ QRfbKeyEvent ev;
+
+ if (ev.read(m_clientSocket)) {
+ if (ev.keycode == Qt::Key_Shift)
+ m_keymod = ev.down ? m_keymod | Qt::ShiftModifier :
+ m_keymod & ~Qt::ShiftModifier;
+ else if (ev.keycode == Qt::Key_Control)
+ m_keymod = ev.down ? m_keymod | Qt::ControlModifier :
+ m_keymod & ~Qt::ControlModifier;
+ else if (ev.keycode == Qt::Key_Alt)
+ m_keymod = ev.down ? m_keymod | Qt::AltModifier :
+ m_keymod & ~Qt::AltModifier;
+ if (ev.unicode || ev.keycode)
+ QWindowSystemInterface::handleKeyEvent(0, ev.down ? QEvent::KeyPress : QEvent::KeyRelease, ev.keycode, m_keymod, QString(ev.unicode));
+ m_handleMsg = false;
+ }
+}
+
+void QVncClient::clientCutText()
+{
+ QRfbClientCutText ev;
+
+ if (m_cutTextPending == 0 && ev.read(m_clientSocket)) {
+ m_cutTextPending = ev.length;
+ if (!m_cutTextPending)
+ m_handleMsg = false;
+ }
+
+ if (m_cutTextPending && m_clientSocket->bytesAvailable() >= m_cutTextPending) {
+ char *text = new char [m_cutTextPending+1];
+ m_clientSocket->read(text, m_cutTextPending);
+ delete [] text;
+ m_cutTextPending = 0;
+ m_handleMsg = false;
+ }
+}
+
+bool QVncClient::pixelConversionNeeded() const
+{
+ if (!m_sameEndian)
+ return true;
+
+#if Q_BYTE_ORDER == Q_BIG_ENDIAN
+ if (qvnc_screen->swapBytes())
+ return true;
+#endif
+
+ const int screendepth = m_server->screen()->depth();
+ if (screendepth != m_pixelFormat.bitsPerPixel)
+ return true;
+
+ switch (screendepth) {
+ case 32:
+ case 24:
+ return false;
+ case 16:
+ return (m_pixelFormat.redBits == 5
+ && m_pixelFormat.greenBits == 6
+ && m_pixelFormat.blueBits == 5);
+ }
+ return true;
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/vnc/qvncclient.h b/src/plugins/platforms/vnc/qvncclient.h
new file mode 100644
index 0000000000..a7a6b6b361
--- /dev/null
+++ b/src/plugins/platforms/vnc/qvncclient.h
@@ -0,0 +1,149 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QVNCCLIENT_H
+#define QVNCCLIENT_H
+
+#include <QObject>
+
+#include "qvnc_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QTcpSocket;
+class QVncServer;
+
+class QVncClient : public QObject
+{
+ Q_OBJECT
+public:
+ enum ClientMsg {
+ SetPixelFormat = 0,
+ FixColourMapEntries = 1,
+ SetEncodings = 2,
+ FramebufferUpdateRequest = 3,
+ KeyEvent = 4,
+ PointerEvent = 5,
+ ClientCutText = 6
+ };
+
+ explicit QVncClient(QTcpSocket *clientSocket, QVncServer *server);
+ ~QVncClient();
+ QTcpSocket *clientSocket() const;
+ QVncServer *server() const { return m_server; }
+
+ void setDirty(const QRegion &region);
+ void setDirtyCursor() { m_dirtyCursor = true; scheduleUpdate(); }
+ QRegion dirtyRegion() const { return m_dirtyRegion; }
+ inline bool isConnected() const { return m_state == Connected; }
+
+ inline int clientBytesPerPixel() const {
+ return m_pixelFormat.bitsPerPixel / 8;
+ }
+
+ void convertPixels(char *dst, const char *src, int count) const;
+ inline bool doPixelConversion() const { return m_needConversion; }
+
+signals:
+
+private slots:
+ void readClient();
+ void discardClient();
+ void checkUpdate();
+ void scheduleUpdate();
+
+protected:
+ bool event(QEvent *event) override;
+
+private:
+ enum ClientState {
+ Disconnected,
+ Protocol,
+ Authentication,
+ Init,
+ Connected
+ };
+ enum ProtocolVersion {
+ V3_3,
+ V3_7,
+ V3_8
+ };
+
+ void setPixelFormat();
+ void setEncodings();
+ void frameBufferUpdateRequest();
+ void pointerEvent();
+ void keyEvent();
+ void clientCutText();
+ bool pixelConversionNeeded() const;
+
+ QVncServer *m_server;
+ QTcpSocket *m_clientSocket;
+ QRfbEncoder *m_encoder;
+
+ // Client State
+ ClientState m_state;
+ quint8 m_msgType;
+ bool m_handleMsg;
+ QRfbPixelFormat m_pixelFormat;
+ bool m_sameEndian;
+ bool m_needConversion;
+ int m_encodingsPending;
+ int m_cutTextPending;
+ uint m_supportCopyRect : 1;
+ uint m_supportRRE : 1;
+ uint m_supportCoRRE : 1;
+ uint m_supportHextile : 1;
+ uint m_supportZRLE : 1;
+ uint m_supportCursor : 1;
+ uint m_supportDesktopSize : 1;
+ bool m_wantUpdate;
+ Qt::KeyboardModifiers m_keymod;
+ bool m_dirtyCursor;
+ bool m_updatePending;
+#if Q_BYTE_ORDER == Q_BIG_ENDIAN
+ bool m_swapBytes;
+#endif
+ QRegion m_dirtyRegion;
+ ProtocolVersion m_protocolVersion;
+};
+
+QT_END_NAMESPACE
+
+#endif // QVNCCLIENT_H
diff --git a/src/plugins/platforms/vnc/qvncintegration.cpp b/src/plugins/platforms/vnc/qvncintegration.cpp
new file mode 100644
index 0000000000..025112c790
--- /dev/null
+++ b/src/plugins/platforms/vnc/qvncintegration.cpp
@@ -0,0 +1,148 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the FOO module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later 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 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qvncintegration.h"
+#include "qvncscreen.h"
+#include "qvnc_p.h"
+
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtServiceSupport/private/qgenericunixservices_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
+
+#include <QtFbSupport/private/qfbbackingstore_p.h>
+#include <QtFbSupport/private/qfbwindow_p.h>
+#include <QtFbSupport/private/qfbcursor_p.h>
+
+#include <QtGui/private/qguiapplication_p.h>
+#include <qpa/qplatforminputcontextfactory_p.h>
+#include <private/qinputdevicemanager_p_p.h>
+#if QT_CONFIG(libinput)
+#include <QtInputSupport/private/qlibinputhandler_p.h>
+#endif
+
+#include <QtCore/QRegularExpression>
+
+QT_BEGIN_NAMESPACE
+
+QVncIntegration::QVncIntegration(const QStringList &paramList)
+ : m_fontDb(new QGenericUnixFontDatabase),
+ m_services(new QGenericUnixServices)
+{
+ QRegularExpression portRx(QLatin1String("port=(\\d+)"));
+ quint16 port = 5900;
+ for (const QString &arg : paramList) {
+ QRegularExpressionMatch match;
+ if (arg.contains(portRx, &match))
+ port = match.captured(1).toInt();
+ }
+
+ m_primaryScreen = new QVncScreen(paramList);
+ m_server = new QVncServer(m_primaryScreen, port);
+ m_primaryScreen->vncServer = m_server;
+}
+
+QVncIntegration::~QVncIntegration()
+{
+ delete m_server;
+ destroyScreen(m_primaryScreen);
+}
+
+void QVncIntegration::initialize()
+{
+ if (m_primaryScreen->initialize())
+ screenAdded(m_primaryScreen);
+ else
+ qWarning("vnc: Failed to initialize screen");
+
+ m_inputContext = QPlatformInputContextFactory::create();
+
+ m_nativeInterface.reset(new QPlatformNativeInterface);
+
+ // we always have exactly one mouse and keyboard
+ QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount(
+ QInputDeviceManager::DeviceTypePointer, 1);
+ QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount(
+ QInputDeviceManager::DeviceTypeKeyboard, 1);
+
+}
+
+bool QVncIntegration::hasCapability(QPlatformIntegration::Capability cap) const
+{
+ switch (cap) {
+ case ThreadedPixmaps: return true;
+ case WindowManagement: return false;
+ default: return QPlatformIntegration::hasCapability(cap);
+ }
+}
+
+QPlatformBackingStore *QVncIntegration::createPlatformBackingStore(QWindow *window) const
+{
+ return new QFbBackingStore(window);
+}
+
+QPlatformWindow *QVncIntegration::createPlatformWindow(QWindow *window) const
+{
+ return new QFbWindow(window);
+}
+
+QAbstractEventDispatcher *QVncIntegration::createEventDispatcher() const
+{
+ return createUnixEventDispatcher();
+}
+
+QList<QPlatformScreen *> QVncIntegration::screens() const
+{
+ QList<QPlatformScreen *> list;
+ list.append(m_primaryScreen);
+ return list;
+}
+
+QPlatformFontDatabase *QVncIntegration::fontDatabase() const
+{
+ return m_fontDb.data();
+}
+
+QPlatformServices *QVncIntegration::services() const
+{
+ return m_services.data();
+}
+
+QPlatformNativeInterface *QVncIntegration::nativeInterface() const
+{
+ return m_nativeInterface.data();
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtfontdatabase.h b/src/plugins/platforms/vnc/qvncintegration.h
index 8539bcb9db..293ff54376 100644
--- a/src/plugins/platforms/winrt/qwinrtfontdatabase.h
+++ b/src/plugins/platforms/vnc/qvncintegration.h
@@ -3,7 +3,7 @@
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -37,43 +37,49 @@
**
****************************************************************************/
-#ifndef QWINRTFONTDATABASE_H
-#define QWINRTFONTDATABASE_H
+#ifndef QVNCINTEGRATION_H
+#define QVNCINTEGRATION_H
-#include <QtPlatformSupport/private/qbasicfontdatabase_p.h>
-#include <QtCore/QLoggingCategory>
-
-struct IDWriteFontFile;
-struct IDWriteFontFamily;
+#include <qpa/qplatformintegration.h>
+#include <qpa/qplatformnativeinterface.h>
QT_BEGIN_NAMESPACE
-Q_DECLARE_LOGGING_CATEGORY(lcQpaFonts)
-
-struct FontDescription
-{
- quint32 index;
- QByteArray uuid;
-};
+class QAbstractEventDispatcher;
+class QVncScreen;
+class QVncServer;
-class QWinRTFontDatabase : public QBasicFontDatabase
+class QVncIntegration : public QPlatformIntegration, public QPlatformNativeInterface
{
public:
- QString fontDir() const;
- ~QWinRTFontDatabase();
- QFont defaultFont() const Q_DECL_OVERRIDE;
- bool fontsAlwaysScalable() const Q_DECL_OVERRIDE;
- void populateFontDatabase() Q_DECL_OVERRIDE;
- void populateFamily(const QString &familyName) Q_DECL_OVERRIDE;
- QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) Q_DECL_OVERRIDE;
- QStringList fallbacksForFamily(const QString &family, QFont::Style style,
- QFont::StyleHint styleHint, QChar::Script script) const Q_DECL_OVERRIDE;
- void releaseHandle(void *handle) Q_DECL_OVERRIDE;
+ QVncIntegration(const QStringList &paramList);
+ ~QVncIntegration();
+
+ void initialize() Q_DECL_OVERRIDE;
+ bool hasCapability(QPlatformIntegration::Capability cap) const Q_DECL_OVERRIDE;
+
+ QPlatformWindow *createPlatformWindow(QWindow *window) const Q_DECL_OVERRIDE;
+ QPlatformBackingStore *createPlatformBackingStore(QWindow *window) const Q_DECL_OVERRIDE;
+
+ QAbstractEventDispatcher *createEventDispatcher() const Q_DECL_OVERRIDE;
+
+ QPlatformFontDatabase *fontDatabase() const Q_DECL_OVERRIDE;
+ QPlatformServices *services() const Q_DECL_OVERRIDE;
+ QPlatformInputContext *inputContext() const Q_DECL_OVERRIDE { return m_inputContext; }
+
+ QPlatformNativeInterface *nativeInterface() const Q_DECL_OVERRIDE;
+
+ QList<QPlatformScreen *> screens() const;
+
private:
- QHash<IDWriteFontFile *, FontDescription> m_fonts;
- QHash<QString, IDWriteFontFamily *> m_fontFamilies;
+ mutable QVncServer *m_server;
+ QVncScreen *m_primaryScreen;
+ QPlatformInputContext *m_inputContext;
+ QScopedPointer<QPlatformFontDatabase> m_fontDb;
+ QScopedPointer<QPlatformServices> m_services;
+ QScopedPointer<QPlatformNativeInterface> m_nativeInterface;
};
QT_END_NAMESPACE
-#endif // QWINRTFONTDATABASE_H
+#endif // QVNCINTEGRATION_H
diff --git a/src/plugins/platforms/vnc/qvncscreen.cpp b/src/plugins/platforms/vnc/qvncscreen.cpp
new file mode 100644
index 0000000000..34def45767
--- /dev/null
+++ b/src/plugins/platforms/vnc/qvncscreen.cpp
@@ -0,0 +1,187 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qvncscreen.h"
+#include "qvnc_p.h"
+#include <QtFbSupport/private/qfbwindow_p.h>
+#include <QtFbSupport/private/qfbcursor_p.h>
+
+#include <QtGui/QPainter>
+#include <QtCore/QRegularExpression>
+
+
+QT_BEGIN_NAMESPACE
+
+
+QVncScreen::QVncScreen(const QStringList &args)
+ : mArgs(args)
+{
+ initialize();
+}
+
+QVncScreen::~QVncScreen()
+{
+ if (clientCursor)
+ delete clientCursor;
+}
+
+bool QVncScreen::initialize()
+{
+ QRegularExpression sizeRx(QLatin1String("size=(\\d+)x(\\d+)"));
+ QRegularExpression mmSizeRx(QLatin1String("mmsize=(?<width>(\\d*\\.)?\\d+)x(?<height>(\\d*\\.)?\\d+)"));
+ QRegularExpression depthRx(QLatin1String("depth=(\\d+)"));
+
+ mGeometry = QRect(0, 0, 1024, 768);
+ mFormat = QImage::Format_ARGB32_Premultiplied;
+ mDepth = 32;
+ mPhysicalSize = QSizeF(mGeometry.width()/96.*25.4, mGeometry.height()/96.*25.4);
+
+ for (const QString &arg : mArgs) {
+ QRegularExpressionMatch match;
+ if (arg.contains(mmSizeRx, &match)) {
+ mPhysicalSize = QSizeF(match.captured("width").toDouble(), match.captured("height").toDouble());
+ } else if (arg.contains(sizeRx, &match)) {
+ mGeometry.setSize(QSize(match.captured(1).toInt(), match.captured(2).toInt()));
+ } else if (arg.contains(depthRx, &match)) {
+ mDepth = match.captured(1).toInt();
+ }
+ }
+
+ QFbScreen::initializeCompositor();
+
+ switch (depth()) {
+ case 32:
+ dirty = new QVncDirtyMapOptimized<quint32>(this);
+ break;
+ case 16:
+ dirty = new QVncDirtyMapOptimized<quint16>(this);
+ break;
+ case 8:
+ dirty = new QVncDirtyMapOptimized<quint8>(this);
+ break;
+ default:
+ qWarning("QVNCScreen::initDevice: No support for screen depth %d",
+ depth());
+ dirty = 0;
+ return false;
+ }
+
+ setPowerState(PowerStateOff);
+
+ return true;
+}
+
+QRegion QVncScreen::doRedraw()
+{
+ QRegion touched = QFbScreen::doRedraw();
+
+ if (touched.isEmpty())
+ return touched;
+ dirtyRegion += touched;
+
+ vncServer->setDirty();
+ return touched;
+}
+
+void QVncScreen::enableClientCursor(QVncClient *client)
+{
+ delete mCursor;
+ mCursor = nullptr;
+ if (!clientCursor)
+ clientCursor = new QVncClientCursor();
+ clientCursor->addClient(client);
+}
+
+void QVncScreen::disableClientCursor(QVncClient *client)
+{
+ uint clientCount = clientCursor->removeClient(client);
+ if (clientCount == 0) {
+ delete clientCursor;
+ clientCursor = nullptr;
+ }
+
+ mCursor = new QFbCursor(this);
+}
+
+QPlatformCursor *QVncScreen::cursor() const
+{
+ return mCursor ? static_cast<QPlatformCursor *>(mCursor) : static_cast<QPlatformCursor *>(clientCursor);
+}
+
+// grabWindow() grabs "from the screen" not from the backingstores.
+// In linuxfb's case it will also include the mouse cursor.
+QPixmap QVncScreen::grabWindow(WId wid, int x, int y, int width, int height) const
+{
+ if (!wid) {
+ if (width < 0)
+ width = mScreenImage->width() - x;
+ if (height < 0)
+ height = mScreenImage->height() - y;
+ return QPixmap::fromImage(*mScreenImage).copy(x, y, width, height);
+ }
+
+ QFbWindow *window = windowForId(wid);
+ if (window) {
+ const QRect geom = window->geometry();
+ if (width < 0)
+ width = geom.width() - x;
+ if (height < 0)
+ height = geom.height() - y;
+ QRect rect(geom.topLeft() + QPoint(x, y), QSize(width, height));
+ rect &= window->geometry();
+ return QPixmap::fromImage(*mScreenImage).copy(rect);
+ }
+
+ return QPixmap();
+}
+
+#if Q_BYTE_ORDER == Q_BIG_ENDIAN
+bool QVNCScreen::swapBytes() const
+{
+ if (depth() != 16)
+ return false;
+
+ if (screen())
+ return screen()->frameBufferLittleEndian();
+ return frameBufferLittleEndian();
+}
+#endif
+
+QT_END_NAMESPACE
+
diff --git a/src/plugins/platforms/vnc/qvncscreen.h b/src/plugins/platforms/vnc/qvncscreen.h
new file mode 100644
index 0000000000..785abd6dc2
--- /dev/null
+++ b/src/plugins/platforms/vnc/qvncscreen.h
@@ -0,0 +1,93 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QVncScreen_H
+#define QVncScreen_H
+
+#include <QtFbSupport/private/qfbscreen_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QPainter;
+class QFbCursor;
+class QTcpSocket;
+class QVncServer;
+class QVncDirtyMap;
+class QVncClientCursor;
+class QVncClient;
+
+class QVncScreen : public QFbScreen
+{
+ Q_OBJECT
+public:
+ QVncScreen(const QStringList &args);
+ ~QVncScreen();
+
+ bool initialize();
+
+ QPixmap grabWindow(WId wid, int x, int y, int width, int height) const Q_DECL_OVERRIDE;
+
+ QRegion doRedraw() Q_DECL_OVERRIDE;
+ QImage *image() const { return mScreenImage; }
+
+ void enableClientCursor(QVncClient *client);
+ void disableClientCursor(QVncClient *client);
+ QPlatformCursor *cursor() const Q_DECL_OVERRIDE;
+
+ void clearDirty() { dirtyRegion = QRegion(); }
+
+#if Q_BYTE_ORDER == Q_BIG_ENDIAN
+ bool swapBytes() const
+#endif
+
+ QStringList mArgs;
+
+ qreal dpiX = 96;
+ qreal dpiY = 96;
+ QVncDirtyMap *dirty = 0;
+ QRegion dirtyRegion;
+ int refreshRate = 30;
+ QVncServer *vncServer = 0;
+ QVncClientCursor *clientCursor = 0;
+};
+
+QT_END_NAMESPACE
+
+#endif // QVncScreen_H
+
diff --git a/src/plugins/platforms/vnc/vnc.json b/src/plugins/platforms/vnc/vnc.json
new file mode 100644
index 0000000000..6a16b08ca8
--- /dev/null
+++ b/src/plugins/platforms/vnc/vnc.json
@@ -0,0 +1,3 @@
+{
+ "Keys": [ "vnc" ]
+}
diff --git a/src/plugins/platforms/vnc/vnc.pro b/src/plugins/platforms/vnc/vnc.pro
new file mode 100644
index 0000000000..3cd7e9b160
--- /dev/null
+++ b/src/plugins/platforms/vnc/vnc.pro
@@ -0,0 +1,31 @@
+TARGET = qvnc
+
+PLUGIN_TYPE = platforms
+PLUGIN_CLASS_NAME = QVncIntegrationPlugin
+!equals(TARGET, $$QT_DEFAULT_QPA_PLUGIN): PLUGIN_EXTENDS = -
+load(qt_plugin)
+
+QT += \
+ core-private network gui-private \
+ service_support-private theme_support-private fb_support-private \
+ eventdispatcher_support-private fontdatabase_support-private
+
+qtHaveModule(input_support-private): \
+ QT += input_support-private
+
+DEFINES += QT_NO_FOREACH
+
+SOURCES = \
+ main.cpp \
+ qvncintegration.cpp \
+ qvncscreen.cpp \
+ qvnc.cpp \
+ qvncclient.cpp
+
+HEADERS = \
+ qvncintegration.h \
+ qvncscreen.h \
+ qvnc_p.h \
+ qvncclient.h
+
+OTHER_FILES += vnc.json
diff --git a/src/plugins/platforms/windows/accessible/accessible.pri b/src/plugins/platforms/windows/accessible/accessible.pri
index 0774d907f2..0e3aacc558 100644
--- a/src/plugins/platforms/windows/accessible/accessible.pri
+++ b/src/plugins/platforms/windows/accessible/accessible.pri
@@ -6,15 +6,13 @@ HEADERS += \
$$PWD/qwindowsaccessibility.h \
$$PWD/comutils.h
-!wince: {
- SOURCES += $$PWD/qwindowsmsaaaccessible.cpp
- HEADERS += $$PWD/qwindowsmsaaaccessible.h
+SOURCES += $$PWD/qwindowsmsaaaccessible.cpp
+HEADERS += $$PWD/qwindowsmsaaaccessible.h
- !mingw: {
- SOURCES += $$PWD/iaccessible2.cpp
- HEADERS += $$PWD/iaccessible2.h
- include(../../../../3rdparty/iaccessible2/iaccessible2.pri)
- }
+!mingw: {
+ SOURCES += $$PWD/iaccessible2.cpp
+ HEADERS += $$PWD/iaccessible2.h
+ include(../../../../3rdparty/iaccessible2/iaccessible2.pri)
}
mingw: LIBS *= -luuid
diff --git a/src/plugins/platforms/windows/accessible/comutils.cpp b/src/plugins/platforms/windows/accessible/comutils.cpp
index 7655bdf622..1c072c5e2c 100644
--- a/src/plugins/platforms/windows/accessible/comutils.cpp
+++ b/src/plugins/platforms/windows/accessible/comutils.cpp
@@ -170,7 +170,6 @@ bool QVariant2VARIANT(const QVariant &var, VARIANT &arg, const QByteArray &typeN
case QVariant::LongLong:
if (out && arg.vt == (VT_CY|VT_BYREF)) {
arg.pcyVal->int64 = qvar.toLongLong();
-#if !defined(Q_OS_WINCE) && defined(_MSC_VER) && _MSC_VER >= 1400
} else if (out && arg.vt == (VT_I8|VT_BYREF)) {
*arg.pllVal = qvar.toLongLong();
} else {
@@ -181,22 +180,11 @@ bool QVariant2VARIANT(const QVariant &var, VARIANT &arg, const QByteArray &typeN
arg.vt |= VT_BYREF;
}
}
-#else
- } else {
- arg.vt = VT_CY;
- arg.cyVal.int64 = qvar.toLongLong();
- if (out) {
- arg.pcyVal = new CY(arg.cyVal);
- arg.vt |= VT_BYREF;
- }
- }
-#endif
break;
case QVariant::ULongLong:
if (out && arg.vt == (VT_CY|VT_BYREF)) {
arg.pcyVal->int64 = qvar.toULongLong();
-#if !defined(Q_OS_WINCE) && defined(_MSC_VER) && _MSC_VER >= 1400
} else if (out && arg.vt == (VT_UI8|VT_BYREF)) {
*arg.pullVal = qvar.toULongLong();
} else {
@@ -207,18 +195,6 @@ bool QVariant2VARIANT(const QVariant &var, VARIANT &arg, const QByteArray &typeN
arg.vt |= VT_BYREF;
}
}
-#else
- } else {
- arg.vt = VT_CY;
- arg.cyVal.int64 = qvar.toULongLong();
- if (out) {
- arg.pcyVal = new CY(arg.cyVal);
- arg.vt |= VT_BYREF;
- }
- }
-
-#endif
-
break;
case QVariant::Bool:
diff --git a/src/plugins/platforms/windows/accessible/iaccessible2.cpp b/src/plugins/platforms/windows/accessible/iaccessible2.cpp
index 5ba49a8a98..d5cd9ac6db 100644
--- a/src/plugins/platforms/windows/accessible/iaccessible2.cpp
+++ b/src/plugins/platforms/windows/accessible/iaccessible2.cpp
@@ -41,7 +41,7 @@
#include "iaccessible2.h"
#include "qwindowsaccessibility.h"
-#include <QtPlatformSupport/private/qaccessiblebridgeutils_p.h>
+#include <QtAccessibilitySupport/private/qaccessiblebridgeutils_p.h>
#include <QtGui/qaccessible.h>
#include <QtGui/qclipboard.h>
#include <QtGui/qguiapplication.h>
diff --git a/src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp b/src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp
index 4a3f0ccb2b..aed9c94003 100644
--- a/src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp
+++ b/src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp
@@ -47,21 +47,19 @@
#include <QtCore/qmap.h>
#include <QtCore/qpair.h>
#include <QtCore/qpointer.h>
-#include <QtCore/qsettings.h>
#include <QtGui/qaccessible.h>
#include <QtGui/private/qguiapplication_p.h>
#include <qpa/qplatformnativeinterface.h>
#include <qpa/qplatformintegration.h>
#include <QtGui/qwindow.h>
#include <QtGui/qguiapplication.h>
+#include <QtFontDatabaseSupport/private/qwindowsfontdatabase_p.h> // registry helper
#include "qwindowsaccessibility.h"
-#if !defined(Q_OS_WINCE)
-# ifdef Q_CC_MINGW
-# include "qwindowsmsaaaccessible.h"
-# else
-# include "iaccessible2.h"
-# endif
+#ifdef Q_CC_MINGW
+# include "qwindowsmsaaaccessible.h"
+#else
+# include "iaccessible2.h"
#endif
#include "comutils.h"
@@ -74,11 +72,7 @@
#include <winuser.h>
#if !defined(WINABLEAPI)
-# if defined(Q_OS_WINCE)
-# include <bldver.h>
-# else
-# include <winable.h>
-# endif
+# include <winable.h>
#endif
#include <servprov.h>
@@ -86,7 +80,7 @@
#include <comdef.h>
#endif
-#include "../qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
QT_BEGIN_NAMESPACE
@@ -120,6 +114,14 @@ static inline QString messageBoxAlertSound(const QObject *messageBox)
return QString();
}
+static QString soundFileName(const QString &soundName)
+{
+ const QString key = QStringLiteral("AppEvents\\Schemes\\Apps\\.Default\\")
+ + soundName + QStringLiteral("\\.Current");
+ return QWindowsFontDatabase::readRegistryString(HKEY_CURRENT_USER,
+ reinterpret_cast<const wchar_t *>(key.utf16()), L"");
+}
+
void QWindowsAccessibility::notifyAccessibilityUpdate(QAccessibleEvent *event)
{
QString soundName;
@@ -140,23 +142,11 @@ void QWindowsAccessibility::notifyAccessibilityUpdate(QAccessibleEvent *event)
break;
}
- if (!soundName.isEmpty()) {
-#ifndef QT_NO_SETTINGS
- QSettings settings(QLatin1String("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\.Default\\") + soundName,
- QSettings::NativeFormat);
- QString file = settings.value(QLatin1String(".Current/.")).toString();
-#else
- QString file;
-#endif
- if (!file.isEmpty()) {
- PlaySound(reinterpret_cast<const wchar_t *>(soundName.utf16()), 0, SND_ALIAS | SND_ASYNC | SND_NODEFAULT | SND_NOWAIT);
- }
+ if (!soundName.isEmpty() && !soundFileName(soundName).isEmpty()) {
+ PlaySound(reinterpret_cast<const wchar_t *>(soundName.utf16()), 0,
+ SND_ALIAS | SND_ASYNC | SND_NODEFAULT | SND_NOWAIT);
}
-#if defined(Q_OS_WINCE) // ### TODO: check for NotifyWinEvent in CE 6.0
- // There is no user32.lib nor NotifyWinEvent for CE
- return;
-#else
// An event has to be associated with a window,
// so find the first parent that is a widget and that has a WId
QAccessibleInterface *iface = event->accessibleInterface();
@@ -179,7 +169,6 @@ void QWindowsAccessibility::notifyAccessibilityUpdate(QAccessibleEvent *event)
event->type() != QAccessible::ObjectDestroyed) {
::NotifyWinEvent(event->type(), hWnd, OBJID_CLIENT, QAccessible::uniqueId(iface));
}
-#endif // Q_OS_WINCE
}
QWindow *QWindowsAccessibility::windowHelper(const QAccessibleInterface *iface)
@@ -202,11 +191,6 @@ QWindow *QWindowsAccessibility::windowHelper(const QAccessibleInterface *iface)
*/
IAccessible *QWindowsAccessibility::wrap(QAccessibleInterface *acc)
{
-#if defined(Q_OS_WINCE)
- Q_UNUSED(acc);
-
- return 0;
-#else
if (!acc)
return 0;
@@ -222,12 +206,10 @@ IAccessible *QWindowsAccessibility::wrap(QAccessibleInterface *acc)
IAccessible *iacc = 0;
wacc->QueryInterface(IID_IAccessible, reinterpret_cast<void **>(&iacc));
return iacc;
-#endif // defined(Q_OS_WINCE)
}
bool QWindowsAccessibility::handleAccessibleObjectFromWindowRequest(HWND hwnd, WPARAM wParam, LPARAM lParam, LRESULT *lResult)
{
-#if !defined(Q_OS_WINCE)
if (static_cast<long>(lParam) == static_cast<long>(UiaRootObjectId)) {
/* For UI Automation */
} else if (DWORD(lParam) == DWORD(OBJID_CLIENT)) {
@@ -263,12 +245,6 @@ bool QWindowsAccessibility::handleAccessibleObjectFromWindowRequest(HWND hwnd, W
}
}
}
-#else
- Q_UNUSED(hwnd);
- Q_UNUSED(wParam);
- Q_UNUSED(lParam);
- Q_UNUSED(lResult);
-#endif // !defined(Q_OS_WINCE)
return false;
}
diff --git a/src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.cpp b/src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.cpp
index 0e2165cdcb..9803dedb1e 100644
--- a/src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.cpp
+++ b/src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.cpp
@@ -50,7 +50,6 @@
#include <QtCore/qdebug.h>
#include <QtCore/qmap.h>
#include <QtCore/qpair.h>
-#include <QtCore/qsettings.h>
#include <QtGui/qaccessible.h>
#include <QtGui/qguiapplication.h>
#include <qpa/qplatformnativeinterface.h>
@@ -67,7 +66,7 @@
#endif
-#include "../qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.h b/src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.h
index 2f8602e320..fd00f8ac8b 100644
--- a/src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.h
+++ b/src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.h
@@ -43,7 +43,7 @@
#ifndef QT_NO_ACCESSIBILITY
#include <QtCore/qglobal.h>
-#include "../qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/qsharedpointer.h>
#include <QtGui/qaccessible.h>
#ifndef Q_CC_MINGW
diff --git a/src/plugins/platforms/windows/qplatformfunctions_wince.h b/src/plugins/platforms/windows/qplatformfunctions_wince.h
deleted file mode 100644
index 309191537a..0000000000
--- a/src/plugins/platforms/windows/qplatformfunctions_wince.h
+++ /dev/null
@@ -1,371 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMFUNCTIONS_WCE_H
-#define QPLATFORMFUNCTIONS_WCE_H
-//
-// W A R N I N G
-// -------------
-//
-// This file is part of the QPA API and is not meant to be used
-// in applications. Usage of this API may make your code
-// source and binary incompatible with future versions of Qt.
-//
-
-#ifdef Q_OS_WINCE
-#include <QtCore/qfunctions_wince.h>
-#define UNDER_NT
-#include <wingdi.h>
-#include <objidl.h>
-
-#ifndef WM_MOUSELEAVE
-# define WM_MOUSELEAVE 0x02A3
-#endif
-
-#ifndef WM_TOUCH
-# define WM_TOUCH 0x0240
-#endif
-
-#ifndef WM_GETOBJECT
-#define WM_GETOBJECT 0x003D
-#endif
-
-#define GetWindowLongPtr GetWindowLong
-#define SetWindowLongPtr SetWindowLong
-#define GWLP_USERDATA GWL_USERDATA
-
-#ifndef CWP_SKIPINVISIBLE
-#define CWP_SKIPINVISIBLE 0x0001
-#define CWP_SKIPTRANSPARENT 0x0004
-#endif
-
-#ifndef CS_OWNDC
-#define CS_OWNDC 0x0020
-#endif
-
-#ifndef HWND_MESSAGE
-#define HWND_MESSAGE 0
-#endif
-
-// Real Value would be 0x40000000, but if we pass this to Windows Embedded Compact
-// he blits it wrongly, so lets not do any harm and define it to 0
-#ifndef CAPTUREBLT
-#define CAPTUREBLT (DWORD)0x0
-#endif
-
-#define SW_SHOWMINIMIZED SW_MINIMIZE
-#define SW_SHOWMINNOACTIVE SW_MINIMIZE
-
-#ifndef CF_DIBV5
-#define CF_DIBV5 17
-#endif
-
-#ifndef WM_MOUSEACTIVATE
-#define WM_MOUSEACTIVATE 0x0021
-#endif
-
-#ifndef WM_CHILDACTIVATE
-#define WM_CHILDACTIVATE 0x0022
-#endif
-
-#ifndef WM_PARENTNOTIFY
-#define WM_PARENTNOTIFY 0x0210
-#endif
-
-#ifndef WM_ENTERIDLE
-#define WM_ENTERIDLE 0x0121
-#endif
-
-#ifndef WM_GETMINMAXINFO
-#define WM_GETMINMAXINFO 0x0024
-#endif
-
-#ifndef WM_WINDOWPOSCHANGING
-#define WM_WINDOWPOSCHANGING 0x0046
-#endif
-
-#ifndef WM_NCMOUSEMOVE
-#define WM_NCMOUSEMOVE 0x00A0
-#endif
-
-#ifndef WM_NCMBUTTONDBLCLK
-#define WM_NCMBUTTONDBLCLK 0x00A
-#endif
-
-#ifndef WM_NCCREATE
-#define WM_NCCREATE 0x0081
-#endif
-
-#ifndef WM_NCCALCSIZE
-#define WM_NCCALCSIZE 0x0083
-#endif
-
-#ifndef WM_NCACTIVATE
-#define WM_NCACTIVATE 0x0086
-#endif
-
-#ifndef WM_NCMOUSELEAVE
-#define WM_NCMOUSELEAVE 0x02A2
-#endif
-
-#ifndef WM_NCLBUTTONDOWN
-#define WM_NCLBUTTONDOWN 0x00A1
-#endif
-
-#ifndef WM_NCLBUTTONUP
-#define WM_NCLBUTTONUP 0x00A2
-#endif
-
-#ifndef WM_NCPAINT
-#define WM_NCPAINT 0x0085
-#endif
-
-#ifndef WM_NCHITTEST
-#define WM_NCHITTEST 0x0084
-#endif
-
-#ifndef WM_THEMECHANGED
-#define WM_THEMECHANGED 0x031A
-#endif
-
-#ifndef WM_DISPLAYCHANGE
-#define WM_DISPLAYCHANGE 0x007E
-#endif
-
-#ifndef VREFRESH
-#define VREFRESH 116
-#endif
-
-#ifndef SM_SWAPBUTTON
-#define SM_SWAPBUTTON 23
-#endif
-
-// application defines
-#define SPI_SETNONCLIENTMETRICS 72
-#define SPI_SETICONTITLELOGFONT 0x0022
-#define WM_ACTIVATEAPP 0x001c
-#define SW_PARENTCLOSING 1
-#define SW_OTHERMAXIMIZED 2
-#define SW_PARENTOPENING 3
-#define SW_OTHERRESTORED 4
-#define GET_XBUTTON_WPARAM(wParam) (HIWORD(wParam))
-
-// drag n drop
-#ifndef CFSTR_PERFORMEDDROPEFFECT
-#define CFSTR_PERFORMEDDROPEFFECT TEXT("Performed DropEffect")
-#endif
-
-// QWidget
-#define SW_SHOWMINIMIZED SW_MINIMIZE
-
-// QRegion
-#define ALTERNATE 0
-#define WINDING 1
-
-// QFontEngine
-typedef struct _FIXED {
- WORD fract;
- short value;
-} FIXED;
-
-typedef struct tagPOINTFX {
- FIXED x;
- FIXED y;
-} POINTFX;
-
-typedef struct _MAT2 {
- FIXED eM11;
- FIXED eM12;
- FIXED eM21;
- FIXED eM22;
-} MAT2;
-
-typedef struct _GLYPHMETRICS {
- UINT gmBlackBoxX;
- UINT gmBlackBoxY;
- POINT gmptGlyphOrigin;
- short gmCellIncX;
- short gmCellIncY;
-} GLYPHMETRICS;
-
-typedef struct tagTTPOLYGONHEADER
-{
- DWORD cb;
- DWORD dwType;
- POINTFX pfxStart;
-} TTPOLYGONHEADER;
-
-typedef struct tagTTPOLYCURVE
-{
- WORD wType;
- WORD cpfx;
- POINTFX apfx[1];
-} TTPOLYCURVE;
-
-#define GGO_NATIVE 2
-#define GGO_GLYPH_INDEX 0x0080
-#define TT_PRIM_LINE 1
-#define TT_PRIM_QSPLINE 2
-#define TT_PRIM_CSPLINE 3
-#define ANSI_VAR_FONT 12
-
-#ifndef OleInitialize
-#define OleInitialize(a) 0
-#endif
-
-#ifndef SPI_GETSNAPTODEFBUTTON
-#define SPI_GETSNAPTODEFBUTTON 95
-#endif
-
-#ifndef WS_EX_LAYERED
-#define WS_EX_LAYERED 0x00080000
-#endif
-
-// Clipboard --------------------------------------------------------
-#ifndef WM_CHANGECBCHAIN
-#define WM_CHANGECBCHAIN 0x030D
-#endif
-
-#ifndef WM_DRAWCLIPBOARD
-#define WM_DRAWCLIPBOARD 0x0308
-#endif
-
-#include <QFileInfo>
-
-inline bool IsIconic( HWND /*hWnd*/ )
-{
- return false;
-}
-
-inline int AddFontResourceExW( LPCWSTR name, DWORD /*fl*/, PVOID /*res*/)
-{
- QString fName = QString::fromWCharArray(name);
- QFileInfo fileinfo(fName);
- fName = fileinfo.absoluteFilePath();
- return AddFontResource((LPCWSTR)fName.utf16());
-}
-
-inline bool RemoveFontResourceExW( LPCWSTR /*name*/, DWORD /*fl*/, PVOID /*pdv*/)
-{
- return 0;
-}
-
-inline void OleUninitialize()
-{
-}
-
-inline DWORD GetGlyphOutline( HDC /*hdc*/, UINT /*uChar*/, INT /*fuFormat*/, GLYPHMETRICS * /*lpgm*/,
- DWORD /*cjBuffer*/, LPVOID /*pvBuffer*/, CONST MAT2 * /*lpmat2*/ )
-{
- qFatal("GetGlyphOutline() not supported under Windows CE. Please try using freetype font-rendering, by "
- "passing the command line argument -platform windows:fontengine=freetype to the application.");
- return GDI_ERROR;
-}
-
-inline HWND GetAncestor(HWND hWnd, UINT /*gaFlags*/)
-{
- return GetParent(hWnd);
-}
-
-#ifndef GA_PARENT
-# define GA_PARENT 1
-#endif
-
-#ifndef SPI_SETFONTSMOOTHINGTYPE
-# define SPI_SETFONTSMOOTHINGTYPE 0x200B
-#endif
-#ifndef SPI_GETFONTSMOOTHINGTYPE
-# define SPI_GETFONTSMOOTHINGTYPE 0x200A
-#endif
-#ifndef FE_FONTSMOOTHINGCLEARTYPE
-# define FE_FONTSMOOTHINGCLEARTYPE 0x0002
-#endif
-
-#ifndef DEVICE_FONTTYPE
-#define DEVICE_FONTTYPE 0x0002
-#endif
-
-#ifndef RASTER_FONTTYPE
-#define RASTER_FONTTYPE 0x0001
-#endif
-
-#ifndef WM_DISPLAYCHANGE
-#define WM_DISPLAYCHANGE 0x007E
-#endif
-
-BOOL qt_wince_ChangeClipboardChain(
- HWND hWndRemove, // handle to window to remove
- HWND hWndNewNext // handle to next window
-);
-#define ChangeClipboardChain(a,b) qt_wince_ChangeClipboardChain(a,b);
-
-HWND qt_wince_SetClipboardViewer(
- HWND hWndNewViewer // handle to clipboard viewer window
-);
-#define SetClipboardViewer(a) qt_wince_SetClipboardViewer(a)
-
-/* Shell stock icon IDs
- SHGetStockIconInfo() is not available on CE, but we're using these
- constants in code that is built on CE as well */
- enum
- {
- SIID_INVALID = -1,
- SIID_DOCNOASSOC = 0,
- SIID_FOLDER = 3,
- SIID_FOLDEROPEN = 4,
- SIID_DRIVE35 = 6,
- SIID_DRIVEFIXED = 8,
- SIID_DRIVENET = 9,
- SIID_DRIVECD = 11,
- SIID_HELP = 23,
- SIID_RECYCLER = 31,
- SIID_DRIVEDVD = 59,
- SIID_SHIELD = 77,
- SIID_WARNING = 78,
- SIID_INFO = 79,
- SIID_ERROR = 80
-};
-
-#ifndef SHGSI_LINKOVERLAY
-// Value is wrong, but doesn't matter, not used at runtime
-#define SHGSI_LINKOVERLAY 0
-#endif
-
-#endif // Q_OS_WINCE
-#endif // QPLATFORMFUNCTIONS_WCE_H
diff --git a/src/plugins/platforms/windows/qtwindows_additional.h b/src/plugins/platforms/windows/qtwindows_additional.h
deleted file mode 100644
index 898a09fba7..0000000000
--- a/src/plugins/platforms/windows/qtwindows_additional.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTWINDOWS_ADDITIONAL_H
-#define QTWINDOWS_ADDITIONAL_H
-
-#include <QtCore/QtGlobal> // get compiler define
-#include <QtCore/qt_windows.h>
-
-#ifndef WM_THEMECHANGED
-# define WM_THEMECHANGED 0x031A
-#endif
-
-#ifndef WM_DWMCOMPOSITIONCHANGED
-# define WM_DWMCOMPOSITIONCHANGED 0x31E
-#endif
-
-#ifndef GWL_HWNDPARENT
-# define GWL_HWNDPARENT (-8)
-#endif
-
-/* Complement the definitions and declarations missing
- * when using MinGW or older Windows SDKs. */
-
-#if defined(Q_CC_MINGW)
-# if !defined(ULW_ALPHA)
-# define ULW_ALPHA 0x00000002
-# define LWA_ALPHA 0x00000002
-# endif // !defined(ULW_ALPHA)
-# define SPI_GETFONTSMOOTHINGTYPE 0x200A
-# define FE_FONTSMOOTHINGCLEARTYPE 0x0002
-# define CLEARTYPE_QUALITY 5
-# define SPI_GETDROPSHADOW 0x1024
-# define COLOR_MENUHILIGHT 29
-# define COLOR_MENUBAR 30
-# define CF_DIBV5 17
-
-#if !defined(CO_E_NOT_SUPPORTED)
-#define CO_E_NOT_SUPPORTED _HRESULT_TYPEDEF_(0x80004021L)
-#endif
-
-#define IFMETHOD HRESULT STDMETHODCALLTYPE
-#define IFACEMETHODIMP STDMETHODIMP
-#define IFACEMETHODIMP_(type) STDMETHODIMP_(type)
-
-// For accessibility:
-#ifdef __cplusplus
- #define EXTERN_C extern "C"
-#else
- #define EXTERN_C extern
-#endif
-
-#define CHILDID_SELF 0
-#define WM_GETOBJECT 0x003D
-
-#ifndef SHGFI_ADDOVERLAYS // Shell structures for icons.
-typedef struct _SHSTOCKICONINFO
-{
- DWORD cbSize;
- HICON hIcon;
- int iSysImageIndex;
- int iIcon;
- WCHAR szPath[MAX_PATH];
-} SHSTOCKICONINFO;
-
-# define SIID_SHIELD 77
-# define SHGFI_ADDOVERLAYS 0x20
-# define SHGFI_OVERLAYINDEX 0x40
-#endif // SIID_SHIELD
-
-#if !defined(__MINGW64_VERSION_MAJOR)
-
-#define STATE_SYSTEM_HASPOPUP 0x40000000
-#define STATE_SYSTEM_PROTECTED 0x20000000
-
-typedef struct tagUPDATELAYEREDWINDOWINFO {
- DWORD cbSize;
- HDC hdcDst;
- const POINT *pptDst;
- const SIZE *psize;
- HDC hdcSrc;
- const POINT *pptSrc;
- COLORREF crKey;
- const BLENDFUNCTION *pblend;
- DWORD dwFlags;
- const RECT *prcDirty;
-} UPDATELAYEREDWINDOWINFO, *PUPDATELAYEREDWINDOWINFO;
-
-#endif // if !defined(__MINGW64_VERSION_MAJOR)
-
-// OpenGL Pixelformat flags.
-#define PFD_SUPPORT_DIRECTDRAW 0x00002000
-#define PFD_DIRECT3D_ACCELERATED 0x00004000
-#define PFD_SUPPORT_COMPOSITION 0x00008000
-
-// IME.
-#define IMR_CONFIRMRECONVERTSTRING 0x0005
-
-#ifndef MAPVK_VK_TO_CHAR
-# define MAPVK_VK_TO_CHAR 2
-#endif
-
-#endif // if defined(Q_CC_MINGW)
-
-/* Touch is supported from Windows 7 onwards and data structures
- * are present in the Windows SDK's, but not in older MSVC Express
- * versions. */
-
-#if defined(Q_CC_MINGW) || !defined(TOUCHEVENTF_MOVE)
-
-#define WM_TOUCH 0x0240
-
-typedef struct tagTOUCHINPUT {
- LONG x;
- LONG y;
- HANDLE hSource;
- DWORD dwID;
- DWORD dwFlags;
- DWORD dwMask;
- DWORD dwTime;
- ULONG_PTR dwExtraInfo;
- DWORD cxContact;
- DWORD cyContact;
-} TOUCHINPUT, *PTOUCHINPUT;
-typedef TOUCHINPUT const * PCTOUCHINPUT;
-
-# 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_PALM 0x0080
-# define TOUCHINPUTMASKF_CONTACTAREA 0x0004
-# define TOUCHINPUTMASKF_EXTRAINFO 0x0002
-
-#endif // if defined(Q_CC_MINGW) || !defined(TOUCHEVENTF_MOVE)
-
-#ifndef WM_GESTURE
-# define WM_GESTURE 0x0119
-#endif
-
-#endif // QTWINDOWS_ADDITIONAL_H
diff --git a/src/plugins/platforms/windows/qtwindowsglobal.h b/src/plugins/platforms/windows/qtwindowsglobal.h
index 90008663e7..ec6a8f62ae 100644
--- a/src/plugins/platforms/windows/qtwindowsglobal.h
+++ b/src/plugins/platforms/windows/qtwindowsglobal.h
@@ -41,10 +41,19 @@
#ifndef QTWINDOWSGLOBAL_H
#define QTWINDOWSGLOBAL_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/qnamespace.h>
-#ifdef Q_OS_WINCE
-# include "qplatformfunctions_wince.h"
+
+#ifndef WM_DWMCOMPOSITIONCHANGED // MinGW.
+# define WM_DWMCOMPOSITIONCHANGED 0x31E
+#endif
+
+#ifndef WM_TOUCH
+# define WM_TOUCH 0x0240
+#endif
+
+#ifndef WM_GESTURE
+# define WM_GESTURE 0x0119
#endif
QT_BEGIN_NAMESPACE
@@ -158,10 +167,8 @@ inline QtWindows::WindowsEventType windowsEventType(UINT message, WPARAM wParamI
case WM_MOUSEWHEEL:
case WM_MOUSEHWHEEL:
return QtWindows::MouseWheelEvent;
-#ifndef Q_OS_WINCE
case WM_WINDOWPOSCHANGING:
return QtWindows::GeometryChangingEvent;
-#endif
case WM_MOVE:
return QtWindows::MoveEvent;
case WM_SHOWWINDOW:
@@ -172,10 +179,8 @@ inline QtWindows::WindowsEventType windowsEventType(UINT message, WPARAM wParamI
return QtWindows::ResizeEvent;
case WM_NCCALCSIZE:
return QtWindows::CalculateSize;
-#ifndef Q_OS_WINCE
case WM_NCHITTEST:
return QtWindows::NonClientHitTest;
-#endif // !Q_OS_WINCE
case WM_GETMINMAXINFO:
return QtWindows::QuerySizeHints;
case WM_KEYDOWN: // keyboard event
@@ -243,12 +248,10 @@ inline QtWindows::WindowsEventType windowsEventType(UINT message, WPARAM wParamI
return QtWindows::ContextMenu;
#endif
case WM_SYSCOMMAND:
-#ifndef Q_OS_WINCE
if ((wParamIn & 0xfff0) == SC_CONTEXTHELP)
return QtWindows::WhatsThisEvent;
-#endif
break;
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
case WM_QUERYENDSESSION:
return QtWindows::QueryEndSessionApplicationEvent;
case WM_ENDSESSION:
diff --git a/src/plugins/platforms/windows/qwindowsbackingstore.cpp b/src/plugins/platforms/windows/qwindowsbackingstore.cpp
index 7123ed826d..49c7144221 100644
--- a/src/plugins/platforms/windows/qwindowsbackingstore.cpp
+++ b/src/plugins/platforms/windows/qwindowsbackingstore.cpp
@@ -39,11 +39,11 @@
#include "qwindowsbackingstore.h"
#include "qwindowswindow.h"
-#include "qwindowsnativeimage.h"
#include "qwindowscontext.h"
#include <QtGui/QWindow>
#include <QtGui/QPainter>
+#include <QtFontDatabaseSupport/private/qwindowsnativeimage_p.h>
#include <private/qhighdpiscaling_p.h>
#include <private/qimage_p.h>
@@ -87,7 +87,6 @@ void QWindowsBackingStore::flush(QWindow *window, const QRegion &region,
QWindowsWindow *rw = QWindowsWindow::windowsWindowOf(window);
Q_ASSERT(rw);
-#ifndef Q_OS_WINCE
const bool hasAlpha = rw->format().hasAlpha();
const Qt::WindowFlags flags = window->flags();
if ((flags & Qt::FramelessWindowHint) && QWindowsWindow::setWindowLayered(rw->handle(), flags, hasAlpha, rw->opacity()) && hasAlpha) {
@@ -101,21 +100,16 @@ void QWindowsBackingStore::flush(QWindow *window, const QRegion &region,
POINT ptDst = {r.x(), r.y()};
POINT ptSrc = {0, 0};
BLENDFUNCTION blend = {AC_SRC_OVER, 0, BYTE(qRound(255.0 * rw->opacity())), AC_SRC_ALPHA};
- if (QWindowsContext::user32dll.updateLayeredWindowIndirect) {
- RECT dirty = {dirtyRect.x(), dirtyRect.y(),
- dirtyRect.x() + dirtyRect.width(), dirtyRect.y() + dirtyRect.height()};
- UPDATELAYEREDWINDOWINFO info = {sizeof(info), NULL, &ptDst, &size, m_image->hdc(), &ptSrc, 0, &blend, ULW_ALPHA, &dirty};
- const BOOL result = QWindowsContext::user32dll.updateLayeredWindowIndirect(rw->handle(), &info);
- if (!result)
- qErrnoWarning("UpdateLayeredWindowIndirect failed for ptDst=(%d, %d),"
- " size=(%dx%d), dirty=(%dx%d %d, %d)", r.x(), r.y(),
- r.width(), r.height(), dirtyRect.width(), dirtyRect.height(),
- dirtyRect.x(), dirtyRect.y());
- } else {
- QWindowsContext::user32dll.updateLayeredWindow(rw->handle(), NULL, &ptDst, &size, m_image->hdc(), &ptSrc, 0, &blend, ULW_ALPHA);
- }
+ RECT dirty = {dirtyRect.x(), dirtyRect.y(),
+ dirtyRect.x() + dirtyRect.width(), dirtyRect.y() + dirtyRect.height()};
+ UPDATELAYEREDWINDOWINFO info = {sizeof(info), NULL, &ptDst, &size, m_image->hdc(), &ptSrc, 0, &blend, ULW_ALPHA, &dirty};
+ const BOOL result = UpdateLayeredWindowIndirect(rw->handle(), &info);
+ if (!result)
+ qErrnoWarning("UpdateLayeredWindowIndirect failed for ptDst=(%d, %d),"
+ " size=(%dx%d), dirty=(%dx%d %d, %d)", r.x(), r.y(),
+ r.width(), r.height(), dirtyRect.width(), dirtyRect.height(),
+ dirtyRect.x(), dirtyRect.y());
} else {
-#endif
const HDC dc = rw->getDC();
if (!dc) {
qErrnoWarning("%s: GetDC failed", __FUNCTION__);
@@ -129,9 +123,7 @@ void QWindowsBackingStore::flush(QWindow *window, const QRegion &region,
qErrnoWarning(int(lastError), "%s: BitBlt failed", __FUNCTION__);
}
rw->releaseDC();
-#ifndef Q_OS_WINCE
}
-#endif
// Write image for debug purposes.
if (QWindowsContext::verbose > 2 && lcQpaBackingStore().isDebugEnabled()) {
@@ -175,7 +167,7 @@ void QWindowsBackingStore::resize(const QSize &size, const QRegion &region)
staticRegion &= QRect(0, 0, newimg.width(), newimg.height());
QPainter painter(&newimg);
painter.setCompositionMode(QPainter::CompositionMode_Source);
- foreach (const QRect &rect, staticRegion.rects())
+ for (const QRect &rect : staticRegion)
painter.drawImage(rect, oldimg, rect);
}
@@ -190,10 +182,9 @@ bool QWindowsBackingStore::scroll(const QRegion &area, int dx, int dy)
if (m_image.isNull() || m_image->image().isNull())
return false;
- const QVector<QRect> rects = area.rects();
const QPoint offset(dx, dy);
- for (int i = 0; i < rects.size(); ++i)
- qt_scrollRectInImage(m_image->image(), rects.at(i), offset);
+ for (const QRect &rect : area)
+ qt_scrollRectInImage(m_image->image(), rect, offset);
return true;
}
@@ -207,7 +198,7 @@ void QWindowsBackingStore::beginPaint(const QRegion &region)
QPainter p(&m_image->image());
p.setCompositionMode(QPainter::CompositionMode_Source);
const QColor blank = Qt::transparent;
- foreach (const QRect &r, region.rects())
+ for (const QRect &r : region)
p.fillRect(r, blank);
}
}
@@ -219,8 +210,6 @@ HDC QWindowsBackingStore::getDC() const
return 0;
}
-#ifndef QT_NO_OPENGL
-
QImage QWindowsBackingStore::toImage() const
{
if (m_image.isNull()) {
@@ -230,6 +219,4 @@ QImage QWindowsBackingStore::toImage() const
return m_image.data()->image();
}
-#endif // !QT_NO_OPENGL
-
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsbackingstore.h b/src/plugins/platforms/windows/qwindowsbackingstore.h
index 26c79348a9..46a7fcc676 100644
--- a/src/plugins/platforms/windows/qwindowsbackingstore.h
+++ b/src/plugins/platforms/windows/qwindowsbackingstore.h
@@ -40,7 +40,7 @@
#ifndef QWINDOWSBACKINGSTORE_H
#define QWINDOWSBACKINGSTORE_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <qpa/qplatformbackingstore.h>
#include <QtCore/QScopedPointer>
@@ -65,9 +65,7 @@ public:
HDC getDC() const;
-#ifndef QT_NO_OPENGL
QImage toImage() const Q_DECL_OVERRIDE;
-#endif
private:
QScopedPointer<QWindowsNativeImage> m_image;
diff --git a/src/plugins/platforms/windows/qwindowsclipboard.cpp b/src/plugins/platforms/windows/qwindowsclipboard.cpp
index d527e07308..d4a7e27762 100644
--- a/src/plugins/platforms/windows/qwindowsclipboard.cpp
+++ b/src/plugins/platforms/windows/qwindowsclipboard.cpp
@@ -53,7 +53,7 @@
#include <QtCore/QVariant>
#include <QtCore/QUrl>
-#include <QtPlatformSupport/private/qwindowsguieventdispatcher_p.h>
+#include <QtEventDispatcherSupport/private/qwindowsguieventdispatcher_p.h>
QT_BEGIN_NAMESPACE
@@ -237,8 +237,7 @@ void QWindowsClipboard::propagateClipboardMessage(UINT message, WPARAM wParam, L
return;
// In rare cases, a clipboard viewer can hang (application crashed,
// suspended by a shell prompt 'Select' or debugger).
- if (QWindowsContext::user32dll.isHungAppWindow
- && QWindowsContext::user32dll.isHungAppWindow(m_nextClipboardViewer)) {
+ if (IsHungAppWindow(m_nextClipboardViewer)) {
qWarning("Cowardly refusing to send clipboard message to hung application...");
return;
}
diff --git a/src/plugins/platforms/windows/qwindowscontext.cpp b/src/plugins/platforms/windows/qwindowscontext.cpp
index 1dbac78fca..1a03df6ac2 100644
--- a/src/plugins/platforms/windows/qwindowscontext.cpp
+++ b/src/plugins/platforms/windows/qwindowscontext.cpp
@@ -52,7 +52,7 @@
#ifndef QT_NO_ACCESSIBILITY
# include "accessible/qwindowsaccessibility.h"
#endif
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
# include <private/qsessionmanager_p.h>
# include "qwindowssessionmanager.h"
#endif
@@ -72,21 +72,18 @@
#include <QtCore/QScopedArrayPointer>
#include <QtCore/private/qsystemlibrary_p.h>
-#include <QtPlatformSupport/private/qwindowsguieventdispatcher_p.h>
+#include <QtEventDispatcherSupport/private/qwindowsguieventdispatcher_p.h>
#include <stdlib.h>
#include <stdio.h>
#include <windowsx.h>
-#ifndef Q_OS_WINCE
-# include <comdef.h>
-#endif
+#include <comdef.h>
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcQpaWindows, "qt.qpa.windows")
Q_LOGGING_CATEGORY(lcQpaBackingStore, "qt.qpa.backingstore")
Q_LOGGING_CATEGORY(lcQpaEvents, "qt.qpa.events")
-Q_LOGGING_CATEGORY(lcQpaFonts, "qt.qpa.fonts")
Q_LOGGING_CATEGORY(lcQpaGl, "qt.qpa.gl")
Q_LOGGING_CATEGORY(lcQpaMime, "qt.qpa.mime")
Q_LOGGING_CATEGORY(lcQpaInputMethods, "qt.qpa.input.methods")
@@ -100,45 +97,29 @@ int QWindowsContext::verbose = 0;
# define LANG_SYRIAC 0x5a
#endif
-static inline bool useRTL_Extensions(QSysInfo::WinVersion ver)
+static inline bool useRTL_Extensions()
{
- // This is SDK dependent on CE so out of scope for now
- if (QSysInfo::windowsVersion() & QSysInfo::WV_CE_based)
- return false;
- if ((ver & QSysInfo::WV_NT_based) && (ver >= QSysInfo::WV_VISTA)) {
- // Since the IsValidLanguageGroup/IsValidLocale functions always return true on
- // Vista, check the Keyboard Layouts for enabling RTL.
- if (const int nLayouts = GetKeyboardLayoutList(0, 0)) {
- QScopedArrayPointer<HKL> lpList(new HKL[nLayouts]);
- GetKeyboardLayoutList(nLayouts, lpList.data());
- for (int i = 0; i < nLayouts; ++i) {
- switch (PRIMARYLANGID((quintptr)lpList[i])) {
- case LANG_ARABIC:
- case LANG_HEBREW:
- case LANG_FARSI:
- case LANG_SYRIAC:
- return true;
- default:
- break;
- }
+ // Since the IsValidLanguageGroup/IsValidLocale functions always return true on
+ // Vista, check the Keyboard Layouts for enabling RTL.
+ if (const int nLayouts = GetKeyboardLayoutList(0, 0)) {
+ QScopedArrayPointer<HKL> lpList(new HKL[nLayouts]);
+ GetKeyboardLayoutList(nLayouts, lpList.data());
+ for (int i = 0; i < nLayouts; ++i) {
+ switch (PRIMARYLANGID((quintptr)lpList[i])) {
+ case LANG_ARABIC:
+ case LANG_HEBREW:
+ case LANG_FARSI:
+ case LANG_SYRIAC:
+ return true;
+ default:
+ break;
}
}
- return false;
- } // NT/Vista
-#ifndef Q_OS_WINCE
- // Pre-NT: figure out whether a RTL language is installed
- return 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)
- || IsValidLocale(MAKELCID(MAKELANGID(LANG_SYRIAC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED)
- || IsValidLocale(MAKELCID(MAKELANGID(LANG_FARSI, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED);
-#else
+ }
return false;
-#endif
}
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
static inline QWindowsSessionManager *platformSessionManager() {
QGuiApplicationPrivate *guiPrivate = static_cast<QGuiApplicationPrivate*>(QObjectPrivate::get(qApp));
QSessionManagerPrivate *managerPrivate = static_cast<QSessionManagerPrivate*>(QObjectPrivate::get(guiPrivate->session_manager));
@@ -161,13 +142,8 @@ static inline QWindowsSessionManager *platformSessionManager() {
\internal
\ingroup qt-lighthouse-win
*/
-
-#ifndef Q_OS_WINCE
-
QWindowsUser32DLL::QWindowsUser32DLL() :
- setLayeredWindowAttributes(0), updateLayeredWindow(0),
- updateLayeredWindowIndirect(0),
- isHungAppWindow(0), isTouchWindow(0),
+ isTouchWindow(0),
registerTouchWindow(0), unregisterTouchWindow(0),
getTouchInputInfo(0), closeTouchInputHandle(0), setProcessDPIAware(0),
addClipboardFormatListener(0), removeClipboardFormatListener(0),
@@ -178,20 +154,11 @@ QWindowsUser32DLL::QWindowsUser32DLL() :
void QWindowsUser32DLL::init()
{
QSystemLibrary library(QStringLiteral("user32"));
- // MinGW (g++ 3.4.5) accepts only C casts.
- setLayeredWindowAttributes = (SetLayeredWindowAttributes)(library.resolve("SetLayeredWindowAttributes"));
- updateLayeredWindow = (UpdateLayeredWindow)(library.resolve("UpdateLayeredWindow"));
- if (Q_UNLIKELY(!setLayeredWindowAttributes || !updateLayeredWindow))
- qFatal("This version of Windows is not supported (User32.dll is missing the symbols 'SetLayeredWindowAttributes', 'UpdateLayeredWindow').");
-
- updateLayeredWindowIndirect = (UpdateLayeredWindowIndirect)(library.resolve("UpdateLayeredWindowIndirect"));
- isHungAppWindow = (IsHungAppWindow)library.resolve("IsHungAppWindow");
setProcessDPIAware = (SetProcessDPIAware)library.resolve("SetProcessDPIAware");
- if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) {
- addClipboardFormatListener = (AddClipboardFormatListener)library.resolve("AddClipboardFormatListener");
- removeClipboardFormatListener = (RemoveClipboardFormatListener)library.resolve("RemoveClipboardFormatListener");
- }
+ addClipboardFormatListener = (AddClipboardFormatListener)library.resolve("AddClipboardFormatListener");
+ removeClipboardFormatListener = (RemoveClipboardFormatListener)library.resolve("RemoveClipboardFormatListener");
+
getDisplayAutoRotationPreferences = (GetDisplayAutoRotationPreferences)library.resolve("GetDisplayAutoRotationPreferences");
setDisplayAutoRotationPreferences = (SetDisplayAutoRotationPreferences)library.resolve("SetDisplayAutoRotationPreferences");
}
@@ -209,38 +176,6 @@ bool QWindowsUser32DLL::initTouch()
return isTouchWindow && registerTouchWindow && unregisterTouchWindow && getTouchInputInfo && closeTouchInputHandle;
}
-/*!
- \class QWindowsShell32DLL
- \brief Struct that contains dynamically resolved symbols of Shell32.dll.
-
- The stub libraries shipped with the MinGW compiler miss some of the
- functions. They need to be retrieved dynamically.
-
- \sa QWindowsUser32DLL
-
- \internal
- \ingroup qt-lighthouse-win
-*/
-
-QWindowsShell32DLL::QWindowsShell32DLL()
- : sHCreateItemFromParsingName(0)
- , sHGetKnownFolderIDList(0)
- , sHGetStockIconInfo(0)
- , sHGetImageList(0)
- , sHCreateItemFromIDList(0)
-{
-}
-
-void QWindowsShell32DLL::init()
-{
- QSystemLibrary library(QStringLiteral("shell32"));
- sHCreateItemFromParsingName = (SHCreateItemFromParsingName)(library.resolve("SHCreateItemFromParsingName"));
- sHGetKnownFolderIDList = (SHGetKnownFolderIDList)(library.resolve("SHGetKnownFolderIDList"));
- sHGetStockIconInfo = (SHGetStockIconInfo)library.resolve("SHGetStockIconInfo");
- sHGetImageList = (SHGetImageList)library.resolve("SHGetImageList");
- sHCreateItemFromIDList = (SHCreateItemFromIDList)library.resolve("SHCreateItemFromIDList");
-}
-
QWindowsShcoreDLL::QWindowsShcoreDLL()
: getProcessDpiAwareness(0)
, setProcessDpiAwareness(0)
@@ -259,11 +194,8 @@ void QWindowsShcoreDLL::init()
}
QWindowsUser32DLL QWindowsContext::user32dll;
-QWindowsShell32DLL QWindowsContext::shell32dll;
QWindowsShcoreDLL QWindowsContext::shcoredll;
-#endif // !Q_OS_WINCE
-
QWindowsContext *QWindowsContext::m_instance = 0;
/*!
@@ -292,7 +224,7 @@ struct QWindowsContextPrivate {
QWindowsMimeConverter m_mimeConverter;
QWindowsScreenManager m_screenManager;
QSharedPointer<QWindowCreationContext> m_creationContext;
-#if !defined(QT_NO_TABLETEVENT) && !defined(Q_OS_WINCE)
+#if !defined(QT_NO_TABLETEVENT)
QScopedPointer<QWindowsTabletSupport> m_tabletSupport;
#endif
const HRESULT m_oleInitializeResult;
@@ -307,18 +239,14 @@ QWindowsContextPrivate::QWindowsContextPrivate()
, m_eventType(QByteArrayLiteral("windows_generic_MSG"))
, m_lastActiveWindow(0), m_asyncExpose(0)
{
- const QSysInfo::WinVersion ver = QSysInfo::windowsVersion();
-#ifndef Q_OS_WINCE
QWindowsContext::user32dll.init();
- QWindowsContext::shell32dll.init();
QWindowsContext::shcoredll.init();
if (m_mouseHandler.touchDevice() && QWindowsContext::user32dll.initTouch())
m_systemInfo |= QWindowsContext::SI_SupportsTouch;
-#endif // !Q_OS_WINCE
m_displayContext = GetDC(0);
m_defaultDPI = GetDeviceCaps(m_displayContext, LOGPIXELSY);
- if (useRTL_Extensions(ver)) {
+ if (useRTL_Extensions()) {
m_systemInfo |= QWindowsContext::SI_RTL_Extensions;
m_keyMapper.setUseRTLExtensions(true);
}
@@ -339,7 +267,7 @@ QWindowsContext::QWindowsContext() :
const QByteArray bv = qgetenv("QT_QPA_VERBOSE");
if (!bv.isEmpty())
QLoggingCategory::setFilterRules(QString::fromLocal8Bit(bv));
-#if !defined(QT_NO_TABLETEVENT) && !defined(Q_OS_WINCE)
+#if !defined(QT_NO_TABLETEVENT)
d->m_tabletSupport.reset(QWindowsTabletSupport::create());
qCDebug(lcQpaTablet) << "Tablet support: " << (d->m_tabletSupport.isNull() ? QStringLiteral("None") : d->m_tabletSupport->description());
#endif
@@ -347,7 +275,7 @@ QWindowsContext::QWindowsContext() :
QWindowsContext::~QWindowsContext()
{
-#if !defined(QT_NO_TABLETEVENT) && !defined(Q_OS_WINCE)
+#if !defined(QT_NO_TABLETEVENT)
d->m_tabletSupport.reset(); // Destroy internal window before unregistering classes.
#endif
unregisterWindowClasses();
@@ -372,12 +300,10 @@ bool QWindowsContext::initTouch(unsigned integrationOptions)
if (!touchDevice)
return false;
-#ifndef Q_OS_WINCE
if (!QWindowsContext::user32dll.initTouch()) {
delete touchDevice;
return false;
}
-#endif // !Q_OS_WINCE
if (!(integrationOptions & QWindowsIntegration::DontPassOsMouseEventsSynthesizedFromTouch))
touchDevice->setCapabilities(touchDevice->capabilities() | QTouchDevice::MouseEmulation);
@@ -390,7 +316,7 @@ bool QWindowsContext::initTouch(unsigned integrationOptions)
void QWindowsContext::setTabletAbsoluteRange(int a)
{
-#if !defined(QT_NO_TABLETEVENT) && !defined(Q_OS_WINCE)
+#if !defined(QT_NO_TABLETEVENT)
if (!d->m_tabletSupport.isNull())
d->m_tabletSupport->setAbsoluteRange(a);
#else
@@ -400,19 +326,16 @@ void QWindowsContext::setTabletAbsoluteRange(int a)
int QWindowsContext::processDpiAwareness()
{
-#ifndef Q_OS_WINCE
int result;
if (QWindowsContext::shcoredll.getProcessDpiAwareness
&& SUCCEEDED(QWindowsContext::shcoredll.getProcessDpiAwareness(NULL, &result))) {
return result;
}
-#endif // !Q_OS_WINCE
return -1;
}
void QWindowsContext::setProcessDpiAwareness(QtWindows::ProcessDpiAwareness dpiAwareness)
{
-#ifndef Q_OS_WINCE
qCDebug(lcQpaWindows) << __FUNCTION__ << dpiAwareness;
if (QWindowsContext::shcoredll.isValid()) {
const HRESULT hr = QWindowsContext::shcoredll.setProcessDpiAwareness(dpiAwareness);
@@ -429,9 +352,6 @@ void QWindowsContext::setProcessDpiAwareness(QtWindows::ProcessDpiAwareness dpiA
qErrnoWarning("SetProcessDPIAware() failed");
}
}
-#else // !Q_OS_WINCE
- Q_UNUSED(dpiAwareness)
-#endif
}
QWindowsContext *QWindowsContext::instance()
@@ -563,19 +483,14 @@ QString QWindowsContext::registerWindowClass(QString cname,
if (d->m_registeredWindowClassNames.contains(cname)) // already registered in our list
return cname;
-#ifndef Q_OS_WINCE
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
-#else
- WNDCLASS wc;
-#endif
wc.style = style;
wc.lpfnWndProc = proc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = appInstance;
wc.hCursor = 0;
-#ifndef Q_OS_WINCE
wc.hbrBackground = brush;
if (icon) {
wc.hIcon = static_cast<HICON>(LoadImage(appInstance, L"IDI_ICON1", IMAGE_ICON, 0, 0, LR_DEFAULTSIZE));
@@ -591,22 +506,10 @@ QString QWindowsContext::registerWindowClass(QString cname,
wc.hIcon = 0;
wc.hIconSm = 0;
}
-#else
- if (icon) {
- wc.hIcon = (HICON)LoadImage(appInstance, L"IDI_ICON1", IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
- } else {
- wc.hIcon = 0;
- }
-#endif
wc.lpszMenuName = 0;
wc.lpszClassName = reinterpret_cast<LPCWSTR>(cname.utf16());
-#ifndef Q_OS_WINCE
ATOM atom = RegisterClassEx(&wc);
-#else
- ATOM atom = RegisterClass(&wc);
-#endif
-
if (!atom)
qErrnoWarning("QApplication::regClass: Registering window class '%s' failed.",
qPrintable(cname));
@@ -724,28 +627,14 @@ static inline bool findPlatformWindowHelper(const POINT &screenPoint, unsigned c
POINT point = screenPoint;
ScreenToClient(*hwnd, &point);
// Returns parent if inside & none matched.
-#ifndef Q_OS_WINCE
const HWND child = ChildWindowFromPointEx(*hwnd, point, cwexFlags);
-#else
-// Under Windows CE we don't use ChildWindowFromPointEx as it's not available
-// and ChildWindowFromPoint does not work properly.
- Q_UNUSED(cwexFlags)
- const HWND child = WindowFromPoint(point);
-#endif
if (!child || child == *hwnd)
return false;
if (QWindowsWindow *window = context->findPlatformWindow(child)) {
*result = window;
*hwnd = child;
-#ifndef Q_OS_WINCE
return true;
-#else
-// WindowFromPoint does not return same handle in two sequential calls, which leads
-// to an endless loop, but calling WindowFromPoint once is good enough.
- return false;
-#endif
}
-#ifndef Q_OS_WINCE // Does not have WS_EX_TRANSPARENT .
// QTBUG-40555: despite CWP_SKIPINVISIBLE, it is possible to hit on invisible
// full screen windows of other applications that have WS_EX_TRANSPARENT set
// (for example created by screen sharing applications). In that case, try to
@@ -761,7 +650,6 @@ static inline bool findPlatformWindowHelper(const POINT &screenPoint, unsigned c
return true;
}
}
-#endif // !Q_OS_WINCE
*hwnd = child;
return true;
}
@@ -788,7 +676,7 @@ QWindowsScreenManager &QWindowsContext::screenManager()
QWindowsTabletSupport *QWindowsContext::tabletSupport() const
{
-#if !defined(QT_NO_TABLETEVENT) && !defined(Q_OS_WINCE)
+#if !defined(QT_NO_TABLETEVENT)
return d->m_tabletSupport.data();
#else
return 0;
@@ -814,7 +702,6 @@ HWND QWindowsContext::createDummyWindow(const QString &classNameIn,
HWND_MESSAGE, NULL, static_cast<HINSTANCE>(GetModuleHandle(0)), NULL);
}
-#ifndef Q_OS_WINCE
// Re-engineered from the inline function _com_error::ErrorMessage().
// We cannot use it directly since it uses swprintf_s(), which is not
// present in the MSVCRT.DLL found on Windows XP (QTBUG-35617).
@@ -833,7 +720,6 @@ static inline QString errorMessageFromComError(const _com_error &comError)
return QString::asprintf("IDispatch error #%u", uint(wCode));
return QString::asprintf("Unknown error 0x0%x", uint(comError.Error()));
}
-#endif // !Q_OS_WINCE
/*!
\brief Common COM error strings.
@@ -901,12 +787,10 @@ QByteArray QWindowsContext::comErrorString(HRESULT hr)
default:
break;
}
-#ifndef Q_OS_WINCE
_com_error error(hr);
result += QByteArrayLiteral(" (");
result += errorMessageFromComError(error);
result += ')';
-#endif // !Q_OS_WINCE
return result;
}
@@ -942,9 +826,7 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
ClientToScreen(msg.hwnd, &msg.pt);
}
} else {
-#ifndef Q_OS_WINCE
GetCursorPos(&msg.pt);
-#endif
}
// Run the native event filters.
@@ -987,7 +869,7 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
switch (et) {
case QtWindows::GestureEvent:
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
return platformSessionManager()->isInteractionBlocked() ? true : d->m_mouseHandler.translateGestureEvent(platformWindow->window(), hwnd, et, msg, result);
#else
return d->m_mouseHandler.translateGestureEvent(platformWindow->window(), hwnd, et, msg, result);
@@ -1028,11 +910,9 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
// Pass on to current creation context
if (!platformWindow && !d->m_creationContext.isNull()) {
switch (et) {
-#ifndef Q_OS_WINCE // maybe available on some SDKs revisit WM_GETMINMAXINFO
case QtWindows::QuerySizeHints:
d->m_creationContext->applyToMinMaxInfo(reinterpret_cast<MINMAXINFO *>(lParam));
return true;
-#endif
case QtWindows::ResizeEvent:
d->m_creationContext->obtainedGeometry.setSize(QSize(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
return true;
@@ -1064,13 +944,14 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
switch (et) {
case QtWindows::KeyboardLayoutChangeEvent:
if (QWindowsInputContext *wic = windowsInputContext())
- wic->handleInputLanguageChanged(wParam, lParam); // fallthrough intended.
+ wic->handleInputLanguageChanged(wParam, lParam);
+ Q_FALLTHROUGH();
case QtWindows::KeyDownEvent:
case QtWindows::KeyEvent:
case QtWindows::InputMethodKeyEvent:
case QtWindows::InputMethodKeyDownEvent:
case QtWindows::AppCommandEvent:
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
return platformSessionManager()->isInteractionBlocked() ? true : d->m_keyMapper.translateKeyEvent(platformWindow->window(), hwnd, msg, result);
#else
return d->m_keyMapper.translateKeyEvent(platformWindow->window(), hwnd, msg, result);
@@ -1081,7 +962,6 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
case QtWindows::ResizeEvent:
platformWindow->handleResized(static_cast<int>(wParam));
return true;
-#ifndef Q_OS_WINCE // maybe available on some SDKs revisit WM_GETMINMAXINFO
case QtWindows::QuerySizeHints:
platformWindow->getSizeHints(reinterpret_cast<MINMAXINFO *>(lParam));
return true;// maybe available on some SDKs revisit WM_NCCALCSIZE
@@ -1091,30 +971,18 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
return platformWindow->handleNonClientHitTest(QPoint(msg.pt.x, msg.pt.y), result);
case QtWindows::GeometryChangingEvent:
return platformWindow->QWindowsWindow::handleGeometryChanging(&msg);
-#endif // !Q_OS_WINCE
case QtWindows::ExposeEvent:
return platformWindow->handleWmPaint(hwnd, message, wParam, lParam);
case QtWindows::NonClientMouseEvent:
if (platformWindow->frameStrutEventsEnabled())
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
return platformSessionManager()->isInteractionBlocked() ? true : d->m_mouseHandler.translateMouseEvent(platformWindow->window(), hwnd, et, msg, result);
#else
return d->m_mouseHandler.translateMouseEvent(platformWindow->window(), hwnd, et, msg, result);
#endif
break;
-/* the mouse tracking on windows already handles the reset of the cursor
- * and does not like somebody else handling it.
- * on WINCE its necessary to handle this event to get the correct cursor
- */
-#ifdef Q_OS_WINCE
- case QtWindows::CursorEvent:
- {
- QWindowsWindow::baseWindowOf(platformWindow->window())->applyCursor();
- return true;
- }
-#endif
case QtWindows::ScrollEvent:
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
return platformSessionManager()->isInteractionBlocked() ? true : d->m_mouseHandler.translateScrollEvent(platformWindow->window(), hwnd, msg, result);
#else
return d->m_mouseHandler.translateScrollEvent(platformWindow->window(), hwnd, msg, result);
@@ -1122,13 +990,13 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
case QtWindows::MouseWheelEvent:
case QtWindows::MouseEvent:
case QtWindows::LeaveEvent:
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
return platformSessionManager()->isInteractionBlocked() ? true : d->m_mouseHandler.translateMouseEvent(platformWindow->window(), hwnd, et, msg, result);
#else
return d->m_mouseHandler.translateMouseEvent(platformWindow->window(), hwnd, et, msg, result);
#endif
case QtWindows::TouchEvent:
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
return platformSessionManager()->isInteractionBlocked() ? true : d->m_mouseHandler.translateTouchEvent(platformWindow->window(), hwnd, et, msg, result);
#else
return d->m_mouseHandler.translateTouchEvent(platformWindow->window(), hwnd, et, msg, result);
@@ -1161,7 +1029,6 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
case QtWindows::CompositionSettingsChanged:
platformWindow->handleCompositionSettingsChanged();
return true;
-#ifndef Q_OS_WINCE
case QtWindows::ActivateWindowEvent:
if (platformWindow->window()->flags() & Qt::WindowDoesNotAcceptFocus) {
*result = LRESULT(MA_NOACTIVATE);
@@ -1184,7 +1051,6 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
return true;
}
break;
-#endif
#ifndef QT_NO_CONTEXTMENU
case QtWindows::ContextMenu:
return handleContextMenuEvent(platformWindow->window(), msg);
@@ -1195,7 +1061,7 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
return true;
#endif
} break;
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
case QtWindows::QueryEndSessionApplicationEvent: {
QWindowsSessionManager *sessionManager = platformSessionManager();
if (sessionManager->isActive()) { // bogus message from windows
@@ -1235,7 +1101,7 @@ bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
}
return true;
}
-#endif // !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#endif // !defined(QT_NO_SESSIONMANAGER)
default:
break;
}
diff --git a/src/plugins/platforms/windows/qwindowscontext.h b/src/plugins/platforms/windows/qwindowscontext.h
index 3559335747..9dfde67797 100644
--- a/src/plugins/platforms/windows/qwindowscontext.h
+++ b/src/plugins/platforms/windows/qwindowscontext.h
@@ -41,7 +41,7 @@
#define QWINDOWSCONTEXT_H
#include "qtwindowsglobal.h"
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/QScopedPointer>
#include <QtCore/QSharedPointer>
@@ -59,7 +59,6 @@ QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(lcQpaWindows)
Q_DECLARE_LOGGING_CATEGORY(lcQpaBackingStore)
Q_DECLARE_LOGGING_CATEGORY(lcQpaEvents)
-Q_DECLARE_LOGGING_CATEGORY(lcQpaFonts)
Q_DECLARE_LOGGING_CATEGORY(lcQpaGl)
Q_DECLARE_LOGGING_CATEGORY(lcQpaMime)
Q_DECLARE_LOGGING_CATEGORY(lcQpaInputMethods)
@@ -79,38 +78,23 @@ class QPoint;
class QKeyEvent;
class QTouchDevice;
-#ifndef Q_OS_WINCE
struct QWindowsUser32DLL
{
QWindowsUser32DLL();
inline void init();
inline bool initTouch();
- typedef BOOL (WINAPI *IsTouchWindow)(HWND, PULONG);
+ typedef BOOL (WINAPI *IsTouchWindow)(HWND, PULONG); // Windows 7
typedef BOOL (WINAPI *RegisterTouchWindow)(HWND, ULONG);
typedef BOOL (WINAPI *UnregisterTouchWindow)(HWND);
typedef BOOL (WINAPI *GetTouchInputInfo)(HANDLE, UINT, PVOID, int);
typedef BOOL (WINAPI *CloseTouchInputHandle)(HANDLE);
- typedef BOOL (WINAPI *SetLayeredWindowAttributes)(HWND, COLORREF, BYTE, DWORD);
- typedef BOOL (WINAPI *UpdateLayeredWindow)(HWND, HDC , const POINT *,
- const SIZE *, HDC, const POINT *, COLORREF,
- const BLENDFUNCTION *, DWORD);
- typedef BOOL (WINAPI *UpdateLayeredWindowIndirect)(HWND, const UPDATELAYEREDWINDOWINFO *);
- typedef BOOL (WINAPI *IsHungAppWindow)(HWND);
typedef BOOL (WINAPI *SetProcessDPIAware)();
typedef BOOL (WINAPI *AddClipboardFormatListener)(HWND);
typedef BOOL (WINAPI *RemoveClipboardFormatListener)(HWND);
typedef BOOL (WINAPI *GetDisplayAutoRotationPreferences)(DWORD *);
typedef BOOL (WINAPI *SetDisplayAutoRotationPreferences)(DWORD);
- // Functions missing in Q_CC_GNU stub libraries.
- SetLayeredWindowAttributes setLayeredWindowAttributes;
- UpdateLayeredWindow updateLayeredWindow;
-
- // Functions missing in older versions of Windows
- UpdateLayeredWindowIndirect updateLayeredWindowIndirect;
- IsHungAppWindow isHungAppWindow;
-
// Touch functions from Windows 7 onwards (also for use with Q_CC_MSVC).
IsTouchWindow isTouchWindow;
RegisterTouchWindow registerTouchWindow;
@@ -121,7 +105,8 @@ struct QWindowsUser32DLL
// Windows Vista onwards
SetProcessDPIAware setProcessDPIAware;
- // Clipboard listeners, Windows Vista onwards
+ // Clipboard listeners are present on Windows Vista onwards
+ // but missing in MinGW 4.9 stub libs. Can be removed in MinGW 5.
AddClipboardFormatListener addClipboardFormatListener;
RemoveClipboardFormatListener removeClipboardFormatListener;
@@ -130,24 +115,6 @@ struct QWindowsUser32DLL
SetDisplayAutoRotationPreferences setDisplayAutoRotationPreferences;
};
-struct QWindowsShell32DLL
-{
- QWindowsShell32DLL();
- inline void init();
-
- typedef HRESULT (WINAPI *SHCreateItemFromParsingName)(PCWSTR, IBindCtx *, const GUID&, void **);
- typedef HRESULT (WINAPI *SHGetKnownFolderIDList)(const GUID &, DWORD, HANDLE, PIDLIST_ABSOLUTE *);
- typedef HRESULT (WINAPI *SHGetStockIconInfo)(int , int , _SHSTOCKICONINFO *);
- typedef HRESULT (WINAPI *SHGetImageList)(int, REFIID , void **);
- typedef HRESULT (WINAPI *SHCreateItemFromIDList)(PCIDLIST_ABSOLUTE, REFIID, void **);
-
- SHCreateItemFromParsingName sHCreateItemFromParsingName;
- SHGetKnownFolderIDList sHGetKnownFolderIDList;
- SHGetStockIconInfo sHGetStockIconInfo;
- SHGetImageList sHGetImageList;
- SHCreateItemFromIDList sHCreateItemFromIDList;
-};
-
// Shell scaling library (Windows 8.1 onwards)
struct QWindowsShcoreDLL {
QWindowsShcoreDLL();
@@ -163,8 +130,6 @@ struct QWindowsShcoreDLL {
GetDpiForMonitor getDpiForMonitor;
};
-#endif // Q_OS_WINCE
-
class QWindowsContext
{
Q_DISABLE_COPY(QWindowsContext)
@@ -236,11 +201,9 @@ public:
QWindowsMimeConverter &mimeConverter() const;
QWindowsScreenManager &screenManager();
QWindowsTabletSupport *tabletSupport() const;
-#ifndef Q_OS_WINCE
+
static QWindowsUser32DLL user32dll;
- static QWindowsShell32DLL shell32dll;
static QWindowsShcoreDLL shcoredll;
-#endif
static QByteArray comErrorString(HRESULT hr);
bool asyncExpose() const;
diff --git a/src/plugins/platforms/windows/qwindowscursor.cpp b/src/plugins/platforms/windows/qwindowscursor.cpp
index d02648fade..1bebe88df7 100644
--- a/src/plugins/platforms/windows/qwindowscursor.cpp
+++ b/src/plugins/platforms/windows/qwindowscursor.cpp
@@ -56,7 +56,7 @@
static bool initResources()
{
-#if !defined (Q_OS_WINCE) && !defined (QT_NO_IMAGEFORMAT_PNG)
+#if !defined (QT_NO_IMAGEFORMAT_PNG)
Q_INIT_RESOURCE(cursors);
#endif
return true;
@@ -143,7 +143,6 @@ static HCURSOR createBitmapCursor(const QImage &bbits, const QImage &mbits,
if (hotSpot.y() < 0)
hotSpot.setY(height / 2);
const int n = qMax(1, width / 8);
-#if !defined(Q_OS_WINCE)
QScopedArrayPointer<uchar> xBits(new uchar[height * n]);
QScopedArrayPointer<uchar> xMask(new uchar[height * n]);
int x = 0;
@@ -164,54 +163,6 @@ static HCURSOR createBitmapCursor(const QImage &bbits, const QImage &mbits,
}
return CreateCursor(GetModuleHandle(0), hotSpot.x(), hotSpot.y(), width, height,
xBits.data(), xMask.data());
-#elif defined(GWES_ICONCURS) // Q_OS_WINCE
- // Windows CE only supports fixed cursor size.
- int sysW = GetSystemMetrics(SM_CXCURSOR);
- int sysH = GetSystemMetrics(SM_CYCURSOR);
- int sysN = qMax(1, sysW / 8);
- uchar* xBits = new uchar[sysH * sysN];
- uchar* xMask = new uchar[sysH * sysN];
- int x = 0;
- for (int i = 0; i < sysH; ++i) {
- if (i >= height) {
- memset(&xBits[x] , 255, sysN);
- memset(&xMask[x] , 0, sysN);
- x += sysN;
- } else {
- int fillWidth = n > sysN ? sysN : n;
- const uchar *bits = bbits.constScanLine(i);
- const uchar *mask = mbits.constScanLine(i);
- for (int j = 0; j < fillWidth; ++j) {
- uchar b = bits[j];
- uchar m = mask[j];
- if (invb)
- b ^= 0xFF;
- if (invm)
- m ^= 0xFF;
- xBits[x] = ~m;
- xMask[x] = b ^ m;
- ++x;
- }
- for (int j = fillWidth; j < sysN; ++j ) {
- xBits[x] = 255;
- xMask[x] = 0;
- ++x;
- }
- }
- }
-
- HCURSOR hcurs = CreateCursor(qWinAppInst(), hotSpot.x(), hotSpot.y(), sysW, sysH,
- xBits, xMask);
- delete [] xBits;
- delete [] xMask;
- return hcurs;
-#else
- Q_UNUSED(n);
- Q_UNUSED(invm);
- Q_UNUSED(invb);
- Q_UNUSED(mbits);
- return 0;
-#endif
}
// Create a cursor from image and mask of the format QImage::Format_Mono.
@@ -252,7 +203,7 @@ static QSize systemCursorSize(const QPlatformScreen *screen = Q_NULLPTR)
return primaryScreenCursorSize;
}
-#if defined (Q_OS_WINCE) || defined (QT_NO_IMAGEFORMAT_PNG)
+#if defined (QT_NO_IMAGEFORMAT_PNG)
static inline QSize standardCursorSize() { return QSize(32, 32); }
@@ -468,7 +419,7 @@ QWindowsCursor::PixmapCursor QWindowsCursor::customCursor(Qt::CursorShape cursor
return QWindowsCursor::PixmapCursor();
}
-#else // Q_OS_WINCE || QT_NO_IMAGEFORMAT_PNG
+#else // QT_NO_IMAGEFORMAT_PNG
struct QWindowsCustomPngCursor {
Qt::CursorShape shape;
int size;
@@ -526,7 +477,7 @@ QWindowsCursor::PixmapCursor QWindowsCursor::customCursor(Qt::CursorShape cursor
QString::fromLatin1(bestFit->fileName));
return PixmapCursor(rawImage, QPoint(bestFit->hotSpotX, bestFit->hotSpotY));
}
-#endif // Q_OS_WINCE || QT_NO_IMAGEFORMAT_PNG
+#endif // !QT_NO_IMAGEFORMAT_PNG
struct QWindowsStandardCursorMapping {
Qt::CursorShape shape;
@@ -575,13 +526,8 @@ HCURSOR QWindowsCursor::createCursorFromShape(Qt::CursorShape cursorShape, const
// Load available standard cursors from resources
const QWindowsStandardCursorMapping *sEnd = standardCursors + sizeof(standardCursors) / sizeof(standardCursors[0]);
for (const QWindowsStandardCursorMapping *s = standardCursors; s < sEnd; ++s) {
- if (s->shape == cursorShape) {
-#ifndef Q_OS_WINCE
+ if (s->shape == cursorShape)
return static_cast<HCURSOR>(LoadImage(0, s->resource, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED));
-#else
- return LoadCursor(0, s->resource);
-#endif
- }
}
qWarning("%s: Invalid cursor shape %d", __FUNCTION__, cursorShape);
@@ -677,7 +623,6 @@ QPoint QWindowsCursor::mousePosition()
QWindowsCursor::CursorState QWindowsCursor::cursorState()
{
-#ifndef Q_OS_WINCE
enum { cursorShowing = 0x1, cursorSuppressed = 0x2 }; // Windows 8: CURSOR_SUPPRESSED
CURSORINFO cursorInfo;
cursorInfo.cbSize = sizeof(CURSORINFO);
@@ -687,7 +632,6 @@ QWindowsCursor::CursorState QWindowsCursor::cursorState()
if (cursorInfo.flags & cursorSuppressed)
return CursorSuppressed;
}
-#endif // !Q_OS_WINCE
return CursorHidden;
}
@@ -758,7 +702,6 @@ QPixmap QWindowsCursor::dragDefaultCursor(Qt::DropAction action) const
"...............XXXX....."};
if (m_ignoreDragCursor.isNull()) {
-#if !defined (Q_OS_WINCE)
HCURSOR cursor = LoadCursor(NULL, IDC_NO);
ICONINFO iconInfo = {0, 0, 0, 0, 0};
GetIconInfo(cursor, &iconInfo);
@@ -782,9 +725,6 @@ QPixmap QWindowsCursor::dragDefaultCursor(Qt::DropAction action) const
DeleteObject(iconInfo.hbmMask);
DeleteObject(iconInfo.hbmColor);
DestroyCursor(cursor);
-#else // !Q_OS_WINCE
- m_ignoreDragCursor = QPixmap(ignoreDragCursorXpmC);
-#endif // !Q_OS_WINCE
}
return m_ignoreDragCursor;
}
diff --git a/src/plugins/platforms/windows/qwindowscursor.h b/src/plugins/platforms/windows/qwindowscursor.h
index c0f9235c30..6fff5f9ab1 100644
--- a/src/plugins/platforms/windows/qwindowscursor.h
+++ b/src/plugins/platforms/windows/qwindowscursor.h
@@ -40,7 +40,7 @@
#ifndef QWINDOWSCURSOR_H
#define QWINDOWSCURSOR_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <qpa/qplatformcursor.h>
#include <QtCore/QSharedPointer>
diff --git a/src/plugins/platforms/windows/qwindowsdialoghelpers.cpp b/src/plugins/platforms/windows/qwindowsdialoghelpers.cpp
index 817728dca2..8f1358de6c 100644
--- a/src/plugins/platforms/windows/qwindowsdialoghelpers.cpp
+++ b/src/plugins/platforms/windows/qwindowsdialoghelpers.cpp
@@ -70,300 +70,10 @@
#include <algorithm>
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
// #define USE_NATIVE_COLOR_DIALOG /* Testing purposes only */
-#ifdef Q_CC_MINGW /* Add missing declarations for MinGW */
-
-#ifndef __IShellLibrary_FWD_DEFINED__
-
-/* Constants obtained by running the below stream operator for
- * CLSID, IID on the constants in the Windows SDK libraries. */
-
-static const IID IID_IFileOpenDialog = {0xd57c7288, 0xd4ad, 0x4768, {0xbe, 0x02, 0x9d, 0x96, 0x95, 0x32, 0xd9, 0x60}};
-static const IID IID_IFileSaveDialog = {0x84bccd23, 0x5fde, 0x4cdb,{0xae, 0xa4, 0xaf, 0x64, 0xb8, 0x3d, 0x78, 0xab}};
-#ifdef __MINGW64_VERSION_MAJOR
-static const IID q_IID_IShellItem = {0x43826d1e, 0xe718, 0x42ee, {0xbc, 0x55, 0xa1, 0xe2, 0x61, 0xc3, 0x7b, 0xfe}};
-#define IID_IShellItem q_IID_IShellItem
-#else
-static const IID IID_IShellItem = {0x43826d1e, 0xe718, 0x42ee, {0xbc, 0x55, 0xa1, 0xe2, 0x61, 0xc3, 0x7b, 0xfe}};
-static const IID IID_IShellItemArray = {0xb63ea76d, 0x1f85, 0x456f, {0xa1, 0x9c, 0x48, 0x15, 0x9e, 0xfa, 0x85, 0x8b}};
-# define LFF_FORCEFILESYSTEM 1
-#endif
-static const IID IID_IFileDialogEvents = {0x973510db, 0x7d7f, 0x452b,{0x89, 0x75, 0x74, 0xa8, 0x58, 0x28, 0xd3, 0x54}};
-static const CLSID CLSID_FileOpenDialog = {0xdc1c5a9c, 0xe88a, 0x4dde, {0xa5, 0xa1, 0x60, 0xf8, 0x2a, 0x20, 0xae, 0xf7}};
-static const CLSID CLSID_FileSaveDialog = {0xc0b4e2f3, 0xba21, 0x4773,{0x8d, 0xba, 0x33, 0x5e, 0xc9, 0x46, 0xeb, 0x8b}};
-
-typedef struct _COMDLG_FILTERSPEC
-{
- LPCWSTR pszName;
- LPCWSTR pszSpec;
-} COMDLG_FILTERSPEC;
-
-
-#define FOS_OVERWRITEPROMPT 0x2
-#define FOS_STRICTFILETYPES 0x4
-#define FOS_NOCHANGEDIR 0x8
-#define FOS_PICKFOLDERS 0x20
-#define FOS_FORCEFILESYSTEM 0x40
-#define FOS_ALLNONSTORAGEITEMS 0x80
-#define FOS_NOVALIDATE 0x100
-#define FOS_ALLOWMULTISELECT 0x200
-#define FOS_PATHMUSTEXIST 0x800
-#define FOS_FILEMUSTEXIST 0x1000
-#define FOS_CREATEPROMPT 0x2000
-#define FOS_SHAREAWARE 0x4000
-#define FOS_NOREADONLYRETURN 0x8000
-#define FOS_NOTESTFILECREATE 0x10000
-#define FOS_HIDEMRUPLACES 0x20000
-#define FOS_HIDEPINNEDPLACES 0x40000
-#define FOS_NODEREFERENCELINKS 0x100000
-#define FOS_DONTADDTORECENT 0x2000000
-#define FOS_FORCESHOWHIDDEN 0x10000000
-#define FOS_DEFAULTNOMINIMODE 0x20000000
-#define FOS_FORCEPREVIEWPANEON 0x40000000
-
-#if __MINGW64_VERSION_MAJOR < 2
-typedef int GETPROPERTYSTOREFLAGS;
-#define GPS_DEFAULT 0x00000000
-#define GPS_HANDLERPROPERTIESONLY 0x00000001
-#define GPS_READWRITE 0x00000002
-#define GPS_TEMPORARY 0x00000004
-#define GPS_FASTPROPERTIESONLY 0x00000008
-#define GPS_OPENSLOWITEM 0x00000010
-#define GPS_DELAYCREATION 0x00000020
-#define GPS_BESTEFFORT 0x00000040
-#define GPS_MASK_VALID 0x0000007F
-#endif
-
-typedef int (QT_WIN_CALLBACK* BFFCALLBACK)(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData);
-// message from browser
-#define BFFM_INITIALIZED 1
-#define BFFM_SELCHANGED 2
-#define BFFM_ENABLEOK (WM_USER + 101)
-// Browsing for directory.
-#define BIF_NONEWFOLDERBUTTON 0x0200
-#define BIF_NOTRANSLATETARGETS 0x0400
-#define BIF_BROWSEFORCOMPUTER 0x1000
-#define BIF_BROWSEFORPRINTER 0x2000
-#define BIF_BROWSEINCLUDEFILES 0x4000
-#define BIF_SHAREABLE 0x8000
-
-//the enums
-typedef enum {
- SIATTRIBFLAGS_AND = 0x1,
- SIATTRIBFLAGS_OR = 0x2,
- SIATTRIBFLAGS_APPCOMPAT = 0x3,
- SIATTRIBFLAGS_MASK = 0x3
-} SIATTRIBFLAGS;
-#ifndef __MINGW64_VERSION_MAJOR
-typedef enum {
- SIGDN_NORMALDISPLAY = 0x00000000,
- SIGDN_PARENTRELATIVEPARSING = 0x80018001,
- SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
- SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
- SIGDN_PARENTRELATIVEEDITING = 0x80031001,
- SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
- SIGDN_FILESYSPATH = 0x80058000,
- SIGDN_URL = 0x80068000
-} SIGDN;
-#endif
-typedef enum {
- FDAP_BOTTOM = 0x00000000,
- FDAP_TOP = 0x00000001
-} FDAP;
-typedef enum {
- FDESVR_DEFAULT = 0x00000000,
- FDESVR_ACCEPT = 0x00000001,
- FDESVR_REFUSE = 0x00000002
-} FDE_SHAREVIOLATION_RESPONSE;
-typedef FDE_SHAREVIOLATION_RESPONSE FDE_OVERWRITE_RESPONSE;
-
-//the structs
-typedef struct {
- LPCWSTR pszName;
- LPCWSTR pszSpec;
-} qt_COMDLG_FILTERSPEC;
-typedef struct {
- GUID fmtid;
- DWORD pid;
-} qt_PROPERTYKEY;
-
-typedef struct {
- USHORT cb;
- BYTE abID[1];
-} qt_SHITEMID, *qt_LPSHITEMID;
-typedef struct {
- qt_SHITEMID mkid;
-} qt_ITEMIDLIST, *qt_LPITEMIDLIST;
-typedef const qt_ITEMIDLIST *qt_LPCITEMIDLIST;
-typedef struct {
- HWND hwndOwner;
- qt_LPCITEMIDLIST pidlRoot;
- LPWSTR pszDisplayName;
- LPCWSTR lpszTitle;
- UINT ulFlags;
- BFFCALLBACK lpfn;
- LPARAM lParam;
- int iImage;
-} qt_BROWSEINFO;
-
-#endif // __IShellLibrary_FWD_DEFINED__
-
-#ifndef __IFileDialogEvents_FWD_DEFINED__
-DECLARE_INTERFACE(IFileDialogEvents);
-#endif
-
-#ifndef __IShellItem_INTERFACE_DEFINED__
-DECLARE_INTERFACE_(IShellItem, IUnknown)
-{
- STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID bhid, REFIID riid, void **ppv) PURE;
- STDMETHOD(GetParent)(THIS_ IShellItem **ppsi) PURE;
- STDMETHOD(GetDisplayName)(THIS_ SIGDN sigdnName, LPWSTR *ppszName) PURE;
- STDMETHOD(GetAttributes)(THIS_ ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE;
- STDMETHOD(Compare)(THIS_ IShellItem *psi, DWORD hint, int *piOrder) PURE;
-};
-#endif
-
-#ifndef __IShellItemFilter_INTERFACE_DEFINED__
-DECLARE_INTERFACE_(IShellItemFilter, IUnknown)
-{
- STDMETHOD(IncludeItem)(THIS_ IShellItem *psi) PURE;
- STDMETHOD(GetEnumFlagsForItem)(THIS_ IShellItem *psi, DWORD *pgrfFlags) PURE;
-};
-#endif
-
-#ifndef __IEnumShellItems_INTERFACE_DEFINED__
-DECLARE_INTERFACE_(IEnumShellItems, IUnknown)
-{
- STDMETHOD(Next)(THIS_ ULONG celt, IShellItem **rgelt, ULONG *pceltFetched) PURE;
- STDMETHOD(Skip)(THIS_ ULONG celt) PURE;
- STDMETHOD(Reset)(THIS_) PURE;
- STDMETHOD(Clone)(THIS_ IEnumShellItems **ppenum) PURE;
-};
-#endif
-
-#ifndef __IShellItemArray_INTERFACE_DEFINED__
-DECLARE_INTERFACE_(IShellItemArray, IUnknown)
-{
- STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID rbhid, REFIID riid, void **ppvOut) PURE;
- STDMETHOD(GetPropertyStore)(THIS_ GETPROPERTYSTOREFLAGS flags, REFIID riid, void **ppv) PURE;
- STDMETHOD(GetPropertyDescriptionList)(THIS_ const qt_PROPERTYKEY *keyType, REFIID riid, void **ppv) PURE;
- STDMETHOD(GetAttributes)(THIS_ SIATTRIBFLAGS dwAttribFlags, ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE;
- STDMETHOD(GetCount)(THIS_ DWORD *pdwNumItems) PURE;
- STDMETHOD(GetItemAt)(THIS_ DWORD dwIndex, IShellItem **ppsi) PURE;
- STDMETHOD(EnumItems)(THIS_ IEnumShellItems **ppenumShellItems) PURE;
-};
-#endif
-
-#ifndef __IShellLibrary_INTERFACE_DEFINED__
-
-enum LIBRARYOPTIONFLAGS {};
-enum DEFAULTSAVEFOLDERTYPE { DSFT_DETECT = 1 };
-enum LIBRARYSAVEFLAGS {};
-
-DECLARE_INTERFACE_(IShellLibrary, IUnknown)
-{
- STDMETHOD(LoadLibraryFromItem)(THIS_ IShellItem *psiLibrary, DWORD grfMode) PURE;
- STDMETHOD(LoadLibraryFromKnownFolder)(THIS_ const GUID &kfidLibrary, DWORD grfMode) PURE;
- STDMETHOD(AddFolder)(THIS_ IShellItem *psiLocation) PURE;
- STDMETHOD(RemoveFolder)(THIS_ IShellItem *psiLocation) PURE;
- STDMETHOD(GetFolders)(THIS_ int lff, REFIID riid, void **ppv) PURE;
- STDMETHOD(ResolveFolder)(THIS_ IShellItem *psiFolderToResolve, DWORD dwTimeout, REFIID riid, void **ppv) PURE;
- STDMETHOD(GetDefaultSaveFolder)(THIS_ DEFAULTSAVEFOLDERTYPE dsft, REFIID riid, void **ppv) PURE;
- STDMETHOD(SetDefaultSaveFolder)(THIS_ DEFAULTSAVEFOLDERTYPE dsft, IShellItem *psi) PURE;
- STDMETHOD(GetOptions)(THIS_ LIBRARYOPTIONFLAGS *plofOptions) PURE;
- STDMETHOD(SetOptions)(THIS_ LIBRARYOPTIONFLAGS lofMask, LIBRARYOPTIONFLAGS lofOptions) PURE;
- STDMETHOD(GetFolderType)(THIS_ GUID *pftid) PURE;
- STDMETHOD(SetFolderType)(THIS_ const GUID &ftid) PURE;
- STDMETHOD(GetIcon)(THIS_ LPWSTR *ppszIcon) PURE;
- STDMETHOD(SetIcon)(THIS_ LPCWSTR pszIcon) PURE;
- STDMETHOD(Commit)(THIS_) PURE;
- STDMETHOD(Save)(THIS_ IShellItem *psiFolderToSaveIn, LPCWSTR pszLibraryName, LIBRARYSAVEFLAGS lsf, IShellItem **ppsiSavedTo) PURE;
- STDMETHOD(SaveInKnownFolder)(THIS_ const GUID &kfidToSaveIn, LPCWSTR pszLibraryName, LIBRARYSAVEFLAGS lsf,IShellItem **ppsiSavedTo) PURE;
-};
-#endif
-
-#ifndef __IModalWindow_INTERFACE_DEFINED__
-DECLARE_INTERFACE_(IModalWindow, IUnknown)
-{
- STDMETHOD(Show)(THIS_ HWND hwndParent) PURE;
-};
-#endif
-
-#ifndef __IFileDialog_INTERFACE_DEFINED__
-DECLARE_INTERFACE_(IFileDialog, IModalWindow)
-{
- STDMETHOD(SetFileTypes)(THIS_ UINT cFileTypes, const COMDLG_FILTERSPEC *rgFilterSpec) PURE;
- STDMETHOD(SetFileTypeIndex)(THIS_ UINT iFileType) PURE;
- STDMETHOD(GetFileTypeIndex)(THIS_ UINT *piFileType) PURE;
- STDMETHOD(Advise)(THIS_ IFileDialogEvents *pfde, DWORD *pdwCookie) PURE;
- STDMETHOD(Unadvise)(THIS_ DWORD dwCookie) PURE;
- STDMETHOD(SetOptions)(THIS_ DWORD fos) PURE;
- STDMETHOD(GetOptions)(THIS_ DWORD *pfos) PURE;
- STDMETHOD(SetDefaultFolder)(THIS_ IShellItem *psi) PURE;
- STDMETHOD(SetFolder)(THIS_ IShellItem *psi) PURE;
- STDMETHOD(GetFolder)(THIS_ IShellItem **ppsi) PURE;
- STDMETHOD(GetCurrentSelection)(THIS_ IShellItem **ppsi) PURE;
- STDMETHOD(SetFileName)(THIS_ LPCWSTR pszName) PURE;
- STDMETHOD(GetFileName)(THIS_ LPWSTR *pszName) PURE;
- STDMETHOD(SetTitle)(THIS_ LPCWSTR pszTitle) PURE;
- STDMETHOD(SetOkButtonLabel)(THIS_ LPCWSTR pszText) PURE;
- STDMETHOD(SetFileNameLabel)(THIS_ LPCWSTR pszLabel) PURE;
- STDMETHOD(GetResult)(THIS_ IShellItem **ppsi) PURE;
- STDMETHOD(AddPlace)(THIS_ IShellItem *psi, FDAP fdap) PURE;
- STDMETHOD(SetDefaultExtension)(THIS_ LPCWSTR pszDefaultExtension) PURE;
- STDMETHOD(Close)(THIS_ HRESULT hr) PURE;
- STDMETHOD(SetClientGuid)(THIS_ REFGUID guid) PURE;
- STDMETHOD(ClearClientData)(THIS_) PURE;
- STDMETHOD(SetFilter)(THIS_ IShellItemFilter *pFilter) PURE;
-};
-#endif
-
-#ifndef __IFileDialogEvents_INTERFACE_DEFINED__
-DECLARE_INTERFACE_(IFileDialogEvents, IUnknown)
-{
- STDMETHOD(OnFileOk)(THIS_ IFileDialog *pfd) PURE;
- STDMETHOD(OnFolderChanging)(THIS_ IFileDialog *pfd, IShellItem *psiFolder) PURE;
- STDMETHOD(OnFolderChange)(THIS_ IFileDialog *pfd) PURE;
- STDMETHOD(OnSelectionChange)(THIS_ IFileDialog *pfd) PURE;
- STDMETHOD(OnShareViolation)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_SHAREVIOLATION_RESPONSE *pResponse) PURE;
- STDMETHOD(OnTypeChange)(THIS_ IFileDialog *pfd) PURE;
- STDMETHOD(OnOverwrite)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_OVERWRITE_RESPONSE *pResponse) PURE;
-};
-#endif
-
-#ifndef __IFileOpenDialog_INTERFACE_DEFINED__
-DECLARE_INTERFACE_(IFileOpenDialog, IFileDialog)
-{
- STDMETHOD(GetResults)(THIS_ IShellItemArray **ppenum) PURE;
- STDMETHOD(GetSelectedItems)(THIS_ IShellItemArray **ppsai) PURE;
-};
-#endif
-
-#ifndef __IPropertyStore_FWD_DEFINED__
-typedef IUnknown IPropertyStore;
-#endif
-
-#ifndef __IFileOperationProgressSink_FWD_DEFINED__
-typedef IUnknown IFileOperationProgressSink;
-#endif
-
-#ifndef __IFileSaveDialog_INTERFACE_DEFINED__
-DECLARE_INTERFACE_(IFileSaveDialog, IFileDialog)
-{
-public:
- STDMETHOD(SetSaveAsItem)(THIS_ IShellItem *psi) PURE;
- STDMETHOD(SetProperties)(THIS_ IPropertyStore *pStore) PURE;
- STDMETHOD(SetCollectedProperties)(THIS_ IPropertyStore *pStore) PURE;
- STDMETHOD(GetProperties)(THIS_ IPropertyStore **ppStore) PURE;
- STDMETHOD(ApplyProperties)(THIS_ IShellItem *psi, IPropertyStore *pStore, HWND hwnd, IFileOperationProgressSink *pSink) PURE;
-};
-#endif
-
-#endif // Q_CC_MINGW
-
QT_BEGIN_NAMESPACE
#ifndef QT_NO_DEBUG_STREAM
@@ -637,7 +347,6 @@ void QWindowsDialogHelperBase<BaseClass>::stopTimer()
}
}
-#ifndef Q_OS_WINCE
// Find a file dialog window created by IFileDialog by process id, window
// title and class, which starts with a hash '#'.
@@ -673,7 +382,6 @@ static inline HWND findDialogWindow(const QString &title)
EnumWindows(findDialogEnumWindowsProc, reinterpret_cast<LPARAM>(&context));
return context.hwnd;
}
-#endif // !Q_OS_WINCE
template <class BaseClass>
void QWindowsDialogHelperBase<BaseClass>::hide()
@@ -989,24 +697,19 @@ void QWindowsNativeFileDialogBase::setWindowTitle(const QString &title)
IShellItem *QWindowsNativeFileDialogBase::shellItem(const QUrl &url)
{
-#ifndef Q_OS_WINCE
if (url.isLocalFile()) {
- if (!QWindowsContext::shell32dll.sHCreateItemFromParsingName)
- return Q_NULLPTR;
IShellItem *result = Q_NULLPTR;
const QString native = QDir::toNativeSeparators(url.toLocalFile());
const HRESULT hr =
- QWindowsContext::shell32dll.sHCreateItemFromParsingName(reinterpret_cast<const wchar_t *>(native.utf16()),
- NULL, IID_IShellItem,
- reinterpret_cast<void **>(&result));
+ SHCreateItemFromParsingName(reinterpret_cast<const wchar_t *>(native.utf16()),
+ NULL, IID_IShellItem,
+ reinterpret_cast<void **>(&result));
if (FAILED(hr)) {
qErrnoWarning("%s: SHCreateItemFromParsingName(%s)) failed", __FUNCTION__, qPrintable(url.toString()));
return Q_NULLPTR;
}
return result;
} else if (url.scheme() == QLatin1String("clsid")) {
- if (!QWindowsContext::shell32dll.sHGetKnownFolderIDList || !QWindowsContext::shell32dll.sHCreateItemFromIDList)
- return Q_NULLPTR;
// Support for virtual folders via GUID
// (see https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457(v=vs.85).aspx)
// specified as "clsid:<GUID>" (without '{', '}').
@@ -1017,12 +720,12 @@ IShellItem *QWindowsNativeFileDialogBase::shellItem(const QUrl &url)
return Q_NULLPTR;
}
PIDLIST_ABSOLUTE idList;
- HRESULT hr = QWindowsContext::shell32dll.sHGetKnownFolderIDList(uuid, 0, 0, &idList);
+ HRESULT hr = SHGetKnownFolderIDList(uuid, 0, 0, &idList);
if (FAILED(hr)) {
qErrnoWarning("%s: SHGetKnownFolderIDList(%s)) failed", __FUNCTION__, qPrintable(url.toString()));
return Q_NULLPTR;
}
- hr = QWindowsContext::shell32dll.sHCreateItemFromIDList(idList, IID_IShellItem, reinterpret_cast<void **>(&result));
+ hr = SHCreateItemFromIDList(idList, IID_IShellItem, reinterpret_cast<void **>(&result));
CoTaskMemFree(idList);
if (FAILED(hr)) {
qErrnoWarning("%s: SHCreateItemFromIDList(%s)) failed", __FUNCTION__, qPrintable(url.toString()));
@@ -1032,9 +735,6 @@ IShellItem *QWindowsNativeFileDialogBase::shellItem(const QUrl &url)
} else {
qWarning() << __FUNCTION__ << ": Unhandled scheme: " << url.scheme();
}
-#else // !Q_OS_WINCE
- Q_UNUSED(url)
-#endif
return 0;
}
@@ -1051,13 +751,11 @@ void QWindowsNativeFileDialogBase::setDirectory(const QUrl &directory)
QString QWindowsNativeFileDialogBase::directory() const
{
QString result;
-#ifndef Q_OS_WINCE
IShellItem *item = 0;
if (m_fileDialog && SUCCEEDED(m_fileDialog->GetFolder(&item)) && item) {
result = QWindowsNativeFileDialogBase::itemPath(item);
item->Release();
}
-#endif
return result;
}
@@ -1109,7 +807,7 @@ void QWindowsNativeFileDialogBase::setMode(QFileDialogOptions::FileMode mode,
qErrnoWarning("%s: SetOptions() failed", __FUNCTION__);
}
-#if !defined(Q_OS_WINCE) && defined(__IShellLibrary_INTERFACE_DEFINED__) // Windows SDK 7
+#if defined(__IShellLibrary_INTERFACE_DEFINED__) // Windows SDK 7
// Helper for "Libraries": collections of folders appearing from Windows 7
// on, visible in the file dialogs.
@@ -1162,7 +860,7 @@ QString QWindowsNativeFileDialogBase::libraryItemDefaultSaveFolder(IShellItem *i
return result;
}
-#else // !Q_OS_WINCE && __IShellLibrary_INTERFACE_DEFINED__
+#else // __IShellLibrary_INTERFACE_DEFINED__
QList<QUrl> QWindowsNativeFileDialogBase::libraryItemFolders(IShellItem *)
{
@@ -1174,7 +872,7 @@ QString QWindowsNativeFileDialogBase::libraryItemDefaultSaveFolder(IShellItem *)
return QString();
}
-#endif // Q_OS_WINCE || !__IShellLibrary_INTERFACE_DEFINED__
+#endif // !__IShellLibrary_INTERFACE_DEFINED__
QString QWindowsNativeFileDialogBase::itemPath(IShellItem *item)
{
@@ -1420,14 +1118,12 @@ bool QWindowsNativeFileDialogBase::onFileOk()
void QWindowsNativeFileDialogBase::close()
{
m_fileDialog->Close(S_OK);
-#ifndef Q_OS_WINCE
// IFileDialog::Close() does not work unless invoked from a callback.
// Try to find the window and send it a WM_CLOSE in addition.
const HWND hwnd = findDialogWindow(m_title);
qCDebug(lcQpaDialogs) << __FUNCTION__ << "closing" << hwnd;
if (hwnd && IsWindowVisible(hwnd))
PostMessageW(hwnd, WM_CLOSE, 0, 0);
-#endif // !Q_OS_WINCE
}
HRESULT QWindowsNativeFileDialogEventHandler::OnFolderChanging(IFileDialog *, IShellItem *item)
@@ -1730,8 +1426,6 @@ QString QWindowsFileDialogHelper::selectedNameFilter() const
return m_data.selectedNameFilter();
}
-#ifndef Q_OS_WINCE
-
/*!
\class QWindowsXpNativeFileDialog
\brief Native Windows directory dialog for Windows XP using SHlib-functions.
@@ -2055,8 +1749,6 @@ QString QWindowsXpFileDialogHelper::selectedNameFilter() const
return m_data.selectedNameFilter();
}
-#endif // Q_OS_WINCE
-
/*!
\class QWindowsNativeColorDialog
\brief Native Windows color dialog.
@@ -2184,7 +1876,6 @@ namespace QWindowsDialogs {
// QWindowsDialogHelperBase creation functions
bool useHelper(QPlatformTheme::DialogType type)
{
-#if !defined(_WIN32_WCE) || _WIN32_WCE < 0x800
if (QWindowsIntegration::instance()->options() & QWindowsIntegration::NoNativeDialogs)
return false;
switch (type) {
@@ -2203,28 +1894,20 @@ bool useHelper(QPlatformTheme::DialogType type)
break;
}
return false;
-#else
- return false;
-#endif // !defined(_WIN32_WCE) || _WIN32_WCE < 0x800
}
QPlatformDialogHelper *createHelper(QPlatformTheme::DialogType type)
{
-#if !defined(_WIN32_WCE) || _WIN32_WCE < 0x800
if (QWindowsIntegration::instance()->options() & QWindowsIntegration::NoNativeDialogs)
return 0;
switch (type) {
- case QPlatformTheme::FileDialog:
-#ifndef Q_OS_WINCE // Note: "Windows XP Professional x64 Edition has version number WV_5_2 (WV_2003).
+ case QPlatformTheme::FileDialog: // Note: "Windows XP Professional x64 Edition has version number WV_5_2 (WV_2003).
if (QWindowsIntegration::instance()->options() & QWindowsIntegration::XpNativeDialogs
|| QSysInfo::windowsVersion() <= QSysInfo::WV_2003) {
return new QWindowsXpFileDialogHelper();
}
if (QSysInfo::windowsVersion() > QSysInfo::WV_2003)
return new QWindowsFileDialogHelper();
-#else
- return new QWindowsFileDialogHelper();
-#endif // Q_OS_WINCE
case QPlatformTheme::ColorDialog:
#ifdef USE_NATIVE_COLOR_DIALOG
return new QWindowsColorDialogHelper();
@@ -2238,9 +1921,6 @@ QPlatformDialogHelper *createHelper(QPlatformTheme::DialogType type)
break;
}
return 0;
-#else
- return 0;
-#endif // !defined(_WIN32_WCE) || _WIN32_WCE < 0x800
}
} // namespace QWindowsDialogs
diff --git a/src/plugins/platforms/windows/qwindowsdialoghelpers.h b/src/plugins/platforms/windows/qwindowsdialoghelpers.h
index b643d9a920..b3101a1419 100644
--- a/src/plugins/platforms/windows/qwindowsdialoghelpers.h
+++ b/src/plugins/platforms/windows/qwindowsdialoghelpers.h
@@ -40,7 +40,7 @@
#ifndef QWINDOWSDIALOGHELPER_H
#define QWINDOWSDIALOGHELPER_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <qpa/qplatformdialoghelper.h>
#include <qpa/qplatformtheme.h>
#include <QtCore/QStringList>
diff --git a/src/plugins/platforms/windows/qwindowsdrag.cpp b/src/plugins/platforms/windows/qwindowsdrag.cpp
index 246f53ef2f..26a5131927 100644
--- a/src/plugins/platforms/windows/qwindowsdrag.cpp
+++ b/src/plugins/platforms/windows/qwindowsdrag.cpp
@@ -45,7 +45,7 @@
#endif
#include "qwindowsintegration.h"
#include "qwindowsole.h"
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include "qwindowswindow.h"
#include "qwindowsmousehandler.h"
#include "qwindowscursor.h"
diff --git a/src/plugins/platforms/windows/qwindowseglcontext.cpp b/src/plugins/platforms/windows/qwindowseglcontext.cpp
index 4261c01ac8..a4738dc100 100644
--- a/src/plugins/platforms/windows/qwindowseglcontext.cpp
+++ b/src/plugins/platforms/windows/qwindowseglcontext.cpp
@@ -95,13 +95,9 @@ static void *resolveFunc(HMODULE lib, const char *name)
return proc;
}
#else
-static void *resolveFunc(HMODULE lib, const char *name)
+static inline void *resolveFunc(HMODULE lib, const char *name)
{
-# ifndef Q_OS_WINCE
- return (void *) ::GetProcAddress(lib, name);
-# else
- return (void *) ::GetProcAddress(lib, (const wchar_t *) QString::fromLatin1(name).utf16());
-# endif // Q_OS_WINCE
+ return ::GetProcAddress(lib, name);
}
#endif // Q_CC_MINGW
@@ -121,7 +117,7 @@ void *QWindowsLibEGL::resolve(const char *name)
bool QWindowsLibEGL::init()
{
const char dllName[] = QT_STRINGIFY(LIBEGL_NAME)
-#if defined(QT_DEBUG) && !defined(Q_OS_WINCE)
+#if defined(QT_DEBUG)
"d"
#endif
"";
@@ -178,7 +174,7 @@ bool QWindowsLibGLESv2::init()
{
const char dllName[] = QT_STRINGIFY(LIBGLESV2_NAME)
-#if defined(QT_DEBUG) && !defined(Q_OS_WINCE)
+#if defined(QT_DEBUG)
"d"
#endif
"";
diff --git a/src/plugins/platforms/windows/qwindowsfontdatabase.cpp b/src/plugins/platforms/windows/qwindowsfontdatabase.cpp
deleted file mode 100644
index bc237bc88c..0000000000
--- a/src/plugins/platforms/windows/qwindowsfontdatabase.cpp
+++ /dev/null
@@ -1,1907 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwindowsfontdatabase.h"
-#include "qwindowsfontdatabase_ft.h" // for default font
-#include "qwindowscontext.h"
-#include "qwindowsintegration.h"
-#include "qwindowsfontengine.h"
-#include "qwindowsfontenginedirectwrite.h"
-#include "qtwindows_additional.h"
-
-#include <QtGui/QFont>
-#include <QtGui/QGuiApplication>
-#include <QtGui/private/qhighdpiscaling_p.h>
-
-#include <QtCore/qmath.h>
-#include <QtCore/QDebug>
-#include <QtCore/QFile>
-#include <QtCore/QtEndian>
-#include <QtCore/QThreadStorage>
-#include <QtCore/private/qsystemlibrary_p.h>
-
-#include <wchar.h>
-
-#ifdef Q_OS_WINCE
-# include "qplatformfunctions_wince.h"
-#endif
-
-#if !defined(QT_NO_DIRECTWRITE)
-# if defined(QT_USE_DIRECTWRITE2)
-# include <dwrite_2.h>
-# else
-# include <dwrite.h>
-# endif
-# include <d2d1.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_DIRECTWRITE
-// ### fixme: Consider direct linking of dwrite.dll once Windows Vista pre SP2 is dropped (QTBUG-49711)
-
-typedef HRESULT (WINAPI *DWriteCreateFactoryType)(DWRITE_FACTORY_TYPE, const IID &, IUnknown **);
-
-static inline DWriteCreateFactoryType resolveDWriteCreateFactory()
-{
- if (QSysInfo::windowsVersion() < QSysInfo::WV_VISTA)
- return Q_NULLPTR;
- QSystemLibrary library(QStringLiteral("dwrite"));
- QFunctionPointer result = library.resolve("DWriteCreateFactory");
- if (Q_UNLIKELY(!result)) {
- qWarning("Unable to load dwrite.dll");
- return Q_NULLPTR;
- }
- return reinterpret_cast<DWriteCreateFactoryType>(result);
-}
-
-static void createDirectWriteFactory(IDWriteFactory **factory)
-{
- *factory = Q_NULLPTR;
-
- static const DWriteCreateFactoryType dWriteCreateFactory = resolveDWriteCreateFactory();
- if (!dWriteCreateFactory)
- return;
-
- IUnknown *result = NULL;
-#if defined(QT_USE_DIRECTWRITE2)
- dWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory2), &result);
-#endif
-
- if (result == NULL) {
- if (FAILED(dWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), &result))) {
- qErrnoWarning("DWriteCreateFactory failed");
- return;
- }
- }
-
- *factory = static_cast<IDWriteFactory *>(result);
-}
-
-static inline bool useDirectWrite(QFont::HintingPreference hintingPreference, bool isColorFont = false)
-{
- const unsigned options = QWindowsIntegration::instance()->options();
- if (Q_UNLIKELY(options & QWindowsIntegration::DontUseDirectWriteFonts))
- return false;
- if (isColorFont)
- return (options & QWindowsIntegration::DontUseColorFonts) == 0;
- return hintingPreference == QFont::PreferNoHinting
- || hintingPreference == QFont::PreferVerticalHinting
- || (QHighDpiScaling::isActive() && hintingPreference == QFont::PreferDefaultHinting);
-}
-#endif // !QT_NO_DIRECTWRITE
-
-// Helper classes for creating font engines directly from font data
-namespace {
-
-# pragma pack(1)
-
- // Common structure for all formats of the "name" table
- struct NameTable
- {
- quint16 format;
- quint16 count;
- quint16 stringOffset;
- };
-
- struct NameRecord
- {
- quint16 platformID;
- quint16 encodingID;
- quint16 languageID;
- quint16 nameID;
- quint16 length;
- quint16 offset;
- };
-
- struct OffsetSubTable
- {
- quint32 scalerType;
- quint16 numTables;
- quint16 searchRange;
- quint16 entrySelector;
- quint16 rangeShift;
- };
-
- struct TableDirectory
- {
- quint32 identifier;
- quint32 checkSum;
- quint32 offset;
- quint32 length;
- };
-
- struct OS2Table
- {
- quint16 version;
- qint16 avgCharWidth;
- quint16 weightClass;
- quint16 widthClass;
- quint16 type;
- qint16 subscriptXSize;
- qint16 subscriptYSize;
- qint16 subscriptXOffset;
- qint16 subscriptYOffset;
- qint16 superscriptXSize;
- qint16 superscriptYSize;
- qint16 superscriptXOffset;
- qint16 superscriptYOffset;
- qint16 strikeOutSize;
- qint16 strikeOutPosition;
- qint16 familyClass;
- quint8 panose[10];
- quint32 unicodeRanges[4];
- quint8 vendorID[4];
- quint16 selection;
- quint16 firstCharIndex;
- quint16 lastCharIndex;
- qint16 typoAscender;
- qint16 typoDescender;
- qint16 typoLineGap;
- quint16 winAscent;
- quint16 winDescent;
- quint32 codepageRanges[2];
- qint16 height;
- qint16 capHeight;
- quint16 defaultChar;
- quint16 breakChar;
- quint16 maxContext;
- };
-
-# pragma pack()
-
- class EmbeddedFont
- {
- public:
- EmbeddedFont(const QByteArray &fontData) : m_fontData(fontData) {}
-
- QString changeFamilyName(const QString &newFamilyName);
- QByteArray data() const { return m_fontData; }
- TableDirectory *tableDirectoryEntry(const QByteArray &tagName);
- QString familyName(TableDirectory *nameTableDirectory = 0);
-
- private:
- QByteArray m_fontData;
- };
-
- TableDirectory *EmbeddedFont::tableDirectoryEntry(const QByteArray &tagName)
- {
- Q_ASSERT(tagName.size() == 4);
- quint32 tagId = *(reinterpret_cast<const quint32 *>(tagName.constData()));
- const size_t fontDataSize = m_fontData.size();
- if (Q_UNLIKELY(fontDataSize < sizeof(OffsetSubTable)))
- return 0;
-
- OffsetSubTable *offsetSubTable = reinterpret_cast<OffsetSubTable *>(m_fontData.data());
- TableDirectory *tableDirectory = reinterpret_cast<TableDirectory *>(offsetSubTable + 1);
-
- const size_t tableCount = qFromBigEndian<quint16>(offsetSubTable->numTables);
- if (Q_UNLIKELY(fontDataSize < sizeof(OffsetSubTable) + sizeof(TableDirectory) * tableCount))
- return 0;
-
- TableDirectory *tableDirectoryEnd = tableDirectory + tableCount;
- for (TableDirectory *entry = tableDirectory; entry < tableDirectoryEnd; ++entry) {
- if (entry->identifier == tagId)
- return entry;
- }
-
- return 0;
- }
-
- QString EmbeddedFont::familyName(TableDirectory *nameTableDirectoryEntry)
- {
- QString name;
-
- if (nameTableDirectoryEntry == 0)
- nameTableDirectoryEntry = tableDirectoryEntry("name");
-
- if (nameTableDirectoryEntry != 0) {
- quint32 offset = qFromBigEndian<quint32>(nameTableDirectoryEntry->offset);
- if (Q_UNLIKELY(quint32(m_fontData.size()) < offset + sizeof(NameTable)))
- return QString();
-
- NameTable *nameTable = reinterpret_cast<NameTable *>(m_fontData.data() + offset);
- NameRecord *nameRecord = reinterpret_cast<NameRecord *>(nameTable + 1);
-
- quint16 nameTableCount = qFromBigEndian<quint16>(nameTable->count);
- if (Q_UNLIKELY(quint32(m_fontData.size()) < offset + sizeof(NameRecord) * nameTableCount))
- return QString();
-
- for (int i = 0; i < nameTableCount; ++i, ++nameRecord) {
- if (qFromBigEndian<quint16>(nameRecord->nameID) == 1
- && qFromBigEndian<quint16>(nameRecord->platformID) == 3 // Windows
- && qFromBigEndian<quint16>(nameRecord->languageID) == 0x0409) { // US English
- quint16 stringOffset = qFromBigEndian<quint16>(nameTable->stringOffset);
- quint16 nameOffset = qFromBigEndian<quint16>(nameRecord->offset);
- quint16 nameLength = qFromBigEndian<quint16>(nameRecord->length);
-
- if (Q_UNLIKELY(quint32(m_fontData.size()) < offset + stringOffset + nameOffset + nameLength))
- return QString();
-
- const void *ptr = reinterpret_cast<const quint8 *>(nameTable)
- + stringOffset
- + nameOffset;
-
- const quint16 *s = reinterpret_cast<const quint16 *>(ptr);
- const quint16 *e = s + nameLength / sizeof(quint16);
- while (s != e)
- name += QChar( qFromBigEndian<quint16>(*s++));
- break;
- }
- }
- }
-
- return name;
- }
-
- QString EmbeddedFont::changeFamilyName(const QString &newFamilyName)
- {
- TableDirectory *nameTableDirectoryEntry = tableDirectoryEntry("name");
- if (nameTableDirectoryEntry == 0)
- return QString();
-
- QString oldFamilyName = familyName(nameTableDirectoryEntry);
-
- // Reserve size for name table header, five required name records and string
- const int requiredRecordCount = 5;
- quint16 nameIds[requiredRecordCount] = { 1, 2, 3, 4, 6 };
-
- int sizeOfHeader = sizeof(NameTable) + sizeof(NameRecord) * requiredRecordCount;
- int newFamilyNameSize = newFamilyName.size() * int(sizeof(quint16));
-
- const QString regularString = QString::fromLatin1("Regular");
- int regularStringSize = regularString.size() * int(sizeof(quint16));
-
- // Align table size of table to 32 bits (pad with 0)
- int fullSize = ((sizeOfHeader + newFamilyNameSize + regularStringSize) & ~3) + 4;
-
- QByteArray newNameTable(fullSize, char(0));
-
- {
- NameTable *nameTable = reinterpret_cast<NameTable *>(newNameTable.data());
- nameTable->count = qbswap<quint16>(requiredRecordCount);
- nameTable->stringOffset = qbswap<quint16>(sizeOfHeader);
-
- NameRecord *nameRecord = reinterpret_cast<NameRecord *>(nameTable + 1);
- for (int i = 0; i < requiredRecordCount; ++i, nameRecord++) {
- nameRecord->nameID = qbswap<quint16>(nameIds[i]);
- nameRecord->encodingID = qbswap<quint16>(1);
- nameRecord->languageID = qbswap<quint16>(0x0409);
- nameRecord->platformID = qbswap<quint16>(3);
- nameRecord->length = qbswap<quint16>(newFamilyNameSize);
-
- // Special case for sub-family
- if (nameIds[i] == 4) {
- nameRecord->offset = qbswap<quint16>(newFamilyNameSize);
- nameRecord->length = qbswap<quint16>(regularStringSize);
- }
- }
-
- // nameRecord now points to string data
- quint16 *stringStorage = reinterpret_cast<quint16 *>(nameRecord);
- const quint16 *sourceString = newFamilyName.utf16();
- for (int i = 0; i < newFamilyName.size(); ++i)
- stringStorage[i] = qbswap<quint16>(sourceString[i]);
- stringStorage += newFamilyName.size();
-
- sourceString = regularString.utf16();
- for (int i = 0; i < regularString.size(); ++i)
- stringStorage[i] = qbswap<quint16>(sourceString[i]);
- }
-
- quint32 *p = reinterpret_cast<quint32 *>(newNameTable.data());
- quint32 *tableEnd = reinterpret_cast<quint32 *>(newNameTable.data() + fullSize);
-
- quint32 checkSum = 0;
- while (p < tableEnd)
- checkSum += qFromBigEndian<quint32>(*(p++));
-
- nameTableDirectoryEntry->checkSum = qbswap<quint32>(checkSum);
- nameTableDirectoryEntry->offset = qbswap<quint32>(m_fontData.size());
- nameTableDirectoryEntry->length = qbswap<quint32>(fullSize);
-
- m_fontData.append(newNameTable);
-
- return oldFamilyName;
- }
-
-#if !defined(QT_NO_DIRECTWRITE)
-
- class DirectWriteFontFileStream: public IDWriteFontFileStream
- {
- public:
- DirectWriteFontFileStream(const QByteArray &fontData)
- : m_fontData(fontData)
- , m_referenceCount(0)
- {
- }
- virtual ~DirectWriteFontFileStream()
- {
- }
-
- HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **object);
- ULONG STDMETHODCALLTYPE AddRef();
- ULONG STDMETHODCALLTYPE Release();
-
- HRESULT STDMETHODCALLTYPE ReadFileFragment(const void **fragmentStart, UINT64 fileOffset,
- UINT64 fragmentSize, OUT void **fragmentContext);
- void STDMETHODCALLTYPE ReleaseFileFragment(void *fragmentContext);
- HRESULT STDMETHODCALLTYPE GetFileSize(OUT UINT64 *fileSize);
- HRESULT STDMETHODCALLTYPE GetLastWriteTime(OUT UINT64 *lastWriteTime);
-
- private:
- QByteArray m_fontData;
- ULONG m_referenceCount;
- };
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::QueryInterface(REFIID iid, void **object)
- {
- if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileStream)) {
- *object = this;
- AddRef();
- return S_OK;
- } else {
- *object = NULL;
- return E_NOINTERFACE;
- }
- }
-
- ULONG STDMETHODCALLTYPE DirectWriteFontFileStream::AddRef()
- {
- return InterlockedIncrement(&m_referenceCount);
- }
-
- ULONG STDMETHODCALLTYPE DirectWriteFontFileStream::Release()
- {
- ULONG newCount = InterlockedDecrement(&m_referenceCount);
- if (newCount == 0)
- delete this;
- return newCount;
- }
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::ReadFileFragment(
- const void **fragmentStart,
- UINT64 fileOffset,
- UINT64 fragmentSize,
- OUT void **fragmentContext)
- {
- *fragmentContext = NULL;
- if (fileOffset + fragmentSize <= quint64(m_fontData.size())) {
- *fragmentStart = m_fontData.data() + fileOffset;
- return S_OK;
- } else {
- *fragmentStart = NULL;
- return E_FAIL;
- }
- }
-
- void STDMETHODCALLTYPE DirectWriteFontFileStream::ReleaseFileFragment(void *)
- {
- }
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::GetFileSize(UINT64 *fileSize)
- {
- *fileSize = m_fontData.size();
- return S_OK;
- }
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::GetLastWriteTime(UINT64 *lastWriteTime)
- {
- *lastWriteTime = 0;
- return E_NOTIMPL;
- }
-
- class DirectWriteFontFileLoader: public IDWriteFontFileLoader
- {
- public:
- DirectWriteFontFileLoader() : m_referenceCount(0) {}
- virtual ~DirectWriteFontFileLoader()
- {
- }
-
- inline void addKey(const void *key, const QByteArray &fontData)
- {
- Q_ASSERT(!m_fontDatas.contains(key));
- m_fontDatas.insert(key, fontData);
- }
-
- inline void removeKey(const void *key)
- {
- m_fontDatas.remove(key);
- }
-
- HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **object);
- ULONG STDMETHODCALLTYPE AddRef();
- ULONG STDMETHODCALLTYPE Release();
-
- HRESULT STDMETHODCALLTYPE CreateStreamFromKey(void const *fontFileReferenceKey,
- UINT32 fontFileReferenceKeySize,
- OUT IDWriteFontFileStream **fontFileStream);
-
- private:
- ULONG m_referenceCount;
- QHash<const void *, QByteArray> m_fontDatas;
- };
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileLoader::QueryInterface(const IID &iid,
- void **object)
- {
- if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileLoader)) {
- *object = this;
- AddRef();
- return S_OK;
- } else {
- *object = NULL;
- return E_NOINTERFACE;
- }
- }
-
- ULONG STDMETHODCALLTYPE DirectWriteFontFileLoader::AddRef()
- {
- return InterlockedIncrement(&m_referenceCount);
- }
-
- ULONG STDMETHODCALLTYPE DirectWriteFontFileLoader::Release()
- {
- ULONG newCount = InterlockedDecrement(&m_referenceCount);
- if (newCount == 0)
- delete this;
- return newCount;
- }
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileLoader::CreateStreamFromKey(
- void const *fontFileReferenceKey,
- UINT32 fontFileReferenceKeySize,
- IDWriteFontFileStream **fontFileStream)
- {
- Q_UNUSED(fontFileReferenceKeySize);
-
- if (fontFileReferenceKeySize != sizeof(const void *)) {
- qWarning("%s: Wrong key size", __FUNCTION__);
- return E_FAIL;
- }
-
- const void *key = *reinterpret_cast<void * const *>(fontFileReferenceKey);
- *fontFileStream = NULL;
- if (!m_fontDatas.contains(key))
- return E_FAIL;
-
- QByteArray fontData = m_fontDatas.value(key);
- DirectWriteFontFileStream *stream = new DirectWriteFontFileStream(fontData);
- stream->AddRef();
- *fontFileStream = stream;
-
- return S_OK;
- }
-
- class CustomFontFileLoader
- {
- public:
- CustomFontFileLoader() : m_directWriteFontFileLoader(Q_NULLPTR)
- {
- createDirectWriteFactory(&m_directWriteFactory);
-
- if (m_directWriteFactory) {
- m_directWriteFontFileLoader = new DirectWriteFontFileLoader();
- m_directWriteFactory->RegisterFontFileLoader(m_directWriteFontFileLoader);
- }
- }
-
- ~CustomFontFileLoader()
- {
- if (m_directWriteFactory != 0 && m_directWriteFontFileLoader != 0)
- m_directWriteFactory->UnregisterFontFileLoader(m_directWriteFontFileLoader);
-
- if (m_directWriteFactory != 0)
- m_directWriteFactory->Release();
- }
-
- void addKey(const void *key, const QByteArray &fontData)
- {
- if (m_directWriteFontFileLoader != 0)
- m_directWriteFontFileLoader->addKey(key, fontData);
- }
-
- void removeKey(const void *key)
- {
- if (m_directWriteFontFileLoader != 0)
- m_directWriteFontFileLoader->removeKey(key);
- }
-
- IDWriteFontFileLoader *loader() const
- {
- return m_directWriteFontFileLoader;
- }
-
- private:
- IDWriteFactory *m_directWriteFactory;
- DirectWriteFontFileLoader *m_directWriteFontFileLoader;
- };
-
-#endif
-
-} // Anonymous namespace
-
-/*!
- \struct QWindowsFontEngineData
- \brief Static constant data shared by the font engines.
- \ingroup qt-lighthouse-win
-*/
-
-QWindowsFontEngineData::QWindowsFontEngineData()
- : clearTypeEnabled(false)
- , fontSmoothingGamma(QWindowsFontDatabase::fontSmoothingGamma())
-#if !defined(QT_NO_DIRECTWRITE)
- , directWriteFactory(0)
- , directWriteGdiInterop(0)
-#endif
-{
- // from qapplication_win.cpp
- UINT result = 0;
- if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0))
- clearTypeEnabled = (result == FE_FONTSMOOTHINGCLEARTYPE);
-
- const qreal gray_gamma = 2.31;
- for (int i=0; i<256; ++i)
- pow_gamma[i] = uint(qRound(qPow(i / qreal(255.), gray_gamma) * 2047));
-
- HDC displayDC = GetDC(0);
- hdc = CreateCompatibleDC(displayDC);
- ReleaseDC(0, displayDC);
-}
-
-QWindowsFontEngineData::~QWindowsFontEngineData()
-{
- if (hdc)
- DeleteDC(hdc);
-#if !defined(QT_NO_DIRECTWRITE)
- if (directWriteGdiInterop)
- directWriteGdiInterop->Release();
- if (directWriteFactory)
- directWriteFactory->Release();
-#endif
-}
-
-qreal QWindowsFontDatabase::fontSmoothingGamma()
-{
- int winSmooth;
- qreal result = 1;
- if (SystemParametersInfo(0x200C /* SPI_GETFONTSMOOTHINGCONTRAST */, 0, &winSmooth, 0))
- result = qreal(winSmooth) / qreal(1000.0);
-
- // Safeguard ourselves against corrupt registry values...
- if (result > 5 || result < 1)
- result = qreal(1.4);
- return result;
-}
-
-#if !defined(QT_NO_DIRECTWRITE)
-static inline bool initDirectWrite(QWindowsFontEngineData *d)
-{
- if (!d->directWriteFactory) {
- createDirectWriteFactory(&d->directWriteFactory);
- if (!d->directWriteFactory)
- return false;
- }
- if (!d->directWriteGdiInterop) {
- const HRESULT hr = d->directWriteFactory->GetGdiInterop(&d->directWriteGdiInterop);
- if (FAILED(hr)) {
- qErrnoWarning("%s: GetGdiInterop failed", __FUNCTION__);
- return false;
- }
- }
- return true;
-}
-
-#endif // !defined(QT_NO_DIRECTWRITE)
-
-/*!
- \class QWindowsFontDatabase
- \brief Font database for Windows
-
- \note The Qt 4.8 WIndows font database employed a mechanism of
- delayed population of the database again passing a font name
- to EnumFontFamiliesEx(), working around the fact that
- EnumFontFamiliesEx() does not list all fonts by default.
- This should be introduced to Lighthouse as well?
-
- \internal
- \ingroup qt-lighthouse-win
-*/
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const QFontDef &def)
-{
- QDebugStateSaver saver(d);
- d.nospace();
- d.noquote();
- d << "QFontDef(Family=\"" << def.family << '"';
- if (!def.styleName.isEmpty())
- d << ", stylename=" << def.styleName;
- d << ", pointsize=" << def.pointSize << ", pixelsize=" << def.pixelSize
- << ", styleHint=" << def.styleHint << ", weight=" << def.weight
- << ", stretch=" << def.stretch << ", hintingPreference="
- << def.hintingPreference << ')';
- return d;
-}
-
-QDebug operator<<(QDebug d, const LOGFONT &lf)
-{
- QDebugStateSaver saver(d);
- d.nospace();
- d.noquote();
- d << "LOGFONT(\"" << QString::fromWCharArray(lf.lfFaceName)
- << "\", lfWidth=" << lf.lfWidth << ", lfHeight=" << lf.lfHeight << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-static inline QFontDatabase::WritingSystem writingSystemFromCharSet(uchar charSet)
-{
- switch (charSet) {
- case ANSI_CHARSET:
- case EASTEUROPE_CHARSET:
- case BALTIC_CHARSET:
- case TURKISH_CHARSET:
- return QFontDatabase::Latin;
- case GREEK_CHARSET:
- return QFontDatabase::Greek;
- case RUSSIAN_CHARSET:
- return QFontDatabase::Cyrillic;
- case HEBREW_CHARSET:
- return QFontDatabase::Hebrew;
- case ARABIC_CHARSET:
- return QFontDatabase::Arabic;
- case THAI_CHARSET:
- return QFontDatabase::Thai;
- case GB2312_CHARSET:
- return QFontDatabase::SimplifiedChinese;
- case CHINESEBIG5_CHARSET:
- return QFontDatabase::TraditionalChinese;
- case SHIFTJIS_CHARSET:
- return QFontDatabase::Japanese;
- case HANGUL_CHARSET:
- case JOHAB_CHARSET:
- return QFontDatabase::Korean;
- case VIETNAMESE_CHARSET:
- return QFontDatabase::Vietnamese;
- case SYMBOL_CHARSET:
- return QFontDatabase::Symbol;
- default:
- break;
- }
- return QFontDatabase::Any;
-}
-
-#ifdef MAKE_TAG
-#undef MAKE_TAG
-#endif
-// GetFontData expects the tags in little endian ;(
-#define MAKE_TAG(ch1, ch2, ch3, ch4) (\
- (((quint32)(ch4)) << 24) | \
- (((quint32)(ch3)) << 16) | \
- (((quint32)(ch2)) << 8) | \
- ((quint32)(ch1)) \
- )
-
-bool localizedName(const QString &name)
-{
- const QChar *c = name.unicode();
- for (int i = 0; i < name.length(); ++i) {
- if (c[i].unicode() >= 0x100)
- return true;
- }
- return false;
-}
-
-static inline quint16 getUShort(const unsigned char *p)
-{
- quint16 val;
- val = *p++ << 8;
- val |= *p;
-
- return val;
-}
-
-static QString getEnglishName(const uchar *table, quint32 bytes)
-{
- QString i18n_name;
- enum {
- NameRecordSize = 12,
- FamilyId = 1,
- MS_LangIdEnglish = 0x009
- };
-
- // get the name table
- quint16 count;
- quint16 string_offset;
- const unsigned char *names;
-
- int microsoft_id = -1;
- int apple_id = -1;
- int unicode_id = -1;
-
- if (getUShort(table) != 0)
- goto error;
-
- count = getUShort(table+2);
- string_offset = getUShort(table+4);
- names = table + 6;
-
- if (string_offset >= bytes || 6 + count*NameRecordSize > string_offset)
- goto error;
-
- for (int i = 0; i < count; ++i) {
- // search for the correct name entry
-
- quint16 platform_id = getUShort(names + i*NameRecordSize);
- quint16 encoding_id = getUShort(names + 2 + i*NameRecordSize);
- quint16 language_id = getUShort(names + 4 + i*NameRecordSize);
- quint16 name_id = getUShort(names + 6 + i*NameRecordSize);
-
- if (name_id != FamilyId)
- continue;
-
- enum {
- PlatformId_Unicode = 0,
- PlatformId_Apple = 1,
- PlatformId_Microsoft = 3
- };
-
- quint16 length = getUShort(names + 8 + i*NameRecordSize);
- quint16 offset = getUShort(names + 10 + i*NameRecordSize);
- if (DWORD(string_offset + offset + length) >= bytes)
- continue;
-
- if ((platform_id == PlatformId_Microsoft
- && (encoding_id == 0 || encoding_id == 1))
- && (language_id & 0x3ff) == MS_LangIdEnglish
- && microsoft_id == -1)
- microsoft_id = i;
- // not sure if encoding id 4 for Unicode is utf16 or ucs4...
- else if (platform_id == PlatformId_Unicode && encoding_id < 4 && unicode_id == -1)
- unicode_id = i;
- else if (platform_id == PlatformId_Apple && encoding_id == 0 && language_id == 0)
- apple_id = i;
- }
- {
- bool unicode = false;
- int id = -1;
- if (microsoft_id != -1) {
- id = microsoft_id;
- unicode = true;
- } else if (apple_id != -1) {
- id = apple_id;
- unicode = false;
- } else if (unicode_id != -1) {
- id = unicode_id;
- unicode = true;
- }
- if (id != -1) {
- quint16 length = getUShort(names + 8 + id*NameRecordSize);
- quint16 offset = getUShort(names + 10 + id*NameRecordSize);
- if (unicode) {
- // utf16
-
- length /= 2;
- i18n_name.resize(length);
- QChar *uc = const_cast<QChar *>(i18n_name.unicode());
- const unsigned char *string = table + string_offset + offset;
- for (int i = 0; i < length; ++i)
- uc[i] = getUShort(string + 2*i);
- } else {
- // Apple Roman
-
- i18n_name.resize(length);
- QChar *uc = const_cast<QChar *>(i18n_name.unicode());
- const unsigned char *string = table + string_offset + offset;
- for (int i = 0; i < length; ++i)
- uc[i] = QLatin1Char(char(string[i]));
- }
- }
- }
-error:
- //qDebug("got i18n name of '%s' for font '%s'", i18n_name.latin1(), familyName.toLocal8Bit().data());
- return i18n_name;
-}
-
-QString getEnglishName(const QString &familyName)
-{
- QString i18n_name;
-
- HDC hdc = GetDC( 0 );
- LOGFONT lf;
- memset(&lf, 0, sizeof(LOGFONT));
- memcpy(lf.lfFaceName, familyName.utf16(), qMin(familyName.length(), LF_FACESIZE - 1) * sizeof(wchar_t));
- lf.lfCharSet = DEFAULT_CHARSET;
- HFONT hfont = CreateFontIndirect(&lf);
-
- if (!hfont) {
- ReleaseDC(0, hdc);
- return QString();
- }
-
- HGDIOBJ oldobj = SelectObject( hdc, hfont );
-
- const DWORD name_tag = MAKE_TAG( 'n', 'a', 'm', 'e' );
-
- // get the name table
- unsigned char *table = 0;
-
- DWORD bytes = GetFontData( hdc, name_tag, 0, 0, 0 );
- if ( bytes == GDI_ERROR ) {
- // ### Unused variable
- // int err = GetLastError();
- goto error;
- }
-
- table = new unsigned char[bytes];
- GetFontData(hdc, name_tag, 0, table, bytes);
- if ( bytes == GDI_ERROR )
- goto error;
-
- i18n_name = getEnglishName(table, bytes);
-error:
- delete [] table;
- SelectObject( hdc, oldobj );
- DeleteObject( hfont );
- ReleaseDC( 0, hdc );
-
- //qDebug("got i18n name of '%s' for font '%s'", i18n_name.latin1(), familyName.toLocal8Bit().data());
- return i18n_name;
-}
-
-static bool addFontToDatabase(const QString &familyName, uchar charSet,
- const TEXTMETRIC *textmetric,
- const FONTSIGNATURE *signature,
- int type,
- bool registerAlias)
-{
- // the "@family" fonts are just the same as "family". Ignore them.
- if (familyName.isEmpty() || familyName.at(0) == QLatin1Char('@') || familyName.startsWith(QLatin1String("WST_")))
- return false;
-
- static const int SMOOTH_SCALABLE = 0xffff;
- const QString foundryName; // No such concept.
- const bool fixed = !(textmetric->tmPitchAndFamily & TMPF_FIXED_PITCH);
- const bool ttf = (textmetric->tmPitchAndFamily & TMPF_TRUETYPE);
- const bool scalable = textmetric->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE);
- const int size = scalable ? SMOOTH_SCALABLE : textmetric->tmHeight;
- const QFont::Style style = textmetric->tmItalic ? QFont::StyleItalic : QFont::StyleNormal;
- const bool antialias = false;
- const QFont::Weight weight = QPlatformFontDatabase::weightFromInteger(textmetric->tmWeight);
- const QFont::Stretch stretch = QFont::Unstretched;
-
-#ifndef QT_NO_DEBUG_OUTPUT
- if (QWindowsContext::verbose > 2) {
- QString message;
- QTextStream str(&message);
- str << __FUNCTION__ << ' ' << familyName << ' ' << charSet << " TTF=" << ttf;
- if (type & DEVICE_FONTTYPE)
- str << " DEVICE";
- if (type & RASTER_FONTTYPE)
- str << " RASTER";
- if (type & TRUETYPE_FONTTYPE)
- str << " TRUETYPE";
- str << " scalable=" << scalable << " Size=" << size
- << " Style=" << style << " Weight=" << weight
- << " stretch=" << stretch;
- qCDebug(lcQpaFonts) << message;
- }
-#endif
-
- QString englishName;
- if (registerAlias && ttf && localizedName(familyName))
- englishName = getEnglishName(familyName);
-
- QSupportedWritingSystems writingSystems;
- if (type & TRUETYPE_FONTTYPE) {
- Q_ASSERT(signature);
- quint32 unicodeRange[4] = {
- signature->fsUsb[0], signature->fsUsb[1],
- signature->fsUsb[2], signature->fsUsb[3]
- };
- quint32 codePageRange[2] = {
- signature->fsCsb[0], signature->fsCsb[1]
- };
-#ifdef Q_OS_WINCE
- if (signature->fsUsb[0] == 0) {
- // If the unicode ranges bit mask is zero then
- // EnumFontFamiliesEx failed to determine it properly.
- // In this case we just pretend that the font supports all languages.
- unicodeRange[0] = 0xbfffffff; // second most significant bit must be zero
- unicodeRange[1] = 0xffffffff;
- unicodeRange[2] = 0xffffffff;
- unicodeRange[3] = 0xffffffff;
- }
-#endif
- writingSystems = QPlatformFontDatabase::writingSystemsFromTrueTypeBits(unicodeRange, codePageRange);
- // ### Hack to work around problem with Thai text on Windows 7. Segoe UI contains
- // the symbol for Baht, and Windows thus reports that it supports the Thai script.
- // Since it's the default UI font on this platform, most widgets will be unable to
- // display Thai text by default. As a temporary work around, we special case Segoe UI
- // and remove the Thai script from its list of supported writing systems.
- if (writingSystems.supported(QFontDatabase::Thai) &&
- familyName == QLatin1String("Segoe UI"))
- writingSystems.setSupported(QFontDatabase::Thai, false);
- } else {
- const QFontDatabase::WritingSystem ws = writingSystemFromCharSet(charSet);
- if (ws != QFontDatabase::Any)
- writingSystems.setSupported(ws);
- }
-
- QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, weight,
- style, stretch, antialias, scalable, size, fixed, writingSystems, 0);
- // add fonts windows can generate for us:
- if (weight <= QFont::DemiBold)
- QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, QFont::Bold,
- style, stretch, antialias, scalable, size, fixed, writingSystems, 0);
- if (style != QFont::StyleItalic)
- QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, weight,
- QFont::StyleItalic, stretch, antialias, scalable, size, fixed, writingSystems, 0);
- if (weight <= QFont::DemiBold && style != QFont::StyleItalic)
- QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, QFont::Bold,
- QFont::StyleItalic, stretch, antialias, scalable, size, fixed, writingSystems, 0);
-
- if (!englishName.isEmpty())
- QPlatformFontDatabase::registerAliasToFontFamily(familyName, englishName);
-
- return true;
-}
-
-static int QT_WIN_CALLBACK storeFont(const LOGFONT *logFont, const TEXTMETRIC *textmetric,
- DWORD type, LPARAM lParam)
-{
- const ENUMLOGFONTEX *f = reinterpret_cast<const ENUMLOGFONTEX *>(logFont);
- const QString familyName = QString::fromWCharArray(f->elfLogFont.lfFaceName);
- const uchar charSet = f->elfLogFont.lfCharSet;
- const bool registerAlias = bool(lParam);
-
- // NEWTEXTMETRICEX (passed for TT fonts) is a NEWTEXTMETRIC, which according
- // to the documentation is identical to a TEXTMETRIC except for the last four
- // members, which we don't use anyway
- const FONTSIGNATURE *signature = Q_NULLPTR;
- if (type & TRUETYPE_FONTTYPE)
- signature = &reinterpret_cast<const NEWTEXTMETRICEX *>(textmetric)->ntmFontSig;
- addFontToDatabase(familyName, charSet, textmetric, signature, type, registerAlias);
-
- // keep on enumerating
- return 1;
-}
-
-void QWindowsFontDatabase::populateFamily(const QString &familyName, bool registerAlias)
-{
- qCDebug(lcQpaFonts) << familyName;
- if (familyName.size() >= LF_FACESIZE) {
- qCWarning(lcQpaFonts) << "Unable to enumerate family '" << familyName << '\'';
- return;
- }
- HDC dummy = GetDC(0);
- LOGFONT lf;
- lf.lfCharSet = DEFAULT_CHARSET;
- familyName.toWCharArray(lf.lfFaceName);
- lf.lfFaceName[familyName.size()] = 0;
- lf.lfPitchAndFamily = 0;
- EnumFontFamiliesEx(dummy, &lf, storeFont, LPARAM(registerAlias), 0);
- ReleaseDC(0, dummy);
-}
-
-void QWindowsFontDatabase::populateFamily(const QString &familyName)
-{
- populateFamily(familyName, false);
-}
-
-namespace {
-// Context for enumerating system fonts, records whether the default font has been encountered,
-// which is normally not enumerated by EnumFontFamiliesEx().
-struct PopulateFamiliesContext
-{
- PopulateFamiliesContext(const QString &f) : systemDefaultFont(f), seenSystemDefaultFont(false) {}
-
- QString systemDefaultFont;
- bool seenSystemDefaultFont;
-};
-} // namespace
-
-static int QT_WIN_CALLBACK populateFontFamilies(const LOGFONT *logFont, const TEXTMETRIC *textmetric,
- DWORD, LPARAM lparam)
-{
- // the "@family" fonts are just the same as "family". Ignore them.
- const ENUMLOGFONTEX *f = reinterpret_cast<const ENUMLOGFONTEX *>(logFont);
- const wchar_t *faceNameW = f->elfLogFont.lfFaceName;
- if (faceNameW[0] && faceNameW[0] != L'@' && wcsncmp(faceNameW, L"WST_", 4)) {
- const QString faceName = QString::fromWCharArray(faceNameW);
- QPlatformFontDatabase::registerFontFamily(faceName);
- PopulateFamiliesContext *context = reinterpret_cast<PopulateFamiliesContext *>(lparam);
- if (!context->seenSystemDefaultFont && faceName == context->systemDefaultFont)
- context->seenSystemDefaultFont = true;
-
- // Register current font's english name as alias
- const bool ttf = textmetric->tmPitchAndFamily & TMPF_TRUETYPE;
- if (ttf && localizedName(faceName)) {
- const QString englishName = getEnglishName(faceName);
- if (!englishName.isEmpty()) {
- QPlatformFontDatabase::registerAliasToFontFamily(faceName, englishName);
- // Check whether the system default font name is an alias of the current font family name,
- // as on Chinese Windows, where the system font "SimSun" is an alias to a font registered under a local name
- if (!context->seenSystemDefaultFont && englishName == context->systemDefaultFont)
- context->seenSystemDefaultFont = true;
- }
- }
- }
- return 1; // continue
-}
-
-void QWindowsFontDatabase::populateFontDatabase()
-{
- removeApplicationFonts();
- HDC dummy = GetDC(0);
- LOGFONT lf;
- lf.lfCharSet = DEFAULT_CHARSET;
- lf.lfFaceName[0] = 0;
- lf.lfPitchAndFamily = 0;
- PopulateFamiliesContext context(QWindowsFontDatabase::systemDefaultFont().family());
- EnumFontFamiliesEx(dummy, &lf, populateFontFamilies, reinterpret_cast<LPARAM>(&context), 0);
- ReleaseDC(0, dummy);
- // Work around EnumFontFamiliesEx() not listing the system font.
- if (!context.seenSystemDefaultFont)
- QPlatformFontDatabase::registerFontFamily(context.systemDefaultFont);
-}
-
-typedef QSharedPointer<QWindowsFontEngineData> QWindowsFontEngineDataPtr;
-
-#ifndef QT_NO_THREAD
-typedef QThreadStorage<QWindowsFontEngineDataPtr> FontEngineThreadLocalData;
-
-Q_GLOBAL_STATIC(FontEngineThreadLocalData, fontEngineThreadLocalData)
-
-QSharedPointer<QWindowsFontEngineData> sharedFontData()
-{
- FontEngineThreadLocalData *data = fontEngineThreadLocalData();
- if (!data->hasLocalData())
- data->setLocalData(QSharedPointer<QWindowsFontEngineData>::create());
- return data->localData();
-}
-#else // !QT_NO_THREAD
-Q_GLOBAL_STATIC(QWindowsFontEngineDataPtr, fontEngineData)
-
-QWindowsFontEngineDataPtr sharedFontData()
-{
- QWindowsFontEngineDataPtr *data = fontEngineData();
- if (data->isNull())
- *data = QWindowsFontEngineDataPtr::create();
- return *data;
-}
-#endif // QT_NO_THREAD
-
-#ifndef Q_OS_WINCE
-extern Q_GUI_EXPORT bool qt_needs_a8_gamma_correction;
-#endif
-QWindowsFontDatabase::QWindowsFontDatabase()
-{
- // Properties accessed by QWin32PrintEngine (Qt Print Support)
- static const int hfontMetaTypeId = qRegisterMetaType<HFONT>();
- static const int logFontMetaTypeId = qRegisterMetaType<LOGFONT>();
- Q_UNUSED(hfontMetaTypeId)
- Q_UNUSED(logFontMetaTypeId)
-
- if (lcQpaFonts().isDebugEnabled()) {
- const QWindowsFontEngineDataPtr data = sharedFontData();
- qCDebug(lcQpaFonts) << __FUNCTION__ << "Clear type: "
- << data->clearTypeEnabled << "gamma: " << data->fontSmoothingGamma;
- }
-#ifndef Q_OS_WINCE
- qt_needs_a8_gamma_correction = true;
-#endif
-}
-
-QWindowsFontDatabase::~QWindowsFontDatabase()
-{
- removeApplicationFonts();
-}
-
-QFontEngineMulti *QWindowsFontDatabase::fontEngineMulti(QFontEngine *fontEngine, QChar::Script script)
-{
- return new QWindowsMultiFontEngine(fontEngine, script);
-}
-
-QFontEngine * QWindowsFontDatabase::fontEngine(const QFontDef &fontDef, void *handle)
-{
- QFontEngine *fe = QWindowsFontDatabase::createEngine(fontDef,
- QWindowsContext::instance()->defaultDPI(),
- sharedFontData());
- qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDEF" << fontDef << fe << handle;
- return fe;
-}
-
-QFontEngine *QWindowsFontDatabase::fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference)
-{
- EmbeddedFont font(fontData);
- QFontEngine *fontEngine = 0;
-
-#if !defined(QT_NO_DIRECTWRITE)
- if (!useDirectWrite(hintingPreference))
-#endif
- {
- GUID guid;
- CoCreateGuid(&guid);
-
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_GCC("-Wstrict-aliasing")
- QString uniqueFamilyName = QLatin1Char('f')
- + QString::number(guid.Data1, 36) + QLatin1Char('-')
- + QString::number(guid.Data2, 36) + QLatin1Char('-')
- + QString::number(guid.Data3, 36) + QLatin1Char('-')
- + QString::number(*reinterpret_cast<quint64 *>(guid.Data4), 36);
-QT_WARNING_POP
-
- QString actualFontName = font.changeFamilyName(uniqueFamilyName);
- if (actualFontName.isEmpty()) {
- qWarning("%s: Can't change family name of font", __FUNCTION__);
- return 0;
- }
-
- DWORD count = 0;
- QByteArray newFontData = font.data();
- HANDLE fontHandle =
- AddFontMemResourceEx(const_cast<char *>(newFontData.constData()),
- DWORD(newFontData.size()), 0, &count);
- if (count == 0 && fontHandle != 0) {
- RemoveFontMemResourceEx(fontHandle);
- fontHandle = 0;
- }
-
- if (fontHandle == 0) {
- qWarning("%s: AddFontMemResourceEx failed", __FUNCTION__);
- } else {
- QFontDef request;
- request.family = uniqueFamilyName;
- request.pixelSize = pixelSize;
- request.styleStrategy = QFont::PreferMatch;
- request.hintingPreference = hintingPreference;
-
- fontEngine = QWindowsFontDatabase::createEngine(request,
- QWindowsContext::instance()->defaultDPI(),
- sharedFontData());
-
- if (fontEngine) {
- if (request.family != fontEngine->fontDef.family) {
- qWarning("%s: Failed to load font. Got fallback instead: %s",
- __FUNCTION__, qPrintable(fontEngine->fontDef.family));
- if (fontEngine->ref.load() == 0)
- delete fontEngine;
- fontEngine = 0;
- } else {
- Q_ASSERT(fontEngine->ref.load() == 0);
-
- // Override the generated font name
- switch (fontEngine->type()) {
- case QFontEngine::Win:
- static_cast<QWindowsFontEngine *>(fontEngine)->setUniqueFamilyName(uniqueFamilyName);
- fontEngine->fontDef.family = actualFontName;
- break;
-
-#if !defined(QT_NO_DIRECTWRITE)
- case QFontEngine::DirectWrite:
- static_cast<QWindowsFontEngineDirectWrite *>(fontEngine)->setUniqueFamilyName(uniqueFamilyName);
- fontEngine->fontDef.family = actualFontName;
- break;
-#endif // !QT_NO_DIRECTWRITE
-
- default:
- Q_ASSERT_X(false, Q_FUNC_INFO, "Unhandled font engine.");
- }
-
- UniqueFontData uniqueData;
- uniqueData.handle = fontHandle;
- uniqueData.refCount.ref();
- m_uniqueFontData[uniqueFamilyName] = uniqueData;
- }
- } else {
- RemoveFontMemResourceEx(fontHandle);
- }
- }
- }
-#if !defined(QT_NO_DIRECTWRITE)
- else {
- CustomFontFileLoader fontFileLoader;
- fontFileLoader.addKey(this, fontData);
-
- QSharedPointer<QWindowsFontEngineData> fontEngineData = sharedFontData();
- if (!initDirectWrite(fontEngineData.data()))
- return 0;
-
- IDWriteFontFile *fontFile = 0;
- void *key = this;
-
- HRESULT hres = fontEngineData->directWriteFactory->CreateCustomFontFileReference(&key,
- sizeof(void *),
- fontFileLoader.loader(),
- &fontFile);
- if (FAILED(hres)) {
- qErrnoWarning(hres, "%s: CreateCustomFontFileReference failed", __FUNCTION__);
- return 0;
- }
-
- BOOL isSupportedFontType;
- DWRITE_FONT_FILE_TYPE fontFileType;
- DWRITE_FONT_FACE_TYPE fontFaceType;
- UINT32 numberOfFaces;
- fontFile->Analyze(&isSupportedFontType, &fontFileType, &fontFaceType, &numberOfFaces);
- if (!isSupportedFontType) {
- fontFile->Release();
- return 0;
- }
-
- IDWriteFontFace *directWriteFontFace = 0;
- hres = fontEngineData->directWriteFactory->CreateFontFace(fontFaceType,
- 1,
- &fontFile,
- 0,
- DWRITE_FONT_SIMULATIONS_NONE,
- &directWriteFontFace);
- if (FAILED(hres)) {
- qErrnoWarning(hres, "%s: CreateFontFace failed", __FUNCTION__);
- fontFile->Release();
- return 0;
- }
-
- fontFile->Release();
-
- fontEngine = new QWindowsFontEngineDirectWrite(directWriteFontFace,
- pixelSize,
- fontEngineData);
-
- // Get font family from font data
- fontEngine->fontDef.family = font.familyName();
- fontEngine->fontDef.hintingPreference = hintingPreference;
-
- directWriteFontFace->Release();
- }
-#endif
-
- // Get style and weight info
- if (fontEngine != 0) {
- TableDirectory *os2TableEntry = font.tableDirectoryEntry("OS/2");
- if (os2TableEntry != 0) {
- const OS2Table *os2Table =
- reinterpret_cast<const OS2Table *>(fontData.constData()
- + qFromBigEndian<quint32>(os2TableEntry->offset));
-
- bool italic = qFromBigEndian<quint16>(os2Table->selection) & 1;
- bool oblique = qFromBigEndian<quint16>(os2Table->selection) & 128;
-
- if (italic)
- fontEngine->fontDef.style = QFont::StyleItalic;
- else if (oblique)
- fontEngine->fontDef.style = QFont::StyleOblique;
- else
- fontEngine->fontDef.style = QFont::StyleNormal;
-
- fontEngine->fontDef.weight = QPlatformFontDatabase::weightFromInteger(qFromBigEndian<quint16>(os2Table->weightClass));
- }
- }
-
- qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDATA" << fontData << pixelSize << hintingPreference << fontEngine;
- return fontEngine;
-}
-
-static QList<quint32> getTrueTypeFontOffsets(const uchar *fontData)
-{
- QList<quint32> offsets;
- const quint32 headerTag = *reinterpret_cast<const quint32 *>(fontData);
- if (headerTag != MAKE_TAG('t', 't', 'c', 'f')) {
- if (headerTag != MAKE_TAG(0, 1, 0, 0)
- && headerTag != MAKE_TAG('O', 'T', 'T', 'O')
- && headerTag != MAKE_TAG('t', 'r', 'u', 'e')
- && headerTag != MAKE_TAG('t', 'y', 'p', '1'))
- return offsets;
- offsets << 0;
- return offsets;
- }
- const quint32 numFonts = qFromBigEndian<quint32>(fontData + 8);
- for (uint i = 0; i < numFonts; ++i) {
- offsets << qFromBigEndian<quint32>(fontData + 12 + i * 4);
- }
- return offsets;
-}
-
-static void getFontTable(const uchar *fileBegin, const uchar *data, quint32 tag, const uchar **table, quint32 *length)
-{
- const quint16 numTables = qFromBigEndian<quint16>(data + 4);
- for (uint i = 0; i < numTables; ++i) {
- const quint32 offset = 12 + 16 * i;
- if (*reinterpret_cast<const quint32 *>(data + offset) == tag) {
- *table = fileBegin + qFromBigEndian<quint32>(data + offset + 8);
- *length = qFromBigEndian<quint32>(data + offset + 12);
- return;
- }
- }
- *table = 0;
- *length = 0;
- return;
-}
-
-static void getFamiliesAndSignatures(const QByteArray &fontData,
- QStringList *families,
- QVector<FONTSIGNATURE> *signatures)
-{
- const uchar *data = reinterpret_cast<const uchar *>(fontData.constData());
-
- QList<quint32> offsets = getTrueTypeFontOffsets(data);
- if (offsets.isEmpty())
- return;
-
- for (int i = 0; i < offsets.count(); ++i) {
- const uchar *font = data + offsets.at(i);
- const uchar *table;
- quint32 length;
- getFontTable(data, font, MAKE_TAG('n', 'a', 'm', 'e'), &table, &length);
- if (!table)
- continue;
- QString name = getEnglishName(table, length);
- if (name.isEmpty())
- continue;
-
- families->append(name);
-
- if (signatures) {
- FONTSIGNATURE signature;
- getFontTable(data, font, MAKE_TAG('O', 'S', '/', '2'), &table, &length);
- if (table && length >= 86) {
- // Offsets taken from OS/2 table in the TrueType spec
- signature.fsUsb[0] = qFromBigEndian<quint32>(table + 42);
- signature.fsUsb[1] = qFromBigEndian<quint32>(table + 46);
- signature.fsUsb[2] = qFromBigEndian<quint32>(table + 50);
- signature.fsUsb[3] = qFromBigEndian<quint32>(table + 54);
-
- signature.fsCsb[0] = qFromBigEndian<quint32>(table + 78);
- signature.fsCsb[1] = qFromBigEndian<quint32>(table + 82);
- } else {
- memset(&signature, 0, sizeof(signature));
- }
- signatures->append(signature);
- }
- }
-}
-
-QStringList QWindowsFontDatabase::addApplicationFont(const QByteArray &fontData, const QString &fileName)
-{
- WinApplicationFont font;
- font.fileName = fileName;
- QVector<FONTSIGNATURE> signatures;
- QStringList families;
-
- if (!fontData.isEmpty()) {
- getFamiliesAndSignatures(fontData, &families, &signatures);
- if (families.isEmpty())
- return families;
-
- DWORD dummy = 0;
- font.handle =
- AddFontMemResourceEx(const_cast<char *>(fontData.constData()),
- DWORD(fontData.size()), 0, &dummy);
- if (font.handle == 0)
- return QStringList();
-
- // Memory fonts won't show up in enumeration, so do add them the hard way.
- for (int j = 0; j < families.count(); ++j) {
- const QString familyName = families.at(j);
- HDC hdc = GetDC(0);
- LOGFONT lf;
- memset(&lf, 0, sizeof(LOGFONT));
- memcpy(lf.lfFaceName, familyName.utf16(), sizeof(wchar_t) * qMin(LF_FACESIZE - 1, familyName.size()));
- lf.lfCharSet = DEFAULT_CHARSET;
- HFONT hfont = CreateFontIndirect(&lf);
- HGDIOBJ oldobj = SelectObject(hdc, hfont);
-
- TEXTMETRIC textMetrics;
- GetTextMetrics(hdc, &textMetrics);
-
- addFontToDatabase(familyName, lf.lfCharSet, &textMetrics, &signatures.at(j),
- TRUETYPE_FONTTYPE, true);
-
- SelectObject(hdc, oldobj);
- DeleteObject(hfont);
- ReleaseDC(0, hdc);
- }
- } else {
- QFile f(fileName);
- if (!f.open(QIODevice::ReadOnly))
- return families;
- QByteArray data = f.readAll();
- f.close();
-
- getFamiliesAndSignatures(data, &families, 0);
- if (families.isEmpty())
- return families;
-
- if (AddFontResourceExW((wchar_t*)fileName.utf16(), FR_PRIVATE, 0) == 0)
- return QStringList();
-
- font.handle = 0;
-
- // Fonts based on files are added via populate, as they will show up in font enumeration.
- for (int j = 0; j < families.count(); ++j)
- populateFamily(families.at(j), true);
- }
-
- m_applicationFonts << font;
-
- return families;
-}
-
-void QWindowsFontDatabase::removeApplicationFonts()
-{
- foreach (const WinApplicationFont &font, m_applicationFonts) {
- if (font.handle) {
- RemoveFontMemResourceEx(font.handle);
- } else {
- RemoveFontResourceExW((LPCWSTR)font.fileName.utf16(), FR_PRIVATE, 0);
- }
- }
- m_applicationFonts.clear();
-}
-
-void QWindowsFontDatabase::releaseHandle(void * /* handle */)
-{
-}
-
-QString QWindowsFontDatabase::fontDir() const
-{
- const QString result = QPlatformFontDatabase::fontDir();
- qCDebug(lcQpaFonts) << __FUNCTION__ << result;
- return result;
-}
-
-bool QWindowsFontDatabase::fontsAlwaysScalable() const
-{
- return true;
-}
-
-void QWindowsFontDatabase::derefUniqueFont(const QString &uniqueFont)
-{
- if (m_uniqueFontData.contains(uniqueFont)) {
- if (!m_uniqueFontData[uniqueFont].refCount.deref()) {
- RemoveFontMemResourceEx(m_uniqueFontData[uniqueFont].handle);
- m_uniqueFontData.remove(uniqueFont);
- }
- }
-}
-
-void QWindowsFontDatabase::refUniqueFont(const QString &uniqueFont)
-{
- if (m_uniqueFontData.contains(uniqueFont))
- m_uniqueFontData[uniqueFont].refCount.ref();
-}
-
-HFONT QWindowsFontDatabase::systemFont()
-{
- static const HFONT stock_sysfont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
- return stock_sysfont;
-}
-
-// Creation functions
-
-static const char *other_tryFonts[] = {
- "Arial",
- "MS UI Gothic",
- "Gulim",
- "SimSun",
- "PMingLiU",
- "Arial Unicode MS",
- 0
-};
-
-static const char *jp_tryFonts [] = {
- "MS UI Gothic",
- "Arial",
- "Gulim",
- "SimSun",
- "PMingLiU",
- "Arial Unicode MS",
- 0
-};
-
-static const char *ch_CN_tryFonts [] = {
- "SimSun",
- "Arial",
- "PMingLiU",
- "Gulim",
- "MS UI Gothic",
- "Arial Unicode MS",
- 0
-};
-
-static const char *ch_TW_tryFonts [] = {
- "PMingLiU",
- "Arial",
- "SimSun",
- "Gulim",
- "MS UI Gothic",
- "Arial Unicode MS",
- 0
-};
-
-static const char *kr_tryFonts[] = {
- "Gulim",
- "Arial",
- "PMingLiU",
- "SimSun",
- "MS UI Gothic",
- "Arial Unicode MS",
- 0
-};
-
-static const char **tryFonts = 0;
-
-LOGFONT QWindowsFontDatabase::fontDefToLOGFONT(const QFontDef &request)
-{
- LOGFONT lf;
- memset(&lf, 0, sizeof(LOGFONT));
-
- lf.lfHeight = -qRound(request.pixelSize);
- lf.lfWidth = 0;
- lf.lfEscapement = 0;
- lf.lfOrientation = 0;
- if (request.weight == 50)
- lf.lfWeight = FW_DONTCARE;
- else
- lf.lfWeight = (request.weight*900)/99;
- lf.lfItalic = request.style != QFont::StyleNormal;
- lf.lfCharSet = DEFAULT_CHARSET;
-
- int strat = OUT_DEFAULT_PRECIS;
- if (request.styleStrategy & QFont::PreferBitmap) {
- strat = OUT_RASTER_PRECIS;
-#ifndef Q_OS_WINCE
- } else if (request.styleStrategy & QFont::PreferDevice) {
- strat = OUT_DEVICE_PRECIS;
- } else if (request.styleStrategy & QFont::PreferOutline) {
- strat = OUT_OUTLINE_PRECIS;
- } else if (request.styleStrategy & QFont::ForceOutline) {
- strat = OUT_TT_ONLY_PRECIS;
-#endif
- }
-
- lf.lfOutPrecision = strat;
-
- int qual = DEFAULT_QUALITY;
-
- if (request.styleStrategy & QFont::PreferMatch)
- qual = DRAFT_QUALITY;
-#ifndef Q_OS_WINCE
- else if (request.styleStrategy & QFont::PreferQuality)
- qual = PROOF_QUALITY;
-#endif
-
- if (request.styleStrategy & QFont::PreferAntialias) {
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP && !(request.styleStrategy & QFont::NoSubpixelAntialias)) {
- qual = CLEARTYPE_QUALITY;
- } else {
- qual = ANTIALIASED_QUALITY;
- }
- } else if (request.styleStrategy & QFont::NoAntialias) {
- qual = NONANTIALIASED_QUALITY;
- } else if ((request.styleStrategy & QFont::NoSubpixelAntialias) && sharedFontData()->clearTypeEnabled) {
- qual = ANTIALIASED_QUALITY;
- }
-
- lf.lfQuality = qual;
-
- lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
-
- int hint = FF_DONTCARE;
- switch (request.styleHint) {
- case QFont::Helvetica:
- hint = FF_SWISS;
- break;
- case QFont::Times:
- hint = FF_ROMAN;
- break;
- case QFont::Courier:
- hint = FF_MODERN;
- break;
- case QFont::OldEnglish:
- hint = FF_DECORATIVE;
- break;
- case QFont::System:
- hint = FF_MODERN;
- break;
- default:
- break;
- }
-
- lf.lfPitchAndFamily = DEFAULT_PITCH | hint;
-
- QString fam = request.family;
- if (Q_UNLIKELY(fam.size() >= LF_FACESIZE)) {
- qCritical("%s: Family name '%s' is too long.", __FUNCTION__, qPrintable(fam));
- fam.truncate(LF_FACESIZE - 1);
- }
-
- if (fam.isEmpty())
- fam = QStringLiteral("MS Sans Serif");
-
- if (fam == QLatin1String("MS Sans Serif")
- && (request.style == QFont::StyleItalic || (-lf.lfHeight > 18 && -lf.lfHeight != 24))) {
- fam = QStringLiteral("Arial"); // MS Sans Serif has bearing problems in italic, and does not scale
- }
- if (fam == QLatin1String("Courier") && !(request.styleStrategy & QFont::PreferBitmap))
- fam = QStringLiteral("Courier New");
-
- memcpy(lf.lfFaceName, fam.utf16(), fam.size() * sizeof(wchar_t));
-
- return lf;
-}
-
-QStringList QWindowsFontDatabase::extraTryFontsForFamily(const QString &family)
-{
- QStringList result;
- QFontDatabase db;
- if (!db.writingSystems(family).contains(QFontDatabase::Symbol)) {
- if (!tryFonts) {
- LANGID lid = GetUserDefaultLangID();
- switch (lid&0xff) {
- case LANG_CHINESE: // Chinese
- if ( lid == 0x0804 || lid == 0x1004) // China mainland and Singapore
- tryFonts = ch_CN_tryFonts;
- else
- tryFonts = ch_TW_tryFonts; // Taiwan, Hong Kong and Macau
- break;
- case LANG_JAPANESE:
- tryFonts = jp_tryFonts;
- break;
- case LANG_KOREAN:
- tryFonts = kr_tryFonts;
- break;
- default:
- tryFonts = other_tryFonts;
- break;
- }
- }
- QFontDatabase db;
- const QStringList families = db.families();
- const char **tf = tryFonts;
- while (tf && *tf) {
- // QTBUG-31689, family might be an English alias for a localized font name.
- const QString family = QString::fromLatin1(*tf);
- if (families.contains(family) || db.hasFamily(family))
- result << family;
- ++tf;
- }
- }
- result.append(QStringLiteral("Segoe UI Emoji"));
- result.append(QStringLiteral("Segoe UI Symbol"));
- return result;
-}
-
-QString QWindowsFontDatabase::familyForStyleHint(QFont::StyleHint styleHint)
-{
- switch (styleHint) {
- case QFont::Times:
- return QStringLiteral("Times New Roman");
- case QFont::Courier:
- return QStringLiteral("Courier New");
- case QFont::Monospace:
- return QStringLiteral("Courier New");
- case QFont::Cursive:
- return QStringLiteral("Comic Sans MS");
- case QFont::Fantasy:
- return QStringLiteral("Impact");
- case QFont::Decorative:
- return QStringLiteral("Old English");
- case QFont::Helvetica:
- return QStringLiteral("Arial");
- case QFont::System:
- default:
- break;
- }
- return QStringLiteral("MS Shell Dlg 2");
-}
-
-QStringList QWindowsFontDatabase::fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const
-{
- QStringList result;
- result.append(QWindowsFontDatabase::familyForStyleHint(styleHint));
- result.append(QWindowsFontDatabase::extraTryFontsForFamily(family));
- result.append(QPlatformFontDatabase::fallbacksForFamily(family, style, styleHint, script));
-
- qCDebug(lcQpaFonts) << __FUNCTION__ << family << style << styleHint
- << script << result;
- return result;
-}
-
-
-QFontEngine *QWindowsFontDatabase::createEngine(const QFontDef &request,
- int dpi,
- const QSharedPointer<QWindowsFontEngineData> &data)
-{
- QFontEngine *fe = 0;
-
- LOGFONT lf = fontDefToLOGFONT(request);
- const bool preferClearTypeAA = lf.lfQuality == CLEARTYPE_QUALITY;
-
- if (request.stretch != 100) {
- HFONT hfont = CreateFontIndirect(&lf);
- if (!hfont) {
- qErrnoWarning("%s: CreateFontIndirect failed", __FUNCTION__);
- hfont = QWindowsFontDatabase::systemFont();
- }
-
- HGDIOBJ oldObj = SelectObject(data->hdc, hfont);
- TEXTMETRIC tm;
- if (!GetTextMetrics(data->hdc, &tm))
- qErrnoWarning("%s: GetTextMetrics failed", __FUNCTION__);
- else
- lf.lfWidth = tm.tmAveCharWidth * request.stretch / 100;
- SelectObject(data->hdc, oldObj);
-
- DeleteObject(hfont);
- }
-
-#if !defined(QT_NO_DIRECTWRITE)
- if (initDirectWrite(data.data())) {
- const QString fam = QString::fromWCharArray(lf.lfFaceName);
- const QString nameSubstitute = QWindowsFontEngineDirectWrite::fontNameSubstitute(fam);
- if (nameSubstitute != fam) {
- const int nameSubstituteLength = qMin(nameSubstitute.length(), LF_FACESIZE - 1);
- memcpy(lf.lfFaceName, nameSubstitute.utf16(), nameSubstituteLength * sizeof(wchar_t));
- lf.lfFaceName[nameSubstituteLength] = 0;
- }
-
- HFONT hfont = CreateFontIndirect(&lf);
- if (!hfont) {
- qErrnoWarning("%s: CreateFontIndirect failed", __FUNCTION__);
- } else {
- HGDIOBJ oldFont = SelectObject(data->hdc, hfont);
-
- IDWriteFontFace *directWriteFontFace = NULL;
- HRESULT hr = data->directWriteGdiInterop->CreateFontFaceFromHdc(data->hdc, &directWriteFontFace);
- if (FAILED(hr)) {
- const QString errorString = qt_error_string(int(hr));
- qWarning().noquote().nospace() << "DirectWrite: CreateFontFaceFromHDC() failed ("
- << errorString << ") for " << request << ' ' << lf << " dpi=" << dpi;
- } else {
- bool isColorFont = false;
-#if defined(QT_USE_DIRECTWRITE2)
- IDWriteFontFace2 *directWriteFontFace2 = Q_NULLPTR;
- if (SUCCEEDED(directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace2),
- reinterpret_cast<void **>(&directWriteFontFace2)))) {
- if (directWriteFontFace2->IsColorFont())
- isColorFont = directWriteFontFace2->GetPaletteEntryCount() > 0;
- }
-#endif
- const QFont::HintingPreference hintingPreference =
- static_cast<QFont::HintingPreference>(request.hintingPreference);
- const bool useDw = useDirectWrite(hintingPreference, isColorFont);
- qCDebug(lcQpaFonts) << __FUNCTION__ << request.family << request.pointSize
- << "pt" << "hintingPreference=" << hintingPreference << "color=" << isColorFont
- << dpi << "dpi" << "useDirectWrite=" << useDw;
- if (useDw) {
- QWindowsFontEngineDirectWrite *fedw = new QWindowsFontEngineDirectWrite(directWriteFontFace,
- request.pixelSize,
- data);
-
- wchar_t n[64];
- GetTextFace(data->hdc, 64, n);
-
- QFontDef fontDef = request;
- fontDef.family = QString::fromWCharArray(n);
-
- if (isColorFont)
- fedw->glyphFormat = QFontEngine::Format_ARGB;
- fedw->initFontInfo(fontDef, dpi);
- fe = fedw;
- } else {
- directWriteFontFace->Release();
- }
- }
-
- SelectObject(data->hdc, oldFont);
- DeleteObject(hfont);
- }
- }
-#endif // QT_NO_DIRECTWRITE
-
- if (!fe) {
- QWindowsFontEngine *few = new QWindowsFontEngine(request.family, lf, data);
- if (preferClearTypeAA)
- few->glyphFormat = QFontEngine::Format_A32;
- few->initFontInfo(request, dpi);
- fe = few;
- }
-
- return fe;
-}
-
-static inline int verticalDPI()
-{
- return GetDeviceCaps(QWindowsContext::instance()->displayContext(), LOGPIXELSY);
-}
-
-QFont QWindowsFontDatabase::systemDefaultFont()
-{
- LOGFONT lf;
- GetObject(QWindowsFontDatabase::systemFont(), sizeof(lf), &lf);
- QFont systemFont = QWindowsFontDatabase::LOGFONT_to_QFont(lf);
- // "MS Shell Dlg 2" is the correct system font >= Win2k
- if (systemFont.family() == QLatin1String("MS Shell Dlg"))
- systemFont.setFamily(QStringLiteral("MS Shell Dlg 2"));
- qCDebug(lcQpaFonts) << __FUNCTION__ << systemFont;
- return systemFont;
-}
-
-QFont QWindowsFontDatabase::LOGFONT_to_QFont(const LOGFONT& logFont, int verticalDPI_In)
-{
- if (verticalDPI_In <= 0)
- verticalDPI_In = verticalDPI();
- QFont qFont(QString::fromWCharArray(logFont.lfFaceName));
- qFont.setItalic(logFont.lfItalic);
- if (logFont.lfWeight != FW_DONTCARE)
- qFont.setWeight(QPlatformFontDatabase::weightFromInteger(logFont.lfWeight));
- const qreal logFontHeight = qAbs(logFont.lfHeight);
- qFont.setPointSizeF(logFontHeight * 72.0 / qreal(verticalDPI_In));
- qFont.setUnderline(logFont.lfUnderline);
- qFont.setOverline(false);
- qFont.setStrikeOut(logFont.lfStrikeOut);
- return qFont;
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsfontdatabase.h b/src/plugins/platforms/windows/qwindowsfontdatabase.h
deleted file mode 100644
index 574e20ef30..0000000000
--- a/src/plugins/platforms/windows/qwindowsfontdatabase.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWINDOWSFONTDATABASE_H
-#define QWINDOWSFONTDATABASE_H
-
-#include <qpa/qplatformfontdatabase.h>
-#include <QtCore/QSharedPointer>
-#include "qtwindows_additional.h"
-
-#if !defined(QT_NO_DIRECTWRITE)
- struct IDWriteFactory;
- struct IDWriteGdiInterop;
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QWindowsFontEngineData
-{
- Q_DISABLE_COPY(QWindowsFontEngineData)
-public:
- QWindowsFontEngineData();
- ~QWindowsFontEngineData();
-
- uint pow_gamma[256];
-
- bool clearTypeEnabled;
- qreal fontSmoothingGamma;
- HDC hdc;
-#if !defined(QT_NO_DIRECTWRITE)
- IDWriteFactory *directWriteFactory;
- IDWriteGdiInterop *directWriteGdiInterop;
-#endif
-};
-
-class QWindowsFontDatabase : public QPlatformFontDatabase
-{
-public:
- QWindowsFontDatabase();
- ~QWindowsFontDatabase();
-
- void populateFontDatabase() Q_DECL_OVERRIDE;
- void populateFamily(const QString &familyName) Q_DECL_OVERRIDE;
- QFontEngineMulti *fontEngineMulti(QFontEngine *fontEngine, QChar::Script script) Q_DECL_OVERRIDE;
- QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) Q_DECL_OVERRIDE;
- QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) Q_DECL_OVERRIDE;
- QStringList fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const Q_DECL_OVERRIDE;
- QStringList addApplicationFont(const QByteArray &fontData, const QString &fileName) Q_DECL_OVERRIDE;
- void releaseHandle(void *handle) Q_DECL_OVERRIDE;
- QString fontDir() const Q_DECL_OVERRIDE;
-
- QFont defaultFont() const Q_DECL_OVERRIDE { return systemDefaultFont(); }
- bool fontsAlwaysScalable() const Q_DECL_OVERRIDE;
- void derefUniqueFont(const QString &uniqueFont);
- void refUniqueFont(const QString &uniqueFont);
-
- static QFont systemDefaultFont();
-
- static QFontEngine *createEngine(const QFontDef &request,
- int dpi,
- const QSharedPointer<QWindowsFontEngineData> &data);
-
- static HFONT systemFont();
- static QFont LOGFONT_to_QFont(const LOGFONT& lf, int verticalDPI = 0);
-
- static qreal fontSmoothingGamma();
- static LOGFONT fontDefToLOGFONT(const QFontDef &fontDef);
-
- static QStringList extraTryFontsForFamily(const QString &family);
- static QString familyForStyleHint(QFont::StyleHint styleHint);
-
-private:
- void populateFamily(const QString &familyName, bool registerAlias);
- void removeApplicationFonts();
-
- struct WinApplicationFont {
- HANDLE handle;
- QString fileName;
- };
-
- QList<WinApplicationFont> m_applicationFonts;
-
- struct UniqueFontData {
- HANDLE handle;
- QAtomicInt refCount;
- };
-
- QMap<QString, UniqueFontData> m_uniqueFontData;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug, const QFontDef &def);
-#endif
-
-QT_END_NAMESPACE
-
-#endif // QWINDOWSFONTDATABASE_H
diff --git a/src/plugins/platforms/windows/qwindowsfontdatabase_ft.cpp b/src/plugins/platforms/windows/qwindowsfontdatabase_ft.cpp
deleted file mode 100644
index fb75e75dcd..0000000000
--- a/src/plugins/platforms/windows/qwindowsfontdatabase_ft.cpp
+++ /dev/null
@@ -1,755 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwindowsfontdatabase_ft.h"
-#include "qwindowsfontdatabase.h"
-#include "qwindowscontext.h"
-
-#include <ft2build.h>
-#include FT_TRUETYPE_TABLES_H
-
-#include <QtCore/QDir>
-#include <QtCore/QDirIterator>
-#include <QtCore/QSettings>
-#include <QtCore/QRegularExpression>
-#include <QtGui/private/qfontengine_ft_p.h>
-#include <QtGui/QGuiApplication>
-#include <QtGui/QFontDatabase>
-
-#include <wchar.h>
-#ifdef Q_OS_WINCE
-#include <QtCore/QFile>
-#include <QtEndian>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-static inline QFontDatabase::WritingSystem writingSystemFromCharSet(uchar charSet)
-{
- switch (charSet) {
- case ANSI_CHARSET:
- case EASTEUROPE_CHARSET:
- case BALTIC_CHARSET:
- case TURKISH_CHARSET:
- return QFontDatabase::Latin;
- case GREEK_CHARSET:
- return QFontDatabase::Greek;
- case RUSSIAN_CHARSET:
- return QFontDatabase::Cyrillic;
- case HEBREW_CHARSET:
- return QFontDatabase::Hebrew;
- case ARABIC_CHARSET:
- return QFontDatabase::Arabic;
- case THAI_CHARSET:
- return QFontDatabase::Thai;
- case GB2312_CHARSET:
- return QFontDatabase::SimplifiedChinese;
- case CHINESEBIG5_CHARSET:
- return QFontDatabase::TraditionalChinese;
- case SHIFTJIS_CHARSET:
- return QFontDatabase::Japanese;
- case HANGUL_CHARSET:
- case JOHAB_CHARSET:
- return QFontDatabase::Korean;
- case VIETNAMESE_CHARSET:
- return QFontDatabase::Vietnamese;
- case SYMBOL_CHARSET:
- return QFontDatabase::Symbol;
- default:
- break;
- }
- return QFontDatabase::Any;
-}
-
-static FontFile * createFontFile(const QString &fileName, int index)
-{
- FontFile *fontFile = new FontFile;
- fontFile->fileName = fileName;
- fontFile->indexValue = index;
- return fontFile;
-}
-
-extern bool localizedName(const QString &name);
-extern QString getEnglishName(const QString &familyName);
-
-#ifndef Q_OS_WINCE
-
-namespace {
-struct FontKey
-{
- QString fileName;
- QStringList fontNames;
-};
-} // namespace
-
-typedef QVector<FontKey> FontKeys;
-
-static FontKeys &fontKeys()
-{
- static FontKeys result;
- if (result.isEmpty()) {
- const QSettings fontRegistry(QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"),
- QSettings::NativeFormat);
- const QStringList allKeys = fontRegistry.allKeys();
- const QString trueType = QStringLiteral("(TrueType)");
- const QRegularExpression sizeListMatch(QStringLiteral("\\s(\\d+,)+\\d+"));
- Q_ASSERT(sizeListMatch.isValid());
- const int size = allKeys.size();
- result.reserve(size);
- for (int i = 0; i < size; ++i) {
- FontKey fontKey;
- const QString &registryFontKey = allKeys.at(i);
- fontKey.fileName = fontRegistry.value(registryFontKey).toString();
- QString realKey = registryFontKey;
- realKey.remove(trueType);
- realKey.remove(sizeListMatch);
- const QStringList fontNames = realKey.trimmed().split(QLatin1Char('&'));
- fontKey.fontNames.reserve(fontNames.size());
- foreach (const QString &fontName, fontNames)
- fontKey.fontNames.append(fontName.trimmed());
- result.append(fontKey);
- }
- }
- return result;
-}
-
-static const FontKey *findFontKey(const QString &name, int *indexIn = Q_NULLPTR)
-{
- const FontKeys &keys = fontKeys();
- for (auto it = keys.constBegin(), cend = keys.constEnd(); it != cend; ++it) {
- const int index = it->fontNames.indexOf(name);
- if (index >= 0) {
- if (indexIn)
- *indexIn = index;
- return &(*it);
- }
- }
- if (indexIn)
- *indexIn = -1;
- return Q_NULLPTR;
-}
-
-#else // Q_OS_WINCE
-
-typedef struct {
- quint16 majorVersion;
- quint16 minorVersion;
- quint16 numTables;
- quint16 searchRange;
- quint16 entrySelector;
- quint16 rangeShift;
-} OFFSET_TABLE;
-
-typedef struct {
- quint32 tag;
- quint32 checkSum;
- quint32 offset;
- quint32 length;
-} TABLE_DIRECTORY;
-
-typedef struct {
- quint16 fontSelector;
- quint16 nrCount;
- quint16 storageOffset;
-} NAME_TABLE_HEADER;
-
-typedef struct {
- quint16 platformID;
- quint16 encodingID;
- quint16 languageID;
- quint16 nameID;
- quint16 stringLength;
- quint16 stringOffset;
-} NAME_RECORD;
-
-typedef struct {
- quint32 tag;
- quint16 majorVersion;
- quint16 minorVersion;
- quint32 numFonts;
-} TTC_TABLE_HEADER;
-
-static QString fontNameFromTTFile(const QString &filename, int startPos = 0)
-{
- QFile f(filename);
- QString retVal;
- qint64 bytesRead;
- qint64 bytesToRead;
-
- if (f.open(QIODevice::ReadOnly)) {
- f.seek(startPos);
- OFFSET_TABLE ttOffsetTable;
- bytesToRead = sizeof(OFFSET_TABLE);
- bytesRead = f.read((char*)&ttOffsetTable, bytesToRead);
- if (bytesToRead != bytesRead)
- return retVal;
- ttOffsetTable.numTables = qFromBigEndian(ttOffsetTable.numTables);
- ttOffsetTable.majorVersion = qFromBigEndian(ttOffsetTable.majorVersion);
- ttOffsetTable.minorVersion = qFromBigEndian(ttOffsetTable.minorVersion);
-
- if (ttOffsetTable.majorVersion != 1 || ttOffsetTable.minorVersion != 0)
- return retVal;
-
- TABLE_DIRECTORY tblDir;
- bool found = false;
-
- for (int i = 0; i < ttOffsetTable.numTables; i++) {
- bytesToRead = sizeof(TABLE_DIRECTORY);
- bytesRead = f.read((char*)&tblDir, bytesToRead);
- if (bytesToRead != bytesRead)
- return retVal;
- if (qFromBigEndian(tblDir.tag) == MAKE_TAG('n', 'a', 'm', 'e')) {
- found = true;
- tblDir.length = qFromBigEndian(tblDir.length);
- tblDir.offset = qFromBigEndian(tblDir.offset);
- break;
- }
- }
-
- if (found) {
- f.seek(tblDir.offset);
- NAME_TABLE_HEADER ttNTHeader;
- bytesToRead = sizeof(NAME_TABLE_HEADER);
- bytesRead = f.read((char*)&ttNTHeader, bytesToRead);
- if (bytesToRead != bytesRead)
- return retVal;
- ttNTHeader.nrCount = qFromBigEndian(ttNTHeader.nrCount);
- ttNTHeader.storageOffset = qFromBigEndian(ttNTHeader.storageOffset);
- NAME_RECORD ttRecord;
- found = false;
-
- for (int i = 0; i < ttNTHeader.nrCount; i++) {
- bytesToRead = sizeof(NAME_RECORD);
- bytesRead = f.read((char*)&ttRecord, bytesToRead);
- if (bytesToRead != bytesRead)
- return retVal;
- ttRecord.nameID = qFromBigEndian(ttRecord.nameID);
- if (ttRecord.nameID == 1) {
- ttRecord.stringLength = qFromBigEndian(ttRecord.stringLength);
- ttRecord.stringOffset = qFromBigEndian(ttRecord.stringOffset);
- int nPos = f.pos();
- f.seek(tblDir.offset + ttRecord.stringOffset + ttNTHeader.storageOffset);
-
- QByteArray nameByteArray = f.read(ttRecord.stringLength);
- if (!nameByteArray.isEmpty()) {
- if (ttRecord.encodingID == 256 || ttRecord.encodingID == 768) {
- //This is UTF-16 in big endian
- int stringLength = ttRecord.stringLength / 2;
- retVal.resize(stringLength);
- QChar *data = retVal.data();
- const ushort *srcData = (const ushort *)nameByteArray.data();
- for (int i = 0; i < stringLength; ++i)
- data[i] = qFromBigEndian(srcData[i]);
- return retVal;
- } else if (ttRecord.encodingID == 0) {
- //This is Latin1
- retVal = QString::fromLatin1(nameByteArray);
- } else {
- qWarning("Could not retrieve Font name from file: %s", qPrintable(QDir::toNativeSeparators(filename)));
- }
- break;
- }
- f.seek(nPos);
- }
- }
- }
- f.close();
- }
- return retVal;
-}
-
-static QStringList fontNamesFromTTCFile(const QString &filename)
-{
- QFile f(filename);
- QStringList retVal;
- qint64 bytesRead;
- qint64 bytesToRead;
-
- if (f.open(QIODevice::ReadOnly)) {
- TTC_TABLE_HEADER ttcTableHeader;
- bytesToRead = sizeof(TTC_TABLE_HEADER);
- bytesRead = f.read((char*)&ttcTableHeader, bytesToRead);
- if (bytesToRead != bytesRead)
- return retVal;
- ttcTableHeader.majorVersion = qFromBigEndian(ttcTableHeader.majorVersion);
- ttcTableHeader.minorVersion = qFromBigEndian(ttcTableHeader.minorVersion);
- ttcTableHeader.numFonts = qFromBigEndian(ttcTableHeader.numFonts);
-
- if (ttcTableHeader.majorVersion < 1 || ttcTableHeader.majorVersion > 2)
- return retVal;
- QVarLengthArray<quint32> offsetTable(ttcTableHeader.numFonts);
- bytesToRead = sizeof(quint32) * ttcTableHeader.numFonts;
- bytesRead = f.read((char*)offsetTable.data(), bytesToRead);
- if (bytesToRead != bytesRead)
- return retVal;
- f.close();
- for (int i = 0; i < (int)ttcTableHeader.numFonts; ++i)
- retVal << fontNameFromTTFile(filename, qFromBigEndian(offsetTable[i]));
- }
- return retVal;
-}
-
-static inline QString fontSettingsOrganization() { return QStringLiteral("Qt-Project"); }
-static inline QString fontSettingsApplication() { return QStringLiteral("Qtbase"); }
-static inline QString fontSettingsGroup() { return QStringLiteral("CEFontCache"); }
-
-static QString findFontFile(const QString &faceName)
-{
- static QHash<QString, QString> fontCache;
-
- if (fontCache.isEmpty()) {
- QSettings settings(QSettings::SystemScope, fontSettingsOrganization(), fontSettingsApplication());
- settings.beginGroup(fontSettingsGroup());
- foreach (const QString &fontName, settings.allKeys())
- fontCache.insert(fontName, settings.value(fontName).toString());
- settings.endGroup();
- }
-
- QString value = fontCache.value(faceName);
-
- //Fallback if we haven't cached the font yet or the font got removed/renamed iterate again over all fonts
- if (value.isEmpty() || !QFile::exists(value)) {
- QSettings settings(QSettings::SystemScope, fontSettingsOrganization(), fontSettingsApplication());
- settings.beginGroup(fontSettingsGroup());
-
- //empty the cache first, as it seems that it is dirty
- settings.remove(QString());
-
- QDirIterator it(QStringLiteral("/Windows"), QStringList() << QStringLiteral("*.ttf") << QStringLiteral("*.ttc"), QDir::Files | QDir::Hidden | QDir::System);
- const QLatin1Char lowerF('f');
- const QLatin1Char upperF('F');
- while (it.hasNext()) {
- const QString fontFile = it.next();
- QStringList fontNames;
- const QChar c = fontFile[fontFile.size() - 1];
- if (c == lowerF || c == upperF)
- fontNames << fontNameFromTTFile(fontFile);
- else
- fontNames << fontNamesFromTTCFile(fontFile);
- foreach (const QString fontName, fontNames) {
- if (fontName.isEmpty())
- continue;
- fontCache.insert(fontName, fontFile);
- settings.setValue(fontName, fontFile);
-
- if (localizedName(fontName)) {
- QString englishFontName = getEnglishName(fontName);
- fontCache.insert(englishFontName, fontFile);
- settings.setValue(englishFontName, fontFile);
- }
- }
- }
- settings.endGroup();
- value = fontCache.value(faceName);
- }
- return value;
-}
-#endif // Q_OS_WINCE
-
-static bool addFontToDatabase(const QString &faceName,
- const QString &fullName,
- uchar charSet,
- const TEXTMETRIC *textmetric,
- const FONTSIGNATURE *signature,
- int type,
- bool registerAlias)
-{
- // the "@family" fonts are just the same as "family". Ignore them.
- if (faceName.isEmpty() || faceName.at(0) == QLatin1Char('@') || faceName.startsWith(QLatin1String("WST_")))
- return false;
-
- static const int SMOOTH_SCALABLE = 0xffff;
- const QString foundryName; // No such concept.
- const bool fixed = !(textmetric->tmPitchAndFamily & TMPF_FIXED_PITCH);
- const bool ttf = (textmetric->tmPitchAndFamily & TMPF_TRUETYPE);
- const bool scalable = textmetric->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE);
- const int size = scalable ? SMOOTH_SCALABLE : textmetric->tmHeight;
- const QFont::Style style = textmetric->tmItalic ? QFont::StyleItalic : QFont::StyleNormal;
- const bool antialias = false;
- const QFont::Weight weight = QPlatformFontDatabase::weightFromInteger(textmetric->tmWeight);
- const QFont::Stretch stretch = QFont::Unstretched;
-
-#ifndef QT_NO_DEBUG_STREAM
- if (QWindowsContext::verbose > 2) {
- QString message;
- QTextStream str(&message);
- str << __FUNCTION__ << ' ' << faceName << "::" << fullName << ' ' << charSet << " TTF=" << ttf;
- if (type & DEVICE_FONTTYPE)
- str << " DEVICE";
- if (type & RASTER_FONTTYPE)
- str << " RASTER";
- if (type & TRUETYPE_FONTTYPE)
- str << " TRUETYPE";
- str << " scalable=" << scalable << " Size=" << size
- << " Style=" << style << " Weight=" << weight
- << " stretch=" << stretch;
- qCDebug(lcQpaFonts) << message;
- }
-#endif
-
- QString englishName;
- if (registerAlias & ttf && localizedName(faceName))
- englishName = getEnglishName(faceName);
-
- QSupportedWritingSystems writingSystems;
- if (type & TRUETYPE_FONTTYPE) {
- Q_ASSERT(signature);
- quint32 unicodeRange[4] = {
- signature->fsUsb[0], signature->fsUsb[1],
- signature->fsUsb[2], signature->fsUsb[3]
- };
- quint32 codePageRange[2] = {
- signature->fsCsb[0], signature->fsCsb[1]
- };
- writingSystems = QPlatformFontDatabase::writingSystemsFromTrueTypeBits(unicodeRange, codePageRange);
- // ### Hack to work around problem with Thai text on Windows 7. Segoe UI contains
- // the symbol for Baht, and Windows thus reports that it supports the Thai script.
- // Since it's the default UI font on this platform, most widgets will be unable to
- // display Thai text by default. As a temporary work around, we special case Segoe UI
- // and remove the Thai script from its list of supported writing systems.
- if (writingSystems.supported(QFontDatabase::Thai) &&
- faceName == QLatin1String("Segoe UI"))
- writingSystems.setSupported(QFontDatabase::Thai, false);
- } else {
- const QFontDatabase::WritingSystem ws = writingSystemFromCharSet(charSet);
- if (ws != QFontDatabase::Any)
- writingSystems.setSupported(ws);
- }
-
- int index = 0;
-#ifndef Q_OS_WINCE
- const FontKey *key = findFontKey(faceName, &index);
- if (!key) {
- key = findFontKey(fullName, &index);
- if (!key && !registerAlias && englishName.isEmpty() && localizedName(faceName))
- englishName = getEnglishName(faceName);
- if (!key && !englishName.isEmpty())
- key = findFontKey(englishName, &index);
- if (!key)
- return false;
- }
- QString value = key->fileName;
-#else
- QString value = findFontFile(faceName);
-#endif
-
- if (value.isEmpty())
- return false;
-
- if (!QDir::isAbsolutePath(value))
-#ifndef Q_OS_WINCE
- value.prepend(QFile::decodeName(qgetenv("windir") + "\\Fonts\\"));
-#else
- value.prepend(QFile::decodeName("/Windows/"));
-#endif
-
- QPlatformFontDatabase::registerFont(faceName, QString(), foundryName, weight, style, stretch,
- antialias, scalable, size, fixed, writingSystems, createFontFile(value, index));
-
- // add fonts windows can generate for us:
- if (weight <= QFont::DemiBold)
- QPlatformFontDatabase::registerFont(faceName, QString(), foundryName, QFont::Bold, style, stretch,
- antialias, scalable, size, fixed, writingSystems, createFontFile(value, index));
-
- if (style != QFont::StyleItalic)
- QPlatformFontDatabase::registerFont(faceName, QString(), foundryName, weight, QFont::StyleItalic, stretch,
- antialias, scalable, size, fixed, writingSystems, createFontFile(value, index));
-
- if (weight <= QFont::DemiBold && style != QFont::StyleItalic)
- QPlatformFontDatabase::registerFont(faceName, QString(), foundryName, QFont::Bold, QFont::StyleItalic, stretch,
- antialias, scalable, size, fixed, writingSystems, createFontFile(value, index));
-
- if (!englishName.isEmpty())
- QPlatformFontDatabase::registerAliasToFontFamily(faceName, englishName);
-
- return true;
-}
-
-#ifdef Q_OS_WINCE
-static QByteArray getFntTable(HFONT hfont, uint tag)
-{
- HDC hdc = GetDC(0);
- HGDIOBJ oldFont = SelectObject(hdc, hfont);
- quint32 t = qFromBigEndian<quint32>(tag);
- QByteArray buffer;
-
- DWORD length = GetFontData(hdc, t, 0, NULL, 0);
- if (length != GDI_ERROR) {
- buffer.resize(length);
- GetFontData(hdc, t, 0, reinterpret_cast<uchar *>(buffer.data()), length);
- }
- SelectObject(hdc, oldFont);
- return buffer;
-}
-#endif
-
-static int QT_WIN_CALLBACK storeFont(const LOGFONT *logFont, const TEXTMETRIC *textmetric,
- DWORD type, LPARAM)
-{
- const ENUMLOGFONTEX *f = reinterpret_cast<const ENUMLOGFONTEX *>(logFont);
- const QString faceName = QString::fromWCharArray(f->elfLogFont.lfFaceName);
- const QString fullName = QString::fromWCharArray(f->elfFullName);
- const uchar charSet = f->elfLogFont.lfCharSet;
-
- // NEWTEXTMETRICEX (passed for TT fonts) is a NEWTEXTMETRIC, which according
- // to the documentation is identical to a TEXTMETRIC except for the last four
- // members, which we don't use anyway
- const FONTSIGNATURE *signature = Q_NULLPTR;
- if (type & TRUETYPE_FONTTYPE)
- signature = &reinterpret_cast<const NEWTEXTMETRICEX *>(textmetric)->ntmFontSig;
- addFontToDatabase(faceName, fullName, charSet, textmetric, signature, type, false);
-
- // keep on enumerating
- return 1;
-}
-
-/*!
- \brief Populate font database using EnumFontFamiliesEx().
-
- Normally, leaving the name empty should enumerate
- all fonts, however, system fonts like "MS Shell Dlg 2"
- are only found when specifying the name explicitly.
-*/
-
-void QWindowsFontDatabaseFT::populateFamily(const QString &familyName)
-{
- qCDebug(lcQpaFonts) << familyName;
- if (familyName.size() >= LF_FACESIZE) {
- qCWarning(lcQpaFonts) << "Unable to enumerate family '" << familyName << '\'';
- return;
- }
- HDC dummy = GetDC(0);
- LOGFONT lf;
- lf.lfCharSet = DEFAULT_CHARSET;
- familyName.toWCharArray(lf.lfFaceName);
- lf.lfFaceName[familyName.size()] = 0;
- lf.lfPitchAndFamily = 0;
- EnumFontFamiliesEx(dummy, &lf, storeFont, 0, 0);
- ReleaseDC(0, dummy);
-}
-
-namespace {
-// Context for enumerating system fonts, records whether the default font has been
-// encountered, which is normally not enumerated.
-struct PopulateFamiliesContext
-{
- PopulateFamiliesContext(const QString &f) : systemDefaultFont(f), seenSystemDefaultFont(false) {}
-
- QString systemDefaultFont;
- bool seenSystemDefaultFont;
-};
-} // namespace
-
-#ifndef Q_OS_WINCE
-
-// Delayed population of font families
-
-static int QT_WIN_CALLBACK populateFontFamilies(const LOGFONT *logFont, const TEXTMETRIC *textmetric,
- DWORD, LPARAM lparam)
-{
- const ENUMLOGFONTEX *f = reinterpret_cast<const ENUMLOGFONTEX *>(logFont);
- // the "@family" fonts are just the same as "family". Ignore them.
- const wchar_t *faceNameW = f->elfLogFont.lfFaceName;
- if (faceNameW[0] && faceNameW[0] != L'@' && wcsncmp(faceNameW, L"WST_", 4)) {
- // Register only font families for which a font file exists for delayed population
- const bool ttf = textmetric->tmPitchAndFamily & TMPF_TRUETYPE;
- const QString faceName = QString::fromWCharArray(faceNameW);
- const FontKey *key = findFontKey(faceName);
- if (!key) {
- key = findFontKey(QString::fromWCharArray(f->elfFullName));
- if (!key && ttf && localizedName(faceName))
- key = findFontKey(getEnglishName(faceName));
- }
- if (key) {
- QPlatformFontDatabase::registerFontFamily(faceName);
- PopulateFamiliesContext *context = reinterpret_cast<PopulateFamiliesContext *>(lparam);
- if (!context->seenSystemDefaultFont && faceName == context->systemDefaultFont)
- context->seenSystemDefaultFont = true;
-
- // Register current font's english name as alias
- if (ttf && localizedName(faceName)) {
- const QString englishName = getEnglishName(faceName);
- if (!englishName.isEmpty()) {
- QPlatformFontDatabase::registerAliasToFontFamily(faceName, englishName);
- // Check whether the system default font name is an alias of the current font family name,
- // as on Chinese Windows, where the system font "SimSun" is an alias to a font registered under a local name
- if (!context->seenSystemDefaultFont && englishName == context->systemDefaultFont)
- context->seenSystemDefaultFont = true;
- }
- }
- }
- }
- return 1; // continue
-}
-
-void QWindowsFontDatabaseFT::populateFontDatabase()
-{
- HDC dummy = GetDC(0);
- LOGFONT lf;
- lf.lfCharSet = DEFAULT_CHARSET;
- lf.lfFaceName[0] = 0;
- lf.lfPitchAndFamily = 0;
- PopulateFamiliesContext context(QWindowsFontDatabase::systemDefaultFont().family());
- EnumFontFamiliesEx(dummy, &lf, populateFontFamilies, reinterpret_cast<LPARAM>(&context), 0);
- ReleaseDC(0, dummy);
- // Work around EnumFontFamiliesEx() not listing the system font
- if (!context.seenSystemDefaultFont)
- QPlatformFontDatabase::registerFontFamily(context.systemDefaultFont);
-}
-
-#else // !Q_OS_WINCE
-
-// Non-delayed population of fonts (Windows CE).
-
-static int QT_WIN_CALLBACK populateFontCe(ENUMLOGFONTEX* f, NEWTEXTMETRICEX *textmetric,
- int type, LPARAM lparam)
-{
- // the "@family" fonts are just the same as "family". Ignore them.
- const wchar_t *faceNameW = f->elfLogFont.lfFaceName;
- if (faceNameW[0] && faceNameW[0] != L'@' && wcsncmp(faceNameW, L"WST_", 4)) {
- const uchar charSet = f->elfLogFont.lfCharSet;
-
- FONTSIGNATURE signature;
- QByteArray table;
-
- if (type & TRUETYPE_FONTTYPE) {
- HFONT hfont = CreateFontIndirect(&f->elfLogFont);
- table = getFntTable(hfont, MAKE_TAG('O', 'S', '/', '2'));
- DeleteObject((HGDIOBJ)hfont);
- }
-
- if (table.length() >= 86) {
- // See also qfontdatabase_mac.cpp, offsets taken from OS/2 table in the TrueType spec
- uchar *tableData = reinterpret_cast<uchar *>(table.data());
-
- signature.fsUsb[0] = qFromBigEndian<quint32>(tableData + 42);
- signature.fsUsb[1] = qFromBigEndian<quint32>(tableData + 46);
- signature.fsUsb[2] = qFromBigEndian<quint32>(tableData + 50);
- signature.fsUsb[3] = qFromBigEndian<quint32>(tableData + 54);
-
- signature.fsCsb[0] = qFromBigEndian<quint32>(tableData + 78);
- signature.fsCsb[1] = qFromBigEndian<quint32>(tableData + 82);
- } else {
- memset(&signature, 0, sizeof(signature));
- }
-
- // 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
- // anyway
- const QString faceName = QString::fromWCharArray(f->elfLogFont.lfFaceName);
- if (addFontToDatabase(faceName, QString::fromWCharArray(f->elfFullName),
- charSet, (TEXTMETRIC *)textmetric, &signature, type, true)) {
- PopulateFamiliesContext *context = reinterpret_cast<PopulateFamiliesContext *>(lparam);
- if (!context->seenSystemDefaultFont && faceName == context->systemDefaultFont)
- context->seenSystemDefaultFont = true;
- }
- }
-
- // keep on enumerating
- return 1;
-}
-
-void QWindowsFontDatabaseFT::populateFontDatabase()
-{
- LOGFONT lf;
- lf.lfCharSet = DEFAULT_CHARSET;
- HDC dummy = GetDC(0);
- lf.lfFaceName[0] = 0;
- lf.lfPitchAndFamily = 0;
- PopulateFamiliesContext context(QWindowsFontDatabase::systemDefaultFont().family());
- EnumFontFamiliesEx(dummy, &lf, (FONTENUMPROC)populateFontCe, reinterpret_cast<LPARAM>(&context), 0);
- ReleaseDC(0, dummy);
- // Work around EnumFontFamiliesEx() not listing the system font, see below.
- if (!context.seenSystemDefaultFont)
- populateFamily(context.systemDefaultFont);
-}
-#endif // Q_OS_WINCE
-
-QFontEngine * QWindowsFontDatabaseFT::fontEngine(const QFontDef &fontDef, void *handle)
-{
- QFontEngine *fe = QBasicFontDatabase::fontEngine(fontDef, handle);
- qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDEF" << fontDef.family << fe << handle;
- return fe;
-}
-
-QFontEngine *QWindowsFontDatabaseFT::fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference)
-{
- QFontEngine *fe = QBasicFontDatabase::fontEngine(fontData, pixelSize, hintingPreference);
- qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDATA" << fontData << pixelSize << hintingPreference << fe;
- return fe;
-}
-
-QStringList QWindowsFontDatabaseFT::fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const
-{
- QStringList result;
-
- result.append(QWindowsFontDatabase::familyForStyleHint(styleHint));
-
-#ifdef Q_OS_WINCE
- QSettings settings(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\FontLink\\SystemLink"), QSettings::NativeFormat);
- const QStringList fontList = settings.value(family).toStringList();
- foreach (const QString &fallback, fontList) {
- const int sep = fallback.indexOf(QLatin1Char(','));
- if (sep > 0)
- result << fallback.mid(sep + 1);
- }
-#endif
-
- result.append(QWindowsFontDatabase::extraTryFontsForFamily(family));
-
- result.append(QBasicFontDatabase::fallbacksForFamily(family, style, styleHint, script));
-
- qCDebug(lcQpaFonts) << __FUNCTION__ << family << style << styleHint
- << script << result;
-
- return result;
-}
-QString QWindowsFontDatabaseFT::fontDir() const
-{
- const QString result = QLatin1String(qgetenv("windir")) + QLatin1String("/Fonts");//QPlatformFontDatabase::fontDir();
- qCDebug(lcQpaFonts) << __FUNCTION__ << result;
- return result;
-}
-
-QFont QWindowsFontDatabaseFT::defaultFont() const
-{
- return QWindowsFontDatabase::systemDefaultFont();
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsfontengine.cpp b/src/plugins/platforms/windows/qwindowsfontengine.cpp
deleted file mode 100644
index 4f3df32f16..0000000000
--- a/src/plugins/platforms/windows/qwindowsfontengine.cpp
+++ /dev/null
@@ -1,1381 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtGui module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwindowsintegration.h"
-#include "qwindowsfontengine.h"
-#include "qwindowsnativeimage.h"
-#include "qwindowscontext.h"
-#include "qwindowsfontdatabase.h"
-#include "qtwindows_additional.h"
-#include "qwindowsfontenginedirectwrite.h"
-
-#include <QtGui/private/qtextengine_p.h> // glyph_metrics_t
-#include <QtGui/private/qguiapplication_p.h>
-#include <QtGui/QPaintDevice>
-#include <QtGui/QBitmap>
-#include <QtGui/QPainter>
-#include <QtGui/private/qpainter_p.h>
-#include <QtGui/QPaintEngine>
-#include <QtGui/private/qpaintengine_raster_p.h>
-
-#include <QtCore/QtEndian>
-#include <QtCore/QFile>
-#include <QtCore/qmath.h>
-#include <QtCore/QThreadStorage>
-#include <QtCore/private/qsystemlibrary_p.h>
-#include <QtCore/private/qstringiterator_p.h>
-
-#include <QtCore/QDebug>
-
-#include <limits.h>
-
-#ifdef Q_OS_WINCE
-# include "qplatformfunctions_wince.h"
-#endif
-
-#if !defined(QT_NO_DIRECTWRITE)
-# include <dwrite.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-//### mingw needed define
-#ifndef TT_PRIM_CSPLINE
-#define TT_PRIM_CSPLINE 3
-#endif
-
-// GetFontData expects the tags in little endian ;(
-#define MAKE_LITTLE_ENDIAN_TAG(ch1, ch2, ch3, ch4) (\
- (((quint32)(ch4)) << 24) | \
- (((quint32)(ch3)) << 16) | \
- (((quint32)(ch2)) << 8) | \
- ((quint32)(ch1)) \
- )
-
-// common DC for all fonts
-
-typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT);
-static PtrGetCharWidthI ptrGetCharWidthI = 0;
-static bool resolvedGetCharWidthI = false;
-
-static void resolveGetCharWidthI()
-{
- if (resolvedGetCharWidthI)
- return;
- resolvedGetCharWidthI = true;
- ptrGetCharWidthI = (PtrGetCharWidthI)QSystemLibrary::resolve(QStringLiteral("gdi32"), "GetCharWidthI");
-}
-
-static inline quint16 getUShort(unsigned char *p)
-{
- quint16 val;
- val = *p++ << 8;
- val |= *p;
-
- return val;
-}
-
-// general font engine
-
-QFixed QWindowsFontEngine::lineThickness() const
-{
- if(lineWidth > 0)
- return lineWidth;
-
- return QFontEngine::lineThickness();
-}
-
-static OUTLINETEXTMETRIC *getOutlineTextMetric(HDC hdc)
-{
- int size;
- size = GetOutlineTextMetrics(hdc, 0, 0);
- OUTLINETEXTMETRIC *otm = (OUTLINETEXTMETRIC *)malloc(size);
- GetOutlineTextMetrics(hdc, size, otm);
- return otm;
-}
-
-bool QWindowsFontEngine::hasCFFTable() const
-{
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- return GetFontData(hdc, MAKE_LITTLE_ENDIAN_TAG('C', 'F', 'F', ' '), 0, 0, 0) != GDI_ERROR;
-}
-
-bool QWindowsFontEngine::hasCMapTable() const
-{
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- return GetFontData(hdc, MAKE_LITTLE_ENDIAN_TAG('c', 'm', 'a', 'p'), 0, 0, 0) != GDI_ERROR;
-}
-
-bool QWindowsFontEngine::hasGlyfTable() const
-{
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- return GetFontData(hdc, MAKE_LITTLE_ENDIAN_TAG('g', 'l', 'y', 'f'), 0, 0, 0) != GDI_ERROR;
-}
-
-bool QWindowsFontEngine::hasEbdtTable() const
-{
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- return GetFontData(hdc, MAKE_LITTLE_ENDIAN_TAG('E', 'B', 'D', 'T'), 0, 0, 0) != GDI_ERROR;
-}
-
-static inline QString stringFromOutLineTextMetric(const OUTLINETEXTMETRIC *otm, PSTR offset)
-{
- const uchar *p = reinterpret_cast<const uchar *>(otm) + quintptr(offset);
- return QString::fromWCharArray(reinterpret_cast<const wchar_t *>(p));
-}
-
-void QWindowsFontEngine::getCMap()
-{
- ttf = (bool)(tm.tmPitchAndFamily & TMPF_TRUETYPE) || hasCMapTable();
-
- cffTable = hasCFFTable();
-
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- bool symb = false;
- if (ttf) {
- cmapTable = getSfntTable(MAKE_TAG('c', 'm', 'a', 'p'));
- cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()),
- cmapTable.size(), &symb, &cmapSize);
- }
- if (!cmap) {
- ttf = false;
- symb = false;
- }
- symbol = symb;
- designToDevice = 1;
- _faceId.index = 0;
- if(cmap) {
- OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc);
- unitsPerEm = int(otm->otmEMSquare);
- const QFixed unitsPerEmF(unitsPerEm);
- designToDevice = unitsPerEmF / QFixed::fromReal(fontDef.pixelSize);
- x_height = int(otm->otmsXHeight);
- loadKerningPairs(designToDevice);
- _faceId.filename = QFile::encodeName(stringFromOutLineTextMetric(otm, otm->otmpFullName));
- lineWidth = otm->otmsUnderscoreSize;
- fsType = otm->otmfsType;
- free(otm);
- } else {
- unitsPerEm = tm.tmHeight;
- }
-}
-
-int QWindowsFontEngine::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout *glyphs) const
-{
- int glyph_pos = 0;
- {
-#if defined(Q_OS_WINCE)
- {
-#else
- if (symbol) {
- QStringIterator it(str, str + numChars);
- while (it.hasNext()) {
- const uint uc = it.next();
- glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, cmapSize, uc);
- if(!glyphs->glyphs[glyph_pos] && uc < 0x100)
- glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, cmapSize, uc + 0xf000);
- ++glyph_pos;
- }
- } else if (ttf) {
- QStringIterator it(str, str + numChars);
- while (it.hasNext()) {
- const uint uc = it.next();
- glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, cmapSize, uc);
- ++glyph_pos;
- }
- } else {
-#endif
- QStringIterator it(str, str + numChars);
- while (it.hasNext()) {
- const uint uc = it.next();
- if (uc >= tm.tmFirstChar && uc <= tm.tmLastChar)
- glyphs->glyphs[glyph_pos] = uc;
- else
- glyphs->glyphs[glyph_pos] = 0;
- ++glyph_pos;
- }
- }
- }
- glyphs->numGlyphs = glyph_pos;
- return glyph_pos;
-}
-
-/*!
- \class QWindowsFontEngine
- \brief Standard Windows font engine.
- \internal
- \ingroup qt-lighthouse-win
-
- Will probably be superseded by a common Free Type font engine in Qt 5.X.
-*/
-
-QWindowsFontEngine::QWindowsFontEngine(const QString &name,
- LOGFONT lf,
- const QSharedPointer<QWindowsFontEngineData> &fontEngineData)
- : QFontEngine(Win),
- m_fontEngineData(fontEngineData),
- _name(name),
- hfont(0),
- m_logfont(lf),
- ttf(0),
- hasOutline(0),
- cmap(0),
- cmapSize(0),
- lbearing(SHRT_MIN),
- rbearing(SHRT_MIN),
- x_height(-1),
- synthesized_flags(-1),
- lineWidth(-1),
- widthCache(0),
- widthCacheSize(0),
- designAdvances(0),
- designAdvancesSize(0)
-{
- qCDebug(lcQpaFonts) << __FUNCTION__ << name << lf.lfHeight;
- hfont = CreateFontIndirect(&m_logfont);
- if (!hfont) {
- qErrnoWarning("%s: CreateFontIndirect failed for family '%s'", __FUNCTION__, qPrintable(name));
- hfont = QWindowsFontDatabase::systemFont();
- }
-
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- const BOOL res = GetTextMetrics(hdc, &tm);
- if (!res) {
- qErrnoWarning("%s: GetTextMetrics failed", __FUNCTION__);
- ZeroMemory(&tm, sizeof(TEXTMETRIC));
- }
-
- fontDef.pixelSize = -lf.lfHeight;
- fontDef.fixedPitch = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH);
-
- cache_cost = tm.tmHeight * tm.tmAveCharWidth * 2000;
- getCMap();
-
- if (!resolvedGetCharWidthI)
- resolveGetCharWidthI();
-
- // ### Properties accessed by QWin32PrintEngine (QtPrintSupport)
- QVariantMap userData;
- userData.insert(QStringLiteral("logFont"), QVariant::fromValue(m_logfont));
- userData.insert(QStringLiteral("hFont"), QVariant::fromValue(hfont));
- userData.insert(QStringLiteral("trueType"), QVariant(bool(ttf)));
- setUserData(userData);
-
- hasUnreliableOutline = hasGlyfTable() && hasEbdtTable();
-}
-
-QWindowsFontEngine::~QWindowsFontEngine()
-{
- if (designAdvances)
- free(designAdvances);
-
- if (widthCache)
- free(widthCache);
-
- // make sure we aren't by accident still selected
- SelectObject(m_fontEngineData->hdc, QWindowsFontDatabase::systemFont());
-
- if (!DeleteObject(hfont))
- qErrnoWarning("%s: QFontEngineWin: failed to delete font...", __FUNCTION__);
- qCDebug(lcQpaFonts) << __FUNCTION__ << _name;
-
- if (!uniqueFamilyName.isEmpty()) {
- QPlatformFontDatabase *pfdb = QWindowsIntegration::instance()->fontDatabase();
- static_cast<QWindowsFontDatabase *>(pfdb)->derefUniqueFont(uniqueFamilyName);
- }
-}
-
-glyph_t QWindowsFontEngine::glyphIndex(uint ucs4) const
-{
- glyph_t glyph;
-
-#if !defined(Q_OS_WINCE)
- if (symbol) {
- glyph = getTrueTypeGlyphIndex(cmap, cmapSize, ucs4);
- if (glyph == 0 && ucs4 < 0x100)
- glyph = getTrueTypeGlyphIndex(cmap, cmapSize, ucs4 + 0xf000);
- } else if (ttf) {
- glyph = getTrueTypeGlyphIndex(cmap, cmapSize, ucs4);
- } else
-#endif
- if (ucs4 >= tm.tmFirstChar && ucs4 <= tm.tmLastChar) {
- glyph = ucs4;
- } else {
- glyph = 0;
- }
-
- return glyph;
-}
-
-HGDIOBJ QWindowsFontEngine::selectDesignFont() const
-{
- LOGFONT f = m_logfont;
- f.lfHeight = -unitsPerEm;
- f.lfWidth = 0;
- HFONT designFont = CreateFontIndirect(&f);
- return SelectObject(m_fontEngineData->hdc, designFont);
-}
-
-bool QWindowsFontEngine::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QFontEngine::ShaperFlags flags) const
-{
- Q_ASSERT(glyphs->numGlyphs >= *nglyphs);
- if (*nglyphs < len) {
- *nglyphs = len;
- return false;
- }
-
- glyphs->numGlyphs = *nglyphs;
- *nglyphs = getGlyphIndexes(str, len, glyphs);
-
- if (!(flags & GlyphIndicesOnly))
- recalcAdvances(glyphs, flags);
-
- return true;
-}
-
-inline void calculateTTFGlyphWidth(HDC hdc, UINT glyph, int &width)
-{
-#if defined(Q_OS_WINCE)
- GetCharWidth32(hdc, glyph, glyph, &width);
-#else
- if (ptrGetCharWidthI)
- ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
-#endif
-}
-
-void QWindowsFontEngine::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags flags) const
-{
- HGDIOBJ oldFont = 0;
- HDC hdc = m_fontEngineData->hdc;
- if (ttf && (flags & DesignMetrics)) {
- for(int i = 0; i < glyphs->numGlyphs; i++) {
- unsigned int glyph = glyphs->glyphs[i];
- if(int(glyph) >= designAdvancesSize) {
- const int newSize = int(glyph + 256) >> 8 << 8;
- designAdvances = reinterpret_cast<QFixed *>(realloc(designAdvances, size_t(newSize) * sizeof(QFixed)));
- Q_CHECK_PTR(designAdvances);
- for(int i = designAdvancesSize; i < newSize; ++i)
- designAdvances[i] = -1000000;
- designAdvancesSize = newSize;
- }
- if (designAdvances[glyph] < -999999) {
- if (!oldFont)
- oldFont = selectDesignFont();
-
- int width = 0;
- calculateTTFGlyphWidth(hdc, glyph, width);
- designAdvances[glyph] = QFixed(width) / designToDevice;
- }
- glyphs->advances[i] = designAdvances[glyph];
- }
- if(oldFont)
- DeleteObject(SelectObject(hdc, oldFont));
- } else {
- for(int i = 0; i < glyphs->numGlyphs; i++) {
- unsigned int glyph = glyphs->glyphs[i];
-
- if (glyph >= widthCacheSize) {
- const uint newSize = (glyph + 256) >> 8 << 8;
- widthCache = reinterpret_cast<unsigned char *>(realloc(widthCache, newSize * sizeof(QFixed)));
- Q_CHECK_PTR(widthCache);
- memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
- widthCacheSize = newSize;
- }
- glyphs->advances[i] = widthCache[glyph];
- // font-width cache failed
- if (glyphs->advances[i].value() == 0) {
- int width = 0;
- if (!oldFont)
- oldFont = SelectObject(hdc, hfont);
-
- if (!ttf) {
- QChar ch[2] = { ushort(glyph), 0 };
- int chrLen = 1;
- if (QChar::requiresSurrogates(glyph)) {
- ch[0] = QChar::highSurrogate(glyph);
- ch[1] = QChar::lowSurrogate(glyph);
- ++chrLen;
- }
- SIZE size = {0, 0};
- GetTextExtentPoint32(hdc, reinterpret_cast<const wchar_t *>(ch), chrLen, &size);
- width = size.cx;
- } else {
- calculateTTFGlyphWidth(hdc, glyph, width);
- }
- glyphs->advances[i] = width;
- // if glyph's within cache range, store it for later
- if (width > 0 && width < 0x100)
- widthCache[glyph] = uchar(width);
- }
- }
-
- if (oldFont)
- SelectObject(hdc, oldFont);
- }
-}
-
-glyph_metrics_t QWindowsFontEngine::boundingBox(const QGlyphLayout &glyphs)
-{
- if (glyphs.numGlyphs == 0)
- return glyph_metrics_t();
-
- QFixed w = 0;
- for (int i = 0; i < glyphs.numGlyphs; ++i)
- w += glyphs.effectiveAdvance(i);
-
- return glyph_metrics_t(0, -tm.tmAscent, w - lastRightBearing(glyphs), tm.tmHeight, w, 0);
-}
-#ifndef Q_OS_WINCE
-bool QWindowsFontEngine::getOutlineMetrics(glyph_t glyph, const QTransform &t, glyph_metrics_t *metrics) const
-{
- Q_ASSERT(metrics != 0);
-
- HDC hdc = m_fontEngineData->hdc;
-
- GLYPHMETRICS gm;
- DWORD res = 0;
- 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;
-
- if (t.type() > QTransform::TxTranslate) {
- // We need to set the transform using the HDC's world
- // matrix rather than using the MAT2 above, because the
- // results provided when transforming via MAT2 does not
- // match the glyphs that are drawn using a WorldTransform
- XFORM xform;
- xform.eM11 = FLOAT(t.m11());
- xform.eM12 = FLOAT(t.m12());
- xform.eM21 = FLOAT(t.m21());
- xform.eM22 = FLOAT(t.m22());
- xform.eDx = 0;
- xform.eDy = 0;
- SetGraphicsMode(hdc, GM_ADVANCED);
- SetWorldTransform(hdc, &xform);
- }
-
- uint format = GGO_METRICS;
- if (ttf)
- format |= GGO_GLYPH_INDEX;
- res = GetGlyphOutline(hdc, glyph, format, &gm, 0, 0, &mat);
-
- if (t.type() > QTransform::TxTranslate) {
- XFORM xform;
- xform.eM11 = xform.eM22 = 1;
- xform.eM12 = xform.eM21 = xform.eDx = xform.eDy = 0;
- SetWorldTransform(hdc, &xform);
- SetGraphicsMode(hdc, GM_COMPATIBLE);
- }
-
- if (res != GDI_ERROR) {
- *metrics = glyph_metrics_t(gm.gmptGlyphOrigin.x, -gm.gmptGlyphOrigin.y,
- int(gm.gmBlackBoxX), int(gm.gmBlackBoxY),
- gm.gmCellIncX, gm.gmCellIncY);
- return true;
- } else {
- return false;
- }
-}
-#endif
-
-glyph_metrics_t QWindowsFontEngine::boundingBox(glyph_t glyph, const QTransform &t)
-{
-#ifndef Q_OS_WINCE
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
-
- glyph_metrics_t glyphMetrics;
- bool success = getOutlineMetrics(glyph, t, &glyphMetrics);
-
- if (!ttf && !success) {
- // Bitmap fonts
- wchar_t ch = wchar_t(glyph);
- ABCFLOAT abc;
- GetCharABCWidthsFloat(hdc, ch, ch, &abc);
- int width = qRound(abc.abcfB);
-
- return glyph_metrics_t(QFixed::fromReal(abc.abcfA), -tm.tmAscent, width, tm.tmHeight, width, 0).transformed(t);
- }
-
- return glyphMetrics;
-#else
- HDC hdc = m_fontEngineData->hdc;
- HGDIOBJ oldFont = SelectObject(hdc, hfont);
-
- ABC abc;
- int width;
- int advance;
-#ifdef GWES_MGTT // true type fonts
- if (GetCharABCWidths(hdc, glyph, glyph, &abc)) {
- width = qAbs(abc.abcA) + abc.abcB + qAbs(abc.abcC);
- advance = abc.abcA + abc.abcB + abc.abcC;
- }
- else
-#endif
-#if defined(GWES_MGRAST) || defined(GWES_MGRAST2) // raster fonts
- if (GetCharWidth32(hdc, glyph, glyph, &width)) {
- advance = width;
- }
- else
-#endif
- { // fallback
- width = tm.tmMaxCharWidth;
- advance = width;
- }
-
- SelectObject(hdc, oldFont);
- return glyph_metrics_t(0, -tm.tmAscent, width, tm.tmHeight, advance, 0).transformed(t);
-#endif
-}
-
-QFixed QWindowsFontEngine::ascent() const
-{
- return tm.tmAscent;
-}
-
-QFixed QWindowsFontEngine::descent() const
-{
- return tm.tmDescent;
-}
-
-QFixed QWindowsFontEngine::leading() const
-{
- return tm.tmExternalLeading;
-}
-
-
-QFixed QWindowsFontEngine::xHeight() const
-{
- if(x_height >= 0)
- return x_height;
- return QFontEngine::xHeight();
-}
-
-QFixed QWindowsFontEngine::averageCharWidth() const
-{
- return tm.tmAveCharWidth;
-}
-
-qreal QWindowsFontEngine::maxCharWidth() const
-{
- return tm.tmMaxCharWidth;
-}
-
-enum { max_font_count = 256 };
-static const ushort char_table[] = {
- 40,
- 67,
- 70,
- 75,
- 86,
- 88,
- 89,
- 91,
- 102,
- 114,
- 124,
- 127,
- 205,
- 645,
- 884,
- 922,
- 1070,
- 12386,
- 0
-};
-
-static const int char_table_entries = sizeof(char_table)/sizeof(ushort);
-
-#ifndef Q_CC_MINGW
-void QWindowsFontEngine::getGlyphBearings(glyph_t glyph, qreal *leftBearing, qreal *rightBearing)
-{
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
-
-#ifndef Q_OS_WINCE
- if (ttf)
-#endif
- {
- ABC abcWidths;
- GetCharABCWidthsI(hdc, glyph, 1, 0, &abcWidths);
- if (leftBearing)
- *leftBearing = abcWidths.abcA;
- if (rightBearing)
- *rightBearing = abcWidths.abcC;
- }
-#ifndef Q_OS_WINCE
- else {
- QFontEngine::getGlyphBearings(glyph, leftBearing, rightBearing);
- }
-#endif
-}
-#endif // Q_CC_MINGW
-
-bool QWindowsFontEngine::hasUnreliableGlyphOutline() const
-{
- return hasUnreliableOutline || QFontEngine::hasUnreliableGlyphOutline();
-}
-
-qreal QWindowsFontEngine::minLeftBearing() const
-{
- if (lbearing == SHRT_MIN)
- minRightBearing(); // calculates both
-
- return lbearing;
-}
-
-qreal QWindowsFontEngine::minRightBearing() const
-{
-#ifndef Q_OS_WINCE
- if (rbearing == SHRT_MIN) {
- int ml = 0;
- int mr = 0;
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- if (ttf) {
- ABC *abc = 0;
- int n = tm.tmLastChar - tm.tmFirstChar;
- if (n <= max_font_count) {
- abc = new ABC[n+1];
- GetCharABCWidths(hdc, tm.tmFirstChar, tm.tmLastChar, abc);
- } else {
- abc = new ABC[char_table_entries+1];
- 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;
- mr = abc[0].abcC;
- for (int i = 1; i < n; i++) {
- if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
- ml = qMin(ml,abc[i].abcA);
- mr = qMin(mr,abc[i].abcC);
- }
- }
- delete [] abc;
- } else {
- 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;
- }
- lbearing = ml;
- rbearing = mr;
- }
-
- return rbearing;
-#else // !Q_OS_WINCE
- if (rbearing == SHRT_MIN) {
- int ml = 0;
- int mr = 0;
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- if (ttf) {
- ABC *abc = 0;
- int n = tm.tmLastChar - tm.tmFirstChar;
- if (n <= max_font_count) {
- abc = new ABC[n+1];
- GetCharABCWidths(hdc, tm.tmFirstChar, tm.tmLastChar, abc);
- } else {
- abc = new ABC[char_table_entries+1];
- 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;
- mr = abc[0].abcC;
- for (int i = 1; i < n; i++) {
- if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
- ml = qMin(ml,abc[i].abcA);
- mr = qMin(mr,abc[i].abcC);
- }
- }
- delete [] abc;
- }
- lbearing = ml;
- rbearing = mr;
- }
-
- return rbearing;
-#endif // Q_OS_WINCE
-}
-
-static inline double qt_fixed_to_double(const FIXED &p) {
- return ((p.value << 16) + p.fract) / 65536.0;
-}
-
-static inline QPointF qt_to_qpointf(const POINTFX &pt, qreal scale) {
- return QPointF(qt_fixed_to_double(pt.x) * scale, -qt_fixed_to_double(pt.y) * scale);
-}
-
-#ifndef GGO_UNHINTED
-#define GGO_UNHINTED 0x0100
-#endif
-
-static bool addGlyphToPath(glyph_t glyph, const QFixedPoint &position, HDC hdc,
- QPainterPath *path, bool ttf, glyph_metrics_t *metric = 0, qreal scale = 1)
-{
- 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;
-
- GLYPHMETRICS gMetric;
- memset(&gMetric, 0, sizeof(GLYPHMETRICS));
-
-#ifndef Q_OS_WINCE
- if (metric) {
- // If metrics requested, retrieve first using GGO_METRICS, because the returned
- // values are incorrect for OpenType PS fonts if obtained at the same time as the
- // glyph paths themselves (ie. with GGO_NATIVE as the format).
- uint format = GGO_METRICS;
- if (ttf)
- format |= GGO_GLYPH_INDEX;
- if (GetGlyphOutline(hdc, glyph, format, &gMetric, 0, 0, &mat) == GDI_ERROR)
- return false;
- // #### obey scale
- *metric = glyph_metrics_t(gMetric.gmptGlyphOrigin.x, -gMetric.gmptGlyphOrigin.y,
- int(gMetric.gmBlackBoxX), int(gMetric.gmBlackBoxY),
- gMetric.gmCellIncX, gMetric.gmCellIncY);
- }
-#endif
-
- uint glyphFormat = GGO_NATIVE;
-
- if (ttf)
- glyphFormat |= GGO_GLYPH_INDEX;
-
- const DWORD bufferSize = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
- if (bufferSize == GDI_ERROR)
- return false;
-
- char *dataBuffer = new char[bufferSize];
- DWORD ret = GDI_ERROR;
- ret = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, bufferSize, dataBuffer, &mat);
- if (ret == GDI_ERROR) {
- delete [] dataBuffer;
- return false;
- }
-
-#ifdef Q_OS_WINCE
- if (metric) {
- // #### obey scale
- *metric = glyph_metrics_t(gMetric.gmptGlyphOrigin.x, -gMetric.gmptGlyphOrigin.y,
- (int)gMetric.gmBlackBoxX, (int)gMetric.gmBlackBoxY,
- gMetric.gmCellIncX, gMetric.gmCellIncY);
- }
-#endif
-
- DWORD offset = 0;
- DWORD headerOffset = 0;
-
- QPointF oset = position.toPointF();
- while (headerOffset < bufferSize) {
- const TTPOLYGONHEADER *ttph = reinterpret_cast<const TTPOLYGONHEADER *>(dataBuffer + headerOffset);
-
- QPointF lastPoint(qt_to_qpointf(ttph->pfxStart, scale));
- path->moveTo(lastPoint + oset);
- offset += sizeof(TTPOLYGONHEADER);
- while (offset < headerOffset + ttph->cb) {
- const TTPOLYCURVE *curve = reinterpret_cast<const TTPOLYCURVE *>(dataBuffer + offset);
- switch (curve->wType) {
- case TT_PRIM_LINE: {
- for (int i=0; i<curve->cpfx; ++i) {
- QPointF p = qt_to_qpointf(curve->apfx[i], scale) + oset;
- path->lineTo(p);
- }
- break;
- }
- case TT_PRIM_QSPLINE: {
- const QPainterPath::Element &elm = path->elementAt(path->elementCount()-1);
- QPointF prev(elm.x, elm.y);
- QPointF endPoint;
- for (int i=0; i<curve->cpfx - 1; ++i) {
- QPointF p1 = qt_to_qpointf(curve->apfx[i], scale) + oset;
- QPointF p2 = qt_to_qpointf(curve->apfx[i+1], scale) + oset;
- if (i < curve->cpfx - 2) {
- endPoint = QPointF((p1.x() + p2.x()) / 2, (p1.y() + p2.y()) / 2);
- } else {
- endPoint = p2;
- }
-
- path->quadTo(p1, endPoint);
- prev = endPoint;
- }
-
- break;
- }
- case TT_PRIM_CSPLINE: {
- for (int i=0; i<curve->cpfx; ) {
- QPointF p2 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
- QPointF p3 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
- QPointF p4 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
- path->cubicTo(p2, p3, p4);
- }
- break;
- }
- default:
- qWarning("QFontEngineWin::addOutlineToPath, unhandled switch case");
- }
- offset += sizeof(TTPOLYCURVE) + (curve->cpfx-1) * sizeof(POINTFX);
- }
- path->closeSubpath();
- headerOffset += ttph->cb;
- }
- delete [] dataBuffer;
-
- return true;
-}
-
-void QWindowsFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
- QPainterPath *path, QTextItem::RenderFlags)
-{
- LOGFONT lf = m_logfont;
- // The sign must be negative here to make sure we match against character height instead of
- // hinted cell height. This ensures that we get linear matching, and we need this for
- // paths since we later on apply a scaling transform to the glyph outline to get the
- // font at the correct pixel size.
- lf.lfHeight = -unitsPerEm;
- lf.lfWidth = 0;
- HFONT hf = CreateFontIndirect(&lf);
- HDC hdc = m_fontEngineData->hdc;
- HGDIOBJ oldfont = SelectObject(hdc, hf);
-
- for(int i = 0; i < nglyphs; ++i) {
- if (!addGlyphToPath(glyphs[i], positions[i], hdc, path, ttf, /*metric*/0,
- qreal(fontDef.pixelSize) / unitsPerEm)) {
- // Some windows fonts, like "Modern", are vector stroke
- // fonts, which are reported as TMPF_VECTOR but do not
- // support GetGlyphOutline, and thus we set this bit so
- // that addOutLineToPath can check it and return safely...
- hasOutline = false;
- break;
- }
- }
- DeleteObject(SelectObject(hdc, oldfont));
-}
-
-void QWindowsFontEngine::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs,
- QPainterPath *path, QTextItem::RenderFlags flags)
-{
- if(tm.tmPitchAndFamily & (TMPF_TRUETYPE | TMPF_VECTOR)) {
- hasOutline = true;
- QFontEngine::addOutlineToPath(x, y, glyphs, path, flags);
- if (hasOutline) {
- // has_outline is set to false if addGlyphToPath gets
- // false from GetGlyphOutline, meaning its not an outline
- // font.
- return;
- }
- }
- QFontEngine::addBitmapFontToPath(x, y, glyphs, path, flags);
-}
-
-QFontEngine::FaceId QWindowsFontEngine::faceId() const
-{
- return _faceId;
-}
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <qdebug.h>
-QT_END_INCLUDE_NAMESPACE
-
-int QWindowsFontEngine::synthesized() const
-{
- if(synthesized_flags == -1) {
- synthesized_flags = 0;
- if(ttf) {
- const DWORD HEAD = MAKE_LITTLE_ENDIAN_TAG('h', 'e', 'a', 'd');
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- uchar data[4];
- GetFontData(hdc, HEAD, 44, &data, 4);
- USHORT macStyle = getUShort(data);
- if (tm.tmItalic && !(macStyle & 2))
- synthesized_flags = SynthesizedItalic;
- if (fontDef.stretch != 100 && ttf)
- synthesized_flags |= SynthesizedStretch;
- if (tm.tmWeight >= 500 && !(macStyle & 1))
- synthesized_flags |= SynthesizedBold;
- //qDebug() << "font is" << _name <<
- // "it=" << (macStyle & 2) << fontDef.style << "flags=" << synthesized_flags;
- }
- }
- return synthesized_flags;
-}
-
-QFixed QWindowsFontEngine::emSquareSize() const
-{
- return unitsPerEm;
-}
-
-QFontEngine::Properties QWindowsFontEngine::properties() const
-{
- LOGFONT lf = m_logfont;
- lf.lfHeight = unitsPerEm;
- HFONT hf = CreateFontIndirect(&lf);
- HDC hdc = m_fontEngineData->hdc;
- HGDIOBJ oldfont = SelectObject(hdc, hf);
- OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc);
- Properties p;
- p.emSquare = unitsPerEm;
- p.italicAngle = otm->otmItalicAngle;
- const QByteArray name = stringFromOutLineTextMetric(otm, otm->otmpFamilyName).toLatin1()
- + stringFromOutLineTextMetric(otm, otm->otmpStyleName).toLatin1();
- p.postscriptName = QFontEngine::convertToPostscriptFontFamilyName(name);
- p.boundingBox = QRectF(otm->otmrcFontBox.left, -otm->otmrcFontBox.top,
- otm->otmrcFontBox.right - otm->otmrcFontBox.left,
- otm->otmrcFontBox.top - otm->otmrcFontBox.bottom);
- p.ascent = otm->otmAscent;
- p.descent = -otm->otmDescent;
- p.leading = int(otm->otmLineGap);
- p.capHeight = 0;
- p.lineWidth = otm->otmsUnderscoreSize;
- free(otm);
- DeleteObject(SelectObject(hdc, oldfont));
- return p;
-}
-
-void QWindowsFontEngine::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
-{
- LOGFONT lf = m_logfont;
- lf.lfHeight = -unitsPerEm;
- int flags = synthesized();
- if(flags & SynthesizedItalic)
- lf.lfItalic = false;
- lf.lfWidth = 0;
- HFONT hf = CreateFontIndirect(&lf);
- HDC hdc = m_fontEngineData->hdc;
- HGDIOBJ oldfont = SelectObject(hdc, hf);
- QFixedPoint p;
- p.x = 0;
- p.y = 0;
- addGlyphToPath(glyph, p, hdc, path, ttf, metrics);
- DeleteObject(SelectObject(hdc, oldfont));
-}
-
-bool QWindowsFontEngine::getSfntTableData(uint tag, uchar *buffer, uint *length) const
-{
- if (!ttf && !cffTable)
- return false;
- HDC hdc = m_fontEngineData->hdc;
- SelectObject(hdc, hfont);
- DWORD t = qbswap<quint32>(tag);
- *length = GetFontData(hdc, t, 0, buffer, *length);
- Q_ASSERT(*length == GDI_ERROR || int(*length) > 0);
- return *length != GDI_ERROR;
-}
-
-#if !defined(CLEARTYPE_QUALITY)
-# define CLEARTYPE_QUALITY 5
-#endif
-
-QWindowsNativeImage *QWindowsFontEngine::drawGDIGlyph(HFONT font, glyph_t glyph, int margin,
- const QTransform &t,
- QImage::Format mask_format)
-{
- Q_UNUSED(mask_format)
- glyph_metrics_t gm = boundingBox(glyph);
-
-// printf(" -> for glyph %4x\n", glyph);
-
- int gx = gm.x.toInt();
- int gy = gm.y.toInt();
- int iw = gm.width.toInt();
- int ih = gm.height.toInt();
-
- if (iw <= 0 || ih <= 0)
- return 0;
-
- bool has_transformation = t.type() > QTransform::TxTranslate;
-
-#ifndef Q_OS_WINCE
- unsigned int options = ttf ? ETO_GLYPH_INDEX : 0;
- XFORM xform;
-
- if (has_transformation) {
- xform.eM11 = FLOAT(t.m11());
- xform.eM12 = FLOAT(t.m12());
- xform.eM21 = FLOAT(t.m21());
- xform.eM22 = FLOAT(t.m22());
- xform.eDx = margin;
- xform.eDy = margin;
-
- const HDC hdc = m_fontEngineData->hdc;
-
- SetGraphicsMode(hdc, GM_ADVANCED);
- SetWorldTransform(hdc, &xform);
- HGDIOBJ old_font = SelectObject(hdc, font);
-
- const UINT ggo_options = GGO_METRICS | (ttf ? GGO_GLYPH_INDEX : 0);
- GLYPHMETRICS tgm;
- MAT2 mat;
- memset(&mat, 0, sizeof(mat));
- mat.eM11.value = mat.eM22.value = 1;
-
- const DWORD result = GetGlyphOutline(hdc, glyph, ggo_options, &tgm, 0, 0, &mat);
-
- XFORM identity = {1, 0, 0, 1, 0, 0};
- SetWorldTransform(hdc, &identity);
- SetGraphicsMode(hdc, GM_COMPATIBLE);
- SelectObject(hdc, old_font);
-
- if (result == GDI_ERROR) {
- const int errorCode = int(GetLastError());
- qErrnoWarning(errorCode, "QWinFontEngine: unable to query transformed glyph metrics (GetGlyphOutline() failed, error %d)...", errorCode);
- return 0;
- }
-
- iw = int(tgm.gmBlackBoxX);
- ih = int(tgm.gmBlackBoxY);
-
- xform.eDx -= tgm.gmptGlyphOrigin.x;
- xform.eDy += tgm.gmptGlyphOrigin.y;
- }
-#else // else wince
- unsigned int options = 0;
- if (has_transformation) {
- qWarning() << "QWindowsFontEngine is unable to apply transformations other than translations for fonts on Windows CE."
- << "If you need them anyway, start your application with -platform windows:fontengine=freetype.";
- }
-#endif // wince
-
- // The padding here needs to be kept in sync with the values in alphaMapBoundingBox.
- QWindowsNativeImage *ni = new QWindowsNativeImage(iw + 2 * margin,
- ih + 2 * margin,
- QWindowsNativeImage::systemFormat());
-
- /*If cleartype is enabled we use the standard system format even on Windows CE
- and not the special textbuffer format we have to use if cleartype is disabled*/
-
- ni->image().fill(0xffffffff);
-
- HDC hdc = ni->hdc();
-
- SelectObject(hdc, GetStockObject(NULL_BRUSH));
- SelectObject(hdc, GetStockObject(BLACK_PEN));
- SetTextColor(hdc, RGB(0,0,0));
- SetBkMode(hdc, TRANSPARENT);
- SetTextAlign(hdc, TA_BASELINE);
-
- HGDIOBJ old_font = SelectObject(hdc, font);
-
-#ifndef Q_OS_WINCE
- if (has_transformation) {
- SetGraphicsMode(hdc, GM_ADVANCED);
- SetWorldTransform(hdc, &xform);
- ExtTextOut(hdc, 0, 0, options, 0, reinterpret_cast<LPCWSTR>(&glyph), 1, 0);
- } else
-#endif // !Q_OS_WINCE
- {
- ExtTextOut(hdc, -gx + margin, -gy + margin, options, 0, reinterpret_cast<LPCWSTR>(&glyph), 1, 0);
- }
-
- SelectObject(hdc, old_font);
- return ni;
-}
-
-glyph_metrics_t QWindowsFontEngine::alphaMapBoundingBox(glyph_t glyph, QFixed, const QTransform &matrix, GlyphFormat format)
-{
- int margin = 0;
- if (format == QFontEngine::Format_A32 || format == QFontEngine::Format_ARGB)
- margin = glyphMargin(QFontEngine::Format_A32);
- glyph_metrics_t gm = boundingBox(glyph, matrix);
- gm.width += margin * 2;
- gm.height += margin * 2;
- return gm;
-}
-
-QImage QWindowsFontEngine::alphaMapForGlyph(glyph_t glyph, const QTransform &xform)
-{
- HFONT font = hfont;
-
- bool clearTypeTemporarilyDisabled = (m_fontEngineData->clearTypeEnabled && m_logfont.lfQuality != NONANTIALIASED_QUALITY);
- if (clearTypeTemporarilyDisabled) {
- LOGFONT lf = m_logfont;
- lf.lfQuality = ANTIALIASED_QUALITY;
- font = CreateFontIndirect(&lf);
- }
- QImage::Format mask_format = QWindowsNativeImage::systemFormat();
- mask_format = QImage::Format_RGB32;
-
- const QWindowsNativeImage *mask = drawGDIGlyph(font, glyph, 0, xform, mask_format);
- if (mask == 0) {
- if (m_fontEngineData->clearTypeEnabled)
- DeleteObject(font);
- return QImage();
- }
-
- QImage alphaMap(mask->width(), mask->height(), QImage::Format_Alpha8);
-
-
- // Copy data... Cannot use QPainter here as GDI has messed up the
- // Alpha channel of the ni.image pixels...
- for (int y=0; y<mask->height(); ++y) {
- uchar *dest = alphaMap.scanLine(y);
- if (mask->image().format() == QImage::Format_RGB16) {
- const qint16 *src = reinterpret_cast<const qint16 *>(mask->image().constScanLine(y));
- for (int x=0; x<mask->width(); ++x)
- dest[x] = 255 - qGray(src[x]);
- } else {
- const uint *src = reinterpret_cast<const uint *>(mask->image().constScanLine(y));
- for (int x=0; x<mask->width(); ++x) {
- if (QWindowsNativeImage::systemFormat() == QImage::Format_RGB16)
- dest[x] = 255 - qGray(src[x]);
- else
- dest[x] = 255 - (m_fontEngineData->pow_gamma[qGray(src[x])] * 255. / 2047.);
- }
- }
- }
-
- // Cleanup...
- delete mask;
- if (clearTypeTemporarilyDisabled) {
- DeleteObject(font);
- }
-
- return alphaMap;
-}
-
-#define SPI_GETFONTSMOOTHINGCONTRAST 0x200C
-#define SPI_SETFONTSMOOTHINGCONTRAST 0x200D
-
-QImage QWindowsFontEngine::alphaRGBMapForGlyph(glyph_t glyph, QFixed, const QTransform &t)
-{
- HFONT font = hfont;
-
- UINT contrast;
- SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &contrast, 0);
- SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, reinterpret_cast<void *>(quintptr(1000)), 0);
-
- int margin = glyphMargin(QFontEngine::Format_A32);
- QWindowsNativeImage *mask = drawGDIGlyph(font, glyph, margin, t, QImage::Format_RGB32);
- SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, reinterpret_cast<void *>(quintptr(contrast)), 0);
-
- if (mask == 0)
- return QImage();
-
- // Gracefully handle the odd case when the display is 16-bit
- const QImage source = mask->image().depth() == 32
- ? mask->image()
- : mask->image().convertToFormat(QImage::Format_RGB32);
-
- QImage rgbMask(mask->width(), mask->height(), QImage::Format_RGB32);
- for (int y=0; y<mask->height(); ++y) {
- uint *dest = (uint *) rgbMask.scanLine(y);
- const uint *src = reinterpret_cast<const uint *>(source.constScanLine(y));
- for (int x=0; x<mask->width(); ++x) {
- dest[x] = 0xffffffff - (0x00ffffff & src[x]);
- }
- }
-
- delete mask;
-
- return rgbMask;
-}
-
-QFontEngine *QWindowsFontEngine::cloneWithSize(qreal pixelSize) const
-{
- QFontDef request = fontDef;
- QString actualFontName = request.family;
- if (!uniqueFamilyName.isEmpty())
- request.family = uniqueFamilyName;
- request.pixelSize = pixelSize;
-
- QFontEngine *fontEngine =
- QWindowsFontDatabase::createEngine(request,
- QWindowsContext::instance()->defaultDPI(),
- m_fontEngineData);
- if (fontEngine) {
- fontEngine->fontDef.family = actualFontName;
- if (!uniqueFamilyName.isEmpty()) {
- static_cast<QWindowsFontEngine *>(fontEngine)->setUniqueFamilyName(uniqueFamilyName);
- QPlatformFontDatabase *pfdb = QWindowsIntegration::instance()->fontDatabase();
- static_cast<QWindowsFontDatabase *>(pfdb)->refUniqueFont(uniqueFamilyName);
- }
- }
- return fontEngine;
-}
-
-Qt::HANDLE QWindowsFontEngine::handle() const
-{
- return hfont;
-}
-
-void QWindowsFontEngine::initFontInfo(const QFontDef &request,
- int dpi)
-{
- fontDef = request; // most settings are equal
- HDC dc = m_fontEngineData->hdc;
- SelectObject(dc, hfont);
- wchar_t n[64];
- GetTextFace(dc, 64, n);
- fontDef.family = QString::fromWCharArray(n);
- fontDef.fixedPitch = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH);
- if (fontDef.pointSize < 0) {
- fontDef.pointSize = fontDef.pixelSize * 72. / dpi;
- } else if (fontDef.pixelSize == -1) {
- fontDef.pixelSize = qRound(fontDef.pointSize * dpi / 72.);
- }
-}
-
-/*!
- \class QWindowsMultiFontEngine
- \brief Standard Windows Multi font engine.
- \internal
- \ingroup qt-lighthouse-win
-
- "Merges" several font engines that have gaps in the
- supported writing systems.
-
- Will probably be superseded by a common Free Type font engine in Qt 5.X.
-*/
-QWindowsMultiFontEngine::QWindowsMultiFontEngine(QFontEngine *fe, int script)
- : QFontEngineMulti(fe, script)
-{
-}
-
-QFontEngine *QWindowsMultiFontEngine::loadEngine(int at)
-{
- QFontEngine *fontEngine = engine(0);
- QSharedPointer<QWindowsFontEngineData> data;
- LOGFONT lf;
-
-#ifndef QT_NO_DIRECTWRITE
- if (fontEngine->type() == QFontEngine::DirectWrite) {
- QWindowsFontEngineDirectWrite *fe = static_cast<QWindowsFontEngineDirectWrite *>(fontEngine);
- lf = QWindowsFontDatabase::fontDefToLOGFONT(fe->fontDef);
-
- data = fe->fontEngineData();
- } else
-#endif
- {
- QWindowsFontEngine *fe = static_cast<QWindowsFontEngine*>(fontEngine);
- lf = fe->m_logfont;
-
- data = fe->fontEngineData();
- }
-
- const QString fam = fallbackFamilyAt(at - 1);
- const int faceNameLength = qMin(fam.length(), LF_FACESIZE - 1);
- memcpy(lf.lfFaceName, fam.utf16(), faceNameLength * sizeof(wchar_t));
- lf.lfFaceName[faceNameLength] = 0;
-
-#ifndef QT_NO_DIRECTWRITE
- if (fontEngine->type() == QFontEngine::DirectWrite) {
- const QString nameSubstitute = QWindowsFontEngineDirectWrite::fontNameSubstitute(fam);
- if (nameSubstitute != fam) {
- const int nameSubstituteLength = qMin(nameSubstitute.length(), LF_FACESIZE - 1);
- memcpy(lf.lfFaceName, nameSubstitute.utf16(), nameSubstituteLength * sizeof(wchar_t));
- lf.lfFaceName[nameSubstituteLength] = 0;
- }
-
- IDWriteFont *directWriteFont = 0;
- HRESULT hr = data->directWriteGdiInterop->CreateFontFromLOGFONT(&lf, &directWriteFont);
- if (FAILED(hr)) {
- qErrnoWarning("%s: CreateFontFromLOGFONT failed", __FUNCTION__);
- } else {
- Q_ASSERT(directWriteFont);
- IDWriteFontFace *directWriteFontFace = NULL;
- HRESULT hr = directWriteFont->CreateFontFace(&directWriteFontFace);
- if (SUCCEEDED(hr)) {
- Q_ASSERT(directWriteFontFace);
- QWindowsFontEngineDirectWrite *fedw = new QWindowsFontEngineDirectWrite(directWriteFontFace,
- fontEngine->fontDef.pixelSize,
- data);
- fedw->fontDef.weight = fontEngine->fontDef.weight;
- if (fontEngine->fontDef.style > QFont::StyleNormal)
- fedw->fontDef.style = fontEngine->fontDef.style;
- fedw->fontDef.family = fam;
- fedw->fontDef.hintingPreference = fontEngine->fontDef.hintingPreference;
- return fedw;
- } else {
- qErrnoWarning("%s: CreateFontFace failed", __FUNCTION__);
- }
- }
- }
-#endif
-
- // Get here if original font is not DirectWrite or DirectWrite creation failed for some
- // reason
-
- QFontEngine *fe = new QWindowsFontEngine(fam, lf, data);
- fe->fontDef.weight = fontEngine->fontDef.weight;
- if (fontEngine->fontDef.style > QFont::StyleNormal)
- fe->fontDef.style = fontEngine->fontDef.style;
- fe->fontDef.family = fam;
- fe->fontDef.hintingPreference = fontEngine->fontDef.hintingPreference;
- return fe;
-}
-
-bool QWindowsFontEngine::supportsTransformation(const QTransform &transform) const
-{
- // Support all transformations for ttf files, and translations for raster fonts
- return ttf || transform.type() <= QTransform::TxTranslate;
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/plugins/platforms/windows/qwindowsfontengine.h b/src/plugins/platforms/windows/qwindowsfontengine.h
deleted file mode 100644
index d4d98422a1..0000000000
--- a/src/plugins/platforms/windows/qwindowsfontengine.h
+++ /dev/null
@@ -1,186 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtGui module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWINDOWSFONTENGINE_H
-#define QWINDOWSFONTENGINE_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtGui/private/qfontengine_p.h>
-
-#include <QtGui/QImage>
-#include <QtCore/QSharedPointer>
-#include <QtCore/QMetaType>
-
-#include "qtwindows_additional.h"
-
-QT_BEGIN_NAMESPACE
-
-class QWindowsNativeImage;
-class QWindowsFontEngineData;
-
-class QWindowsFontEngine : public QFontEngine
-{
- friend class QWindowsMultiFontEngine;
-
-public:
- QWindowsFontEngine(const QString &name, LOGFONT lf,
- const QSharedPointer<QWindowsFontEngineData> &fontEngineData);
-
- ~QWindowsFontEngine();
- void initFontInfo(const QFontDef &request,
- int dpi);
-
- QFixed lineThickness() const Q_DECL_OVERRIDE;
- Properties properties() const Q_DECL_OVERRIDE;
- void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics) Q_DECL_OVERRIDE;
- FaceId faceId() const Q_DECL_OVERRIDE;
- bool getSfntTableData(uint tag, uchar *buffer, uint *length) const Q_DECL_OVERRIDE;
- int synthesized() const Q_DECL_OVERRIDE;
- QFixed emSquareSize() const Q_DECL_OVERRIDE;
-
- glyph_t glyphIndex(uint ucs4) const Q_DECL_OVERRIDE;
- bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, ShaperFlags flags) const Q_DECL_OVERRIDE;
- void recalcAdvances(QGlyphLayout *glyphs, ShaperFlags) const Q_DECL_OVERRIDE;
-
- void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
- virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
- QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
-
- HGDIOBJ selectDesignFont() const;
-
- glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) Q_DECL_OVERRIDE;
- glyph_metrics_t boundingBox(glyph_t g) Q_DECL_OVERRIDE { return boundingBox(g, QTransform()); }
- glyph_metrics_t boundingBox(glyph_t g, const QTransform &t) Q_DECL_OVERRIDE;
-
-
- QFixed ascent() const Q_DECL_OVERRIDE;
- QFixed descent() const Q_DECL_OVERRIDE;
- QFixed leading() const Q_DECL_OVERRIDE;
- QFixed xHeight() const Q_DECL_OVERRIDE;
- QFixed averageCharWidth() const Q_DECL_OVERRIDE;
- qreal maxCharWidth() const Q_DECL_OVERRIDE;
- qreal minLeftBearing() const Q_DECL_OVERRIDE;
- qreal minRightBearing() const Q_DECL_OVERRIDE;
-
- QImage alphaMapForGlyph(glyph_t t) Q_DECL_OVERRIDE { return alphaMapForGlyph(t, QTransform()); }
- QImage alphaMapForGlyph(glyph_t, const QTransform &xform) Q_DECL_OVERRIDE;
- QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, const QTransform &xform) Q_DECL_OVERRIDE;
- glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, QFixed, const QTransform &matrix, GlyphFormat) Q_DECL_OVERRIDE;
-
- QFontEngine *cloneWithSize(qreal pixelSize) const Q_DECL_OVERRIDE;
- Qt::HANDLE handle() const Q_DECL_OVERRIDE;
- bool supportsTransformation(const QTransform &transform) const Q_DECL_OVERRIDE;
-
-#ifndef Q_CC_MINGW
- void getGlyphBearings(glyph_t glyph, qreal *leftBearing = 0, qreal *rightBearing = 0) Q_DECL_OVERRIDE;
-#endif
-
- bool hasUnreliableGlyphOutline() const Q_DECL_OVERRIDE;
-
- int getGlyphIndexes(const QChar *ch, int numChars, QGlyphLayout *glyphs) const;
- void getCMap();
-
- bool getOutlineMetrics(glyph_t glyph, const QTransform &t, glyph_metrics_t *metrics) const;
-
- const QSharedPointer<QWindowsFontEngineData> &fontEngineData() const { return m_fontEngineData; }
-
- void setUniqueFamilyName(const QString &newName) { uniqueFamilyName = newName; }
-
-private:
- QWindowsNativeImage *drawGDIGlyph(HFONT font, glyph_t, int margin, const QTransform &xform,
- QImage::Format mask_format);
- bool hasCFFTable() const;
- bool hasCMapTable() const;
- bool hasGlyfTable() const;
- bool hasEbdtTable() const;
-
- const QSharedPointer<QWindowsFontEngineData> m_fontEngineData;
-
- const QString _name;
- QString uniqueFamilyName;
- HFONT hfont;
- const LOGFONT m_logfont;
- uint ttf : 1;
- uint hasOutline : 1;
- uint hasUnreliableOutline : 1;
- uint cffTable : 1;
- TEXTMETRIC tm;
- const unsigned char *cmap;
- int cmapSize;
- QByteArray cmapTable;
- mutable qreal lbearing;
- mutable qreal rbearing;
- QFixed designToDevice;
- int unitsPerEm;
- QFixed x_height;
- FaceId _faceId;
-
- mutable int synthesized_flags;
- mutable QFixed lineWidth;
- mutable unsigned char *widthCache;
- mutable uint widthCacheSize;
- mutable QFixed *designAdvances;
- mutable int designAdvancesSize;
-};
-
-class QWindowsMultiFontEngine : public QFontEngineMulti
-{
-public:
- explicit QWindowsMultiFontEngine(QFontEngine *fe, int script);
-
- QFontEngine *loadEngine(int at) Q_DECL_OVERRIDE;
-};
-
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(HFONT)
-Q_DECLARE_METATYPE(LOGFONT)
-
-#endif // QWINDOWSFONTENGINE_H
-
diff --git a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp
deleted file mode 100644
index 0fdd4615f6..0000000000
--- a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp
+++ /dev/null
@@ -1,891 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtGui module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QT_NO_DIRECTWRITE
-
-#include "qwindowsfontenginedirectwrite.h"
-#include "qwindowsfontdatabase.h"
-#include "qwindowscontext.h"
-
-#include <QtCore/QSettings>
-#include <QtCore/QtEndian>
-#include <QtCore/QVarLengthArray>
-#include <private/qstringiterator_p.h>
-#include <QtCore/private/qsystemlibrary_p.h>
-#include <QtGui/private/qguiapplication_p.h>
-#include <qpa/qplatformintegration.h>
-
-#if defined(QT_USE_DIRECTWRITE2)
-# include <dwrite_2.h>
-#else
-# include <dwrite.h>
-#endif
-
-#include <d2d1.h>
-
-QT_BEGIN_NAMESPACE
-
-// Convert from design units to logical pixels
-#define DESIGN_TO_LOGICAL(DESIGN_UNIT_VALUE) \
- QFixed::fromReal((qreal(DESIGN_UNIT_VALUE) / qreal(m_unitsPerEm)) * fontDef.pixelSize)
-
-namespace {
-
- class GeometrySink: public IDWriteGeometrySink
- {
- public:
- GeometrySink(QPainterPath *path)
- : m_refCount(0), m_path(path)
- {
- Q_ASSERT(m_path != 0);
- }
- virtual ~GeometrySink()
- {
- }
-
- IFACEMETHOD_(void, AddBeziers)(const D2D1_BEZIER_SEGMENT *beziers, UINT bezierCount);
- IFACEMETHOD_(void, AddLines)(const D2D1_POINT_2F *points, UINT pointCount);
- IFACEMETHOD_(void, BeginFigure)(D2D1_POINT_2F startPoint, D2D1_FIGURE_BEGIN figureBegin);
- IFACEMETHOD(Close)();
- IFACEMETHOD_(void, EndFigure)(D2D1_FIGURE_END figureEnd);
- IFACEMETHOD_(void, SetFillMode)(D2D1_FILL_MODE fillMode);
- IFACEMETHOD_(void, SetSegmentFlags)(D2D1_PATH_SEGMENT vertexFlags);
-
- IFACEMETHOD_(unsigned long, AddRef)();
- IFACEMETHOD_(unsigned long, Release)();
- IFACEMETHOD(QueryInterface)(IID const &riid, void **ppvObject);
-
- private:
- inline static QPointF fromD2D1_POINT_2F(const D2D1_POINT_2F &inp)
- {
- return QPointF(inp.x, inp.y);
- }
-
- unsigned long m_refCount;
- QPointF m_startPoint;
- QPainterPath *m_path;
- };
-
- void GeometrySink::AddBeziers(const D2D1_BEZIER_SEGMENT *beziers,
- UINT bezierCount)
- {
- for (uint i=0; i<bezierCount; ++i) {
- QPointF c1 = fromD2D1_POINT_2F(beziers[i].point1);
- QPointF c2 = fromD2D1_POINT_2F(beziers[i].point2);
- QPointF p2 = fromD2D1_POINT_2F(beziers[i].point3);
-
- m_path->cubicTo(c1, c2, p2);
- }
- }
-
- void GeometrySink::AddLines(const D2D1_POINT_2F *points, UINT pointsCount)
- {
- for (uint i=0; i<pointsCount; ++i)
- m_path->lineTo(fromD2D1_POINT_2F(points[i]));
- }
-
- void GeometrySink::BeginFigure(D2D1_POINT_2F startPoint,
- D2D1_FIGURE_BEGIN /*figureBegin*/)
- {
- m_startPoint = fromD2D1_POINT_2F(startPoint);
- m_path->moveTo(m_startPoint);
- }
-
- IFACEMETHODIMP GeometrySink::Close()
- {
- return E_NOTIMPL;
- }
-
- void GeometrySink::EndFigure(D2D1_FIGURE_END figureEnd)
- {
- if (figureEnd == D2D1_FIGURE_END_CLOSED)
- m_path->closeSubpath();
- }
-
- void GeometrySink::SetFillMode(D2D1_FILL_MODE fillMode)
- {
- m_path->setFillRule(fillMode == D2D1_FILL_MODE_ALTERNATE
- ? Qt::OddEvenFill
- : Qt::WindingFill);
- }
-
- void GeometrySink::SetSegmentFlags(D2D1_PATH_SEGMENT /*vertexFlags*/)
- {
- /* Not implemented */
- }
-
- IFACEMETHODIMP_(unsigned long) GeometrySink::AddRef()
- {
- return InterlockedIncrement(&m_refCount);
- }
-
- IFACEMETHODIMP_(unsigned long) GeometrySink::Release()
- {
- unsigned long newCount = InterlockedDecrement(&m_refCount);
- if (newCount == 0)
- {
- delete this;
- return 0;
- }
-
- return newCount;
- }
-
- IFACEMETHODIMP GeometrySink::QueryInterface(IID const &riid, void **ppvObject)
- {
- if (__uuidof(IDWriteGeometrySink) == riid) {
- *ppvObject = this;
- } else if (__uuidof(IUnknown) == riid) {
- *ppvObject = this;
- } else {
- *ppvObject = NULL;
- return E_FAIL;
- }
-
- AddRef();
- return S_OK;
- }
-
-}
-
-/*!
- \class QWindowsFontEngineDirectWrite
- \brief Windows font engine using Direct Write.
- \internal
- \ingroup qt-lighthouse-win
-
- Font engine for subpixel positioned text on Windows Vista
- (with platform update) and Windows 7. If selected during
- configuration, the engine will be selected only when the hinting
- preference of a font is set to None or Vertical hinting. The font
- database uses most of the same logic but creates a direct write
- font based on the LOGFONT rather than a GDI handle.
-
- Will probably be superseded by a common Free Type font engine in Qt 5.X.
-*/
-
-QWindowsFontEngineDirectWrite::QWindowsFontEngineDirectWrite(IDWriteFontFace *directWriteFontFace,
- qreal pixelSize,
- const QSharedPointer<QWindowsFontEngineData> &d)
- : QFontEngine(DirectWrite)
- , m_fontEngineData(d)
- , m_directWriteFontFace(directWriteFontFace)
- , m_directWriteBitmapRenderTarget(0)
- , m_lineThickness(-1)
- , m_unitsPerEm(-1)
- , m_ascent(-1)
- , m_descent(-1)
- , m_xHeight(-1)
- , m_lineGap(-1)
-{
- qCDebug(lcQpaFonts) << __FUNCTION__ << pixelSize;
-
- Q_ASSERT(m_directWriteFontFace);
-
- m_fontEngineData->directWriteFactory->AddRef();
- m_directWriteFontFace->AddRef();
-
- fontDef.pixelSize = pixelSize;
- collectMetrics();
- cache_cost = (m_ascent.toInt() + m_descent.toInt()) * m_xHeight.toInt() * 2000;
-}
-
-QWindowsFontEngineDirectWrite::~QWindowsFontEngineDirectWrite()
-{
- qCDebug(lcQpaFonts) << __FUNCTION__;
-
- m_fontEngineData->directWriteFactory->Release();
- m_directWriteFontFace->Release();
-
- if (m_directWriteBitmapRenderTarget != 0)
- m_directWriteBitmapRenderTarget->Release();
-
- if (!m_uniqueFamilyName.isEmpty()) {
- QPlatformFontDatabase *pfdb = QGuiApplicationPrivate::platformIntegration()->fontDatabase();
- static_cast<QWindowsFontDatabase *>(pfdb)->derefUniqueFont(m_uniqueFamilyName);
- }
-}
-
-void QWindowsFontEngineDirectWrite::collectMetrics()
-{
- DWRITE_FONT_METRICS metrics;
-
- m_directWriteFontFace->GetMetrics(&metrics);
- m_unitsPerEm = metrics.designUnitsPerEm;
-
- m_lineThickness = DESIGN_TO_LOGICAL(metrics.underlineThickness);
- m_ascent = DESIGN_TO_LOGICAL(metrics.ascent);
- m_descent = DESIGN_TO_LOGICAL(metrics.descent);
- m_xHeight = DESIGN_TO_LOGICAL(metrics.xHeight);
- m_lineGap = DESIGN_TO_LOGICAL(metrics.lineGap);
- m_underlinePosition = DESIGN_TO_LOGICAL(metrics.underlinePosition);
-}
-
-QFixed QWindowsFontEngineDirectWrite::underlinePosition() const
-{
- if (m_underlinePosition > 0)
- return m_underlinePosition;
- else
- return QFontEngine::underlinePosition();
-}
-
-QFixed QWindowsFontEngineDirectWrite::lineThickness() const
-{
- if (m_lineThickness > 0)
- return m_lineThickness;
- else
- return QFontEngine::lineThickness();
-}
-
-bool QWindowsFontEngineDirectWrite::getSfntTableData(uint tag, uchar *buffer, uint *length) const
-{
- bool ret = false;
-
- const void *tableData = 0;
- UINT32 tableSize;
- void *tableContext = 0;
- BOOL exists;
- HRESULT hr = m_directWriteFontFace->TryGetFontTable(qbswap<quint32>(tag),
- &tableData, &tableSize,
- &tableContext, &exists);
- if (SUCCEEDED(hr)) {
- if (exists) {
- ret = true;
- if (buffer && *length >= tableSize)
- memcpy(buffer, tableData, tableSize);
- *length = tableSize;
- Q_ASSERT(int(*length) > 0);
- }
- m_directWriteFontFace->ReleaseFontTable(tableContext);
- } else {
- qErrnoWarning("%s: TryGetFontTable failed", __FUNCTION__);
- }
-
- return ret;
-}
-
-QFixed QWindowsFontEngineDirectWrite::emSquareSize() const
-{
- if (m_unitsPerEm > 0)
- return m_unitsPerEm;
- else
- return QFontEngine::emSquareSize();
-}
-
-glyph_t QWindowsFontEngineDirectWrite::glyphIndex(uint ucs4) const
-{
- UINT16 glyphIndex;
-
- HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(&ucs4, 1, &glyphIndex);
- if (FAILED(hr)) {
- qErrnoWarning("%s: glyphIndex failed", __FUNCTION__);
- glyphIndex = 0;
- }
-
- return glyphIndex;
-}
-
-bool QWindowsFontEngineDirectWrite::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
- int *nglyphs, QFontEngine::ShaperFlags flags) const
-{
- Q_ASSERT(glyphs->numGlyphs >= *nglyphs);
- if (*nglyphs < len) {
- *nglyphs = len;
- return false;
- }
-
- QVarLengthArray<UINT32> codePoints(len);
- int actualLength = 0;
- QStringIterator it(str, str + len);
- while (it.hasNext())
- codePoints[actualLength++] = it.next();
-
- QVarLengthArray<UINT16> glyphIndices(actualLength);
- HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(codePoints.data(), actualLength,
- glyphIndices.data());
- if (FAILED(hr)) {
- qErrnoWarning("%s: GetGlyphIndicesW failed", __FUNCTION__);
- return false;
- }
-
- for (int i = 0; i < actualLength; ++i)
- glyphs->glyphs[i] = glyphIndices.at(i);
-
- *nglyphs = actualLength;
- glyphs->numGlyphs = actualLength;
-
- if (!(flags & GlyphIndicesOnly))
- recalcAdvances(glyphs, 0);
-
- return true;
-}
-
-void QWindowsFontEngineDirectWrite::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags) const
-{
- QVarLengthArray<UINT16> glyphIndices(glyphs->numGlyphs);
-
- // ### Caching?
- for(int i=0; i<glyphs->numGlyphs; i++)
- glyphIndices[i] = UINT16(glyphs->glyphs[i]);
-
- QVarLengthArray<DWRITE_GLYPH_METRICS> glyphMetrics(glyphIndices.size());
- HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(glyphIndices.data(),
- glyphIndices.size(),
- glyphMetrics.data());
- if (SUCCEEDED(hr)) {
- qreal stretch = fontDef.stretch / 100.0;
- for (int i = 0; i < glyphs->numGlyphs; ++i)
- glyphs->advances[i] = DESIGN_TO_LOGICAL(glyphMetrics[i].advanceWidth * stretch);
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- for (int i = 0; i < glyphs->numGlyphs; ++i)
- glyphs->advances[i] = glyphs->advances[i].round();
- }
- } else {
- qErrnoWarning("%s: GetDesignGlyphMetrics failed", __FUNCTION__);
- }
-}
-
-void QWindowsFontEngineDirectWrite::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
- QPainterPath *path, QTextItem::RenderFlags flags)
-{
- QVarLengthArray<UINT16> glyphIndices(nglyphs);
- QVarLengthArray<DWRITE_GLYPH_OFFSET> glyphOffsets(nglyphs);
- QVarLengthArray<FLOAT> glyphAdvances(nglyphs);
-
- for (int i=0; i<nglyphs; ++i) {
- glyphIndices[i] = glyphs[i];
- glyphOffsets[i].advanceOffset = positions[i].x.toReal();
- glyphOffsets[i].ascenderOffset = -positions[i].y.toReal();
- glyphAdvances[i] = 0.0;
- }
-
- GeometrySink geometrySink(path);
- HRESULT hr = m_directWriteFontFace->GetGlyphRunOutline(
- fontDef.pixelSize,
- glyphIndices.data(),
- glyphAdvances.data(),
- glyphOffsets.data(),
- nglyphs,
- false,
- flags & QTextItem::RightToLeft,
- &geometrySink
- );
-
- if (FAILED(hr))
- qErrnoWarning("%s: GetGlyphRunOutline failed", __FUNCTION__);
-}
-
-glyph_metrics_t QWindowsFontEngineDirectWrite::boundingBox(const QGlyphLayout &glyphs)
-{
- if (glyphs.numGlyphs == 0)
- return glyph_metrics_t();
-
- bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics;
-
- QFixed w = 0;
- for (int i = 0; i < glyphs.numGlyphs; ++i) {
- w += round ? glyphs.effectiveAdvance(i).round() : glyphs.effectiveAdvance(i);
-
- }
-
- return glyph_metrics_t(0, -m_ascent, w - lastRightBearing(glyphs), m_ascent + m_descent, w, 0);
-}
-
-glyph_metrics_t QWindowsFontEngineDirectWrite::boundingBox(glyph_t g)
-{
- UINT16 glyphIndex = g;
-
- DWRITE_GLYPH_METRICS glyphMetrics;
- HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(&glyphIndex, 1, &glyphMetrics);
- if (SUCCEEDED(hr)) {
- QFixed advanceWidth = DESIGN_TO_LOGICAL(glyphMetrics.advanceWidth);
- QFixed leftSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.leftSideBearing);
- QFixed rightSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.rightSideBearing);
- QFixed advanceHeight = DESIGN_TO_LOGICAL(glyphMetrics.advanceHeight);
- QFixed verticalOriginY = DESIGN_TO_LOGICAL(glyphMetrics.verticalOriginY);
- QFixed topSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.topSideBearing);
- QFixed bottomSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.bottomSideBearing);
-
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- advanceWidth = advanceWidth.round();
- advanceHeight = advanceHeight.round();
- }
-
- QFixed width = advanceWidth - leftSideBearing - rightSideBearing;
- QFixed height = advanceHeight - topSideBearing - bottomSideBearing;
- return glyph_metrics_t(leftSideBearing,
- -verticalOriginY + topSideBearing,
- width,
- height,
- advanceWidth,
- 0);
- } else {
- qErrnoWarning("%s: GetDesignGlyphMetrics failed", __FUNCTION__);
- }
-
- return glyph_metrics_t();
-}
-
-QFixed QWindowsFontEngineDirectWrite::ascent() const
-{
- return fontDef.styleStrategy & QFont::ForceIntegerMetrics
- ? m_ascent.round()
- : m_ascent;
-}
-
-QFixed QWindowsFontEngineDirectWrite::descent() const
-{
- return fontDef.styleStrategy & QFont::ForceIntegerMetrics
- ? m_descent.round()
- : m_descent;
-}
-
-QFixed QWindowsFontEngineDirectWrite::leading() const
-{
- return fontDef.styleStrategy & QFont::ForceIntegerMetrics
- ? m_lineGap.round()
- : m_lineGap;
-}
-
-QFixed QWindowsFontEngineDirectWrite::xHeight() const
-{
- return fontDef.styleStrategy & QFont::ForceIntegerMetrics
- ? m_xHeight.round()
- : m_xHeight;
-}
-
-qreal QWindowsFontEngineDirectWrite::maxCharWidth() const
-{
- // ###
- return 0;
-}
-
-QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t)
-{
- QImage im = alphaRGBMapForGlyph(glyph, subPixelPosition, t);
-
- QImage alphaMap(im.width(), im.height(), QImage::Format_Alpha8);
-
- for (int y=0; y<im.height(); ++y) {
- const uint *src = reinterpret_cast<const uint *>(im.constScanLine(y));
- uchar *dst = alphaMap.scanLine(y);
- for (int x=0; x<im.width(); ++x) {
- *dst = 255 - (m_fontEngineData->pow_gamma[qGray(0xffffffff - *src)] * 255. / 2047.);
- ++dst;
- ++src;
- }
- }
-
- return alphaMap;
-}
-
-QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition)
-{
- return alphaMapForGlyph(glyph, subPixelPosition, QTransform());
-}
-
-bool QWindowsFontEngineDirectWrite::supportsSubPixelPositions() const
-{
- return true;
-}
-
-QImage QWindowsFontEngineDirectWrite::imageForGlyph(glyph_t t,
- QFixed subPixelPosition,
- int margin,
- const QTransform &originalTransform)
-{
- UINT16 glyphIndex = t;
- FLOAT glyphAdvance = 0;
-
- DWRITE_GLYPH_OFFSET glyphOffset;
- glyphOffset.advanceOffset = 0;
- glyphOffset.ascenderOffset = 0;
-
- DWRITE_GLYPH_RUN glyphRun;
- glyphRun.fontFace = m_directWriteFontFace;
- glyphRun.fontEmSize = fontDef.pixelSize;
- glyphRun.glyphCount = 1;
- glyphRun.glyphIndices = &glyphIndex;
- glyphRun.glyphAdvances = &glyphAdvance;
- glyphRun.isSideways = false;
- glyphRun.bidiLevel = 0;
- glyphRun.glyphOffsets = &glyphOffset;
-
- QTransform xform = originalTransform;
- if (fontDef.stretch != 100)
- xform.scale(fontDef.stretch / 100.0, 1.0);
-
- DWRITE_MATRIX transform;
- transform.dx = subPixelPosition.toReal();
- transform.dy = 0;
- transform.m11 = xform.m11();
- transform.m12 = xform.m12();
- transform.m21 = xform.m21();
- transform.m22 = xform.m22();
-
- DWRITE_RENDERING_MODE renderMode =
- fontDef.hintingPreference == QFont::PreferNoHinting
- ? DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC
- : DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL;
-
- IDWriteGlyphRunAnalysis *glyphAnalysis = NULL;
- HRESULT hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis(
- &glyphRun,
- 1.0f,
- &transform,
- renderMode,
- DWRITE_MEASURING_MODE_NATURAL,
- 0.0, 0.0,
- &glyphAnalysis
- );
-
- if (SUCCEEDED(hr)) {
- RECT rect;
- glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect);
-
- QRect boundingRect = QRect(QPoint(rect.left - margin,
- rect.top - margin),
- QPoint(rect.right + margin,
- rect.bottom + margin));
-
-
- const int width = boundingRect.width() - 1; // -1 due to Qt's off-by-one definition of a QRect
- const int height = boundingRect.height() - 1;
-
- QImage image;
-#if defined(QT_USE_DIRECTWRITE2)
- HRESULT hr = DWRITE_E_NOCOLOR;
- IDWriteColorGlyphRunEnumerator *enumerator = 0;
- IDWriteFactory2 *factory2 = Q_NULLPTR;
- if (glyphFormat == QFontEngine::Format_ARGB
- && SUCCEEDED(m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2),
- reinterpret_cast<void **>(&factory2)))) {
- hr = factory2->TranslateColorGlyphRun(0.0f,
- 0.0f,
- &glyphRun,
- NULL,
- DWRITE_MEASURING_MODE_NATURAL,
- NULL,
- 0,
- &enumerator);
- image = QImage(width, height, QImage::Format_ARGB32_Premultiplied);
- image.fill(0);
- } else
-#endif
- {
- image = QImage(width, height, QImage::Format_RGB32);
- image.fill(0xffffffff);
- }
-
-#if defined(QT_USE_DIRECTWRITE2)
- BOOL ok = true;
- if (SUCCEEDED(hr)) {
- while (SUCCEEDED(hr) && ok) {
- const DWRITE_COLOR_GLYPH_RUN *colorGlyphRun = 0;
- hr = enumerator->GetCurrentRun(&colorGlyphRun);
- if (FAILED(hr)) { // No colored runs, only outline
- qErrnoWarning(hr, "%s: IDWriteColorGlyphRunEnumerator::GetCurrentRun failed", __FUNCTION__);
- break;
- }
-
- IDWriteGlyphRunAnalysis *colorGlyphsAnalysis = NULL;
- hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis(
- &colorGlyphRun->glyphRun,
- 1.0f,
- &transform,
- renderMode,
- DWRITE_MEASURING_MODE_NATURAL,
- 0.0, 0.0,
- &colorGlyphsAnalysis
- );
- if (FAILED(hr)) {
- qErrnoWarning(hr, "%s: CreateGlyphRunAnalysis failed for color run", __FUNCTION__);
- break;
- }
-
- float r = qBound(0.0f, colorGlyphRun->runColor.r, 1.0f);
- float g = qBound(0.0f, colorGlyphRun->runColor.g, 1.0f);
- float b = qBound(0.0f, colorGlyphRun->runColor.b, 1.0f);
- float a = qBound(0.0f, colorGlyphRun->runColor.a, 1.0f);
-
- if (!qFuzzyIsNull(a)) {
- renderGlyphRun(&image,
- r,
- g,
- b,
- a,
- colorGlyphsAnalysis,
- boundingRect);
- }
- colorGlyphsAnalysis->Release();
-
- hr = enumerator->MoveNext(&ok);
- if (FAILED(hr)) {
- qErrnoWarning(hr, "%s: IDWriteColorGlyphRunEnumerator::MoveNext failed", __FUNCTION__);
- break;
- }
- }
- } else
-#endif
- {
- renderGlyphRun(&image,
- 0.0,
- 0.0,
- 0.0,
- 1.0,
- glyphAnalysis,
- boundingRect);
- }
-
- glyphAnalysis->Release();
- return image;
- } else {
- qErrnoWarning(hr, "%s: CreateGlyphRunAnalysis failed", __FUNCTION__);
- return QImage();
- }
-}
-
-
-void QWindowsFontEngineDirectWrite::renderGlyphRun(QImage *destination,
- float r,
- float g,
- float b,
- float a,
- IDWriteGlyphRunAnalysis *glyphAnalysis,
- const QRect &boundingRect)
-{
- const int width = destination->width();
- const int height = destination->height();
-
- r *= 255.0;
- g *= 255.0;
- b *= 255.0;
-
- const int size = width * height * 3;
- if (size > 0) {
- RECT rect;
- rect.left = boundingRect.left();
- rect.top = boundingRect.top();
- rect.right = boundingRect.right();
- rect.bottom = boundingRect.bottom();
-
- QVarLengthArray<BYTE, 1024> alphaValueArray(size);
- BYTE *alphaValues = alphaValueArray.data();
- memset(alphaValues, 0, size);
-
- HRESULT hr = glyphAnalysis->CreateAlphaTexture(DWRITE_TEXTURE_CLEARTYPE_3x1,
- &rect,
- alphaValues,
- size);
- if (SUCCEEDED(hr)) {
- if (destination->hasAlphaChannel()) {
- for (int y = 0; y < height; ++y) {
- uint *dest = reinterpret_cast<uint *>(destination->scanLine(y));
- BYTE *src = alphaValues + width * 3 * y;
-
- for (int x = 0; x < width; ++x) {
- float redAlpha = a * *src++ / 255.0;
- float greenAlpha = a * *src++ / 255.0;
- float blueAlpha = a * *src++ / 255.0;
- float averageAlpha = (redAlpha + greenAlpha + blueAlpha) / 3.0;
-
- QRgb currentRgb = dest[x];
- dest[x] = qRgba(qRound(qRed(currentRgb) * (1.0 - averageAlpha) + averageAlpha * r),
- qRound(qGreen(currentRgb) * (1.0 - averageAlpha) + averageAlpha * g),
- qRound(qBlue(currentRgb) * (1.0 - averageAlpha) + averageAlpha * b),
- qRound(qAlpha(currentRgb) * (1.0 - averageAlpha) + averageAlpha * 255));
- }
- }
-
- } else {
- for (int y = 0; y < height; ++y) {
- uint *dest = reinterpret_cast<uint *>(destination->scanLine(y));
- BYTE *src = alphaValues + width * 3 * y;
-
- for (int x = 0; x < width; ++x) {
- dest[x] = *(src + 0) << 16
- | *(src + 1) << 8
- | *(src + 2);
-
- src += 3;
- }
- }
- }
- } else {
- qErrnoWarning("%s: CreateAlphaTexture failed", __FUNCTION__);
- }
- } else {
- glyphAnalysis->Release();
- qWarning("%s: Glyph has no bounds", __FUNCTION__);
- }
-}
-
-QImage QWindowsFontEngineDirectWrite::alphaRGBMapForGlyph(glyph_t t,
- QFixed subPixelPosition,
- const QTransform &xform)
-{
- QImage mask = imageForGlyph(t,
- subPixelPosition,
- glyphMargin(QFontEngine::Format_A32),
- xform);
-
- return mask.depth() == 32
- ? mask
- : mask.convertToFormat(QImage::Format_RGB32);
-}
-
-QFontEngine *QWindowsFontEngineDirectWrite::cloneWithSize(qreal pixelSize) const
-{
- QWindowsFontEngineDirectWrite *fontEngine = new QWindowsFontEngineDirectWrite(m_directWriteFontFace,
- pixelSize,
- m_fontEngineData);
-
- fontEngine->fontDef = fontDef;
- fontEngine->fontDef.pixelSize = pixelSize;
- if (!m_uniqueFamilyName.isEmpty()) {
- fontEngine->setUniqueFamilyName(m_uniqueFamilyName);
- QPlatformFontDatabase *pfdb = QGuiApplicationPrivate::platformIntegration()->fontDatabase();
- static_cast<QWindowsFontDatabase *>(pfdb)->refUniqueFont(m_uniqueFamilyName);
- }
-
- return fontEngine;
-}
-
-Qt::HANDLE QWindowsFontEngineDirectWrite::handle() const
-{
- return m_directWriteFontFace;
-}
-
-void QWindowsFontEngineDirectWrite::initFontInfo(const QFontDef &request,
- int dpi)
-{
- fontDef = request;
-
- if (fontDef.pointSize < 0)
- fontDef.pointSize = fontDef.pixelSize * 72. / dpi;
- else if (fontDef.pixelSize == -1)
- fontDef.pixelSize = qRound(fontDef.pointSize * dpi / 72.);
-}
-
-QString QWindowsFontEngineDirectWrite::fontNameSubstitute(const QString &familyName)
-{
- static const char keyC[] = "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\"
- "FontSubstitutes";
- return QSettings(QLatin1String(keyC), QSettings::NativeFormat).value(familyName, familyName).toString();
-}
-
-glyph_metrics_t QWindowsFontEngineDirectWrite::alphaMapBoundingBox(glyph_t glyph,
- QFixed subPixelPosition,
- const QTransform &originalTransform,
- GlyphFormat format)
-{
- Q_UNUSED(format);
-
- QTransform matrix = originalTransform;
- if (fontDef.stretch != 100)
- matrix.scale(fontDef.stretch / 100.0, 1.0);
-
- glyph_metrics_t bbox = QFontEngine::boundingBox(glyph, matrix); // To get transformed advance
-
- UINT16 glyphIndex = glyph;
- FLOAT glyphAdvance = 0;
-
- DWRITE_GLYPH_OFFSET glyphOffset;
- glyphOffset.advanceOffset = 0;
- glyphOffset.ascenderOffset = 0;
-
- DWRITE_GLYPH_RUN glyphRun;
- glyphRun.fontFace = m_directWriteFontFace;
- glyphRun.fontEmSize = fontDef.pixelSize;
- glyphRun.glyphCount = 1;
- glyphRun.glyphIndices = &glyphIndex;
- glyphRun.glyphAdvances = &glyphAdvance;
- glyphRun.isSideways = false;
- glyphRun.bidiLevel = 0;
- glyphRun.glyphOffsets = &glyphOffset;
-
- DWRITE_MATRIX transform;
- transform.dx = subPixelPosition.toReal();
- transform.dy = 0;
- transform.m11 = matrix.m11();
- transform.m12 = matrix.m12();
- transform.m21 = matrix.m21();
- transform.m22 = matrix.m22();
-
- DWRITE_RENDERING_MODE renderMode =
- fontDef.hintingPreference == QFont::PreferNoHinting
- ? DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC
- : DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL;
-
- IDWriteGlyphRunAnalysis *glyphAnalysis = NULL;
- HRESULT hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis(
- &glyphRun,
- 1.0f,
- &transform,
- renderMode,
- DWRITE_MEASURING_MODE_NATURAL,
- 0.0, 0.0,
- &glyphAnalysis
- );
-
- if (SUCCEEDED(hr)) {
- RECT rect;
- glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect);
- glyphAnalysis->Release();
-
- int margin = glyphMargin(QFontEngine::Format_A32);
-
- return glyph_metrics_t(rect.left,
- rect.top,
- rect.right - rect.left + margin * 2,
- rect.bottom - rect.top + margin * 2,
- bbox.xoff, bbox.yoff);
- } else {
- return glyph_metrics_t();
- }
-}
-
-QImage QWindowsFontEngineDirectWrite::bitmapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t)
-{
- return imageForGlyph(glyph, subPixelPosition, glyphMargin(QFontEngine::Format_A32), t);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DIRECTWRITE
diff --git a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h
deleted file mode 100644
index 37e511ce3e..0000000000
--- a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtGui module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWINDOWSFONTENGINEDIRECTWRITE_H
-#define QWINDOWSFONTENGINEDIRECTWRITE_H
-
-#include <QtCore/qglobal.h>
-
-#ifndef QT_NO_DIRECTWRITE
-
-#include <QtGui/private/qfontengine_p.h>
-#include <QtCore/QSharedPointer>
-
-struct IDWriteFont;
-struct IDWriteFontFace;
-struct IDWriteFactory;
-struct IDWriteBitmapRenderTarget;
-struct IDWriteGdiInterop;
-struct IDWriteGlyphRunAnalysis;
-
-QT_BEGIN_NAMESPACE
-
-class QWindowsFontEngineData;
-
-class QWindowsFontEngineDirectWrite : public QFontEngine
-{
-public:
- explicit QWindowsFontEngineDirectWrite(IDWriteFontFace *directWriteFontFace,
- qreal pixelSize,
- const QSharedPointer<QWindowsFontEngineData> &d);
- ~QWindowsFontEngineDirectWrite();
-
- void initFontInfo(const QFontDef &request, int dpi);
-
- QFixed lineThickness() const Q_DECL_OVERRIDE;
- QFixed underlinePosition() const Q_DECL_OVERRIDE;
- bool getSfntTableData(uint tag, uchar *buffer, uint *length) const Q_DECL_OVERRIDE;
- QFixed emSquareSize() const Q_DECL_OVERRIDE;
-
- glyph_t glyphIndex(uint ucs4) const Q_DECL_OVERRIDE;
- bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs,
- ShaperFlags flags) const Q_DECL_OVERRIDE;
- void recalcAdvances(QGlyphLayout *glyphs, ShaperFlags) const Q_DECL_OVERRIDE;
-
- void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
- QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
-
- glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) Q_DECL_OVERRIDE;
- glyph_metrics_t boundingBox(glyph_t g) Q_DECL_OVERRIDE;
- glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, QFixed,
- const QTransform &matrix, GlyphFormat) Q_DECL_OVERRIDE;
-
- QFixed ascent() const Q_DECL_OVERRIDE;
- QFixed descent() const Q_DECL_OVERRIDE;
- QFixed leading() const Q_DECL_OVERRIDE;
- QFixed xHeight() const Q_DECL_OVERRIDE;
- qreal maxCharWidth() const Q_DECL_OVERRIDE;
-
- bool supportsSubPixelPositions() const Q_DECL_OVERRIDE;
-
- QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition) Q_DECL_OVERRIDE;
- QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t) Q_DECL_OVERRIDE;
- QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, const QTransform &xform) Q_DECL_OVERRIDE;
- QImage bitmapForGlyph(glyph_t, QFixed subPixelPosition, const QTransform &t) Q_DECL_OVERRIDE;
-
- QFontEngine *cloneWithSize(qreal pixelSize) const Q_DECL_OVERRIDE;
- Qt::HANDLE handle() const Q_DECL_OVERRIDE;
-
- const QSharedPointer<QWindowsFontEngineData> &fontEngineData() const { return m_fontEngineData; }
-
- static QString fontNameSubstitute(const QString &familyName);
-
- IDWriteFontFace *directWriteFontFace() const { return m_directWriteFontFace; }
-
- void setUniqueFamilyName(const QString &newName) { m_uniqueFamilyName = newName; }
-
-private:
- QImage imageForGlyph(glyph_t t, QFixed subPixelPosition, int margin, const QTransform &xform);
- void collectMetrics();
- void renderGlyphRun(QImage *destination, float r, float g, float b, float a, IDWriteGlyphRunAnalysis *glyphAnalysis, const QRect &boundingRect);
-
- const QSharedPointer<QWindowsFontEngineData> m_fontEngineData;
-
- IDWriteFontFace *m_directWriteFontFace;
- IDWriteBitmapRenderTarget *m_directWriteBitmapRenderTarget;
-
- QFixed m_lineThickness;
- QFixed m_underlinePosition;
- int m_unitsPerEm;
- QFixed m_ascent;
- QFixed m_descent;
- QFixed m_xHeight;
- QFixed m_lineGap;
- FaceId m_faceId;
- QString m_uniqueFamilyName;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DIRECTWRITE
-
-#endif // QWINDOWSFONTENGINEDIRECTWRITE_H
diff --git a/src/plugins/platforms/windows/qwindowsglcontext.cpp b/src/plugins/platforms/windows/qwindowsglcontext.cpp
index 0a2d30319e..c1eb664324 100644
--- a/src/plugins/platforms/windows/qwindowsglcontext.cpp
+++ b/src/plugins/platforms/windows/qwindowsglcontext.cpp
@@ -149,15 +149,9 @@ QT_BEGIN_NAMESPACE
QWindowsOpengl32DLL QOpenGLStaticContext::opengl32;
-PROC QWindowsOpengl32DLL::resolve(const char *name)
+FARPROC QWindowsOpengl32DLL::resolve(const char *name)
{
-#ifndef Q_OS_WINCE
- PROC proc = m_lib ? ::GetProcAddress(m_lib, name) : 0;
-#else
- PROC proc = m_lib ? ::GetProcAddress(m_lib, (const wchar_t *) QString::fromLatin1(name).utf16()) : 0;
-#endif
-
- return proc;
+ return m_lib ? ::GetProcAddress(m_lib, name) : nullptr;
}
bool QWindowsOpengl32DLL::init(bool softwareRendering)
diff --git a/src/plugins/platforms/windows/qwindowsglcontext.h b/src/plugins/platforms/windows/qwindowsglcontext.h
index 2944ab7192..4c804a612e 100644
--- a/src/plugins/platforms/windows/qwindowsglcontext.h
+++ b/src/plugins/platforms/windows/qwindowsglcontext.h
@@ -40,7 +40,7 @@
#ifndef QWINDOWSGLCONTEXT_H
#define QWINDOWSGLCONTEXT_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include "qwindowsopenglcontext.h"
#include <QtGui/QOpenGLContext>
@@ -122,7 +122,7 @@ struct QWindowsOpengl32DLL
void (APIENTRY * glGetIntegerv)(GLenum pname, GLint* params);
const GLubyte * (APIENTRY * glGetString)(GLenum name);
- PROC resolve(const char *name);
+ FARPROC resolve(const char *name);
private:
HMODULE m_lib;
bool m_nonOpengl32;
diff --git a/src/plugins/platforms/windows/qwindowsinputcontext.cpp b/src/plugins/platforms/windows/qwindowsinputcontext.cpp
index 501b956a68..8adbd494c4 100644
--- a/src/plugins/platforms/windows/qwindowsinputcontext.cpp
+++ b/src/plugins/platforms/windows/qwindowsinputcontext.cpp
@@ -190,11 +190,7 @@ bool QWindowsInputContext::hasCapability(Capability capability) const
{
switch (capability) {
case QPlatformInputContext::HiddenTextCapability:
-#ifndef Q_OS_WINCE
return false; // QTBUG-40691, do not show IME on desktop for password entry fields.
-#else
- break; // Windows CE: Show software keyboard.
-#endif
default:
break;
}
diff --git a/src/plugins/platforms/windows/qwindowsinputcontext.h b/src/plugins/platforms/windows/qwindowsinputcontext.h
index 4c08fa0ef2..a7fa2c4f94 100644
--- a/src/plugins/platforms/windows/qwindowsinputcontext.h
+++ b/src/plugins/platforms/windows/qwindowsinputcontext.h
@@ -40,7 +40,7 @@
#ifndef QWINDOWSINPUTCONTEXT_H
#define QWINDOWSINPUTCONTEXT_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/QLocale>
#include <QtCore/QPointer>
diff --git a/src/plugins/platforms/windows/qwindowsintegration.cpp b/src/plugins/platforms/windows/qwindowsintegration.cpp
index b6d2c16f89..004b03d9a9 100644
--- a/src/plugins/platforms/windows/qwindowsintegration.cpp
+++ b/src/plugins/platforms/windows/qwindowsintegration.cpp
@@ -47,9 +47,8 @@
#include "qwindowstheme.h"
#include "qwindowsservices.h"
#ifndef QT_NO_FREETYPE
-# include "qwindowsfontdatabase_ft.h"
+# include <QtFontDatabaseSupport/private/qwindowsfontdatabase_ft_p.h>
#endif
-#include "qwindowsfontdatabase.h"
#ifndef QT_NO_CLIPBOARD
# include "qwindowsclipboard.h"
# ifndef QT_NO_DRAGANDDROP
@@ -64,7 +63,7 @@
#include <qpa/qplatformnativeinterface.h>
#include <qpa/qwindowsysteminterface.h>
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#ifndef QT_NO_SESSIONMANAGER
# include "qwindowssessionmanager.h"
#endif
#include <QtGui/qtouchdevice.h>
@@ -72,7 +71,7 @@
#include <QtGui/private/qhighdpiscaling_p.h>
#include <QtGui/qpa/qplatforminputcontextfactory_p.h>
-#include <QtPlatformSupport/private/qwindowsguieventdispatcher_p.h>
+#include <QtEventDispatcherSupport/private/qwindowsguieventdispatcher_p.h>
#include <QtCore/QDebug>
#include <QtCore/QVariant>
@@ -102,7 +101,7 @@ QT_BEGIN_NAMESPACE
It should compile with:
\list
- \li Microsoft Visual Studio 2008 or later (using the Microsoft Windows SDK,
+ \li Microsoft Visual Studio 2013 or later (using the Microsoft Windows SDK,
(\c Q_CC_MSVC).
\li Stock \l{http://mingw.org/}{MinGW} (\c Q_CC_MINGW).
This version ships with headers that are missing a lot of WinAPI.
@@ -112,15 +111,8 @@ QT_BEGIN_NAMESPACE
(\c Q_CC_MINGW and \c __MINGW64_VERSION_MAJOR indicating the version).
MinGW-w64 provides more complete headers (compared to stock MinGW from mingw.org),
including a considerable part of the Windows SDK.
- \li Visual Studio 2008 for Windows Embedded (\c Q_OS_WINCE).
\endlist
- The file \c qtwindows_additional.h contains defines and declarations that
- are missing in MinGW. When encountering missing declarations, it should
- be added there so that \c #ifdefs for MinGW can be avoided. Similarly,
- \c qplatformfunctions_wince.h contains defines and declarations for
- Windows Embedded.
-
When using a function from the WinAPI, the minimum supported Windows version
and Windows Embedded support should be checked. If the function is not supported
on Windows XP or is not present in the MinGW-headers, it should be dynamically
@@ -219,9 +211,7 @@ QWindowsIntegrationPrivate::QWindowsIntegrationPrivate(const QStringList &paramL
: m_options(0)
, m_fontDatabase(0)
{
-#ifndef Q_OS_WINCE
Q_INIT_RESOURCE(openglblacklists);
-#endif
static bool dpiAwarenessSet = false;
int tabletAbsoluteRange = -1;
@@ -229,6 +219,7 @@ QWindowsIntegrationPrivate::QWindowsIntegrationPrivate(const QStringList &paramL
// are connected to Windows 8.1
QtWindows::ProcessDpiAwareness dpiAwareness = QtWindows::ProcessPerMonitorDpiAware;
m_options = parseOptions(paramList, &tabletAbsoluteRange, &dpiAwareness);
+ QWindowsFontDatabase::setFontOptions(m_options);
if (tabletAbsoluteRange >= 0)
m_context.setTabletAbsoluteRange(tabletAbsoluteRange);
if (!dpiAwarenessSet) { // Set only once in case of repeated instantiations of QGuiApplication.
@@ -483,46 +474,16 @@ QWindowsStaticOpenGLContext *QWindowsIntegration::staticOpenGLContext()
}
#endif // !QT_NO_OPENGL
-/* Workaround for QTBUG-24205: In 'Auto', pick the FreeType engine for
- * QML2 applications. */
-
-#ifdef Q_OS_WINCE
-// It's not easy to detect if we are running a QML application
-// Let's try to do so by checking if the Qt Quick module is loaded.
-inline bool isQMLApplication()
-{
- // check if the Qt Quick module is loaded
-#ifdef _DEBUG
- HMODULE handle = GetModuleHandle(L"Qt5Quick" QT_LIBINFIX L"d.dll");
-#else
- HMODULE handle = GetModuleHandle(L"Qt5Quick" QT_LIBINFIX L".dll");
-#endif
- return (handle != NULL);
-}
-#endif
-
QPlatformFontDatabase *QWindowsIntegration::fontDatabase() const
{
if (!d->m_fontDatabase) {
#ifdef QT_NO_FREETYPE
d->m_fontDatabase = new QWindowsFontDatabase();
#else // QT_NO_FREETYPE
- if (d->m_options & QWindowsIntegration::FontDatabaseFreeType) {
+ if (d->m_options & QWindowsIntegration::FontDatabaseFreeType)
d->m_fontDatabase = new QWindowsFontDatabaseFT;
- } else if (d->m_options & QWindowsIntegration::FontDatabaseNative){
- d->m_fontDatabase = new QWindowsFontDatabase;
- } else {
-#ifndef Q_OS_WINCE
+ else
d->m_fontDatabase = new QWindowsFontDatabase;
-#else
- if (isQMLApplication()) {
- qCDebug(lcQpaFonts) << "QML application detected, using FreeType rendering";
- d->m_fontDatabase = new QWindowsFontDatabaseFT;
- }
- else
- d->m_fontDatabase = new QWindowsFontDatabase;
-#endif
- }
#endif // QT_NO_FREETYPE
}
return d->m_fontDatabase;
@@ -610,7 +571,7 @@ unsigned QWindowsIntegration::options() const
return d->m_options;
}
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
QPlatformSessionManager *QWindowsIntegration::createPlatformSessionManager(const QString &id, const QString &key) const
{
return new QWindowsSessionManager(id, key);
diff --git a/src/plugins/platforms/windows/qwindowsintegration.h b/src/plugins/platforms/windows/qwindowsintegration.h
index 0c03274799..a668470993 100644
--- a/src/plugins/platforms/windows/qwindowsintegration.h
+++ b/src/plugins/platforms/windows/qwindowsintegration.h
@@ -43,6 +43,7 @@
#include <qpa/qplatformintegration.h>
#include <QtCore/QScopedPointer>
+#include <QtFontDatabaseSupport/private/qwindowsfontdatabase_p.h>
QT_BEGIN_NAMESPACE
@@ -61,8 +62,9 @@ public:
NoNativeDialogs = 0x8,
XpNativeDialogs = 0x10,
DontPassOsMouseEventsSynthesizedFromTouch = 0x20, // Do not pass OS-generated mouse events from touch.
- DontUseDirectWriteFonts = 0x40,
- DontUseColorFonts = 0x80
+ // Keep in sync with QWindowsFontDatabase::FontOptions
+ DontUseDirectWriteFonts = QWindowsFontDatabase::DontUseDirectWriteFonts,
+ DontUseColorFonts = QWindowsFontDatabase::DontUseColorFonts
};
explicit QWindowsIntegration(const QStringList &paramList);
@@ -106,7 +108,7 @@ public:
void beep() const Q_DECL_OVERRIDE;
-#if !defined(Q_OS_WINCE) && !defined(QT_NO_SESSIONMANAGER)
+#if !defined(QT_NO_SESSIONMANAGER)
QPlatformSessionManager *createPlatformSessionManager(const QString &id, const QString &key) const Q_DECL_OVERRIDE;
#endif
diff --git a/src/plugins/platforms/windows/qwindowsinternalmimedata.cpp b/src/plugins/platforms/windows/qwindowsinternalmimedata.cpp
index 2dfe7fc5f9..21ebee6262 100644
--- a/src/plugins/platforms/windows/qwindowsinternalmimedata.cpp
+++ b/src/plugins/platforms/windows/qwindowsinternalmimedata.cpp
@@ -39,7 +39,6 @@
#include "qwindowsinternalmimedata.h"
#include "qwindowscontext.h"
-#include "qplatformfunctions_wince.h"
#include "qwindowsmime.h"
#include <QDebug>
/*!
diff --git a/src/plugins/platforms/windows/qwindowsinternalmimedata.h b/src/plugins/platforms/windows/qwindowsinternalmimedata.h
index 4ac7a303af..4d775b1f21 100644
--- a/src/plugins/platforms/windows/qwindowsinternalmimedata.h
+++ b/src/plugins/platforms/windows/qwindowsinternalmimedata.h
@@ -40,7 +40,7 @@
#ifndef QWINDOWSINTERNALMIME_H
#define QWINDOWSINTERNALMIME_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtGui/private/qdnd_p.h> // QInternalMime
#include <QtCore/QVariant>
diff --git a/src/plugins/platforms/windows/qwindowskeymapper.cpp b/src/plugins/platforms/windows/qwindowskeymapper.cpp
index 1afce9cde9..b8c4f0b736 100644
--- a/src/plugins/platforms/windows/qwindowskeymapper.cpp
+++ b/src/plugins/platforms/windows/qwindowskeymapper.cpp
@@ -49,7 +49,7 @@
#include <private/qguiapplication_p.h>
#include <private/qhighdpiscaling_p.h>
#include <QtGui/QKeyEvent>
-#include <QtPlatformSupport/private/qwindowsguieventdispatcher_p.h>
+#include <QtEventDispatcherSupport/private/qwindowsguieventdispatcher_p.h>
#if defined(WM_APPCOMMAND)
# ifndef FAPPCOMMAND_MOUSE
@@ -553,34 +553,6 @@ inline quint32 winceKeyBend(quint32 keyCode)
return KeyTbl[keyCode];
}
-#ifdef Q_OS_WINCE
-QT_BEGIN_INCLUDE_NAMESPACE
-int ToUnicode(UINT vk, int /*scancode*/, unsigned char* /*kbdBuffer*/, LPWSTR unicodeBuffer, int, int)
-{
- QT_USE_NAMESPACE
- QChar* buf = reinterpret_cast< QChar*>(unicodeBuffer);
- if (KeyTbl[vk] == 0) {
- buf[0] = vk;
- return 1;
- }
- return 0;
-}
-
-int ToAscii(UINT vk, int scancode, unsigned char *kbdBuffer, LPWORD unicodeBuffer, int flag)
-{
- return ToUnicode(vk, scancode, kbdBuffer, (LPWSTR) unicodeBuffer, 0, flag);
-
-}
-
-bool GetKeyboardState(unsigned char* kbuffer)
-{
- for (int i=0; i< 256; ++i)
- kbuffer[i] = GetAsyncKeyState(i);
- return true;
-}
-QT_END_INCLUDE_NAMESPACE
-#endif // Q_OS_WINCE
-
// Translate a VK into a Qt key code, or unicode character
static inline quint32 toKeyOrUnicode(quint32 vk, quint32 scancode, unsigned char *kbdBuffer, bool *isDeadkey = 0)
{
@@ -781,7 +753,6 @@ static void showSystemMenu(QWindow* w)
if (!menu)
return; // no menu for this window
-#ifndef Q_OS_WINCE
#define enabled (MF_BYCOMMAND | MF_ENABLED)
#define disabled (MF_BYCOMMAND | MF_GRAYED)
@@ -806,7 +777,6 @@ static void showSystemMenu(QWindow* w)
#undef enabled
#undef disabled
-#endif // !Q_OS_WINCE
const QPoint pos = QHighDpi::toNativePixels(topLevel->geometry().topLeft(), topLevel);
const int ret = TrackPopupMenuEx(menu,
TPM_LEFTALIGN | TPM_TOPALIGN | TPM_NONOTIFY | TPM_RETURNCMD,
@@ -1188,7 +1158,6 @@ bool QWindowsKeyMapper::translateKeyEventInternal(QWindow *window, const MSG &ms
modifiers, scancode, quint32(msg.wParam), nModifiers, text, false);
result =true;
bool store = true;
-#ifndef Q_OS_WINCE
// Alt+<alphanumerical> go to the Win32 menu system if unhandled by Qt
if (msgType == WM_SYSKEYDOWN && !result && a) {
HWND parent = GetParent(QWindowsWindow::handleOf(receiver));
@@ -1202,7 +1171,6 @@ bool QWindowsKeyMapper::translateKeyEventInternal(QWindow *window, const MSG &ms
parent = GetParent(parent);
}
}
-#endif // !Q_OS_WINCE
if (!store)
key_recorder.findKey(int(msg.wParam), true);
}
@@ -1232,7 +1200,6 @@ bool QWindowsKeyMapper::translateKeyEventInternal(QWindow *window, const MSG &ms
nModifiers,
(rec ? rec->text : QString()), false);
result = true;
-#ifndef Q_OS_WINCE
// don't pass Alt to Windows unless we are embedded in a non-Qt window
if (code == Qt::Key_Alt) {
const QWindowsContext *context = QWindowsContext::instance();
@@ -1245,7 +1212,6 @@ bool QWindowsKeyMapper::translateKeyEventInternal(QWindow *window, const MSG &ms
parent = GetParent(parent);
}
}
-#endif
}
}
return result;
diff --git a/src/plugins/platforms/windows/qwindowskeymapper.h b/src/plugins/platforms/windows/qwindowskeymapper.h
index 1e32ddabcc..2657644780 100644
--- a/src/plugins/platforms/windows/qwindowskeymapper.h
+++ b/src/plugins/platforms/windows/qwindowskeymapper.h
@@ -40,7 +40,7 @@
#ifndef QWINDOWSKEYMAPPER_H
#define QWINDOWSKEYMAPPER_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/QLocale>
diff --git a/src/plugins/platforms/windows/qwindowsmime.cpp b/src/plugins/platforms/windows/qwindowsmime.cpp
index b86972996c..30d438a127 100644
--- a/src/plugins/platforms/windows/qwindowsmime.cpp
+++ b/src/plugins/platforms/windows/qwindowsmime.cpp
@@ -403,11 +403,9 @@ QDebug operator<<(QDebug d, const FORMATETC &tc)
case CF_UNICODETEXT:
d << "CF_UNICODETEXT";
break;
-#ifndef Q_OS_WINCE
case CF_ENHMETAFILE:
d << "CF_ENHMETAFILE";
break;
-#endif // !Q_OS_WINCE
default:
d << QWindowsMimeConverter::clipboardFormatName(tc.cfFormat);
break;
diff --git a/src/plugins/platforms/windows/qwindowsmime.h b/src/plugins/platforms/windows/qwindowsmime.h
index b727f13747..4c0cbf9f31 100644
--- a/src/plugins/platforms/windows/qwindowsmime.h
+++ b/src/plugins/platforms/windows/qwindowsmime.h
@@ -40,7 +40,7 @@
#ifndef QWINDOWSMIME_H
#define QWINDOWSMIME_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/QVector>
#include <QtCore/QList>
diff --git a/src/plugins/platforms/windows/qwindowsmousehandler.cpp b/src/plugins/platforms/windows/qwindowsmousehandler.cpp
index b92387d397..3f6230172e 100644
--- a/src/plugins/platforms/windows/qwindowsmousehandler.cpp
+++ b/src/plugins/platforms/windows/qwindowsmousehandler.cpp
@@ -56,6 +56,37 @@
#include <windowsx.h>
+/* Touch is supported from Windows 7 onwards and data structures
+ * are present in the Windows SDK's, but not in older MSVC Express
+ * versions. */
+
+#if defined(Q_CC_MINGW) || !defined(TOUCHEVENTF_MOVE)
+
+typedef struct tagTOUCHINPUT {
+ LONG x;
+ LONG y;
+ HANDLE hSource;
+ DWORD dwID;
+ DWORD dwFlags;
+ DWORD dwMask;
+ DWORD dwTime;
+ ULONG_PTR dwExtraInfo;
+ DWORD cxContact;
+ DWORD cyContact;
+} TOUCHINPUT, *PTOUCHINPUT;
+typedef TOUCHINPUT const * PCTOUCHINPUT;
+
+# 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_PALM 0x0080
+# define TOUCHINPUTMASKF_CONTACTAREA 0x0004
+# define TOUCHINPUTMASKF_EXTRAINFO 0x0002
+#endif // if defined(Q_CC_MINGW) || !defined(TOUCHEVENTF_MOVE)
+
QT_BEGIN_NAMESPACE
static inline void compressMouseMove(MSG *msg)
@@ -203,7 +234,6 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd,
Qt::MouseEventSource source = Qt::MouseEventNotSynthesized;
-#ifndef Q_OS_WINCE
// Check for events synthesized from touch. Lower byte is touch index, 0 means pen.
static const bool passSynthesizedMouseEvents =
!(QWindowsIntegration::instance()->options() & QWindowsIntegration::DontPassOsMouseEventsSynthesizedFromTouch);
@@ -218,7 +248,6 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd,
return false;
}
}
-#endif // !Q_OS_WINCE
const QPoint winEventPosition(GET_X_LPARAM(msg.lParam), GET_Y_LPARAM(msg.lParam));
if (et & QtWindows::NonClientEventFlag) {
@@ -320,7 +349,6 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd,
const bool hasCapture = platformWindow->hasMouseCapture();
const bool currentNotCapturing = hasCapture && currentWindowUnderMouse != window;
-#ifndef Q_OS_WINCE
// Enter new window: track to generate leave event.
// If there is an active capture, only track if the current window is capturing,
// so we don't get extra leave when cursor leaves the application.
@@ -334,7 +362,6 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd,
qWarning("TrackMouseEvent failed.");
m_trackedWindow = window;
}
-#endif // !Q_OS_WINCE
// No enter or leave events are sent as long as there is an autocapturing window.
if (!hasCapture || !platformWindow->testFlag(QWindowsWindow::AutoMouseCapture)) {
@@ -489,7 +516,6 @@ bool QWindowsMouseHandler::translateTouchEvent(QWindow *window, HWND,
QtWindows::WindowsEventType,
MSG msg, LRESULT *)
{
-#ifndef Q_OS_WINCE
typedef QWindowSystemInterface::TouchPoint QTouchPoint;
typedef QList<QWindowSystemInterface::TouchPoint> QTouchPointList;
@@ -565,109 +591,17 @@ bool QWindowsMouseHandler::translateTouchEvent(QWindow *window, HWND,
QWindowSystemInterface::handleTouchEvent(window,
m_touchDevice,
touchPoints);
-#else // !Q_OS_WINCE
- Q_UNUSED(window)
- Q_UNUSED(msg)
-#endif
return true;
-
}
bool QWindowsMouseHandler::translateGestureEvent(QWindow *window, HWND hwnd,
QtWindows::WindowsEventType,
MSG msg, LRESULT *)
{
-#ifndef Q_OS_WINCE
Q_UNUSED(window)
Q_UNUSED(hwnd)
Q_UNUSED(msg)
return false;
-#else // !Q_OS_WINCE
- GESTUREINFO gi;
- memset(&gi, 0, sizeof(GESTUREINFO));
- gi.cbSize = sizeof(GESTUREINFO);
-
- if (!GetGestureInfo((HGESTUREINFO)msg.lParam, &gi))
- return false;
-
- const QPoint position = QPoint(gi.ptsLocation.x, gi.ptsLocation.y);
-
- if (gi.dwID != GID_DIRECTMANIPULATION)
- return true;
- static QPoint lastTouchPos;
- const QScreen *screen = window->screen();
- if (!screen)
- screen = QGuiApplication::primaryScreen();
- if (!screen)
- return true;
- const QRect screenGeometry = screen->geometry();
- QWindowSystemInterface::TouchPoint touchPoint;
- static QWindowSystemInterface::TouchPoint touchPoint2;
- touchPoint.id = 0;//gi.dwInstanceID;
- touchPoint.pressure = 1.0;
-
- if (gi.dwFlags & GF_BEGIN)
- touchPoint.state = Qt::TouchPointPressed;
- else if (gi.dwFlags & GF_END)
- touchPoint.state = Qt::TouchPointReleased;
- else if (gi.dwFlags == 0)
- touchPoint.state = Qt::TouchPointMoved;
- else
- return true;
- touchPoint2.pressure = 1.0;
- touchPoint2.id = 1;
- const QPoint winEventPosition = position;
- const int deltaX = GID_DIRECTMANIPULATION_DELTA_X(gi.ullArguments);
- const int deltaY = GID_DIRECTMANIPULATION_DELTA_Y(gi.ullArguments);
- //Touch points are taken from the whole screen so map the position to the screen
- const QPoint globalPosition = QWindowsGeometryHint::mapToGlobal(hwnd, winEventPosition);
- const QPoint globalPosition2 = QWindowsGeometryHint::mapToGlobal(hwnd, QPoint(position.x() + deltaX, position.y() + deltaY));
-
- touchPoint.normalPosition =
- QPointF( (qreal)globalPosition.x() / screenGeometry.width(), (qreal)globalPosition.y() / screenGeometry.height() );
-
- touchPoint.area.moveCenter(globalPosition);
-
- QList<QWindowSystemInterface::TouchPoint> pointList;
- pointList.append(touchPoint);
- if (deltaX != 0 && deltaY != 0) {
- touchPoint2.state = m_had2ndTouchPoint ? Qt::TouchPointMoved : Qt::TouchPointPressed;
- m_had2ndTouchPoint = true;
- touchPoint2.normalPosition =
- QPointF( (qreal)globalPosition2.x() / screenGeometry.width(), (qreal)globalPosition2.y() / screenGeometry.height() );
-
- touchPoint2.area.moveCenter(globalPosition2);
- lastTouchPos = globalPosition2;
- pointList.append(touchPoint2);
- } else if (m_had2ndTouchPoint) {
- touchPoint2.normalPosition =
- QPointF( (qreal)lastTouchPos.x() / screenGeometry.width(), (qreal)lastTouchPos.y() / screenGeometry.height() );
-
- touchPoint2.area.moveCenter(lastTouchPos);
- touchPoint2.state = Qt::TouchPointReleased;
- pointList.append(touchPoint2);
- m_had2ndTouchPoint = false;
- }
-
- if (!m_touchDevice) {
- m_touchDevice = new QTouchDevice;
- // TODO: Device used to be hardcoded to screen in previous code.
- m_touchDevice->setType(QTouchDevice::TouchScreen);
- m_touchDevice->setCapabilities(QTouchDevice::Position | QTouchDevice::Area | QTouchDevice::NormalizedPosition);
- QWindowSystemInterface::registerTouchDevice(m_touchDevice);
- }
-
- QWindowSystemInterface::handleTouchEvent(window, m_touchDevice, pointList);
- // handle window focusing in/out
- if (window != m_windowUnderMouse) {
- if (m_windowUnderMouse)
- QWindowSystemInterface::handleLeaveEvent(m_windowUnderMouse);
- if (window)
- QWindowSystemInterface::handleEnterEvent(window);
- m_windowUnderMouse = window;
- }
- return true;
-#endif // Q_OS_WINCE
}
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsmousehandler.h b/src/plugins/platforms/windows/qwindowsmousehandler.h
index d16c9f9e02..bd36d9f44c 100644
--- a/src/plugins/platforms/windows/qwindowsmousehandler.h
+++ b/src/plugins/platforms/windows/qwindowsmousehandler.h
@@ -41,7 +41,7 @@
#define QWINDOWSMOUSEHANDLER_H
#include "qtwindowsglobal.h"
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/QPointer>
#include <QtCore/QHash>
@@ -91,10 +91,6 @@ private:
QTouchDevice *m_touchDevice;
bool m_leftButtonDown;
QWindow *m_previousCaptureWindow;
-#ifdef Q_OS_WINCE
-//This is required to send a touch up if we don't get a second touch position any more
- bool m_had2ndTouchPoint;
-#endif
};
Qt::MouseButtons QWindowsMouseHandler::keyStateToMouseButtons(int wParam)
diff --git a/src/plugins/platforms/windows/qwindowsnativeimage.cpp b/src/plugins/platforms/windows/qwindowsnativeimage.cpp
deleted file mode 100644
index bc8bfda32b..0000000000
--- a/src/plugins/platforms/windows/qwindowsnativeimage.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwindowsnativeimage.h"
-#include "qwindowscontext.h"
-
-#include <QtGui/private/qpaintengine_p.h>
-#include <QtGui/private/qpaintengine_raster_p.h>
-
-QT_BEGIN_NAMESPACE
-
-typedef struct {
- BITMAPINFOHEADER bmiHeader;
- DWORD redMask;
- DWORD greenMask;
- DWORD blueMask;
-} BITMAPINFO_MASK;
-
-/*!
- \class QWindowsNativeImage
- \brief Windows Native image
-
- Note that size can be 0 (widget autotests with zero size), which
- causes CreateDIBSection() to fail.
-
- \sa QWindowsBackingStore
- \internal
- \ingroup qt-lighthouse-win
-*/
-
-static inline HDC createDC()
-{
- HDC display_dc = GetDC(0);
- HDC hdc = CreateCompatibleDC(display_dc);
- ReleaseDC(0, display_dc);
- Q_ASSERT(hdc);
- return hdc;
-}
-
-static inline HBITMAP createDIB(HDC hdc, int width, int height,
- QImage::Format format,
- uchar **bitsIn)
-{
- BITMAPINFO_MASK bmi;
- memset(&bmi, 0, sizeof(bmi));
- bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- bmi.bmiHeader.biWidth = width;
- bmi.bmiHeader.biHeight = -height; // top-down.
- bmi.bmiHeader.biPlanes = 1;
- bmi.bmiHeader.biSizeImage = 0;
-
- if (format == QImage::Format_RGB16) {
- bmi.bmiHeader.biBitCount = 16;
- bmi.bmiHeader.biCompression = BI_BITFIELDS;
- bmi.redMask = 0xF800;
- bmi.greenMask = 0x07E0;
- bmi.blueMask = 0x001F;
- } else {
- bmi.bmiHeader.biBitCount = 32;
- bmi.bmiHeader.biCompression = BI_RGB;
- bmi.redMask = 0;
- bmi.greenMask = 0;
- bmi.blueMask = 0;
- }
-
- uchar *bits = Q_NULLPTR;
- HBITMAP bitmap = CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO *>(&bmi),
- DIB_RGB_COLORS, reinterpret_cast<void **>(&bits), 0, 0);
- if (Q_UNLIKELY(!bitmap || !bits))
- qFatal("%s: CreateDIBSection failed.", __FUNCTION__);
-
- *bitsIn = bits;
- return bitmap;
-}
-
-QWindowsNativeImage::QWindowsNativeImage(int width, int height,
- QImage::Format format) :
- m_hdc(createDC()),
- m_bitmap(0),
- m_null_bitmap(0)
-{
- if (width != 0 && height != 0) {
- uchar *bits;
- m_bitmap = createDIB(m_hdc, width, height, format, &bits);
- m_null_bitmap = static_cast<HBITMAP>(SelectObject(m_hdc, m_bitmap));
- m_image = QImage(bits, width, height, format);
- Q_ASSERT(m_image.paintEngine()->type() == QPaintEngine::Raster);
- static_cast<QRasterPaintEngine *>(m_image.paintEngine())->setDC(m_hdc);
- } else {
- m_image = QImage(width, height, format);
- }
-
-#ifndef Q_OS_WINCE
- GdiFlush();
-#endif
-}
-
-QWindowsNativeImage::~QWindowsNativeImage()
-{
- if (m_hdc) {
- if (m_bitmap) {
- if (m_null_bitmap)
- SelectObject(m_hdc, m_null_bitmap);
- DeleteObject(m_bitmap);
- }
- DeleteDC(m_hdc);
- }
-}
-
-QImage::Format QWindowsNativeImage::systemFormat()
-{
- static const int depth = QWindowsContext::instance()->screenDepth();
- return depth == 16 ? QImage::Format_RGB16 : QImage::Format_RGB32;
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsnativeinterface.cpp b/src/plugins/platforms/windows/qwindowsnativeinterface.cpp
index e0ae111b9a..eaa6e45b9f 100644
--- a/src/plugins/platforms/windows/qwindowsnativeinterface.cpp
+++ b/src/plugins/platforms/windows/qwindowsnativeinterface.cpp
@@ -41,7 +41,6 @@
#include "qwindowswindow.h"
#include "qwindowscontext.h"
#include "qwindowscursor.h"
-#include "qwindowsfontdatabase.h"
#include "qwindowsopenglcontext.h"
#include "qwindowsopengltester.h"
#include "qwindowsintegration.h"
@@ -51,6 +50,7 @@
#include <QtGui/QOpenGLContext>
#include <QtGui/QScreen>
#include <qpa/qplatformscreen.h>
+#include <QtFontDatabaseSupport/private/qwindowsfontdatabase_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsole.h b/src/plugins/platforms/windows/qwindowsole.h
index 009111e55c..dc31c793e9 100644
--- a/src/plugins/platforms/windows/qwindowsole.h
+++ b/src/plugins/platforms/windows/qwindowsole.h
@@ -40,7 +40,7 @@
#ifndef QWINDOWSOLE_H
#define QWINDOWSOLE_H
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/QMap>
#include <QtCore/QPointer>
diff --git a/src/plugins/platforms/windows/qwindowsopengltester.cpp b/src/plugins/platforms/windows/qwindowsopengltester.cpp
index c24e0ba0ae..5283d6b260 100644
--- a/src/plugins/platforms/windows/qwindowsopengltester.cpp
+++ b/src/plugins/platforms/windows/qwindowsopengltester.cpp
@@ -54,17 +54,14 @@
#include <private/qopengl_p.h>
#endif
-#ifndef Q_OS_WINCE
-# include <QtCore/qt_windows.h>
-# include <private/qsystemlibrary_p.h>
-# include <d3d9.h>
-#endif
+#include <QtCore/qt_windows.h>
+#include <private/qsystemlibrary_p.h>
+#include <d3d9.h>
QT_BEGIN_NAMESPACE
GpuDescription GpuDescription::detect()
{
-#ifndef Q_OS_WINCE
typedef IDirect3D9 * (WINAPI *PtrDirect3DCreate9)(UINT);
GpuDescription result;
@@ -95,13 +92,6 @@ GpuDescription GpuDescription::detect()
result.description = adapterIdentifier.Description;
}
return result;
-#else // !Q_OS_WINCE
- GpuDescription result;
- result.vendorId = result.deviceId = result.revision =1;
- result.driverVersion = QVersionNumber(1, 1, 1);
- result.driverName = result.description = QByteArrayLiteral("Generic");
- return result;
-#endif
}
#ifndef QT_NO_DEBUG_STREAM
@@ -155,7 +145,6 @@ QVariant GpuDescription::toVariant() const
QWindowsOpenGLTester::Renderer QWindowsOpenGLTester::requestedGlesRenderer()
{
-#ifndef Q_OS_WINCE
const char platformVar[] = "QT_ANGLE_PLATFORM";
if (qEnvironmentVariableIsSet(platformVar)) {
const QByteArray anglePlatform = qgetenv(platformVar);
@@ -167,13 +156,11 @@ QWindowsOpenGLTester::Renderer QWindowsOpenGLTester::requestedGlesRenderer()
return QWindowsOpenGLTester::AngleRendererD3d11Warp;
qCWarning(lcQpaGl) << "Invalid value set for " << platformVar << ": " << anglePlatform;
}
-#endif // !Q_OS_WINCE
return QWindowsOpenGLTester::InvalidRenderer;
}
QWindowsOpenGLTester::Renderer QWindowsOpenGLTester::requestedRenderer()
{
-#ifndef Q_OS_WINCE
const char openGlVar[] = "QT_OPENGL";
if (QCoreApplication::testAttribute(Qt::AA_UseOpenGLES)) {
const Renderer glesRenderer = QWindowsOpenGLTester::requestedGlesRenderer();
@@ -195,12 +182,9 @@ QWindowsOpenGLTester::Renderer QWindowsOpenGLTester::requestedRenderer()
return QWindowsOpenGLTester::SoftwareRasterizer;
qCWarning(lcQpaGl) << "Invalid value set for " << openGlVar << ": " << requested;
}
-#endif // !Q_OS_WINCE
return QWindowsOpenGLTester::InvalidRenderer;
}
-#ifndef Q_OS_WINCE
-
static inline QString resolveBugListFile(const QString &fileName)
{
if (QFileInfo(fileName).isAbsolute())
@@ -216,12 +200,10 @@ static inline QString resolveBugListFile(const QString &fileName)
return QStandardPaths::locate(QStandardPaths::ConfigLocation, fileName);
}
-# ifndef QT_NO_OPENGL
+#ifndef QT_NO_OPENGL
typedef QHash<QOpenGLConfig::Gpu, QWindowsOpenGLTester::Renderers> SupportedRenderersCache;
Q_GLOBAL_STATIC(SupportedRenderersCache, supportedRenderersCache)
-# endif
-
-#endif // !Q_OS_WINCE
+#endif
QWindowsOpenGLTester::Renderers QWindowsOpenGLTester::detectSupportedRenderers(const GpuDescription &gpu, bool glesOnly)
{
@@ -229,8 +211,6 @@ QWindowsOpenGLTester::Renderers QWindowsOpenGLTester::detectSupportedRenderers(c
Q_UNUSED(glesOnly)
#if defined(QT_NO_OPENGL)
return 0;
-#elif defined(Q_OS_WINCE)
- return QWindowsOpenGLTester::Gles;
#else
QOpenGLConfig::Gpu qgpu = QOpenGLConfig::Gpu::fromDevice(gpu.vendorId, gpu.deviceId, gpu.driverVersion, gpu.description);
SupportedRenderersCache *srCache = supportedRenderersCache();
@@ -281,7 +261,7 @@ QWindowsOpenGLTester::Renderers QWindowsOpenGLTester::detectSupportedRenderers(c
}
srCache->insert(qgpu, result);
return result;
-#endif // !Q_OS_WINCE && !QT_NO_OPENGL
+#endif // !QT_NO_OPENGL
}
QWindowsOpenGLTester::Renderers QWindowsOpenGLTester::supportedGlesRenderers()
@@ -302,7 +282,7 @@ QWindowsOpenGLTester::Renderers QWindowsOpenGLTester::supportedRenderers()
bool QWindowsOpenGLTester::testDesktopGL()
{
-#if !defined(QT_NO_OPENGL) && !defined(Q_OS_WINCE)
+#if !defined(QT_NO_OPENGL)
HMODULE lib = 0;
HWND wnd = 0;
HDC dc = 0;
@@ -429,7 +409,7 @@ cleanup:
return result;
#else
return false;
-#endif // !QT_NO_OPENGL && !Q_OS_WINCE
+#endif // !QT_NO_OPENGL
}
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsscreen.cpp b/src/plugins/platforms/windows/qwindowsscreen.cpp
index b476c9be1d..23d43a95a5 100644
--- a/src/plugins/platforms/windows/qwindowsscreen.cpp
+++ b/src/plugins/platforms/windows/qwindowsscreen.cpp
@@ -43,7 +43,7 @@
#include "qwindowsintegration.h"
#include "qwindowscursor.h"
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/QSettings>
#include <QtGui/QPixmap>
@@ -68,8 +68,6 @@ static inline QDpi deviceDPI(HDC hdc)
return QDpi(GetDeviceCaps(hdc, LOGPIXELSX), GetDeviceCaps(hdc, LOGPIXELSY));
}
-#ifndef Q_OS_WINCE
-
static inline QDpi monitorDPI(HMONITOR hMonitor)
{
if (QWindowsContext::shcoredll.isValid()) {
@@ -81,8 +79,6 @@ static inline QDpi monitorDPI(HMONITOR hMonitor)
return QDpi(0, 0);
}
-#endif // !Q_OS_WINCE
-
typedef QList<QWindowsScreenData> WindowsScreenDataList;
static bool monitorData(HMONITOR hMonitor, QWindowsScreenData *data)
@@ -99,20 +95,9 @@ static bool monitorData(HMONITOR hMonitor, QWindowsScreenData *data)
if (data->name == QLatin1String("WinDisc")) {
data->flags |= QWindowsScreenData::LockScreen;
} else {
-#ifdef Q_OS_WINCE
- //Windows CE, just supports one Display and expects to get only DISPLAY,
- //instead of DISPLAY0 and so on, which are passed by info.szDevice
- HDC hdc = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
-#else
- HDC hdc = CreateDC(info.szDevice, NULL, NULL, NULL);
-#endif
- if (hdc) {
-#ifndef Q_OS_WINCE
+ if (const HDC hdc = CreateDC(info.szDevice, NULL, NULL, NULL)) {
const QDpi dpi = monitorDPI(hMonitor);
data->dpi = dpi.first ? dpi : deviceDPI(hdc);
-#else
- data->dpi = deviceDPI(hdc);
-#endif
data->depth = GetDeviceCaps(hdc, BITSPIXEL);
data->format = data->depth == 16 ? QImage::Format_RGB16 : QImage::Format_RGB32;
data->physicalSizeMM = QSizeF(GetDeviceCaps(hdc, HORZSIZE), GetDeviceCaps(hdc, VERTSIZE));
@@ -330,7 +315,6 @@ enum OrientationPreference // matching Win32 API ORIENTATION_PREFERENCE
bool QWindowsScreen::setOrientationPreference(Qt::ScreenOrientation o)
{
bool result = false;
-#ifndef Q_OS_WINCE
if (QWindowsContext::user32dll.setDisplayAutoRotationPreferences) {
DWORD orientationPreference = 0;
switch (o) {
@@ -352,14 +336,12 @@ bool QWindowsScreen::setOrientationPreference(Qt::ScreenOrientation o)
}
result = QWindowsContext::user32dll.setDisplayAutoRotationPreferences(orientationPreference);
}
-#endif // !Q_OS_WINCE
return result;
}
Qt::ScreenOrientation QWindowsScreen::orientationPreference()
{
Qt::ScreenOrientation result = Qt::PrimaryOrientation;
-#ifndef Q_OS_WINCE
if (QWindowsContext::user32dll.getDisplayAutoRotationPreferences) {
DWORD orientationPreference = 0;
if (QWindowsContext::user32dll.getDisplayAutoRotationPreferences(&orientationPreference)) {
@@ -379,7 +361,6 @@ Qt::ScreenOrientation QWindowsScreen::orientationPreference()
}
}
}
-#endif // !Q_OS_WINCE
return result;
}
@@ -388,7 +369,7 @@ Qt::ScreenOrientation QWindowsScreen::orientationPreference()
*/
QPlatformScreen::SubpixelAntialiasingType QWindowsScreen::subpixelAntialiasingTypeHint() const
{
-#if defined(Q_OS_WINCE) || !defined(FT_LCD_FILTER_H) || !defined(FT_CONFIG_OPTION_SUBPIXEL_RENDERING)
+#if !defined(FT_LCD_FILTER_H) || !defined(FT_CONFIG_OPTION_SUBPIXEL_RENDERING)
return QPlatformScreen::Subpixel_None;
#else
QPlatformScreen::SubpixelAntialiasingType type = QPlatformScreen::subpixelAntialiasingTypeHint();
diff --git a/src/plugins/platforms/windows/qwindowsscreen.h b/src/plugins/platforms/windows/qwindowsscreen.h
index 2afc410e07..02a9dc3bc3 100644
--- a/src/plugins/platforms/windows/qwindowsscreen.h
+++ b/src/plugins/platforms/windows/qwindowsscreen.h
@@ -41,9 +41,6 @@
#define QWINDOWSSCREEN_H
#include "qtwindowsglobal.h"
-#ifdef Q_OS_WINCE
-# include "qplatformfunctions_wince.h"
-#endif
#include <QtCore/QList>
#include <QtCore/QVector>
diff --git a/src/plugins/platforms/windows/qwindowsservices.cpp b/src/plugins/platforms/windows/qwindowsservices.cpp
index d8058fcd06..7f9c9bd205 100644
--- a/src/plugins/platforms/windows/qwindowsservices.cpp
+++ b/src/plugins/platforms/windows/qwindowsservices.cpp
@@ -39,16 +39,14 @@
#define QT_NO_URL_CAST_FROM_STRING
#include "qwindowsservices.h"
-#include "qtwindows_additional.h"
+#include <QtCore/qt_windows.h>
#include <QtCore/QUrl>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <shlobj.h>
-#ifndef Q_OS_WINCE
-# include <intshcut.h>
-#endif
+#include <intshcut.h>
QT_BEGIN_NAMESPACE
@@ -56,7 +54,6 @@ enum { debug = 0 };
static inline bool shellExecute(const QUrl &url)
{
-#ifndef Q_OS_WINCE
const QString nativeFilePath = url.isLocalFile() && !url.hasFragment() && !url.hasQuery()
? QDir::toNativeSeparators(url.toLocalFile())
: url.toString(QUrl::FullyEncoded);
@@ -70,10 +67,6 @@ static inline bool shellExecute(const QUrl &url)
return false;
}
return true;
-#else
- Q_UNUSED(url);
- return false;
-#endif
}
// Retrieve the commandline for the default mail client. It contains a
@@ -107,13 +100,9 @@ static inline QString mailCommand()
}
if (!command[0])
return QString();
-#ifndef Q_OS_WINCE
wchar_t expandedCommand[MAX_PATH] = {0};
return ExpandEnvironmentStrings(command, expandedCommand, MAX_PATH) ?
QString::fromWCharArray(expandedCommand) : QString::fromWCharArray(command);
-#else
- return QString();
-#endif
}
static inline bool launchMail(const QUrl &url)
diff --git a/src/plugins/platforms/windows/qwindowstabletsupport.h b/src/plugins/platforms/windows/qwindowstabletsupport.h
index 4a24d62770..2c05dcddfc 100644
--- a/src/plugins/platforms/windows/qwindowstabletsupport.h
+++ b/src/plugins/platforms/windows/qwindowstabletsupport.h
@@ -42,7 +42,7 @@
#include "qtwindowsglobal.h"
-#if !defined(QT_NO_TABLETEVENT) && !defined(Q_OS_WINCE)
+#if !defined(QT_NO_TABLETEVENT)
#include <QtCore/QVector>
#include <QtCore/QPointF>
@@ -143,5 +143,5 @@ private:
QT_END_NAMESPACE
-#endif // !QT_NO_TABLETEVENT && !Q_OS_WINCE
+#endif // !QT_NO_TABLETEVENT
#endif // QWINDOWSTABLETSUPPORT_H
diff --git a/src/plugins/platforms/windows/qwindowstheme.cpp b/src/plugins/platforms/windows/qwindowstheme.cpp
index ff4cfe63cb..ed12c8124e 100644
--- a/src/plugins/platforms/windows/qwindowstheme.cpp
+++ b/src/plugins/platforms/windows/qwindowstheme.cpp
@@ -48,18 +48,12 @@
#include "qwindowscontext.h"
#include "qwindowsintegration.h"
#include "qt_windows.h"
-#include "qwindowsfontdatabase.h"
-#ifdef Q_OS_WINCE
-# include "qplatformfunctions_wince.h"
-# include "winuser.h"
-#else
-# include <commctrl.h>
-# include <objbase.h>
-# ifndef Q_CC_MINGW
-# include <commoncontrols.h>
-# endif
-# include <shellapi.h>
+#include <commctrl.h>
+#include <objbase.h>
+#ifndef Q_CC_MINGW
+# include <commoncontrols.h>
#endif
+#include <shellapi.h>
#include <QtCore/QVariant>
#include <QtCore/QCoreApplication>
@@ -73,6 +67,8 @@
#include <QtGui/QPainter>
#include <QtGui/QPixmapCache>
#include <qpa/qwindowsysteminterface.h>
+#include <QtThemeSupport/private/qabstractfileiconengine_p.h>
+#include <QtFontDatabaseSupport/private/qwindowsfontdatabase_p.h>
#include <private/qhighdpiscaling_p.h>
#include <private/qsystemlibrary_p.h>
@@ -128,7 +124,6 @@ static inline QColor getSysColor(int index)
return COLORREFToQColor(GetSysColor(index));
}
-#ifndef QT_NO_WINCE_SHELLSDK
// QTBUG-48823/Windows 10: SHGetFileInfo() (as called by item views on file system
// models has been observed to trigger a WM_PAINT on the mainwindow. Suppress the
// behavior by running it in a thread.
@@ -170,7 +165,6 @@ static bool shGetFileInfoBackground(QWindowsThreadPoolRunner &r,
}
return result;
}
-#endif // !QT_NO_WINCE_SHELLSDK
// from QStyle::standardPalette
static inline QPalette standardPalette()
@@ -281,14 +275,9 @@ static inline QPalette menuPalette(const QPalette &systemPalette)
result.setColor(QPalette::Active, QPalette::ButtonText, menuTextColor);
result.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
result.setColor(QPalette::Disabled, QPalette::Text, disabled);
-#ifndef Q_OS_WINCE
const bool isFlat = booleanSystemParametersInfo(SPI_GETFLATMENU, false);
result.setColor(QPalette::Disabled, QPalette::Highlight,
getSysColor(isFlat ? COLOR_MENUHILIGHT : COLOR_HIGHLIGHT));
-#else
- result.setColor(QPalette::Disabled, QPalette::Highlight,
- getSysColor(COLOR_HIGHLIGHT));
-#endif
result.setColor(QPalette::Disabled, QPalette::HighlightedText, disabled);
result.setColor(QPalette::Disabled, QPalette::Button,
result.color(QPalette::Active, QPalette::Button));
@@ -314,11 +303,7 @@ static inline QPalette *menuBarPalette(const QPalette &menuPalette)
QPalette *result = 0;
if (booleanSystemParametersInfo(SPI_GETFLATMENU, false)) {
result = new QPalette(menuPalette);
-#ifndef Q_OS_WINCE
const QColor menubar(getSysColor(COLOR_MENUBAR));
-#else
- const QColor menubar(getSysColor(COLOR_MENU));
-#endif
result->setColor(QPalette::Active, QPalette::Button, menubar);
result->setColor(QPalette::Disabled, QPalette::Button, menubar);
result->setColor(QPalette::Inactive, QPalette::Button, menubar);
@@ -330,6 +315,7 @@ const char *QWindowsTheme::name = "windows";
QWindowsTheme *QWindowsTheme::m_instance = 0;
QWindowsTheme::QWindowsTheme()
+ : m_threadPoolRunner(new QWindowsThreadPoolRunner)
{
m_instance = this;
std::fill(m_fonts, m_fonts + NFonts, static_cast<QFont *>(0));
@@ -364,7 +350,7 @@ static inline QStringList styleNames()
static inline int uiEffects()
{
- int result = 0;
+ int result = QPlatformTheme::HoverEffect;
if (booleanSystemParametersInfo(SPI_GETUIEFFECTS, false))
result |= QPlatformTheme::GeneralUiEffect;
if (booleanSystemParametersInfo(SPI_GETMENUANIMATION, false))
@@ -389,12 +375,10 @@ QVariant QWindowsTheme::themeHint(ThemeHint hint) const
return QVariant(iconThemeSearchPaths());
case StyleNames:
return QVariant(styleNames());
-#ifndef Q_OS_WINCE
case TextCursorWidth:
return QVariant(int(dWordSystemParametersInfo(SPI_GETCARETWIDTH, 1u)));
case DropShadow:
return QVariant(booleanSystemParametersInfo(SPI_GETDROPSHADOW, false));
-#endif // !Q_OS_WINCE
case MaximumScrollBarDragDistance:
return QVariant(qRound(qreal(QWindowsContext::instance()->defaultDPI()) * 1.375));
case KeyboardScheme:
@@ -402,7 +386,7 @@ QVariant QWindowsTheme::themeHint(ThemeHint hint) const
case UiEffects:
return QVariant(uiEffects());
case IconPixmapSizes:
- return m_fileIconSizes;
+ return QVariant::fromValue(m_fileIconSizes);
case DialogSnapToDefaultButton:
return QVariant(booleanSystemParametersInfo(SPI_GETSNAPTODEFBUTTON, false));
case ContextMenuOnMouseRelease:
@@ -445,7 +429,6 @@ void QWindowsTheme::clearFonts()
void QWindowsTheme::refreshFonts()
{
-#ifndef Q_OS_WINCE // ALL THIS FUNCTIONALITY IS MISSING ON WINCE
clearFonts();
if (!QGuiApplication::desktopSettingsAware())
return;
@@ -474,7 +457,6 @@ void QWindowsTheme::refreshFonts()
m_fonts[DockWidgetTitleFont] = new QFont(titleFont);
m_fonts[ItemViewFont] = new QFont(iconTitleFont);
m_fonts[FixedFont] = new QFont(fixedFont);
-#endif // !Q_OS_WINCE
}
enum FileIconSize {
@@ -512,15 +494,14 @@ void QWindowsTheme::refreshIconPixmapSizes()
fileIconSizes[ExtraLargeFileIcon] =
fileIconSizes[LargeFileIcon] + fileIconSizes[LargeFileIcon] / 2;
fileIconSizes[JumboFileIcon] = 8 * fileIconSizes[LargeFileIcon]; // empirical, has not been observed to work
- QList<int> sizes;
- sizes << fileIconSizes[SmallFileIcon] << fileIconSizes[LargeFileIcon];
+
#ifdef USE_IIMAGELIST
- sizes << fileIconSizes[ExtraLargeFileIcon]; // sHIL_EXTRALARGE
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)
- sizes << fileIconSizes[JumboFileIcon]; // SHIL_JUMBO
+ int *availEnd = fileIconSizes + JumboFileIcon + 1;
+#else
+ int *availEnd = fileIconSizes + LargeFileIcon + 1;
#endif // USE_IIMAGELIST
- qCDebug(lcQpaWindows) << __FUNCTION__ << sizes;
- m_fileIconSizes = QVariant::fromValue(sizes);
+ m_fileIconSizes = QAbstractFileIconEngine::toSizeList(fileIconSizes, availEnd);
+ qCDebug(lcQpaWindows) << __FUNCTION__ << m_fileIconSizes;
}
// Defined in qpixmap_win.cpp
@@ -528,12 +509,7 @@ Q_GUI_EXPORT QPixmap qt_pixmapFromWinHICON(HICON icon);
static QPixmap loadIconFromShell32(int resourceId, QSizeF size)
{
-#ifdef Q_OS_WINCE
- HMODULE hmod = LoadLibrary(L"ceshell");
-#else
- HMODULE hmod = QSystemLibrary::load(L"shell32");
-#endif
- if (hmod) {
+ if (const HMODULE hmod = QSystemLibrary::load(L"shell32")) {
HICON iconHandle =
static_cast<HICON>(LoadImage(hmod, MAKEINTRESOURCE(resourceId),
IMAGE_ICON, int(size.width()), int(size.height()), 0));
@@ -549,7 +525,7 @@ static QPixmap loadIconFromShell32(int resourceId, QSizeF size)
QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSize) const
{
int resourceId = -1;
- int stockId = SIID_INVALID;
+ SHSTOCKICONID stockId = SIID_INVALID;
UINT stockFlags = 0;
LPCTSTR iconName = 0;
switch (sp) {
@@ -575,14 +551,14 @@ QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSiz
break;
case FileLinkIcon:
stockFlags = SHGSI_LINKOVERLAY;
- // Fall through
+ Q_FALLTHROUGH();
case FileIcon:
stockId = SIID_DOCNOASSOC;
resourceId = 1;
break;
case DirLinkIcon:
stockFlags = SHGSI_LINKOVERLAY;
- // Fall through
+ Q_FALLTHROUGH();
case DirClosedIcon:
case DirIcon:
stockId = SIID_FOLDER;
@@ -596,7 +572,7 @@ QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSiz
break;
case DirLinkOpenIcon:
stockFlags = SHGSI_LINKOVERLAY;
- // Fall through
+ Q_FALLTHROUGH();
case DirOpenIcon:
stockId = SIID_FOLDEROPEN;
resourceId = 5;
@@ -612,7 +588,6 @@ QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSiz
stockId = SIID_RECYCLER;
resourceId = 191;
break;
-#ifndef Q_OS_WINCE
case MessageBoxInformation:
stockId = SIID_INFO;
iconName = IDI_INFORMATION;
@@ -632,29 +607,22 @@ QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSiz
case VistaShield:
stockId = SIID_SHIELD;
break;
-#endif
default:
break;
}
-#ifndef Q_OS_WINCE
if (stockId != SIID_INVALID) {
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA
- && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)
- && QWindowsContext::shell32dll.sHGetStockIconInfo) {
- QPixmap pixmap;
- SHSTOCKICONINFO iconInfo;
- memset(&iconInfo, 0, sizeof(iconInfo));
- iconInfo.cbSize = sizeof(iconInfo);
- stockFlags |= (pixmapSize.width() > 16 ? SHGFI_LARGEICON : SHGFI_SMALLICON);
- if (QWindowsContext::shell32dll.sHGetStockIconInfo(stockId, SHGFI_ICON | stockFlags, &iconInfo) == S_OK) {
- pixmap = qt_pixmapFromWinHICON(iconInfo.hIcon);
- DestroyIcon(iconInfo.hIcon);
- return pixmap;
- }
+ QPixmap pixmap;
+ SHSTOCKICONINFO iconInfo;
+ memset(&iconInfo, 0, sizeof(iconInfo));
+ iconInfo.cbSize = sizeof(iconInfo);
+ stockFlags |= (pixmapSize.width() > 16 ? SHGFI_LARGEICON : SHGFI_SMALLICON);
+ if (SHGetStockIconInfo(stockId, SHGFI_ICON | stockFlags, &iconInfo) == S_OK) {
+ pixmap = qt_pixmapFromWinHICON(iconInfo.hIcon);
+ DestroyIcon(iconInfo.hIcon);
+ return pixmap;
}
}
-#endif
if (resourceId != -1) {
QPixmap pixmap = loadIconFromShell32(resourceId, pixmapSize);
@@ -729,14 +697,8 @@ static QPixmap pixmapFromShellImageList(int iImageList, const SHFILEINFO &info)
// For MinGW:
static const IID iID_IImageList = {0x46eb5926, 0x582e, 0x4017, {0x9f, 0xdf, 0xe8, 0x99, 0x8d, 0xaa, 0x9, 0x50}};
- if (!QWindowsContext::shell32dll.sHGetImageList)
- return result;
- if (iImageList == sHIL_JUMBO && QSysInfo::WindowsVersion < QSysInfo::WV_VISTA)
- return result;
-
IImageList *imageList = 0;
- HRESULT hr = QWindowsContext::shell32dll.sHGetImageList(iImageList, iID_IImageList,
- reinterpret_cast<void **>(&imageList));
+ HRESULT hr = SHGetImageList(iImageList, iID_IImageList, reinterpret_cast<void **>(&imageList));
if (hr != S_OK)
return result;
HICON hIcon;
@@ -753,8 +715,46 @@ static QPixmap pixmapFromShellImageList(int iImageList, const SHFILEINFO &info)
return result;
}
-QPixmap QWindowsTheme::fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &size,
- QPlatformTheme::IconOptions iconOptions) const
+class QWindowsFileIconEngine : public QAbstractFileIconEngine
+{
+public:
+ explicit QWindowsFileIconEngine(const QFileInfo &info,
+ QPlatformTheme::IconOptions opts,
+ const QSharedPointer<QWindowsThreadPoolRunner> &runner) :
+ QAbstractFileIconEngine(info, opts), m_threadPoolRunner(runner) {}
+
+ QList<QSize> availableSizes(QIcon::Mode = QIcon::Normal, QIcon::State = QIcon::Off) const override
+ { return QWindowsTheme::instance()->availableFileIconSizes(); }
+
+protected:
+ QString cacheKey() const override;
+ QPixmap filePixmap(const QSize &size, QIcon::Mode mode, QIcon::State) override;
+
+private:
+ const QSharedPointer<QWindowsThreadPoolRunner> m_threadPoolRunner;
+};
+
+QString QWindowsFileIconEngine::cacheKey() const
+{
+ // Cache directories unless custom or drives, which have custom icons depending on type
+ if ((options() & QPlatformTheme::DontUseCustomDirectoryIcons) && fileInfo().isDir() && !fileInfo().isRoot())
+ return QStringLiteral("qt_/directory/");
+ if (!fileInfo().isFile())
+ return QString();
+ // Return "" for .exe, .lnk and .ico extensions.
+ // It is faster to just look at the file extensions;
+ // avoiding slow QFileInfo::isExecutable() (QTBUG-13182)
+ const QString &suffix = fileInfo().suffix();
+ if (!suffix.compare(QLatin1String("exe"), Qt::CaseInsensitive)
+ || !suffix.compare(QLatin1String("lnk"), Qt::CaseInsensitive)
+ || !suffix.compare(QLatin1String("ico"), Qt::CaseInsensitive)) {
+ return QString();
+ }
+ return QLatin1String("qt_.")
+ + (suffix.isEmpty() ? fileInfo().fileName() : suffix.toUpper()); // handle "Makefile" ;)
+}
+
+QPixmap QWindowsFileIconEngine::filePixmap(const QSize &size, QIcon::Mode, QIcon::State)
{
/* We don't use the variable, but by storing it statically, we
* ensure CoInitialize is only called once. */
@@ -764,10 +764,10 @@ QPixmap QWindowsTheme::fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &s
static QCache<QString, FakePointer<int> > dirIconEntryCache(1000);
static QMutex mx;
static int defaultFolderIIcon = -1;
- const bool useDefaultFolderIcon = iconOptions & QPlatformTheme::DontUseCustomDirectoryIcons;
+ const bool useDefaultFolderIcon = options() & QPlatformTheme::DontUseCustomDirectoryIcons;
QPixmap pixmap;
- const QString filePath = QDir::toNativeSeparators(fileInfo.filePath());
+ const QString filePath = QDir::toNativeSeparators(fileInfo().filePath());
const int width = int(size.width());
const int iconSize = width > fileIconSizes[SmallFileIcon] ? SHGFI_LARGEICON : SHGFI_SMALLICON;
const int requestedImageListSize =
@@ -778,7 +778,7 @@ QPixmap QWindowsTheme::fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &s
#else
0;
#endif // !USE_IIMAGELIST
- bool cacheableDirIcon = fileInfo.isDir() && !fileInfo.isRoot();
+ bool cacheableDirIcon = fileInfo().isDir() && !fileInfo().isRoot();
if (cacheableDirIcon) {
QMutexLocker locker(&mx);
int iIcon = (useDefaultFolderIcon && defaultFolderIIcon >= 0) ? defaultFolderIIcon
@@ -794,22 +794,13 @@ QPixmap QWindowsTheme::fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &s
SHFILEINFO info;
const unsigned int flags =
-#ifndef Q_OS_WINCE
SHGFI_ICON|iconSize|SHGFI_SYSICONINDEX|SHGFI_ADDOVERLAYS|SHGFI_OVERLAYINDEX;
-#else
- iconSize|SHGFI_SYSICONINDEX;
-#endif // Q_OS_WINCE
-
-#if !defined(QT_NO_WINCE_SHELLSDK)
const bool val = cacheableDirIcon && useDefaultFolderIcon
- ? shGetFileInfoBackground(m_threadPoolRunner, L"dummy", FILE_ATTRIBUTE_DIRECTORY,
+ ? shGetFileInfoBackground(*m_threadPoolRunner.data(), L"dummy", FILE_ATTRIBUTE_DIRECTORY,
&info, flags | SHGFI_USEFILEATTRIBUTES)
- : shGetFileInfoBackground(m_threadPoolRunner, reinterpret_cast<const wchar_t *>(filePath.utf16()), 0,
+ : shGetFileInfoBackground(*m_threadPoolRunner.data(), reinterpret_cast<const wchar_t *>(filePath.utf16()), 0,
&info, flags);
-#else
- const bool val = false;
-#endif // !QT_NO_WINCE_SHELLSDK
// Even if GetFileInfo returns a valid result, hIcon can be empty in some cases
if (val && info.hIcon) {
@@ -848,9 +839,12 @@ QPixmap QWindowsTheme::fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &s
DestroyIcon(info.hIcon);
}
- if (!pixmap.isNull())
- return pixmap;
- return QPlatformTheme::fileIconPixmap(fileInfo, size);
+ return pixmap;
+}
+
+QIcon QWindowsTheme::fileIcon(const QFileInfo &fileInfo, QPlatformTheme::IconOptions iconOptions) const
+{
+ return QIcon(new QWindowsFileIconEngine(fileInfo, iconOptions, m_threadPoolRunner));
}
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowstheme.h b/src/plugins/platforms/windows/qwindowstheme.h
index fa1fb4d998..0384899efa 100644
--- a/src/plugins/platforms/windows/qwindowstheme.h
+++ b/src/plugins/platforms/windows/qwindowstheme.h
@@ -43,6 +43,7 @@
#include "qwindowsthreadpoolrunner.h"
#include <qpa/qplatformtheme.h>
+#include <QtCore/QSharedPointer>
#include <QtCore/QVariant>
QT_BEGIN_NAMESPACE
@@ -66,12 +67,14 @@ public:
{ return m_fonts[type]; }
QPixmap standardPixmap(StandardPixmap sp, const QSizeF &size) const Q_DECL_OVERRIDE;
- QPixmap fileIconPixmap(const QFileInfo &fileInfo, const QSizeF &size,
- QPlatformTheme::IconOptions iconOptions = 0) const Q_DECL_OVERRIDE;
+
+ QIcon fileIcon(const QFileInfo &fileInfo, QPlatformTheme::IconOptions iconOptions = 0) const override;
void windowsThemeChanged(QWindow *window);
void displayChanged() { refreshIconPixmapSizes(); }
+ QList<QSize> availableFileIconSizes() const { return m_fileIconSizes; }
+
static const char *name;
private:
@@ -85,8 +88,8 @@ private:
static QWindowsTheme *m_instance;
QPalette *m_palettes[NPalettes];
QFont *m_fonts[NFonts];
- mutable QWindowsThreadPoolRunner m_threadPoolRunner;
- QVariant m_fileIconSizes;
+ const QSharedPointer<QWindowsThreadPoolRunner> m_threadPoolRunner;
+ QList<QSize> m_fileIconSizes;
};
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowswindow.cpp b/src/plugins/platforms/windows/qwindowswindow.cpp
index 434d0ad953..a9b061ad73 100644
--- a/src/plugins/platforms/windows/qwindowswindow.cpp
+++ b/src/plugins/platforms/windows/qwindowswindow.cpp
@@ -38,7 +38,6 @@
****************************************************************************/
#include "qwindowswindow.h"
-#include "qwindowsnativeimage.h"
#include "qwindowscontext.h"
#include "qwindowsdrag.h"
#include "qwindowsscreen.h"
@@ -62,6 +61,8 @@
#include <QtCore/QDebug>
+#include <dwmapi.h>
+
QT_BEGIN_NAMESPACE
enum {
@@ -147,7 +148,6 @@ QDebug operator<<(QDebug d, const POINT &p)
return d;
}
-# ifndef Q_OS_WINCE
QDebug operator<<(QDebug d, const NCCALCSIZE_PARAMS &p)
{
QDebugStateSaver saver(d);
@@ -178,14 +178,12 @@ QDebug operator<<(QDebug d, const WINDOWPLACEMENT &wp)
<< ", rcNormalPosition=" << wp.rcNormalPosition;
return d;
}
-# endif // !Q_OS_WINCE
#endif // !QT_NO_DEBUG_STREAM
// QTBUG-43872, for windows that do not have WS_EX_TOOLWINDOW set, WINDOWPLACEMENT
// is in workspace/available area coordinates.
static QPoint windowPlacementOffset(HWND hwnd, const QPoint &point)
{
-#ifndef Q_OS_WINCE
if (GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_TOOLWINDOW)
return QPoint(0, 0);
const QWindowsScreenManager &screenManager = QWindowsContext::instance()->screenManager();
@@ -193,10 +191,6 @@ static QPoint windowPlacementOffset(HWND hwnd, const QPoint &point)
? screenManager.screens().constFirst() : screenManager.screenAtDp(point);
if (screen)
return screen->availableGeometry().topLeft() - screen->geometry().topLeft();
-#else
- Q_UNUSED(hwnd)
- Q_UNUSED(point)
-#endif
return QPoint(0, 0);
}
@@ -205,7 +199,6 @@ static QPoint windowPlacementOffset(HWND hwnd, const QPoint &point)
static inline QRect frameGeometry(HWND hwnd, bool topLevel)
{
RECT rect = { 0, 0, 0, 0 };
-#ifndef Q_OS_WINCE
if (topLevel) {
WINDOWPLACEMENT windowPlacement;
windowPlacement.length = sizeof(WINDOWPLACEMENT);
@@ -215,7 +208,6 @@ static inline QRect frameGeometry(HWND hwnd, bool topLevel)
return result.translated(windowPlacementOffset(hwnd, result.topLeft()));
}
}
-#endif // !Q_OS_WINCE
GetWindowRect(hwnd, &rect); // Screen coordinates.
const HWND parent = GetParent(hwnd);
if (parent && !topLevel) {
@@ -236,7 +228,6 @@ static QWindow::Visibility windowVisibility_sys(HWND hwnd)
{
if (!IsWindowVisible(hwnd))
return QWindow::Hidden;
-#ifndef Q_OS_WINCE
WINDOWPLACEMENT windowPlacement;
windowPlacement.length = sizeof(WINDOWPLACEMENT);
if (GetWindowPlacement(hwnd, &windowPlacement)) {
@@ -251,7 +242,6 @@ static QWindow::Visibility windowVisibility_sys(HWND hwnd)
break;
}
}
-#endif // !Q_OS_WINCE
return QWindow::Windowed;
}
@@ -269,65 +259,27 @@ static inline bool windowIsOpenGL(const QWindow *w)
static bool applyBlurBehindWindow(HWND hwnd)
{
-#ifdef Q_OS_WINCE
- Q_UNUSED(hwnd);
- return false;
-#else
- enum { dwmBbEnable = 0x1, dwmBbBlurRegion = 0x2 };
-
- struct DwmBlurBehind {
- DWORD dwFlags;
- BOOL fEnable;
- HRGN hRgnBlur;
- BOOL fTransitionOnMaximized;
- };
-
- typedef HRESULT (WINAPI *PtrDwmEnableBlurBehindWindow)(HWND, const DwmBlurBehind*);
- typedef HRESULT (WINAPI *PtrDwmIsCompositionEnabled)(BOOL *);
-
- // DWM API is available only from Windows Vista
- if (QSysInfo::windowsVersion() < QSysInfo::WV_VISTA)
- return false;
-
- static bool functionPointersResolved = false;
- static PtrDwmEnableBlurBehindWindow dwmBlurBehind = 0;
- static PtrDwmIsCompositionEnabled dwmIsCompositionEnabled = 0;
-
- if (Q_UNLIKELY(!functionPointersResolved)) {
- QSystemLibrary library(QStringLiteral("dwmapi"));
- if (library.load()) {
- dwmBlurBehind = (PtrDwmEnableBlurBehindWindow)(library.resolve("DwmEnableBlurBehindWindow"));
- dwmIsCompositionEnabled = (PtrDwmIsCompositionEnabled)(library.resolve("DwmIsCompositionEnabled"));
- }
-
- functionPointersResolved = true;
- }
-
- if (Q_UNLIKELY(!dwmBlurBehind || !dwmIsCompositionEnabled))
- return false;
-
BOOL compositionEnabled;
- if (dwmIsCompositionEnabled(&compositionEnabled) != S_OK)
+ if (DwmIsCompositionEnabled(&compositionEnabled) != S_OK)
return false;
- DwmBlurBehind blurBehind = {0, 0, 0, 0};
+ DWM_BLURBEHIND blurBehind = {0, 0, 0, 0};
if (compositionEnabled) {
- blurBehind.dwFlags = dwmBbEnable | dwmBbBlurRegion;
+ blurBehind.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
blurBehind.fEnable = TRUE;
blurBehind.hRgnBlur = CreateRectRgn(0, 0, -1, -1);
} else {
- blurBehind.dwFlags = dwmBbEnable;
+ blurBehind.dwFlags = DWM_BB_ENABLE;
blurBehind.fEnable = FALSE;
}
- const bool result = dwmBlurBehind(hwnd, &blurBehind) == S_OK;
+ const bool result = DwmEnableBlurBehindWindow(hwnd, &blurBehind) == S_OK;
if (blurBehind.hRgnBlur)
DeleteObject(blurBehind.hRgnBlur);
return result;
-#endif // Q_OS_WINCE
}
// from qwidget_win.cpp, pass flags separately in case they have been "autofixed".
@@ -346,7 +298,6 @@ static bool shouldShowMaximizeButton(const QWindow *w, Qt::WindowFlags flags)
// Qt::WindowTransparentForInput (in combination with WS_EX_TRANSPARENT).
bool QWindowsWindow::setWindowLayered(HWND hwnd, Qt::WindowFlags flags, bool hasAlpha, qreal opacity)
{
-#ifndef Q_OS_WINCE // maybe needs revisiting WS_EX_LAYERED
const LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
const bool needsLayered = (flags & Qt::WindowTransparentForInput)
|| (hasAlpha && (flags & Qt::FramelessWindowHint)) || opacity < 1.0;
@@ -359,36 +310,22 @@ bool QWindowsWindow::setWindowLayered(HWND hwnd, Qt::WindowFlags flags, bool has
}
}
return needsLayered;
-#else // !Q_OS_WINCE
- Q_UNUSED(hwnd);
- Q_UNUSED(flags);
- Q_UNUSED(hasAlpha);
- Q_UNUSED(opacity);
- return false;
-#endif // Q_OS_WINCE
}
static void setWindowOpacity(HWND hwnd, Qt::WindowFlags flags, bool hasAlpha, bool openGL, qreal level)
{
-#ifdef Q_OS_WINCE // WINCE does not support that feature and microsoft explicitly warns to use those calls
- Q_UNUSED(hwnd);
- Q_UNUSED(flags);
- Q_UNUSED(hasAlpha);
- Q_UNUSED(level);
-#else
if (QWindowsWindow::setWindowLayered(hwnd, flags, hasAlpha, level)) {
const BYTE alpha = BYTE(qRound(255.0 * level));
if (hasAlpha && !openGL && (flags & Qt::FramelessWindowHint)) {
// Non-GL windows with alpha: Use blend function to update.
BLENDFUNCTION blend = {AC_SRC_OVER, 0, alpha, AC_SRC_ALPHA};
- QWindowsContext::user32dll.updateLayeredWindow(hwnd, NULL, NULL, NULL, NULL, NULL, 0, &blend, ULW_ALPHA);
+ UpdateLayeredWindow(hwnd, NULL, NULL, NULL, NULL, NULL, 0, &blend, ULW_ALPHA);
} else {
- QWindowsContext::user32dll.setLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA);
+ SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA);
}
} else if (IsWindowVisible(hwnd)) { // Repaint when switching from layered.
InvalidateRect(hwnd, NULL, TRUE);
}
-#endif // !Q_OS_WINCE
}
static inline void updateGLWindowSettings(const QWindow *w, HWND hwnd, Qt::WindowFlags flags, qreal opacity)
@@ -486,11 +423,9 @@ static inline void fixTopLevelWindowFlags(Qt::WindowFlags &flags)
|Qt::WindowMaximizeButtonHint|Qt::WindowCloseButtonHint;
break;
case Qt::Dialog:
- flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
- break;
case Qt::Tool:
- flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
- break;
+ flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
+ break;
default:
break;
}
@@ -604,12 +539,10 @@ void WindowCreationData::fromWindow(const QWindow *w, const Qt::WindowFlags flag
exStyle |= WS_EX_TOOLWINDOW;
}
-#ifndef Q_OS_WINCE
// make mouse events fall through this window
// NOTE: WS_EX_TRANSPARENT flag can make mouse inputs fall through a layered window
if (flagsIn & Qt::WindowTransparentForInput)
exStyle |= WS_EX_LAYERED | WS_EX_TRANSPARENT;
-#endif
}
}
@@ -650,10 +583,6 @@ QWindowsWindowData
context->frameX, context->frameY,
context->frameWidth, context->frameHeight,
parentHandle, NULL, appinst, NULL);
-#ifdef Q_OS_WINCE
- if (DisableGestures(result.hwnd, TGF_GID_ALL, TGF_SCOPE_WINDOW))
- EnableGestures(result.hwnd, TGF_GID_DIRECTMANIPULATION, TGF_SCOPE_WINDOW);
-#endif
qCDebug(lcQpaWindows).nospace()
<< "CreateWindowEx: returns " << w << ' ' << result.hwnd << " obtained geometry: "
<< context->obtainedGeometry << ' ' << context->margins;
@@ -764,9 +693,7 @@ bool QWindowsGeometryHint::validSize(const QSize &s) const
QMargins QWindowsGeometryHint::frame(DWORD style, DWORD exStyle)
{
RECT rect = {0,0,0,0};
-#ifndef Q_OS_WINCE
style &= ~(WS_OVERLAPPED); // Not permitted, see docs.
-#endif
if (!AdjustWindowRectEx(&rect, style, FALSE, exStyle))
qErrnoWarning("%s: AdjustWindowRectEx failed", __FUNCTION__);
const QMargins result(qAbs(rect.left), qAbs(rect.top),
@@ -779,7 +706,6 @@ QMargins QWindowsGeometryHint::frame(DWORD style, DWORD exStyle)
bool QWindowsGeometryHint::handleCalculateSize(const QMargins &customMargins, const MSG &msg, LRESULT *result)
{
-#ifndef Q_OS_WINCE
// NCCALCSIZE_PARAMS structure if wParam==TRUE
if (!msg.wParam || customMargins.isNull())
return false;
@@ -795,15 +721,8 @@ bool QWindowsGeometryHint::handleCalculateSize(const QMargins &customMargins, co
<< ncp->rgrc[0] << ' ' << ncp->rgrc[1] << ' ' << ncp->rgrc[2]
<< ' ' << ncp->lppos->cx << ',' << ncp->lppos->cy;
return true;
-#else
- Q_UNUSED(customMargins)
- Q_UNUSED(msg)
- Q_UNUSED(result)
- return false;
-#endif
}
-#ifndef Q_OS_WINCE
void QWindowsGeometryHint::applyToMinMaxInfo(HWND hwnd, MINMAXINFO *mmi) const
{
return applyToMinMaxInfo(DWORD(GetWindowLong(hwnd, GWL_STYLE)),
@@ -835,7 +754,6 @@ void QWindowsGeometryHint::applyToMinMaxInfo(DWORD style, DWORD exStyle, MINMAXI
<< " frame=" << margins << ' ' << frameWidth << ',' << frameHeight
<< " out " << *mmi;
}
-#endif // !Q_OS_WINCE
bool QWindowsGeometryHint::positionIncludesFrame(const QWindow *w)
{
@@ -1080,9 +998,6 @@ QWindowsWindow::QWindowsWindow(QWindow *aWindow, const QWindowsWindowData &data)
m_dropTarget(0),
m_savedStyle(0),
m_format(aWindow->requestedFormat()),
-#ifdef Q_OS_WINCE
- m_previouslyHidden(false),
-#endif
m_iconSmall(0),
m_iconBig(0),
m_surface(0)
@@ -1116,10 +1031,8 @@ QWindowsWindow::QWindowsWindow(QWindow *aWindow, const QWindowsWindowData &data)
QWindowsWindow::~QWindowsWindow()
{
setFlag(WithinDestroy);
-#ifndef Q_OS_WINCE
if (testFlag(TouchRegistered))
QWindowsContext::user32dll.unregisterTouchWindow(m_data.hwnd);
-#endif // !Q_OS_WINCE
destroyWindow();
destroyIcon();
}
@@ -1163,14 +1076,6 @@ void QWindowsWindow::destroyWindow()
m_surface = 0;
}
#endif
-#ifdef Q_OS_WINCE
- if ((m_windowState & Qt::WindowFullScreen) && !m_previouslyHidden) {
- HWND handle = FindWindow(L"HHTaskBar", L"");
- if (handle) {
- ShowWindow(handle, SW_SHOW);
- }
- }
-#endif // !Q_OS_WINCE
DestroyWindow(m_data.hwnd);
context->removeWindow(m_data.hwnd);
m_data.hwnd = 0;
@@ -1338,7 +1243,6 @@ QPoint QWindowsWindow::mapFromGlobal(const QPoint &pos) const
return pos;
}
-#ifndef Q_OS_WINCE
static inline HWND transientParentHwnd(HWND hwnd)
{
if (GetAncestor(hwnd, GA_PARENT) == GetDesktopWindow()) {
@@ -1348,15 +1252,18 @@ static inline HWND transientParentHwnd(HWND hwnd)
}
return 0;
}
-#endif // !Q_OS_WINCE
// Update the transient parent for a toplevel window. The concept does not
// really exist on Windows, the relationship is set by passing a parent along with !WS_CHILD
// to window creation or by setting the parent using GWL_HWNDPARENT (as opposed to
// SetParent, which would make it a real child).
+
+#ifndef GWL_HWNDPARENT
+# define GWL_HWNDPARENT (-8)
+#endif
+
void QWindowsWindow::updateTransientParent() const
{
-#ifndef Q_OS_WINCE
if (window()->type() == Qt::Popup)
return; // QTBUG-34503, // a popup stays on top, no parent, see also WindowCreationData::fromWindow().
// Update transient parent.
@@ -1368,7 +1275,6 @@ void QWindowsWindow::updateTransientParent() const
newTransientParent = tw->handle();
if (newTransientParent != oldTransientParent)
SetWindowLongPtr(m_data.hwnd, GWL_HWNDPARENT, LONG_PTR(newTransientParent));
-#endif // !Q_OS_WINCE
}
static inline bool testShowWithoutActivating(const QWindow *window)
@@ -1486,16 +1392,12 @@ void QWindowsWindow::handleCompositionSettingsChanged()
static QRect normalFrameGeometry(HWND hwnd)
{
-#ifndef Q_OS_WINCE
WINDOWPLACEMENT wp;
wp.length = sizeof(WINDOWPLACEMENT);
if (GetWindowPlacement(hwnd, &wp)) {
const QRect result = qrectFromRECT(wp.rcNormalPosition);
return result.translated(windowPlacementOffset(hwnd, result.topLeft()));
}
-#else
- Q_UNUSED(hwnd)
-#endif
return QRect();
}
@@ -1615,7 +1517,6 @@ void QWindowsBaseWindow::setGeometry_sys(const QRect &rect) const
<< " new frame: " << frameGeometry;
bool result = false;
-#ifndef Q_OS_WINCE
const HWND hwnd = handle();
WINDOWPLACEMENT windowPlacement;
windowPlacement.length = sizeof(WINDOWPLACEMENT);
@@ -1628,9 +1529,7 @@ void QWindowsBaseWindow::setGeometry_sys(const QRect &rect) const
RECTfromQRect(frameGeometry.translated(-windowPlacementOffset(hwnd, frameGeometry.topLeft())));
windowPlacement.showCmd = windowPlacement.showCmd == SW_SHOWMINIMIZED ? SW_SHOWMINIMIZED : SW_HIDE;
result = SetWindowPlacement(hwnd, &windowPlacement);
- } else
-#endif // !Q_OS_WINCE
- {
+ } else {
result = MoveWindow(hwnd, frameGeometry.x(), frameGeometry.y(),
frameGeometry.width(), frameGeometry.height(), true);
}
@@ -1667,6 +1566,12 @@ void QWindowsWindow::releaseDC()
}
}
+static inline bool dwmIsCompositionEnabled()
+{
+ BOOL dWmCompositionEnabled = FALSE;
+ return SUCCEEDED(DwmIsCompositionEnabled(&dWmCompositionEnabled)) && dWmCompositionEnabled == TRUE;
+}
+
bool QWindowsWindow::handleWmPaint(HWND hwnd, UINT message,
WPARAM, LPARAM)
{
@@ -1680,8 +1585,7 @@ bool QWindowsWindow::handleWmPaint(HWND hwnd, UINT message,
BeginPaint(hwnd, &ps);
// Observed painting problems with Aero style disabled (QTBUG-7865).
- // 5.8: Consider making it dependent on !DwmIsCompositionEnabled().
- if (testFlag(OpenGLSurface) && testFlag(OpenGLDoubleBuffered))
+ if (Q_UNLIKELY(testFlag(OpenGLSurface) && testFlag(OpenGLDoubleBuffered) && !dwmIsCompositionEnabled()))
SelectClipRgn(ps.hdc, NULL);
// If the a window is obscured by another window (such as a child window)
@@ -1823,18 +1727,6 @@ void QWindowsWindow::setWindowState_sys(Qt::WindowState newState)
setFlag(FrameDirty);
if ((oldState == Qt::WindowFullScreen) != (newState == Qt::WindowFullScreen)) {
-#ifdef Q_OS_WINCE
- HWND handle = FindWindow(L"HHTaskBar", L"");
- if (handle) {
- if (newState == Qt::WindowFullScreen) {
- BOOL hidden = ShowWindow(handle, SW_HIDE);
- if (!hidden)
- m_previouslyHidden = true;
- } else if (!m_previouslyHidden){
- ShowWindow(handle, SW_SHOW);
- }
- }
-#endif
if (newState == Qt::WindowFullScreen) {
#ifndef Q_FLATTEN_EXPOSE
UINT newStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_POPUP;
@@ -1846,17 +1738,13 @@ void QWindowsWindow::setWindowState_sys(Qt::WindowState newState)
// Window state but emulated by changing geometry and style.
if (!m_savedStyle) {
m_savedStyle = style();
-#ifndef Q_OS_WINCE
if (oldState == Qt::WindowMinimized || oldState == Qt::WindowMaximized) {
const QRect nf = normalFrameGeometry(m_data.hwnd);
if (nf.isValid())
m_savedFrameGeometry = nf;
} else {
-#endif
m_savedFrameGeometry = frameGeometry_sys();
-#ifndef Q_OS_WINCE
}
-#endif
}
if (m_savedStyle & WS_SYSMENU)
newStyle |= WS_SYSMENU;
@@ -1969,7 +1857,6 @@ void QWindowsWindow::propagateSizeHints()
bool QWindowsWindow::handleGeometryChangingMessage(MSG *message, const QWindow *qWindow, const QMargins &margins)
{
-#ifndef Q_OS_WINCE
if (!qWindow->isTopLevel()) // Implement hasHeightForWidth().
return false;
WINDOWPOS *windowPos = reinterpret_cast<WINDOWPOS *>(message->lParam);
@@ -1989,10 +1876,6 @@ bool QWindowsWindow::handleGeometryChangingMessage(MSG *message, const QWindow *
windowPos->cx = correctedFrameGeometry.width();
windowPos->cy = correctedFrameGeometry.height();
return true;
-#else // !Q_OS_WINCE
- Q_UNUSED(message)
- return false;
-#endif
}
bool QWindowsWindow::handleGeometryChanging(MSG *message) const
@@ -2050,15 +1933,13 @@ static inline void addRectToWinRegion(const QRect &rect, HRGN *winRegion)
static HRGN qRegionToWinRegion(const QRegion &region)
{
- const QVector<QRect> rects = region.rects();
- if (rects.isEmpty())
- return NULL;
- const int rectCount = rects.size();
- if (rectCount == 1)
- return createRectRegion(region.boundingRect());
- HRGN hRegion = createRectRegion(rects.front());
- for (int i = 1; i < rectCount; ++i)
- addRectToWinRegion(rects.at(i), &hRegion);
+ auto it = region.begin();
+ const auto end = region.end();
+ if (it == end)
+ return nullptr;
+ HRGN hRegion = createRectRegion(*it);
+ while (++it != end)
+ addRectToWinRegion(*it, &hRegion);
return hRegion;
}
@@ -2087,7 +1968,6 @@ void QWindowsWindow::requestActivateWindow()
// 'Active' state handling is based in focus since it needs to work for
// child windows as well.
if (m_data.hwnd) {
-#ifndef Q_OS_WINCE
const DWORD currentThread = GetCurrentThreadId();
bool attached = false;
DWORD foregroundThread = 0;
@@ -2104,13 +1984,10 @@ void QWindowsWindow::requestActivateWindow()
attached = AttachThreadInput(foregroundThread, currentThread, TRUE) == TRUE;
}
}
-#endif // !Q_OS_WINCE
SetForegroundWindow(m_data.hwnd);
SetFocus(m_data.hwnd);
-#ifndef Q_OS_WINCE
if (attached)
AttachThreadInput(foregroundThread, currentThread, FALSE);
-#endif // !Q_OS_WINCE
}
}
@@ -2192,7 +2069,6 @@ void QWindowsWindow::setFrameStrutEventsEnabled(bool enabled)
}
}
-#ifndef Q_OS_WINCE // maybe available on some SDKs revisit WM_GETMINMAXINFO
void QWindowsWindow::getSizeHints(MINMAXINFO *mmi) const
{
const QWindowsGeometryHint hint(window(), m_data.customMargins);
@@ -2263,8 +2139,6 @@ bool QWindowsWindow::handleNonClientHitTest(const QPoint &globalPos, LRESULT *re
return false;
}
-#endif // !Q_OS_WINCE
-
#ifndef QT_NO_CURSOR
// Return the default cursor (Arrow) from QWindowsCursor's cache.
static inline CursorHandlePtr defaultCursor(const QWindow *w)
@@ -2331,7 +2205,6 @@ void QWindowsWindow::setCursor(const CursorHandlePtr &c)
#endif
}
-#ifndef Q_OS_WINCE
void QWindowsWindow::setAlertState(bool enabled)
{
if (isAlertState() == enabled)
@@ -2370,7 +2243,6 @@ void QWindowsWindow::stopAlertWindow()
info.uCount = 0;
FlashWindowEx(&info);
}
-#endif // !Q_OS_WINCE
bool QWindowsWindow::isEnabled() const
{
@@ -2486,7 +2358,6 @@ void QWindowsWindow::setTouchWindowTouchTypeStatic(QWindow *window, QWindowsWind
void QWindowsWindow::registerTouchWindow(QWindowsWindowFunctions::TouchWindowTouchTypes touchTypes)
{
-#ifndef Q_OS_WINCE
if ((QWindowsContext::instance()->systemInfo() & QWindowsContext::SI_SupportsTouch)) {
ULONG touchFlags = 0;
const bool ret = QWindowsContext::user32dll.isTouchWindow(m_data.hwnd, &touchFlags);
@@ -2499,7 +2370,6 @@ void QWindowsWindow::registerTouchWindow(QWindowsWindowFunctions::TouchWindowTou
else
qErrnoWarning("RegisterTouchWindow() failed for window '%s'.", qPrintable(window()->objectName()));
}
-#endif // !Q_OS_WINCE
}
void QWindowsWindow::aboutToMakeCurrent()
diff --git a/src/plugins/platforms/windows/qwindowswindow.h b/src/plugins/platforms/windows/qwindowswindow.h
index df7d2295a9..924f242e6e 100644
--- a/src/plugins/platforms/windows/qwindowswindow.h
+++ b/src/plugins/platforms/windows/qwindowswindow.h
@@ -40,10 +40,7 @@
#ifndef QWINDOWSWINDOW_H
#define QWINDOWSWINDOW_H
-#include "qtwindows_additional.h"
-#ifdef Q_OS_WINCE
-# include "qplatformfunctions_wince.h"
-#endif
+#include <QtCore/qt_windows.h>
#include "qwindowscursor.h"
#include <qpa/qplatformwindow.h>
@@ -60,10 +57,8 @@ struct QWindowsGeometryHint
explicit QWindowsGeometryHint(const QWindow *w, const QMargins &customMargins);
static QMargins frame(DWORD style, DWORD exStyle);
static bool handleCalculateSize(const QMargins &customMargins, const MSG &msg, LRESULT *result);
-#ifndef Q_OS_WINCE //MinMax maybe define struct if not available
void applyToMinMaxInfo(DWORD style, DWORD exStyle, MINMAXINFO *mmi) const;
void applyToMinMaxInfo(HWND hwnd, MINMAXINFO *mmi) const;
-#endif
bool validSize(const QSize &s) const;
static inline QPoint mapToGlobal(HWND hwnd, const QPoint &);
@@ -83,10 +78,8 @@ struct QWindowCreationContext
QWindowCreationContext(const QWindow *w, const QRect &r,
const QMargins &customMargins,
DWORD style, DWORD exStyle);
-#ifndef Q_OS_WINCE //MinMax maybe define struct if not available
void applyToMinMaxInfo(MINMAXINFO *mmi) const
{ geometryHint.applyToMinMaxInfo(style, exStyle, mmi); }
-#endif
QWindowsGeometryHint geometryHint;
const QWindow *window;
@@ -293,10 +286,8 @@ public:
HDC getDC();
void releaseDC();
-#ifndef Q_OS_WINCE // maybe available on some SDKs revisit WM_GETMINMAXINFO
void getSizeHints(MINMAXINFO *mmi) const;
bool handleNonClientHitTest(const QPoint &globalPos, LRESULT *result) const;
-#endif // !Q_OS_WINCE
#ifndef QT_NO_CURSOR
CursorHandlePtr cursor() const { return m_cursor; }
@@ -316,12 +307,10 @@ public:
void invalidateSurface() Q_DECL_OVERRIDE;
void aboutToMakeCurrent();
-#ifndef Q_OS_WINCE
void setAlertState(bool enabled) Q_DECL_OVERRIDE;
bool isAlertState() const Q_DECL_OVERRIDE { return testFlag(AlertState); }
void alertWindow(int durationMs = 0);
void stopAlertWindow();
-#endif
static void setTouchWindowTouchTypeStatic(QWindow *window, QWindowsWindowFunctions::TouchWindowTouchTypes touchTypes);
void registerTouchWindow(QWindowsWindowFunctions::TouchWindowTouchTypes touchTypes = QWindowsWindowFunctions::NormalTouch);
@@ -357,9 +346,6 @@ private:
unsigned m_savedStyle;
QRect m_savedFrameGeometry;
const QSurfaceFormat m_format;
-#ifdef Q_OS_WINCE
- bool m_previouslyHidden;
-#endif
HICON m_iconSmall;
HICON m_iconBig;
void *m_surface;
@@ -368,11 +354,9 @@ private:
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug d, const RECT &r);
QDebug operator<<(QDebug d, const POINT &);
-# ifndef Q_OS_WINCE
QDebug operator<<(QDebug d, const MINMAXINFO &i);
QDebug operator<<(QDebug d, const NCCALCSIZE_PARAMS &p);
QDebug operator<<(QDebug d, const WINDOWPLACEMENT &);
-# endif // !Q_OS_WINCE
#endif // !QT_NO_DEBUG_STREAM
// ---------- QWindowsGeometryHint inline functions.
@@ -436,11 +420,7 @@ inline void QWindowsWindow::destroyIcon()
inline bool QWindowsWindow::isLayered() const
{
-#ifndef Q_OS_WINCE
return GetWindowLongPtr(m_data.hwnd, GWL_EXSTYLE) & WS_EX_LAYERED;
-#else
- return false;
-#endif
}
QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/windows.pri b/src/plugins/platforms/windows/windows.pri
index 48c53592d6..d97e49309f 100644
--- a/src/plugins/platforms/windows/windows.pri
+++ b/src/plugins/platforms/windows/windows.pri
@@ -1,35 +1,20 @@
# Note: OpenGL32 must precede Gdi32 as it overwrites some functions.
-LIBS *= -lole32
-!wince: LIBS *= -luser32 -lwinspool -limm32 -lwinmm -loleaut32
+LIBS += -lole32 -luser32 -lwinspool -limm32 -lwinmm -loleaut32
-contains(QT_CONFIG, opengl):!contains(QT_CONFIG, opengles2):!contains(QT_CONFIG, dynamicgl): LIBS *= -lopengl32
+qtConfig(opengl):!qtConfig(opengles2):!qtConfig(dynamicgl): LIBS *= -lopengl32
mingw: LIBS *= -luuid
# For the dialog helpers:
-!wince: LIBS *= -lshlwapi -lshell32
-!wince: LIBS *= -ladvapi32
-wince: DEFINES *= QT_LIBINFIX=L"\"\\\"$${QT_LIBINFIX}\\\"\""
+LIBS += -lshlwapi -lshell32 -ladvapi32
DEFINES *= QT_NO_CAST_FROM_ASCII
-contains(QT_CONFIG, directwrite) {
- contains(QT_CONFIG, directwrite2): \
- DEFINES *= QT_USE_DIRECTWRITE2
-
- SOURCES += $$PWD/qwindowsfontenginedirectwrite.cpp
- HEADERS += $$PWD/qwindowsfontenginedirectwrite.h
-} else {
- DEFINES *= QT_NO_DIRECTWRITE
-}
-
SOURCES += \
$$PWD/qwindowswindow.cpp \
$$PWD/qwindowsintegration.cpp \
$$PWD/qwindowscontext.cpp \
$$PWD/qwindowsscreen.cpp \
$$PWD/qwindowskeymapper.cpp \
- $$PWD/qwindowsfontengine.cpp \
- $$PWD/qwindowsfontdatabase.cpp \
$$PWD/qwindowsmousehandler.cpp \
$$PWD/qwindowsole.cpp \
$$PWD/qwindowsmime.cpp \
@@ -39,7 +24,6 @@ SOURCES += \
$$PWD/qwindowstheme.cpp \
$$PWD/qwindowsdialoghelpers.cpp \
$$PWD/qwindowsservices.cpp \
- $$PWD/qwindowsnativeimage.cpp \
$$PWD/qwindowsnativeinterface.cpp \
$$PWD/qwindowsopengltester.cpp
@@ -49,11 +33,8 @@ HEADERS += \
$$PWD/qwindowscontext.h \
$$PWD/qwindowsscreen.h \
$$PWD/qwindowskeymapper.h \
- $$PWD/qwindowsfontengine.h \
- $$PWD/qwindowsfontdatabase.h \
$$PWD/qwindowsmousehandler.h \
$$PWD/qtwindowsglobal.h \
- $$PWD/qtwindows_additional.h \
$$PWD/qwindowsole.h \
$$PWD/qwindowsmime.h \
$$PWD/qwindowsinternalmimedata.h \
@@ -62,26 +43,24 @@ HEADERS += \
$$PWD/qwindowstheme.h \
$$PWD/qwindowsdialoghelpers.h \
$$PWD/qwindowsservices.h \
- $$PWD/qplatformfunctions_wince.h \
- $$PWD/qwindowsnativeimage.h \
$$PWD/qwindowsnativeinterface.h \
$$PWD/qwindowsopengltester.h \
$$PWD/qwindowsthreadpoolrunner.h
INCLUDEPATH += $$PWD
-contains(QT_CONFIG,opengl): HEADERS += $$PWD/qwindowsopenglcontext.h
+qtConfig(opengl): HEADERS += $$PWD/qwindowsopenglcontext.h
-contains(QT_CONFIG, opengles2) {
+qtConfig(opengles2) {
SOURCES += $$PWD/qwindowseglcontext.cpp
HEADERS += $$PWD/qwindowseglcontext.h
-} else: contains(QT_CONFIG,opengl) {
+} else: qtConfig(opengl) {
SOURCES += $$PWD/qwindowsglcontext.cpp
HEADERS += $$PWD/qwindowsglcontext.h
}
# Dynamic GL needs both WGL and EGL
-contains(QT_CONFIG,dynamicgl) {
+qtConfig(dynamicgl) {
SOURCES += $$PWD/qwindowseglcontext.cpp
HEADERS += $$PWD/qwindowseglcontext.h
}
@@ -101,40 +80,22 @@ contains(QT_CONFIG,dynamicgl) {
}
}
-!wince:!contains( DEFINES, QT_NO_TABLETEVENT ) {
+!contains( DEFINES, QT_NO_TABLETEVENT ) {
INCLUDEPATH += $$QT_SOURCE_TREE/src/3rdparty/wintab
HEADERS += $$PWD/qwindowstabletsupport.h
SOURCES += $$PWD/qwindowstabletsupport.cpp
}
-!wince:!contains( DEFINES, QT_NO_SESSIONMANAGER ) {
+!contains( DEFINES, QT_NO_SESSIONMANAGER ) {
SOURCES += $$PWD/qwindowssessionmanager.cpp
HEADERS += $$PWD/qwindowssessionmanager.h
}
-!wince:!contains( DEFINES, QT_NO_IMAGEFORMAT_PNG ) {
- RESOURCES += $$PWD/cursors.qrc
-}
+!contains( DEFINES, QT_NO_IMAGEFORMAT_PNG ):RESOURCES += $$PWD/cursors.qrc
-!wince: RESOURCES += $$PWD/openglblacklists.qrc
-
-contains(QT_CONFIG, freetype) {
- DEFINES *= QT_NO_FONTCONFIG
- include($$QT_SOURCE_TREE/src/3rdparty/freetype_dependency.pri)
- HEADERS += \
- $$PWD/qwindowsfontdatabase_ft.h
- SOURCES += \
- $$PWD/qwindowsfontdatabase_ft.cpp
-} else:contains(QT_CONFIG, system-freetype) {
- CONFIG += qpa/basicunixfontdatabase
- include($$QT_SOURCE_TREE/src/platformsupport/fontdatabases/basic/basic.pri)
- HEADERS += \
- $$PWD/qwindowsfontdatabase_ft.h
- SOURCES += \
- $$PWD/qwindowsfontdatabase_ft.cpp
-}
+RESOURCES += $$PWD/openglblacklists.qrc
-contains(QT_CONFIG, accessibility):include($$PWD/accessible/accessible.pri)
+qtConfig(accessibility): include($$PWD/accessible/accessible.pri)
DEFINES *= LIBEGL_NAME=$${LIBEGL_NAME}
DEFINES *= LIBGLESV2_NAME=$${LIBGLESV2_NAME}
diff --git a/src/plugins/platforms/windows/windows.pro b/src/plugins/platforms/windows/windows.pro
index 2e0f723693..23168c10dc 100644
--- a/src/plugins/platforms/windows/windows.pro
+++ b/src/plugins/platforms/windows/windows.pro
@@ -1,10 +1,11 @@
TARGET = qwindows
-QT *= core-private
-QT *= gui-private
-QT *= platformsupport-private
+QT += \
+ core-private gui-private \
+ eventdispatcher_support-private accessibility_support-private \
+ fontdatabase_support-private theme_support-private
-!wince:LIBS *= -lgdi32
+LIBS += -lgdi32 -ldwmapi
include(windows.pri)
diff --git a/src/plugins/platforms/winrt/qwinrteglcontext.cpp b/src/plugins/platforms/winrt/qwinrteglcontext.cpp
index 5c3ecd8726..8a250c516a 100644
--- a/src/plugins/platforms/winrt/qwinrteglcontext.cpp
+++ b/src/plugins/platforms/winrt/qwinrteglcontext.cpp
@@ -51,8 +51,8 @@
#include <QOffscreenSurface>
#include <QOpenGLContext>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-#include <QtPlatformSupport/private/qeglpbuffer_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglpbuffer_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtfontdatabase.cpp b/src/plugins/platforms/winrt/qwinrtfontdatabase.cpp
deleted file mode 100644
index d4f2ba1bd6..0000000000
--- a/src/plugins/platforms/winrt/qwinrtfontdatabase.cpp
+++ /dev/null
@@ -1,491 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwinrtfontdatabase.h"
-
-#include <QtCore/QCoreApplication>
-#include <QtCore/QFile>
-
-#include <QtCore/QUuid>
-#include <QtGui/private/qfontengine_ft_p.h>
-#include <dwrite_1.h>
-#include <wrl.h>
-using namespace Microsoft::WRL;
-
-QT_BEGIN_NAMESPACE
-
-Q_LOGGING_CATEGORY(lcQpaFonts, "qt.qpa.fonts")
-
-QDebug operator<<(QDebug d, const QFontDef &def)
-{
- QDebugStateSaver saver(d);
- d.nospace();
- d << "Family=" << def.family << " Stylename=" << def.styleName
- << " pointsize=" << def.pointSize << " pixelsize=" << def.pixelSize
- << " styleHint=" << def.styleHint << " weight=" << def.weight
- << " stretch=" << def.stretch << " hintingPreference="
- << def.hintingPreference;
- return d;
-}
-
-// Based on unicode range tables at http://www.microsoft.com/typography/otspec/os2.htm#ur
-static QFontDatabase::WritingSystem writingSystemFromUnicodeRange(const DWRITE_UNICODE_RANGE &range)
-{
- if (range.first >= 0x0000 && range.last <= 0x007F)
- return QFontDatabase::Latin;
- if (range.first >= 0x0370 && range.last <= 0x03FF)
- return QFontDatabase::Greek;
- if (range.first >= 0x0400 && range.last <= 0x04FF)
- return QFontDatabase::Cyrillic;
- if (range.first >= 0x0530 && range.last <= 0x058F)
- return QFontDatabase::Armenian;
- if (range.first >= 0x0590 && range.last <= 0x05FF)
- return QFontDatabase::Hebrew;
- if (range.first >= 0x0600 && range.last <= 0x06FF)
- return QFontDatabase::Arabic;
- if (range.first >= 0x0700 && range.last <= 0x074F)
- return QFontDatabase::Syriac;
- if (range.first >= 0x0780 && range.last <= 0x07BF)
- return QFontDatabase::Thaana;
- if (range.first >= 0x0900 && range.last <= 0x097F)
- return QFontDatabase::Devanagari;
- if (range.first >= 0x0980 && range.last <= 0x09FF)
- return QFontDatabase::Bengali;
- if (range.first >= 0x0A00 && range.last <= 0x0A7F)
- return QFontDatabase::Gurmukhi;
- if (range.first >= 0x0A80 && range.last <= 0x0AFF)
- return QFontDatabase::Gujarati;
- if (range.first >= 0x0B00 && range.last <= 0x0B7F)
- return QFontDatabase::Oriya;
- if (range.first >= 0x0B80 && range.last <= 0x0BFF)
- return QFontDatabase::Tamil;
- if (range.first >= 0x0C00 && range.last <= 0x0C7F)
- return QFontDatabase::Telugu;
- if (range.first >= 0x0C80 && range.last <= 0x0CFF)
- return QFontDatabase::Kannada;
- if (range.first >= 0x0D00 && range.last <= 0x0D7F)
- return QFontDatabase::Malayalam;
- if (range.first >= 0x0D80 && range.last <= 0x0DFF)
- return QFontDatabase::Sinhala;
- if (range.first >= 0x0E00 && range.last <= 0x0E7F)
- return QFontDatabase::Thai;
- if (range.first >= 0x0E80 && range.last <= 0x0EFF)
- return QFontDatabase::Lao;
- if (range.first >= 0x0F00 && range.last <= 0x0FFF)
- return QFontDatabase::Tibetan;
- if (range.first >= 0x1000 && range.last <= 0x109F)
- return QFontDatabase::Myanmar;
- if (range.first >= 0x10A0 && range.last <= 0x10FF)
- return QFontDatabase::Georgian;
- if (range.first >= 0x1780 && range.last <= 0x17FF)
- return QFontDatabase::Khmer;
- if (range.first >= 0x4E00 && range.last <= 0x9FFF)
- return QFontDatabase::SimplifiedChinese;
- if (range.first >= 0xAC00 && range.last <= 0xD7AF)
- return QFontDatabase::Korean;
- if (range.first >= 0x1680 && range.last <= 0x169F)
- return QFontDatabase::Ogham;
- if (range.first >= 0x16A0 && range.last <= 0x16FF)
- return QFontDatabase::Runic;
- if (range.first >= 0x07C0 && range.last <= 0x07FF)
- return QFontDatabase::Nko;
-
- return QFontDatabase::Other;
-}
-
-QString QWinRTFontDatabase::fontDir() const
-{
- qCDebug(lcQpaFonts) << __FUNCTION__;
- QString fontDirectory = QBasicFontDatabase::fontDir();
- if (!QFile::exists(fontDirectory)) {
- // Fall back to app directory + fonts, and just app directory after that
- const QString applicationDirPath = QCoreApplication::applicationDirPath();
- fontDirectory = applicationDirPath + QLatin1String("/fonts");
- if (!QFile::exists(fontDirectory)) {
- if (m_fontFamilies.isEmpty())
- qWarning("No fonts directory found in application package.");
- fontDirectory = applicationDirPath;
- }
- }
- return fontDirectory;
-}
-
-QWinRTFontDatabase::~QWinRTFontDatabase()
-{
- qCDebug(lcQpaFonts) << __FUNCTION__;
-
- foreach (IDWriteFontFile *fontFile, m_fonts.keys())
- fontFile->Release();
-
- foreach (IDWriteFontFamily *fontFamily, m_fontFamilies)
- fontFamily->Release();
-}
-
-QFont QWinRTFontDatabase::defaultFont() const
-{
- return QFont(QStringLiteral("Segoe UI"));
-}
-
-bool QWinRTFontDatabase::fontsAlwaysScalable() const
-{
- return true;
-}
-
-void QWinRTFontDatabase::populateFontDatabase()
-{
- qCDebug(lcQpaFonts) << __FUNCTION__;
-
- ComPtr<IDWriteFactory1> factory;
- HRESULT hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_ISOLATED, __uuidof(IDWriteFactory1), &factory);
- if (FAILED(hr)) {
- qWarning("Failed to create DirectWrite factory: %s", qPrintable(qt_error_string(hr)));
- QBasicFontDatabase::populateFontDatabase();
- return;
- }
-
- ComPtr<IDWriteFontCollection> fontCollection;
- hr = factory->GetSystemFontCollection(&fontCollection);
- if (FAILED(hr)) {
- qWarning("Failed to open system font collection: %s", qPrintable(qt_error_string(hr)));
- QBasicFontDatabase::populateFontDatabase();
- return;
- }
-
- int fontFamilyCount = fontCollection->GetFontFamilyCount();
- for (int i = 0; i < fontFamilyCount; ++i) {
- ComPtr<IDWriteFontFamily> fontFamily;
- hr = fontCollection->GetFontFamily(i, &fontFamily);
- if (FAILED(hr)) {
- qWarning("Unable to get font family: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
-
- ComPtr<IDWriteLocalizedStrings> names;
- hr = fontFamily->GetFamilyNames(&names);
- if (FAILED(hr)) {
- qWarning("Unable to get font family names: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
- quint32 familyNameLength;
- hr = names->GetStringLength(0, &familyNameLength);
- if (FAILED(hr)) {
- qWarning("Unable to get family name length: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
- QVector<wchar_t> familyBuffer(familyNameLength + 1);
- hr = names->GetString(0, familyBuffer.data(), familyBuffer.size());
- if (FAILED(hr)) {
- qWarning("Unable to create font family name: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
- QString familyName = QString::fromWCharArray(familyBuffer.data(), familyNameLength);
-
- m_fontFamilies.insert(familyName, fontFamily.Detach());
-
- registerFontFamily(familyName);
- }
-
- QBasicFontDatabase::populateFontDatabase();
-}
-
-void QWinRTFontDatabase::populateFamily(const QString &familyName)
-{
- qCDebug(lcQpaFonts) << __FUNCTION__ << familyName;
-
- IDWriteFontFamily *fontFamily = m_fontFamilies.value(familyName);
- if (!fontFamily) {
- qWarning("The font family %s was not found.", qPrintable(familyName));
- return;
- }
-
- bool fontRegistered = false;
- const int fontCount = fontFamily->GetFontCount();
- for (int j = 0; j < fontCount; ++j) {
- ComPtr<IDWriteFont> font;
- HRESULT hr = fontFamily->GetFont(j, &font);
- if (FAILED(hr)) {
- qWarning("Unable to get font: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
-
- // Skip simulated faces
- if (font->GetSimulations() != DWRITE_FONT_SIMULATIONS_NONE)
- continue;
-
- ComPtr<IDWriteFontFace> baseFontFace;
- hr = font->CreateFontFace(&baseFontFace);
- if (FAILED(hr)) {
- qWarning("Unable to create base font face: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
- ComPtr<IDWriteFontFace1> fontFace;
- hr = baseFontFace.As(&fontFace);
- if (FAILED(hr)) {
- qWarning("Unable to create font face: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
-
- // We can't deal with multi-file fonts
- quint32 fileCount;
- hr = fontFace->GetFiles(&fileCount, NULL);
- if (FAILED(hr)) {
- qWarning("Unable to get font file count: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
- if (fileCount != 1)
- continue;
-
- ComPtr<IDWriteLocalizedStrings> informationalStrings;
- BOOL exists;
- hr = font->GetInformationalStrings(DWRITE_INFORMATIONAL_STRING_MANUFACTURER,
- &informationalStrings, &exists);
- if (FAILED(hr)) {
- qWarning("Unable to get font foundry: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
- QString foundryName;
- if (exists) {
- quint32 length;
- hr = informationalStrings->GetStringLength(0, &length);
- if (FAILED(hr))
- qWarning("Unable to get foundry name length: %s", qPrintable(qt_error_string(hr)));
- if (SUCCEEDED(hr)) {
- QVector<wchar_t> buffer(length + 1);
- hr = informationalStrings->GetString(0, buffer.data(), buffer.size());
- if (FAILED(hr))
- qWarning("Unable to get foundry name: %s", qPrintable(qt_error_string(hr)));
- if (SUCCEEDED(hr))
- foundryName = QString::fromWCharArray(buffer.data(), length);
- }
- }
-
- QFont::Weight weight = QPlatformFontDatabase::weightFromInteger(font->GetWeight());
-
- QFont::Style style;
- switch (font->GetStyle()) {
- default:
- case DWRITE_FONT_STYLE_NORMAL:
- style = QFont::StyleNormal;
- break;
- case DWRITE_FONT_STYLE_OBLIQUE:
- style = QFont::StyleOblique;
- break;
- case DWRITE_FONT_STYLE_ITALIC:
- style = QFont::StyleItalic;
- break;
- }
-
- QFont::Stretch stretch;
- switch (font->GetStretch()) {
- default:
- case DWRITE_FONT_STRETCH_UNDEFINED:
- case DWRITE_FONT_STRETCH_NORMAL:
- stretch = QFont::Unstretched;
- break;
- case DWRITE_FONT_STRETCH_ULTRA_CONDENSED:
- stretch = QFont::UltraCondensed;
- break;
- case DWRITE_FONT_STRETCH_EXTRA_CONDENSED:
- stretch = QFont::ExtraCondensed;
- break;
- case DWRITE_FONT_STRETCH_CONDENSED:
- stretch = QFont::Condensed;
- break;
- case DWRITE_FONT_STRETCH_SEMI_CONDENSED:
- stretch = QFont::SemiCondensed;
- break;
- case DWRITE_FONT_STRETCH_SEMI_EXPANDED:
- stretch = QFont::SemiExpanded;
- break;
- case DWRITE_FONT_STRETCH_EXPANDED:
- stretch = QFont::Expanded;
- break;
- case DWRITE_FONT_STRETCH_EXTRA_EXPANDED:
- stretch = QFont::ExtraExpanded;
- break;
- case DWRITE_FONT_STRETCH_ULTRA_EXPANDED:
- stretch = QFont::UltraExpanded;
- break;
- }
-
- const bool fixedPitch = fontFace->IsMonospacedFont();
-
- // Get writing systems from unicode ranges
- quint32 actualRangeCount;
- hr = fontFace->GetUnicodeRanges(0, nullptr, &actualRangeCount);
- Q_ASSERT(hr == E_NOT_SUFFICIENT_BUFFER);
- QVector<DWRITE_UNICODE_RANGE> unicodeRanges(actualRangeCount);
- hr = fontFace->GetUnicodeRanges(actualRangeCount, unicodeRanges.data(), &actualRangeCount);
- if (FAILED(hr)) {
- qWarning("Unable to get font unicode range: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
- QSupportedWritingSystems writingSystems;
- for (quint32 i = 0; i < actualRangeCount; ++i) {
- const QFontDatabase::WritingSystem writingSystem = writingSystemFromUnicodeRange(unicodeRanges.at(i));
- writingSystems.setSupported(writingSystem);
- }
- if (writingSystems.supported(QFontDatabase::SimplifiedChinese)) {
- writingSystems.setSupported(QFontDatabase::TraditionalChinese);
- writingSystems.setSupported(QFontDatabase::Japanese);
- }
- if (writingSystems.supported(QFontDatabase::Latin))
- writingSystems.setSupported(QFontDatabase::Vietnamese);
-
- IDWriteFontFile *fontFile;
- hr = fontFace->GetFiles(&fileCount, &fontFile);
- if (FAILED(hr)) {
- qWarning("Unable to get font file: %s", qPrintable(qt_error_string(hr)));
- continue;
- }
-
- FontDescription description = { fontFace->GetIndex(), QUuid::createUuid().toByteArray() };
- m_fonts.insert(fontFile, description);
- registerFont(familyName, QString(), foundryName, weight, style, stretch,
- true, true, 0, fixedPitch, writingSystems, fontFile);
- fontRegistered = true;
- }
-
- // Always populate something to avoid an assert
- if (!fontRegistered) {
- registerFont(familyName, QString(), QString(), QFont::Normal, QFont::StyleNormal,
- QFont::Unstretched, false, false, 0, false, QSupportedWritingSystems(), 0);
- }
-}
-
-QFontEngine *QWinRTFontDatabase::fontEngine(const QFontDef &fontDef, void *handle)
-{
- qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDEF" << fontDef << handle;
-
- if (!handle) // Happens if a font family population failed
- return 0;
-
- IDWriteFontFile *fontFile = reinterpret_cast<IDWriteFontFile *>(handle);
- if (!m_fonts.contains(fontFile))
- return QBasicFontDatabase::fontEngine(fontDef, handle);
-
- const void *referenceKey;
- quint32 referenceKeySize;
- HRESULT hr = fontFile->GetReferenceKey(&referenceKey, &referenceKeySize);
- if (FAILED(hr)) {
- qWarning("Unable to get font file reference key: %s", qPrintable(qt_error_string(hr)));
- return 0;
- }
-
- ComPtr<IDWriteFontFileLoader> loader;
- hr = fontFile->GetLoader(&loader);
- if (FAILED(hr)) {
- qWarning("Unable to get font file loader: %s", qPrintable(qt_error_string(hr)));
- return 0;
- }
-
- ComPtr<IDWriteFontFileStream> stream;
- hr =loader->CreateStreamFromKey(referenceKey, referenceKeySize, &stream);
- if (FAILED(hr)) {
- qWarning("Unable to get font file stream: %s", qPrintable(qt_error_string(hr)));
- return 0;
- }
-
- quint64 fileSize;
- hr = stream->GetFileSize(&fileSize);
- if (FAILED(hr)) {
- qWarning("Unable to get font file size: %s", qPrintable(qt_error_string(hr)));
- return 0;
- }
-
- const void *data;
- void *context;
- hr = stream->ReadFileFragment(&data, 0, fileSize, &context);
- if (FAILED(hr)) {
- qWarning("Unable to get font file data: %s", qPrintable(qt_error_string(hr)));
- return 0;
- }
- const QByteArray fontData((const char *)data, fileSize);
- stream->ReleaseFileFragment(context);
-
- QFontEngine::FaceId faceId;
- const FontDescription description = m_fonts.value(fontFile);
- faceId.uuid = description.uuid;
- faceId.index = description.index;
- const bool antialias = !(fontDef.styleStrategy & QFont::NoAntialias);
- QFontEngineFT::GlyphFormat format = antialias ? QFontEngineFT::Format_A8 : QFontEngineFT::Format_Mono;
- QFontEngineFT *engine = new QFontEngineFT(fontDef);
- if (!engine->init(faceId, antialias, format, fontData) || engine->invalid()) {
- delete engine;
- return 0;
- }
-
- return engine;
-}
-
-QStringList QWinRTFontDatabase::fallbacksForFamily(const QString &family, QFont::Style style,
- QFont::StyleHint styleHint,
- QChar::Script script) const
-{
- Q_UNUSED(style)
- Q_UNUSED(styleHint)
- Q_UNUSED(script)
-
- qCDebug(lcQpaFonts) << __FUNCTION__ << family;
-
- QStringList result;
- if (family == QLatin1String("Helvetica"))
- result.append(QStringLiteral("Arial"));
- result.append(QBasicFontDatabase::fallbacksForFamily(family, style, styleHint, script));
- return result;
-}
-
-void QWinRTFontDatabase::releaseHandle(void *handle)
-{
- qCDebug(lcQpaFonts) << __FUNCTION__ << handle;
-
- if (!handle)
- return;
-
- IDWriteFontFile *fontFile = reinterpret_cast<IDWriteFontFile *>(handle);
- if (m_fonts.contains(fontFile)) {
- m_fonts.remove(fontFile);
- fontFile->Release();
- return;
- }
-
- QBasicFontDatabase::releaseHandle(handle);
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtinputcontext.cpp b/src/plugins/platforms/winrt/qwinrtinputcontext.cpp
index 3f476556ee..63e5b0cf27 100644
--- a/src/plugins/platforms/winrt/qwinrtinputcontext.cpp
+++ b/src/plugins/platforms/winrt/qwinrtinputcontext.cpp
@@ -39,6 +39,7 @@
#include "qwinrtinputcontext.h"
#include "qwinrtscreen.h"
+#include <QtGui/QGuiApplication>
#include <QtGui/QWindow>
#include <private/qeventdispatcher_winrt_p.h>
@@ -59,7 +60,7 @@ QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcQpaInputMethods, "qt.qpa.input.methods")
-inline QRectF getInputPaneRect(IInputPane *pane, qreal scaleFactor)
+inline QRectF getInputPaneRect(ComPtr<IInputPane> pane, qreal scaleFactor)
{
Rect rect;
pane->get_OccludedRect(&rect);
@@ -85,28 +86,33 @@ QWinRTInputContext::QWinRTInputContext(QWinRTScreen *screen)
{
qCDebug(lcQpaInputMethods) << __FUNCTION__ << screen;
- IInputPaneStatics *statics;
- if (FAILED(GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_ViewManagement_InputPane).Get(),
- &statics))) {
- qWarning("failed to retrieve input pane statics.");
- return;
- }
+ QEventDispatcherWinRT::runOnXamlThread([this]() {
+ ComPtr<IInputPaneStatics> statics;
+ if (FAILED(GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_ViewManagement_InputPane).Get(),
+ &statics))) {
+ qWarning("failed to retrieve input pane statics.");
+ return S_OK;
+ }
+
+ ComPtr<IInputPane> inputPane;
+ statics->GetForCurrentView(&inputPane);
+ if (inputPane) {
+ EventRegistrationToken showToken, hideToken;
+ inputPane->add_Showing(Callback<InputPaneVisibilityHandler>(
+ this, &QWinRTInputContext::onShowing).Get(), &showToken);
+ inputPane->add_Hiding(Callback<InputPaneVisibilityHandler>(
+ this, &QWinRTInputContext::onHiding).Get(), &hideToken);
+
+ m_keyboardRect = getInputPaneRect(inputPane, m_screen->scaleFactor());
+ m_isInputPanelVisible = !m_keyboardRect.isEmpty();
+ } else {
+ qWarning("failed to retrieve InputPane.");
+ }
+ return S_OK;
+ });
- IInputPane *inputPane;
- statics->GetForCurrentView(&inputPane);
- statics->Release();
- if (inputPane) {
- EventRegistrationToken showToken, hideToken;
- inputPane->add_Showing(Callback<InputPaneVisibilityHandler>(
- this, &QWinRTInputContext::onShowing).Get(), &showToken);
- inputPane->add_Hiding(Callback<InputPaneVisibilityHandler>(
- this, &QWinRTInputContext::onHiding).Get(), &hideToken);
-
- m_keyboardRect = getInputPaneRect(inputPane, m_screen->scaleFactor());
- m_isInputPanelVisible = !m_keyboardRect.isEmpty();
- } else {
- qWarning("failed to retrieve InputPane.");
- }
+ connect(QGuiApplication::inputMethod(), &QInputMethod::cursorRectangleChanged,
+ this, &QWinRTInputContext::updateScreenCursorRect);
}
QRectF QWinRTInputContext::keyboardRect() const
@@ -119,6 +125,11 @@ bool QWinRTInputContext::isInputPanelVisible() const
return m_isInputPanelVisible;
}
+void QWinRTInputContext::updateScreenCursorRect()
+{
+ m_screen->setCursorRect(QGuiApplication::inputMethod()->cursorRectangle());
+}
+
HRESULT QWinRTInputContext::onShowing(IInputPane *pane, IInputPaneVisibilityEventArgs *)
{
qCDebug(lcQpaInputMethods) << __FUNCTION__ << pane;
@@ -141,6 +152,7 @@ HRESULT QWinRTInputContext::handleVisibilityChange(IInputPane *pane)
const QRectF keyboardRect = getInputPaneRect(pane, m_screen->scaleFactor());
if (m_keyboardRect != keyboardRect) {
m_keyboardRect = keyboardRect;
+ m_screen->setKeyboardRect(m_keyboardRect);
emitKeyboardRectChanged();
}
return S_OK;
diff --git a/src/plugins/platforms/winrt/qwinrtinputcontext.h b/src/plugins/platforms/winrt/qwinrtinputcontext.h
index 5e416bb99f..9d5c4187e2 100644
--- a/src/plugins/platforms/winrt/qwinrtinputcontext.h
+++ b/src/plugins/platforms/winrt/qwinrtinputcontext.h
@@ -79,6 +79,9 @@ public:
void hideInputPanel();
#endif
+private slots:
+ void updateScreenCursorRect();
+
private:
HRESULT onShowing(ABI::Windows::UI::ViewManagement::IInputPane *,
ABI::Windows::UI::ViewManagement::IInputPaneVisibilityEventArgs *);
@@ -89,6 +92,7 @@ private:
QWinRTScreen *m_screen;
QRectF m_keyboardRect;
+ QRectF m_cursorRect;
bool m_isInputPanelVisible;
};
diff --git a/src/plugins/platforms/winrt/qwinrtintegration.cpp b/src/plugins/platforms/winrt/qwinrtintegration.cpp
index 42b7f7e909..ffc3bbf077 100644
--- a/src/plugins/platforms/winrt/qwinrtintegration.cpp
+++ b/src/plugins/platforms/winrt/qwinrtintegration.cpp
@@ -45,7 +45,6 @@
#include "qwinrtinputcontext.h"
#include "qwinrtservices.h"
#include "qwinrteglcontext.h"
-#include "qwinrtfontdatabase.h"
#include "qwinrttheme.h"
#include "qwinrtclipboard.h"
#ifndef QT_NO_DRAGANDDROP
@@ -56,7 +55,8 @@
#include <QtGui/QOpenGLContext>
#include <QtGui/QSurface>
-#include <QtPlatformSupport/private/qeglpbuffer_p.h>
+#include <QtFontDatabaseSupport/private/qwinrtfontdatabase_p.h>
+#include <QtEglSupport/private/qeglpbuffer_p.h>
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qplatformwindow.h>
#include <qpa/qplatformoffscreensurface.h>
@@ -197,9 +197,9 @@ QWinRTIntegration::QWinRTIntegration() : d_ptr(new QWinRTIntegrationPrivate)
QEventDispatcherWinRT::runOnXamlThread([d]() {
d->mainScreen = new QWinRTScreen;
- d->inputContext.reset(new QWinRTInputContext(d->mainScreen));
return S_OK;
});
+ d->inputContext.reset(new QWinRTInputContext(d->mainScreen));
screenAdded(d->mainScreen);
d->platformServices = new QWinRTServices;
diff --git a/src/plugins/platforms/winrt/qwinrtscreen.cpp b/src/plugins/platforms/winrt/qwinrtscreen.cpp
index c120de9d8f..6d4edcc8dc 100644
--- a/src/plugins/platforms/winrt/qwinrtscreen.cpp
+++ b/src/plugins/platforms/winrt/qwinrtscreen.cpp
@@ -625,7 +625,7 @@ int QWinRTScreen::depth() const
QImage::Format QWinRTScreen::format() const
{
- return QImage::Format_ARGB32_Premultiplied;
+ return QImage::Format_RGB32;
}
QSizeF QWinRTScreen::physicalSize() const
@@ -753,12 +753,66 @@ void QWinRTScreen::initialize()
onVisibilityChanged(nullptr, nullptr);
}
+void QWinRTScreen::setCursorRect(const QRectF &cursorRect)
+{
+ mCursorRect = cursorRect;
+}
+
+void QWinRTScreen::setKeyboardRect(const QRectF &keyboardRect)
+{
+ Q_D(QWinRTScreen);
+ QRectF visibleRectF;
+ HRESULT hr;
+ Rect windowSize;
+
+ hr = d->coreWindow->get_Bounds(&windowSize);
+ if (FAILED(hr)) {
+ qErrnoWarning(hr, "Failed to get window bounds");
+ return;
+ }
+ d->logicalRect = QRectF(windowSize.X, windowSize.Y, windowSize.Width, windowSize.Height);
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
+ Rect visibleRect;
+ hr = d->view2->get_VisibleBounds(&visibleRect);
+ if (FAILED(hr)) {
+ qErrnoWarning(hr, "Failed to get window visible bounds");
+ return;
+ }
+ visibleRectF = QRectF(visibleRect.X, visibleRect.Y, visibleRect.Width, visibleRect.Height);
+#else
+ visibleRectF = d->logicalRect;
+#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
+ // if keyboard is snapped to the bottom of the screen and would cover the cursor the content is
+ // moved up to make it visible
+ if (keyboardRect.intersects(mCursorRect)
+ && qFuzzyCompare(geometry().height(), keyboardRect.y() + keyboardRect.height())) {
+ visibleRectF.moveTop(visibleRectF.top() - keyboardRect.height() / d->scaleFactor);
+ }
+ d->visibleRect = visibleRectF;
+
+ qCDebug(lcQpaWindows) << __FUNCTION__ << d->visibleRect;
+ QWindowSystemInterface::handleScreenGeometryChange(screen(), geometry(), availableGeometry());
+ QPlatformScreen::resizeMaximizedWindows();
+ handleExpose();
+}
+
QWindow *QWinRTScreen::topWindow() const
{
Q_D(const QWinRTScreen);
return d->visibleWindows.isEmpty() ? 0 : d->visibleWindows.first();
}
+QWindow *QWinRTScreen::windowAt(const QPoint &pos)
+{
+ Q_D(const QWinRTScreen);
+ for (auto w : qAsConst(d->visibleWindows)) {
+ if (w->geometry().contains(pos))
+ return w;
+ }
+ qCDebug(lcQpaWindows) << __FUNCTION__ << ": No window found at:" << pos;
+ return nullptr;
+}
+
void QWinRTScreen::addWindow(QWindow *window)
{
Q_D(QWinRTScreen);
@@ -767,8 +821,12 @@ void QWinRTScreen::addWindow(QWindow *window)
return;
d->visibleWindows.prepend(window);
- updateWindowTitle(window->title());
- QWindowSystemInterface::handleWindowActivated(window, Qt::OtherFocusReason);
+ const Qt::WindowType type = window->type();
+ if (type != Qt::Popup && type != Qt::ToolTip && type != Qt::Tool) {
+ updateWindowTitle(window->title());
+ QWindowSystemInterface::handleWindowActivated(window, Qt::OtherFocusReason);
+ }
+
handleExpose();
QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
@@ -785,7 +843,9 @@ void QWinRTScreen::removeWindow(QWindow *window)
const bool wasTopWindow = window == topWindow();
if (!d->visibleWindows.removeAll(window))
return;
- if (wasTopWindow)
+
+ const Qt::WindowType type = window->type();
+ if (wasTopWindow && type != Qt::Popup && type != Qt::ToolTip && type != Qt::Tool)
QWindowSystemInterface::handleWindowActivated(Q_NULLPTR, Qt::OtherFocusReason);
handleExpose();
QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
@@ -1001,9 +1061,12 @@ HRESULT QWinRTScreen::onPointerUpdated(ICoreWindow *, IPointerEventArgs *args)
pointerPoint->get_Position(&point);
QPointF pos(point.X * d->scaleFactor, point.Y * d->scaleFactor);
QPointF localPos = pos;
- if (topWindow()) {
- const QPointF globalPosDelta = pos - pos.toPoint();
- localPos = topWindow()->mapFromGlobal(pos.toPoint()) + globalPosDelta;
+
+ const QPoint posPoint = pos.toPoint();
+ QWindow *targetWindow = windowAt(posPoint);
+ if (targetWindow) {
+ const QPointF globalPosDelta = pos - posPoint;
+ localPos = targetWindow->mapFromGlobal(posPoint) + globalPosDelta;
}
VirtualKeyModifiers modifiers;
@@ -1038,7 +1101,7 @@ HRESULT QWinRTScreen::onPointerUpdated(ICoreWindow *, IPointerEventArgs *args)
boolean isHorizontal;
properties->get_IsHorizontalMouseWheel(&isHorizontal);
QPoint angleDelta(isHorizontal ? delta : 0, isHorizontal ? 0 : delta);
- QWindowSystemInterface::handleWheelEvent(topWindow(), localPos, pos, QPoint(), angleDelta, mods);
+ QWindowSystemInterface::handleWheelEvent(targetWindow, localPos, pos, QPoint(), angleDelta, mods);
break;
}
@@ -1064,7 +1127,7 @@ HRESULT QWinRTScreen::onPointerUpdated(ICoreWindow *, IPointerEventArgs *args)
if (isPressed)
buttons |= Qt::XButton2;
- QWindowSystemInterface::handleMouseEvent(topWindow(), localPos, pos, buttons, mods);
+ QWindowSystemInterface::handleMouseEvent(targetWindow, localPos, pos, buttons, mods);
break;
}
@@ -1122,7 +1185,7 @@ HRESULT QWinRTScreen::onPointerUpdated(ICoreWindow *, IPointerEventArgs *args)
it.value().normalPosition = QPointF(point.X/d->logicalRect.width(), point.Y/d->logicalRect.height());
it.value().pressure = pressure;
- QWindowSystemInterface::handleTouchEvent(topWindow(), d->touchDevice, d->touchPoints.values(), mods);
+ QWindowSystemInterface::handleTouchEvent(targetWindow, d->touchDevice, d->touchPoints.values(), mods);
// Fall-through for pen to generate tablet event
if (pointerDeviceType != PointerDeviceType_Pen)
@@ -1141,7 +1204,7 @@ HRESULT QWinRTScreen::onPointerUpdated(ICoreWindow *, IPointerEventArgs *args)
float rotation;
properties->get_Twist(&rotation);
- QWindowSystemInterface::handleTabletEvent(topWindow(), isPressed, pos, pos, 0,
+ QWindowSystemInterface::handleTabletEvent(targetWindow, isPressed, pos, pos, 0,
pointerType, pressure, xTilt, yTilt,
0, rotation, 0, id, mods);
diff --git a/src/plugins/platforms/winrt/qwinrtscreen.h b/src/plugins/platforms/winrt/qwinrtscreen.h
index 0e753b748b..e489e208d5 100644
--- a/src/plugins/platforms/winrt/qwinrtscreen.h
+++ b/src/plugins/platforms/winrt/qwinrtscreen.h
@@ -104,6 +104,7 @@ public:
Qt::ScreenOrientation orientation() const Q_DECL_OVERRIDE;
QWindow *topWindow() const;
+ QWindow *windowAt(const QPoint &pos);
void addWindow(QWindow *window);
void removeWindow(QWindow *window);
void raise(QWindow *window);
@@ -116,6 +117,9 @@ public:
void initialize();
+ void setCursorRect(const QRectF &cursorRect);
+ void setKeyboardRect(const QRectF &keyboardRect);
+
private:
void handleExpose();
@@ -140,6 +144,7 @@ private:
#endif
QScopedPointer<QWinRTScreenPrivate> d_ptr;
+ QRectF mCursorRect;
Q_DECLARE_PRIVATE(QWinRTScreen)
};
diff --git a/src/plugins/platforms/winrt/qwinrttheme.cpp b/src/plugins/platforms/winrt/qwinrttheme.cpp
index e9938894e6..f84688f045 100644
--- a/src/plugins/platforms/winrt/qwinrttheme.cpp
+++ b/src/plugins/platforms/winrt/qwinrttheme.cpp
@@ -369,6 +369,17 @@ QVariant QWinRTTheme::styleHint(QPlatformIntegration::StyleHint hint)
return QVariant();
}
+QVariant QWinRTTheme::themeHint(ThemeHint hint) const
+{
+ qCDebug(lcQpaTheme) << __FUNCTION__ << hint;
+ switch (hint) {
+ case StyleNames:
+ return QStringList() << QStringLiteral("fusion") << QStringLiteral("windows");
+ default:
+ return QPlatformTheme::themeHint(hint);
+ }
+}
+
const QPalette *QWinRTTheme::palette(Palette type) const
{
Q_D(const QWinRTTheme);
diff --git a/src/plugins/platforms/winrt/qwinrttheme.h b/src/plugins/platforms/winrt/qwinrttheme.h
index 2b8817d014..bd244f9fdb 100644
--- a/src/plugins/platforms/winrt/qwinrttheme.h
+++ b/src/plugins/platforms/winrt/qwinrttheme.h
@@ -60,7 +60,7 @@ public:
const QPalette *palette(Palette type = SystemPalette) const Q_DECL_OVERRIDE;
static QVariant styleHint(QPlatformIntegration::StyleHint hint);
-
+ QVariant themeHint(ThemeHint hint) const override;
private:
QScopedPointer<QWinRTThemePrivate> d_ptr;
Q_DECLARE_PRIVATE(QWinRTTheme)
diff --git a/src/plugins/platforms/winrt/qwinrtwindow.cpp b/src/plugins/platforms/winrt/qwinrtwindow.cpp
index 5b82183d40..297e6618d1 100644
--- a/src/plugins/platforms/winrt/qwinrtwindow.cpp
+++ b/src/plugins/platforms/winrt/qwinrtwindow.cpp
@@ -50,7 +50,7 @@
#include <QtGui/QGuiApplication>
#include <QtGui/QOpenGLContext>
#include <QtGui/QWindow>
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
#include <functional>
#include <wrl.h>
diff --git a/src/plugins/platforms/winrt/winrt.pro b/src/plugins/platforms/winrt/winrt.pro
index 28456f66ec..be2f5ca7e2 100644
--- a/src/plugins/platforms/winrt/winrt.pro
+++ b/src/plugins/platforms/winrt/winrt.pro
@@ -2,12 +2,13 @@ TARGET = qwinrt
CONFIG -= precompile_header
-QT += core-private gui-private platformsupport-private
+QT += \
+ core-private gui-private \
+ fontdatabase_support-private egl_support-private
DEFINES *= QT_NO_CAST_FROM_ASCII __WRL_NO_DEFAULT_LIB__
-LIBS += $$QMAKE_LIBS_CORE -ldwrite -ld3d11
-INCLUDEPATH += $$QT_SOURCE_TREE/src/3rdparty/freetype/include
+LIBS += $$QMAKE_LIBS_CORE -ld3d11
SOURCES = \
main.cpp \
@@ -19,7 +20,6 @@ SOURCES = \
qwinrteventdispatcher.cpp \
qwinrtfiledialoghelper.cpp \
qwinrtfileengine.cpp \
- qwinrtfontdatabase.cpp \
qwinrtinputcontext.cpp \
qwinrtintegration.cpp \
qwinrtmessagedialoghelper.cpp \
@@ -38,7 +38,6 @@ HEADERS = \
qwinrteventdispatcher.h \
qwinrtfiledialoghelper.h \
qwinrtfileengine.h \
- qwinrtfontdatabase.h \
qwinrtinputcontext.h \
qwinrtintegration.h \
qwinrtmessagedialoghelper.h \
diff --git a/src/plugins/platforms/xcb/README b/src/plugins/platforms/xcb/README
index 15cf4cf241..5efc9b7f99 100644
--- a/src/plugins/platforms/xcb/README
+++ b/src/plugins/platforms/xcb/README
@@ -21,3 +21,13 @@ REDUCING RUNTIME DEPENDENCIES
The '-qt-xcb' configure option can be used to get rid of most xcb- dependencies. Only libxcb will
still be linked dynamically, since it will be most likely be pulled in via other dependencies anyway.
This should allow for binaries that are portable across most modern Linux distributions.
+
+PACKAGE VERSION REQUIREMENTS
+
+When using touch input via XInput 2.2 or higher, there is a potential issue on systems that ship with
+a libXi older than 1.7.4. This is because XIAllowTouchEvents can deadlock with libXi 1.7.3 and earlier.
+When touch events are never received, this is not an issue, so plain mouse/keyboard systems are not affected.
+See http://lists.x.org/archives/xorg-devel/2014-July/043059.html for details on the libXi patch.
+Qt versions before 5.8 attempted to recognize this scenario based on the pkg-config package version and skip
+the call. This has been removed starting from 5.8 since relying on pkg-config package versions is unsafe given
+that Qt must also support systems with limited or incomplete pkg-config setups.
diff --git a/src/plugins/platforms/xcb/gl_integrations/gl_integrations.pro b/src/plugins/platforms/xcb/gl_integrations/gl_integrations.pro
index 9de0476810..b8f878ffe8 100644
--- a/src/plugins/platforms/xcb/gl_integrations/gl_integrations.pro
+++ b/src/plugins/platforms/xcb/gl_integrations/gl_integrations.pro
@@ -1,9 +1,10 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += gui-private
-contains(QT_CONFIG, egl): contains(QT_CONFIG, egl_x11): contains(QT_CONFIG, opengl) {
+qtConfig(egl):qtConfig(egl_x11):qtConfig(opengl) {
SUBDIRS += xcb_egl
}
-contains(QT_CONFIG, xcb-xlib): contains(QT_CONFIG, opengl): !contains(QT_CONFIG, opengles2) {
+qtConfig(xcb-xlib):qtConfig(opengl):!qtConfig(opengles2) {
SUBDIRS += xcb_glx
}
diff --git a/src/plugins/platforms/xcb/gl_integrations/gl_integrations_plugin_base.pri b/src/plugins/platforms/xcb/gl_integrations/gl_integrations_plugin_base.pri
index 68cb91ff3d..4ab406acb9 100644
--- a/src/plugins/platforms/xcb/gl_integrations/gl_integrations_plugin_base.pri
+++ b/src/plugins/platforms/xcb/gl_integrations/gl_integrations_plugin_base.pri
@@ -1,4 +1,4 @@
-QT += core-private gui-private platformsupport-private xcb_qpa_lib-private
+QT += core-private gui-private xcb_qpa_lib-private
INCLUDEPATH += $$PWD
INCLUDEPATH += $$PWD/../
@@ -6,35 +6,26 @@ INCLUDEPATH += $$PWD/../
load(qt_build_paths)
# needed by Xcursor ...
-contains(QT_CONFIG, xcb-xlib) {
+qtConfig(xcb-xlib) {
DEFINES += XCB_USE_XLIB
- contains(QT_CONFIG, xinput2) {
+ qtConfig(xinput2) {
DEFINES += XCB_USE_XINPUT2
}
}
-# to support custom cursors with depth > 1
-contains(QT_CONFIG, xcb-render) {
- DEFINES += XCB_USE_RENDER
-}
-
# build with session management support
-contains(QT_CONFIG, xcb-sm) {
+qtConfig(xcb-sm) {
DEFINES += XCB_USE_SM
}
-DEFINES += $$QMAKE_DEFINES_XCB
-LIBS += $$QMAKE_LIBS_XCB
-QMAKE_CXXFLAGS += $$QMAKE_CFLAGS_XCB
-
-CONFIG += qpa/genericunixfontdatabase
-
-contains(QT_CONFIG, xcb-qt) {
+!qtConfig(system-xcb) {
DEFINES += XCB_USE_RENDER
- XCB_DIR = $$clean_path($$PWD/../../../../3rdparty/xcb)
- INCLUDEPATH += $$XCB_DIR/include $$XCB_DIR/include/xcb $$XCB_DIR/sysinclude
- LIBS += -lxcb -L$$MODULE_BASE_OUTDIR/lib -lxcb-static$$qtPlatformTargetSuffix()
+ QMAKE_USE += xcb-static xcb
} else {
- LIBS += -lxcb -lxcb-image -lxcb-icccm -lxcb-sync -lxcb-xfixes -lxcb-shm -lxcb-randr -lxcb-shape -lxcb-keysyms
- !contains(DEFINES, QT_NO_XKB):LIBS += -lxcb-xkb
+ qtConfig(xkb): QMAKE_USE += xcb_xkb
+ # to support custom cursors with depth > 1
+ qtConfig(xcb-render) {
+ DEFINES += XCB_USE_RENDER
+ }
+ QMAKE_USE += xcb_syslibs
}
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglcontext.h b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglcontext.h
index 64e9bec6db..48e774bbb2 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglcontext.h
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglcontext.h
@@ -41,8 +41,8 @@
#define QXCBEGLCONTEXT_H
#include "qxcbeglwindow.h"
-#include <QtPlatformSupport/private/qeglplatformcontext_p.h>
-#include <QtPlatformSupport/private/qeglpbuffer_p.h>
+#include <QtEglSupport/private/qeglplatformcontext_p.h>
+#include <QtEglSupport/private/qeglpbuffer_p.h>
#include <QtPlatformHeaders/QEGLNativeContext>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglinclude.h b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglinclude.h
index 7c6524c8ee..a5a47dd0bb 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglinclude.h
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglinclude.h
@@ -46,7 +46,7 @@
#include <QtGui/private/qcssparser_p.h>
#include <QtGui/private/qtextengine_p.h>
-#include <QtPlatformSupport/private/qt_egl_p.h>
+#include <QtEglSupport/private/qt_egl_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglintegration.cpp b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglintegration.cpp
index 079f0466dc..4852d38f7e 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglintegration.cpp
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglintegration.cpp
@@ -42,6 +42,7 @@
#include "qxcbeglcontext.h"
#include <QtGui/QOffscreenSurface>
+#include <QtEglSupport/private/qeglstreamconvenience_p.h>
#include "qxcbeglnativeinterfacehandler.h"
@@ -63,7 +64,18 @@ QXcbEglIntegration::~QXcbEglIntegration()
bool QXcbEglIntegration::initialize(QXcbConnection *connection)
{
m_connection = connection;
- m_egl_display = eglGetDisplay(reinterpret_cast<EGLNativeDisplayType>(xlib_display()));
+
+ const char *extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
+
+ if (extensions && strstr(extensions, "EGL_EXT_platform_x11")) {
+ QEGLStreamConvenience streamFuncs;
+ m_egl_display = streamFuncs.get_platform_display(EGL_PLATFORM_X11_KHR,
+ xlib_display(),
+ nullptr);
+ }
+
+ if (!m_egl_display)
+ m_egl_display = eglGetDisplay(reinterpret_cast<EGLNativeDisplayType>(xlib_display()));
EGLint major, minor;
bool success = eglInitialize(m_egl_display, &major, &minor);
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglwindow.cpp b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglwindow.cpp
index 69b7dfbdbf..3f7ef94238 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglwindow.cpp
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/qxcbeglwindow.cpp
@@ -41,8 +41,8 @@
#include "qxcbeglintegration.h"
-#include <QtPlatformSupport/private/qeglconvenience_p.h>
-#include <QtPlatformSupport/private/qxlibeglintegration_p.h>
+#include <QtEglSupport/private/qeglconvenience_p.h>
+#include <QtEglSupport/private/qxlibeglintegration_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/xcb_egl.pro b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/xcb_egl.pro
index 6d52332bad..1c193849ca 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_egl/xcb_egl.pro
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_egl/xcb_egl.pro
@@ -1,10 +1,13 @@
TARGET = qxcb-egl-integration
include(../gl_integrations_plugin_base.pri)
+QT += egl_support-private
CONFIG += egl
-contains(QT_CONFIG, xcb-xlib): DEFINES += XCB_USE_XLIB
+qtConfig(xcb-xlib): DEFINES += XCB_USE_XLIB
+
+DEFINES += QT_NO_FOREACH
HEADERS += \
qxcbeglcontext.h \
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
index 4c4176a063..1f36a1ad2a 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
@@ -51,7 +51,7 @@
#include <QtGui/QOffscreenSurface>
#include "qglxintegration.h"
-#include <QtPlatformSupport/private/qglxconvenience_p.h>
+#include <QtGlxSupport/private/qglxconvenience_p.h>
#include <QtPlatformHeaders/QGLXNativeContext>
#if defined(Q_OS_LINUX) || defined(Q_OS_BSD4)
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qxcbglxwindow.cpp b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qxcbglxwindow.cpp
index a8d51d5e8c..8df8b28f72 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qxcbglxwindow.cpp
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qxcbglxwindow.cpp
@@ -40,7 +40,7 @@
#include "qxcbglxwindow.h"
#include "qxcbscreen.h"
-#include <QtPlatformSupport/private/qglxconvenience_p.h>
+#include <QtGlxSupport/private/qglxconvenience_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/xcb_glx.pro b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/xcb_glx.pro
index 67fd68765a..8aa6e1febd 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/xcb_glx.pro
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/xcb_glx.pro
@@ -1,15 +1,15 @@
TARGET = qxcb-glx-integration
include(../gl_integrations_plugin_base.pri)
+QT += glx_support-private
#should be removed from the sources
DEFINES += XCB_USE_GLX XCB_USE_XLIB
+DEFINES += QT_NO_FOREACH
-LIBS += -lxcb
-
-contains(QT_CONFIG, xcb-glx) {
+qtConfig(xcb-glx) {
DEFINES += XCB_HAS_XCB_GLX
- LIBS += -lxcb-glx
+ QMAKE_USE += xcb_glx
}
LIBS += $$QMAKE_LIBS_DYNLOAD
diff --git a/src/plugins/platforms/xcb/qxcbbackingstore.cpp b/src/plugins/platforms/xcb/qxcbbackingstore.cpp
index ce9e5d926e..3d09b1c139 100644
--- a/src/plugins/platforms/xcb/qxcbbackingstore.cpp
+++ b/src/plugins/platforms/xcb/qxcbbackingstore.cpp
@@ -225,14 +225,14 @@ bool QXcbShmImage::scroll(const QRegion &area, int dx, int dy)
preparePaint(area);
const QPoint delta(dx, dy);
- foreach (const QRect &rect, area.rects())
+ for (const QRect &rect : area)
qt_scrollRectInImage(*image(), rect, delta);
if (m_xcb_pixmap) {
flushPixmap(area);
ensureGC(m_xcb_pixmap);
const QRect bounds(QPoint(0, 0), size());
- foreach (const QRect &src, area.rects()) {
+ for (const QRect &src : area) {
const QRect dst = src.translated(delta).intersected(bounds);
Q_XCB_CALL(xcb_copy_area(xcb_connection(),
m_xcb_pixmap,
@@ -533,11 +533,9 @@ void QXcbBackingStore::beginPaint(const QRegion &region)
if (m_image->hasAlpha()) {
QPainter p(paintDevice());
p.setCompositionMode(QPainter::CompositionMode_Source);
- const QVector<QRect> rects = region.rects();
const QColor blank = Qt::transparent;
- for (QVector<QRect>::const_iterator it = rects.begin(); it != rects.end(); ++it) {
- p.fillRect(*it, blank);
- }
+ for (const QRect &rect : region)
+ p.fillRect(rect, blank);
}
}
@@ -557,22 +555,21 @@ void QXcbBackingStore::endPaint()
// Slow path: the paint device was m_rgbImage. Now copy with swapping red
// and blue into m_image.
- const QVector<QRect> rects = region.rects();
- if (rects.isEmpty())
+ auto it = region.begin();
+ const auto end = region.end();
+ if (it == end)
return;
QPainter p(m_image->image());
- for (QVector<QRect>::const_iterator it = rects.begin(); it != rects.end(); ++it) {
+ while (it != end) {
const QRect rect = *it;
p.drawImage(rect.topLeft(), m_rgbImage.copy(rect).rgbSwapped());
}
}
-#ifndef QT_NO_OPENGL
QImage QXcbBackingStore::toImage() const
{
return m_image && m_image->image() ? *m_image->image() : QImage();
}
-#endif
QPlatformGraphicsBuffer *QXcbBackingStore::graphicsBuffer() const
{
diff --git a/src/plugins/platforms/xcb/qxcbbackingstore.h b/src/plugins/platforms/xcb/qxcbbackingstore.h
index 5a8f385c1b..6af679d28a 100644
--- a/src/plugins/platforms/xcb/qxcbbackingstore.h
+++ b/src/plugins/platforms/xcb/qxcbbackingstore.h
@@ -63,8 +63,8 @@ public:
void composeAndFlush(QWindow *window, const QRegion &region, const QPoint &offset,
QPlatformTextureList *textures, QOpenGLContext *context,
bool translucentBackground) Q_DECL_OVERRIDE;
- QImage toImage() const Q_DECL_OVERRIDE;
#endif
+ QImage toImage() const Q_DECL_OVERRIDE;
QPlatformGraphicsBuffer *graphicsBuffer() const Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/xcb/qxcbconnection.cpp b/src/plugins/platforms/xcb/qxcbconnection.cpp
index 7052e88141..7bd233f387 100644
--- a/src/plugins/platforms/xcb/qxcbconnection.cpp
+++ b/src/plugins/platforms/xcb/qxcbconnection.cpp
@@ -602,7 +602,7 @@ QXcbConnection::QXcbConnection(QXcbNativeInterface *nativeInterface, bool canGra
xcb_extension_t *extensions[] = {
&xcb_shm_id, &xcb_xfixes_id, &xcb_randr_id, &xcb_shape_id, &xcb_sync_id,
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
&xcb_xkb_id,
#endif
#ifdef XCB_USE_RENDER
@@ -1072,7 +1072,7 @@ Qt::MouseButton QXcbConnection::translateMouseButton(xcb_button_t s)
}
}
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
namespace {
typedef union {
/* All XKB events share these fields. */
@@ -1258,7 +1258,7 @@ void QXcbConnection::handleXcbEvent(xcb_generic_event_t *event)
s->handleScreenChange(change_event);
}
handled = true;
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
} else if (response_type == xkb_first_event) { // https://bugs.freedesktop.org/show_bug.cgi?id=51295
_xkb_event *xkb_event = reinterpret_cast<_xkb_event *>(event);
if (xkb_event->any.deviceID == m_keyboard->coreDeviceId()) {
@@ -1725,11 +1725,13 @@ void QXcbConnection::processXcbEvents()
compressEvent(event, i, eventqueue))
continue;
+#ifndef QT_NO_CLIPBOARD
bool accepted = false;
if (clipboard()->processIncr())
clipboard()->incrTransactionPeeker(event, accepted);
if (accepted)
continue;
+#endif
auto isWaitingFor = [=](PeekFunc peekFunc) {
// These callbacks return true if the event is what they were
@@ -1779,24 +1781,6 @@ void QXcbConnection::handleClientMessageEvent(const xcb_client_message_event_t *
window->handleClientMessageEvent(event);
}
-xcb_generic_event_t *QXcbConnection::checkEvent(int type)
-{
- QXcbEventArray *eventqueue = m_reader->lock();
-
- for (int i = 0; i < eventqueue->size(); ++i) {
- xcb_generic_event_t *event = eventqueue->at(i);
- if (event && event->response_type == type) {
- (*eventqueue)[i] = 0;
- m_reader->unlock();
- return event;
- }
- }
-
- m_reader->unlock();
-
- return 0;
-}
-
static const char * xcb_atomnames = {
// window-manager <-> client protocols
"WM_PROTOCOLS\0"
@@ -2198,7 +2182,7 @@ void QXcbConnection::initializeXShape()
void QXcbConnection::initializeXKB()
{
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
const xcb_query_extension_reply_t *reply = xcb_get_extension_data(m_connection, &xcb_xkb_id);
if (!reply || !reply->present) {
qWarning("Qt: XKEYBOARD extension not present on the X server.");
diff --git a/src/plugins/platforms/xcb/qxcbconnection.h b/src/plugins/platforms/xcb/qxcbconnection.h
index ebea8d5460..f6ba828a15 100644
--- a/src/plugins/platforms/xcb/qxcbconnection.h
+++ b/src/plugins/platforms/xcb/qxcbconnection.h
@@ -43,6 +43,7 @@
#include <xcb/xcb.h>
#include <xcb/randr.h>
+#include <QtGui/private/qtguiglobal_p.h>
#include "qxcbexport.h"
#include <QHash>
#include <QList>
@@ -53,10 +54,11 @@
#include <QVarLengthArray>
#include <qpa/qwindowsysteminterface.h>
#include <QtCore/QLoggingCategory>
+#include <QtCore/private/qglobal_p.h>
// This is needed to make Qt compile together with XKB. xkb.h is using a variable
// which is called 'explicit', this is a reserved keyword in c++
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
#define explicit dont_use_cxx_explicit
#include <xcb/xkb.h>
#undef explicit
@@ -448,7 +450,6 @@ public:
QXcbWindowEventListener *windowEventListenerFromId(xcb_window_t id);
QXcbWindow *platformWindowFromId(xcb_window_t id);
- xcb_generic_event_t *checkEvent(int type);
template<typename T>
inline xcb_generic_event_t *checkEvent(T &checker);
@@ -582,6 +583,8 @@ private:
};
QHash<int, ValuatorClassInfo> valuatorInfo;
};
+ friend class QTypeInfo<TabletData>;
+ friend class QTypeInfo<TabletData::ValuatorClassInfo>;
bool xi2HandleTabletEvent(const void *event, TabletData *tabletData);
void xi2ReportTabletEvent(const void *event, TabletData *tabletData);
QVector<TabletData> m_tabletData;
@@ -684,6 +687,12 @@ private:
friend class QXcbEventReader;
};
+#ifdef XCB_USE_XINPUT2
+#ifndef QT_NO_TABLETEVENT
+Q_DECLARE_TYPEINFO(QXcbConnection::TabletData::ValuatorClassInfo, Q_PRIMITIVE_TYPE);
+Q_DECLARE_TYPEINFO(QXcbConnection::TabletData, Q_MOVABLE_TYPE);
+#endif
+#endif
#define DISPLAY_FROM_XCB(object) ((Display *)(object->connection()->xlib_display()))
#define CREATE_VISUALINFO_FROM_DEFAULT_VISUALID(object) ((XVisualInfo *)(object->connection()->createVisualInfoForDefaultVisualId()))
diff --git a/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp b/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
index f2824b6d65..93f8db92bf 100644
--- a/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
+++ b/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
@@ -697,23 +697,7 @@ void QXcbConnection::xi2ProcessTouch(void *xiDevEvent, QXcbWindow *platformWindo
if (m_xiGrab) {
// XIAllowTouchEvents deadlocks with libXi < 1.7.4 (this has nothing to do with the XI2 versions like 2.2)
// http://lists.x.org/archives/xorg-devel/2014-July/043059.html
-#ifndef LIBXI_MAJOR
- static bool allowTouchWarningShown = false;
- if (!allowTouchWarningShown) {
- allowTouchWarningShown = true;
- qWarning("Skipping XIAllowTouchEvents() because it was not possible to detect libXi version at build time."
- " Minimum libXi version required is 1.7.4."
- " Expect issues with touch behavior.");
- }
-#elif LIBXI_MAJOR == 1 && (LIBXI_MINOR < 7 || (LIBXI_MINOR == 7 && LIBXI_PATCH < 4))
- static bool allowTouchWarningShown = false;
- if (!allowTouchWarningShown) {
- allowTouchWarningShown = true;
- qWarning("Skipping XIAllowTouchEvents() due to not having libXi >= 1.7.4."
- " libXi version at build time was %d.%d.%d."
- " Expect issues with touch behavior.", LIBXI_MAJOR, LIBXI_MINOR, LIBXI_PATCH);
- }
-#else
+#ifdef XCB_USE_XINPUT2
XIAllowTouchEvents(static_cast<Display *>(m_xlib_display), xiDeviceEvent->deviceid,
xiDeviceEvent->detail, xiDeviceEvent->event, XIAcceptTouch);
#endif
diff --git a/src/plugins/platforms/xcb/qxcbcursor.cpp b/src/plugins/platforms/xcb/qxcbcursor.cpp
index 4de4be43d1..80fe5a2199 100644
--- a/src/plugins/platforms/xcb/qxcbcursor.cpp
+++ b/src/plugins/platforms/xcb/qxcbcursor.cpp
@@ -74,6 +74,8 @@ static PtrXcursorLibraryGetDefaultSize ptrXcursorLibraryGetDefaultSize = 0;
static xcb_font_t cursorFont = 0;
static int cursorCount = 0;
+#ifndef QT_NO_CURSOR
+
static uint8_t cur_blank_bits[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
@@ -276,8 +278,6 @@ static const char * const cursorNames[] = {
"link"
};
-#ifndef QT_NO_CURSOR
-
QXcbCursorCacheKey::QXcbCursorCacheKey(const QCursor &c)
: shape(c.shape()), bitmapCacheKey(0), maskCacheKey(0)
{
diff --git a/src/plugins/platforms/xcb/qxcbdrag.cpp b/src/plugins/platforms/xcb/qxcbdrag.cpp
index dd0c557de6..4915bb1b11 100644
--- a/src/plugins/platforms/xcb/qxcbdrag.cpp
+++ b/src/plugins/platforms/xcb/qxcbdrag.cpp
@@ -194,8 +194,10 @@ void QXcbDrag::startDrag()
init();
+#ifndef QT_NO_CLIPBOARD
xcb_set_selection_owner(xcb_connection(), connection()->clipboard()->owner(),
atom(QXcbAtom::XdndSelection), connection()->time());
+#endif
QStringList fmts = QXcbMime::formatsHelper(drag()->mimeData());
for (int i = 0; i < fmts.size(); ++i) {
@@ -205,10 +207,12 @@ void QXcbDrag::startDrag()
drag_types.append(atoms.at(j));
}
}
+#ifndef QT_NO_CLIPBOARD
if (drag_types.size() > 3)
xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, connection()->clipboard()->owner(),
atom(QXcbAtom::XdndTypelist),
XCB_ATOM_ATOM, 32, drag_types.size(), (const void *)drag_types.constData());
+#endif
setUseCompositing(current_virtual_desktop->compositingActive());
setScreen(current_virtual_desktop->screens().constFirst()->screen());
@@ -447,7 +451,11 @@ void QXcbDrag::move(const QPoint &globalPos)
enter.window = target;
enter.format = 32;
enter.type = atom(QXcbAtom::XdndEnter);
+#ifndef QT_NO_CLIPBOARD
enter.data.data32[0] = connection()->clipboard()->owner();
+#else
+ enter.data.data32[0] = 0;
+#endif
enter.data.data32[1] = flags;
enter.data.data32[2] = drag_types.size()>0 ? drag_types.at(0) : 0;
enter.data.data32[3] = drag_types.size()>1 ? drag_types.at(1) : 0;
@@ -476,7 +484,11 @@ void QXcbDrag::move(const QPoint &globalPos)
move.window = target;
move.format = 32;
move.type = atom(QXcbAtom::XdndPosition);
+#ifndef QT_NO_CLIPBOARD
move.data.data32[0] = connection()->clipboard()->owner();
+#else
+ move.data.data32[0] = 0;
+#endif
move.data.data32[1] = 0; // flags
move.data.data32[2] = (globalPos.x() << 16) + globalPos.y();
move.data.data32[3] = connection()->time();
@@ -505,7 +517,11 @@ void QXcbDrag::drop(const QPoint &globalPos)
drop.window = current_target;
drop.format = 32;
drop.type = atom(QXcbAtom::XdndDrop);
+#ifndef QT_NO_CLIPBOARD
drop.data.data32[0] = connection()->clipboard()->owner();
+#else
+ drop.data.data32[0] = 0;
+#endif
drop.data.data32[1] = 0; // flags
drop.data.data32[2] = connection()->time();
@@ -791,9 +807,11 @@ void QXcbDrag::handle_xdnd_position(QPlatformWindow *w, const xcb_client_message
// reset
target_time = XCB_CURRENT_TIME;
+#ifndef QT_NO_CLIPBOARD
if (xdnd_dragsource == connection()->clipboard()->owner())
handle_xdnd_status(&response);
else
+#endif
Q_XCB_CALL(xcb_send_event(xcb_connection(), false, current_proxy_target,
XCB_EVENT_MASK_NO_EVENT, (const char *)&response));
}
@@ -859,7 +877,11 @@ void QXcbDrag::handle_xdnd_status(const xcb_client_message_event_t *event)
void QXcbDrag::handleStatus(const xcb_client_message_event_t *event)
{
- if (event->window != connection()->clipboard()->owner() || !drag())
+ if (
+#ifndef QT_NO_CLIPBOARD
+ event->window != connection()->clipboard()->owner() ||
+#endif
+ !drag())
return;
xcb_client_message_event_t *lastEvent = const_cast<xcb_client_message_event_t *>(event);
@@ -914,7 +936,11 @@ void QXcbDrag::send_leave()
leave.window = current_target;
leave.format = 32;
leave.type = atom(QXcbAtom::XdndLeave);
+#ifndef QT_NO_CLIPBOARD
leave.data.data32[0] = connection()->clipboard()->owner();
+#else
+ leave.data.data32[0] = 0;
+#endif
leave.data.data32[1] = 0; // flags
leave.data.data32[2] = 0; // x, y
leave.data.data32[3] = 0; // w, h
@@ -1006,8 +1032,10 @@ void QXcbDrag::handleDrop(QPlatformWindow *, const xcb_client_message_event_t *e
void QXcbDrag::handleFinished(const xcb_client_message_event_t *event)
{
DEBUG("xdndHandleFinished");
+#ifndef QT_NO_CLIPBOARD
if (event->window != connection()->clipboard()->owner())
return;
+#endif
const unsigned long *l = (const unsigned long *)event->data.data32;
@@ -1287,11 +1315,13 @@ QVariant QXcbDropData::xdndObtainData(const QByteArray &format, QVariant::Type r
if (a == XCB_NONE)
return result;
+#ifndef QT_NO_CLIPBOARD
if (c->clipboard()->getSelectionOwner(drag->atom(QXcbAtom::XdndSelection)) == XCB_NONE)
return result; // should never happen?
xcb_atom_t xdnd_selection = c->atom(QXcbAtom::XdndSelection);
result = c->clipboard()->getSelection(xdnd_selection, a, xdnd_selection, drag->targetTime());
+#endif
return mimeConvertToFormat(c, a, result, QLatin1String(format), requestedType, encoding);
}
diff --git a/src/plugins/platforms/xcb/qxcbdrag.h b/src/plugins/platforms/xcb/qxcbdrag.h
index f65dbda05d..cb6e95cc9a 100644
--- a/src/plugins/platforms/xcb/qxcbdrag.h
+++ b/src/plugins/platforms/xcb/qxcbdrag.h
@@ -159,6 +159,7 @@ private:
QPointer<QDrag> drag;
QTime time;
};
+ friend class QTypeInfo<Transaction>;
QVector<Transaction> transactions;
int transaction_expiry_timer;
@@ -167,6 +168,7 @@ private:
int findTransactionByTime(xcb_timestamp_t timestamp);
xcb_window_t findRealWindow(const QPoint & pos, xcb_window_t w, int md, bool ignoreNonXdndAwareWindows);
};
+Q_DECLARE_TYPEINFO(QXcbDrag::Transaction, Q_MOVABLE_TYPE);
#endif // QT_NO_DRAGANDDROP
diff --git a/src/plugins/platforms/xcb/qxcbintegration.cpp b/src/plugins/platforms/xcb/qxcbintegration.cpp
index 802f7b85ce..f4da7ba033 100644
--- a/src/plugins/platforms/xcb/qxcbintegration.cpp
+++ b/src/plugins/platforms/xcb/qxcbintegration.cpp
@@ -55,19 +55,14 @@
#include <xcb/xcb.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qgenericunixservices_p.h>
+#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtServiceSupport/private/qgenericunixservices_p.h>
#include <stdio.h>
-//this has to be included before egl, since egl pulls in X headers
#include <QtGui/private/qguiapplication_p.h>
-#ifdef XCB_USE_EGL
-# include <QtPlatformSupport/private/qt_egl_p.h>
-#endif
-
#ifdef XCB_USE_XLIB
#include <X11/Xlib.h>
#endif
@@ -82,7 +77,7 @@
#ifndef QT_NO_ACCESSIBILITY
#include <qpa/qplatformaccessibility.h>
#ifndef QT_NO_ACCESSIBILITY_ATSPI_BRIDGE
-#include "../../../platformsupport/linuxaccessibility/bridge_p.h"
+#include <QtLinuxAccessibilitySupport/private/bridge_p.h>
#endif
#endif
diff --git a/src/plugins/platforms/xcb/qxcbkeyboard.cpp b/src/plugins/platforms/xcb/qxcbkeyboard.cpp
index 4e4bfad1d6..a5aff7f11f 100644
--- a/src/plugins/platforms/xcb/qxcbkeyboard.cpp
+++ b/src/plugins/platforms/xcb/qxcbkeyboard.cpp
@@ -711,7 +711,7 @@ void QXcbKeyboard::updateKeymap()
xkb_keymap = 0;
struct xkb_state *new_state = 0;
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
if (connection()->hasXKB()) {
xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, xcb_connection(), core_device_id, (xkb_keymap_compile_flags)0);
if (xkb_keymap) {
@@ -753,7 +753,7 @@ void QXcbKeyboard::updateKeymap()
checkForLatinLayout();
}
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
void QXcbKeyboard::updateXKBState(xcb_xkb_state_notify_event_t *state)
{
if (m_config && connection()->hasXKB()) {
@@ -1144,7 +1144,7 @@ QXcbKeyboard::QXcbKeyboard(QXcbConnection *connection)
, m_hasLatinLayout(false)
{
memset(&xkb_names, 0, sizeof(xkb_names));
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
core_device_id = 0;
if (connection->hasXKB()) {
updateVModMapping();
@@ -1158,7 +1158,7 @@ QXcbKeyboard::QXcbKeyboard(QXcbConnection *connection)
#endif
m_key_symbols = xcb_key_symbols_alloc(xcb_connection());
updateModifiers();
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
}
#endif
updateKeymap();
@@ -1177,7 +1177,7 @@ QXcbKeyboard::~QXcbKeyboard()
void QXcbKeyboard::updateVModMapping()
{
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
xcb_xkb_get_names_cookie_t names_cookie;
xcb_xkb_get_names_reply_t *name_reply;
xcb_xkb_get_names_value_list_t names_list;
@@ -1246,7 +1246,7 @@ void QXcbKeyboard::updateVModMapping()
void QXcbKeyboard::updateVModToRModMapping()
{
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
xcb_xkb_get_map_cookie_t map_cookie;
xcb_xkb_get_map_reply_t *map_reply;
xcb_xkb_get_map_map_t map;
diff --git a/src/plugins/platforms/xcb/qxcbkeyboard.h b/src/plugins/platforms/xcb/qxcbkeyboard.h
index 18f1aa5732..dfd2926435 100644
--- a/src/plugins/platforms/xcb/qxcbkeyboard.h
+++ b/src/plugins/platforms/xcb/qxcbkeyboard.h
@@ -45,7 +45,7 @@
#include <xcb/xcb_keysyms.h>
#include <xkbcommon/xkbcommon.h>
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
#include <xkbcommon/xkbcommon-x11.h>
#endif
@@ -77,7 +77,7 @@ public:
#ifdef XCB_USE_XINPUT22
void updateXKBStateFromXI(void *modInfo, void *groupInfo);
#endif
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
// when XKEYBOARD is present on the X server
int coreDeviceId() const { return core_device_id; }
void updateXKBState(xcb_xkb_state_notify_event_t *state);
@@ -138,7 +138,7 @@ private:
xkb_mod_index_t mod5;
};
_xkb_mods xkb_mods;
-#ifndef QT_NO_XKB
+#if QT_CONFIG(xkb)
// when XKEYBOARD is present on the X server
_mod_masks vmod_masks;
int core_device_id;
diff --git a/src/plugins/platforms/xcb/qxcbmime.cpp b/src/plugins/platforms/xcb/qxcbmime.cpp
index f7244739a5..7592eb2887 100644
--- a/src/plugins/platforms/xcb/qxcbmime.cpp
+++ b/src/plugins/platforms/xcb/qxcbmime.cpp
@@ -121,9 +121,7 @@ bool QXcbMime::mimeDataForAtom(QXcbConnection *connection, xcb_atom_t a, QMimeDa
// so QXcbConnection::atomName() has to be used.
if (atomName == QLatin1String("text/uri-list")
&& connection->atomName(a) == "text/x-moz-url") {
- const QByteArray uri = data->split('\n').first();
- QString mozUri = QString::fromLatin1(uri, uri.size());
- mozUri += QLatin1Char('\n');
+ const QString mozUri = QLatin1String(data->split('\n').constFirst()) + QLatin1Char('\n');
*data = QByteArray(reinterpret_cast<const char *>(mozUri.utf16()),
mozUri.length() * 2);
} else if (atomName == QLatin1String("application/x-color"))
@@ -175,7 +173,7 @@ QVariant QXcbMime::mimeConvertToFormat(QXcbConnection *connection, xcb_atom_t a,
// qDebug() << "mimeConvertDataToFormat" << format << atomName << data;
if (!encoding.isEmpty()
- && atomName == format + QLatin1String(";charset=") + QString::fromLatin1(encoding)) {
+ && atomName == format + QLatin1String(";charset=") + QLatin1String(encoding)) {
#ifndef QT_NO_TEXTCODEC
if (requestedType == QVariant::String) {
@@ -210,10 +208,11 @@ QVariant QXcbMime::mimeConvertToFormat(QXcbConnection *connection, xcb_atom_t a,
reinterpret_cast<const ushort *>(data.constData()), data.size() / 2);
if (!str.isNull()) {
if (format == QLatin1String("text/uri-list")) {
- const QStringList urls = str.split(QLatin1Char('\n'));
+ const auto urls = str.splitRef(QLatin1Char('\n'));
QList<QVariant> list;
- foreach (const QString &s, urls) {
- const QUrl url(s.trimmed());
+ list.reserve(urls.size());
+ for (const QStringRef &s : urls) {
+ const QUrl url(s.trimmed().toString());
if (url.isValid())
list.append(url);
}
@@ -221,7 +220,7 @@ QVariant QXcbMime::mimeConvertToFormat(QXcbConnection *connection, xcb_atom_t a,
// The atomName variable is not used because mimeAtomToString()
// converts "text/x-moz-url" to "text/uri-list".
if (!list.isEmpty() && connection->atomName(a) == "text/x-moz-url")
- return list.first();
+ return list.constFirst();
return list;
} else {
return str;
diff --git a/src/plugins/platforms/xcb/qxcbnativeinterface.cpp b/src/plugins/platforms/xcb/qxcbnativeinterface.cpp
index a3e8da7df8..b1575cbee4 100644
--- a/src/plugins/platforms/xcb/qxcbnativeinterface.cpp
+++ b/src/plugins/platforms/xcb/qxcbnativeinterface.cpp
@@ -57,10 +57,6 @@
#include <QtPlatformHeaders/qxcbintegrationfunctions.h>
#include <QtPlatformHeaders/qxcbscreenfunctions.h>
-#ifndef QT_NO_DBUS
-#include "QtPlatformSupport/private/qdbusmenuconnection_p.h"
-#endif
-
#ifdef XCB_USE_XLIB
# include <X11/Xlib.h>
#else
@@ -85,7 +81,6 @@ static int resourceType(const QByteArray &key)
QByteArrayLiteral("gettimestamp"), QByteArrayLiteral("x11screen"),
QByteArrayLiteral("rootwindow"),
QByteArrayLiteral("subpixeltype"), QByteArrayLiteral("antialiasingenabled"),
- QByteArrayLiteral("nofonthinting"),
QByteArrayLiteral("atspibus"),
QByteArrayLiteral("compositingenabled")
};
@@ -242,9 +237,6 @@ void *QXcbNativeInterface::nativeResourceForScreen(const QByteArray &resourceStr
case GetTimestamp:
result = getTimestamp(xcbScreen);
break;
- case NoFontHinting:
- result = xcbScreen->noFontHinting() ? this : 0; //qboolptr...
- break;
case RootWindow:
result = reinterpret_cast<void *>(xcbScreen->root());
break;
diff --git a/src/plugins/platforms/xcb/qxcbnativeinterface.h b/src/plugins/platforms/xcb/qxcbnativeinterface.h
index ba19cd869c..acecbf4116 100644
--- a/src/plugins/platforms/xcb/qxcbnativeinterface.h
+++ b/src/plugins/platforms/xcb/qxcbnativeinterface.h
@@ -53,7 +53,6 @@ class QWidget;
class QXcbScreen;
class QXcbConnection;
class QXcbNativeInterfaceHandler;
-class QDBusMenuConnection;
class Q_XCB_EXPORT QXcbNativeInterface : public QPlatformNativeInterface
{
@@ -73,7 +72,6 @@ public:
RootWindow,
ScreenSubpixelType,
ScreenAntialiasingEnabled,
- NoFontHinting,
AtspiBus,
CompositingEnabled
};
diff --git a/src/plugins/platforms/xcb/qxcbscreen.cpp b/src/plugins/platforms/xcb/qxcbscreen.cpp
index dc6846b20b..a9675935f4 100644
--- a/src/plugins/platforms/xcb/qxcbscreen.cpp
+++ b/src/plugins/platforms/xcb/qxcbscreen.cpp
@@ -61,8 +61,7 @@ QXcbVirtualDesktop::QXcbVirtualDesktop(QXcbConnection *connection, xcb_screen_t
, m_number(number)
, m_xSettings(Q_NULLPTR)
{
- QByteArray cmAtomName("_NET_WM_CM_S");
- cmAtomName += QByteArray::number(m_number);
+ const QByteArray cmAtomName = "_NET_WM_CM_S" + QByteArray::number(m_number);
m_net_wm_cm_atom = connection->internAtom(cmAtomName.constData());
m_compositingActive = connection->getSelectionOwner(m_net_wm_cm_atom);
@@ -188,7 +187,6 @@ QXcbScreen::QXcbScreen(QXcbConnection *connection, QXcbVirtualDesktop *virtualDe
, m_forcedDpi(-1)
, m_pixelDensity(1)
, m_hintStyle(QFontEngine::HintStyle(-1))
- , m_noFontHinting(false)
, m_subpixelType(QFontEngine::SubpixelAntialiasingType(-1))
, m_antialiasingEnabled(-1)
{
diff --git a/src/plugins/platforms/xcb/qxcbscreen.h b/src/plugins/platforms/xcb/qxcbscreen.h
index 8716af29b5..0d32c3d624 100644
--- a/src/plugins/platforms/xcb/qxcbscreen.h
+++ b/src/plugins/platforms/xcb/qxcbscreen.h
@@ -172,7 +172,6 @@ public:
void readXResources();
QFontEngine::HintStyle hintStyle() const { return m_hintStyle; }
- bool noFontHinting() const { return m_noFontHinting; }
QFontEngine::SubpixelAntialiasingType subpixelType() const { return m_subpixelType; }
int antialiasingEnabled() const { return m_antialiasingEnabled; }
@@ -208,7 +207,6 @@ private:
int m_forcedDpi;
int m_pixelDensity;
QFontEngine::HintStyle m_hintStyle;
- bool m_noFontHinting;
QFontEngine::SubpixelAntialiasingType m_subpixelType;
int m_antialiasingEnabled;
};
diff --git a/src/plugins/platforms/xcb/qxcbsessionmanager.cpp b/src/plugins/platforms/xcb/qxcbsessionmanager.cpp
index 802e4cfe08..2303ccf806 100644
--- a/src/plugins/platforms/xcb/qxcbsessionmanager.cpp
+++ b/src/plugins/platforms/xcb/qxcbsessionmanager.cpp
@@ -40,6 +40,8 @@
#include "qxcbsessionmanager.h"
+#ifndef QT_NO_SESSIONMANAGER
+
#include <qguiapplication.h>
#include <qdatetime.h>
#include <qfileinfo.h>
@@ -144,7 +146,7 @@ static void sm_setProperty(const QString &name, const QStringList &value)
for (QStringList::ConstIterator it = value.begin(); it != value.end(); ++it) {
prop[count].length = (*it).length();
vl.append((*it).toUtf8());
- prop[count].value = (char*)vl.last().data();
+ prop[count].value = (char*)vl.constLast().data();
++count;
}
sm_setProperty(name.toLatin1().data(), SmLISTofARRAY8, count, prop);
@@ -491,3 +493,5 @@ void QXcbSessionManager::exitEventLoop()
}
#include "qxcbsessionmanager.moc"
+
+#endif
diff --git a/src/plugins/platforms/xcb/qxcbsessionmanager.h b/src/plugins/platforms/xcb/qxcbsessionmanager.h
index cba0ab91ad..a184282034 100644
--- a/src/plugins/platforms/xcb/qxcbsessionmanager.h
+++ b/src/plugins/platforms/xcb/qxcbsessionmanager.h
@@ -52,6 +52,8 @@
#include <qpa/qplatformsessionmanager.h>
+#ifndef QT_NO_SESSIONMANAGER
+
QT_BEGIN_NAMESPACE
class QEventLoop;
@@ -89,4 +91,6 @@ private:
QT_END_NAMESPACE
+#endif //QT_NO_SESSIONMANAGER
+
#endif //QXCBSESSIONMANAGER_H
diff --git a/src/plugins/platforms/xcb/qxcbwindow.cpp b/src/plugins/platforms/xcb/qxcbwindow.cpp
index f744b34901..0c8e78491e 100644
--- a/src/plugins/platforms/xcb/qxcbwindow.cpp
+++ b/src/plugins/platforms/xcb/qxcbwindow.cpp
@@ -119,6 +119,8 @@ enum {
QT_BEGIN_NAMESPACE
+Q_DECLARE_TYPEINFO(xcb_rectangle_t, Q_PRIMITIVE_TYPE);
+
#undef FocusIn
enum QX11EmbedFocusInDetail {
@@ -256,6 +258,7 @@ static inline XTextProperty* qstringToXTP(Display *dpy, const QString& s)
free_prop = true;
}
+#if QT_CONFIG(textcodec)
static const QTextCodec* mapper = QTextCodec::codecForLocale();
int errCode = 0;
if (mapper) {
@@ -271,6 +274,7 @@ static inline XTextProperty* qstringToXTP(Display *dpy, const QString& s)
mapper = QTextCodec::codecForName("latin1");
if (!mapper || !mapper->canEncode(s))
return Q_NULLPTR;
+#endif
static QByteArray qcs;
qcs = s.toLatin1();
tp.value = (uchar*)qcs.data();
@@ -278,7 +282,9 @@ static inline XTextProperty* qstringToXTP(Display *dpy, const QString& s)
tp.format = 8;
tp.nitems = qcs.length();
free_prop = false;
+#if QT_CONFIG(textcodec)
}
+#endif
return &tp;
}
#endif // XCB_USE_XLIB
@@ -2417,6 +2423,17 @@ static inline int fixed1616ToInt(FP1616 val)
return int((qreal(val >> 16)) + (val & 0xFFFF) / (qreal)0xFFFF);
}
+void QXcbWindow::handleXIMouseButtonState(const xcb_ge_event_t *event)
+{
+ QXcbConnection *conn = connection();
+ const xXIDeviceEvent *ev = reinterpret_cast<const xXIDeviceEvent *>(event);
+ if (ev->buttons_len > 0) {
+ unsigned char *buttonMask = (unsigned char *) &ev[1];
+ for (int i = 1; i <= 15; ++i)
+ conn->setButton(conn->translateMouseButton(i), XIMaskIsSet(buttonMask, i));
+ }
+}
+
// With XI 2.2+ press/release/motion comes here instead of the above handlers.
void QXcbWindow::handleXIMouseEvent(xcb_ge_event_t *event, Qt::MouseEventSource source)
{
@@ -2432,12 +2449,6 @@ void QXcbWindow::handleXIMouseEvent(xcb_ge_event_t *event, Qt::MouseEventSource
const Qt::MouseButton button = conn->xiToQtMouseButton(ev->detail);
- if (ev->buttons_len > 0) {
- unsigned char *buttonMask = (unsigned char *) &ev[1];
- for (int i = 1; i <= 15; ++i)
- conn->setButton(conn->translateMouseButton(i), XIMaskIsSet(buttonMask, i));
- }
-
const char *sourceName = 0;
if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled())) {
const QMetaObject *metaObject = qt_getEnumMetaObject(source);
@@ -2447,18 +2458,23 @@ void QXcbWindow::handleXIMouseEvent(xcb_ge_event_t *event, Qt::MouseEventSource
switch (ev->evtype) {
case XI_ButtonPress:
+ handleXIMouseButtonState(event);
if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled()))
qCDebug(lcQpaXInputEvents, "XI2 mouse press, button %d, time %d, source %s", button, ev->time, sourceName);
conn->setButton(button, true);
handleButtonPressEvent(event_x, event_y, root_x, root_y, ev->detail, modifiers, ev->time, source);
break;
case XI_ButtonRelease:
+ handleXIMouseButtonState(event);
if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled()))
qCDebug(lcQpaXInputEvents, "XI2 mouse release, button %d, time %d, source %s", button, ev->time, sourceName);
conn->setButton(button, false);
handleButtonReleaseEvent(event_x, event_y, root_x, root_y, ev->detail, modifiers, ev->time, source);
break;
case XI_Motion:
+ // Here we do NOT call handleXIMouseButtonState because we don't expect button state change to be bundled with motion.
+ // When a touchscreen is pressed, an XI_Motion event occurs in which XIMaskIsSet says the left button is pressed,
+ // but we don't want QGuiApplicationPrivate::processMouseEvent() to react by generating a mouse press event.
if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled()))
qCDebug(lcQpaXInputEvents, "XI2 mouse motion %d,%d, time %d, source %s", event_x, event_y, ev->time, sourceName);
handleMotionNotifyEvent(event_x, event_y, root_x, root_y, modifiers, ev->time, source);
@@ -2856,9 +2872,8 @@ void QXcbWindow::setMask(const QRegion &region)
XCB_SHAPE_SK_BOUNDING, xcb_window(), 0, 0, XCB_NONE);
} else {
QVector<xcb_rectangle_t> rects;
- const QVector<QRect> regionRects = region.rects();
- rects.reserve(regionRects.count());
- foreach (const QRect &r, regionRects)
+ rects.reserve(region.rectCount());
+ for (const QRect &r : region)
rects.push_back(qRectToXCBRectangle(r));
xcb_shape_rectangles(connection()->xcb_connection(), XCB_SHAPE_SO_SET,
XCB_SHAPE_SK_BOUNDING, XCB_CLIP_ORDERING_UNSORTED,
diff --git a/src/plugins/platforms/xcb/qxcbwindow.h b/src/plugins/platforms/xcb/qxcbwindow.h
index 717c424e11..92f3f7a67c 100644
--- a/src/plugins/platforms/xcb/qxcbwindow.h
+++ b/src/plugins/platforms/xcb/qxcbwindow.h
@@ -139,6 +139,7 @@ public:
void handleFocusOutEvent(const xcb_focus_out_event_t *event) Q_DECL_OVERRIDE;
void handlePropertyNotifyEvent(const xcb_property_notify_event_t *event) Q_DECL_OVERRIDE;
#ifdef XCB_USE_XINPUT22
+ void handleXIMouseButtonState(const xcb_ge_event_t *);
void handleXIMouseEvent(xcb_ge_event_t *, Qt::MouseEventSource source = Qt::MouseEventNotSynthesized) Q_DECL_OVERRIDE;
void handleXIEnterLeave(xcb_ge_event_t *) Q_DECL_OVERRIDE;
#endif
diff --git a/src/plugins/platforms/xcb/xcb-plugin.pro b/src/plugins/platforms/xcb/xcb-plugin.pro
index 75684a769b..01d493156d 100644
--- a/src/plugins/platforms/xcb/xcb-plugin.pro
+++ b/src/plugins/platforms/xcb/xcb-plugin.pro
@@ -1,6 +1,8 @@
TARGET = qxcb
-QT += core-private gui-private platformsupport-private xcb_qpa_lib-private
+QT += core-private gui-private xcb_qpa_lib-private
+
+DEFINES += QT_NO_FOREACH
SOURCES = \
qxcbmain.cpp
diff --git a/src/plugins/platforms/xcb/xcb-static/xcb-static.pro b/src/plugins/platforms/xcb/xcb-static/xcb-static.pro
index 20481e4834..20d8b83e7c 100644
--- a/src/plugins/platforms/xcb/xcb-static/xcb-static.pro
+++ b/src/plugins/platforms/xcb/xcb-static/xcb-static.pro
@@ -5,14 +5,13 @@
# libxcb-xinerama
#
CONFIG += static
-load(qt_helper_lib)
-XCB_DIR = ../../../../3rdparty/xcb
+XCB_DIR = $$QT_SOURCE_TREE/src/3rdparty/xcb
-INCLUDEPATH += $$XCB_DIR/include $$XCB_DIR/include/xcb $$XCB_DIR/sysinclude
+MODULE_INCLUDEPATH += $$XCB_DIR/include $$XCB_DIR/sysinclude
+INCLUDEPATH += $$XCB_DIR/include/xcb
-QMAKE_CXXFLAGS += $$QMAKE_CFLAGS_XCB
-QMAKE_CFLAGS += $$QMAKE_CFLAGS_XCB
+QMAKE_USE += xcb/nolink
# ignore compiler warnings in 3rdparty code
QMAKE_CFLAGS_STATIC_LIB+=-w
@@ -76,3 +75,5 @@ SOURCES += \
OTHER_FILES = $$XCB_DIR/README
TR_EXCLUDE += $$XCB_DIR/*
+
+load(qt_helper_lib)
diff --git a/src/plugins/platforms/xcb/xcb.pro b/src/plugins/platforms/xcb/xcb.pro
index 5915a59c0b..0d27645a60 100644
--- a/src/plugins/platforms/xcb/xcb.pro
+++ b/src/plugins/platforms/xcb/xcb.pro
@@ -1,7 +1,8 @@
TEMPLATE = subdirs
CONFIG += ordered
+QT_FOR_CONFIG += gui-private
-contains(QT_CONFIG, xcb-qt):SUBDIRS+=xcb-static
+!qtConfig(system-xcb): SUBDIRS += xcb-static
SUBDIRS += xcb_qpa_lib.pro
SUBDIRS += xcb-plugin.pro
diff --git a/src/plugins/platforms/xcb/xcb_qpa_lib.pro b/src/plugins/platforms/xcb/xcb_qpa_lib.pro
index 9ca8872cb2..6db0c76dea 100644
--- a/src/plugins/platforms/xcb/xcb_qpa_lib.pro
+++ b/src/plugins/platforms/xcb/xcb_qpa_lib.pro
@@ -1,7 +1,14 @@
TARGET = QtXcbQpa
CONFIG += no_module_headers internal_module
+DEFINES += QT_NO_FOREACH
-QT += core-private gui-private platformsupport-private
+QT += \
+ core-private gui-private \
+ service_support-private theme_support-private \
+ eventdispatcher_support-private fontdatabase_support-private
+
+qtHaveModule(linuxaccessibility_support-private): \
+ QT += linuxaccessibility_support-private
SOURCES = \
qxcbclipboard.cpp \
@@ -42,67 +49,50 @@ load(qt_build_paths)
DEFINES += QT_BUILD_XCB_PLUGIN
# needed by Xcursor ...
-contains(QT_CONFIG, xcb-xlib) {
+qtConfig(xcb-xlib) {
DEFINES += XCB_USE_XLIB
- LIBS += -lX11 -lX11-xcb
+ QMAKE_USE += xcb_xlib
- contains(QT_CONFIG, xinput2) {
+ qtConfig(xinput2) {
DEFINES += XCB_USE_XINPUT2
SOURCES += qxcbconnection_xi2.cpp
- LIBS += -lXi
- !isEmpty(QMAKE_LIBXI_VERSION_MAJOR) {
- DEFINES += LIBXI_MAJOR=$$QMAKE_LIBXI_VERSION_MAJOR \
- LIBXI_MINOR=$$QMAKE_LIBXI_VERSION_MINOR \
- LIBXI_PATCH=$$QMAKE_LIBXI_VERSION_PATCH
- }
+ QMAKE_USE += xinput2
}
}
-# to support custom cursors with depth > 1
-contains(QT_CONFIG, xcb-render) {
- DEFINES += XCB_USE_RENDER
- LIBS += -lxcb-render -lxcb-render-util
-}
-
# build with session management support
-contains(QT_CONFIG, xcb-sm) {
+qtConfig(xcb-sm) {
DEFINES += XCB_USE_SM
- LIBS += -lSM -lICE
+ QMAKE_USE += x11sm
SOURCES += qxcbsessionmanager.cpp
HEADERS += qxcbsessionmanager.h
}
include(gl_integrations/gl_integrations.pri)
-DEFINES += $$QMAKE_DEFINES_XCB
-LIBS += $$QMAKE_LIBS_XCB
-QMAKE_CXXFLAGS += $$QMAKE_CFLAGS_XCB
-QMAKE_CFLAGS += $$QMAKE_CFLAGS_XCB
-
-CONFIG += qpa/genericunixfontdatabase
-
-contains(QT_CONFIG, dbus-linked) {
- QT += dbus
- LIBS += $$QT_LIBS_DBUS
-}
-
-contains(QT_CONFIG, xcb-qt) {
+!qtConfig(system-xcb) {
DEFINES += XCB_USE_RENDER
- XCB_DIR = ../../../3rdparty/xcb
- INCLUDEPATH += $$XCB_DIR/include $$XCB_DIR/sysinclude
- LIBS += -lxcb -L$$MODULE_BASE_OUTDIR/lib -lxcb-static$$qtPlatformTargetSuffix()
+ QMAKE_USE += xcb-static xcb
} else {
- LIBS += -lxcb -lxcb-image -lxcb-icccm -lxcb-sync -lxcb-xfixes -lxcb-shm -lxcb-randr -lxcb-shape -lxcb-keysyms -lxcb-xinerama
- !contains(DEFINES, QT_NO_XKB):LIBS += -lxcb-xkb
+ LIBS += -lxcb-xinerama ### there is no configure test for this!
+ qtConfig(xkb): QMAKE_USE += xcb_xkb
+ # to support custom cursors with depth > 1
+ qtConfig(xcb-render) {
+ DEFINES += XCB_USE_RENDER
+ QMAKE_USE += xcb_render
+ }
+ QMAKE_USE += xcb_syslibs
}
# libxkbcommon
-contains(QT_CONFIG, xkbcommon-qt) {
- QT_CONFIG += use-xkbcommon-x11support
- include(../../../3rdparty/xkbcommon.pri)
+!qtConfig(xkbcommon-system) {
+ qtConfig(xkb) {
+ include(../../../3rdparty/xkbcommon-x11.pri)
+ } else {
+ include(../../../3rdparty/xkbcommon.pri)
+ }
} else {
- LIBS += $$QMAKE_LIBS_XKBCOMMON
- QMAKE_CXXFLAGS += $$QMAKE_CFLAGS_XKBCOMMON
+ QMAKE_USE += xkbcommon
}
load(qt_module)
diff --git a/src/plugins/platformthemes/gtk3/gtk3.pro b/src/plugins/platformthemes/gtk3/gtk3.pro
index cd19e73ed8..c291ac56a0 100644
--- a/src/plugins/platformthemes/gtk3/gtk3.pro
+++ b/src/plugins/platformthemes/gtk3/gtk3.pro
@@ -5,17 +5,18 @@ PLUGIN_EXTENDS = -
PLUGIN_CLASS_NAME = QGtk3ThemePlugin
load(qt_plugin)
-QT += core-private gui-private platformsupport-private
+QT += core-private gui-private theme_support-private
CONFIG += X11
-QMAKE_CXXFLAGS += $$QT_CFLAGS_QGTK3
-LIBS += $$QT_LIBS_QGTK3
+QMAKE_USE += gtk3
HEADERS += \
qgtk3dialoghelpers.h \
+ qgtk3menu.h \
qgtk3theme.h
SOURCES += \
main.cpp \
qgtk3dialoghelpers.cpp \
+ qgtk3menu.cpp \
qgtk3theme.cpp
diff --git a/src/plugins/platformthemes/gtk3/qgtk3dialoghelpers.cpp b/src/plugins/platformthemes/gtk3/qgtk3dialoghelpers.cpp
index ba88af917d..ba5089a8bc 100644
--- a/src/plugins/platformthemes/gtk3/qgtk3dialoghelpers.cpp
+++ b/src/plugins/platformthemes/gtk3/qgtk3dialoghelpers.cpp
@@ -424,6 +424,9 @@ void QGtk3FileDialogHelper::applyOptions()
const bool confirmOverwrite = !opts->testOption(QFileDialogOptions::DontConfirmOverwrite);
gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(gtkDialog), confirmOverwrite);
+ const bool readOnly = opts->testOption(QFileDialogOptions::ReadOnly);
+ gtk_file_chooser_set_create_folders(GTK_FILE_CHOOSER(gtkDialog), !readOnly);
+
const QStringList nameFilters = opts->nameFilters();
if (!nameFilters.isEmpty())
setNameFilters(nameFilters);
@@ -468,10 +471,10 @@ void QGtk3FileDialogHelper::setNameFilters(const QStringList &filters)
foreach (const QString &filter, filters) {
GtkFileFilter *gtkFilter = gtk_file_filter_new();
- const QString name = filter.left(filter.indexOf(QLatin1Char('(')));
+ const QStringRef name = filter.leftRef(filter.indexOf(QLatin1Char('(')));
const QStringList extensions = cleanFilterList(filter);
- gtk_file_filter_set_name(gtkFilter, name.isEmpty() ? extensions.join(QStringLiteral(", ")).toUtf8() : name.toUtf8());
+ gtk_file_filter_set_name(gtkFilter, name.isEmpty() ? extensions.join(QLatin1String(", ")).toUtf8() : name.toUtf8());
foreach (const QString &ext, extensions)
gtk_file_filter_add_pattern(gtkFilter, ext.toUtf8());
diff --git a/src/plugins/platformthemes/gtk3/qgtk3menu.cpp b/src/plugins/platformthemes/gtk3/qgtk3menu.cpp
new file mode 100644
index 0000000000..52757587b4
--- /dev/null
+++ b/src/plugins/platformthemes/gtk3/qgtk3menu.cpp
@@ -0,0 +1,489 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qgtk3menu.h"
+
+#include <QtGui/qwindow.h>
+#include <QtGui/qpa/qplatformtheme.h>
+
+#undef signals
+#include <gtk/gtk.h>
+
+QT_BEGIN_NAMESPACE
+
+static guint qt_gdkKey(const QKeySequence &shortcut)
+{
+ if (shortcut.isEmpty())
+ return 0;
+
+ // TODO: proper mapping
+ Qt::KeyboardModifiers mods = Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier;
+ return (shortcut[0] ^ mods) & shortcut[0];
+}
+
+static GdkModifierType qt_gdkModifiers(const QKeySequence &shortcut)
+{
+ if (shortcut.isEmpty())
+ return GdkModifierType(0);
+
+ guint mods = 0;
+ int m = shortcut[0];
+ if (m & Qt::ShiftModifier)
+ mods |= GDK_SHIFT_MASK;
+ if (m & Qt::ControlModifier)
+ mods |= GDK_CONTROL_MASK;
+ if (m & Qt::AltModifier)
+ mods |= GDK_MOD1_MASK;
+ if (m & Qt::MetaModifier)
+ mods |= GDK_META_MASK;
+
+ return static_cast<GdkModifierType>(mods);
+}
+
+QGtk3MenuItem::QGtk3MenuItem()
+ : m_visible(true),
+ m_separator(false),
+ m_checkable(false),
+ m_checked(false),
+ m_enabled(true),
+ m_underline(false),
+ m_invalid(true),
+ m_tag(reinterpret_cast<quintptr>(this)),
+ m_menu(nullptr),
+ m_item(nullptr)
+{
+}
+
+QGtk3MenuItem::~QGtk3MenuItem()
+{
+}
+
+bool QGtk3MenuItem::isInvalid() const
+{
+ return m_invalid;
+}
+
+GtkWidget *QGtk3MenuItem::create()
+{
+ if (m_invalid) {
+ if (m_item) {
+ gtk_widget_destroy(m_item);
+ m_item = nullptr;
+ }
+ m_invalid = false;
+ }
+
+ if (!m_item) {
+ if (m_separator) {
+ m_item = gtk_separator_menu_item_new();
+ } else {
+ if (m_checkable) {
+ m_item = gtk_check_menu_item_new();
+ gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(m_item), m_checked);
+ g_signal_connect(m_item, "toggled", G_CALLBACK(onToggle), this);
+ } else {
+ m_item = gtk_menu_item_new();
+ g_signal_connect(m_item, "activate", G_CALLBACK(onActivate), this);
+ }
+ gtk_menu_item_set_label(GTK_MENU_ITEM(m_item), m_text.toUtf8());
+ gtk_menu_item_set_use_underline(GTK_MENU_ITEM(m_item), m_underline);
+ if (m_menu)
+ gtk_menu_item_set_submenu(GTK_MENU_ITEM(m_item), m_menu->handle());
+ g_signal_connect(m_item, "select", G_CALLBACK(onSelect), this);
+ if (!m_shortcut.isEmpty()) {
+ GtkWidget *label = gtk_bin_get_child(GTK_BIN(m_item));
+ gtk_accel_label_set_accel(GTK_ACCEL_LABEL(label), qt_gdkKey(m_shortcut), qt_gdkModifiers(m_shortcut));
+ }
+ }
+ gtk_widget_set_sensitive(m_item, m_enabled);
+ gtk_widget_set_visible(m_item, m_visible);
+ if (GTK_IS_CHECK_MENU_ITEM(m_item))
+ g_object_set(m_item, "draw-as-radio", m_exclusive, NULL);
+ }
+
+ return m_item;
+}
+
+GtkWidget *QGtk3MenuItem::handle() const
+{
+ return m_item;
+}
+
+quintptr QGtk3MenuItem::tag() const
+{
+ return m_tag;
+}
+
+void QGtk3MenuItem::setTag(quintptr tag)
+{
+ m_tag = tag;
+}
+
+QString QGtk3MenuItem::text() const
+{
+ return m_text;
+}
+
+static QString convertMnemonics(QString text, bool *found)
+{
+ *found = false;
+
+ int i = text.length() - 1;
+ while (i >= 0) {
+ const QChar c = text.at(i);
+ if (c == QLatin1Char('&')) {
+ if (i == 0 || text.at(i - 1) != QLatin1Char('&')) {
+ // convert Qt to GTK mnemonic
+ if (i < text.length() - 1 && !text.at(i + 1).isSpace()) {
+ text.replace(i, 1, QLatin1Char('_'));
+ *found = true;
+ }
+ } else if (text.at(i - 1) == QLatin1Char('&')) {
+ // unescape ampersand
+ text.replace(--i, 2, QLatin1Char('&'));
+ }
+ } else if (c == QLatin1Char('_')) {
+ // escape GTK mnemonic
+ text.insert(i, QLatin1Char('_'));
+ }
+ --i;
+ }
+
+ return text;
+}
+
+void QGtk3MenuItem::setText(const QString &text)
+{
+ m_text = convertMnemonics(text, &m_underline);
+ if (GTK_IS_MENU_ITEM(m_item)) {
+ gtk_menu_item_set_label(GTK_MENU_ITEM(m_item), m_text.toUtf8());
+ gtk_menu_item_set_use_underline(GTK_MENU_ITEM(m_item), m_underline);
+ }
+}
+
+QGtk3Menu *QGtk3MenuItem::menu() const
+{
+ return m_menu;
+}
+
+void QGtk3MenuItem::setMenu(QPlatformMenu *menu)
+{
+ m_menu = qobject_cast<QGtk3Menu *>(menu);
+ if (GTK_IS_MENU_ITEM(m_item))
+ gtk_menu_item_set_submenu(GTK_MENU_ITEM(m_item), m_menu ? m_menu->handle() : NULL);
+}
+
+bool QGtk3MenuItem::isVisible() const
+{
+ return m_visible;
+}
+
+void QGtk3MenuItem::setVisible(bool visible)
+{
+ if (m_visible == visible)
+ return;
+
+ m_visible = visible;
+ if (GTK_IS_MENU_ITEM(m_item))
+ gtk_widget_set_visible(m_item, visible);
+}
+
+bool QGtk3MenuItem::isSeparator() const
+{
+ return m_separator;
+}
+
+void QGtk3MenuItem::setIsSeparator(bool separator)
+{
+ if (m_separator == separator)
+ return;
+
+ m_invalid = true;
+ m_separator = separator;
+}
+
+bool QGtk3MenuItem::isCheckable() const
+{
+ return m_checkable;
+}
+
+void QGtk3MenuItem::setCheckable(bool checkable)
+{
+ if (m_checkable == checkable)
+ return;
+
+ m_invalid = true;
+ m_checkable = checkable;
+}
+
+bool QGtk3MenuItem::isChecked() const
+{
+ return m_checked;
+}
+
+void QGtk3MenuItem::setChecked(bool checked)
+{
+ if (m_checked == checked)
+ return;
+
+ m_checked = checked;
+ if (GTK_IS_CHECK_MENU_ITEM(m_item))
+ gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(m_item), checked);
+}
+
+QKeySequence QGtk3MenuItem::shortcut() const
+{
+ return m_shortcut;
+}
+
+void QGtk3MenuItem::setShortcut(const QKeySequence& shortcut)
+{
+ if (m_shortcut == shortcut)
+ return;
+
+ m_shortcut = shortcut;
+ if (GTK_IS_MENU_ITEM(m_item)) {
+ GtkWidget *label = gtk_bin_get_child(GTK_BIN(m_item));
+ gtk_accel_label_set_accel(GTK_ACCEL_LABEL(label), qt_gdkKey(m_shortcut), qt_gdkModifiers(m_shortcut));
+ }
+}
+
+bool QGtk3MenuItem::isEnabled() const
+{
+ return m_enabled;
+}
+
+void QGtk3MenuItem::setEnabled(bool enabled)
+{
+ if (m_enabled == enabled)
+ return;
+
+ m_enabled = enabled;
+ if (m_item)
+ gtk_widget_set_sensitive(m_item, enabled);
+}
+
+bool QGtk3MenuItem::hasExclusiveGroup() const
+{
+ return m_exclusive;
+}
+
+void QGtk3MenuItem::setHasExclusiveGroup(bool exclusive)
+{
+ if (m_exclusive == exclusive)
+ return;
+
+ m_exclusive = exclusive;
+ if (GTK_IS_CHECK_MENU_ITEM(m_item))
+ g_object_set(m_item, "draw-as-radio", exclusive, NULL);
+}
+
+void QGtk3MenuItem::onSelect(GtkMenuItem *, void *data)
+{
+ QGtk3MenuItem *item = static_cast<QGtk3MenuItem *>(data);
+ if (item)
+ emit item->hovered();
+}
+
+void QGtk3MenuItem::onActivate(GtkMenuItem *, void *data)
+{
+ QGtk3MenuItem *item = static_cast<QGtk3MenuItem *>(data);
+ if (item)
+ emit item->activated();
+}
+
+void QGtk3MenuItem::onToggle(GtkCheckMenuItem *check, void *data)
+{
+ QGtk3MenuItem *item = static_cast<QGtk3MenuItem *>(data);
+ if (item) {
+ bool active = gtk_check_menu_item_get_active(check);
+ if (active != item->isChecked()) {
+ item->setChecked(active);
+ emit item->activated();
+ }
+ }
+}
+
+QGtk3Menu::QGtk3Menu()
+ : m_tag(reinterpret_cast<quintptr>(this))
+{
+ m_menu = gtk_menu_new();
+
+ g_signal_connect(m_menu, "show", G_CALLBACK(onShow), this);
+ g_signal_connect(m_menu, "hide", G_CALLBACK(onHide), this);
+}
+
+QGtk3Menu::~QGtk3Menu()
+{
+ if (GTK_IS_WIDGET(m_menu))
+ gtk_widget_destroy(m_menu);
+}
+
+GtkWidget *QGtk3Menu::handle() const
+{
+ return m_menu;
+}
+
+void QGtk3Menu::insertMenuItem(QPlatformMenuItem *item, QPlatformMenuItem *before)
+{
+ QGtk3MenuItem *gitem = static_cast<QGtk3MenuItem *>(item);
+ if (!gitem || m_items.contains(gitem))
+ return;
+
+ GtkWidget *handle = gitem->create();
+ int index = m_items.indexOf(static_cast<QGtk3MenuItem *>(before));
+ if (index < 0)
+ index = m_items.count();
+ m_items.insert(index, gitem);
+ gtk_menu_shell_insert(GTK_MENU_SHELL(m_menu), handle, index);
+}
+
+void QGtk3Menu::removeMenuItem(QPlatformMenuItem *item)
+{
+ QGtk3MenuItem *gitem = static_cast<QGtk3MenuItem *>(item);
+ if (!gitem || !m_items.removeOne(gitem))
+ return;
+
+ GtkWidget *handle = gitem->handle();
+ if (handle)
+ gtk_container_remove(GTK_CONTAINER(m_menu), handle);
+}
+
+void QGtk3Menu::syncMenuItem(QPlatformMenuItem *item)
+{
+ QGtk3MenuItem *gitem = static_cast<QGtk3MenuItem *>(item);
+ int index = m_items.indexOf(gitem);
+ if (index == -1 || !gitem->isInvalid())
+ return;
+
+ GtkWidget *handle = gitem->create();
+ if (handle)
+ gtk_menu_shell_insert(GTK_MENU_SHELL(m_menu), handle, index);
+}
+
+void QGtk3Menu::syncSeparatorsCollapsible(bool enable)
+{
+ Q_UNUSED(enable);
+}
+
+quintptr QGtk3Menu::tag() const
+{
+ return m_tag;
+}
+
+void QGtk3Menu::setTag(quintptr tag)
+{
+ m_tag = tag;
+}
+
+void QGtk3Menu::setEnabled(bool enabled)
+{
+ gtk_widget_set_sensitive(m_menu, enabled);
+}
+
+void QGtk3Menu::setVisible(bool visible)
+{
+ gtk_widget_set_visible(m_menu, visible);
+}
+
+static void qt_gtk_menu_position_func(GtkMenu *, gint *x, gint *y, gboolean *push_in, gpointer data)
+{
+ QGtk3Menu *menu = static_cast<QGtk3Menu *>(data);
+ QPoint targetPos = menu->targetPos();
+ *x = targetPos.x();
+ *y = targetPos.y();
+ *push_in = true;
+}
+
+QPoint QGtk3Menu::targetPos() const
+{
+ return m_targetPos;
+}
+
+void QGtk3Menu::showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item)
+{
+ int index = m_items.indexOf(static_cast<QGtk3MenuItem *>(const_cast<QPlatformMenuItem *>(item)));
+ if (index != -1)
+ gtk_menu_set_active(GTK_MENU(m_menu), index);
+
+ m_targetPos = targetRect.bottomLeft();
+ if (parentWindow)
+ m_targetPos = parentWindow->mapToGlobal(m_targetPos);
+
+ gtk_menu_popup(GTK_MENU(m_menu), NULL, NULL, qt_gtk_menu_position_func, this, 0, gtk_get_current_event_time());
+}
+
+void QGtk3Menu::dismiss()
+{
+ gtk_menu_popdown(GTK_MENU(m_menu));
+}
+
+QPlatformMenuItem *QGtk3Menu::menuItemAt(int position) const
+{
+ return m_items.value(position);
+}
+
+QPlatformMenuItem *QGtk3Menu::menuItemForTag(quintptr tag) const
+{
+ for (QGtk3MenuItem *item : m_items) {
+ if (item->tag() == tag)
+ return item;
+ }
+ return nullptr;
+}
+
+QPlatformMenuItem *QGtk3Menu::createMenuItem() const
+{
+ return new QGtk3MenuItem;
+}
+
+QPlatformMenu *QGtk3Menu::createSubMenu() const
+{
+ return new QGtk3Menu;
+}
+
+void QGtk3Menu::onShow(GtkWidget *, void *data)
+{
+ QGtk3Menu *menu = static_cast<QGtk3Menu *>(data);
+ if (menu)
+ emit menu->aboutToShow();
+}
+
+void QGtk3Menu::onHide(GtkWidget *, void *data)
+{
+ QGtk3Menu *menu = static_cast<QGtk3Menu *>(data);
+ if (menu)
+ emit menu->aboutToHide();
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platformthemes/gtk3/qgtk3menu.h b/src/plugins/platformthemes/gtk3/qgtk3menu.h
new file mode 100644
index 0000000000..ad108f1218
--- /dev/null
+++ b/src/plugins/platformthemes/gtk3/qgtk3menu.h
@@ -0,0 +1,162 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://www.qt.io/contact-us.
+**
+** 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 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QGTK3MENU_H
+#define QGTK3MENU_H
+
+#include <QtGui/qpa/qplatformmenu.h>
+
+typedef struct _GtkWidget GtkWidget;
+typedef struct _GtkMenuItem GtkMenuItem;
+typedef struct _GtkCheckMenuItem GtkCheckMenuItem;
+
+QT_BEGIN_NAMESPACE
+
+class QGtk3Menu;
+
+class QGtk3MenuItem: public QPlatformMenuItem
+{
+public:
+ QGtk3MenuItem();
+ ~QGtk3MenuItem();
+
+ bool isInvalid() const;
+
+ GtkWidget *create();
+ GtkWidget *handle() const;
+
+ quintptr tag() const;
+ void setTag(quintptr tag) override;
+
+ QString text() const;
+ void setText(const QString &text) override;
+
+ QGtk3Menu *menu() const;
+ void setMenu(QPlatformMenu *menu) override;
+
+ bool isVisible() const;
+ void setVisible(bool visible) override;
+
+ bool isSeparator() const;
+ void setIsSeparator(bool separator) override;
+
+ bool isCheckable() const;
+ void setCheckable(bool checkable) override;
+
+ bool isChecked() const;
+ void setChecked(bool checked) override;
+
+ QKeySequence shortcut() const;
+ void setShortcut(const QKeySequence &shortcut) override;
+
+ bool isEnabled() const;
+ void setEnabled(bool enabled) override;
+
+ bool hasExclusiveGroup() const;
+ void setHasExclusiveGroup(bool exclusive) override;
+
+ void setRole(MenuRole role) override { Q_UNUSED(role); }
+ void setFont(const QFont &font) override { Q_UNUSED(font); }
+ void setIcon(const QIcon &icon) override { Q_UNUSED(icon); }
+ void setIconSize(int size) override { Q_UNUSED(size); }
+
+protected:
+ static void onSelect(GtkMenuItem *item, void *data);
+ static void onActivate(GtkMenuItem *item, void *data);
+ static void onToggle(GtkCheckMenuItem *item, void *data);
+
+private:
+ bool m_visible;
+ bool m_separator;
+ bool m_checkable;
+ bool m_checked;
+ bool m_enabled;
+ bool m_exclusive;
+ bool m_underline;
+ bool m_invalid;
+ quintptr m_tag;
+ QGtk3Menu *m_menu;
+ GtkWidget *m_item;
+ QString m_text;
+ QKeySequence m_shortcut;
+};
+
+class QGtk3Menu : public QPlatformMenu
+{
+ Q_OBJECT
+
+public:
+ QGtk3Menu();
+ ~QGtk3Menu();
+
+ GtkWidget *handle() const;
+
+ void insertMenuItem(QPlatformMenuItem *item, QPlatformMenuItem *before) override;
+ void removeMenuItem(QPlatformMenuItem *item) override;
+ void syncMenuItem(QPlatformMenuItem *item) override;
+ void syncSeparatorsCollapsible(bool enable) override;
+
+ quintptr tag() const override;
+ void setTag(quintptr tag) override;
+
+ void setEnabled(bool enabled) override;
+ void setVisible(bool visible) override;
+
+ void setIcon(const QIcon &icon) override { Q_UNUSED(icon); }
+ void setText(const QString &text) override { Q_UNUSED(text); }
+
+ QPoint targetPos() const;
+
+ void showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item) override;
+ void dismiss() override;
+
+ QPlatformMenuItem *menuItemAt(int position) const override;
+ QPlatformMenuItem *menuItemForTag(quintptr tag) const override;
+
+ QPlatformMenuItem *createMenuItem() const override;
+ QPlatformMenu *createSubMenu() const override;
+
+protected:
+ static void onShow(GtkWidget *menu, void *data);
+ static void onHide(GtkWidget *menu, void *data);
+
+private:
+ quintptr m_tag;
+ GtkWidget *m_menu;
+ QPoint m_targetPos;
+ QVector<QGtk3MenuItem *> m_items;
+};
+
+QT_END_NAMESPACE
+
+#endif // QGTK3MENU_H
diff --git a/src/plugins/platformthemes/gtk3/qgtk3theme.cpp b/src/plugins/platformthemes/gtk3/qgtk3theme.cpp
index 65bec3dbd1..6df631bff3 100644
--- a/src/plugins/platformthemes/gtk3/qgtk3theme.cpp
+++ b/src/plugins/platformthemes/gtk3/qgtk3theme.cpp
@@ -39,6 +39,7 @@
#include "qgtk3theme.h"
#include "qgtk3dialoghelpers.h"
+#include "qgtk3menu.h"
#include <QVariant>
#undef signals
@@ -142,4 +143,14 @@ QPlatformDialogHelper *QGtk3Theme::createPlatformDialogHelper(DialogType type) c
}
}
+QPlatformMenu* QGtk3Theme::createPlatformMenu() const
+{
+ return new QGtk3Menu;
+}
+
+QPlatformMenuItem* QGtk3Theme::createPlatformMenuItem() const
+{
+ return new QGtk3MenuItem;
+}
+
QT_END_NAMESPACE
diff --git a/src/plugins/platformthemes/gtk3/qgtk3theme.h b/src/plugins/platformthemes/gtk3/qgtk3theme.h
index 8bb9adeab8..52036680c6 100644
--- a/src/plugins/platformthemes/gtk3/qgtk3theme.h
+++ b/src/plugins/platformthemes/gtk3/qgtk3theme.h
@@ -55,6 +55,9 @@ public:
bool usePlatformNativeDialog(DialogType type) const Q_DECL_OVERRIDE;
QPlatformDialogHelper *createPlatformDialogHelper(DialogType type) const Q_DECL_OVERRIDE;
+ QPlatformMenu* createPlatformMenu() const Q_DECL_OVERRIDE;
+ QPlatformMenuItem* createPlatformMenuItem() const Q_DECL_OVERRIDE;
+
static const char *name;
};
diff --git a/src/plugins/platformthemes/platformthemes.pro b/src/plugins/platformthemes/platformthemes.pro
index f5f54068a2..0e2812bed3 100644
--- a/src/plugins/platformthemes/platformthemes.pro
+++ b/src/plugins/platformthemes/platformthemes.pro
@@ -1,3 +1,4 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += widgets-private
-contains(QT_CONFIG, gtk3): SUBDIRS += gtk3
+qtHaveModule(widgets):qtConfig(gtk3): SUBDIRS += gtk3
diff --git a/src/plugins/plugins.pro b/src/plugins/plugins.pro
index 0f4207c636..941c25361f 100644
--- a/src/plugins/plugins.pro
+++ b/src/plugins/plugins.pro
@@ -1,14 +1,13 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += network
-load(qfeatures)
SUBDIRS *= sqldrivers
-qtHaveModule(network):!contains(QT_DISABLED_FEATURES, bearermanagement): SUBDIRS += bearer
+qtHaveModule(network):qtConfig(bearermanagement): SUBDIRS += bearer
qtHaveModule(gui) {
SUBDIRS *= platforms platforminputcontexts platformthemes
- !contains(QT_DISABLED_FEATURES, imageformatplugin): SUBDIRS *= imageformats
- !android:!contains(QT_DISABLED_FEATURES, library): SUBDIRS *= generic
+ qtConfig(imageformatplugin): SUBDIRS *= imageformats
+ !android:qtConfig(library): SUBDIRS *= generic
}
-!winrt:!wince*:qtHaveModule(widgets):!contains(QT_DISABLED_FEATURES, printer) {
+!winrt:!wince:qtHaveModule(printsupport): \
SUBDIRS += printsupport
-}
diff --git a/src/plugins/printsupport/cups/cups.pro b/src/plugins/printsupport/cups/cups.pro
index 757408e7f7..58bc11606b 100644
--- a/src/plugins/printsupport/cups/cups.pro
+++ b/src/plugins/printsupport/cups/cups.pro
@@ -3,7 +3,7 @@ MODULE = cupsprintersupport
QT += core-private gui-private printsupport printsupport-private
-LIBS_PRIVATE += -lcups
+QMAKE_USE_PRIVATE += cups
INCLUDEPATH += ../../../printsupport/kernel
diff --git a/src/plugins/printsupport/cups/qppdprintdevice.cpp b/src/plugins/printsupport/cups/qppdprintdevice.cpp
index caa7382462..9efa83d409 100644
--- a/src/plugins/printsupport/cups/qppdprintdevice.cpp
+++ b/src/plugins/printsupport/cups/qppdprintdevice.cpp
@@ -63,7 +63,7 @@ QPpdPrintDevice::QPpdPrintDevice(const QString &id)
if (!id.isEmpty()) {
// TODO For now each dest is an individual device
- QStringList parts = id.split(QLatin1Char('/'));
+ const auto parts = id.splitRef(QLatin1Char('/'));
m_cupsName = parts.at(0).toUtf8();
if (parts.size() > 1)
m_cupsInstance = parts.at(1).toUtf8();
diff --git a/src/plugins/printsupport/printsupport.pro b/src/plugins/printsupport/printsupport.pro
index bd6681f53c..05cf1bc0b2 100644
--- a/src/plugins/printsupport/printsupport.pro
+++ b/src/plugins/printsupport/printsupport.pro
@@ -1,8 +1,6 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += printsupport-private
osx: SUBDIRS += cocoa
win32: SUBDIRS += windows
-unix:!mac:contains(QT_CONFIG, cups) {
- load(qfeatures)
- !contains(QT_DISABLED_FEATURES, cups): SUBDIRS += cups
-}
+unix:!darwin:qtConfig(cups): SUBDIRS += cups
diff --git a/src/plugins/sqldrivers/db2/db2.pro b/src/plugins/sqldrivers/db2/db2.pro
index 2365c5bc0e..eef65fac66 100644
--- a/src/plugins/sqldrivers/db2/db2.pro
+++ b/src/plugins/sqldrivers/db2/db2.pro
@@ -1,8 +1,11 @@
TARGET = qsqldb2
-SOURCES = main.cpp
+HEADERS += $$PWD/qsql_db2_p.h
+SOURCES += $$PWD/qsql_db2.cpp $$PWD/main.cpp
+
+QMAKE_USE += db2
+
OTHER_FILES += db2.json
-include(../../../sql/drivers/db2/qsql_db2.pri)
PLUGIN_CLASS_NAME = QDB2DriverPlugin
include(../qsqldriverbase.pri)
diff --git a/src/plugins/sqldrivers/db2/main.cpp b/src/plugins/sqldrivers/db2/main.cpp
index 3869d7798d..97338b8eef 100644
--- a/src/plugins/sqldrivers/db2/main.cpp
+++ b/src/plugins/sqldrivers/db2/main.cpp
@@ -39,7 +39,7 @@
#include <qsqldriverplugin.h>
#include <qstringlist.h>
-#include "../../../sql/drivers/db2/qsql_db2_p.h"
+#include "qsql_db2_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/sqldrivers/db2/qsql_db2.cpp b/src/plugins/sqldrivers/db2/qsql_db2.cpp
new file mode 100644
index 0000000000..27d0e7001a
--- /dev/null
+++ b/src/plugins/sqldrivers/db2/qsql_db2.cpp
@@ -0,0 +1,1699 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsql_db2_p.h"
+#include <qcoreapplication.h>
+#include <qdatetime.h>
+#include <qsqlfield.h>
+#include <qsqlerror.h>
+#include <qsqlindex.h>
+#include <qsqlrecord.h>
+#include <qstringlist.h>
+#include <qvarlengtharray.h>
+#include <qvector.h>
+#include <QDebug>
+#include <QtSql/private/qsqldriver_p.h>
+#include <QtSql/private/qsqlresult_p.h>
+
+#if defined(Q_CC_BOR)
+// DB2's sqlsystm.h (included through sqlcli1.h) defines the SQL_BIGINT_TYPE
+// and SQL_BIGUINT_TYPE to wrong the types for Borland; so do the defines to
+// the right type before including the header
+#define SQL_BIGINT_TYPE qint64
+#define SQL_BIGUINT_TYPE quint64
+#endif
+
+#include <sqlcli1.h>
+
+#include <string.h>
+
+QT_BEGIN_NAMESPACE
+
+static const int COLNAMESIZE = 255;
+static const SQLSMALLINT qParamType[4] = { SQL_PARAM_INPUT, SQL_PARAM_INPUT, SQL_PARAM_OUTPUT, SQL_PARAM_INPUT_OUTPUT };
+
+class QDB2DriverPrivate : public QSqlDriverPrivate
+{
+ Q_DECLARE_PUBLIC(QDB2Driver)
+
+public:
+ QDB2DriverPrivate() : QSqlDriverPrivate(), hEnv(0), hDbc(0) { dbmsType = QSqlDriver::DB2; }
+ SQLHANDLE hEnv;
+ SQLHANDLE hDbc;
+ QString user;
+};
+
+class QDB2ResultPrivate;
+
+class QDB2Result: public QSqlResult
+{
+ Q_DECLARE_PRIVATE(QDB2Result)
+
+public:
+ QDB2Result(const QDB2Driver *drv);
+ ~QDB2Result();
+ bool prepare(const QString &query) Q_DECL_OVERRIDE;
+ bool exec() Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+protected:
+ QVariant data(int field) Q_DECL_OVERRIDE;
+ bool reset(const QString &query) Q_DECL_OVERRIDE;
+ bool fetch(int i) Q_DECL_OVERRIDE;
+ bool fetchNext() Q_DECL_OVERRIDE;
+ bool fetchFirst() Q_DECL_OVERRIDE;
+ bool fetchLast() Q_DECL_OVERRIDE;
+ bool isNull(int i) Q_DECL_OVERRIDE;
+ int size() Q_DECL_OVERRIDE;
+ int numRowsAffected() Q_DECL_OVERRIDE;
+ QSqlRecord record() const Q_DECL_OVERRIDE;
+ void virtual_hook(int id, void *data) Q_DECL_OVERRIDE;
+ void detachFromResultSet() Q_DECL_OVERRIDE;
+ bool nextResult() Q_DECL_OVERRIDE;
+};
+
+class QDB2ResultPrivate: public QSqlResultPrivate
+{
+ Q_DECLARE_PUBLIC(QDB2Result)
+
+public:
+ Q_DECLARE_SQLDRIVER_PRIVATE(QDB2Driver)
+ QDB2ResultPrivate(QDB2Result *q, const QDB2Driver *drv)
+ : QSqlResultPrivate(q, drv),
+ hStmt(0)
+ {}
+ ~QDB2ResultPrivate()
+ {
+ emptyValueCache();
+ }
+ void clearValueCache()
+ {
+ for (int i = 0; i < valueCache.count(); ++i) {
+ delete valueCache[i];
+ valueCache[i] = NULL;
+ }
+ }
+ void emptyValueCache()
+ {
+ clearValueCache();
+ valueCache.clear();
+ }
+
+ SQLHANDLE hStmt;
+ QSqlRecord recInf;
+ QVector<QVariant*> valueCache;
+};
+
+static QString qFromTChar(SQLTCHAR* str)
+{
+ return QString((const QChar *)str);
+}
+
+// dangerous!! (but fast). Don't use in functions that
+// require out parameters!
+static SQLTCHAR* qToTChar(const QString& str)
+{
+ return (SQLTCHAR*)str.utf16();
+}
+
+static QString qWarnDB2Handle(int handleType, SQLHANDLE handle)
+{
+ SQLINTEGER nativeCode;
+ SQLSMALLINT msgLen;
+ SQLRETURN r = SQL_ERROR;
+ SQLTCHAR state[SQL_SQLSTATE_SIZE + 1];
+ SQLTCHAR description[SQL_MAX_MESSAGE_LENGTH];
+ r = SQLGetDiagRec(handleType,
+ handle,
+ 1,
+ (SQLTCHAR*) state,
+ &nativeCode,
+ (SQLTCHAR*) description,
+ SQL_MAX_MESSAGE_LENGTH - 1, /* in bytes, not in characters */
+ &msgLen);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO)
+ return QString(qFromTChar(description));
+ return QString();
+}
+
+static QString qDB2Warn(const QDB2DriverPrivate* d)
+{
+ return (qWarnDB2Handle(SQL_HANDLE_ENV, d->hEnv) + QLatin1Char(' ')
+ + qWarnDB2Handle(SQL_HANDLE_DBC, d->hDbc));
+}
+
+static QString qDB2Warn(const QDB2ResultPrivate* d)
+{
+ return (qWarnDB2Handle(SQL_HANDLE_ENV, d->drv_d_func()->hEnv) + QLatin1Char(' ')
+ + qWarnDB2Handle(SQL_HANDLE_DBC, d->drv_d_func()->hDbc)
+ + qWarnDB2Handle(SQL_HANDLE_STMT, d->hStmt));
+}
+
+static void qSqlWarning(const QString& message, const QDB2DriverPrivate* d)
+{
+ qWarning("%s\tError: %s", message.toLocal8Bit().constData(),
+ qDB2Warn(d).toLocal8Bit().constData());
+}
+
+static void qSqlWarning(const QString& message, const QDB2ResultPrivate* d)
+{
+ qWarning("%s\tError: %s", message.toLocal8Bit().constData(),
+ qDB2Warn(d).toLocal8Bit().constData());
+}
+
+static QSqlError qMakeError(const QString& err, QSqlError::ErrorType type,
+ const QDB2DriverPrivate* p)
+{
+ return QSqlError(QLatin1String("QDB2: ") + err, qDB2Warn(p), type);
+}
+
+static QSqlError qMakeError(const QString& err, QSqlError::ErrorType type,
+ const QDB2ResultPrivate* p)
+{
+ return QSqlError(QLatin1String("QDB2: ") + err, qDB2Warn(p), type);
+}
+
+static QVariant::Type qDecodeDB2Type(SQLSMALLINT sqltype)
+{
+ QVariant::Type type = QVariant::Invalid;
+ switch (sqltype) {
+ case SQL_REAL:
+ case SQL_FLOAT:
+ case SQL_DOUBLE:
+ case SQL_DECIMAL:
+ case SQL_NUMERIC:
+ type = QVariant::Double;
+ break;
+ case SQL_SMALLINT:
+ case SQL_INTEGER:
+ case SQL_BIT:
+ case SQL_TINYINT:
+ type = QVariant::Int;
+ break;
+ case SQL_BIGINT:
+ type = QVariant::LongLong;
+ break;
+ case SQL_BLOB:
+ case SQL_BINARY:
+ case SQL_VARBINARY:
+ case SQL_LONGVARBINARY:
+ case SQL_CLOB:
+ case SQL_DBCLOB:
+ type = QVariant::ByteArray;
+ break;
+ case SQL_DATE:
+ case SQL_TYPE_DATE:
+ type = QVariant::Date;
+ break;
+ case SQL_TIME:
+ case SQL_TYPE_TIME:
+ type = QVariant::Time;
+ break;
+ case SQL_TIMESTAMP:
+ case SQL_TYPE_TIMESTAMP:
+ type = QVariant::DateTime;
+ break;
+ case SQL_WCHAR:
+ case SQL_WVARCHAR:
+ case SQL_WLONGVARCHAR:
+ case SQL_CHAR:
+ case SQL_VARCHAR:
+ case SQL_LONGVARCHAR:
+ type = QVariant::String;
+ break;
+ default:
+ type = QVariant::ByteArray;
+ break;
+ }
+ return type;
+}
+
+static QSqlField qMakeFieldInfo(const QDB2ResultPrivate* d, int i)
+{
+ SQLSMALLINT colNameLen;
+ SQLSMALLINT colType;
+ SQLUINTEGER colSize;
+ SQLSMALLINT colScale;
+ SQLSMALLINT nullable;
+ SQLRETURN r = SQL_ERROR;
+ SQLTCHAR colName[COLNAMESIZE];
+ r = SQLDescribeCol(d->hStmt,
+ i+1,
+ colName,
+ (SQLSMALLINT) COLNAMESIZE,
+ &colNameLen,
+ &colType,
+ &colSize,
+ &colScale,
+ &nullable);
+
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QString::fromLatin1("qMakeFieldInfo: Unable to describe column %1").arg(i), d);
+ return QSqlField();
+ }
+ QSqlField f(qFromTChar(colName), qDecodeDB2Type(colType));
+ // nullable can be SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
+ if (nullable == SQL_NO_NULLS)
+ f.setRequired(true);
+ else if (nullable == SQL_NULLABLE)
+ f.setRequired(false);
+ // else required is unknown
+ f.setLength(colSize == 0 ? -1 : int(colSize));
+ f.setPrecision(colScale == 0 ? -1 : int(colScale));
+ f.setSqlType(int(colType));
+ return f;
+}
+
+static int qGetIntData(SQLHANDLE hStmt, int column, bool& isNull)
+{
+ SQLINTEGER intbuf;
+ isNull = false;
+ SQLINTEGER lengthIndicator = 0;
+ SQLRETURN r = SQLGetData(hStmt,
+ column + 1,
+ SQL_C_SLONG,
+ (SQLPOINTER) &intbuf,
+ 0,
+ &lengthIndicator);
+ if ((r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) || lengthIndicator == SQL_NULL_DATA) {
+ isNull = true;
+ return 0;
+ }
+ return int(intbuf);
+}
+
+static double qGetDoubleData(SQLHANDLE hStmt, int column, bool& isNull)
+{
+ SQLDOUBLE dblbuf;
+ isNull = false;
+ SQLINTEGER lengthIndicator = 0;
+ SQLRETURN r = SQLGetData(hStmt,
+ column+1,
+ SQL_C_DOUBLE,
+ (SQLPOINTER) &dblbuf,
+ 0,
+ &lengthIndicator);
+ if ((r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) || lengthIndicator == SQL_NULL_DATA) {
+ isNull = true;
+ return 0.0;
+ }
+
+ return (double) dblbuf;
+}
+
+static SQLBIGINT qGetBigIntData(SQLHANDLE hStmt, int column, bool& isNull)
+{
+ SQLBIGINT lngbuf = Q_INT64_C(0);
+ isNull = false;
+ SQLINTEGER lengthIndicator = 0;
+ SQLRETURN r = SQLGetData(hStmt,
+ column+1,
+ SQL_C_SBIGINT,
+ (SQLPOINTER) &lngbuf,
+ 0,
+ &lengthIndicator);
+ if ((r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) || lengthIndicator == SQL_NULL_DATA)
+ isNull = true;
+
+ return lngbuf;
+}
+
+static QString qGetStringData(SQLHANDLE hStmt, int column, int colSize, bool& isNull)
+{
+ QString fieldVal;
+ SQLRETURN r = SQL_ERROR;
+ SQLINTEGER lengthIndicator = 0;
+
+ if (colSize <= 0)
+ colSize = 255;
+ else if (colSize > 65536) // limit buffer size to 64 KB
+ colSize = 65536;
+ else
+ colSize++; // make sure there is room for more than the 0 termination
+ SQLTCHAR* buf = new SQLTCHAR[colSize];
+
+ while (true) {
+ r = SQLGetData(hStmt,
+ column + 1,
+ SQL_C_WCHAR,
+ (SQLPOINTER)buf,
+ colSize * sizeof(SQLTCHAR),
+ &lengthIndicator);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) {
+ if (lengthIndicator == SQL_NULL_DATA || lengthIndicator == SQL_NO_TOTAL) {
+ fieldVal.clear();
+ isNull = true;
+ break;
+ }
+ fieldVal += qFromTChar(buf);
+ } else if (r == SQL_NO_DATA) {
+ break;
+ } else {
+ qWarning("qGetStringData: Error while fetching data (%d)", r);
+ fieldVal.clear();
+ break;
+ }
+ }
+ delete[] buf;
+ return fieldVal;
+}
+
+static QByteArray qGetBinaryData(SQLHANDLE hStmt, int column, SQLINTEGER& lengthIndicator, bool& isNull)
+{
+ QByteArray fieldVal;
+ SQLSMALLINT colNameLen;
+ SQLSMALLINT colType;
+ SQLUINTEGER colSize;
+ SQLSMALLINT colScale;
+ SQLSMALLINT nullable;
+ SQLRETURN r = SQL_ERROR;
+
+ SQLTCHAR colName[COLNAMESIZE];
+ r = SQLDescribeCol(hStmt,
+ column+1,
+ colName,
+ COLNAMESIZE,
+ &colNameLen,
+ &colType,
+ &colSize,
+ &colScale,
+ &nullable);
+ if (r != SQL_SUCCESS)
+ qWarning("qGetBinaryData: Unable to describe column %d", column);
+ // SQLDescribeCol may return 0 if size cannot be determined
+ if (!colSize)
+ colSize = 255;
+ else if (colSize > 65536) // read the field in 64 KB chunks
+ colSize = 65536;
+ char * buf = new char[colSize];
+ while (true) {
+ r = SQLGetData(hStmt,
+ column+1,
+ colType == SQL_DBCLOB ? SQL_C_CHAR : SQL_C_BINARY,
+ (SQLPOINTER) buf,
+ colSize,
+ &lengthIndicator);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) {
+ if (lengthIndicator == SQL_NULL_DATA) {
+ isNull = true;
+ break;
+ } else {
+ int rSize;
+ r == SQL_SUCCESS ? rSize = lengthIndicator : rSize = colSize;
+ if (lengthIndicator == SQL_NO_TOTAL) // size cannot be determined
+ rSize = colSize;
+ fieldVal.append(QByteArray(buf, rSize));
+ if (r == SQL_SUCCESS) // the whole field was read in one chunk
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+ delete [] buf;
+ return fieldVal;
+}
+
+static void qSplitTableQualifier(const QString & qualifier, QString * catalog,
+ QString * schema, QString * table)
+{
+ if (!catalog || !schema || !table)
+ return;
+ QStringList l = qualifier.split(QLatin1Char('.'));
+ if (l.count() > 3)
+ return; // can't possibly be a valid table qualifier
+ int i = 0, n = l.count();
+ if (n == 1) {
+ *table = qualifier;
+ } else {
+ for (QStringList::Iterator it = l.begin(); it != l.end(); ++it) {
+ if (n == 3) {
+ if (i == 0)
+ *catalog = *it;
+ else if (i == 1)
+ *schema = *it;
+ else if (i == 2)
+ *table = *it;
+ } else if (n == 2) {
+ if (i == 0)
+ *schema = *it;
+ else if (i == 1)
+ *table = *it;
+ }
+ i++;
+ }
+ }
+}
+
+// creates a QSqlField from a valid hStmt generated
+// by SQLColumns. The hStmt has to point to a valid position.
+static QSqlField qMakeFieldInfo(const SQLHANDLE hStmt)
+{
+ bool isNull;
+ int type = qGetIntData(hStmt, 4, isNull);
+ QSqlField f(qGetStringData(hStmt, 3, -1, isNull), qDecodeDB2Type(type));
+ int required = qGetIntData(hStmt, 10, isNull); // nullable-flag
+ // required can be SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
+ if (required == SQL_NO_NULLS)
+ f.setRequired(true);
+ else if (required == SQL_NULLABLE)
+ f.setRequired(false);
+ // else we don't know.
+ f.setLength(qGetIntData(hStmt, 6, isNull)); // column size
+ f.setPrecision(qGetIntData(hStmt, 8, isNull)); // precision
+ f.setSqlType(type);
+ return f;
+}
+
+static bool qMakeStatement(QDB2ResultPrivate* d, bool forwardOnly, bool setForwardOnly = true)
+{
+ SQLRETURN r;
+ if (!d->hStmt) {
+ r = SQLAllocHandle(SQL_HANDLE_STMT,
+ d->drv_d_func()->hDbc,
+ &d->hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QDB2Result::reset: Unable to allocate statement handle"), d);
+ return false;
+ }
+ } else {
+ r = SQLFreeStmt(d->hStmt, SQL_CLOSE);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QDB2Result::reset: Unable to close statement handle"), d);
+ return false;
+ }
+ }
+
+ if (!setForwardOnly)
+ return true;
+
+ if (forwardOnly) {
+ r = SQLSetStmtAttr(d->hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER) SQL_CURSOR_FORWARD_ONLY,
+ SQL_IS_UINTEGER);
+ } else {
+ r = SQLSetStmtAttr(d->hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER) SQL_CURSOR_STATIC,
+ SQL_IS_UINTEGER);
+ }
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ qSqlWarning(QString::fromLatin1("QDB2Result::reset: Unable to set %1 attribute.").arg(
+ forwardOnly ? QLatin1String("SQL_CURSOR_FORWARD_ONLY")
+ : QLatin1String("SQL_CURSOR_STATIC")), d);
+ return false;
+ }
+ return true;
+}
+
+QVariant QDB2Result::handle() const
+{
+ Q_D(const QDB2Result);
+ return QVariant(qRegisterMetaType<SQLHANDLE>("SQLHANDLE"), &d->hStmt);
+}
+
+/************************************/
+
+QDB2Result::QDB2Result(const QDB2Driver *drv)
+ : QSqlResult(*new QDB2ResultPrivate(this, drv))
+{
+}
+
+QDB2Result::~QDB2Result()
+{
+ Q_D(const QDB2Result);
+ if (d->hStmt) {
+ SQLRETURN r = SQLFreeHandle(SQL_HANDLE_STMT, d->hStmt);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QDB2Driver: Unable to free statement handle ")
+ + QString::number(r), d);
+ }
+}
+
+bool QDB2Result::reset (const QString& query)
+{
+ Q_D(QDB2Result);
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+ SQLRETURN r;
+
+ d->recInf.clear();
+ d->emptyValueCache();
+
+ if (!qMakeStatement(d, isForwardOnly()))
+ return false;
+
+ r = SQLExecDirect(d->hStmt,
+ qToTChar(query),
+ (SQLINTEGER) query.length());
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ setLastError(qMakeError(QCoreApplication::translate("QDB2Result",
+ "Unable to execute statement"), QSqlError::StatementError, d));
+ return false;
+ }
+ SQLSMALLINT count = 0;
+ r = SQLNumResultCols(d->hStmt, &count);
+ if (count) {
+ setSelect(true);
+ for (int i = 0; i < count; ++i) {
+ d->recInf.append(qMakeFieldInfo(d, i));
+ }
+ } else {
+ setSelect(false);
+ }
+ d->valueCache.resize(count);
+ d->valueCache.fill(NULL);
+ setActive(true);
+ return true;
+}
+
+bool QDB2Result::prepare(const QString& query)
+{
+ Q_D(QDB2Result);
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+ SQLRETURN r;
+
+ d->recInf.clear();
+ d->emptyValueCache();
+
+ if (!qMakeStatement(d, isForwardOnly()))
+ return false;
+
+ r = SQLPrepare(d->hStmt,
+ qToTChar(query),
+ (SQLINTEGER) query.length());
+
+ if (r != SQL_SUCCESS) {
+ setLastError(qMakeError(QCoreApplication::translate("QDB2Result",
+ "Unable to prepare statement"), QSqlError::StatementError, d));
+ return false;
+ }
+ return true;
+}
+
+bool QDB2Result::exec()
+{
+ Q_D(QDB2Result);
+ QList<QByteArray> tmpStorage; // holds temporary ptrs
+ QVarLengthArray<SQLINTEGER, 32> indicators(boundValues().count());
+
+ memset(indicators.data(), 0, indicators.size() * sizeof(SQLINTEGER));
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+ SQLRETURN r;
+
+ d->recInf.clear();
+ d->emptyValueCache();
+
+ if (!qMakeStatement(d, isForwardOnly(), false))
+ return false;
+
+
+ QVector<QVariant> &values = boundValues();
+ int i;
+ for (i = 0; i < values.count(); ++i) {
+ // bind parameters - only positional binding allowed
+ SQLINTEGER *ind = &indicators[i];
+ if (values.at(i).isNull())
+ *ind = SQL_NULL_DATA;
+ if (bindValueType(i) & QSql::Out)
+ values[i].detach();
+
+ switch (values.at(i).type()) {
+ case QVariant::Date: {
+ QByteArray ba;
+ ba.resize(sizeof(DATE_STRUCT));
+ DATE_STRUCT *dt = (DATE_STRUCT *)ba.constData();
+ QDate qdt = values.at(i).toDate();
+ dt->year = qdt.year();
+ dt->month = qdt.month();
+ dt->day = qdt.day();
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & 3],
+ SQL_C_DATE,
+ SQL_DATE,
+ 0,
+ 0,
+ (void *) dt,
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ tmpStorage.append(ba);
+ break; }
+ case QVariant::Time: {
+ QByteArray ba;
+ ba.resize(sizeof(TIME_STRUCT));
+ TIME_STRUCT *dt = (TIME_STRUCT *)ba.constData();
+ QTime qdt = values.at(i).toTime();
+ dt->hour = qdt.hour();
+ dt->minute = qdt.minute();
+ dt->second = qdt.second();
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & 3],
+ SQL_C_TIME,
+ SQL_TIME,
+ 0,
+ 0,
+ (void *) dt,
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ tmpStorage.append(ba);
+ break; }
+ case QVariant::DateTime: {
+ QByteArray ba;
+ ba.resize(sizeof(TIMESTAMP_STRUCT));
+ TIMESTAMP_STRUCT * dt = (TIMESTAMP_STRUCT *)ba.constData();
+ QDateTime qdt = values.at(i).toDateTime();
+ dt->year = qdt.date().year();
+ dt->month = qdt.date().month();
+ dt->day = qdt.date().day();
+ dt->hour = qdt.time().hour();
+ dt->minute = qdt.time().minute();
+ dt->second = qdt.time().second();
+ dt->fraction = qdt.time().msec() * 1000000;
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & 3],
+ SQL_C_TIMESTAMP,
+ SQL_TIMESTAMP,
+ 0,
+ 0,
+ (void *) dt,
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ tmpStorage.append(ba);
+ break; }
+ case QVariant::Int:
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & 3],
+ SQL_C_SLONG,
+ SQL_INTEGER,
+ 0,
+ 0,
+ (void *)values.at(i).constData(),
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break;
+ case QVariant::Double:
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & 3],
+ SQL_C_DOUBLE,
+ SQL_DOUBLE,
+ 0,
+ 0,
+ (void *)values.at(i).constData(),
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break;
+ case QVariant::ByteArray: {
+ int len = values.at(i).toByteArray().size();
+ if (*ind != SQL_NULL_DATA)
+ *ind = len;
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & 3],
+ SQL_C_BINARY,
+ SQL_LONGVARBINARY,
+ len,
+ 0,
+ (void *)values.at(i).toByteArray().constData(),
+ len,
+ ind);
+ break; }
+ case QVariant::String:
+ {
+ QString str(values.at(i).toString());
+ if (*ind != SQL_NULL_DATA)
+ *ind = str.length() * sizeof(QChar);
+ if (bindValueType(i) & QSql::Out) {
+ QByteArray ba((char*)str.utf16(), str.capacity() * sizeof(QChar));
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & 3],
+ SQL_C_WCHAR,
+ SQL_WVARCHAR,
+ str.length(),
+ 0,
+ (void *)ba.constData(),
+ ba.size(),
+ ind);
+ tmpStorage.append(ba);
+ } else {
+ void *data = (void*)str.utf16();
+ int len = str.length();
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & 3],
+ SQL_C_WCHAR,
+ SQL_WVARCHAR,
+ len,
+ 0,
+ data,
+ len * sizeof(QChar),
+ ind);
+ }
+ break;
+ }
+ default: {
+ QByteArray ba = values.at(i).toString().toLatin1();
+ int len = ba.length() + 1;
+ if (*ind != SQL_NULL_DATA)
+ *ind = ba.length();
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & 3],
+ SQL_C_CHAR,
+ SQL_VARCHAR,
+ len,
+ 0,
+ (void *) ba.constData(),
+ len,
+ ind);
+ tmpStorage.append(ba);
+ break; }
+ }
+ if (r != SQL_SUCCESS) {
+ qWarning("QDB2Result::exec: unable to bind variable: %s",
+ qDB2Warn(d).toLocal8Bit().constData());
+ setLastError(qMakeError(QCoreApplication::translate("QDB2Result",
+ "Unable to bind variable"), QSqlError::StatementError, d));
+ return false;
+ }
+ }
+
+ r = SQLExecute(d->hStmt);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ qWarning("QDB2Result::exec: Unable to execute statement: %s",
+ qDB2Warn(d).toLocal8Bit().constData());
+ setLastError(qMakeError(QCoreApplication::translate("QDB2Result",
+ "Unable to execute statement"), QSqlError::StatementError, d));
+ return false;
+ }
+ SQLSMALLINT count = 0;
+ r = SQLNumResultCols(d->hStmt, &count);
+ if (count) {
+ setSelect(true);
+ for (int i = 0; i < count; ++i) {
+ d->recInf.append(qMakeFieldInfo(d, i));
+ }
+ } else {
+ setSelect(false);
+ }
+ setActive(true);
+ d->valueCache.resize(count);
+ d->valueCache.fill(NULL);
+
+ //get out parameters
+ if (!hasOutValues())
+ return true;
+
+ for (i = 0; i < values.count(); ++i) {
+ switch (values[i].type()) {
+ case QVariant::Date: {
+ DATE_STRUCT ds = *((DATE_STRUCT *)tmpStorage.takeFirst().constData());
+ values[i] = QVariant(QDate(ds.year, ds.month, ds.day));
+ break; }
+ case QVariant::Time: {
+ TIME_STRUCT dt = *((TIME_STRUCT *)tmpStorage.takeFirst().constData());
+ values[i] = QVariant(QTime(dt.hour, dt.minute, dt.second));
+ break; }
+ case QVariant::DateTime: {
+ TIMESTAMP_STRUCT dt = *((TIMESTAMP_STRUCT *)tmpStorage.takeFirst().constData());
+ values[i] = QVariant(QDateTime(QDate(dt.year, dt.month, dt.day),
+ QTime(dt.hour, dt.minute, dt.second, dt.fraction / 1000000)));
+ break; }
+ case QVariant::Int:
+ case QVariant::Double:
+ case QVariant::ByteArray:
+ break;
+ case QVariant::String:
+ if (bindValueType(i) & QSql::Out)
+ values[i] = QString((const QChar *)tmpStorage.takeFirst().constData());
+ break;
+ default: {
+ values[i] = QString::fromLatin1(tmpStorage.takeFirst().constData());
+ break; }
+ }
+ if (indicators[i] == SQL_NULL_DATA)
+ values[i] = QVariant(values[i].type());
+ }
+ return true;
+}
+
+bool QDB2Result::fetch(int i)
+{
+ Q_D(QDB2Result);
+ if (isForwardOnly() && i < at())
+ return false;
+ if (i == at())
+ return true;
+ d->clearValueCache();
+ int actualIdx = i + 1;
+ if (actualIdx <= 0) {
+ setAt(QSql::BeforeFirstRow);
+ return false;
+ }
+ SQLRETURN r;
+ if (isForwardOnly()) {
+ bool ok = true;
+ while (ok && i > at())
+ ok = fetchNext();
+ return ok;
+ } else {
+ r = SQLFetchScroll(d->hStmt,
+ SQL_FETCH_ABSOLUTE,
+ actualIdx);
+ }
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO && r != SQL_NO_DATA) {
+ setLastError(qMakeError(QCoreApplication::translate("QDB2Result",
+ "Unable to fetch record %1").arg(i), QSqlError::StatementError, d));
+ return false;
+ }
+ else if (r == SQL_NO_DATA)
+ return false;
+ setAt(i);
+ return true;
+}
+
+bool QDB2Result::fetchNext()
+{
+ Q_D(QDB2Result);
+ SQLRETURN r;
+ d->clearValueCache();
+ r = SQLFetchScroll(d->hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ if (r != SQL_NO_DATA)
+ setLastError(qMakeError(QCoreApplication::translate("QDB2Result",
+ "Unable to fetch next"), QSqlError::StatementError, d));
+ return false;
+ }
+ setAt(at() + 1);
+ return true;
+}
+
+bool QDB2Result::fetchFirst()
+{
+ Q_D(QDB2Result);
+ if (isForwardOnly() && at() != QSql::BeforeFirstRow)
+ return false;
+ if (isForwardOnly())
+ return fetchNext();
+ d->clearValueCache();
+ SQLRETURN r;
+ r = SQLFetchScroll(d->hStmt,
+ SQL_FETCH_FIRST,
+ 0);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ if(r!= SQL_NO_DATA)
+ setLastError(qMakeError(QCoreApplication::translate("QDB2Result", "Unable to fetch first"),
+ QSqlError::StatementError, d));
+ return false;
+ }
+ setAt(0);
+ return true;
+}
+
+bool QDB2Result::fetchLast()
+{
+ Q_D(QDB2Result);
+ d->clearValueCache();
+
+ int i = at();
+ if (i == QSql::AfterLastRow) {
+ if (isForwardOnly()) {
+ return false;
+ } else {
+ if (!fetch(0))
+ return false;
+ i = at();
+ }
+ }
+
+ while (fetchNext())
+ ++i;
+
+ if (i == QSql::BeforeFirstRow) {
+ setAt(QSql::AfterLastRow);
+ return false;
+ }
+
+ if (!isForwardOnly())
+ return fetch(i);
+
+ setAt(i);
+ return true;
+}
+
+
+QVariant QDB2Result::data(int field)
+{
+ Q_D(QDB2Result);
+ if (field >= d->recInf.count()) {
+ qWarning("QDB2Result::data: column %d out of range", field);
+ return QVariant();
+ }
+ SQLRETURN r = 0;
+ SQLINTEGER lengthIndicator = 0;
+ bool isNull = false;
+ const QSqlField info = d->recInf.field(field);
+
+ if (!info.isValid() || field >= d->valueCache.size())
+ return QVariant();
+
+ if (d->valueCache[field])
+ return *d->valueCache[field];
+
+
+ QVariant* v = 0;
+ switch (info.type()) {
+ case QVariant::LongLong:
+ v = new QVariant((qint64) qGetBigIntData(d->hStmt, field, isNull));
+ break;
+ case QVariant::Int:
+ v = new QVariant(qGetIntData(d->hStmt, field, isNull));
+ break;
+ case QVariant::Date: {
+ DATE_STRUCT dbuf;
+ r = SQLGetData(d->hStmt,
+ field + 1,
+ SQL_C_DATE,
+ (SQLPOINTER) &dbuf,
+ 0,
+ &lengthIndicator);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && (lengthIndicator != SQL_NULL_DATA)) {
+ v = new QVariant(QDate(dbuf.year, dbuf.month, dbuf.day));
+ } else {
+ v = new QVariant(QDate());
+ isNull = true;
+ }
+ break; }
+ case QVariant::Time: {
+ TIME_STRUCT tbuf;
+ r = SQLGetData(d->hStmt,
+ field + 1,
+ SQL_C_TIME,
+ (SQLPOINTER) &tbuf,
+ 0,
+ &lengthIndicator);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && (lengthIndicator != SQL_NULL_DATA)) {
+ v = new QVariant(QTime(tbuf.hour, tbuf.minute, tbuf.second));
+ } else {
+ v = new QVariant(QTime());
+ isNull = true;
+ }
+ break; }
+ case QVariant::DateTime: {
+ TIMESTAMP_STRUCT dtbuf;
+ r = SQLGetData(d->hStmt,
+ field + 1,
+ SQL_C_TIMESTAMP,
+ (SQLPOINTER) &dtbuf,
+ 0,
+ &lengthIndicator);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && (lengthIndicator != SQL_NULL_DATA)) {
+ v = new QVariant(QDateTime(QDate(dtbuf.year, dtbuf.month, dtbuf.day),
+ QTime(dtbuf.hour, dtbuf.minute, dtbuf.second, dtbuf.fraction / 1000000)));
+ } else {
+ v = new QVariant(QDateTime());
+ isNull = true;
+ }
+ break; }
+ case QVariant::ByteArray:
+ v = new QVariant(qGetBinaryData(d->hStmt, field, lengthIndicator, isNull));
+ break;
+ case QVariant::Double:
+ {
+ switch(numericalPrecisionPolicy()) {
+ case QSql::LowPrecisionInt32:
+ v = new QVariant(qGetIntData(d->hStmt, field, isNull));
+ break;
+ case QSql::LowPrecisionInt64:
+ v = new QVariant((qint64) qGetBigIntData(d->hStmt, field, isNull));
+ break;
+ case QSql::LowPrecisionDouble:
+ v = new QVariant(qGetDoubleData(d->hStmt, field, isNull));
+ break;
+ case QSql::HighPrecision:
+ default:
+ // length + 1 for the comma
+ v = new QVariant(qGetStringData(d->hStmt, field, info.length() + 1, isNull));
+ break;
+ }
+ break;
+ }
+ case QVariant::String:
+ default:
+ v = new QVariant(qGetStringData(d->hStmt, field, info.length(), isNull));
+ break;
+ }
+ if (isNull)
+ *v = QVariant(info.type());
+ d->valueCache[field] = v;
+ return *v;
+}
+
+bool QDB2Result::isNull(int i)
+{
+ Q_D(const QDB2Result);
+ if (i >= d->valueCache.size())
+ return true;
+
+ if (d->valueCache[i])
+ return d->valueCache[i]->isNull();
+ return data(i).isNull();
+}
+
+int QDB2Result::numRowsAffected()
+{
+ Q_D(const QDB2Result);
+ SQLINTEGER affectedRowCount = 0;
+ SQLRETURN r = SQLRowCount(d->hStmt, &affectedRowCount);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO)
+ return affectedRowCount;
+ else
+ qSqlWarning(QLatin1String("QDB2Result::numRowsAffected: Unable to count affected rows"), d);
+ return -1;
+}
+
+int QDB2Result::size()
+{
+ return -1;
+}
+
+QSqlRecord QDB2Result::record() const
+{
+ Q_D(const QDB2Result);
+ if (isActive())
+ return d->recInf;
+ return QSqlRecord();
+}
+
+bool QDB2Result::nextResult()
+{
+ Q_D(QDB2Result);
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+ d->recInf.clear();
+ d->emptyValueCache();
+ setSelect(false);
+
+ SQLRETURN r = SQLMoreResults(d->hStmt);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ if (r != SQL_NO_DATA) {
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to fetch last"), QSqlError::ConnectionError, d));
+ }
+ return false;
+ }
+
+ SQLSMALLINT fieldCount = 0;
+ r = SQLNumResultCols(d->hStmt, &fieldCount);
+ setSelect(fieldCount > 0);
+ for (int i = 0; i < fieldCount; ++i)
+ d->recInf.append(qMakeFieldInfo(d, i));
+
+ d->valueCache.resize(fieldCount);
+ d->valueCache.fill(NULL);
+ setActive(true);
+
+ return true;
+}
+
+void QDB2Result::virtual_hook(int id, void *data)
+{
+ QSqlResult::virtual_hook(id, data);
+}
+
+void QDB2Result::detachFromResultSet()
+{
+ Q_D(QDB2Result);
+ if (d->hStmt)
+ SQLCloseCursor(d->hStmt);
+}
+
+/************************************/
+
+QDB2Driver::QDB2Driver(QObject* parent)
+ : QSqlDriver(*new QDB2DriverPrivate, parent)
+{
+}
+
+QDB2Driver::QDB2Driver(Qt::HANDLE env, Qt::HANDLE con, QObject* parent)
+ : QSqlDriver(*new QDB2DriverPrivate, parent)
+{
+ Q_D(QDB2Driver);
+ d->hEnv = reinterpret_cast<SQLHANDLE>(env);
+ d->hDbc = reinterpret_cast<SQLHANDLE>(con);
+ if (env && con) {
+ setOpen(true);
+ setOpenError(false);
+ }
+}
+
+QDB2Driver::~QDB2Driver()
+{
+ close();
+}
+
+bool QDB2Driver::open(const QString& db, const QString& user, const QString& password, const QString& host, int port,
+ const QString& connOpts)
+{
+ Q_D(QDB2Driver);
+ if (isOpen())
+ close();
+ SQLRETURN r;
+ r = SQLAllocHandle(SQL_HANDLE_ENV,
+ SQL_NULL_HANDLE,
+ &d->hEnv);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ qSqlWarning(QLatin1String("QDB2Driver::open: Unable to allocate environment"), d);
+ setOpenError(true);
+ return false;
+ }
+
+ r = SQLAllocHandle(SQL_HANDLE_DBC,
+ d->hEnv,
+ &d->hDbc);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ qSqlWarning(QLatin1String("QDB2Driver::open: Unable to allocate connection"), d);
+ setOpenError(true);
+ return false;
+ }
+
+ QString protocol;
+ // Set connection attributes
+ const QStringList opts(connOpts.split(QLatin1Char(';'), QString::SkipEmptyParts));
+ for (int i = 0; i < opts.count(); ++i) {
+ const QString tmp(opts.at(i));
+ int idx;
+ if ((idx = tmp.indexOf(QLatin1Char('='))) == -1) {
+ qWarning("QDB2Driver::open: Illegal connect option value '%s'",
+ tmp.toLocal8Bit().constData());
+ continue;
+ }
+
+ const QString opt(tmp.left(idx));
+ const QString val(tmp.mid(idx + 1).simplified());
+
+ SQLUINTEGER v = 0;
+ r = SQL_SUCCESS;
+ if (opt == QLatin1String("SQL_ATTR_ACCESS_MODE")) {
+ if (val == QLatin1String("SQL_MODE_READ_ONLY")) {
+ v = SQL_MODE_READ_ONLY;
+ } else if (val == QLatin1String("SQL_MODE_READ_WRITE")) {
+ v = SQL_MODE_READ_WRITE;
+ } else {
+ qWarning("QDB2Driver::open: Unknown option value '%s'",
+ tmp.toLocal8Bit().constData());
+ continue;
+ }
+ r = SQLSetConnectAttr(d->hDbc, SQL_ATTR_ACCESS_MODE, reinterpret_cast<SQLPOINTER>(v), 0);
+ } else if (opt == QLatin1String("SQL_ATTR_LOGIN_TIMEOUT")) {
+ v = val.toUInt();
+ r = SQLSetConnectAttr(d->hDbc, SQL_ATTR_LOGIN_TIMEOUT, reinterpret_cast<SQLPOINTER>(v), 0);
+ } else if (opt.compare(QLatin1String("PROTOCOL"), Qt::CaseInsensitive) == 0) {
+ protocol = tmp;
+ }
+ else {
+ qWarning("QDB2Driver::open: Unknown connection attribute '%s'",
+ tmp.toLocal8Bit().constData());
+ }
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO)
+ qSqlWarning(QString::fromLatin1("QDB2Driver::open: "
+ "Unable to set connection attribute '%1'").arg(opt), d);
+ }
+
+ if (protocol.isEmpty())
+ protocol = QLatin1String("PROTOCOL=TCPIP");
+
+ if (port < 0 )
+ port = 50000;
+
+ QString connQStr;
+ connQStr = protocol + QLatin1String(";DATABASE=") + db + QLatin1String(";HOSTNAME=") + host
+ + QLatin1String(";PORT=") + QString::number(port) + QLatin1String(";UID=") + user
+ + QLatin1String(";PWD=") + password;
+
+
+ SQLTCHAR connOut[SQL_MAX_OPTION_STRING_LENGTH];
+ SQLSMALLINT cb;
+
+ r = SQLDriverConnect(d->hDbc,
+ NULL,
+ qToTChar(connQStr),
+ (SQLSMALLINT) connQStr.length(),
+ connOut,
+ SQL_MAX_OPTION_STRING_LENGTH,
+ &cb,
+ SQL_DRIVER_NOPROMPT);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ setLastError(qMakeError(tr("Unable to connect"),
+ QSqlError::ConnectionError, d));
+ setOpenError(true);
+ return false;
+ }
+
+ d->user = user;
+ setOpen(true);
+ setOpenError(false);
+ return true;
+}
+
+void QDB2Driver::close()
+{
+ Q_D(QDB2Driver);
+ SQLRETURN r;
+ if (d->hDbc) {
+ // Open statements/descriptors handles are automatically cleaned up by SQLDisconnect
+ if (isOpen()) {
+ r = SQLDisconnect(d->hDbc);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QDB2Driver::close: Unable to disconnect datasource"), d);
+ }
+ r = SQLFreeHandle(SQL_HANDLE_DBC, d->hDbc);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QDB2Driver::close: Unable to free connection handle"), d);
+ d->hDbc = 0;
+ }
+
+ if (d->hEnv) {
+ r = SQLFreeHandle(SQL_HANDLE_ENV, d->hEnv);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QDB2Driver::close: Unable to free environment handle"), d);
+ d->hEnv = 0;
+ }
+ setOpen(false);
+ setOpenError(false);
+}
+
+QSqlResult *QDB2Driver::createResult() const
+{
+ return new QDB2Result(this);
+}
+
+QSqlRecord QDB2Driver::record(const QString& tableName) const
+{
+ Q_D(const QDB2Driver);
+ QSqlRecord fil;
+ if (!isOpen())
+ return fil;
+
+ SQLHANDLE hStmt;
+ QString catalog, schema, table;
+ qSplitTableQualifier(tableName, &catalog, &schema, &table);
+ if (schema.isEmpty())
+ schema = d->user;
+
+ if (isIdentifierEscaped(catalog, QSqlDriver::TableName))
+ catalog = stripDelimiters(catalog, QSqlDriver::TableName);
+ else
+ catalog = catalog.toUpper();
+
+ if (isIdentifierEscaped(schema, QSqlDriver::TableName))
+ schema = stripDelimiters(schema, QSqlDriver::TableName);
+ else
+ schema = schema.toUpper();
+
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+ else
+ table = table.toUpper();
+
+ SQLRETURN r = SQLAllocHandle(SQL_HANDLE_STMT,
+ d->hDbc,
+ &hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QDB2Driver::record: Unable to allocate handle"), d);
+ return fil;
+ }
+
+ r = SQLSetStmtAttr(hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER) SQL_CURSOR_FORWARD_ONLY,
+ SQL_IS_UINTEGER);
+
+
+ //Aside: szSchemaName and szTableName parameters of SQLColumns
+ //are case sensitive search patterns, so no escaping is used.
+ r = SQLColumns(hStmt,
+ NULL,
+ 0,
+ qToTChar(schema),
+ schema.length(),
+ qToTChar(table),
+ table.length(),
+ NULL,
+ 0);
+
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QDB2Driver::record: Unable to execute column list"), d);
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ while (r == SQL_SUCCESS) {
+ fil.append(qMakeFieldInfo(hStmt));
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ }
+
+ r = SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QDB2Driver: Unable to free statement handle ")
+ + QString::number(r), d);
+
+ return fil;
+}
+
+QStringList QDB2Driver::tables(QSql::TableType type) const
+{
+ Q_D(const QDB2Driver);
+ QStringList tl;
+ if (!isOpen())
+ return tl;
+
+ SQLHANDLE hStmt;
+
+ SQLRETURN r = SQLAllocHandle(SQL_HANDLE_STMT,
+ d->hDbc,
+ &hStmt);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ qSqlWarning(QLatin1String("QDB2Driver::tables: Unable to allocate handle"), d);
+ return tl;
+ }
+ r = SQLSetStmtAttr(hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER)SQL_CURSOR_FORWARD_ONLY,
+ SQL_IS_UINTEGER);
+
+ QString tableType;
+ if (type & QSql::Tables)
+ tableType += QLatin1String("TABLE,");
+ if (type & QSql::Views)
+ tableType += QLatin1String("VIEW,");
+ if (type & QSql::SystemTables)
+ tableType += QLatin1String("SYSTEM TABLE,");
+ if (tableType.isEmpty())
+ return tl;
+ tableType.chop(1);
+
+ r = SQLTables(hStmt,
+ NULL,
+ 0,
+ NULL,
+ 0,
+ NULL,
+ 0,
+ qToTChar(tableType),
+ tableType.length());
+
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO)
+ qSqlWarning(QLatin1String("QDB2Driver::tables: Unable to execute table list"), d);
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ while (r == SQL_SUCCESS) {
+ bool isNull;
+ QString fieldVal = qGetStringData(hStmt, 2, -1, isNull);
+ QString userVal = qGetStringData(hStmt, 1, -1, isNull);
+ QString user = d->user;
+ if ( isIdentifierEscaped(user, QSqlDriver::TableName))
+ user = stripDelimiters(user, QSqlDriver::TableName);
+ else
+ user = user.toUpper();
+
+ if (userVal != user)
+ fieldVal = userVal + QLatin1Char('.') + fieldVal;
+ tl.append(fieldVal);
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ }
+
+ r = SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QDB2Driver::tables: Unable to free statement handle ")
+ + QString::number(r), d);
+ return tl;
+}
+
+QSqlIndex QDB2Driver::primaryIndex(const QString& tablename) const
+{
+ Q_D(const QDB2Driver);
+ QSqlIndex index(tablename);
+ if (!isOpen())
+ return index;
+ QSqlRecord rec = record(tablename);
+
+ SQLHANDLE hStmt;
+ SQLRETURN r = SQLAllocHandle(SQL_HANDLE_STMT,
+ d->hDbc,
+ &hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QDB2Driver::primaryIndex: Unable to list primary key"), d);
+ return index;
+ }
+ QString catalog, schema, table;
+ qSplitTableQualifier(tablename, &catalog, &schema, &table);
+
+ if (isIdentifierEscaped(catalog, QSqlDriver::TableName))
+ catalog = stripDelimiters(catalog, QSqlDriver::TableName);
+ else
+ catalog = catalog.toUpper();
+
+ if (isIdentifierEscaped(schema, QSqlDriver::TableName))
+ schema = stripDelimiters(schema, QSqlDriver::TableName);
+ else
+ schema = schema.toUpper();
+
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+ else
+ table = table.toUpper();
+
+ r = SQLSetStmtAttr(hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER)SQL_CURSOR_FORWARD_ONLY,
+ SQL_IS_UINTEGER);
+
+ r = SQLPrimaryKeys(hStmt,
+ NULL,
+ 0,
+ qToTChar(schema),
+ schema.length(),
+ qToTChar(table),
+ table.length());
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+
+ bool isNull;
+ QString cName, idxName;
+ // Store all fields in a StringList because the driver can't detail fields in this FETCH loop
+ while (r == SQL_SUCCESS) {
+ cName = qGetStringData(hStmt, 3, -1, isNull); // column name
+ idxName = qGetStringData(hStmt, 5, -1, isNull); // pk index name
+ index.append(rec.field(cName));
+ index.setName(idxName);
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ }
+ r = SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
+ if (r!= SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QDB2Driver: Unable to free statement handle ")
+ + QString::number(r), d);
+ return index;
+}
+
+bool QDB2Driver::hasFeature(DriverFeature f) const
+{
+ switch (f) {
+ case QuerySize:
+ case NamedPlaceholders:
+ case BatchOperations:
+ case LastInsertId:
+ case SimpleLocking:
+ case EventNotifications:
+ case CancelQuery:
+ return false;
+ case BLOB:
+ case Transactions:
+ case MultipleResultSets:
+ case PreparedQueries:
+ case PositionalPlaceholders:
+ case LowPrecisionNumbers:
+ case FinishQuery:
+ return true;
+ case Unicode:
+ return true;
+ }
+ return false;
+}
+
+bool QDB2Driver::beginTransaction()
+{
+ if (!isOpen()) {
+ qWarning("QDB2Driver::beginTransaction: Database not open");
+ return false;
+ }
+ return setAutoCommit(false);
+}
+
+bool QDB2Driver::commitTransaction()
+{
+ Q_D(QDB2Driver);
+ if (!isOpen()) {
+ qWarning("QDB2Driver::commitTransaction: Database not open");
+ return false;
+ }
+ SQLRETURN r = SQLEndTran(SQL_HANDLE_DBC,
+ d->hDbc,
+ SQL_COMMIT);
+ if (r != SQL_SUCCESS) {
+ setLastError(qMakeError(tr("Unable to commit transaction"),
+ QSqlError::TransactionError, d));
+ return false;
+ }
+ return setAutoCommit(true);
+}
+
+bool QDB2Driver::rollbackTransaction()
+{
+ Q_D(QDB2Driver);
+ if (!isOpen()) {
+ qWarning("QDB2Driver::rollbackTransaction: Database not open");
+ return false;
+ }
+ SQLRETURN r = SQLEndTran(SQL_HANDLE_DBC,
+ d->hDbc,
+ SQL_ROLLBACK);
+ if (r != SQL_SUCCESS) {
+ setLastError(qMakeError(tr("Unable to rollback transaction"),
+ QSqlError::TransactionError, d));
+ return false;
+ }
+ return setAutoCommit(true);
+}
+
+bool QDB2Driver::setAutoCommit(bool autoCommit)
+{
+ Q_D(QDB2Driver);
+ SQLUINTEGER ac = autoCommit ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF;
+ SQLRETURN r = SQLSetConnectAttr(d->hDbc,
+ SQL_ATTR_AUTOCOMMIT,
+ reinterpret_cast<SQLPOINTER>(ac),
+ sizeof(ac));
+ if (r != SQL_SUCCESS) {
+ setLastError(qMakeError(tr("Unable to set autocommit"),
+ QSqlError::TransactionError, d));
+ return false;
+ }
+ return true;
+}
+
+QString QDB2Driver::formatValue(const QSqlField &field, bool trimStrings) const
+{
+ if (field.isNull())
+ return QLatin1String("NULL");
+
+ switch (field.type()) {
+ case QVariant::DateTime: {
+ // Use an escape sequence for the datetime fields
+ if (field.value().toDateTime().isValid()) {
+ QDate dt = field.value().toDateTime().date();
+ QTime tm = field.value().toDateTime().time();
+ // Dateformat has to be "yyyy-MM-dd hh:mm:ss", with leading zeroes if month or day < 10
+ return QLatin1Char('\'') + QString::number(dt.year()) + QLatin1Char('-')
+ + QString::number(dt.month()) + QLatin1Char('-')
+ + QString::number(dt.day()) + QLatin1Char('-')
+ + QString::number(tm.hour()) + QLatin1Char('.')
+ + QString::number(tm.minute()).rightJustified(2, QLatin1Char('0'), true)
+ + QLatin1Char('.')
+ + QString::number(tm.second()).rightJustified(2, QLatin1Char('0'), true)
+ + QLatin1Char('.')
+ + QString::number(tm.msec() * 1000).rightJustified(6, QLatin1Char('0'), true)
+ + QLatin1Char('\'');
+ } else {
+ return QLatin1String("NULL");
+ }
+ }
+ case QVariant::ByteArray: {
+ QByteArray ba = field.value().toByteArray();
+ QString res;
+ res += QLatin1String("BLOB(X'");
+ static const char hexchars[] = "0123456789abcdef";
+ for (int i = 0; i < ba.size(); ++i) {
+ uchar s = (uchar) ba[i];
+ res += QLatin1Char(hexchars[s >> 4]);
+ res += QLatin1Char(hexchars[s & 0x0f]);
+ }
+ res += QLatin1String("')");
+ return res;
+ }
+ default:
+ return QSqlDriver::formatValue(field, trimStrings);
+ }
+}
+
+QVariant QDB2Driver::handle() const
+{
+ Q_D(const QDB2Driver);
+ return QVariant(qRegisterMetaType<SQLHANDLE>("SQLHANDLE"), &d->hDbc);
+}
+
+QString QDB2Driver::escapeIdentifier(const QString &identifier, IdentifierType) const
+{
+ QString res = identifier;
+ if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) {
+ res.replace(QLatin1Char('"'), QLatin1String("\"\""));
+ res.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
+ res.replace(QLatin1Char('.'), QLatin1String("\".\""));
+ }
+ return res;
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/sqldrivers/db2/qsql_db2_p.h b/src/plugins/sqldrivers/db2/qsql_db2_p.h
new file mode 100644
index 0000000000..fa6d739479
--- /dev/null
+++ b/src/plugins/sqldrivers/db2/qsql_db2_p.h
@@ -0,0 +1,103 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSQL_DB2_H
+#define QSQL_DB2_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtCore/qglobal.h>
+
+#ifdef QT_PLUGIN
+#define Q_EXPORT_SQLDRIVER_DB2
+#else
+#define Q_EXPORT_SQLDRIVER_DB2 Q_SQL_EXPORT
+#endif
+
+#include <QtSql/qsqldriver.h>
+
+QT_BEGIN_NAMESPACE
+
+class QDB2DriverPrivate;
+
+class Q_EXPORT_SQLDRIVER_DB2 QDB2Driver : public QSqlDriver
+{
+ Q_DECLARE_PRIVATE(QDB2Driver)
+ Q_OBJECT
+ friend class QDB2ResultPrivate;
+
+public:
+ explicit QDB2Driver(QObject* parent = 0);
+ QDB2Driver(Qt::HANDLE env, Qt::HANDLE con, QObject* parent = 0);
+ ~QDB2Driver();
+ bool hasFeature(DriverFeature) const Q_DECL_OVERRIDE;
+ void close() Q_DECL_OVERRIDE;
+ QSqlRecord record(const QString &tableName) const Q_DECL_OVERRIDE;
+ QStringList tables(QSql::TableType type) const Q_DECL_OVERRIDE;
+ QSqlResult *createResult() const Q_DECL_OVERRIDE;
+ QSqlIndex primaryIndex(const QString &tablename) const Q_DECL_OVERRIDE;
+ bool beginTransaction() Q_DECL_OVERRIDE;
+ bool commitTransaction() Q_DECL_OVERRIDE;
+ bool rollbackTransaction() Q_DECL_OVERRIDE;
+ QString formatValue(const QSqlField &field, bool trimStrings) const Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+ bool open(const QString &db,
+ const QString &user,
+ const QString &password,
+ const QString &host,
+ int port,
+ const QString& connOpts) Q_DECL_OVERRIDE;
+ QString escapeIdentifier(const QString &identifier, IdentifierType type) const Q_DECL_OVERRIDE;
+
+private:
+ bool setAutoCommit(bool autoCommit);
+};
+
+QT_END_NAMESPACE
+
+#endif // QSQL_DB2_H
diff --git a/src/plugins/sqldrivers/ibase/ibase.pro b/src/plugins/sqldrivers/ibase/ibase.pro
index 1f29597a2b..e5709207d1 100644
--- a/src/plugins/sqldrivers/ibase/ibase.pro
+++ b/src/plugins/sqldrivers/ibase/ibase.pro
@@ -1,8 +1,12 @@
TARGET = qsqlibase
-SOURCES = main.cpp
+HEADERS += $$PWD/qsql_ibase_p.h
+SOURCES += $$PWD/qsql_ibase.cpp $$PWD/main.cpp
+
+# FIXME: ignores libfb (unix)/fbclient (win32) - but that's for the test anyway
+QMAKE_USE += ibase
+
OTHER_FILES += ibase.json
-include(../../../sql/drivers/ibase/qsql_ibase.pri)
PLUGIN_CLASS_NAME = QIBaseDriverPlugin
include(../qsqldriverbase.pri)
diff --git a/src/plugins/sqldrivers/ibase/main.cpp b/src/plugins/sqldrivers/ibase/main.cpp
index c6f0b785de..8d462afcdc 100644
--- a/src/plugins/sqldrivers/ibase/main.cpp
+++ b/src/plugins/sqldrivers/ibase/main.cpp
@@ -39,7 +39,7 @@
#include <qsqldriverplugin.h>
#include <qstringlist.h>
-#include "../../../sql/drivers/ibase/qsql_ibase_p.h"
+#include "qsql_ibase_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/sqldrivers/ibase/qsql_ibase.cpp b/src/plugins/sqldrivers/ibase/qsql_ibase.cpp
new file mode 100644
index 0000000000..6fd91b6b76
--- /dev/null
+++ b/src/plugins/sqldrivers/ibase/qsql_ibase.cpp
@@ -0,0 +1,1948 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsql_ibase_p.h"
+#include <qcoreapplication.h>
+#include <qdatetime.h>
+#include <qvariant.h>
+#include <qsqlerror.h>
+#include <qsqlfield.h>
+#include <qsqlindex.h>
+#include <qsqlquery.h>
+#include <QtSql/private/qsqlcachedresult_p.h>
+#include <QtSql/private/qsqldriver_p.h>
+#include <qlist.h>
+#include <qvector.h>
+#include <qtextcodec.h>
+#include <qmutex.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <math.h>
+#include <qdebug.h>
+#include <QVarLengthArray>
+
+QT_BEGIN_NAMESPACE
+
+#define FBVERSION SQL_DIALECT_V6
+
+#ifndef SQLDA_CURRENT_VERSION
+#define SQLDA_CURRENT_VERSION SQLDA_VERSION1
+#endif
+
+enum { QIBaseChunkSize = SHRT_MAX / 2 };
+
+#if defined(FB_API_VER) && FB_API_VER >= 20
+static bool getIBaseError(QString& msg, const ISC_STATUS* status, ISC_LONG &sqlcode, QTextCodec *tc)
+#else
+static bool getIBaseError(QString& msg, ISC_STATUS* status, ISC_LONG &sqlcode, QTextCodec *tc)
+#endif
+{
+ if (status[0] != 1 || status[1] <= 0)
+ return false;
+
+ msg.clear();
+ sqlcode = isc_sqlcode(status);
+ char buf[512];
+#if defined(FB_API_VER) && FB_API_VER >= 20
+ while(fb_interpret(buf, 512, &status)) {
+#else
+ while(isc_interprete(buf, &status)) {
+#endif
+ if(!msg.isEmpty())
+ msg += QLatin1String(" - ");
+ if (tc)
+ msg += tc->toUnicode(buf);
+ else
+ msg += QString::fromUtf8(buf);
+ }
+ return true;
+}
+
+static void createDA(XSQLDA *&sqlda)
+{
+ sqlda = (XSQLDA *) malloc(XSQLDA_LENGTH(1));
+ if (sqlda == (XSQLDA*)0) return;
+ sqlda->sqln = 1;
+ sqlda->sqld = 0;
+ sqlda->version = SQLDA_CURRENT_VERSION;
+ sqlda->sqlvar[0].sqlind = 0;
+ sqlda->sqlvar[0].sqldata = 0;
+}
+
+static void enlargeDA(XSQLDA *&sqlda, int n)
+{
+ if (sqlda != (XSQLDA*)0)
+ free(sqlda);
+ sqlda = (XSQLDA *) malloc(XSQLDA_LENGTH(n));
+ if (sqlda == (XSQLDA*)0) return;
+ sqlda->sqln = n;
+ sqlda->version = SQLDA_CURRENT_VERSION;
+}
+
+static void initDA(XSQLDA *sqlda)
+{
+ for (int i = 0; i < sqlda->sqld; ++i) {
+ switch (sqlda->sqlvar[i].sqltype & ~1) {
+ case SQL_INT64:
+ case SQL_LONG:
+ case SQL_SHORT:
+ case SQL_FLOAT:
+ case SQL_DOUBLE:
+ case SQL_TIMESTAMP:
+ case SQL_TYPE_TIME:
+ case SQL_TYPE_DATE:
+ case SQL_TEXT:
+ case SQL_BLOB:
+ sqlda->sqlvar[i].sqldata = new char[sqlda->sqlvar[i].sqllen];
+ break;
+ case SQL_ARRAY:
+ sqlda->sqlvar[i].sqldata = new char[sizeof(ISC_QUAD)];
+ memset(sqlda->sqlvar[i].sqldata, 0, sizeof(ISC_QUAD));
+ break;
+ case SQL_VARYING:
+ sqlda->sqlvar[i].sqldata = new char[sqlda->sqlvar[i].sqllen + sizeof(short)];
+ break;
+ default:
+ // not supported - do not bind.
+ sqlda->sqlvar[i].sqldata = 0;
+ break;
+ }
+ if (sqlda->sqlvar[i].sqltype & 1) {
+ sqlda->sqlvar[i].sqlind = new short[1];
+ *(sqlda->sqlvar[i].sqlind) = 0;
+ } else {
+ sqlda->sqlvar[i].sqlind = 0;
+ }
+ }
+}
+
+static void delDA(XSQLDA *&sqlda)
+{
+ if (!sqlda)
+ return;
+ for (int i = 0; i < sqlda->sqld; ++i) {
+ delete [] sqlda->sqlvar[i].sqlind;
+ delete [] sqlda->sqlvar[i].sqldata;
+ }
+ free(sqlda);
+ sqlda = 0;
+}
+
+static QVariant::Type qIBaseTypeName(int iType, bool hasScale)
+{
+ switch (iType) {
+ case blr_varying:
+ case blr_varying2:
+ case blr_text:
+ case blr_cstring:
+ case blr_cstring2:
+ return QVariant::String;
+ case blr_sql_time:
+ return QVariant::Time;
+ case blr_sql_date:
+ return QVariant::Date;
+ case blr_timestamp:
+ return QVariant::DateTime;
+ case blr_blob:
+ return QVariant::ByteArray;
+ case blr_quad:
+ case blr_short:
+ case blr_long:
+ return (hasScale ? QVariant::Double : QVariant::Int);
+ case blr_int64:
+ return (hasScale ? QVariant::Double : QVariant::LongLong);
+ case blr_float:
+ case blr_d_float:
+ case blr_double:
+ return QVariant::Double;
+ }
+ qWarning("qIBaseTypeName: unknown datatype: %d", iType);
+ return QVariant::Invalid;
+}
+
+static QVariant::Type qIBaseTypeName2(int iType, bool hasScale)
+{
+ switch(iType & ~1) {
+ case SQL_VARYING:
+ case SQL_TEXT:
+ return QVariant::String;
+ case SQL_LONG:
+ case SQL_SHORT:
+ return (hasScale ? QVariant::Double : QVariant::Int);
+ case SQL_INT64:
+ return (hasScale ? QVariant::Double : QVariant::LongLong);
+ case SQL_FLOAT:
+ case SQL_DOUBLE:
+ return QVariant::Double;
+ case SQL_TIMESTAMP:
+ return QVariant::DateTime;
+ case SQL_TYPE_TIME:
+ return QVariant::Time;
+ case SQL_TYPE_DATE:
+ return QVariant::Date;
+ case SQL_ARRAY:
+ return QVariant::List;
+ case SQL_BLOB:
+ return QVariant::ByteArray;
+ default:
+ return QVariant::Invalid;
+ }
+}
+
+static ISC_TIMESTAMP toTimeStamp(const QDateTime &dt)
+{
+ static const QTime midnight(0, 0, 0, 0);
+ static const QDate basedate(1858, 11, 17);
+ ISC_TIMESTAMP ts;
+ ts.timestamp_time = midnight.msecsTo(dt.time()) * 10;
+ ts.timestamp_date = basedate.daysTo(dt.date());
+ return ts;
+}
+
+static QDateTime fromTimeStamp(char *buffer)
+{
+ static const QDate bd(1858, 11, 17);
+ QTime t(0, 0);
+ QDate d;
+
+ // have to demangle the structure ourselves because isc_decode_time
+ // strips the msecs
+ t = t.addMSecs(int(((ISC_TIMESTAMP*)buffer)->timestamp_time / 10));
+ d = bd.addDays(int(((ISC_TIMESTAMP*)buffer)->timestamp_date));
+
+ return QDateTime(d, t);
+}
+
+static ISC_TIME toTime(const QTime &t)
+{
+ static const QTime midnight(0, 0, 0, 0);
+ return (ISC_TIME)midnight.msecsTo(t) * 10;
+}
+
+static QTime fromTime(char *buffer)
+{
+ QTime t(0, 0);
+ // have to demangle the structure ourselves because isc_decode_time
+ // strips the msecs
+ t = t.addMSecs(int((*(ISC_TIME*)buffer) / 10));
+
+ return t;
+}
+
+static ISC_DATE toDate(const QDate &t)
+{
+ static const QDate basedate(1858, 11, 17);
+ ISC_DATE date;
+
+ date = basedate.daysTo(t);
+ return date;
+}
+
+static QDate fromDate(char *buffer)
+{
+ static const QDate bd(1858, 11, 17);
+ QDate d;
+
+ // have to demangle the structure ourselves because isc_decode_time
+ // strips the msecs
+ d = bd.addDays(int(((ISC_TIMESTAMP*)buffer)->timestamp_date));
+
+ return d;
+}
+
+static QByteArray encodeString(QTextCodec *tc, const QString &str)
+{
+ if (tc)
+ return tc->fromUnicode(str);
+ return str.toUtf8();
+}
+
+struct QIBaseEventBuffer {
+#if defined(FB_API_VER) && FB_API_VER >= 20
+ ISC_UCHAR *eventBuffer;
+ ISC_UCHAR *resultBuffer;
+#else
+ char *eventBuffer;
+ char *resultBuffer;
+#endif
+ ISC_LONG bufferLength;
+ ISC_LONG eventId;
+
+ enum QIBaseSubscriptionState { Starting, Subscribed, Finished };
+ QIBaseSubscriptionState subscriptionState;
+};
+
+class QIBaseDriverPrivate : public QSqlDriverPrivate
+{
+ Q_DECLARE_PUBLIC(QIBaseDriver)
+public:
+ QIBaseDriverPrivate() : QSqlDriverPrivate(), ibase(0), trans(0), tc(0) { dbmsType = QSqlDriver::Interbase; }
+
+ bool isError(const char *msg, QSqlError::ErrorType typ = QSqlError::UnknownError)
+ {
+ Q_Q(QIBaseDriver);
+ QString imsg;
+ ISC_LONG sqlcode;
+ if (!getIBaseError(imsg, status, sqlcode, tc))
+ return false;
+
+ q->setLastError(QSqlError(QCoreApplication::translate("QIBaseDriver", msg),
+ imsg, typ, int(sqlcode)));
+ return true;
+ }
+
+public:
+ isc_db_handle ibase;
+ isc_tr_handle trans;
+ QTextCodec *tc;
+ ISC_STATUS status[20];
+ QMap<QString, QIBaseEventBuffer*> eventBuffers;
+};
+
+typedef QMap<void *, QIBaseDriver *> QIBaseBufferDriverMap;
+Q_GLOBAL_STATIC(QIBaseBufferDriverMap, qBufferDriverMap)
+Q_GLOBAL_STATIC(QMutex, qMutex);
+
+static void qFreeEventBuffer(QIBaseEventBuffer* eBuffer)
+{
+ qMutex()->lock();
+ qBufferDriverMap()->remove(reinterpret_cast<void *>(eBuffer->resultBuffer));
+ qMutex()->unlock();
+ delete eBuffer;
+}
+
+class QIBaseResultPrivate;
+
+class QIBaseResult : public QSqlCachedResult
+{
+ Q_DECLARE_PRIVATE(QIBaseResult)
+
+public:
+ explicit QIBaseResult(const QIBaseDriver* db);
+
+ bool prepare(const QString &query) Q_DECL_OVERRIDE;
+ bool exec() Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+protected:
+ bool gotoNext(QSqlCachedResult::ValueCache& row, int rowIdx) Q_DECL_OVERRIDE;
+ bool reset (const QString &query) Q_DECL_OVERRIDE;
+ int size() Q_DECL_OVERRIDE;
+ int numRowsAffected() Q_DECL_OVERRIDE;
+ QSqlRecord record() const Q_DECL_OVERRIDE;
+};
+
+class QIBaseResultPrivate: public QSqlCachedResultPrivate
+{
+ Q_DECLARE_PUBLIC(QIBaseResult)
+
+public:
+ Q_DECLARE_SQLDRIVER_PRIVATE(QIBaseDriver)
+
+ QIBaseResultPrivate(QIBaseResult *q, const QIBaseDriver *drv);
+ ~QIBaseResultPrivate() { cleanup(); }
+
+ void cleanup();
+ bool isError(const char *msg, QSqlError::ErrorType typ = QSqlError::UnknownError)
+ {
+ Q_Q(QIBaseResult);
+ QString imsg;
+ ISC_LONG sqlcode;
+ if (!getIBaseError(imsg, status, sqlcode, tc))
+ return false;
+
+ q->setLastError(QSqlError(QCoreApplication::translate("QIBaseResult", msg),
+ imsg, typ, int(sqlcode)));
+ return true;
+ }
+
+ bool transaction();
+ bool commit();
+
+ bool isSelect();
+ QVariant fetchBlob(ISC_QUAD *bId);
+ bool writeBlob(int i, const QByteArray &ba);
+ QVariant fetchArray(int pos, ISC_QUAD *arr);
+ bool writeArray(int i, const QList<QVariant> &list);
+
+public:
+ ISC_STATUS status[20];
+ isc_tr_handle trans;
+ //indicator whether we have a local transaction or a transaction on driver level
+ bool localTransaction;
+ isc_stmt_handle stmt;
+ isc_db_handle ibase;
+ XSQLDA *sqlda; // output sqlda
+ XSQLDA *inda; // input parameters
+ int queryType;
+ QTextCodec *tc;
+};
+
+
+QIBaseResultPrivate::QIBaseResultPrivate(QIBaseResult *q, const QIBaseDriver *drv)
+ : QSqlCachedResultPrivate(q, drv),
+ trans(0),
+ localTransaction(!drv_d_func()->ibase),
+ stmt(0),
+ ibase(drv_d_func()->ibase),
+ sqlda(0),
+ inda(0),
+ queryType(-1),
+ tc(drv_d_func()->tc)
+{
+}
+
+void QIBaseResultPrivate::cleanup()
+{
+ Q_Q(QIBaseResult);
+ commit();
+ if (!localTransaction)
+ trans = 0;
+
+ if (stmt) {
+ isc_dsql_free_statement(status, &stmt, DSQL_drop);
+ stmt = 0;
+ }
+
+ delDA(sqlda);
+ delDA(inda);
+
+ queryType = -1;
+ q->cleanup();
+}
+
+bool QIBaseResultPrivate::writeBlob(int i, const QByteArray &ba)
+{
+ isc_blob_handle handle = 0;
+ ISC_QUAD *bId = (ISC_QUAD*)inda->sqlvar[i].sqldata;
+ isc_create_blob2(status, &ibase, &trans, &handle, bId, 0, 0);
+ if (!isError(QT_TRANSLATE_NOOP("QIBaseResult", "Unable to create BLOB"),
+ QSqlError::StatementError)) {
+ int i = 0;
+ while (i < ba.size()) {
+ isc_put_segment(status, &handle, qMin(ba.size() - i, int(QIBaseChunkSize)),
+ const_cast<char*>(ba.data()) + i);
+ if (isError(QT_TRANSLATE_NOOP("QIBaseResult", "Unable to write BLOB")))
+ return false;
+ i += qMin(ba.size() - i, int(QIBaseChunkSize));
+ }
+ }
+ isc_close_blob(status, &handle);
+ return true;
+}
+
+QVariant QIBaseResultPrivate::fetchBlob(ISC_QUAD *bId)
+{
+ isc_blob_handle handle = 0;
+
+ isc_open_blob2(status, &ibase, &trans, &handle, bId, 0, 0);
+ if (isError(QT_TRANSLATE_NOOP("QIBaseResult", "Unable to open BLOB"),
+ QSqlError::StatementError))
+ return QVariant();
+
+ unsigned short len = 0;
+ QByteArray ba;
+ int chunkSize = QIBaseChunkSize;
+ ba.resize(chunkSize);
+ int read = 0;
+ while (isc_get_segment(status, &handle, &len, chunkSize, ba.data() + read) == 0 || status[1] == isc_segment) {
+ read += len;
+ ba.resize(read + chunkSize);
+ }
+ ba.resize(read);
+
+ bool isErr = (status[1] == isc_segstr_eof ? false :
+ isError(QT_TRANSLATE_NOOP("QIBaseResult",
+ "Unable to read BLOB"),
+ QSqlError::StatementError));
+
+ isc_close_blob(status, &handle);
+
+ if (isErr)
+ return QVariant();
+
+ ba.resize(read);
+ return ba;
+}
+
+template<typename T>
+static QList<QVariant> toList(char** buf, int count, T* = 0)
+{
+ QList<QVariant> res;
+ for (int i = 0; i < count; ++i) {
+ res.append(*(T*)(*buf));
+ *buf += sizeof(T);
+ }
+ return res;
+}
+/* char** ? seems like bad influence from oracle ... */
+template<>
+QList<QVariant> toList<long>(char** buf, int count, long*)
+{
+ QList<QVariant> res;
+ for (int i = 0; i < count; ++i) {
+ if (sizeof(int) == sizeof(long))
+ res.append(int((*(long*)(*buf))));
+ else
+ res.append((qint64)(*(long*)(*buf)));
+ *buf += sizeof(long);
+ }
+ return res;
+}
+
+static char* readArrayBuffer(QList<QVariant>& list, char *buffer, short curDim,
+ short* numElements, ISC_ARRAY_DESC *arrayDesc,
+ QTextCodec *tc)
+{
+ const short dim = arrayDesc->array_desc_dimensions - 1;
+ const unsigned char dataType = arrayDesc->array_desc_dtype;
+ QList<QVariant> valList;
+ unsigned short strLen = arrayDesc->array_desc_length;
+
+ if (curDim != dim) {
+ for(int i = 0; i < numElements[curDim]; ++i)
+ buffer = readArrayBuffer(list, buffer, curDim + 1, numElements,
+ arrayDesc, tc);
+ } else {
+ switch(dataType) {
+ case blr_varying:
+ case blr_varying2:
+ strLen += 2; // for the two terminating null values
+ case blr_text:
+ case blr_text2: {
+ int o;
+ for (int i = 0; i < numElements[dim]; ++i) {
+ for(o = 0; o < strLen && buffer[o]!=0; ++o )
+ ;
+
+ if (tc)
+ valList.append(tc->toUnicode(buffer, o));
+ else
+ valList.append(QString::fromUtf8(buffer, o));
+
+ buffer += strLen;
+ }
+ break; }
+ case blr_long:
+ valList = toList<long>(&buffer, numElements[dim], static_cast<long *>(0));
+ break;
+ case blr_short:
+ valList = toList<short>(&buffer, numElements[dim]);
+ break;
+ case blr_int64:
+ valList = toList<qint64>(&buffer, numElements[dim]);
+ break;
+ case blr_float:
+ valList = toList<float>(&buffer, numElements[dim]);
+ break;
+ case blr_double:
+ valList = toList<double>(&buffer, numElements[dim]);
+ break;
+ case blr_timestamp:
+ for(int i = 0; i < numElements[dim]; ++i) {
+ valList.append(fromTimeStamp(buffer));
+ buffer += sizeof(ISC_TIMESTAMP);
+ }
+ break;
+ case blr_sql_time:
+ for(int i = 0; i < numElements[dim]; ++i) {
+ valList.append(fromTime(buffer));
+ buffer += sizeof(ISC_TIME);
+ }
+ break;
+ case blr_sql_date:
+ for(int i = 0; i < numElements[dim]; ++i) {
+ valList.append(fromDate(buffer));
+ buffer += sizeof(ISC_DATE);
+ }
+ break;
+ }
+ }
+ if (dim > 0)
+ list.append(valList);
+ else
+ list += valList;
+ return buffer;
+}
+
+QVariant QIBaseResultPrivate::fetchArray(int pos, ISC_QUAD *arr)
+{
+ QList<QVariant> list;
+ ISC_ARRAY_DESC desc;
+
+ if (!arr)
+ return list;
+
+ QByteArray relname(sqlda->sqlvar[pos].relname, sqlda->sqlvar[pos].relname_length);
+ QByteArray sqlname(sqlda->sqlvar[pos].aliasname, sqlda->sqlvar[pos].aliasname_length);
+
+ isc_array_lookup_bounds(status, &ibase, &trans, relname.data(), sqlname.data(), &desc);
+ if (isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not find array"),
+ QSqlError::StatementError))
+ return list;
+
+
+ int arraySize = 1, subArraySize;
+ short dimensions = desc.array_desc_dimensions;
+ QVarLengthArray<short> numElements(dimensions);
+
+ for(int i = 0; i < dimensions; ++i) {
+ subArraySize = (desc.array_desc_bounds[i].array_bound_upper -
+ desc.array_desc_bounds[i].array_bound_lower + 1);
+ numElements[i] = subArraySize;
+ arraySize = subArraySize * arraySize;
+ }
+
+ ISC_LONG bufLen;
+ QByteArray ba;
+ /* varying arrayelements are stored with 2 trailing null bytes
+ indicating the length of the string
+ */
+ if (desc.array_desc_dtype == blr_varying
+ || desc.array_desc_dtype == blr_varying2) {
+ desc.array_desc_length += 2;
+ bufLen = desc.array_desc_length * arraySize * sizeof(short);
+ } else {
+ bufLen = desc.array_desc_length * arraySize;
+ }
+
+
+ ba.resize(int(bufLen));
+ isc_array_get_slice(status, &ibase, &trans, arr, &desc, ba.data(), &bufLen);
+ if (isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not get array data"),
+ QSqlError::StatementError))
+ return list;
+
+ readArrayBuffer(list, ba.data(), 0, numElements.data(), &desc, tc);
+
+ return QVariant(list);
+}
+
+template<typename T>
+static char* fillList(char *buffer, const QList<QVariant> &list, T* = 0)
+{
+ for (int i = 0; i < list.size(); ++i) {
+ T val;
+ val = qvariant_cast<T>(list.at(i));
+ memcpy(buffer, &val, sizeof(T));
+ buffer += sizeof(T);
+ }
+ return buffer;
+}
+
+template<>
+char* fillList<float>(char *buffer, const QList<QVariant> &list, float*)
+{
+ for (int i = 0; i < list.size(); ++i) {
+ double val;
+ float val2 = 0;
+ val = qvariant_cast<double>(list.at(i));
+ val2 = (float)val;
+ memcpy(buffer, &val2, sizeof(float));
+ buffer += sizeof(float);
+ }
+ return buffer;
+}
+
+static char* qFillBufferWithString(char *buffer, const QString& string,
+ short buflen, bool varying, bool array,
+ QTextCodec *tc)
+{
+ QByteArray str = encodeString(tc, string); // keep a copy of the string alive in this scope
+ if (varying) {
+ short tmpBuflen = buflen;
+ if (str.length() < buflen)
+ buflen = str.length();
+ if (array) { // interbase stores varying arrayelements different than normal varying elements
+ memcpy(buffer, str.data(), buflen);
+ memset(buffer + buflen, 0, tmpBuflen - buflen);
+ } else {
+ *(short*)buffer = buflen; // first two bytes is the length
+ memcpy(buffer + sizeof(short), str.data(), buflen);
+ }
+ buffer += tmpBuflen;
+ } else {
+ str = str.leftJustified(buflen, ' ', true);
+ memcpy(buffer, str.data(), buflen);
+ buffer += buflen;
+ }
+ return buffer;
+}
+
+static char* createArrayBuffer(char *buffer, const QList<QVariant> &list,
+ QVariant::Type type, short curDim, ISC_ARRAY_DESC *arrayDesc,
+ QString& error, QTextCodec *tc)
+{
+ int i;
+ ISC_ARRAY_BOUND *bounds = arrayDesc->array_desc_bounds;
+ short dim = arrayDesc->array_desc_dimensions - 1;
+
+ int elements = (bounds[curDim].array_bound_upper -
+ bounds[curDim].array_bound_lower + 1);
+
+ if (list.size() != elements) { // size mismatch
+ error = QLatin1String("Expected size: %1. Supplied size: %2");
+ error = QLatin1String("Array size mismatch. Fieldname: %1 ")
+ + error.arg(elements).arg(list.size());
+ return 0;
+ }
+
+ if (curDim != dim) {
+ for(i = 0; i < list.size(); ++i) {
+
+ if (list.at(i).type() != QVariant::List) { // dimensions mismatch
+ error = QLatin1String("Array dimensons mismatch. Fieldname: %1");
+ return 0;
+ }
+
+ buffer = createArrayBuffer(buffer, list.at(i).toList(), type, curDim + 1,
+ arrayDesc, error, tc);
+ if (!buffer)
+ return 0;
+ }
+ } else {
+ switch(type) {
+ case QVariant::Int:
+ case QVariant::UInt:
+ if (arrayDesc->array_desc_dtype == blr_short)
+ buffer = fillList<short>(buffer, list);
+ else
+ buffer = fillList<int>(buffer, list);
+ break;
+ case QVariant::Double:
+ if (arrayDesc->array_desc_dtype == blr_float)
+ buffer = fillList<float>(buffer, list, static_cast<float *>(0));
+ else
+ buffer = fillList<double>(buffer, list);
+ break;
+ case QVariant::LongLong:
+ buffer = fillList<qint64>(buffer, list);
+ break;
+ case QVariant::ULongLong:
+ buffer = fillList<quint64>(buffer, list);
+ break;
+ case QVariant::String:
+ for (i = 0; i < list.size(); ++i)
+ buffer = qFillBufferWithString(buffer, list.at(i).toString(),
+ arrayDesc->array_desc_length,
+ arrayDesc->array_desc_dtype == blr_varying,
+ true, tc);
+ break;
+ case QVariant::Date:
+ for (i = 0; i < list.size(); ++i) {
+ *((ISC_DATE*)buffer) = toDate(list.at(i).toDate());
+ buffer += sizeof(ISC_DATE);
+ }
+ break;
+ case QVariant::Time:
+ for (i = 0; i < list.size(); ++i) {
+ *((ISC_TIME*)buffer) = toTime(list.at(i).toTime());
+ buffer += sizeof(ISC_TIME);
+ }
+ break;
+
+ case QVariant::DateTime:
+ for (i = 0; i < list.size(); ++i) {
+ *((ISC_TIMESTAMP*)buffer) = toTimeStamp(list.at(i).toDateTime());
+ buffer += sizeof(ISC_TIMESTAMP);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ return buffer;
+}
+
+bool QIBaseResultPrivate::writeArray(int column, const QList<QVariant> &list)
+{
+ Q_Q(QIBaseResult);
+ QString error;
+ ISC_QUAD *arrayId = (ISC_QUAD*) inda->sqlvar[column].sqldata;
+ ISC_ARRAY_DESC desc;
+
+ QByteArray relname(inda->sqlvar[column].relname, inda->sqlvar[column].relname_length);
+ QByteArray sqlname(inda->sqlvar[column].aliasname, inda->sqlvar[column].aliasname_length);
+
+ isc_array_lookup_bounds(status, &ibase, &trans, relname.data(), sqlname.data(), &desc);
+ if (isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not find array"),
+ QSqlError::StatementError))
+ return false;
+
+ short arraySize = 1;
+ ISC_LONG bufLen;
+ QList<QVariant> subList = list;
+
+ short dimensions = desc.array_desc_dimensions;
+ for(int i = 0; i < dimensions; ++i) {
+ arraySize *= (desc.array_desc_bounds[i].array_bound_upper -
+ desc.array_desc_bounds[i].array_bound_lower + 1);
+ }
+
+ /* varying arrayelements are stored with 2 trailing null bytes
+ indicating the length of the string
+ */
+ if (desc.array_desc_dtype == blr_varying ||
+ desc.array_desc_dtype == blr_varying2)
+ desc.array_desc_length += 2;
+
+ bufLen = desc.array_desc_length * arraySize;
+ QByteArray ba;
+ ba.resize(int(bufLen));
+
+ if (list.size() > arraySize) {
+ error = QLatin1String("Array size missmatch: size of %1 is %2, size of provided list is %3");
+ error = error.arg(QLatin1String(sqlname)).arg(arraySize).arg(list.size());
+ q->setLastError(QSqlError(error, QLatin1String(""), QSqlError::StatementError));
+ return false;
+ }
+
+ if (!createArrayBuffer(ba.data(), list,
+ qIBaseTypeName(desc.array_desc_dtype, inda->sqlvar[column].sqlscale < 0),
+ 0, &desc, error, tc)) {
+ q->setLastError(QSqlError(error.arg(QLatin1String(sqlname)), QLatin1String(""),
+ QSqlError::StatementError));
+ return false;
+ }
+
+ /* readjust the buffer size*/
+ if (desc.array_desc_dtype == blr_varying
+ || desc.array_desc_dtype == blr_varying2)
+ desc.array_desc_length -= 2;
+
+ isc_array_put_slice(status, &ibase, &trans, arrayId, &desc, ba.data(), &bufLen);
+ return true;
+}
+
+
+bool QIBaseResultPrivate::isSelect()
+{
+ char acBuffer[9];
+ char qType = isc_info_sql_stmt_type;
+ isc_dsql_sql_info(status, &stmt, 1, &qType, sizeof(acBuffer), acBuffer);
+ if (isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not get query info"),
+ QSqlError::StatementError))
+ return false;
+ int iLength = isc_vax_integer(&acBuffer[1], 2);
+ queryType = isc_vax_integer(&acBuffer[3], iLength);
+ return (queryType == isc_info_sql_stmt_select || queryType == isc_info_sql_stmt_exec_procedure);
+}
+
+bool QIBaseResultPrivate::transaction()
+{
+ if (trans)
+ return true;
+ if (drv_d_func()->trans) {
+ localTransaction = false;
+ trans = drv_d_func()->trans;
+ return true;
+ }
+ localTransaction = true;
+
+ isc_start_transaction(status, &trans, 1, &ibase, 0, NULL);
+ if (isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not start transaction"),
+ QSqlError::TransactionError))
+ return false;
+
+ return true;
+}
+
+// does nothing if the transaction is on the
+// driver level
+bool QIBaseResultPrivate::commit()
+{
+ if (!trans)
+ return false;
+ // don't commit driver's transaction, the driver will do it for us
+ if (!localTransaction)
+ return true;
+
+ isc_commit_transaction(status, &trans);
+ trans = 0;
+ return !isError(QT_TRANSLATE_NOOP("QIBaseResult", "Unable to commit transaction"),
+ QSqlError::TransactionError);
+}
+
+//////////
+
+QIBaseResult::QIBaseResult(const QIBaseDriver *db)
+ : QSqlCachedResult(*new QIBaseResultPrivate(this, db))
+{
+}
+
+bool QIBaseResult::prepare(const QString& query)
+{
+ Q_D(QIBaseResult);
+// qDebug("prepare: %s", qPrintable(query));
+ if (!driver() || !driver()->isOpen() || driver()->isOpenError())
+ return false;
+ d->cleanup();
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+
+ createDA(d->sqlda);
+ if (d->sqlda == (XSQLDA*)0) {
+ qWarning()<<"QIOBaseResult: createDA(): failed to allocate memory";
+ return false;
+ }
+
+ createDA(d->inda);
+ if (d->inda == (XSQLDA*)0){
+ qWarning()<<"QIOBaseResult: createDA(): failed to allocate memory";
+ return false;
+ }
+
+ if (!d->transaction())
+ return false;
+
+ isc_dsql_allocate_statement(d->status, &d->ibase, &d->stmt);
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not allocate statement"),
+ QSqlError::StatementError))
+ return false;
+ isc_dsql_prepare(d->status, &d->trans, &d->stmt, 0,
+ const_cast<char*>(encodeString(d->tc, query).constData()), FBVERSION, d->sqlda);
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not prepare statement"),
+ QSqlError::StatementError))
+ return false;
+
+ isc_dsql_describe_bind(d->status, &d->stmt, FBVERSION, d->inda);
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseResult",
+ "Could not describe input statement"), QSqlError::StatementError))
+ return false;
+ if (d->inda->sqld > d->inda->sqln) {
+ enlargeDA(d->inda, d->inda->sqld);
+ if (d->inda == (XSQLDA*)0) {
+ qWarning()<<"QIOBaseResult: enlargeDA(): failed to allocate memory";
+ return false;
+ }
+
+ isc_dsql_describe_bind(d->status, &d->stmt, FBVERSION, d->inda);
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseResult",
+ "Could not describe input statement"), QSqlError::StatementError))
+ return false;
+ }
+ initDA(d->inda);
+ if (d->sqlda->sqld > d->sqlda->sqln) {
+ // need more field descriptors
+ enlargeDA(d->sqlda, d->sqlda->sqld);
+ if (d->sqlda == (XSQLDA*)0) {
+ qWarning()<<"QIOBaseResult: enlargeDA(): failed to allocate memory";
+ return false;
+ }
+
+ isc_dsql_describe(d->status, &d->stmt, FBVERSION, d->sqlda);
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not describe statement"),
+ QSqlError::StatementError))
+ return false;
+ }
+ initDA(d->sqlda);
+
+ setSelect(d->isSelect());
+ if (!isSelect()) {
+ free(d->sqlda);
+ d->sqlda = 0;
+ }
+
+ return true;
+}
+
+
+bool QIBaseResult::exec()
+{
+ Q_D(QIBaseResult);
+ bool ok = true;
+
+ if (!d->trans)
+ d->transaction();
+
+ if (!driver() || !driver()->isOpen() || driver()->isOpenError())
+ return false;
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+
+ if (d->inda) {
+ QVector<QVariant>& values = boundValues();
+ int i;
+ if (values.count() > d->inda->sqld) {
+ qWarning("QIBaseResult::exec: Parameter mismatch, expected %d, got %d parameters",
+ d->inda->sqld, values.count());
+ return false;
+ }
+ int para = 0;
+ for (i = 0; i < values.count(); ++i) {
+ para = i;
+ if (!d->inda->sqlvar[para].sqldata)
+ // skip unknown datatypes
+ continue;
+ const QVariant val(values[i]);
+ if (d->inda->sqlvar[para].sqltype & 1) {
+ if (val.isNull()) {
+ // set null indicator
+ *(d->inda->sqlvar[para].sqlind) = -1;
+ // and set the value to 0, otherwise it would count as empty string.
+ // it seems to be working with just setting sqlind to -1
+ //*((char*)d->inda->sqlvar[para].sqldata) = 0;
+ continue;
+ }
+ // a value of 0 means non-null.
+ *(d->inda->sqlvar[para].sqlind) = 0;
+ }
+ switch(d->inda->sqlvar[para].sqltype & ~1) {
+ case SQL_INT64:
+ if (d->inda->sqlvar[para].sqlscale < 0)
+ *((qint64*)d->inda->sqlvar[para].sqldata) =
+ (qint64)floor(0.5 + val.toDouble() * pow(10.0, d->inda->sqlvar[para].sqlscale * -1));
+ else
+ *((qint64*)d->inda->sqlvar[para].sqldata) = val.toLongLong();
+ break;
+ case SQL_LONG:
+ if (d->inda->sqlvar[para].sqllen == 4) {
+ if (d->inda->sqlvar[para].sqlscale < 0)
+ *((qint32*)d->inda->sqlvar[para].sqldata) =
+ (qint32)floor(0.5 + val.toDouble() * pow(10.0, d->inda->sqlvar[para].sqlscale * -1));
+ else
+ *((qint32*)d->inda->sqlvar[para].sqldata) = (qint32)val.toInt();
+ } else {
+ *((qint64*)d->inda->sqlvar[para].sqldata) = val.toLongLong();
+ }
+ break;
+ case SQL_SHORT:
+ if (d->inda->sqlvar[para].sqlscale < 0)
+ *((short*)d->inda->sqlvar[para].sqldata) =
+ (short)floor(0.5 + val.toDouble() * pow(10.0, d->inda->sqlvar[para].sqlscale * -1));
+ else
+ *((short*)d->inda->sqlvar[para].sqldata) = (short)val.toInt();
+ break;
+ case SQL_FLOAT:
+ *((float*)d->inda->sqlvar[para].sqldata) = (float)val.toDouble();
+ break;
+ case SQL_DOUBLE:
+ *((double*)d->inda->sqlvar[para].sqldata) = val.toDouble();
+ break;
+ case SQL_TIMESTAMP:
+ *((ISC_TIMESTAMP*)d->inda->sqlvar[para].sqldata) = toTimeStamp(val.toDateTime());
+ break;
+ case SQL_TYPE_TIME:
+ *((ISC_TIME*)d->inda->sqlvar[para].sqldata) = toTime(val.toTime());
+ break;
+ case SQL_TYPE_DATE:
+ *((ISC_DATE*)d->inda->sqlvar[para].sqldata) = toDate(val.toDate());
+ break;
+ case SQL_VARYING:
+ case SQL_TEXT:
+ qFillBufferWithString(d->inda->sqlvar[para].sqldata, val.toString(),
+ d->inda->sqlvar[para].sqllen,
+ (d->inda->sqlvar[para].sqltype & ~1) == SQL_VARYING, false, d->tc);
+ break;
+ case SQL_BLOB:
+ ok &= d->writeBlob(para, val.toByteArray());
+ break;
+ case SQL_ARRAY:
+ ok &= d->writeArray(para, val.toList());
+ break;
+ default:
+ qWarning("QIBaseResult::exec: Unknown datatype %d",
+ d->inda->sqlvar[para].sqltype & ~1);
+ break;
+ }
+ }
+ }
+
+ if (ok) {
+ if (colCount() && d->queryType != isc_info_sql_stmt_exec_procedure) {
+ isc_dsql_free_statement(d->status, &d->stmt, DSQL_close);
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseResult", "Unable to close statement")))
+ return false;
+ cleanup();
+ }
+ if (d->queryType == isc_info_sql_stmt_exec_procedure)
+ isc_dsql_execute2(d->status, &d->trans, &d->stmt, FBVERSION, d->inda, d->sqlda);
+ else
+ isc_dsql_execute(d->status, &d->trans, &d->stmt, FBVERSION, d->inda);
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseResult", "Unable to execute query")))
+ return false;
+
+ // Not all stored procedures necessarily return values.
+ if (d->queryType == isc_info_sql_stmt_exec_procedure && d->sqlda && d->sqlda->sqld == 0)
+ delDA(d->sqlda);
+
+ if (d->sqlda)
+ init(d->sqlda->sqld);
+
+ if (!isSelect())
+ d->commit();
+
+ setActive(true);
+ return true;
+ }
+ return false;
+}
+
+bool QIBaseResult::reset (const QString& query)
+{
+ if (!prepare(query))
+ return false;
+ return exec();
+}
+
+bool QIBaseResult::gotoNext(QSqlCachedResult::ValueCache& row, int rowIdx)
+{
+ Q_D(QIBaseResult);
+ ISC_STATUS stat = 0;
+
+ // Stored Procedures are special - they populate our d->sqlda when executing,
+ // so we don't have to call isc_dsql_fetch
+ if (d->queryType == isc_info_sql_stmt_exec_procedure) {
+ // the first "fetch" shall succeed, all consecutive ones will fail since
+ // we only have one row to fetch for stored procedures
+ if (rowIdx != 0)
+ stat = 100;
+ } else {
+ stat = isc_dsql_fetch(d->status, &d->stmt, FBVERSION, d->sqlda);
+ }
+
+ if (stat == 100) {
+ // no more rows
+ setAt(QSql::AfterLastRow);
+ return false;
+ }
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not fetch next item"),
+ QSqlError::StatementError))
+ return false;
+ if (rowIdx < 0) // not interested in actual values
+ return true;
+
+ for (int i = 0; i < d->sqlda->sqld; ++i) {
+ int idx = rowIdx + i;
+ char *buf = d->sqlda->sqlvar[i].sqldata;
+ int size = d->sqlda->sqlvar[i].sqllen;
+ Q_ASSERT(buf);
+
+ if ((d->sqlda->sqlvar[i].sqltype & 1) && *d->sqlda->sqlvar[i].sqlind) {
+ // null value
+ QVariant v;
+ v.convert(qIBaseTypeName2(d->sqlda->sqlvar[i].sqltype, d->sqlda->sqlvar[i].sqlscale < 0));
+ if(v.type() == QVariant::Double) {
+ switch(numericalPrecisionPolicy()) {
+ case QSql::LowPrecisionInt32:
+ v.convert(QVariant::Int);
+ break;
+ case QSql::LowPrecisionInt64:
+ v.convert(QVariant::LongLong);
+ break;
+ case QSql::HighPrecision:
+ v.convert(QVariant::String);
+ break;
+ case QSql::LowPrecisionDouble:
+ // no conversion
+ break;
+ }
+ }
+ row[idx] = v;
+ continue;
+ }
+
+ switch(d->sqlda->sqlvar[i].sqltype & ~1) {
+ case SQL_VARYING:
+ // pascal strings - a short with a length information followed by the data
+ if (d->tc)
+ row[idx] = d->tc->toUnicode(buf + sizeof(short), *(short*)buf);
+ else
+ row[idx] = QString::fromUtf8(buf + sizeof(short), *(short*)buf);
+ break;
+ case SQL_INT64:
+ if (d->sqlda->sqlvar[i].sqlscale < 0)
+ row[idx] = *(qint64*)buf * pow(10.0, d->sqlda->sqlvar[i].sqlscale);
+ else
+ row[idx] = QVariant(*(qint64*)buf);
+ break;
+ case SQL_LONG:
+ if (d->sqlda->sqlvar[i].sqllen == 4)
+ if (d->sqlda->sqlvar[i].sqlscale < 0)
+ row[idx] = QVariant(*(qint32*)buf * pow(10.0, d->sqlda->sqlvar[i].sqlscale));
+ else
+ row[idx] = QVariant(*(qint32*)buf);
+ else
+ row[idx] = QVariant(*(qint64*)buf);
+ break;
+ case SQL_SHORT:
+ if (d->sqlda->sqlvar[i].sqlscale < 0)
+ row[idx] = QVariant(long((*(short*)buf)) * pow(10.0, d->sqlda->sqlvar[i].sqlscale));
+ else
+ row[idx] = QVariant(int((*(short*)buf)));
+ break;
+ case SQL_FLOAT:
+ row[idx] = QVariant(double((*(float*)buf)));
+ break;
+ case SQL_DOUBLE:
+ row[idx] = QVariant(*(double*)buf);
+ break;
+ case SQL_TIMESTAMP:
+ row[idx] = fromTimeStamp(buf);
+ break;
+ case SQL_TYPE_TIME:
+ row[idx] = fromTime(buf);
+ break;
+ case SQL_TYPE_DATE:
+ row[idx] = fromDate(buf);
+ break;
+ case SQL_TEXT:
+ if (d->tc)
+ row[idx] = d->tc->toUnicode(buf, size);
+ else
+ row[idx] = QString::fromUtf8(buf, size);
+ break;
+ case SQL_BLOB:
+ row[idx] = d->fetchBlob((ISC_QUAD*)buf);
+ break;
+ case SQL_ARRAY:
+ row[idx] = d->fetchArray(i, (ISC_QUAD*)buf);
+ break;
+ default:
+ // unknown type - don't even try to fetch
+ row[idx] = QVariant();
+ break;
+ }
+ if (d->sqlda->sqlvar[i].sqlscale < 0) {
+ QVariant v = row[idx];
+ switch(numericalPrecisionPolicy()) {
+ case QSql::LowPrecisionInt32:
+ if(v.convert(QVariant::Int))
+ row[idx]=v;
+ break;
+ case QSql::LowPrecisionInt64:
+ if(v.convert(QVariant::LongLong))
+ row[idx]=v;
+ break;
+ case QSql::LowPrecisionDouble:
+ if(v.convert(QVariant::Double))
+ row[idx]=v;
+ break;
+ case QSql::HighPrecision:
+ if(v.convert(QVariant::String))
+ row[idx]=v;
+ break;
+ }
+ }
+ }
+
+ return true;
+}
+
+int QIBaseResult::size()
+{
+ return -1;
+
+#if 0 /// ### FIXME
+ static char sizeInfo[] = {isc_info_sql_records};
+ char buf[64];
+
+ //qDebug() << sizeInfo;
+ if (!isActive() || !isSelect())
+ return -1;
+
+ char ct;
+ short len;
+ int val = 0;
+// while(val == 0) {
+ isc_dsql_sql_info(d->status, &d->stmt, sizeof(sizeInfo), sizeInfo, sizeof(buf), buf);
+// isc_database_info(d->status, &d->ibase, sizeof(sizeInfo), sizeInfo, sizeof(buf), buf);
+
+ for(int i = 0; i < 66; ++i)
+ qDebug() << QString::number(buf[i]);
+
+ for (char* c = buf + 3; *c != isc_info_end; /*nothing*/) {
+ ct = *(c++);
+ len = isc_vax_integer(c, 2);
+ c += 2;
+ val = isc_vax_integer(c, len);
+ c += len;
+ qDebug() << "size" << val;
+ if (ct == isc_info_req_select_count)
+ return val;
+ }
+ //qDebug("size -1");
+ return -1;
+
+ unsigned int i, result_size;
+ if (buf[0] == isc_info_sql_records) {
+ i = 3;
+ result_size = isc_vax_integer(&buf[1],2);
+ while (buf[i] != isc_info_end && i < result_size) {
+ len = (short)isc_vax_integer(&buf[i+1],2);
+ if (buf[i] == isc_info_req_select_count)
+ return (isc_vax_integer(&buf[i+3],len));
+ i += len+3;
+ }
+ }
+// }
+ return -1;
+#endif
+}
+
+int QIBaseResult::numRowsAffected()
+{
+ Q_D(QIBaseResult);
+ static char acCountInfo[] = {isc_info_sql_records};
+ char cCountType;
+ bool bIsProcedure = false;
+
+ switch (d->queryType) {
+ case isc_info_sql_stmt_select:
+ cCountType = isc_info_req_select_count;
+ break;
+ case isc_info_sql_stmt_update:
+ cCountType = isc_info_req_update_count;
+ break;
+ case isc_info_sql_stmt_delete:
+ cCountType = isc_info_req_delete_count;
+ break;
+ case isc_info_sql_stmt_insert:
+ cCountType = isc_info_req_insert_count;
+ break;
+ case isc_info_sql_stmt_exec_procedure:
+ bIsProcedure = true; // will sum all changes
+ break;
+ default:
+ qWarning() << "numRowsAffected: Unknown statement type (" << d->queryType << ")";
+ return -1;
+ }
+
+ char acBuffer[33];
+ int iResult = -1;
+ isc_dsql_sql_info(d->status, &d->stmt, sizeof(acCountInfo), acCountInfo, sizeof(acBuffer), acBuffer);
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseResult", "Could not get statement info"),
+ QSqlError::StatementError))
+ return -1;
+ for (char *pcBuf = acBuffer + 3; *pcBuf != isc_info_end; /*nothing*/) {
+ char cType = *pcBuf++;
+ short sLength = isc_vax_integer (pcBuf, 2);
+ pcBuf += 2;
+ int iValue = isc_vax_integer (pcBuf, sLength);
+ pcBuf += sLength;
+ if (bIsProcedure) {
+ if (cType == isc_info_req_insert_count || cType == isc_info_req_update_count
+ || cType == isc_info_req_delete_count) {
+ if (iResult == -1)
+ iResult = 0;
+ iResult += iValue;
+ }
+ } else if (cType == cCountType) {
+ iResult = iValue;
+ break;
+ }
+ }
+ return iResult;
+}
+
+QSqlRecord QIBaseResult::record() const
+{
+ Q_D(const QIBaseResult);
+ QSqlRecord rec;
+ if (!isActive() || !d->sqlda)
+ return rec;
+
+ XSQLVAR v;
+ for (int i = 0; i < d->sqlda->sqld; ++i) {
+ v = d->sqlda->sqlvar[i];
+ QSqlField f(QString::fromLatin1(v.aliasname, v.aliasname_length).simplified(),
+ qIBaseTypeName2(v.sqltype, v.sqlscale < 0));
+ f.setLength(v.sqllen);
+ f.setPrecision(qAbs(v.sqlscale));
+ f.setRequiredStatus((v.sqltype & 1) == 0 ? QSqlField::Required : QSqlField::Optional);
+ if(v.sqlscale < 0) {
+ QSqlQuery q(driver()->createResult());
+ q.setForwardOnly(true);
+ q.exec(QLatin1String("select b.RDB$FIELD_PRECISION, b.RDB$FIELD_SCALE, b.RDB$FIELD_LENGTH, a.RDB$NULL_FLAG "
+ "FROM RDB$RELATION_FIELDS a, RDB$FIELDS b "
+ "WHERE b.RDB$FIELD_NAME = a.RDB$FIELD_SOURCE "
+ "AND a.RDB$RELATION_NAME = '") + QString::fromLatin1(v.relname, v.relname_length).toUpper() + QLatin1String("' "
+ "AND a.RDB$FIELD_NAME = '") + QString::fromLatin1(v.sqlname, v.sqlname_length).toUpper() + QLatin1String("' "));
+ if(q.first()) {
+ if(v.sqlscale < 0) {
+ f.setLength(q.value(0).toInt());
+ f.setPrecision(qAbs(q.value(1).toInt()));
+ } else {
+ f.setLength(q.value(2).toInt());
+ f.setPrecision(0);
+ }
+ f.setRequiredStatus(q.value(3).toBool() ? QSqlField::Required : QSqlField::Optional);
+ }
+ }
+ f.setSqlType(v.sqltype);
+ rec.append(f);
+ }
+ return rec;
+}
+
+QVariant QIBaseResult::handle() const
+{
+ Q_D(const QIBaseResult);
+ return QVariant(qRegisterMetaType<isc_stmt_handle>("isc_stmt_handle"), &d->stmt);
+}
+
+/*********************************/
+
+QIBaseDriver::QIBaseDriver(QObject * parent)
+ : QSqlDriver(*new QIBaseDriverPrivate, parent)
+{
+}
+
+QIBaseDriver::QIBaseDriver(isc_db_handle connection, QObject *parent)
+ : QSqlDriver(*new QIBaseDriverPrivate, parent)
+{
+ Q_D(QIBaseDriver);
+ d->ibase = connection;
+ setOpen(true);
+ setOpenError(false);
+}
+
+QIBaseDriver::~QIBaseDriver()
+{
+}
+
+bool QIBaseDriver::hasFeature(DriverFeature f) const
+{
+ switch (f) {
+ case QuerySize:
+ case NamedPlaceholders:
+ case LastInsertId:
+ case BatchOperations:
+ case SimpleLocking:
+ case FinishQuery:
+ case MultipleResultSets:
+ case CancelQuery:
+ return false;
+ case Transactions:
+ case PreparedQueries:
+ case PositionalPlaceholders:
+ case Unicode:
+ case BLOB:
+ case EventNotifications:
+ case LowPrecisionNumbers:
+ return true;
+ }
+ return false;
+}
+
+bool QIBaseDriver::open(const QString & db,
+ const QString & user,
+ const QString & password,
+ const QString & host,
+ int port,
+ const QString & connOpts)
+{
+ Q_D(QIBaseDriver);
+ if (isOpen())
+ close();
+
+ const QStringList opts(connOpts.split(QLatin1Char(';'), QString::SkipEmptyParts));
+
+ QString encString;
+ QByteArray role;
+ for (int i = 0; i < opts.count(); ++i) {
+ QString tmp(opts.at(i).simplified());
+ int idx;
+ if ((idx = tmp.indexOf(QLatin1Char('='))) != -1) {
+ QString val = tmp.mid(idx + 1).simplified();
+ QString opt = tmp.left(idx).simplified();
+ if (opt.toUpper() == QLatin1String("ISC_DPB_LC_CTYPE"))
+ encString = val;
+ else if (opt.toUpper() == QLatin1String("ISC_DPB_SQL_ROLE_NAME")) {
+ role = val.toLocal8Bit();
+ role.truncate(255);
+ }
+ }
+ }
+
+ // Use UNICODE_FSS when no ISC_DPB_LC_CTYPE is provided
+ if (encString.isEmpty())
+ encString = QLatin1String("UNICODE_FSS");
+ else {
+ d->tc = QTextCodec::codecForName(encString.toLocal8Bit());
+ if (!d->tc) {
+ qWarning("Unsupported encoding: %s. Using UNICODE_FFS for ISC_DPB_LC_CTYPE.", encString.toLocal8Bit().constData());
+ encString = QLatin1String("UNICODE_FSS"); // Fallback to UNICODE_FSS
+ }
+ }
+
+ QByteArray enc = encString.toLocal8Bit();
+ QByteArray usr = user.toLocal8Bit();
+ QByteArray pass = password.toLocal8Bit();
+ enc.truncate(255);
+ usr.truncate(255);
+ pass.truncate(255);
+
+ QByteArray ba;
+ ba.reserve(usr.length() + pass.length() + enc.length() + role.length() + 9);
+ ba.append(char(isc_dpb_version1));
+ ba.append(char(isc_dpb_user_name));
+ ba.append(char(usr.length()));
+ ba.append(usr.data(), usr.length());
+ ba.append(char(isc_dpb_password));
+ ba.append(char(pass.length()));
+ ba.append(pass.data(), pass.length());
+ ba.append(char(isc_dpb_lc_ctype));
+ ba.append(char(enc.length()));
+ ba.append(enc.data(), enc.length());
+
+ if (!role.isEmpty()) {
+ ba.append(char(isc_dpb_sql_role_name));
+ ba.append(char(role.length()));
+ ba.append(role.data(), role.length());
+ }
+
+ QString portString;
+ if (port != -1)
+ portString = QStringLiteral("/%1").arg(port);
+
+ QString ldb;
+ if (!host.isEmpty())
+ ldb += host + portString + QLatin1Char(':');
+ ldb += db;
+ isc_attach_database(d->status, 0, const_cast<char *>(ldb.toLocal8Bit().constData()),
+ &d->ibase, ba.size(), ba.data());
+ if (d->isError(QT_TRANSLATE_NOOP("QIBaseDriver", "Error opening database"),
+ QSqlError::ConnectionError)) {
+ setOpenError(true);
+ return false;
+ }
+
+ setOpen(true);
+ setOpenError(false);
+ return true;
+}
+
+void QIBaseDriver::close()
+{
+ Q_D(QIBaseDriver);
+ if (isOpen()) {
+
+ if (d->eventBuffers.size()) {
+ ISC_STATUS status[20];
+ QMap<QString, QIBaseEventBuffer *>::const_iterator i;
+ for (i = d->eventBuffers.constBegin(); i != d->eventBuffers.constEnd(); ++i) {
+ QIBaseEventBuffer *eBuffer = i.value();
+ eBuffer->subscriptionState = QIBaseEventBuffer::Finished;
+ isc_cancel_events(status, &d->ibase, &eBuffer->eventId);
+ qFreeEventBuffer(eBuffer);
+ }
+ d->eventBuffers.clear();
+
+#if defined(FB_API_VER)
+ // Workaround for Firebird crash
+ QTime timer;
+ timer.start();
+ while (timer.elapsed() < 500)
+ QCoreApplication::processEvents();
+#endif
+ }
+
+ isc_detach_database(d->status, &d->ibase);
+ d->ibase = 0;
+ setOpen(false);
+ setOpenError(false);
+ }
+}
+
+QSqlResult *QIBaseDriver::createResult() const
+{
+ return new QIBaseResult(this);
+}
+
+bool QIBaseDriver::beginTransaction()
+{
+ Q_D(QIBaseDriver);
+ if (!isOpen() || isOpenError())
+ return false;
+ if (d->trans)
+ return false;
+
+ isc_start_transaction(d->status, &d->trans, 1, &d->ibase, 0, NULL);
+ return !d->isError(QT_TRANSLATE_NOOP("QIBaseDriver", "Could not start transaction"),
+ QSqlError::TransactionError);
+}
+
+bool QIBaseDriver::commitTransaction()
+{
+ Q_D(QIBaseDriver);
+ if (!isOpen() || isOpenError())
+ return false;
+ if (!d->trans)
+ return false;
+
+ isc_commit_transaction(d->status, &d->trans);
+ d->trans = 0;
+ return !d->isError(QT_TRANSLATE_NOOP("QIBaseDriver", "Unable to commit transaction"),
+ QSqlError::TransactionError);
+}
+
+bool QIBaseDriver::rollbackTransaction()
+{
+ Q_D(QIBaseDriver);
+ if (!isOpen() || isOpenError())
+ return false;
+ if (!d->trans)
+ return false;
+
+ isc_rollback_transaction(d->status, &d->trans);
+ d->trans = 0;
+ return !d->isError(QT_TRANSLATE_NOOP("QIBaseDriver", "Unable to rollback transaction"),
+ QSqlError::TransactionError);
+}
+
+QStringList QIBaseDriver::tables(QSql::TableType type) const
+{
+ QStringList res;
+ if (!isOpen())
+ return res;
+
+ QString typeFilter;
+
+ if (type == QSql::SystemTables) {
+ typeFilter += QLatin1String("RDB$SYSTEM_FLAG != 0");
+ } else if (type == (QSql::SystemTables | QSql::Views)) {
+ typeFilter += QLatin1String("RDB$SYSTEM_FLAG != 0 OR RDB$VIEW_BLR NOT NULL");
+ } else {
+ if (!(type & QSql::SystemTables))
+ typeFilter += QLatin1String("RDB$SYSTEM_FLAG = 0 AND ");
+ if (!(type & QSql::Views))
+ typeFilter += QLatin1String("RDB$VIEW_BLR IS NULL AND ");
+ if (!(type & QSql::Tables))
+ typeFilter += QLatin1String("RDB$VIEW_BLR IS NOT NULL AND ");
+ if (!typeFilter.isEmpty())
+ typeFilter.chop(5);
+ }
+ if (!typeFilter.isEmpty())
+ typeFilter.prepend(QLatin1String("where "));
+
+ QSqlQuery q(createResult());
+ q.setForwardOnly(true);
+ if (!q.exec(QLatin1String("select rdb$relation_name from rdb$relations ") + typeFilter))
+ return res;
+ while(q.next())
+ res << q.value(0).toString().simplified();
+
+ return res;
+}
+
+QSqlRecord QIBaseDriver::record(const QString& tablename) const
+{
+ QSqlRecord rec;
+ if (!isOpen())
+ return rec;
+
+ QSqlQuery q(createResult());
+ q.setForwardOnly(true);
+ QString table = tablename;
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+ else
+ table = table.toUpper();
+ q.exec(QLatin1String("SELECT a.RDB$FIELD_NAME, b.RDB$FIELD_TYPE, b.RDB$FIELD_LENGTH, "
+ "b.RDB$FIELD_SCALE, b.RDB$FIELD_PRECISION, a.RDB$NULL_FLAG "
+ "FROM RDB$RELATION_FIELDS a, RDB$FIELDS b "
+ "WHERE b.RDB$FIELD_NAME = a.RDB$FIELD_SOURCE "
+ "AND a.RDB$RELATION_NAME = '") + table + QLatin1String("' "
+ "ORDER BY a.RDB$FIELD_POSITION"));
+
+ while (q.next()) {
+ int type = q.value(1).toInt();
+ bool hasScale = q.value(3).toInt() < 0;
+ QSqlField f(q.value(0).toString().simplified(), qIBaseTypeName(type, hasScale));
+ if(hasScale) {
+ f.setLength(q.value(4).toInt());
+ f.setPrecision(qAbs(q.value(3).toInt()));
+ } else {
+ f.setLength(q.value(2).toInt());
+ f.setPrecision(0);
+ }
+ f.setRequired(q.value(5).toInt() > 0);
+ f.setSqlType(type);
+
+ rec.append(f);
+ }
+ return rec;
+}
+
+QSqlIndex QIBaseDriver::primaryIndex(const QString &table) const
+{
+ QSqlIndex index(table);
+ if (!isOpen())
+ return index;
+
+ QString tablename = table;
+ if (isIdentifierEscaped(tablename, QSqlDriver::TableName))
+ tablename = stripDelimiters(tablename, QSqlDriver::TableName);
+ else
+ tablename = tablename.toUpper();
+
+ QSqlQuery q(createResult());
+ q.setForwardOnly(true);
+ q.exec(QLatin1String("SELECT a.RDB$INDEX_NAME, b.RDB$FIELD_NAME, d.RDB$FIELD_TYPE, d.RDB$FIELD_SCALE "
+ "FROM RDB$RELATION_CONSTRAINTS a, RDB$INDEX_SEGMENTS b, RDB$RELATION_FIELDS c, RDB$FIELDS d "
+ "WHERE a.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' "
+ "AND a.RDB$RELATION_NAME = '") + tablename +
+ QLatin1String(" 'AND a.RDB$INDEX_NAME = b.RDB$INDEX_NAME "
+ "AND c.RDB$RELATION_NAME = a.RDB$RELATION_NAME "
+ "AND c.RDB$FIELD_NAME = b.RDB$FIELD_NAME "
+ "AND d.RDB$FIELD_NAME = c.RDB$FIELD_SOURCE "
+ "ORDER BY b.RDB$FIELD_POSITION"));
+
+ while (q.next()) {
+ QSqlField field(q.value(1).toString().simplified(), qIBaseTypeName(q.value(2).toInt(), q.value(3).toInt() < 0));
+ index.append(field); //TODO: asc? desc?
+ index.setName(q.value(0).toString());
+ }
+
+ return index;
+}
+
+QString QIBaseDriver::formatValue(const QSqlField &field, bool trimStrings) const
+{
+ switch (field.type()) {
+ case QVariant::DateTime: {
+ QDateTime datetime = field.value().toDateTime();
+ if (datetime.isValid())
+ return QLatin1Char('\'') + QString::number(datetime.date().year()) + QLatin1Char('-') +
+ QString::number(datetime.date().month()) + QLatin1Char('-') +
+ QString::number(datetime.date().day()) + QLatin1Char(' ') +
+ QString::number(datetime.time().hour()) + QLatin1Char(':') +
+ QString::number(datetime.time().minute()) + QLatin1Char(':') +
+ QString::number(datetime.time().second()) + QLatin1Char('.') +
+ QString::number(datetime.time().msec()).rightJustified(3, QLatin1Char('0'), true) +
+ QLatin1Char('\'');
+ else
+ return QLatin1String("NULL");
+ }
+ case QVariant::Time: {
+ QTime time = field.value().toTime();
+ if (time.isValid())
+ return QLatin1Char('\'') + QString::number(time.hour()) + QLatin1Char(':') +
+ QString::number(time.minute()) + QLatin1Char(':') +
+ QString::number(time.second()) + QLatin1Char('.') +
+ QString::number(time.msec()).rightJustified(3, QLatin1Char('0'), true) +
+ QLatin1Char('\'');
+ else
+ return QLatin1String("NULL");
+ }
+ case QVariant::Date: {
+ QDate date = field.value().toDate();
+ if (date.isValid())
+ return QLatin1Char('\'') + QString::number(date.year()) + QLatin1Char('-') +
+ QString::number(date.month()) + QLatin1Char('-') +
+ QString::number(date.day()) + QLatin1Char('\'');
+ else
+ return QLatin1String("NULL");
+ }
+ default:
+ return QSqlDriver::formatValue(field, trimStrings);
+ }
+}
+
+QVariant QIBaseDriver::handle() const
+{
+ Q_D(const QIBaseDriver);
+ return QVariant(qRegisterMetaType<isc_db_handle>("isc_db_handle"), &d->ibase);
+}
+
+#if defined(FB_API_VER) && FB_API_VER >= 20
+static ISC_EVENT_CALLBACK qEventCallback(char *result, ISC_USHORT length, const ISC_UCHAR *updated)
+#else
+static isc_callback qEventCallback(char *result, short length, char *updated)
+#endif
+{
+ if (!updated)
+ return 0;
+
+
+ memcpy(result, updated, length);
+ qMutex()->lock();
+ QIBaseDriver *driver = qBufferDriverMap()->value(result);
+ qMutex()->unlock();
+
+ // We use an asynchronous call (i.e., queued connection) because the event callback
+ // is executed in a different thread than the one in which the driver lives.
+ if (driver)
+ QMetaObject::invokeMethod(driver, "qHandleEventNotification", Qt::QueuedConnection, Q_ARG(void *, reinterpret_cast<void *>(result)));
+
+ return 0;
+}
+
+bool QIBaseDriver::subscribeToNotification(const QString &name)
+{
+ Q_D(QIBaseDriver);
+ if (!isOpen()) {
+ qWarning("QIBaseDriver::subscribeFromNotificationImplementation: database not open.");
+ return false;
+ }
+
+ if (d->eventBuffers.contains(name)) {
+ qWarning("QIBaseDriver::subscribeToNotificationImplementation: already subscribing to '%s'.",
+ qPrintable(name));
+ return false;
+ }
+
+ QIBaseEventBuffer *eBuffer = new QIBaseEventBuffer;
+ eBuffer->subscriptionState = QIBaseEventBuffer::Starting;
+ eBuffer->bufferLength = isc_event_block(&eBuffer->eventBuffer,
+ &eBuffer->resultBuffer,
+ 1,
+ name.toLocal8Bit().constData());
+
+ qMutex()->lock();
+ qBufferDriverMap()->insert(eBuffer->resultBuffer, this);
+ qMutex()->unlock();
+
+ d->eventBuffers.insert(name, eBuffer);
+
+ ISC_STATUS status[20];
+ isc_que_events(status,
+ &d->ibase,
+ &eBuffer->eventId,
+ eBuffer->bufferLength,
+ eBuffer->eventBuffer,
+#if defined (FB_API_VER) && FB_API_VER >= 20
+ (ISC_EVENT_CALLBACK)qEventCallback,
+#else
+ (isc_callback)qEventCallback,
+#endif
+ eBuffer->resultBuffer);
+
+ if (status[0] == 1 && status[1]) {
+ setLastError(QSqlError(QString::fromLatin1("Could not subscribe to event notifications for %1.").arg(name)));
+ d->eventBuffers.remove(name);
+ qFreeEventBuffer(eBuffer);
+ return false;
+ }
+
+ return true;
+}
+
+bool QIBaseDriver::unsubscribeFromNotification(const QString &name)
+{
+ Q_D(QIBaseDriver);
+ if (!isOpen()) {
+ qWarning("QIBaseDriver::unsubscribeFromNotificationImplementation: database not open.");
+ return false;
+ }
+
+ if (!d->eventBuffers.contains(name)) {
+ qWarning("QIBaseDriver::QIBaseSubscriptionState not subscribed to '%s'.",
+ qPrintable(name));
+ return false;
+ }
+
+ QIBaseEventBuffer *eBuffer = d->eventBuffers.value(name);
+ ISC_STATUS status[20];
+ eBuffer->subscriptionState = QIBaseEventBuffer::Finished;
+ isc_cancel_events(status, &d->ibase, &eBuffer->eventId);
+
+ if (status[0] == 1 && status[1]) {
+ setLastError(QSqlError(QString::fromLatin1("Could not unsubscribe from event notifications for %1.").arg(name)));
+ return false;
+ }
+
+ d->eventBuffers.remove(name);
+ qFreeEventBuffer(eBuffer);
+
+ return true;
+}
+
+QStringList QIBaseDriver::subscribedToNotifications() const
+{
+ Q_D(const QIBaseDriver);
+ return QStringList(d->eventBuffers.keys());
+}
+
+void QIBaseDriver::qHandleEventNotification(void *updatedResultBuffer)
+{
+ Q_D(QIBaseDriver);
+ QMap<QString, QIBaseEventBuffer *>::const_iterator i;
+ for (i = d->eventBuffers.constBegin(); i != d->eventBuffers.constEnd(); ++i) {
+ QIBaseEventBuffer* eBuffer = i.value();
+ if (reinterpret_cast<void *>(eBuffer->resultBuffer) != updatedResultBuffer)
+ continue;
+
+ ISC_ULONG counts[20];
+ memset(counts, 0, sizeof(counts));
+ isc_event_counts(counts, eBuffer->bufferLength, eBuffer->eventBuffer, eBuffer->resultBuffer);
+ if (counts[0]) {
+
+ if (eBuffer->subscriptionState == QIBaseEventBuffer::Subscribed) {
+ emit notification(i.key());
+ emit notification(i.key(), QSqlDriver::UnknownSource, QVariant());
+ }
+ else if (eBuffer->subscriptionState == QIBaseEventBuffer::Starting)
+ eBuffer->subscriptionState = QIBaseEventBuffer::Subscribed;
+
+ ISC_STATUS status[20];
+ isc_que_events(status,
+ &d->ibase,
+ &eBuffer->eventId,
+ eBuffer->bufferLength,
+ eBuffer->eventBuffer,
+#if defined (FB_API_VER) && FB_API_VER >= 20
+ (ISC_EVENT_CALLBACK)qEventCallback,
+#else
+ (isc_callback)qEventCallback,
+#endif
+ eBuffer->resultBuffer);
+ if (Q_UNLIKELY(status[0] == 1 && status[1])) {
+ qCritical("QIBaseDriver::qHandleEventNotification: could not resubscribe to '%s'",
+ qPrintable(i.key()));
+ }
+
+ return;
+ }
+ }
+}
+
+QString QIBaseDriver::escapeIdentifier(const QString &identifier, IdentifierType) const
+{
+ QString res = identifier;
+ if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) {
+ res.replace(QLatin1Char('"'), QLatin1String("\"\""));
+ res.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
+ res.replace(QLatin1Char('.'), QLatin1String("\".\""));
+ }
+ return res;
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/sqldrivers/ibase/qsql_ibase_p.h b/src/plugins/sqldrivers/ibase/qsql_ibase_p.h
new file mode 100644
index 0000000000..c7cee41462
--- /dev/null
+++ b/src/plugins/sqldrivers/ibase/qsql_ibase_p.h
@@ -0,0 +1,114 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSQL_IBASE_H
+#define QSQL_IBASE_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtSql/qsqldriver.h>
+#include <ibase.h>
+
+#ifdef QT_PLUGIN
+#define Q_EXPORT_SQLDRIVER_IBASE
+#else
+#define Q_EXPORT_SQLDRIVER_IBASE Q_SQL_EXPORT
+#endif
+
+QT_BEGIN_NAMESPACE
+
+class QSqlResult;
+class QIBaseDriverPrivate;
+
+class Q_EXPORT_SQLDRIVER_IBASE QIBaseDriver : public QSqlDriver
+{
+ friend class QIBaseResultPrivate;
+ Q_DECLARE_PRIVATE(QIBaseDriver)
+ Q_OBJECT
+public:
+ explicit QIBaseDriver(QObject *parent = 0);
+ explicit QIBaseDriver(isc_db_handle connection, QObject *parent = 0);
+ virtual ~QIBaseDriver();
+ bool hasFeature(DriverFeature f) const Q_DECL_OVERRIDE;
+ bool open(const QString &db,
+ const QString &user,
+ const QString &password,
+ const QString &host,
+ int port,
+ const QString &connOpts) Q_DECL_OVERRIDE;
+ bool open(const QString &db,
+ const QString &user,
+ const QString &password,
+ const QString &host,
+ int port) { return open(db, user, password, host, port, QString()); }
+ void close() Q_DECL_OVERRIDE;
+ QSqlResult *createResult() const Q_DECL_OVERRIDE;
+ bool beginTransaction() Q_DECL_OVERRIDE;
+ bool commitTransaction() Q_DECL_OVERRIDE;
+ bool rollbackTransaction() Q_DECL_OVERRIDE;
+ QStringList tables(QSql::TableType) const Q_DECL_OVERRIDE;
+
+ QSqlRecord record(const QString& tablename) const Q_DECL_OVERRIDE;
+ QSqlIndex primaryIndex(const QString &table) const Q_DECL_OVERRIDE;
+
+ QString formatValue(const QSqlField &field, bool trimStrings) const Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+ QString escapeIdentifier(const QString &identifier, IdentifierType type) const Q_DECL_OVERRIDE;
+
+ bool subscribeToNotification(const QString &name) Q_DECL_OVERRIDE;
+ bool unsubscribeFromNotification(const QString &name) Q_DECL_OVERRIDE;
+ QStringList subscribedToNotifications() const Q_DECL_OVERRIDE;
+
+private Q_SLOTS:
+ void qHandleEventNotification(void* updatedResultBuffer);
+};
+
+QT_END_NAMESPACE
+
+#endif // QSQL_IBASE_H
diff --git a/src/plugins/sqldrivers/mysql/main.cpp b/src/plugins/sqldrivers/mysql/main.cpp
index 855a6eeb9c..00d9c5bb34 100644
--- a/src/plugins/sqldrivers/mysql/main.cpp
+++ b/src/plugins/sqldrivers/mysql/main.cpp
@@ -39,7 +39,7 @@
#include <qsqldriverplugin.h>
#include <qstringlist.h>
-#include "../../../sql/drivers/mysql/qsql_mysql_p.h"
+#include "qsql_mysql_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/sqldrivers/mysql/mysql.pro b/src/plugins/sqldrivers/mysql/mysql.pro
index c917bfca48..56dd5f598c 100644
--- a/src/plugins/sqldrivers/mysql/mysql.pro
+++ b/src/plugins/sqldrivers/mysql/mysql.pro
@@ -1,8 +1,11 @@
TARGET = qsqlmysql
-SOURCES = main.cpp
+HEADERS += $$PWD/qsql_mysql_p.h
+SOURCES += $$PWD/qsql_mysql.cpp $$PWD/main.cpp
+
+QMAKE_USE += mysql
+
OTHER_FILES += mysql.json
-include(../../../sql/drivers/mysql/qsql_mysql.pri)
PLUGIN_CLASS_NAME = QMYSQLDriverPlugin
include(../qsqldriverbase.pri)
diff --git a/src/plugins/sqldrivers/mysql/qsql_mysql.cpp b/src/plugins/sqldrivers/mysql/qsql_mysql.cpp
new file mode 100644
index 0000000000..eb2bddd0bd
--- /dev/null
+++ b/src/plugins/sqldrivers/mysql/qsql_mysql.cpp
@@ -0,0 +1,1678 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsql_mysql_p.h"
+
+#include <qcoreapplication.h>
+#include <qvariant.h>
+#include <qdatetime.h>
+#include <qsqlerror.h>
+#include <qsqlfield.h>
+#include <qsqlindex.h>
+#include <qsqlquery.h>
+#include <qsqlrecord.h>
+#include <qstringlist.h>
+#include <qtextcodec.h>
+#include <qvector.h>
+#include <qfile.h>
+#include <qdebug.h>
+#include <QtSql/private/qsqldriver_p.h>
+#include <QtSql/private/qsqlresult_p.h>
+
+#ifdef Q_OS_WIN32
+// comment the next line out if you want to use MySQL/embedded on Win32 systems.
+// note that it will crash if you don't statically link to the mysql/e library!
+# define Q_NO_MYSQL_EMBEDDED
+#endif
+
+Q_DECLARE_METATYPE(MYSQL_RES*)
+Q_DECLARE_METATYPE(MYSQL*)
+
+#if MYSQL_VERSION_ID >= 40108
+Q_DECLARE_METATYPE(MYSQL_STMT*)
+#endif
+
+#if MYSQL_VERSION_ID >= 40100
+# define Q_CLIENT_MULTI_STATEMENTS CLIENT_MULTI_STATEMENTS
+#else
+# define Q_CLIENT_MULTI_STATEMENTS 0
+#endif
+
+QT_BEGIN_NAMESPACE
+
+class QMYSQLDriverPrivate : public QSqlDriverPrivate
+{
+ Q_DECLARE_PUBLIC(QMYSQLDriver)
+
+public:
+ QMYSQLDriverPrivate() : QSqlDriverPrivate(), mysql(0),
+#ifndef QT_NO_TEXTCODEC
+ tc(QTextCodec::codecForLocale()),
+#else
+ tc(0),
+#endif
+ preparedQuerysEnabled(false) { dbmsType = QSqlDriver::MySqlServer; }
+ MYSQL *mysql;
+ QTextCodec *tc;
+
+ bool preparedQuerysEnabled;
+};
+
+static inline QString toUnicode(QTextCodec *tc, const char *str)
+{
+#ifdef QT_NO_TEXTCODEC
+ Q_UNUSED(tc);
+ return QString::fromLatin1(str);
+#else
+ return tc->toUnicode(str);
+#endif
+}
+
+static inline QString toUnicode(QTextCodec *tc, const char *str, int length)
+{
+#ifdef QT_NO_TEXTCODEC
+ Q_UNUSED(tc);
+ return QString::fromLatin1(str, length);
+#else
+ return tc->toUnicode(str, length);
+#endif
+}
+
+static inline QByteArray fromUnicode(QTextCodec *tc, const QString &str)
+{
+#ifdef QT_NO_TEXTCODEC
+ Q_UNUSED(tc);
+ return str.toLatin1();
+#else
+ return tc->fromUnicode(str);
+#endif
+}
+
+static inline QVariant qDateFromString(const QString &val)
+{
+#ifdef QT_NO_DATESTRING
+ Q_UNUSED(val);
+ return QVariant(val);
+#else
+ if (val.isEmpty())
+ return QVariant(QDate());
+ return QVariant(QDate::fromString(val, Qt::ISODate));
+#endif
+}
+
+static inline QVariant qTimeFromString(const QString &val)
+{
+#ifdef QT_NO_DATESTRING
+ Q_UNUSED(val);
+ return QVariant(val);
+#else
+ if (val.isEmpty())
+ return QVariant(QTime());
+ return QVariant(QTime::fromString(val, Qt::ISODate));
+#endif
+}
+
+static inline QVariant qDateTimeFromString(QString &val)
+{
+#ifdef QT_NO_DATESTRING
+ Q_UNUSED(val);
+ return QVariant(val);
+#else
+ if (val.isEmpty())
+ return QVariant(QDateTime());
+ if (val.length() == 14)
+ // TIMESTAMPS have the format yyyyMMddhhmmss
+ val.insert(4, QLatin1Char('-')).insert(7, QLatin1Char('-')).insert(10,
+ QLatin1Char('T')).insert(13, QLatin1Char(':')).insert(16, QLatin1Char(':'));
+ return QVariant(QDateTime::fromString(val, Qt::ISODate));
+#endif
+}
+
+class QMYSQLResultPrivate;
+
+class QMYSQLResult : public QSqlResult
+{
+ Q_DECLARE_PRIVATE(QMYSQLResult)
+ friend class QMYSQLDriver;
+
+public:
+ explicit QMYSQLResult(const QMYSQLDriver *db);
+ ~QMYSQLResult();
+
+ QVariant handle() const Q_DECL_OVERRIDE;
+protected:
+ void cleanup();
+ bool fetch(int i) Q_DECL_OVERRIDE;
+ bool fetchNext() Q_DECL_OVERRIDE;
+ bool fetchLast() Q_DECL_OVERRIDE;
+ bool fetchFirst() Q_DECL_OVERRIDE;
+ QVariant data(int field) Q_DECL_OVERRIDE;
+ bool isNull(int field) Q_DECL_OVERRIDE;
+ bool reset (const QString& query) Q_DECL_OVERRIDE;
+ int size() Q_DECL_OVERRIDE;
+ int numRowsAffected() Q_DECL_OVERRIDE;
+ QVariant lastInsertId() const Q_DECL_OVERRIDE;
+ QSqlRecord record() const Q_DECL_OVERRIDE;
+ void virtual_hook(int id, void *data) Q_DECL_OVERRIDE;
+ bool nextResult() Q_DECL_OVERRIDE;
+
+#if MYSQL_VERSION_ID >= 40108
+ bool prepare(const QString &stmt) Q_DECL_OVERRIDE;
+ bool exec() Q_DECL_OVERRIDE;
+#endif
+};
+
+class QMYSQLResultPrivate: public QSqlResultPrivate
+{
+ Q_DECLARE_PUBLIC(QMYSQLResult)
+
+public:
+ Q_DECLARE_SQLDRIVER_PRIVATE(QMYSQLDriver)
+
+ QMYSQLResultPrivate(QMYSQLResult *q, const QMYSQLDriver *drv)
+ : QSqlResultPrivate(q, drv),
+ result(0),
+ rowsAffected(0),
+ hasBlobs(false)
+#if MYSQL_VERSION_ID >= 40108
+ , stmt(0), meta(0), inBinds(0), outBinds(0)
+#endif
+ , preparedQuery(false)
+ { }
+
+ MYSQL_RES *result;
+ MYSQL_ROW row;
+
+ int rowsAffected;
+
+ bool bindInValues();
+ void bindBlobs();
+
+ bool hasBlobs;
+ struct QMyField
+ {
+ QMyField()
+ : outField(0), nullIndicator(false), bufLength(0ul),
+ myField(0), type(QVariant::Invalid)
+ {}
+ char *outField;
+ my_bool nullIndicator;
+ ulong bufLength;
+ MYSQL_FIELD *myField;
+ QVariant::Type type;
+ };
+
+ QVector<QMyField> fields;
+
+#if MYSQL_VERSION_ID >= 40108
+ MYSQL_STMT* stmt;
+ MYSQL_RES* meta;
+
+ MYSQL_BIND *inBinds;
+ MYSQL_BIND *outBinds;
+#endif
+
+ bool preparedQuery;
+};
+
+#ifndef QT_NO_TEXTCODEC
+static QTextCodec* codec(MYSQL* mysql)
+{
+#if MYSQL_VERSION_ID >= 32321
+ QTextCodec* heuristicCodec = QTextCodec::codecForName(mysql_character_set_name(mysql));
+ if (heuristicCodec)
+ return heuristicCodec;
+#endif
+ return QTextCodec::codecForLocale();
+}
+#endif // QT_NO_TEXTCODEC
+
+static QSqlError qMakeError(const QString& err, QSqlError::ErrorType type,
+ const QMYSQLDriverPrivate* p)
+{
+ const char *cerr = p->mysql ? mysql_error(p->mysql) : 0;
+ return QSqlError(QLatin1String("QMYSQL: ") + err,
+ p->tc ? toUnicode(p->tc, cerr) : QString::fromLatin1(cerr),
+ type, mysql_errno(p->mysql));
+}
+
+
+static QVariant::Type qDecodeMYSQLType(int mysqltype, uint flags)
+{
+ QVariant::Type type;
+ switch (mysqltype) {
+ case FIELD_TYPE_TINY :
+ type = static_cast<QVariant::Type>((flags & UNSIGNED_FLAG) ? QMetaType::UChar : QMetaType::Char);
+ break;
+ case FIELD_TYPE_SHORT :
+ type = static_cast<QVariant::Type>((flags & UNSIGNED_FLAG) ? QMetaType::UShort : QMetaType::Short);
+ break;
+ case FIELD_TYPE_LONG :
+ case FIELD_TYPE_INT24 :
+ type = (flags & UNSIGNED_FLAG) ? QVariant::UInt : QVariant::Int;
+ break;
+ case FIELD_TYPE_YEAR :
+ type = QVariant::Int;
+ break;
+ case FIELD_TYPE_LONGLONG :
+ type = (flags & UNSIGNED_FLAG) ? QVariant::ULongLong : QVariant::LongLong;
+ break;
+ case FIELD_TYPE_FLOAT :
+ case FIELD_TYPE_DOUBLE :
+ case FIELD_TYPE_DECIMAL :
+#if defined(FIELD_TYPE_NEWDECIMAL)
+ case FIELD_TYPE_NEWDECIMAL:
+#endif
+ type = QVariant::Double;
+ break;
+ case FIELD_TYPE_DATE :
+ type = QVariant::Date;
+ break;
+ case FIELD_TYPE_TIME :
+ type = QVariant::Time;
+ break;
+ case FIELD_TYPE_DATETIME :
+ case FIELD_TYPE_TIMESTAMP :
+ type = QVariant::DateTime;
+ break;
+ case FIELD_TYPE_STRING :
+ case FIELD_TYPE_VAR_STRING :
+ case FIELD_TYPE_BLOB :
+ case FIELD_TYPE_TINY_BLOB :
+ case FIELD_TYPE_MEDIUM_BLOB :
+ case FIELD_TYPE_LONG_BLOB :
+ type = (flags & BINARY_FLAG) ? QVariant::ByteArray : QVariant::String;
+ break;
+ default:
+ case FIELD_TYPE_ENUM :
+ case FIELD_TYPE_SET :
+ type = QVariant::String;
+ break;
+ }
+ return type;
+}
+
+static QSqlField qToField(MYSQL_FIELD *field, QTextCodec *tc)
+{
+ QSqlField f(toUnicode(tc, field->name),
+ qDecodeMYSQLType(int(field->type), field->flags));
+ f.setRequired(IS_NOT_NULL(field->flags));
+ f.setLength(field->length);
+ f.setPrecision(field->decimals);
+ f.setSqlType(field->type);
+ f.setAutoValue(field->flags & AUTO_INCREMENT_FLAG);
+ return f;
+}
+
+#if MYSQL_VERSION_ID >= 40108
+
+static QSqlError qMakeStmtError(const QString& err, QSqlError::ErrorType type,
+ MYSQL_STMT* stmt)
+{
+ const char *cerr = mysql_stmt_error(stmt);
+ return QSqlError(QLatin1String("QMYSQL3: ") + err,
+ QString::fromLatin1(cerr),
+ type, mysql_stmt_errno(stmt));
+}
+
+static bool qIsBlob(int t)
+{
+ return t == MYSQL_TYPE_TINY_BLOB
+ || t == MYSQL_TYPE_BLOB
+ || t == MYSQL_TYPE_MEDIUM_BLOB
+ || t == MYSQL_TYPE_LONG_BLOB;
+}
+
+static bool qIsInteger(int t)
+{
+ return t == QMetaType::Char || t == QMetaType::UChar
+ || t == QMetaType::Short || t == QMetaType::UShort
+ || t == QMetaType::Int || t == QMetaType::UInt
+ || t == QMetaType::LongLong || t == QMetaType::ULongLong;
+}
+
+void QMYSQLResultPrivate::bindBlobs()
+{
+ int i;
+ MYSQL_FIELD *fieldInfo;
+ MYSQL_BIND *bind;
+
+ for(i = 0; i < fields.count(); ++i) {
+ fieldInfo = fields.at(i).myField;
+ if (qIsBlob(inBinds[i].buffer_type) && meta && fieldInfo) {
+ bind = &inBinds[i];
+ bind->buffer_length = fieldInfo->max_length;
+ delete[] static_cast<char*>(bind->buffer);
+ bind->buffer = new char[fieldInfo->max_length];
+ fields[i].outField = static_cast<char*>(bind->buffer);
+ }
+ }
+}
+
+bool QMYSQLResultPrivate::bindInValues()
+{
+ MYSQL_BIND *bind;
+ char *field;
+ int i = 0;
+
+ if (!meta)
+ meta = mysql_stmt_result_metadata(stmt);
+ if (!meta)
+ return false;
+
+ fields.resize(mysql_num_fields(meta));
+
+ inBinds = new MYSQL_BIND[fields.size()];
+ memset(inBinds, 0, fields.size() * sizeof(MYSQL_BIND));
+
+ MYSQL_FIELD *fieldInfo;
+
+ while((fieldInfo = mysql_fetch_field(meta))) {
+ QMyField &f = fields[i];
+ f.myField = fieldInfo;
+
+ f.type = qDecodeMYSQLType(fieldInfo->type, fieldInfo->flags);
+ if (qIsBlob(fieldInfo->type)) {
+ // the size of a blob-field is available as soon as we call
+ // mysql_stmt_store_result()
+ // after mysql_stmt_exec() in QMYSQLResult::exec()
+ fieldInfo->length = 0;
+ hasBlobs = true;
+ } else if (qIsInteger(f.type)) {
+ fieldInfo->length = 8;
+ } else {
+ fieldInfo->type = MYSQL_TYPE_STRING;
+ }
+ bind = &inBinds[i];
+ field = new char[fieldInfo->length + 1];
+ memset(field, 0, fieldInfo->length + 1);
+
+ bind->buffer_type = fieldInfo->type;
+ bind->buffer = field;
+ bind->buffer_length = f.bufLength = fieldInfo->length + 1;
+ bind->is_null = &f.nullIndicator;
+ bind->length = &f.bufLength;
+ bind->is_unsigned = fieldInfo->flags & UNSIGNED_FLAG ? 1 : 0;
+ f.outField=field;
+
+ ++i;
+ }
+ return true;
+}
+#endif
+
+QMYSQLResult::QMYSQLResult(const QMYSQLDriver* db)
+ : QSqlResult(*new QMYSQLResultPrivate(this, db))
+{
+}
+
+QMYSQLResult::~QMYSQLResult()
+{
+ cleanup();
+}
+
+QVariant QMYSQLResult::handle() const
+{
+ Q_D(const QMYSQLResult);
+#if MYSQL_VERSION_ID >= 40108
+ if(d->preparedQuery)
+ return d->meta ? QVariant::fromValue(d->meta) : QVariant::fromValue(d->stmt);
+ else
+#endif
+ return QVariant::fromValue(d->result);
+}
+
+void QMYSQLResult::cleanup()
+{
+ Q_D(QMYSQLResult);
+ if (d->result)
+ mysql_free_result(d->result);
+
+// must iterate trough leftover result sets from multi-selects or stored procedures
+// if this isn't done subsequent queries will fail with "Commands out of sync"
+#if MYSQL_VERSION_ID >= 40100
+ while (driver() && d->drv_d_func()->mysql && mysql_next_result(d->drv_d_func()->mysql) == 0) {
+ MYSQL_RES *res = mysql_store_result(d->drv_d_func()->mysql);
+ if (res)
+ mysql_free_result(res);
+ }
+#endif
+
+#if MYSQL_VERSION_ID >= 40108
+ if (d->stmt) {
+ if (mysql_stmt_close(d->stmt))
+ qWarning("QMYSQLResult::cleanup: unable to free statement handle");
+ d->stmt = 0;
+ }
+
+ if (d->meta) {
+ mysql_free_result(d->meta);
+ d->meta = 0;
+ }
+
+ int i;
+ for (i = 0; i < d->fields.count(); ++i)
+ delete[] d->fields[i].outField;
+
+ if (d->outBinds) {
+ delete[] d->outBinds;
+ d->outBinds = 0;
+ }
+
+ if (d->inBinds) {
+ delete[] d->inBinds;
+ d->inBinds = 0;
+ }
+#endif
+
+ d->hasBlobs = false;
+ d->fields.clear();
+ d->result = NULL;
+ d->row = NULL;
+ setAt(-1);
+ setActive(false);
+}
+
+bool QMYSQLResult::fetch(int i)
+{
+ Q_D(QMYSQLResult);
+ if (!driver())
+ return false;
+ if (isForwardOnly()) { // fake a forward seek
+ if (at() < i) {
+ int x = i - at();
+ while (--x && fetchNext()) {};
+ return fetchNext();
+ } else {
+ return false;
+ }
+ }
+ if (at() == i)
+ return true;
+ if (d->preparedQuery) {
+#if MYSQL_VERSION_ID >= 40108
+ mysql_stmt_data_seek(d->stmt, i);
+
+ int nRC = mysql_stmt_fetch(d->stmt);
+ if (nRC) {
+#ifdef MYSQL_DATA_TRUNCATED
+ if (nRC == 1 || nRC == MYSQL_DATA_TRUNCATED)
+#else
+ if (nRC == 1)
+#endif
+ setLastError(qMakeStmtError(QCoreApplication::translate("QMYSQLResult",
+ "Unable to fetch data"), QSqlError::StatementError, d->stmt));
+ return false;
+ }
+#else
+ return false;
+#endif
+ } else {
+ mysql_data_seek(d->result, i);
+ d->row = mysql_fetch_row(d->result);
+ if (!d->row)
+ return false;
+ }
+
+ setAt(i);
+ return true;
+}
+
+bool QMYSQLResult::fetchNext()
+{
+ Q_D(QMYSQLResult);
+ if (!driver())
+ return false;
+ if (d->preparedQuery) {
+#if MYSQL_VERSION_ID >= 40108
+ int nRC = mysql_stmt_fetch(d->stmt);
+ if (nRC) {
+#ifdef MYSQL_DATA_TRUNCATED
+ if (nRC == 1 || nRC == MYSQL_DATA_TRUNCATED)
+#else
+ if (nRC == 1)
+#endif // MYSQL_DATA_TRUNCATED
+ setLastError(qMakeStmtError(QCoreApplication::translate("QMYSQLResult",
+ "Unable to fetch data"), QSqlError::StatementError, d->stmt));
+ return false;
+ }
+#else
+ return false;
+#endif
+ } else {
+ d->row = mysql_fetch_row(d->result);
+ if (!d->row)
+ return false;
+ }
+ setAt(at() + 1);
+ return true;
+}
+
+bool QMYSQLResult::fetchLast()
+{
+ Q_D(QMYSQLResult);
+ if (!driver())
+ return false;
+ if (isForwardOnly()) { // fake this since MySQL can't seek on forward only queries
+ bool success = fetchNext(); // did we move at all?
+ while (fetchNext()) {};
+ return success;
+ }
+
+ my_ulonglong numRows;
+ if (d->preparedQuery) {
+#if MYSQL_VERSION_ID >= 40108
+ numRows = mysql_stmt_num_rows(d->stmt);
+#else
+ numRows = 0;
+#endif
+ } else {
+ numRows = mysql_num_rows(d->result);
+ }
+ if (at() == int(numRows))
+ return true;
+ if (!numRows)
+ return false;
+ return fetch(numRows - 1);
+}
+
+bool QMYSQLResult::fetchFirst()
+{
+ if (at() == 0)
+ return true;
+
+ if (isForwardOnly())
+ return (at() == QSql::BeforeFirstRow) ? fetchNext() : false;
+ return fetch(0);
+}
+
+QVariant QMYSQLResult::data(int field)
+{
+ Q_D(QMYSQLResult);
+ if (!isSelect() || field >= d->fields.count()) {
+ qWarning("QMYSQLResult::data: column %d out of range", field);
+ return QVariant();
+ }
+
+ if (!driver())
+ return QVariant();
+
+ int fieldLength = 0;
+ const QMYSQLResultPrivate::QMyField &f = d->fields.at(field);
+ QString val;
+ if (d->preparedQuery) {
+ if (f.nullIndicator)
+ return QVariant(f.type);
+
+ if (qIsInteger(f.type)) {
+ QVariant variant(f.type, f.outField);
+ // we never want to return char variants here, see QTBUG-53397
+ if (static_cast<int>(f.type) == QMetaType::UChar)
+ return variant.toUInt();
+ else if (static_cast<int>(f.type) == QMetaType::Char)
+ return variant.toInt();
+ return variant;
+ }
+
+ if (f.type != QVariant::ByteArray)
+ val = toUnicode(d->drv_d_func()->tc, f.outField, f.bufLength);
+ } else {
+ if (d->row[field] == NULL) {
+ // NULL value
+ return QVariant(f.type);
+ }
+
+ fieldLength = mysql_fetch_lengths(d->result)[field];
+
+ if (f.type != QVariant::ByteArray)
+ val = toUnicode(d->drv_d_func()->tc, d->row[field], fieldLength);
+ }
+
+ switch (static_cast<int>(f.type)) {
+ case QVariant::LongLong:
+ return QVariant(val.toLongLong());
+ case QVariant::ULongLong:
+ return QVariant(val.toULongLong());
+ case QMetaType::Char:
+ case QMetaType::Short:
+ case QVariant::Int:
+ return QVariant(val.toInt());
+ case QMetaType::UChar:
+ case QMetaType::UShort:
+ case QVariant::UInt:
+ return QVariant(val.toUInt());
+ case QVariant::Double: {
+ QVariant v;
+ bool ok=false;
+ double dbl = val.toDouble(&ok);
+ switch(numericalPrecisionPolicy()) {
+ case QSql::LowPrecisionInt32:
+ v=QVariant(dbl).toInt();
+ break;
+ case QSql::LowPrecisionInt64:
+ v = QVariant(dbl).toLongLong();
+ break;
+ case QSql::LowPrecisionDouble:
+ v = QVariant(dbl);
+ break;
+ case QSql::HighPrecision:
+ default:
+ v = val;
+ ok = true;
+ break;
+ }
+ if(ok)
+ return v;
+ else
+ return QVariant();
+ }
+ return QVariant(val.toDouble());
+ case QVariant::Date:
+ return qDateFromString(val);
+ case QVariant::Time:
+ return qTimeFromString(val);
+ case QVariant::DateTime:
+ return qDateTimeFromString(val);
+ case QVariant::ByteArray: {
+
+ QByteArray ba;
+ if (d->preparedQuery) {
+ ba = QByteArray(f.outField, f.bufLength);
+ } else {
+ ba = QByteArray(d->row[field], fieldLength);
+ }
+ return QVariant(ba);
+ }
+ default:
+ case QVariant::String:
+ return QVariant(val);
+ }
+ qWarning("QMYSQLResult::data: unknown data type");
+ return QVariant();
+}
+
+bool QMYSQLResult::isNull(int field)
+{
+ Q_D(const QMYSQLResult);
+ if (field < 0 || field >= d->fields.count())
+ return true;
+ if (d->preparedQuery)
+ return d->fields.at(field).nullIndicator;
+ else
+ return d->row[field] == NULL;
+}
+
+bool QMYSQLResult::reset (const QString& query)
+{
+ Q_D(QMYSQLResult);
+ if (!driver() || !driver()->isOpen() || driver()->isOpenError())
+ return false;
+
+ d->preparedQuery = false;
+
+ cleanup();
+
+ const QByteArray encQuery(fromUnicode(d->drv_d_func()->tc, query));
+ if (mysql_real_query(d->drv_d_func()->mysql, encQuery.data(), encQuery.length())) {
+ setLastError(qMakeError(QCoreApplication::translate("QMYSQLResult", "Unable to execute query"),
+ QSqlError::StatementError, d->drv_d_func()));
+ return false;
+ }
+ d->result = mysql_store_result(d->drv_d_func()->mysql);
+ if (!d->result && mysql_field_count(d->drv_d_func()->mysql) > 0) {
+ setLastError(qMakeError(QCoreApplication::translate("QMYSQLResult", "Unable to store result"),
+ QSqlError::StatementError, d->drv_d_func()));
+ return false;
+ }
+ int numFields = mysql_field_count(d->drv_d_func()->mysql);
+ setSelect(numFields != 0);
+ d->fields.resize(numFields);
+ d->rowsAffected = mysql_affected_rows(d->drv_d_func()->mysql);
+
+ if (isSelect()) {
+ for(int i = 0; i < numFields; i++) {
+ MYSQL_FIELD* field = mysql_fetch_field_direct(d->result, i);
+ d->fields[i].type = qDecodeMYSQLType(field->type, field->flags);
+ }
+ setAt(QSql::BeforeFirstRow);
+ }
+ setActive(true);
+ return isActive();
+}
+
+int QMYSQLResult::size()
+{
+ Q_D(const QMYSQLResult);
+ if (driver() && isSelect())
+ if (d->preparedQuery)
+#if MYSQL_VERSION_ID >= 40108
+ return mysql_stmt_num_rows(d->stmt);
+#else
+ return -1;
+#endif
+ else
+ return int(mysql_num_rows(d->result));
+ else
+ return -1;
+}
+
+int QMYSQLResult::numRowsAffected()
+{
+ Q_D(const QMYSQLResult);
+ return d->rowsAffected;
+}
+
+QVariant QMYSQLResult::lastInsertId() const
+{
+ Q_D(const QMYSQLResult);
+ if (!isActive() || !driver())
+ return QVariant();
+
+ if (d->preparedQuery) {
+#if MYSQL_VERSION_ID >= 40108
+ quint64 id = mysql_stmt_insert_id(d->stmt);
+ if (id)
+ return QVariant(id);
+#endif
+ } else {
+ quint64 id = mysql_insert_id(d->drv_d_func()->mysql);
+ if (id)
+ return QVariant(id);
+ }
+ return QVariant();
+}
+
+QSqlRecord QMYSQLResult::record() const
+{
+ Q_D(const QMYSQLResult);
+ QSqlRecord info;
+ MYSQL_RES *res;
+ if (!isActive() || !isSelect() || !driver())
+ return info;
+
+#if MYSQL_VERSION_ID >= 40108
+ res = d->preparedQuery ? d->meta : d->result;
+#else
+ res = d->result;
+#endif
+
+ if (!mysql_errno(d->drv_d_func()->mysql)) {
+ mysql_field_seek(res, 0);
+ MYSQL_FIELD* field = mysql_fetch_field(res);
+ while(field) {
+ info.append(qToField(field, d->drv_d_func()->tc));
+ field = mysql_fetch_field(res);
+ }
+ }
+ mysql_field_seek(res, 0);
+ return info;
+}
+
+bool QMYSQLResult::nextResult()
+{
+ Q_D(QMYSQLResult);
+ if (!driver())
+ return false;
+#if MYSQL_VERSION_ID >= 40100
+ setAt(-1);
+ setActive(false);
+
+ if (d->result && isSelect())
+ mysql_free_result(d->result);
+ d->result = 0;
+ setSelect(false);
+
+ for (int i = 0; i < d->fields.count(); ++i)
+ delete[] d->fields[i].outField;
+ d->fields.clear();
+
+ int status = mysql_next_result(d->drv_d_func()->mysql);
+ if (status > 0) {
+ setLastError(qMakeError(QCoreApplication::translate("QMYSQLResult", "Unable to execute next query"),
+ QSqlError::StatementError, d->drv_d_func()));
+ return false;
+ } else if (status == -1) {
+ return false; // No more result sets
+ }
+
+ d->result = mysql_store_result(d->drv_d_func()->mysql);
+ int numFields = mysql_field_count(d->drv_d_func()->mysql);
+ if (!d->result && numFields > 0) {
+ setLastError(qMakeError(QCoreApplication::translate("QMYSQLResult", "Unable to store next result"),
+ QSqlError::StatementError, d->drv_d_func()));
+ return false;
+ }
+
+ setSelect(numFields > 0);
+ d->fields.resize(numFields);
+ d->rowsAffected = mysql_affected_rows(d->drv_d_func()->mysql);
+
+ if (isSelect()) {
+ for (int i = 0; i < numFields; i++) {
+ MYSQL_FIELD* field = mysql_fetch_field_direct(d->result, i);
+ d->fields[i].type = qDecodeMYSQLType(field->type, field->flags);
+ }
+ }
+
+ setActive(true);
+ return true;
+#else
+ return false;
+#endif
+}
+
+void QMYSQLResult::virtual_hook(int id, void *data)
+{
+ QSqlResult::virtual_hook(id, data);
+}
+
+
+#if MYSQL_VERSION_ID >= 40108
+
+static MYSQL_TIME *toMySqlDate(QDate date, QTime time, QVariant::Type type)
+{
+ Q_ASSERT(type == QVariant::Time || type == QVariant::Date
+ || type == QVariant::DateTime);
+
+ MYSQL_TIME *myTime = new MYSQL_TIME;
+ memset(myTime, 0, sizeof(MYSQL_TIME));
+
+ if (type == QVariant::Time || type == QVariant::DateTime) {
+ myTime->hour = time.hour();
+ myTime->minute = time.minute();
+ myTime->second = time.second();
+ myTime->second_part = time.msec() * 1000;
+ }
+ if (type == QVariant::Date || type == QVariant::DateTime) {
+ myTime->year = date.year();
+ myTime->month = date.month();
+ myTime->day = date.day();
+ }
+
+ return myTime;
+}
+
+bool QMYSQLResult::prepare(const QString& query)
+{
+ Q_D(QMYSQLResult);
+ if (!driver())
+ return false;
+#if MYSQL_VERSION_ID >= 40108
+ cleanup();
+ if (!d->drv_d_func()->preparedQuerysEnabled)
+ return QSqlResult::prepare(query);
+
+ int r;
+
+ if (query.isEmpty())
+ return false;
+
+ if (!d->stmt)
+ d->stmt = mysql_stmt_init(d->drv_d_func()->mysql);
+ if (!d->stmt) {
+ setLastError(qMakeError(QCoreApplication::translate("QMYSQLResult", "Unable to prepare statement"),
+ QSqlError::StatementError, d->drv_d_func()));
+ return false;
+ }
+
+ const QByteArray encQuery(fromUnicode(d->drv_d_func()->tc, query));
+ r = mysql_stmt_prepare(d->stmt, encQuery.constData(), encQuery.length());
+ if (r != 0) {
+ setLastError(qMakeStmtError(QCoreApplication::translate("QMYSQLResult",
+ "Unable to prepare statement"), QSqlError::StatementError, d->stmt));
+ cleanup();
+ return false;
+ }
+
+ if (mysql_stmt_param_count(d->stmt) > 0) {// allocate memory for outvalues
+ d->outBinds = new MYSQL_BIND[mysql_stmt_param_count(d->stmt)];
+ }
+
+ setSelect(d->bindInValues());
+ d->preparedQuery = true;
+ return true;
+#else
+ return false;
+#endif
+}
+
+bool QMYSQLResult::exec()
+{
+ Q_D(QMYSQLResult);
+ if (!driver())
+ return false;
+ if (!d->preparedQuery)
+ return QSqlResult::exec();
+ if (!d->stmt)
+ return false;
+
+ int r = 0;
+ MYSQL_BIND* currBind;
+ QVector<MYSQL_TIME *> timeVector;
+ QVector<QByteArray> stringVector;
+ QVector<my_bool> nullVector;
+
+ const QVector<QVariant> values = boundValues();
+
+ r = mysql_stmt_reset(d->stmt);
+ if (r != 0) {
+ setLastError(qMakeStmtError(QCoreApplication::translate("QMYSQLResult",
+ "Unable to reset statement"), QSqlError::StatementError, d->stmt));
+ return false;
+ }
+
+ if (mysql_stmt_param_count(d->stmt) > 0 &&
+ mysql_stmt_param_count(d->stmt) == (uint)values.count()) {
+
+ nullVector.resize(values.count());
+ for (int i = 0; i < values.count(); ++i) {
+ const QVariant &val = boundValues().at(i);
+ void *data = const_cast<void *>(val.constData());
+
+ currBind = &d->outBinds[i];
+
+ nullVector[i] = static_cast<my_bool>(val.isNull());
+ currBind->is_null = &nullVector[i];
+ currBind->length = 0;
+ currBind->is_unsigned = 0;
+
+ switch (val.type()) {
+ case QVariant::ByteArray:
+ currBind->buffer_type = MYSQL_TYPE_BLOB;
+ currBind->buffer = const_cast<char *>(val.toByteArray().constData());
+ currBind->buffer_length = val.toByteArray().size();
+ break;
+
+ case QVariant::Time:
+ case QVariant::Date:
+ case QVariant::DateTime: {
+ MYSQL_TIME *myTime = toMySqlDate(val.toDate(), val.toTime(), val.type());
+ timeVector.append(myTime);
+
+ currBind->buffer = myTime;
+ switch(val.type()) {
+ case QVariant::Time:
+ currBind->buffer_type = MYSQL_TYPE_TIME;
+ myTime->time_type = MYSQL_TIMESTAMP_TIME;
+ break;
+ case QVariant::Date:
+ currBind->buffer_type = MYSQL_TYPE_DATE;
+ myTime->time_type = MYSQL_TIMESTAMP_DATE;
+ break;
+ case QVariant::DateTime:
+ currBind->buffer_type = MYSQL_TYPE_DATETIME;
+ myTime->time_type = MYSQL_TIMESTAMP_DATETIME;
+ break;
+ default:
+ break;
+ }
+ currBind->buffer_length = sizeof(MYSQL_TIME);
+ currBind->length = 0;
+ break; }
+ case QVariant::UInt:
+ case QVariant::Int:
+ currBind->buffer_type = MYSQL_TYPE_LONG;
+ currBind->buffer = data;
+ currBind->buffer_length = sizeof(int);
+ currBind->is_unsigned = (val.type() != QVariant::Int);
+ break;
+ case QVariant::Bool:
+ currBind->buffer_type = MYSQL_TYPE_TINY;
+ currBind->buffer = data;
+ currBind->buffer_length = sizeof(bool);
+ currBind->is_unsigned = false;
+ break;
+ case QVariant::Double:
+ currBind->buffer_type = MYSQL_TYPE_DOUBLE;
+ currBind->buffer = data;
+ currBind->buffer_length = sizeof(double);
+ break;
+ case QVariant::LongLong:
+ case QVariant::ULongLong:
+ currBind->buffer_type = MYSQL_TYPE_LONGLONG;
+ currBind->buffer = data;
+ currBind->buffer_length = sizeof(qint64);
+ currBind->is_unsigned = (val.type() == QVariant::ULongLong);
+ break;
+ case QVariant::String:
+ default: {
+ QByteArray ba = fromUnicode(d->drv_d_func()->tc, val.toString());
+ stringVector.append(ba);
+ currBind->buffer_type = MYSQL_TYPE_STRING;
+ currBind->buffer = const_cast<char *>(ba.constData());
+ currBind->buffer_length = ba.length();
+ break; }
+ }
+ }
+
+ r = mysql_stmt_bind_param(d->stmt, d->outBinds);
+ if (r != 0) {
+ setLastError(qMakeStmtError(QCoreApplication::translate("QMYSQLResult",
+ "Unable to bind value"), QSqlError::StatementError, d->stmt));
+ qDeleteAll(timeVector);
+ return false;
+ }
+ }
+ r = mysql_stmt_execute(d->stmt);
+
+ qDeleteAll(timeVector);
+
+ if (r != 0) {
+ setLastError(qMakeStmtError(QCoreApplication::translate("QMYSQLResult",
+ "Unable to execute statement"), QSqlError::StatementError, d->stmt));
+ return false;
+ }
+ //if there is meta-data there is also data
+ setSelect(d->meta);
+
+ d->rowsAffected = mysql_stmt_affected_rows(d->stmt);
+
+ if (isSelect()) {
+ my_bool update_max_length = true;
+
+ r = mysql_stmt_bind_result(d->stmt, d->inBinds);
+ if (r != 0) {
+ setLastError(qMakeStmtError(QCoreApplication::translate("QMYSQLResult",
+ "Unable to bind outvalues"), QSqlError::StatementError, d->stmt));
+ return false;
+ }
+ if (d->hasBlobs)
+ mysql_stmt_attr_set(d->stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &update_max_length);
+
+ r = mysql_stmt_store_result(d->stmt);
+ if (r != 0) {
+ setLastError(qMakeStmtError(QCoreApplication::translate("QMYSQLResult",
+ "Unable to store statement results"), QSqlError::StatementError, d->stmt));
+ return false;
+ }
+
+ if (d->hasBlobs) {
+ // mysql_stmt_store_result() with STMT_ATTR_UPDATE_MAX_LENGTH set to true crashes
+ // when called without a preceding call to mysql_stmt_bind_result()
+ // in versions < 4.1.8
+ d->bindBlobs();
+ r = mysql_stmt_bind_result(d->stmt, d->inBinds);
+ if (r != 0) {
+ setLastError(qMakeStmtError(QCoreApplication::translate("QMYSQLResult",
+ "Unable to bind outvalues"), QSqlError::StatementError, d->stmt));
+ return false;
+ }
+ }
+ setAt(QSql::BeforeFirstRow);
+ }
+ setActive(true);
+ return true;
+}
+#endif
+/////////////////////////////////////////////////////////
+
+static int qMySqlConnectionCount = 0;
+static bool qMySqlInitHandledByUser = false;
+
+static void qLibraryInit()
+{
+#ifndef Q_NO_MYSQL_EMBEDDED
+# if MYSQL_VERSION_ID >= 40000
+ if (qMySqlInitHandledByUser || qMySqlConnectionCount > 1)
+ return;
+
+# if (MYSQL_VERSION_ID >= 40110 && MYSQL_VERSION_ID < 50000) || MYSQL_VERSION_ID >= 50003
+ if (mysql_library_init(0, 0, 0)) {
+# else
+ if (mysql_server_init(0, 0, 0)) {
+# endif
+ qWarning("QMYSQLDriver::qServerInit: unable to start server.");
+ }
+# endif // MYSQL_VERSION_ID
+#endif // Q_NO_MYSQL_EMBEDDED
+}
+
+static void qLibraryEnd()
+{
+#ifndef Q_NO_MYSQL_EMBEDDED
+# if MYSQL_VERSION_ID > 40000
+# if (MYSQL_VERSION_ID >= 40110 && MYSQL_VERSION_ID < 50000) || MYSQL_VERSION_ID >= 50003
+ mysql_library_end();
+# else
+ mysql_server_end();
+# endif
+# endif
+#endif
+}
+
+QMYSQLDriver::QMYSQLDriver(QObject * parent)
+ : QSqlDriver(*new QMYSQLDriverPrivate, parent)
+{
+ init();
+ qLibraryInit();
+}
+
+/*!
+ Create a driver instance with the open connection handle, \a con.
+ The instance's parent (owner) is \a parent.
+*/
+
+QMYSQLDriver::QMYSQLDriver(MYSQL * con, QObject * parent)
+ : QSqlDriver(*new QMYSQLDriverPrivate, parent)
+{
+ Q_D(QMYSQLDriver);
+ init();
+ if (con) {
+ d->mysql = (MYSQL *) con;
+#ifndef QT_NO_TEXTCODEC
+ d->tc = codec(con);
+#endif
+ setOpen(true);
+ setOpenError(false);
+ if (qMySqlConnectionCount == 1)
+ qMySqlInitHandledByUser = true;
+ } else {
+ qLibraryInit();
+ }
+}
+
+void QMYSQLDriver::init()
+{
+ Q_D(QMYSQLDriver);
+ d->mysql = 0;
+ qMySqlConnectionCount++;
+}
+
+QMYSQLDriver::~QMYSQLDriver()
+{
+ qMySqlConnectionCount--;
+ if (qMySqlConnectionCount == 0 && !qMySqlInitHandledByUser)
+ qLibraryEnd();
+}
+
+bool QMYSQLDriver::hasFeature(DriverFeature f) const
+{
+ Q_D(const QMYSQLDriver);
+ switch (f) {
+ case Transactions:
+// CLIENT_TRANSACTION should be defined in all recent mysql client libs > 3.23.34
+#ifdef CLIENT_TRANSACTIONS
+ if (d->mysql) {
+ if ((d->mysql->server_capabilities & CLIENT_TRANSACTIONS) == CLIENT_TRANSACTIONS)
+ return true;
+ }
+#endif
+ return false;
+ case NamedPlaceholders:
+ case BatchOperations:
+ case SimpleLocking:
+ case EventNotifications:
+ case FinishQuery:
+ case CancelQuery:
+ return false;
+ case QuerySize:
+ case BLOB:
+ case LastInsertId:
+ case Unicode:
+ case LowPrecisionNumbers:
+ return true;
+ case PreparedQueries:
+ case PositionalPlaceholders:
+#if MYSQL_VERSION_ID >= 40108
+ return d->preparedQuerysEnabled;
+#else
+ return false;
+#endif
+ case MultipleResultSets:
+#if MYSQL_VERSION_ID >= 40100
+ return true;
+#else
+ return false;
+#endif
+ }
+ return false;
+}
+
+static void setOptionFlag(uint &optionFlags, const QString &opt)
+{
+ if (opt == QLatin1String("CLIENT_COMPRESS"))
+ optionFlags |= CLIENT_COMPRESS;
+ else if (opt == QLatin1String("CLIENT_FOUND_ROWS"))
+ optionFlags |= CLIENT_FOUND_ROWS;
+ else if (opt == QLatin1String("CLIENT_IGNORE_SPACE"))
+ optionFlags |= CLIENT_IGNORE_SPACE;
+ else if (opt == QLatin1String("CLIENT_INTERACTIVE"))
+ optionFlags |= CLIENT_INTERACTIVE;
+ else if (opt == QLatin1String("CLIENT_NO_SCHEMA"))
+ optionFlags |= CLIENT_NO_SCHEMA;
+ else if (opt == QLatin1String("CLIENT_ODBC"))
+ optionFlags |= CLIENT_ODBC;
+ else if (opt == QLatin1String("CLIENT_SSL"))
+ qWarning("QMYSQLDriver: SSL_KEY, SSL_CERT and SSL_CA should be used instead of CLIENT_SSL.");
+ else
+ qWarning("QMYSQLDriver::open: Unknown connect option '%s'", opt.toLocal8Bit().constData());
+}
+
+bool QMYSQLDriver::open(const QString& db,
+ const QString& user,
+ const QString& password,
+ const QString& host,
+ int port,
+ const QString& connOpts)
+{
+ Q_D(QMYSQLDriver);
+ if (isOpen())
+ close();
+
+ /* This is a hack to get MySQL's stored procedure support working.
+ Since a stored procedure _may_ return multiple result sets,
+ we have to enable CLIEN_MULTI_STATEMENTS here, otherwise _any_
+ stored procedure call will fail.
+ */
+ unsigned int optionFlags = Q_CLIENT_MULTI_STATEMENTS;
+ const QStringList opts(connOpts.split(QLatin1Char(';'), QString::SkipEmptyParts));
+ QString unixSocket;
+ QString sslCert;
+ QString sslCA;
+ QString sslKey;
+ QString sslCAPath;
+ QString sslCipher;
+#if MYSQL_VERSION_ID >= 50000
+ my_bool reconnect=false;
+ uint connectTimeout = 0;
+ uint readTimeout = 0;
+ uint writeTimeout = 0;
+#endif
+
+ // extract the real options from the string
+ for (int i = 0; i < opts.count(); ++i) {
+ QString tmp(opts.at(i).simplified());
+ int idx;
+ if ((idx = tmp.indexOf(QLatin1Char('='))) != -1) {
+ QString val = tmp.mid(idx + 1).simplified();
+ QString opt = tmp.left(idx).simplified();
+ if (opt == QLatin1String("UNIX_SOCKET"))
+ unixSocket = val;
+#if MYSQL_VERSION_ID >= 50000
+ else if (opt == QLatin1String("MYSQL_OPT_RECONNECT")) {
+ if (val == QLatin1String("TRUE") || val == QLatin1String("1") || val.isEmpty())
+ reconnect = true;
+ } else if (opt == QLatin1String("MYSQL_OPT_CONNECT_TIMEOUT")) {
+ connectTimeout = val.toInt();
+ } else if (opt == QLatin1String("MYSQL_OPT_READ_TIMEOUT")) {
+ readTimeout = val.toInt();
+ } else if (opt == QLatin1String("MYSQL_OPT_WRITE_TIMEOUT")) {
+ writeTimeout = val.toInt();
+ }
+#endif
+ else if (opt == QLatin1String("SSL_KEY"))
+ sslKey = val;
+ else if (opt == QLatin1String("SSL_CERT"))
+ sslCert = val;
+ else if (opt == QLatin1String("SSL_CA"))
+ sslCA = val;
+ else if (opt == QLatin1String("SSL_CAPATH"))
+ sslCAPath = val;
+ else if (opt == QLatin1String("SSL_CIPHER"))
+ sslCipher = val;
+ else if (val == QLatin1String("TRUE") || val == QLatin1String("1"))
+ setOptionFlag(optionFlags, tmp.left(idx).simplified());
+ else
+ qWarning("QMYSQLDriver::open: Illegal connect option value '%s'",
+ tmp.toLocal8Bit().constData());
+ } else {
+ setOptionFlag(optionFlags, tmp);
+ }
+ }
+
+ if (!(d->mysql = mysql_init((MYSQL*) 0))) {
+ setLastError(qMakeError(tr("Unable to allocate a MYSQL object"),
+ QSqlError::ConnectionError, d));
+ setOpenError(true);
+ return false;
+ }
+
+ if (!sslKey.isNull() || !sslCert.isNull() || !sslCA.isNull() ||
+ !sslCAPath.isNull() || !sslCipher.isNull()) {
+ mysql_ssl_set(d->mysql,
+ sslKey.isNull() ? static_cast<const char *>(0)
+ : QFile::encodeName(sslKey).constData(),
+ sslCert.isNull() ? static_cast<const char *>(0)
+ : QFile::encodeName(sslCert).constData(),
+ sslCA.isNull() ? static_cast<const char *>(0)
+ : QFile::encodeName(sslCA).constData(),
+ sslCAPath.isNull() ? static_cast<const char *>(0)
+ : QFile::encodeName(sslCAPath).constData(),
+ sslCipher.isNull() ? static_cast<const char *>(0)
+ : sslCipher.toLocal8Bit().constData());
+ }
+
+#if MYSQL_VERSION_ID >= 50100
+ if (connectTimeout != 0)
+ mysql_options(d->mysql, MYSQL_OPT_CONNECT_TIMEOUT, &connectTimeout);
+ if (readTimeout != 0)
+ mysql_options(d->mysql, MYSQL_OPT_READ_TIMEOUT, &readTimeout);
+ if (writeTimeout != 0)
+ mysql_options(d->mysql, MYSQL_OPT_WRITE_TIMEOUT, &writeTimeout);
+#endif
+ MYSQL *mysql = mysql_real_connect(d->mysql,
+ host.isNull() ? static_cast<const char *>(0)
+ : host.toLocal8Bit().constData(),
+ user.isNull() ? static_cast<const char *>(0)
+ : user.toLocal8Bit().constData(),
+ password.isNull() ? static_cast<const char *>(0)
+ : password.toLocal8Bit().constData(),
+ db.isNull() ? static_cast<const char *>(0)
+ : db.toLocal8Bit().constData(),
+ (port > -1) ? port : 0,
+ unixSocket.isNull() ? static_cast<const char *>(0)
+ : unixSocket.toLocal8Bit().constData(),
+ optionFlags);
+
+ if (mysql == d->mysql) {
+ if (!db.isEmpty() && mysql_select_db(d->mysql, db.toLocal8Bit().constData())) {
+ setLastError(qMakeError(tr("Unable to open database '%1'").arg(db), QSqlError::ConnectionError, d));
+ mysql_close(d->mysql);
+ setOpenError(true);
+ return false;
+ }
+#if MYSQL_VERSION_ID >= 50100
+ if (reconnect)
+ mysql_options(d->mysql, MYSQL_OPT_RECONNECT, &reconnect);
+#endif
+ } else {
+ setLastError(qMakeError(tr("Unable to connect"),
+ QSqlError::ConnectionError, d));
+ mysql_close(d->mysql);
+ d->mysql = NULL;
+ setOpenError(true);
+ return false;
+ }
+
+#if (MYSQL_VERSION_ID >= 40113 && MYSQL_VERSION_ID < 50000) || MYSQL_VERSION_ID >= 50007
+ if (mysql_get_client_version() >= 50503 && mysql_get_server_version(d->mysql) >= 50503) {
+ // force the communication to be utf8mb4 (only utf8mb4 supports 4-byte characters)
+ mysql_set_character_set(d->mysql, "utf8mb4");
+ } else {
+ // force the communication to be utf8
+ mysql_set_character_set(d->mysql, "utf8");
+ }
+#endif
+#ifndef QT_NO_TEXTCODEC
+ d->tc = codec(d->mysql);
+#endif
+
+#if MYSQL_VERSION_ID >= 40108
+ d->preparedQuerysEnabled = mysql_get_client_version() >= 40108
+ && mysql_get_server_version(d->mysql) >= 40100;
+#else
+ d->preparedQuerysEnabled = false;
+#endif
+
+#ifndef QT_NO_THREAD
+ mysql_thread_init();
+#endif
+
+
+ setOpen(true);
+ setOpenError(false);
+ return true;
+}
+
+void QMYSQLDriver::close()
+{
+ Q_D(QMYSQLDriver);
+ if (isOpen()) {
+#ifndef QT_NO_THREAD
+ mysql_thread_end();
+#endif
+ mysql_close(d->mysql);
+ d->mysql = NULL;
+ setOpen(false);
+ setOpenError(false);
+ }
+}
+
+QSqlResult *QMYSQLDriver::createResult() const
+{
+ return new QMYSQLResult(this);
+}
+
+QStringList QMYSQLDriver::tables(QSql::TableType type) const
+{
+ Q_D(const QMYSQLDriver);
+ QStringList tl;
+#if MYSQL_VERSION_ID >= 40100
+ if( mysql_get_server_version(d->mysql) < 50000)
+ {
+#endif
+ if (!isOpen())
+ return tl;
+ if (!(type & QSql::Tables))
+ return tl;
+
+ MYSQL_RES* tableRes = mysql_list_tables(d->mysql, NULL);
+ MYSQL_ROW row;
+ int i = 0;
+ while (tableRes) {
+ mysql_data_seek(tableRes, i);
+ row = mysql_fetch_row(tableRes);
+ if (!row)
+ break;
+ tl.append(toUnicode(d->tc, row[0]));
+ i++;
+ }
+ mysql_free_result(tableRes);
+#if MYSQL_VERSION_ID >= 40100
+ } else {
+ QSqlQuery q(createResult());
+ if(type & QSql::Tables) {
+ QString sql = QLatin1String("select table_name from information_schema.tables where table_schema = '") + QLatin1String(d->mysql->db) + QLatin1String("' and table_type = 'BASE TABLE'");
+ q.exec(sql);
+
+ while(q.next())
+ tl.append(q.value(0).toString());
+ }
+ if(type & QSql::Views) {
+ QString sql = QLatin1String("select table_name from information_schema.tables where table_schema = '") + QLatin1String(d->mysql->db) + QLatin1String("' and table_type = 'VIEW'");
+ q.exec(sql);
+
+ while(q.next())
+ tl.append(q.value(0).toString());
+ }
+ }
+#endif
+ return tl;
+}
+
+QSqlIndex QMYSQLDriver::primaryIndex(const QString& tablename) const
+{
+ QSqlIndex idx;
+ if (!isOpen())
+ return idx;
+
+ QSqlQuery i(createResult());
+ QString stmt(QLatin1String("show index from %1;"));
+ QSqlRecord fil = record(tablename);
+ i.exec(stmt.arg(tablename));
+ while (i.isActive() && i.next()) {
+ if (i.value(2).toString() == QLatin1String("PRIMARY")) {
+ idx.append(fil.field(i.value(4).toString()));
+ idx.setCursorName(i.value(0).toString());
+ idx.setName(i.value(2).toString());
+ }
+ }
+
+ return idx;
+}
+
+QSqlRecord QMYSQLDriver::record(const QString& tablename) const
+{
+ Q_D(const QMYSQLDriver);
+ QString table=tablename;
+ if(isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+
+ QSqlRecord info;
+ if (!isOpen())
+ return info;
+ MYSQL_RES* r = mysql_list_fields(d->mysql, table.toLocal8Bit().constData(), 0);
+ if (!r) {
+ return info;
+ }
+ MYSQL_FIELD* field;
+
+ while ((field = mysql_fetch_field(r)))
+ info.append(qToField(field, d->tc));
+ mysql_free_result(r);
+ return info;
+}
+
+QVariant QMYSQLDriver::handle() const
+{
+ Q_D(const QMYSQLDriver);
+ return QVariant::fromValue(d->mysql);
+}
+
+bool QMYSQLDriver::beginTransaction()
+{
+ Q_D(QMYSQLDriver);
+#ifndef CLIENT_TRANSACTIONS
+ return false;
+#endif
+ if (!isOpen()) {
+ qWarning("QMYSQLDriver::beginTransaction: Database not open");
+ return false;
+ }
+ if (mysql_query(d->mysql, "BEGIN WORK")) {
+ setLastError(qMakeError(tr("Unable to begin transaction"),
+ QSqlError::StatementError, d));
+ return false;
+ }
+ return true;
+}
+
+bool QMYSQLDriver::commitTransaction()
+{
+ Q_D(QMYSQLDriver);
+#ifndef CLIENT_TRANSACTIONS
+ return false;
+#endif
+ if (!isOpen()) {
+ qWarning("QMYSQLDriver::commitTransaction: Database not open");
+ return false;
+ }
+ if (mysql_query(d->mysql, "COMMIT")) {
+ setLastError(qMakeError(tr("Unable to commit transaction"),
+ QSqlError::StatementError, d));
+ return false;
+ }
+ return true;
+}
+
+bool QMYSQLDriver::rollbackTransaction()
+{
+ Q_D(QMYSQLDriver);
+#ifndef CLIENT_TRANSACTIONS
+ return false;
+#endif
+ if (!isOpen()) {
+ qWarning("QMYSQLDriver::rollbackTransaction: Database not open");
+ return false;
+ }
+ if (mysql_query(d->mysql, "ROLLBACK")) {
+ setLastError(qMakeError(tr("Unable to rollback transaction"),
+ QSqlError::StatementError, d));
+ return false;
+ }
+ return true;
+}
+
+QString QMYSQLDriver::formatValue(const QSqlField &field, bool trimStrings) const
+{
+ Q_D(const QMYSQLDriver);
+ QString r;
+ if (field.isNull()) {
+ r = QLatin1String("NULL");
+ } else {
+ switch(field.type()) {
+ case QVariant::Double:
+ r = QString::number(field.value().toDouble(), 'g', field.precision());
+ break;
+ case QVariant::String:
+ // Escape '\' characters
+ r = QSqlDriver::formatValue(field, trimStrings);
+ r.replace(QLatin1String("\\"), QLatin1String("\\\\"));
+ break;
+ case QVariant::ByteArray:
+ if (isOpen()) {
+ const QByteArray ba = field.value().toByteArray();
+ // buffer has to be at least length*2+1 bytes
+ char* buffer = new char[ba.size() * 2 + 1];
+ int escapedSize = int(mysql_real_escape_string(d->mysql, buffer,
+ ba.data(), ba.size()));
+ r.reserve(escapedSize + 3);
+ r.append(QLatin1Char('\'')).append(toUnicode(d->tc, buffer)).append(QLatin1Char('\''));
+ delete[] buffer;
+ break;
+ } else {
+ qWarning("QMYSQLDriver::formatValue: Database not open");
+ }
+ // fall through
+ default:
+ r = QSqlDriver::formatValue(field, trimStrings);
+ }
+ }
+ return r;
+}
+
+QString QMYSQLDriver::escapeIdentifier(const QString &identifier, IdentifierType) const
+{
+ QString res = identifier;
+ if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('`')) && !identifier.endsWith(QLatin1Char('`')) ) {
+ res.prepend(QLatin1Char('`')).append(QLatin1Char('`'));
+ res.replace(QLatin1Char('.'), QLatin1String("`.`"));
+ }
+ return res;
+}
+
+bool QMYSQLDriver::isIdentifierEscaped(const QString &identifier, IdentifierType type) const
+{
+ Q_UNUSED(type);
+ return identifier.size() > 2
+ && identifier.startsWith(QLatin1Char('`')) //left delimited
+ && identifier.endsWith(QLatin1Char('`')); //right delimited
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/sqldrivers/mysql/qsql_mysql_p.h b/src/plugins/sqldrivers/mysql/qsql_mysql_p.h
new file mode 100644
index 0000000000..7641f9aa34
--- /dev/null
+++ b/src/plugins/sqldrivers/mysql/qsql_mysql_p.h
@@ -0,0 +1,110 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSQL_MYSQL_H
+#define QSQL_MYSQL_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtSql/qsqldriver.h>
+
+#if defined (Q_OS_WIN32)
+#include <QtCore/qt_windows.h>
+#endif
+
+#include <mysql.h>
+
+#ifdef QT_PLUGIN
+#define Q_EXPORT_SQLDRIVER_MYSQL
+#else
+#define Q_EXPORT_SQLDRIVER_MYSQL Q_SQL_EXPORT
+#endif
+
+QT_BEGIN_NAMESPACE
+
+class QMYSQLDriverPrivate;
+
+class Q_EXPORT_SQLDRIVER_MYSQL QMYSQLDriver : public QSqlDriver
+{
+ friend class QMYSQLResultPrivate;
+ Q_DECLARE_PRIVATE(QMYSQLDriver)
+ Q_OBJECT
+public:
+ explicit QMYSQLDriver(QObject *parent=0);
+ explicit QMYSQLDriver(MYSQL *con, QObject * parent=0);
+ ~QMYSQLDriver();
+ bool hasFeature(DriverFeature f) const Q_DECL_OVERRIDE;
+ bool open(const QString & db,
+ const QString & user,
+ const QString & password,
+ const QString & host,
+ int port,
+ const QString& connOpts) Q_DECL_OVERRIDE;
+ void close() Q_DECL_OVERRIDE;
+ QSqlResult *createResult() const Q_DECL_OVERRIDE;
+ QStringList tables(QSql::TableType) const Q_DECL_OVERRIDE;
+ QSqlIndex primaryIndex(const QString& tablename) const Q_DECL_OVERRIDE;
+ QSqlRecord record(const QString& tablename) const Q_DECL_OVERRIDE;
+ QString formatValue(const QSqlField &field,
+ bool trimStrings) const Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+ QString escapeIdentifier(const QString &identifier, IdentifierType type) const Q_DECL_OVERRIDE;
+
+ bool isIdentifierEscaped(const QString &identifier, IdentifierType type) const Q_DECL_OVERRIDE;
+
+protected:
+ bool beginTransaction() Q_DECL_OVERRIDE;
+ bool commitTransaction() Q_DECL_OVERRIDE;
+ bool rollbackTransaction() Q_DECL_OVERRIDE;
+private:
+ void init();
+};
+
+QT_END_NAMESPACE
+
+#endif // QSQL_MYSQL_H
diff --git a/src/plugins/sqldrivers/oci/main.cpp b/src/plugins/sqldrivers/oci/main.cpp
index 980116123d..e576928d31 100644
--- a/src/plugins/sqldrivers/oci/main.cpp
+++ b/src/plugins/sqldrivers/oci/main.cpp
@@ -39,7 +39,7 @@
#include <qsqldriverplugin.h>
#include <qstringlist.h>
-#include "../../../sql/drivers/oci/qsql_oci_p.h"
+#include "qsql_oci_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/sqldrivers/oci/oci.pro b/src/plugins/sqldrivers/oci/oci.pro
index 96a0dd9ab6..e6ef71f20f 100644
--- a/src/plugins/sqldrivers/oci/oci.pro
+++ b/src/plugins/sqldrivers/oci/oci.pro
@@ -1,8 +1,13 @@
TARGET = qsqloci
-SOURCES = main.cpp
+HEADERS += $$PWD/qsql_oci_p.h
+SOURCES += $$PWD/qsql_oci.cpp $$PWD/main.cpp
+
+QMAKE_USE += oci
+
+darwin:QMAKE_LFLAGS += -Wl,-flat_namespace,-U,_environ
+
OTHER_FILES += oci.json
-include(../../../sql/drivers/oci/qsql_oci.pri)
PLUGIN_CLASS_NAME = QOCIDriverPlugin
include(../qsqldriverbase.pri)
diff --git a/src/plugins/sqldrivers/oci/qsql_oci.cpp b/src/plugins/sqldrivers/oci/qsql_oci.cpp
new file mode 100644
index 0000000000..47d6db7ea4
--- /dev/null
+++ b/src/plugins/sqldrivers/oci/qsql_oci.cpp
@@ -0,0 +1,2725 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsql_oci_p.h"
+
+#include <qcoreapplication.h>
+#include <qvariant.h>
+#include <qdatetime.h>
+#include <qmetatype.h>
+#include <qregexp.h>
+#include <qshareddata.h>
+#include <qsqlerror.h>
+#include <qsqlfield.h>
+#include <qsqlindex.h>
+#include <qsqlquery.h>
+#include <QtSql/private/qsqlcachedresult_p.h>
+#include <QtSql/private/qsqldriver_p.h>
+#include <qstringlist.h>
+#include <qvarlengtharray.h>
+#include <qvector.h>
+#include <qdebug.h>
+
+// This is needed for oracle oci when compiling with mingw-w64 headers
+#if defined(__MINGW64_VERSION_MAJOR) && defined(_WIN64)
+#define _int64 __int64
+#endif
+
+
+#include <oci.h>
+#ifdef max
+#undef max
+#endif
+#ifdef min
+#undef min
+#endif
+
+#include <stdlib.h>
+
+#define QOCI_DYNAMIC_CHUNK_SIZE 65535
+#define QOCI_PREFETCH_MEM 10240
+
+// setting this define will allow using a query from a different
+// thread than its database connection.
+// warning - this is not fully tested and can lead to race conditions
+#define QOCI_THREADED
+
+//#define QOCI_DEBUG
+
+Q_DECLARE_OPAQUE_POINTER(OCIEnv*);
+Q_DECLARE_METATYPE(OCIEnv*)
+Q_DECLARE_OPAQUE_POINTER(OCIStmt*);
+Q_DECLARE_METATYPE(OCIStmt*)
+
+QT_BEGIN_NAMESPACE
+
+#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
+enum { QOCIEncoding = 2002 }; // AL16UTF16LE
+#else
+enum { QOCIEncoding = 2000 }; // AL16UTF16
+#endif
+
+#ifdef OCI_ATTR_CHARSET_FORM
+// Always set the OCI_ATTR_CHARSET_FORM to SQLCS_NCHAR is safe
+// because Oracle server will deal with the implicit Conversion
+// Between CHAR and NCHAR.
+// see: http://download.oracle.com/docs/cd/A91202_01/901_doc/appdev.901/a89857/oci05bnd.htm#422705
+static const ub1 qOraCharsetForm = SQLCS_NCHAR;
+#endif
+
+#if defined (OCI_UTF16ID)
+static const ub2 qOraCharset = OCI_UTF16ID;
+#else
+static const ub2 qOraCharset = OCI_UCS2ID;
+#endif
+
+typedef QVarLengthArray<sb2, 32> IndicatorArray;
+typedef QVarLengthArray<ub2, 32> SizeArray;
+
+static QByteArray qMakeOraDate(const QDateTime& dt);
+static QDateTime qMakeDate(const char* oraDate);
+
+static QByteArray qMakeOCINumber(const qlonglong &ll, OCIError *err);
+static QByteArray qMakeOCINumber(const qulonglong& ull, OCIError* err);
+
+static qlonglong qMakeLongLong(const char* ociNumber, OCIError* err);
+static qulonglong qMakeULongLong(const char* ociNumber, OCIError* err);
+
+static QString qOraWarn(OCIError *err, int *errorCode = 0);
+
+#ifndef Q_CC_SUN
+static // for some reason, Sun CC can't use qOraWarning when it's declared static
+#endif
+void qOraWarning(const char* msg, OCIError *err);
+static QSqlError qMakeError(const QString& errString, QSqlError::ErrorType type, OCIError *err);
+
+
+
+class QOCIRowId: public QSharedData
+{
+public:
+ QOCIRowId(OCIEnv *env);
+ ~QOCIRowId();
+
+ OCIRowid *id;
+
+private:
+ QOCIRowId(const QOCIRowId &other): QSharedData(other) { Q_ASSERT(false); }
+};
+
+QOCIRowId::QOCIRowId(OCIEnv *env)
+ : id(0)
+{
+ OCIDescriptorAlloc (env, reinterpret_cast<dvoid **>(&id),
+ OCI_DTYPE_ROWID, 0, 0);
+}
+
+QOCIRowId::~QOCIRowId()
+{
+ if (id)
+ OCIDescriptorFree(id, OCI_DTYPE_ROWID);
+}
+
+typedef QSharedDataPointer<QOCIRowId> QOCIRowIdPointer;
+QT_BEGIN_INCLUDE_NAMESPACE
+Q_DECLARE_METATYPE(QOCIRowIdPointer)
+QT_END_INCLUDE_NAMESPACE
+
+class QOCIDriverPrivate : public QSqlDriverPrivate
+{
+ Q_DECLARE_PUBLIC(QOCIDriver)
+
+public:
+ QOCIDriverPrivate();
+
+ OCIEnv *env;
+ OCISvcCtx *svc;
+ OCIServer *srvhp;
+ OCISession *authp;
+ OCIError *err;
+ bool transaction;
+ int serverVersion;
+ int prefetchRows;
+ int prefetchMem;
+ QString user;
+
+ void allocErrorHandle();
+};
+
+class QOCICols;
+class QOCIResultPrivate;
+
+class QOCIResult: public QSqlCachedResult
+{
+ Q_DECLARE_PRIVATE(QOCIResult)
+ friend class QOCIDriver;
+ friend class QOCICols;
+public:
+ QOCIResult(const QOCIDriver *db);
+ ~QOCIResult();
+ bool prepare(const QString &query) Q_DECL_OVERRIDE;
+ bool exec() Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+protected:
+ bool gotoNext(ValueCache &values, int index) Q_DECL_OVERRIDE;
+ bool reset(const QString &query) Q_DECL_OVERRIDE;
+ int size() Q_DECL_OVERRIDE;
+ int numRowsAffected() Q_DECL_OVERRIDE;
+ QSqlRecord record() const Q_DECL_OVERRIDE;
+ QVariant lastInsertId() const Q_DECL_OVERRIDE;
+ bool execBatch(bool arrayBind = false) Q_DECL_OVERRIDE;
+ void virtual_hook(int id, void *data) Q_DECL_OVERRIDE;
+};
+
+class QOCIResultPrivate: public QSqlCachedResultPrivate
+{
+public:
+ Q_DECLARE_PUBLIC(QOCIResult)
+ Q_DECLARE_SQLDRIVER_PRIVATE(QOCIDriver)
+ QOCIResultPrivate(QOCIResult *q, const QOCIDriver *drv);
+ ~QOCIResultPrivate();
+
+ QOCICols *cols;
+ OCIEnv *env;
+ OCIError *err;
+ OCISvcCtx *&svc;
+ OCIStmt *sql;
+ bool transaction;
+ int serverVersion;
+ int prefetchRows, prefetchMem;
+
+ void setStatementAttributes();
+ int bindValue(OCIStmt *sql, OCIBind **hbnd, OCIError *err, int pos,
+ const QVariant &val, dvoid *indPtr, ub2 *tmpSize, QList<QByteArray> &tmpStorage);
+ int bindValues(QVector<QVariant> &values, IndicatorArray &indicators, SizeArray &tmpSizes,
+ QList<QByteArray> &tmpStorage);
+ void outValues(QVector<QVariant> &values, IndicatorArray &indicators,
+ QList<QByteArray> &tmpStorage);
+ inline bool isOutValue(int i) const
+ { Q_Q(const QOCIResult); return q->bindValueType(i) & QSql::Out; }
+ inline bool isBinaryValue(int i) const
+ { Q_Q(const QOCIResult); return q->bindValueType(i) & QSql::Binary; }
+
+ void setCharset(dvoid* handle, ub4 type) const
+ {
+ int r = 0;
+ Q_ASSERT(handle);
+
+#ifdef OCI_ATTR_CHARSET_FORM
+ r = OCIAttrSet(handle,
+ type,
+ // this const cast is safe since OCI doesn't touch
+ // the charset.
+ const_cast<void *>(static_cast<const void *>(&qOraCharsetForm)),
+ 0,
+ OCI_ATTR_CHARSET_FORM,
+ //Strange Oracle bug: some Oracle servers crash the server process with non-zero error handle (mostly for 10g).
+ //So ignore the error message here.
+ 0);
+ #ifdef QOCI_DEBUG
+ if (r != 0)
+ qWarning("QOCIResultPrivate::setCharset: Couldn't set OCI_ATTR_CHARSET_FORM.");
+ #endif
+#endif
+
+ r = OCIAttrSet(handle,
+ type,
+ // this const cast is safe since OCI doesn't touch
+ // the charset.
+ const_cast<void *>(static_cast<const void *>(&qOraCharset)),
+ 0,
+ OCI_ATTR_CHARSET_ID,
+ err);
+ if (r != 0)
+ qOraWarning("QOCIResultPrivate::setCharsetI Couldn't set OCI_ATTR_CHARSET_ID: ", err);
+
+ }
+};
+
+void QOCIResultPrivate::setStatementAttributes()
+{
+ Q_ASSERT(sql);
+
+ int r = 0;
+
+ if (prefetchRows >= 0) {
+ r = OCIAttrSet(sql,
+ OCI_HTYPE_STMT,
+ &prefetchRows,
+ 0,
+ OCI_ATTR_PREFETCH_ROWS,
+ err);
+ if (r != 0)
+ qOraWarning("QOCIResultPrivate::setStatementAttributes:"
+ " Couldn't set OCI_ATTR_PREFETCH_ROWS: ", err);
+ }
+ if (prefetchMem >= 0) {
+ r = OCIAttrSet(sql,
+ OCI_HTYPE_STMT,
+ &prefetchMem,
+ 0,
+ OCI_ATTR_PREFETCH_MEMORY,
+ err);
+ if (r != 0)
+ qOraWarning("QOCIResultPrivate::setStatementAttributes:"
+ " Couldn't set OCI_ATTR_PREFETCH_MEMORY: ", err);
+ }
+}
+
+int QOCIResultPrivate::bindValue(OCIStmt *sql, OCIBind **hbnd, OCIError *err, int pos,
+ const QVariant &val, dvoid *indPtr, ub2 *tmpSize, QList<QByteArray> &tmpStorage)
+{
+ int r = OCI_SUCCESS;
+ void *data = const_cast<void *>(val.constData());
+
+ switch (val.type()) {
+ case QVariant::ByteArray:
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ isOutValue(pos)
+ ? const_cast<char *>(reinterpret_cast<QByteArray *>(data)->constData())
+ : reinterpret_cast<QByteArray *>(data)->data(),
+ reinterpret_cast<QByteArray *>(data)->size(),
+ SQLT_BIN, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ break;
+ case QVariant::Time:
+ case QVariant::Date:
+ case QVariant::DateTime: {
+ QByteArray ba = qMakeOraDate(val.toDateTime());
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ ba.data(),
+ ba.size(),
+ SQLT_DAT, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ tmpStorage.append(ba);
+ break; }
+ case QVariant::Int:
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ // if it's an out value, the data is already detached
+ // so the const cast is safe.
+ const_cast<void *>(data),
+ sizeof(int),
+ SQLT_INT, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ break;
+ case QVariant::UInt:
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ // if it's an out value, the data is already detached
+ // so the const cast is safe.
+ const_cast<void *>(data),
+ sizeof(uint),
+ SQLT_UIN, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ break;
+ case QVariant::LongLong:
+ {
+ QByteArray ba = qMakeOCINumber(val.toLongLong(), err);
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ ba.data(),
+ ba.size(),
+ SQLT_VNU, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ tmpStorage.append(ba);
+ break;
+ }
+ case QVariant::ULongLong:
+ {
+ QByteArray ba = qMakeOCINumber(val.toULongLong(), err);
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ ba.data(),
+ ba.size(),
+ SQLT_VNU, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ tmpStorage.append(ba);
+ break;
+ }
+ case QVariant::Double:
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ // if it's an out value, the data is already detached
+ // so the const cast is safe.
+ const_cast<void *>(data),
+ sizeof(double),
+ SQLT_FLT, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ break;
+ case QVariant::UserType:
+ if (val.canConvert<QOCIRowIdPointer>() && !isOutValue(pos)) {
+ // use a const pointer to prevent a detach
+ const QOCIRowIdPointer rptr = qvariant_cast<QOCIRowIdPointer>(val);
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ // it's an IN value, so const_cast is ok
+ const_cast<OCIRowid **>(&rptr->id),
+ -1,
+ SQLT_RDD, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ } else {
+ qWarning("Unknown bind variable");
+ r = OCI_ERROR;
+ }
+ break;
+ case QVariant::String: {
+ const QString s = val.toString();
+ if (isBinaryValue(pos)) {
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ const_cast<ushort *>(s.utf16()),
+ s.length() * sizeof(QChar),
+ SQLT_LNG, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ break;
+ } else if (!isOutValue(pos)) {
+ // don't detach the string
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ // safe since oracle doesn't touch OUT values
+ const_cast<ushort *>(s.utf16()),
+ (s.length() + 1) * sizeof(QChar),
+ SQLT_STR, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ if (r == OCI_SUCCESS)
+ setCharset(*hbnd, OCI_HTYPE_BIND);
+ break;
+ }
+ } // fall through for OUT values
+ default: {
+ const QString s = val.toString();
+ // create a deep-copy
+ QByteArray ba(reinterpret_cast<const char *>(s.utf16()), (s.length() + 1) * sizeof(QChar));
+ if (isOutValue(pos)) {
+ ba.reserve((s.capacity() + 1) * sizeof(QChar));
+ *tmpSize = ba.size();
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ ba.data(),
+ ba.capacity(),
+ SQLT_STR, indPtr, tmpSize, 0, 0, 0, OCI_DEFAULT);
+ } else {
+ r = OCIBindByPos(sql, hbnd, err,
+ pos + 1,
+ ba.data(),
+ ba.size(),
+ SQLT_STR, indPtr, 0, 0, 0, 0, OCI_DEFAULT);
+ }
+ if (r == OCI_SUCCESS)
+ setCharset(*hbnd, OCI_HTYPE_BIND);
+ tmpStorage.append(ba);
+ break;
+ } // default case
+ } // switch
+ if (r != OCI_SUCCESS)
+ qOraWarning("QOCIResultPrivate::bindValue:", err);
+ return r;
+}
+
+int QOCIResultPrivate::bindValues(QVector<QVariant> &values, IndicatorArray &indicators,
+ SizeArray &tmpSizes, QList<QByteArray> &tmpStorage)
+{
+ int r = OCI_SUCCESS;
+ for (int i = 0; i < values.count(); ++i) {
+ if (isOutValue(i))
+ values[i].detach();
+ const QVariant &val = values.at(i);
+
+ OCIBind * hbnd = 0; // Oracle handles these automatically
+ sb2 *indPtr = &indicators[i];
+ *indPtr = val.isNull() ? -1 : 0;
+
+ bindValue(sql, &hbnd, err, i, val, indPtr, &tmpSizes[i], tmpStorage);
+ }
+ return r;
+}
+
+// will assign out value and remove its temp storage.
+static void qOraOutValue(QVariant &value, QList<QByteArray> &storage, OCIError* err)
+{
+ switch (value.type()) {
+ case QVariant::Time:
+ value = qMakeDate(storage.takeFirst()).time();
+ break;
+ case QVariant::Date:
+ value = qMakeDate(storage.takeFirst()).date();
+ break;
+ case QVariant::DateTime:
+ value = qMakeDate(storage.takeFirst());
+ break;
+ case QVariant::LongLong:
+ value = qMakeLongLong(storage.takeFirst(), err);
+ break;
+ case QVariant::ULongLong:
+ value = qMakeULongLong(storage.takeFirst(), err);
+ break;
+ case QVariant::String:
+ value = QString(
+ reinterpret_cast<const QChar *>(storage.takeFirst().constData()));
+ break;
+ default:
+ break; //nothing
+ }
+}
+
+void QOCIResultPrivate::outValues(QVector<QVariant> &values, IndicatorArray &indicators,
+ QList<QByteArray> &tmpStorage)
+{
+ for (int i = 0; i < values.count(); ++i) {
+
+ if (!isOutValue(i))
+ continue;
+
+ qOraOutValue(values[i], tmpStorage, err);
+
+ QVariant::Type typ = values.at(i).type();
+ if (indicators[i] == -1) // NULL
+ values[i] = QVariant(typ);
+ else
+ values[i] = QVariant(typ, values.at(i).constData());
+ }
+}
+
+
+QOCIDriverPrivate::QOCIDriverPrivate()
+ : QSqlDriverPrivate(), env(0), svc(0), srvhp(0), authp(0), err(0), transaction(false),
+ serverVersion(-1), prefetchRows(-1), prefetchMem(QOCI_PREFETCH_MEM)
+{
+ dbmsType = QSqlDriver::Oracle;
+}
+
+void QOCIDriverPrivate::allocErrorHandle()
+{
+ int r = OCIHandleAlloc(env,
+ reinterpret_cast<void **>(&err),
+ OCI_HTYPE_ERROR,
+ 0,
+ 0);
+ if (r != 0)
+ qWarning("QOCIDriver: unable to allocate error handle");
+}
+
+struct OraFieldInfo
+{
+ QString name;
+ QVariant::Type type;
+ ub1 oraIsNull;
+ ub4 oraType;
+ sb1 oraScale;
+ ub4 oraLength; // size in bytes
+ ub4 oraFieldLength; // amount of characters
+ sb2 oraPrecision;
+};
+
+QString qOraWarn(OCIError *err, int *errorCode)
+{
+ sb4 errcode;
+ text errbuf[1024];
+ errbuf[0] = 0;
+ errbuf[1] = 0;
+
+ OCIErrorGet(err,
+ 1,
+ 0,
+ &errcode,
+ errbuf,
+ sizeof(errbuf),
+ OCI_HTYPE_ERROR);
+ if (errorCode)
+ *errorCode = errcode;
+ return QString(reinterpret_cast<const QChar *>(errbuf));
+}
+
+void qOraWarning(const char* msg, OCIError *err)
+{
+#ifdef QOCI_DEBUG
+ qWarning("%s %s", msg, qPrintable(qOraWarn(err)));
+#else
+ Q_UNUSED(msg);
+ Q_UNUSED(err);
+#endif
+}
+
+static int qOraErrorNumber(OCIError *err)
+{
+ sb4 errcode;
+ OCIErrorGet(err,
+ 1,
+ 0,
+ &errcode,
+ 0,
+ 0,
+ OCI_HTYPE_ERROR);
+ return errcode;
+}
+
+QSqlError qMakeError(const QString& errString, QSqlError::ErrorType type, OCIError *err)
+{
+ int errorCode = 0;
+ const QString oraErrorString = qOraWarn(err, &errorCode);
+ return QSqlError(errString, oraErrorString, type, errorCode);
+}
+
+QVariant::Type qDecodeOCIType(const QString& ocitype, QSql::NumericalPrecisionPolicy precisionPolicy)
+{
+ QVariant::Type type = QVariant::Invalid;
+ if (ocitype == QLatin1String("VARCHAR2") || ocitype == QLatin1String("VARCHAR")
+ || ocitype.startsWith(QLatin1String("INTERVAL"))
+ || ocitype == QLatin1String("CHAR") || ocitype == QLatin1String("NVARCHAR2")
+ || ocitype == QLatin1String("NCHAR"))
+ type = QVariant::String;
+ else if (ocitype == QLatin1String("NUMBER")
+ || ocitype == QLatin1String("FLOAT")
+ || ocitype == QLatin1String("BINARY_FLOAT")
+ || ocitype == QLatin1String("BINARY_DOUBLE")) {
+ switch(precisionPolicy) {
+ case QSql::LowPrecisionInt32:
+ type = QVariant::Int;
+ break;
+ case QSql::LowPrecisionInt64:
+ type = QVariant::LongLong;
+ break;
+ case QSql::LowPrecisionDouble:
+ type = QVariant::Double;
+ break;
+ case QSql::HighPrecision:
+ default:
+ type = QVariant::String;
+ break;
+ }
+ }
+ else if (ocitype == QLatin1String("LONG") || ocitype == QLatin1String("NCLOB")
+ || ocitype == QLatin1String("CLOB"))
+ type = QVariant::ByteArray;
+ else if (ocitype == QLatin1String("RAW") || ocitype == QLatin1String("LONG RAW")
+ || ocitype == QLatin1String("ROWID") || ocitype == QLatin1String("BLOB")
+ || ocitype == QLatin1String("CFILE") || ocitype == QLatin1String("BFILE"))
+ type = QVariant::ByteArray;
+ else if (ocitype == QLatin1String("DATE") || ocitype.startsWith(QLatin1String("TIME")))
+ type = QVariant::DateTime;
+ else if (ocitype == QLatin1String("UNDEFINED"))
+ type = QVariant::Invalid;
+ if (type == QVariant::Invalid)
+ qWarning("qDecodeOCIType: unknown type: %s", ocitype.toLocal8Bit().constData());
+ return type;
+}
+
+QVariant::Type qDecodeOCIType(int ocitype, QSql::NumericalPrecisionPolicy precisionPolicy)
+{
+ QVariant::Type type = QVariant::Invalid;
+ switch (ocitype) {
+ case SQLT_STR:
+ case SQLT_VST:
+ case SQLT_CHR:
+ case SQLT_AFC:
+ case SQLT_VCS:
+ case SQLT_AVC:
+ case SQLT_RDD:
+ case SQLT_LNG:
+#ifdef SQLT_INTERVAL_YM
+ case SQLT_INTERVAL_YM:
+#endif
+#ifdef SQLT_INTERVAL_DS
+ case SQLT_INTERVAL_DS:
+#endif
+ type = QVariant::String;
+ break;
+ case SQLT_INT:
+ type = QVariant::Int;
+ break;
+ case SQLT_FLT:
+ case SQLT_NUM:
+ case SQLT_VNU:
+ case SQLT_UIN:
+ switch(precisionPolicy) {
+ case QSql::LowPrecisionInt32:
+ type = QVariant::Int;
+ break;
+ case QSql::LowPrecisionInt64:
+ type = QVariant::LongLong;
+ break;
+ case QSql::LowPrecisionDouble:
+ type = QVariant::Double;
+ break;
+ case QSql::HighPrecision:
+ default:
+ type = QVariant::String;
+ break;
+ }
+ break;
+ case SQLT_VBI:
+ case SQLT_BIN:
+ case SQLT_LBI:
+ case SQLT_LVC:
+ case SQLT_LVB:
+ case SQLT_BLOB:
+ case SQLT_CLOB:
+ case SQLT_FILE:
+ case SQLT_NTY:
+ case SQLT_REF:
+ case SQLT_RID:
+ type = QVariant::ByteArray;
+ break;
+ case SQLT_DAT:
+ case SQLT_ODT:
+#ifdef SQLT_TIMESTAMP
+ case SQLT_TIMESTAMP:
+ case SQLT_TIMESTAMP_TZ:
+ case SQLT_TIMESTAMP_LTZ:
+#endif
+ type = QVariant::DateTime;
+ break;
+ default:
+ type = QVariant::Invalid;
+ qWarning("qDecodeOCIType: unknown OCI datatype: %d", ocitype);
+ break;
+ }
+ return type;
+}
+
+static QSqlField qFromOraInf(const OraFieldInfo &ofi)
+{
+ QSqlField f(ofi.name, ofi.type);
+ f.setRequired(ofi.oraIsNull == 0);
+
+ if (ofi.type == QVariant::String && ofi.oraType != SQLT_NUM && ofi.oraType != SQLT_VNU)
+ f.setLength(ofi.oraFieldLength);
+ else
+ f.setLength(ofi.oraPrecision == 0 ? 38 : int(ofi.oraPrecision));
+
+ f.setPrecision(ofi.oraScale);
+ f.setSqlType(int(ofi.oraType));
+ return f;
+}
+
+/*!
+ \internal
+
+ Convert QDateTime to the internal Oracle DATE format NB!
+ It does not handle BCE dates.
+*/
+QByteArray qMakeOraDate(const QDateTime& dt)
+{
+ QByteArray ba;
+ ba.resize(7);
+ int year = dt.date().year();
+ ba[0]= (year / 100) + 100; // century
+ ba[1]= (year % 100) + 100; // year
+ ba[2]= dt.date().month();
+ ba[3]= dt.date().day();
+ ba[4]= dt.time().hour() + 1;
+ ba[5]= dt.time().minute() + 1;
+ ba[6]= dt.time().second() + 1;
+ return ba;
+}
+
+/*!
+ \internal
+
+ Convert qlonglong to the internal Oracle OCINumber format.
+ */
+QByteArray qMakeOCINumber(const qlonglong& ll, OCIError* err)
+{
+ QByteArray ba(sizeof(OCINumber), 0);
+
+ OCINumberFromInt(err,
+ &ll,
+ sizeof(qlonglong),
+ OCI_NUMBER_SIGNED,
+ reinterpret_cast<OCINumber*>(ba.data()));
+ return ba;
+}
+
+/*!
+ \internal
+
+ Convert qulonglong to the internal Oracle OCINumber format.
+ */
+QByteArray qMakeOCINumber(const qulonglong& ull, OCIError* err)
+{
+ QByteArray ba(sizeof(OCINumber), 0);
+
+ OCINumberFromInt(err,
+ &ull,
+ sizeof(qlonglong),
+ OCI_NUMBER_UNSIGNED,
+ reinterpret_cast<OCINumber*>(ba.data()));
+ return ba;
+}
+
+qlonglong qMakeLongLong(const char* ociNumber, OCIError* err)
+{
+ qlonglong qll = 0;
+ OCINumberToInt(err, reinterpret_cast<const OCINumber *>(ociNumber), sizeof(qlonglong),
+ OCI_NUMBER_SIGNED, &qll);
+ return qll;
+}
+
+qulonglong qMakeULongLong(const char* ociNumber, OCIError* err)
+{
+ qulonglong qull = 0;
+ OCINumberToInt(err, reinterpret_cast<const OCINumber *>(ociNumber), sizeof(qulonglong),
+ OCI_NUMBER_UNSIGNED, &qull);
+ return qull;
+}
+
+QDateTime qMakeDate(const char* oraDate)
+{
+ int century = uchar(oraDate[0]);
+ if(century >= 100){
+ int year = uchar(oraDate[1]);
+ year = ((century-100)*100) + (year-100);
+ int month = oraDate[2];
+ int day = oraDate[3];
+ int hour = oraDate[4] - 1;
+ int min = oraDate[5] - 1;
+ int sec = oraDate[6] - 1;
+ return QDateTime(QDate(year,month,day), QTime(hour,min,sec));
+ }
+ return QDateTime();
+}
+
+class QOCICols
+{
+public:
+ QOCICols(int size, QOCIResultPrivate* dp);
+ ~QOCICols();
+ int readPiecewise(QVector<QVariant> &values, int index = 0);
+ int readLOBs(QVector<QVariant> &values, int index = 0);
+ int fieldFromDefine(OCIDefine* d);
+ void getValues(QVector<QVariant> &v, int index);
+ inline int size() { return fieldInf.size(); }
+ static bool execBatch(QOCIResultPrivate *d, QVector<QVariant> &boundValues, bool arrayBind);
+
+ QSqlRecord rec;
+
+private:
+ char* create(int position, int size);
+ OCILobLocator ** createLobLocator(int position, OCIEnv* env);
+ OraFieldInfo qMakeOraField(const QOCIResultPrivate* p, OCIParam* param) const;
+
+ class OraFieldInf
+ {
+ public:
+ OraFieldInf(): data(0), len(0), ind(0), typ(QVariant::Invalid), oraType(0), def(0), lob(0)
+ {}
+ ~OraFieldInf();
+ char *data;
+ int len;
+ sb2 ind;
+ QVariant::Type typ;
+ ub4 oraType;
+ OCIDefine *def;
+ OCILobLocator *lob;
+ };
+
+ QVector<OraFieldInf> fieldInf;
+ const QOCIResultPrivate *const d;
+};
+
+QOCICols::OraFieldInf::~OraFieldInf()
+{
+ delete [] data;
+ if (lob) {
+ int r = OCIDescriptorFree(lob, OCI_DTYPE_LOB);
+ if (r != 0)
+ qWarning("QOCICols: Cannot free LOB descriptor");
+ }
+}
+
+QOCICols::QOCICols(int size, QOCIResultPrivate* dp)
+ : fieldInf(size), d(dp)
+{
+ ub4 dataSize = 0;
+ OCIDefine* dfn = 0;
+ int r;
+
+ OCIParam* param = 0;
+ sb4 parmStatus = 0;
+ ub4 count = 1;
+ int idx = 0;
+ parmStatus = OCIParamGet(d->sql,
+ OCI_HTYPE_STMT,
+ d->err,
+ reinterpret_cast<void **>(&param),
+ count);
+
+ while (parmStatus == OCI_SUCCESS) {
+ OraFieldInfo ofi = qMakeOraField(d, param);
+ if (ofi.oraType == SQLT_RDD)
+ dataSize = 50;
+#ifdef SQLT_INTERVAL_YM
+#ifdef SQLT_INTERVAL_DS
+ else if (ofi.oraType == SQLT_INTERVAL_YM || ofi.oraType == SQLT_INTERVAL_DS)
+ // since we are binding interval datatype as string,
+ // we are not interested in the number of bytes but characters.
+ dataSize = 50; // magic number
+#endif //SQLT_INTERVAL_DS
+#endif //SQLT_INTERVAL_YM
+ else if (ofi.oraType == SQLT_NUM || ofi.oraType == SQLT_VNU){
+ if (ofi.oraPrecision > 0)
+ dataSize = (ofi.oraPrecision + 1) * sizeof(utext);
+ else
+ dataSize = (38 + 1) * sizeof(utext);
+ }
+ else
+ dataSize = ofi.oraLength;
+
+ fieldInf[idx].typ = ofi.type;
+ fieldInf[idx].oraType = ofi.oraType;
+ rec.append(qFromOraInf(ofi));
+
+ switch (ofi.type) {
+ case QVariant::DateTime:
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ create(idx, dataSize+1),
+ dataSize+1,
+ SQLT_DAT,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DEFAULT);
+ break;
+ case QVariant::Double:
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ create(idx, sizeof(double) - 1),
+ sizeof(double),
+ SQLT_FLT,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DEFAULT);
+ break;
+ case QVariant::Int:
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ create(idx, sizeof(qint32) - 1),
+ sizeof(qint32),
+ SQLT_INT,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DEFAULT);
+ break;
+ case QVariant::LongLong:
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ create(idx, sizeof(OCINumber)),
+ sizeof(OCINumber),
+ SQLT_VNU,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DEFAULT);
+ break;
+ case QVariant::ByteArray:
+ // RAW and LONG RAW fields can't be bound to LOB locators
+ if (ofi.oraType == SQLT_BIN) {
+// qDebug("binding SQLT_BIN");
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ create(idx, dataSize),
+ dataSize,
+ SQLT_BIN,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DYNAMIC_FETCH);
+ } else if (ofi.oraType == SQLT_LBI) {
+// qDebug("binding SQLT_LBI");
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ 0,
+ SB4MAXVAL,
+ SQLT_LBI,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DYNAMIC_FETCH);
+ } else if (ofi.oraType == SQLT_CLOB) {
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ createLobLocator(idx, d->env),
+ -1,
+ SQLT_CLOB,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DEFAULT);
+ } else {
+// qDebug("binding SQLT_BLOB");
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ createLobLocator(idx, d->env),
+ -1,
+ SQLT_BLOB,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DEFAULT);
+ }
+ break;
+ case QVariant::String:
+ if (ofi.oraType == SQLT_LNG) {
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ 0,
+ SB4MAXVAL,
+ SQLT_LNG,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DYNAMIC_FETCH);
+ } else {
+ dataSize += dataSize + sizeof(QChar);
+ //qDebug("OCIDefineByPosStr(%d): %d", count, dataSize);
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ create(idx, dataSize),
+ dataSize,
+ SQLT_STR,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DEFAULT);
+ if (r == 0)
+ d->setCharset(dfn, OCI_HTYPE_DEFINE);
+ }
+ break;
+ default:
+ // this should make enough space even with character encoding
+ dataSize = (dataSize + 1) * sizeof(utext) ;
+ //qDebug("OCIDefineByPosDef(%d): %d", count, dataSize);
+ r = OCIDefineByPos(d->sql,
+ &dfn,
+ d->err,
+ count,
+ create(idx, dataSize),
+ dataSize+1,
+ SQLT_STR,
+ &(fieldInf[idx].ind),
+ 0, 0, OCI_DEFAULT);
+ break;
+ }
+ if (r != 0)
+ qOraWarning("QOCICols::bind:", d->err);
+ fieldInf[idx].def = dfn;
+ ++count;
+ ++idx;
+ parmStatus = OCIParamGet(d->sql,
+ OCI_HTYPE_STMT,
+ d->err,
+ reinterpret_cast<void **>(&param),
+ count);
+ }
+}
+
+QOCICols::~QOCICols()
+{
+}
+
+char* QOCICols::create(int position, int size)
+{
+ char* c = new char[size+1];
+ // Oracle may not fill fixed width fields
+ memset(c, 0, size+1);
+ fieldInf[position].data = c;
+ fieldInf[position].len = size;
+ return c;
+}
+
+OCILobLocator **QOCICols::createLobLocator(int position, OCIEnv* env)
+{
+ OCILobLocator *& lob = fieldInf[position].lob;
+ int r = OCIDescriptorAlloc(env,
+ reinterpret_cast<void **>(&lob),
+ OCI_DTYPE_LOB,
+ 0,
+ 0);
+ if (r != 0) {
+ qWarning("QOCICols: Cannot create LOB locator");
+ lob = 0;
+ }
+ return &lob;
+}
+
+int QOCICols::readPiecewise(QVector<QVariant> &values, int index)
+{
+ OCIDefine* dfn;
+ ub4 typep;
+ ub1 in_outp;
+ ub4 iterp;
+ ub4 idxp;
+ ub1 piecep;
+ sword status;
+ text col [QOCI_DYNAMIC_CHUNK_SIZE+1];
+ int fieldNum = -1;
+ int r = 0;
+ bool nullField;
+
+ do {
+ r = OCIStmtGetPieceInfo(d->sql, d->err, reinterpret_cast<void **>(&dfn), &typep,
+ &in_outp, &iterp, &idxp, &piecep);
+ if (r != OCI_SUCCESS)
+ qOraWarning("OCIResultPrivate::readPiecewise: unable to get piece info:", d->err);
+ fieldNum = fieldFromDefine(dfn);
+ bool isStringField = fieldInf.at(fieldNum).oraType == SQLT_LNG;
+ ub4 chunkSize = QOCI_DYNAMIC_CHUNK_SIZE;
+ nullField = false;
+ r = OCIStmtSetPieceInfo(dfn, OCI_HTYPE_DEFINE,
+ d->err, col,
+ &chunkSize, piecep, NULL, NULL);
+ if (r != OCI_SUCCESS)
+ qOraWarning("OCIResultPrivate::readPiecewise: unable to set piece info:", d->err);
+ status = OCIStmtFetch (d->sql, d->err, 1, OCI_FETCH_NEXT, OCI_DEFAULT);
+ if (status == -1) {
+ sb4 errcode;
+ OCIErrorGet(d->err, 1, 0, &errcode, 0, 0,OCI_HTYPE_ERROR);
+ switch (errcode) {
+ case 1405: /* NULL */
+ nullField = true;
+ break;
+ default:
+ qOraWarning("OCIResultPrivate::readPiecewise: unable to fetch next:", d->err);
+ break;
+ }
+ }
+ if (status == OCI_NO_DATA)
+ break;
+ if (nullField || !chunkSize) {
+ fieldInf[fieldNum].ind = -1;
+ } else {
+ if (isStringField) {
+ QString str = values.at(fieldNum + index).toString();
+ str += QString(reinterpret_cast<const QChar *>(col), chunkSize / 2);
+ values[fieldNum + index] = str;
+ fieldInf[fieldNum].ind = 0;
+ } else {
+ QByteArray ba = values.at(fieldNum + index).toByteArray();
+ int sz = ba.size();
+ ba.resize(sz + chunkSize);
+ memcpy(ba.data() + sz, reinterpret_cast<char *>(col), chunkSize);
+ values[fieldNum + index] = ba;
+ fieldInf[fieldNum].ind = 0;
+ }
+ }
+ } while (status == OCI_SUCCESS_WITH_INFO || status == OCI_NEED_DATA);
+ return r;
+}
+
+OraFieldInfo QOCICols::qMakeOraField(const QOCIResultPrivate* p, OCIParam* param) const
+{
+ OraFieldInfo ofi;
+ ub2 colType(0);
+ text *colName = 0;
+ ub4 colNameLen(0);
+ sb1 colScale(0);
+ ub2 colLength(0);
+ ub2 colFieldLength(0);
+ sb2 colPrecision(0);
+ ub1 colIsNull(0);
+ int r(0);
+ QVariant::Type type(QVariant::Invalid);
+
+ r = OCIAttrGet(param,
+ OCI_DTYPE_PARAM,
+ &colType,
+ 0,
+ OCI_ATTR_DATA_TYPE,
+ p->err);
+ if (r != 0)
+ qOraWarning("qMakeOraField:", p->err);
+
+ r = OCIAttrGet(param,
+ OCI_DTYPE_PARAM,
+ &colName,
+ &colNameLen,
+ OCI_ATTR_NAME,
+ p->err);
+ if (r != 0)
+ qOraWarning("qMakeOraField:", p->err);
+
+ r = OCIAttrGet(param,
+ OCI_DTYPE_PARAM,
+ &colLength,
+ 0,
+ OCI_ATTR_DATA_SIZE, /* in bytes */
+ p->err);
+ if (r != 0)
+ qOraWarning("qMakeOraField:", p->err);
+
+#ifdef OCI_ATTR_CHAR_SIZE
+ r = OCIAttrGet(param,
+ OCI_DTYPE_PARAM,
+ &colFieldLength,
+ 0,
+ OCI_ATTR_CHAR_SIZE,
+ p->err);
+ if (r != 0)
+ qOraWarning("qMakeOraField:", p->err);
+#else
+ // for Oracle8.
+ colFieldLength = colLength;
+#endif
+
+ r = OCIAttrGet(param,
+ OCI_DTYPE_PARAM,
+ &colPrecision,
+ 0,
+ OCI_ATTR_PRECISION,
+ p->err);
+ if (r != 0)
+ qOraWarning("qMakeOraField:", p->err);
+
+ r = OCIAttrGet(param,
+ OCI_DTYPE_PARAM,
+ &colScale,
+ 0,
+ OCI_ATTR_SCALE,
+ p->err);
+ if (r != 0)
+ qOraWarning("qMakeOraField:", p->err);
+ r = OCIAttrGet(param,
+ OCI_DTYPE_PARAM,
+ &colType,
+ 0,
+ OCI_ATTR_DATA_TYPE,
+ p->err);
+ if (r != 0)
+ qOraWarning("qMakeOraField:", p->err);
+ r = OCIAttrGet(param,
+ OCI_DTYPE_PARAM,
+ &colIsNull,
+ 0,
+ OCI_ATTR_IS_NULL,
+ p->err);
+ if (r != 0)
+ qOraWarning("qMakeOraField:", p->err);
+
+ type = qDecodeOCIType(colType, p->q_func()->numericalPrecisionPolicy());
+
+ if (type == QVariant::Int) {
+ if (colLength == 22 && colPrecision == 0 && colScale == 0)
+ type = QVariant::String;
+ if (colScale > 0)
+ type = QVariant::String;
+ }
+
+ // bind as double if the precision policy asks for it
+ if (((colType == SQLT_FLT) || (colType == SQLT_NUM))
+ && (p->q_func()->numericalPrecisionPolicy() == QSql::LowPrecisionDouble)) {
+ type = QVariant::Double;
+ }
+
+ // bind as int32 or int64 if the precision policy asks for it
+ if ((colType == SQLT_NUM) || (colType == SQLT_VNU) || (colType == SQLT_UIN)
+ || (colType == SQLT_INT)) {
+ if (p->q_func()->numericalPrecisionPolicy() == QSql::LowPrecisionInt64)
+ type = QVariant::LongLong;
+ else if (p->q_func()->numericalPrecisionPolicy() == QSql::LowPrecisionInt32)
+ type = QVariant::Int;
+ }
+
+ if (colType == SQLT_BLOB)
+ colLength = 0;
+
+ // colNameLen is length in bytes
+ ofi.name = QString(reinterpret_cast<const QChar*>(colName), colNameLen / 2);
+ ofi.type = type;
+ ofi.oraType = colType;
+ ofi.oraFieldLength = colFieldLength;
+ ofi.oraLength = colLength;
+ ofi.oraScale = colScale;
+ ofi.oraPrecision = colPrecision;
+ ofi.oraIsNull = colIsNull;
+
+ return ofi;
+}
+
+struct QOCIBatchColumn
+{
+ inline QOCIBatchColumn()
+ : bindh(0), bindAs(0), maxLen(0), recordCount(0),
+ data(0), lengths(0), indicators(0), maxarr_len(0), curelep(0) {}
+
+ OCIBind* bindh;
+ ub2 bindAs;
+ ub4 maxLen;
+ ub4 recordCount;
+ char* data;
+ ub2* lengths;
+ sb2* indicators;
+ ub4 maxarr_len;
+ ub4 curelep;
+};
+
+struct QOCIBatchCleanupHandler
+{
+ inline QOCIBatchCleanupHandler(QVector<QOCIBatchColumn> &columns)
+ : col(columns) {}
+
+ ~QOCIBatchCleanupHandler()
+ {
+ // deleting storage, length and indicator arrays
+ for ( int j = 0; j < col.count(); ++j){
+ delete[] col[j].lengths;
+ delete[] col[j].indicators;
+ delete[] col[j].data;
+ }
+ }
+
+ QVector<QOCIBatchColumn> &col;
+};
+
+bool QOCICols::execBatch(QOCIResultPrivate *d, QVector<QVariant> &boundValues, bool arrayBind)
+{
+ int columnCount = boundValues.count();
+ if (boundValues.isEmpty() || columnCount == 0)
+ return false;
+
+#ifdef QOCI_DEBUG
+ qDebug() << "columnCount:" << columnCount << boundValues;
+#endif
+
+ int i;
+ sword r;
+
+ QVarLengthArray<QVariant::Type> fieldTypes;
+ for (i = 0; i < columnCount; ++i) {
+ QVariant::Type tp = boundValues.at(i).type();
+ fieldTypes.append(tp == QVariant::List ? boundValues.at(i).toList().value(0).type()
+ : tp);
+ }
+
+ QList<QByteArray> tmpStorage;
+ SizeArray tmpSizes(columnCount);
+ QVector<QOCIBatchColumn> columns(columnCount);
+ QOCIBatchCleanupHandler cleaner(columns);
+
+ // figuring out buffer sizes
+ for (i = 0; i < columnCount; ++i) {
+
+ if (boundValues.at(i).type() != QVariant::List) {
+
+ // not a list - create a deep-copy of the single value
+ QOCIBatchColumn &singleCol = columns[i];
+ singleCol.indicators = new sb2[1];
+ *singleCol.indicators = boundValues.at(i).isNull() ? -1 : 0;
+
+ r = d->bindValue(d->sql, &singleCol.bindh, d->err, i,
+ boundValues.at(i), singleCol.indicators, &tmpSizes[i], tmpStorage);
+
+ if (r != OCI_SUCCESS && r != OCI_SUCCESS_WITH_INFO) {
+ qOraWarning("QOCIPrivate::execBatch: unable to bind column:", d->err);
+ d->q_func()->setLastError(qMakeError(QCoreApplication::translate("QOCIResult",
+ "Unable to bind column for batch execute"),
+ QSqlError::StatementError, d->err));
+ return false;
+ }
+ continue;
+ }
+
+ QOCIBatchColumn &col = columns[i];
+ col.recordCount = boundValues.at(i).toList().count();
+
+ col.lengths = new ub2[col.recordCount];
+ col.indicators = new sb2[col.recordCount];
+ col.maxarr_len = col.recordCount;
+ col.curelep = col.recordCount;
+
+ switch (fieldTypes[i]) {
+ case QVariant::Time:
+ case QVariant::Date:
+ case QVariant::DateTime:
+ col.bindAs = SQLT_DAT;
+ col.maxLen = 7;
+ break;
+
+ case QVariant::Int:
+ col.bindAs = SQLT_INT;
+ col.maxLen = sizeof(int);
+ break;
+
+ case QVariant::UInt:
+ col.bindAs = SQLT_UIN;
+ col.maxLen = sizeof(uint);
+ break;
+
+ case QVariant::LongLong:
+ col.bindAs = SQLT_VNU;
+ col.maxLen = sizeof(OCINumber);
+ break;
+
+ case QVariant::ULongLong:
+ col.bindAs = SQLT_VNU;
+ col.maxLen = sizeof(OCINumber);
+ break;
+
+ case QVariant::Double:
+ col.bindAs = SQLT_FLT;
+ col.maxLen = sizeof(double);
+ break;
+
+ case QVariant::UserType:
+ col.bindAs = SQLT_RDD;
+ col.maxLen = sizeof(OCIRowid*);
+ break;
+
+ case QVariant::String: {
+ col.bindAs = SQLT_STR;
+ for (uint j = 0; j < col.recordCount; ++j) {
+ uint len;
+ if(d->isOutValue(i))
+ len = boundValues.at(i).toList().at(j).toString().capacity() + 1;
+ else
+ len = boundValues.at(i).toList().at(j).toString().length() + 1;
+ if (len > col.maxLen)
+ col.maxLen = len;
+ }
+ col.maxLen *= sizeof(QChar);
+ break; }
+
+ case QVariant::ByteArray:
+ default: {
+ col.bindAs = SQLT_LBI;
+ for (uint j = 0; j < col.recordCount; ++j) {
+ if(d->isOutValue(i))
+ col.lengths[j] = boundValues.at(i).toList().at(j).toByteArray().capacity();
+ else
+ col.lengths[j] = boundValues.at(i).toList().at(j).toByteArray().size();
+ if (col.lengths[j] > col.maxLen)
+ col.maxLen = col.lengths[j];
+ }
+ break; }
+ }
+
+ col.data = new char[col.maxLen * col.recordCount];
+ memset(col.data, 0, col.maxLen * col.recordCount);
+
+ // we may now populate column with data
+ for (uint row = 0; row < col.recordCount; ++row) {
+ const QVariant &val = boundValues.at(i).toList().at(row);
+
+ if (val.isNull()){
+ columns[i].indicators[row] = -1;
+ columns[i].lengths[row] = 0;
+ } else {
+ columns[i].indicators[row] = 0;
+ char *dataPtr = columns[i].data + (columns[i].maxLen * row);
+ switch (fieldTypes[i]) {
+ case QVariant::Time:
+ case QVariant::Date:
+ case QVariant::DateTime:{
+ columns[i].lengths[row] = columns[i].maxLen;
+ const QByteArray ba = qMakeOraDate(val.toDateTime());
+ Q_ASSERT(ba.size() == int(columns[i].maxLen));
+ memcpy(dataPtr, ba.constData(), columns[i].maxLen);
+ break;
+ }
+ case QVariant::Int:
+ columns[i].lengths[row] = columns[i].maxLen;
+ *reinterpret_cast<int*>(dataPtr) = val.toInt();
+ break;
+
+ case QVariant::UInt:
+ columns[i].lengths[row] = columns[i].maxLen;
+ *reinterpret_cast<uint*>(dataPtr) = val.toUInt();
+ break;
+
+ case QVariant::LongLong:
+ {
+ columns[i].lengths[row] = columns[i].maxLen;
+ const QByteArray ba = qMakeOCINumber(val.toLongLong(), d->err);
+ Q_ASSERT(ba.size() == int(columns[i].maxLen));
+ memcpy(dataPtr, ba.constData(), columns[i].maxLen);
+ break;
+ }
+ case QVariant::ULongLong:
+ {
+ columns[i].lengths[row] = columns[i].maxLen;
+ const QByteArray ba = qMakeOCINumber(val.toULongLong(), d->err);
+ Q_ASSERT(ba.size() == int(columns[i].maxLen));
+ memcpy(dataPtr, ba.constData(), columns[i].maxLen);
+ break;
+ }
+ case QVariant::Double:
+ columns[i].lengths[row] = columns[i].maxLen;
+ *reinterpret_cast<double*>(dataPtr) = val.toDouble();
+ break;
+
+ case QVariant::String: {
+ const QString s = val.toString();
+ columns[i].lengths[row] = (s.length() + 1) * sizeof(QChar);
+ memcpy(dataPtr, s.utf16(), columns[i].lengths[row]);
+ break;
+ }
+ case QVariant::UserType:
+ if (val.canConvert<QOCIRowIdPointer>()) {
+ const QOCIRowIdPointer rptr = qvariant_cast<QOCIRowIdPointer>(val);
+ *reinterpret_cast<OCIRowid**>(dataPtr) = rptr->id;
+ columns[i].lengths[row] = 0;
+ break;
+ }
+ case QVariant::ByteArray:
+ default: {
+ const QByteArray ba = val.toByteArray();
+ columns[i].lengths[row] = ba.size();
+ memcpy(dataPtr, ba.constData(), ba.size());
+ break;
+ }
+ }
+ }
+ }
+
+ QOCIBatchColumn &bindColumn = columns[i];
+
+#ifdef QOCI_DEBUG
+ qDebug("OCIBindByPos(%p, %p, %p, %d, %p, %d, %d, %p, %p, 0, %d, %p, OCI_DEFAULT)",
+ d->sql, &bindColumn.bindh, d->err, i + 1, bindColumn.data,
+ bindColumn.maxLen, bindColumn.bindAs, bindColumn.indicators, bindColumn.lengths,
+ arrayBind ? bindColumn.maxarr_len : 0, arrayBind ? &bindColumn.curelep : 0);
+
+ for (int ii = 0; ii < (int)bindColumn.recordCount; ++ii) {
+ qDebug(" record %d: indicator %d, length %d", ii, bindColumn.indicators[ii],
+ bindColumn.lengths[ii]);
+ }
+#endif
+
+
+ // binding the column
+ r = OCIBindByPos(
+ d->sql, &bindColumn.bindh, d->err, i + 1,
+ bindColumn.data,
+ bindColumn.maxLen,
+ bindColumn.bindAs,
+ bindColumn.indicators,
+ bindColumn.lengths,
+ 0,
+ arrayBind ? bindColumn.maxarr_len : 0,
+ arrayBind ? &bindColumn.curelep : 0,
+ OCI_DEFAULT);
+
+#ifdef QOCI_DEBUG
+ qDebug("After OCIBindByPos: r = %d, bindh = %p", r, bindColumn.bindh);
+#endif
+
+ if (r != OCI_SUCCESS && r != OCI_SUCCESS_WITH_INFO) {
+ qOraWarning("QOCIPrivate::execBatch: unable to bind column:", d->err);
+ d->q_func()->setLastError(qMakeError(QCoreApplication::translate("QOCIResult",
+ "Unable to bind column for batch execute"),
+ QSqlError::StatementError, d->err));
+ return false;
+ }
+
+ r = OCIBindArrayOfStruct (
+ columns[i].bindh, d->err,
+ columns[i].maxLen,
+ sizeof(columns[i].indicators[0]),
+ sizeof(columns[i].lengths[0]),
+ 0);
+
+ if (r != OCI_SUCCESS && r != OCI_SUCCESS_WITH_INFO) {
+ qOraWarning("QOCIPrivate::execBatch: unable to bind column:", d->err);
+ d->q_func()->setLastError(qMakeError(QCoreApplication::translate("QOCIResult",
+ "Unable to bind column for batch execute"),
+ QSqlError::StatementError, d->err));
+ return false;
+ }
+ }
+
+ //finaly we can execute
+ r = OCIStmtExecute(d->svc, d->sql, d->err,
+ arrayBind ? 1 : columns[0].recordCount,
+ 0, NULL, NULL,
+ d->transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS);
+
+ if (r != OCI_SUCCESS && r != OCI_SUCCESS_WITH_INFO) {
+ qOraWarning("QOCIPrivate::execBatch: unable to execute batch statement:", d->err);
+ d->q_func()->setLastError(qMakeError(QCoreApplication::translate("QOCIResult",
+ "Unable to execute batch statement"),
+ QSqlError::StatementError, d->err));
+ return false;
+ }
+
+ // for out parameters we copy data back to value vector
+ for (i = 0; i < columnCount; ++i) {
+
+ if (!d->isOutValue(i))
+ continue;
+
+ QVariant::Type tp = boundValues.at(i).type();
+ if (tp != QVariant::List) {
+ qOraOutValue(boundValues[i], tmpStorage, d->err);
+ if (*columns[i].indicators == -1)
+ boundValues[i] = QVariant(tp);
+ continue;
+ }
+
+ QVariantList *list = static_cast<QVariantList *>(const_cast<void*>(boundValues.at(i).data()));
+
+ char* data = columns[i].data;
+ for (uint r = 0; r < columns[i].recordCount; ++r){
+
+ if (columns[i].indicators[r] == -1) {
+ (*list)[r] = QVariant();
+ continue;
+ }
+
+ switch(columns[i].bindAs) {
+
+ case SQLT_DAT:
+ (*list)[r] = qMakeDate(data + r * columns[i].maxLen);
+ break;
+
+ case SQLT_INT:
+ (*list)[r] = *reinterpret_cast<int*>(data + r * columns[i].maxLen);
+ break;
+
+ case SQLT_UIN:
+ (*list)[r] = *reinterpret_cast<uint*>(data + r * columns[i].maxLen);
+ break;
+
+ case SQLT_VNU:
+ {
+ switch (boundValues.at(i).type()) {
+ case QVariant::LongLong:
+ (*list)[r] = qMakeLongLong(data + r * columns[i].maxLen, d->err);
+ break;
+ case QVariant::ULongLong:
+ (*list)[r] = qMakeULongLong(data + r * columns[i].maxLen, d->err);
+ break;
+ default:
+ break;
+ }
+ break;
+ }
+
+ case SQLT_FLT:
+ (*list)[r] = *reinterpret_cast<double*>(data + r * columns[i].maxLen);
+ break;
+
+ case SQLT_STR:
+ (*list)[r] = QString(reinterpret_cast<const QChar *>(data
+ + r * columns[i].maxLen));
+ break;
+
+ default:
+ (*list)[r] = QByteArray(data + r * columns[i].maxLen, columns[i].maxLen);
+ break;
+ }
+ }
+ }
+
+ d->q_func()->setSelect(false);
+ d->q_func()->setAt(QSql::BeforeFirstRow);
+ d->q_func()->setActive(true);
+
+ return true;
+}
+
+template<class T, int sz>
+int qReadLob(T &buf, const QOCIResultPrivate *d, OCILobLocator *lob)
+{
+ ub1 csfrm;
+ ub4 amount;
+ int r;
+
+ // Read this from the database, don't assume we know what it is set to
+ r = OCILobCharSetForm(d->env, d->err, lob, &csfrm);
+ if (r != OCI_SUCCESS) {
+ qOraWarning("OCIResultPrivate::readLobs: Couldn't get LOB char set form: ", d->err);
+ csfrm = 0;
+ }
+
+ // Get the length of the LOB (this is in characters)
+ r = OCILobGetLength(d->svc, d->err, lob, &amount);
+ if (r == OCI_SUCCESS) {
+ if (amount == 0) {
+ // Short cut for null LOBs
+ buf.resize(0);
+ return OCI_SUCCESS;
+ }
+ } else {
+ qOraWarning("OCIResultPrivate::readLobs: Couldn't get LOB length: ", d->err);
+ return r;
+ }
+
+ // Resize the buffer to hold the LOB contents
+ buf.resize(amount);
+
+ // Read the LOB into the buffer
+ r = OCILobRead(d->svc,
+ d->err,
+ lob,
+ &amount,
+ 1,
+ buf.data(),
+ buf.size() * sz, // this argument is in bytes, not characters
+ 0,
+ 0,
+ // Extract the data from a CLOB in UTF-16 (ie. what QString uses internally)
+ sz == 1 ? ub2(0) : ub2(QOCIEncoding),
+ csfrm);
+
+ if (r != OCI_SUCCESS)
+ qOraWarning("OCIResultPrivate::readLOBs: Cannot read LOB: ", d->err);
+
+ return r;
+}
+
+int QOCICols::readLOBs(QVector<QVariant> &values, int index)
+{
+ OCILobLocator *lob;
+ int r = OCI_SUCCESS;
+
+ for (int i = 0; i < size(); ++i) {
+ const OraFieldInf &fi = fieldInf.at(i);
+ if (fi.ind == -1 || !(lob = fi.lob))
+ continue;
+
+ bool isClob = fi.oraType == SQLT_CLOB;
+ QVariant var;
+
+ if (isClob) {
+ QString str;
+ r = qReadLob<QString, sizeof(QChar)>(str, d, lob);
+ var = str;
+ } else {
+ QByteArray buf;
+ r = qReadLob<QByteArray, sizeof(char)>(buf, d, lob);
+ var = buf;
+ }
+ if (r == OCI_SUCCESS)
+ values[index + i] = var;
+ else
+ break;
+ }
+ return r;
+}
+
+int QOCICols::fieldFromDefine(OCIDefine* d)
+{
+ for (int i = 0; i < fieldInf.count(); ++i) {
+ if (fieldInf.at(i).def == d)
+ return i;
+ }
+ return -1;
+}
+
+void QOCICols::getValues(QVector<QVariant> &v, int index)
+{
+ for (int i = 0; i < fieldInf.size(); ++i) {
+ const OraFieldInf &fld = fieldInf.at(i);
+
+ if (fld.ind == -1) {
+ // got a NULL value
+ v[index + i] = QVariant(fld.typ);
+ continue;
+ }
+
+ if (fld.oraType == SQLT_BIN || fld.oraType == SQLT_LBI || fld.oraType == SQLT_LNG)
+ continue; // already fetched piecewise
+
+ switch (fld.typ) {
+ case QVariant::DateTime:
+ v[index + i] = QVariant(qMakeDate(fld.data));
+ break;
+ case QVariant::Double:
+ case QVariant::Int:
+ case QVariant::LongLong:
+ if (d->q_func()->numericalPrecisionPolicy() != QSql::HighPrecision) {
+ if ((d->q_func()->numericalPrecisionPolicy() == QSql::LowPrecisionDouble)
+ && (fld.typ == QVariant::Double)) {
+ v[index + i] = *reinterpret_cast<double *>(fld.data);
+ break;
+ } else if ((d->q_func()->numericalPrecisionPolicy() == QSql::LowPrecisionInt64)
+ && (fld.typ == QVariant::LongLong)) {
+ qint64 qll = 0;
+ int r = OCINumberToInt(d->err, reinterpret_cast<OCINumber *>(fld.data), sizeof(qint64),
+ OCI_NUMBER_SIGNED, &qll);
+ if(r == OCI_SUCCESS)
+ v[index + i] = qll;
+ else
+ v[index + i] = QVariant();
+ break;
+ } else if ((d->q_func()->numericalPrecisionPolicy() == QSql::LowPrecisionInt32)
+ && (fld.typ == QVariant::Int)) {
+ v[index + i] = *reinterpret_cast<int *>(fld.data);
+ break;
+ }
+ }
+ // else fall through
+ case QVariant::String:
+ v[index + i] = QString(reinterpret_cast<const QChar *>(fld.data));
+ break;
+ case QVariant::ByteArray:
+ if (fld.len > 0)
+ v[index + i] = QByteArray(fld.data, fld.len);
+ else
+ v[index + i] = QVariant(QVariant::ByteArray);
+ break;
+ default:
+ qWarning("QOCICols::value: unknown data type");
+ break;
+ }
+ }
+}
+
+QOCIResultPrivate::QOCIResultPrivate(QOCIResult *q, const QOCIDriver *drv)
+ : QSqlCachedResultPrivate(q, drv),
+ cols(0),
+ env(drv_d_func()->env),
+ err(0),
+ svc(const_cast<OCISvcCtx*&>(drv_d_func()->svc)),
+ sql(0),
+ transaction(drv_d_func()->transaction),
+ serverVersion(drv_d_func()->serverVersion),
+ prefetchRows(drv_d_func()->prefetchRows),
+ prefetchMem(drv_d_func()->prefetchMem)
+{
+ int r = OCIHandleAlloc(env,
+ reinterpret_cast<void **>(&err),
+ OCI_HTYPE_ERROR,
+ 0,
+ 0);
+ if (r != 0)
+ qWarning("QOCIResult: unable to alloc error handle");
+}
+
+QOCIResultPrivate::~QOCIResultPrivate()
+{
+ delete cols;
+
+ int r = OCIHandleFree(err, OCI_HTYPE_ERROR);
+ if (r != 0)
+ qWarning("~QOCIResult: unable to free statement handle");
+}
+
+
+////////////////////////////////////////////////////////////////////////////
+
+QOCIResult::QOCIResult(const QOCIDriver *db)
+ : QSqlCachedResult(*new QOCIResultPrivate(this, db))
+{
+}
+
+QOCIResult::~QOCIResult()
+{
+ Q_D(QOCIResult);
+ if (d->sql) {
+ int r = OCIHandleFree(d->sql, OCI_HTYPE_STMT);
+ if (r != 0)
+ qWarning("~QOCIResult: unable to free statement handle");
+ }
+}
+
+QVariant QOCIResult::handle() const
+{
+ Q_D(const QOCIResult);
+ return QVariant::fromValue(d->sql);
+}
+
+bool QOCIResult::reset (const QString& query)
+{
+ if (!prepare(query))
+ return false;
+ return exec();
+}
+
+bool QOCIResult::gotoNext(QSqlCachedResult::ValueCache &values, int index)
+{
+ Q_D(QOCIResult);
+ if (at() == QSql::AfterLastRow)
+ return false;
+
+ bool piecewise = false;
+ int r = OCI_SUCCESS;
+ r = OCIStmtFetch(d->sql, d->err, 1, OCI_FETCH_NEXT, OCI_DEFAULT);
+
+ if (index < 0) //not interested in values
+ return r == OCI_SUCCESS || r == OCI_SUCCESS_WITH_INFO;
+
+ switch (r) {
+ case OCI_SUCCESS:
+ break;
+ case OCI_SUCCESS_WITH_INFO:
+ qOraWarning("QOCIResult::gotoNext: SuccessWithInfo: ", d->err);
+ r = OCI_SUCCESS; //ignore it
+ break;
+ case OCI_NO_DATA:
+ // end of rowset
+ return false;
+ case OCI_NEED_DATA:
+ piecewise = true;
+ r = OCI_SUCCESS;
+ break;
+ case OCI_ERROR:
+ if (qOraErrorNumber(d->err) == 1406) {
+ qWarning("QOCI Warning: data truncated for %s", lastQuery().toLocal8Bit().constData());
+ r = OCI_SUCCESS; /* ignore it */
+ break;
+ }
+ // fall through
+ default:
+ qOraWarning("QOCIResult::gotoNext: ", d->err);
+ setLastError(qMakeError(QCoreApplication::translate("QOCIResult",
+ "Unable to goto next"),
+ QSqlError::StatementError, d->err));
+ break;
+ }
+
+ // need to read piecewise before assigning values
+ if (r == OCI_SUCCESS && piecewise)
+ r = d->cols->readPiecewise(values, index);
+
+ if (r == OCI_SUCCESS)
+ d->cols->getValues(values, index);
+ if (r == OCI_SUCCESS)
+ r = d->cols->readLOBs(values, index);
+ if (r != OCI_SUCCESS)
+ setAt(QSql::AfterLastRow);
+ return r == OCI_SUCCESS || r == OCI_SUCCESS_WITH_INFO;
+}
+
+int QOCIResult::size()
+{
+ return -1;
+}
+
+int QOCIResult::numRowsAffected()
+{
+ Q_D(QOCIResult);
+ int rowCount;
+ OCIAttrGet(d->sql,
+ OCI_HTYPE_STMT,
+ &rowCount,
+ NULL,
+ OCI_ATTR_ROW_COUNT,
+ d->err);
+ return rowCount;
+}
+
+bool QOCIResult::prepare(const QString& query)
+{
+ Q_D(QOCIResult);
+ int r = 0;
+ QSqlResult::prepare(query);
+
+ delete d->cols;
+ d->cols = 0;
+ QSqlCachedResult::cleanup();
+
+ if (d->sql) {
+ r = OCIHandleFree(d->sql, OCI_HTYPE_STMT);
+ if (r != OCI_SUCCESS)
+ qOraWarning("QOCIResult::prepare: unable to free statement handle:", d->err);
+ }
+ if (query.isEmpty())
+ return false;
+ r = OCIHandleAlloc(d->env,
+ reinterpret_cast<void **>(&d->sql),
+ OCI_HTYPE_STMT,
+ 0,
+ 0);
+ if (r != OCI_SUCCESS) {
+ qOraWarning("QOCIResult::prepare: unable to alloc statement:", d->err);
+ setLastError(qMakeError(QCoreApplication::translate("QOCIResult",
+ "Unable to alloc statement"), QSqlError::StatementError, d->err));
+ return false;
+ }
+ d->setStatementAttributes();
+ const OraText *txt = reinterpret_cast<const OraText *>(query.utf16());
+ const int len = query.length() * sizeof(QChar);
+ r = OCIStmtPrepare(d->sql,
+ d->err,
+ txt,
+ len,
+ OCI_NTV_SYNTAX,
+ OCI_DEFAULT);
+ if (r != OCI_SUCCESS) {
+ qOraWarning("QOCIResult::prepare: unable to prepare statement:", d->err);
+ setLastError(qMakeError(QCoreApplication::translate("QOCIResult",
+ "Unable to prepare statement"), QSqlError::StatementError, d->err));
+ return false;
+ }
+ return true;
+}
+
+bool QOCIResult::exec()
+{
+ Q_D(QOCIResult);
+ int r = 0;
+ ub2 stmtType=0;
+ ub4 iters;
+ ub4 mode;
+ QList<QByteArray> tmpStorage;
+ IndicatorArray indicators(boundValueCount());
+ SizeArray tmpSizes(boundValueCount());
+
+ r = OCIAttrGet(d->sql,
+ OCI_HTYPE_STMT,
+ &stmtType,
+ NULL,
+ OCI_ATTR_STMT_TYPE,
+ d->err);
+
+ if (r != OCI_SUCCESS && r != OCI_SUCCESS_WITH_INFO) {
+ qOraWarning("QOCIResult::exec: Unable to get statement type:", d->err);
+ setLastError(qMakeError(QCoreApplication::translate("QOCIResult",
+ "Unable to get statement type"), QSqlError::StatementError, d->err));
+#ifdef QOCI_DEBUG
+ qDebug() << "lastQuery()" << lastQuery();
+#endif
+ return false;
+ }
+
+ iters = stmtType == OCI_STMT_SELECT ? 0 : 1;
+ mode = d->transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
+
+ // bind placeholders
+ if (boundValueCount() > 0
+ && d->bindValues(boundValues(), indicators, tmpSizes, tmpStorage) != OCI_SUCCESS) {
+ qOraWarning("QOCIResult::exec: unable to bind value: ", d->err);
+ setLastError(qMakeError(QCoreApplication::translate("QOCIResult", "Unable to bind value"),
+ QSqlError::StatementError, d->err));
+#ifdef QOCI_DEBUG
+ qDebug() << "lastQuery()" << lastQuery();
+#endif
+ return false;
+ }
+
+ // execute
+ r = OCIStmtExecute(d->svc,
+ d->sql,
+ d->err,
+ iters,
+ 0,
+ 0,
+ 0,
+ mode);
+ if (r != OCI_SUCCESS && r != OCI_SUCCESS_WITH_INFO) {
+ qOraWarning("QOCIResult::exec: unable to execute statement:", d->err);
+ setLastError(qMakeError(QCoreApplication::translate("QOCIResult",
+ "Unable to execute statement"), QSqlError::StatementError, d->err));
+#ifdef QOCI_DEBUG
+ qDebug() << "lastQuery()" << lastQuery();
+#endif
+ return false;
+ }
+
+ if (stmtType == OCI_STMT_SELECT) {
+ ub4 parmCount = 0;
+ int r = OCIAttrGet(d->sql, OCI_HTYPE_STMT, reinterpret_cast<void **>(&parmCount),
+ 0, OCI_ATTR_PARAM_COUNT, d->err);
+ if (r == 0 && !d->cols)
+ d->cols = new QOCICols(parmCount, d);
+ setSelect(true);
+ QSqlCachedResult::init(parmCount);
+ } else { /* non-SELECT */
+ setSelect(false);
+ }
+ setAt(QSql::BeforeFirstRow);
+ setActive(true);
+
+ if (hasOutValues())
+ d->outValues(boundValues(), indicators, tmpStorage);
+
+ return true;
+}
+
+QSqlRecord QOCIResult::record() const
+{
+ Q_D(const QOCIResult);
+ QSqlRecord inf;
+ if (!isActive() || !isSelect() || !d->cols)
+ return inf;
+ return d->cols->rec;
+}
+
+QVariant QOCIResult::lastInsertId() const
+{
+ Q_D(const QOCIResult);
+ if (isActive()) {
+ QOCIRowIdPointer ptr(new QOCIRowId(d->env));
+
+ int r = OCIAttrGet(d->sql, OCI_HTYPE_STMT, ptr.constData()->id,
+ 0, OCI_ATTR_ROWID, d->err);
+ if (r == OCI_SUCCESS)
+ return QVariant::fromValue(ptr);
+ }
+ return QVariant();
+}
+
+bool QOCIResult::execBatch(bool arrayBind)
+{
+ Q_D(QOCIResult);
+ QOCICols::execBatch(d, boundValues(), arrayBind);
+ resetBindCount();
+ return lastError().type() == QSqlError::NoError;
+}
+
+void QOCIResult::virtual_hook(int id, void *data)
+{
+ Q_ASSERT(data);
+
+ QSqlCachedResult::virtual_hook(id, data);
+}
+
+////////////////////////////////////////////////////////////////////////////
+
+
+QOCIDriver::QOCIDriver(QObject* parent)
+ : QSqlDriver(*new QOCIDriverPrivate, parent)
+{
+ Q_D(QOCIDriver);
+#ifdef QOCI_THREADED
+ const ub4 mode = OCI_UTF16 | OCI_OBJECT | OCI_THREADED;
+#else
+ const ub4 mode = OCI_UTF16 | OCI_OBJECT;
+#endif
+ int r = OCIEnvCreate(&d->env,
+ mode,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ 0,
+ NULL);
+ if (r != 0) {
+ qWarning("QOCIDriver: unable to create environment");
+ setLastError(qMakeError(tr("Unable to initialize", "QOCIDriver"),
+ QSqlError::ConnectionError, d->err));
+ return;
+ }
+
+ d->allocErrorHandle();
+}
+
+QOCIDriver::QOCIDriver(OCIEnv* env, OCISvcCtx* ctx, QObject* parent)
+ : QSqlDriver(*new QOCIDriverPrivate, parent)
+{
+ Q_D(QOCIDriver);
+ d->env = env;
+ d->svc = ctx;
+
+ d->allocErrorHandle();
+
+ if (env && ctx) {
+ setOpen(true);
+ setOpenError(false);
+ }
+}
+
+QOCIDriver::~QOCIDriver()
+{
+ Q_D(QOCIDriver);
+ if (isOpen())
+ close();
+ int r = OCIHandleFree(d->err, OCI_HTYPE_ERROR);
+ if (r != OCI_SUCCESS)
+ qWarning("Unable to free Error handle: %d", r);
+ r = OCIHandleFree(d->env, OCI_HTYPE_ENV);
+ if (r != OCI_SUCCESS)
+ qWarning("Unable to free Environment handle: %d", r);
+}
+
+bool QOCIDriver::hasFeature(DriverFeature f) const
+{
+ Q_D(const QOCIDriver);
+ switch (f) {
+ case Transactions:
+ case LastInsertId:
+ case BLOB:
+ case PreparedQueries:
+ case NamedPlaceholders:
+ case BatchOperations:
+ case LowPrecisionNumbers:
+ return true;
+ case QuerySize:
+ case PositionalPlaceholders:
+ case SimpleLocking:
+ case EventNotifications:
+ case FinishQuery:
+ case CancelQuery:
+ case MultipleResultSets:
+ return false;
+ case Unicode:
+ return d->serverVersion >= 9;
+ }
+ return false;
+}
+
+static void qParseOpts(const QString &options, QOCIDriverPrivate *d)
+{
+ const QStringList opts(options.split(QLatin1Char(';'), QString::SkipEmptyParts));
+ for (int i = 0; i < opts.count(); ++i) {
+ const QString tmp(opts.at(i));
+ int idx;
+ if ((idx = tmp.indexOf(QLatin1Char('='))) == -1) {
+ qWarning("QOCIDriver::parseArgs: Invalid parameter: '%s'",
+ tmp.toLocal8Bit().constData());
+ continue;
+ }
+ const QString opt = tmp.left(idx);
+ const QString val = tmp.mid(idx + 1).simplified();
+ bool ok;
+ if (opt == QLatin1String("OCI_ATTR_PREFETCH_ROWS")) {
+ d->prefetchRows = val.toInt(&ok);
+ if (!ok)
+ d->prefetchRows = -1;
+ } else if (opt == QLatin1String("OCI_ATTR_PREFETCH_MEMORY")) {
+ d->prefetchMem = val.toInt(&ok);
+ if (!ok)
+ d->prefetchMem = -1;
+ } else {
+ qWarning ("QOCIDriver::parseArgs: Invalid parameter: '%s'",
+ opt.toLocal8Bit().constData());
+ }
+ }
+}
+
+bool QOCIDriver::open(const QString & db,
+ const QString & user,
+ const QString & password,
+ const QString & hostname,
+ int port,
+ const QString &opts)
+{
+ Q_D(QOCIDriver);
+ int r;
+
+ if (isOpen())
+ close();
+
+ qParseOpts(opts, d);
+
+ // Connect without tnsnames.ora if a hostname is given
+ QString connectionString = db;
+ if (!hostname.isEmpty())
+ connectionString =
+ QString::fromLatin1("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host=%1)(Port=%2))"
+ "(CONNECT_DATA=(SID=%3)))").arg(hostname).arg((port > -1 ? port : 1521)).arg(db);
+
+ r = OCIHandleAlloc(d->env, reinterpret_cast<void **>(&d->srvhp), OCI_HTYPE_SERVER, 0, 0);
+ if (r == OCI_SUCCESS)
+ r = OCIServerAttach(d->srvhp, d->err, reinterpret_cast<const OraText *>(connectionString.utf16()),
+ connectionString.length() * sizeof(QChar), OCI_DEFAULT);
+ if (r == OCI_SUCCESS || r == OCI_SUCCESS_WITH_INFO)
+ r = OCIHandleAlloc(d->env, reinterpret_cast<void **>(&d->svc), OCI_HTYPE_SVCCTX, 0, 0);
+ if (r == OCI_SUCCESS)
+ r = OCIAttrSet(d->svc, OCI_HTYPE_SVCCTX, d->srvhp, 0, OCI_ATTR_SERVER, d->err);
+ if (r == OCI_SUCCESS)
+ r = OCIHandleAlloc(d->env, reinterpret_cast<void **>(&d->authp), OCI_HTYPE_SESSION, 0, 0);
+ if (r == OCI_SUCCESS)
+ r = OCIAttrSet(d->authp, OCI_HTYPE_SESSION, const_cast<ushort *>(user.utf16()),
+ user.length() * sizeof(QChar), OCI_ATTR_USERNAME, d->err);
+ if (r == OCI_SUCCESS)
+ r = OCIAttrSet(d->authp, OCI_HTYPE_SESSION, const_cast<ushort *>(password.utf16()),
+ password.length() * sizeof(QChar), OCI_ATTR_PASSWORD, d->err);
+
+ OCITrans* trans;
+ if (r == OCI_SUCCESS)
+ r = OCIHandleAlloc(d->env, reinterpret_cast<void **>(&trans), OCI_HTYPE_TRANS, 0, 0);
+ if (r == OCI_SUCCESS)
+ r = OCIAttrSet(d->svc, OCI_HTYPE_SVCCTX, trans, 0, OCI_ATTR_TRANS, d->err);
+
+ if (r == OCI_SUCCESS) {
+ if (user.isEmpty() && password.isEmpty())
+ r = OCISessionBegin(d->svc, d->err, d->authp, OCI_CRED_EXT, OCI_DEFAULT);
+ else
+ r = OCISessionBegin(d->svc, d->err, d->authp, OCI_CRED_RDBMS, OCI_DEFAULT);
+ }
+ if (r == OCI_SUCCESS || r == OCI_SUCCESS_WITH_INFO)
+ r = OCIAttrSet(d->svc, OCI_HTYPE_SVCCTX, d->authp, 0, OCI_ATTR_SESSION, d->err);
+
+ if (r != OCI_SUCCESS) {
+ setLastError(qMakeError(tr("Unable to logon"), QSqlError::ConnectionError, d->err));
+ setOpenError(true);
+ if (d->authp)
+ OCIHandleFree(d->authp, OCI_HTYPE_SESSION);
+ d->authp = 0;
+ if (d->srvhp)
+ OCIHandleFree(d->srvhp, OCI_HTYPE_SERVER);
+ d->srvhp = 0;
+ return false;
+ }
+
+ // get server version
+ char vertxt[512];
+ r = OCIServerVersion(d->svc,
+ d->err,
+ reinterpret_cast<OraText *>(vertxt),
+ sizeof(vertxt),
+ OCI_HTYPE_SVCCTX);
+ if (r != 0) {
+ qWarning("QOCIDriver::open: could not get Oracle server version.");
+ } else {
+ QString versionStr;
+ versionStr = QString(reinterpret_cast<const QChar *>(vertxt));
+ QRegExp vers(QLatin1String("([0-9]+)\\.[0-9\\.]+[0-9]"));
+ if (vers.indexIn(versionStr) >= 0)
+ d->serverVersion = vers.cap(1).toInt();
+ if (d->serverVersion == 0)
+ d->serverVersion = -1;
+ }
+
+ setOpen(true);
+ setOpenError(false);
+ d->user = user;
+
+ return true;
+}
+
+void QOCIDriver::close()
+{
+ Q_D(QOCIDriver);
+ if (!isOpen())
+ return;
+
+ OCISessionEnd(d->svc, d->err, d->authp, OCI_DEFAULT);
+ OCIServerDetach(d->srvhp, d->err, OCI_DEFAULT);
+ OCIHandleFree(d->authp, OCI_HTYPE_SESSION);
+ d->authp = 0;
+ OCIHandleFree(d->srvhp, OCI_HTYPE_SERVER);
+ d->srvhp = 0;
+ OCIHandleFree(d->svc, OCI_HTYPE_SVCCTX);
+ d->svc = 0;
+ setOpen(false);
+ setOpenError(false);
+}
+
+QSqlResult *QOCIDriver::createResult() const
+{
+ return new QOCIResult(this);
+}
+
+bool QOCIDriver::beginTransaction()
+{
+ Q_D(QOCIDriver);
+ if (!isOpen()) {
+ qWarning("QOCIDriver::beginTransaction: Database not open");
+ return false;
+ }
+ int r = OCITransStart(d->svc,
+ d->err,
+ 2,
+ OCI_TRANS_READWRITE);
+ if (r == OCI_ERROR) {
+ qOraWarning("QOCIDriver::beginTransaction: ", d->err);
+ setLastError(qMakeError(QCoreApplication::translate("QOCIDriver",
+ "Unable to begin transaction"), QSqlError::TransactionError, d->err));
+ return false;
+ }
+ d->transaction = true;
+ return true;
+}
+
+bool QOCIDriver::commitTransaction()
+{
+ Q_D(QOCIDriver);
+ if (!isOpen()) {
+ qWarning("QOCIDriver::commitTransaction: Database not open");
+ return false;
+ }
+ int r = OCITransCommit(d->svc,
+ d->err,
+ 0);
+ if (r == OCI_ERROR) {
+ qOraWarning("QOCIDriver::commitTransaction:", d->err);
+ setLastError(qMakeError(QCoreApplication::translate("QOCIDriver",
+ "Unable to commit transaction"), QSqlError::TransactionError, d->err));
+ return false;
+ }
+ d->transaction = false;
+ return true;
+}
+
+bool QOCIDriver::rollbackTransaction()
+{
+ Q_D(QOCIDriver);
+ if (!isOpen()) {
+ qWarning("QOCIDriver::rollbackTransaction: Database not open");
+ return false;
+ }
+ int r = OCITransRollback(d->svc,
+ d->err,
+ 0);
+ if (r == OCI_ERROR) {
+ qOraWarning("QOCIDriver::rollbackTransaction:", d->err);
+ setLastError(qMakeError(QCoreApplication::translate("QOCIDriver",
+ "Unable to rollback transaction"), QSqlError::TransactionError, d->err));
+ return false;
+ }
+ d->transaction = false;
+ return true;
+}
+
+enum Expression {
+ OrExpression,
+ AndExpression
+};
+
+static QString make_where_clause(const QString &user, Expression e)
+{
+ static const char sysUsers[][8] = {
+ "MDSYS",
+ "LBACSYS",
+ "SYS",
+ "SYSTEM",
+ "WKSYS",
+ "CTXSYS",
+ "WMSYS",
+ };
+ static const char joinC[][4] = { "or" , "and" };
+ static Q_CONSTEXPR QLatin1Char bang[] = { QLatin1Char(' '), QLatin1Char('!') };
+
+ const QLatin1String join(joinC[e], -1); // -1: force strlen call
+
+ QString result;
+ result.reserve(sizeof sysUsers / sizeof *sysUsers *
+ // max-sizeof(owner != <sysuser> and )
+ (9 + sizeof *sysUsers + 5));
+ for (const auto &sysUser : sysUsers) {
+ const QLatin1String l1(sysUser, -1); // -1: force strlen call
+ if (l1 != user)
+ result += QLatin1String("owner ") + bang[e] + QLatin1String("= '") + l1 + QLatin1Char(' ') + join + QLatin1Char(' ');
+ }
+
+ result.chop(join.size() + 2); // remove final " <join> "
+
+ return result;
+}
+
+QStringList QOCIDriver::tables(QSql::TableType type) const
+{
+ Q_D(const QOCIDriver);
+ QStringList tl;
+
+ QString user = d->user;
+ if ( isIdentifierEscaped(user, QSqlDriver::TableName))
+ user = stripDelimiters(user, QSqlDriver::TableName);
+ else
+ user = user.toUpper();
+
+ if (!isOpen())
+ return tl;
+
+ QSqlQuery t(createResult());
+ t.setForwardOnly(true);
+ if (type & QSql::Tables) {
+ const QLatin1String tableQuery("select owner, table_name from all_tables where ");
+ const QString where = make_where_clause(user, AndExpression);
+ t.exec(tableQuery + where);
+ while (t.next()) {
+ if (t.value(0).toString().toUpper() != user.toUpper())
+ tl.append(t.value(0).toString() + QLatin1Char('.') + t.value(1).toString());
+ else
+ tl.append(t.value(1).toString());
+ }
+
+ // list all table synonyms as well
+ const QLatin1String synonymQuery("select owner, synonym_name from all_synonyms where ");
+ t.exec(synonymQuery + where);
+ while (t.next()) {
+ if (t.value(0).toString() != d->user)
+ tl.append(t.value(0).toString() + QLatin1Char('.') + t.value(1).toString());
+ else
+ tl.append(t.value(1).toString());
+ }
+ }
+ if (type & QSql::Views) {
+ const QLatin1String query("select owner, view_name from all_views where ");
+ const QString where = make_where_clause(user, AndExpression);
+ t.exec(query + where);
+ while (t.next()) {
+ if (t.value(0).toString().toUpper() != d->user.toUpper())
+ tl.append(t.value(0).toString() + QLatin1Char('.') + t.value(1).toString());
+ else
+ tl.append(t.value(1).toString());
+ }
+ }
+ if (type & QSql::SystemTables) {
+ t.exec(QLatin1String("select table_name from dictionary"));
+ while (t.next()) {
+ tl.append(t.value(0).toString());
+ }
+ const QLatin1String tableQuery("select owner, table_name from all_tables where ");
+ const QString where = make_where_clause(user, OrExpression);
+ t.exec(tableQuery + where);
+ while (t.next()) {
+ if (t.value(0).toString().toUpper() != user.toUpper())
+ tl.append(t.value(0).toString() + QLatin1Char('.') + t.value(1).toString());
+ else
+ tl.append(t.value(1).toString());
+ }
+
+ // list all table synonyms as well
+ const QLatin1String synonymQuery("select owner, synonym_name from all_synonyms where ");
+ t.exec(synonymQuery + where);
+ while (t.next()) {
+ if (t.value(0).toString() != d->user)
+ tl.append(t.value(0).toString() + QLatin1Char('.') + t.value(1).toString());
+ else
+ tl.append(t.value(1).toString());
+ }
+ }
+ return tl;
+}
+
+void qSplitTableAndOwner(const QString & tname, QString * tbl,
+ QString * owner)
+{
+ int i = tname.indexOf(QLatin1Char('.')); // prefixed with owner?
+ if (i != -1) {
+ *tbl = tname.right(tname.length() - i - 1);
+ *owner = tname.left(i);
+ } else {
+ *tbl = tname;
+ }
+}
+
+QSqlRecord QOCIDriver::record(const QString& tablename) const
+{
+ Q_D(const QOCIDriver);
+ QSqlRecord fil;
+ if (!isOpen())
+ return fil;
+
+ QSqlQuery t(createResult());
+ // using two separate queries for this is A LOT faster than using
+ // eg. a sub-query on the sys.synonyms table
+ QString stmt(QLatin1String("select column_name, data_type, data_length, "
+ "data_precision, data_scale, nullable, data_default%1"
+ "from all_tab_columns a "
+ "where a.table_name=%2"));
+ if (d->serverVersion >= 9)
+ stmt = stmt.arg(QLatin1String(", char_length "));
+ else
+ stmt = stmt.arg(QLatin1String(" "));
+ bool buildRecordInfo = false;
+ QString table, owner, tmpStmt;
+ qSplitTableAndOwner(tablename, &table, &owner);
+
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+ else
+ table = table.toUpper();
+
+ tmpStmt = stmt.arg(QLatin1Char('\'') + table + QLatin1Char('\''));
+ if (owner.isEmpty()) {
+ owner = d->user;
+ }
+
+ if (isIdentifierEscaped(owner, QSqlDriver::TableName))
+ owner = stripDelimiters(owner, QSqlDriver::TableName);
+ else
+ owner = owner.toUpper();
+
+ tmpStmt += QLatin1String(" and a.owner='") + owner + QLatin1Char('\'');
+ t.setForwardOnly(true);
+ t.exec(tmpStmt);
+ if (!t.next()) { // try and see if the tablename is a synonym
+ stmt = stmt + QLatin1String(" join all_synonyms b "
+ "on a.owner=b.table_owner and a.table_name=b.table_name "
+ "where b.owner='") + owner +
+ QLatin1String("' and b.synonym_name='") + table +
+ QLatin1Char('\'');
+ t.setForwardOnly(true);
+ t.exec(stmt);
+ if (t.next())
+ buildRecordInfo = true;
+ } else {
+ buildRecordInfo = true;
+ }
+ QStringList keywords = QStringList() << QLatin1String("NUMBER") << QLatin1String("FLOAT") << QLatin1String("BINARY_FLOAT")
+ << QLatin1String("BINARY_DOUBLE");
+ if (buildRecordInfo) {
+ do {
+ QVariant::Type ty = qDecodeOCIType(t.value(1).toString(), t.numericalPrecisionPolicy());
+ QSqlField f(t.value(0).toString(), ty);
+ f.setRequired(t.value(5).toString() == QLatin1String("N"));
+ f.setPrecision(t.value(4).toInt());
+ if (d->serverVersion >= 9 && (ty == QVariant::String) && !t.isNull(3) && !keywords.contains(t.value(1).toString())) {
+ // Oracle9: data_length == size in bytes, char_length == amount of characters
+ f.setLength(t.value(7).toInt());
+ } else {
+ f.setLength(t.value(t.isNull(3) ? 2 : 3).toInt());
+ }
+ f.setDefaultValue(t.value(6));
+ fil.append(f);
+ } while (t.next());
+ }
+ return fil;
+}
+
+QSqlIndex QOCIDriver::primaryIndex(const QString& tablename) const
+{
+ Q_D(const QOCIDriver);
+ QSqlIndex idx(tablename);
+ if (!isOpen())
+ return idx;
+ QSqlQuery t(createResult());
+ QString stmt(QLatin1String("select b.column_name, b.index_name, a.table_name, a.owner "
+ "from all_constraints a, all_ind_columns b "
+ "where a.constraint_type='P' "
+ "and b.index_name = a.constraint_name "
+ "and b.index_owner = a.owner"));
+
+ bool buildIndex = false;
+ QString table, owner, tmpStmt;
+ qSplitTableAndOwner(tablename, &table, &owner);
+
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+ else
+ table = table.toUpper();
+
+ tmpStmt = stmt + QLatin1String(" and a.table_name='") + table + QLatin1Char('\'');
+ if (owner.isEmpty()) {
+ owner = d->user;
+ }
+
+ if (isIdentifierEscaped(owner, QSqlDriver::TableName))
+ owner = stripDelimiters(owner, QSqlDriver::TableName);
+ else
+ owner = owner.toUpper();
+
+ tmpStmt += QLatin1String(" and a.owner='") + owner + QLatin1Char('\'');
+ t.setForwardOnly(true);
+ t.exec(tmpStmt);
+
+ if (!t.next()) {
+ stmt += QLatin1String(" and a.table_name=(select tname from sys.synonyms "
+ "where sname='") + table + QLatin1String("' and creator=a.owner)");
+ t.setForwardOnly(true);
+ t.exec(stmt);
+ if (t.next()) {
+ owner = t.value(3).toString();
+ buildIndex = true;
+ }
+ } else {
+ buildIndex = true;
+ }
+ if (buildIndex) {
+ QSqlQuery tt(createResult());
+ tt.setForwardOnly(true);
+ idx.setName(t.value(1).toString());
+ do {
+ tt.exec(QLatin1String("select data_type from all_tab_columns where table_name='") +
+ t.value(2).toString() + QLatin1String("' and column_name='") +
+ t.value(0).toString() + QLatin1String("' and owner='") +
+ owner + QLatin1Char('\''));
+ if (!tt.next()) {
+ return QSqlIndex();
+ }
+ QSqlField f(t.value(0).toString(), qDecodeOCIType(tt.value(0).toString(), t.numericalPrecisionPolicy()));
+ idx.append(f);
+ } while (t.next());
+ return idx;
+ }
+ return QSqlIndex();
+}
+
+QString QOCIDriver::formatValue(const QSqlField &field, bool trimStrings) const
+{
+ switch (field.type()) {
+ case QVariant::DateTime: {
+ QDateTime datetime = field.value().toDateTime();
+ QString datestring;
+ if (datetime.isValid()) {
+ datestring = QLatin1String("TO_DATE('") + QString::number(datetime.date().year())
+ + QLatin1Char('-')
+ + QString::number(datetime.date().month()) + QLatin1Char('-')
+ + QString::number(datetime.date().day()) + QLatin1Char(' ')
+ + QString::number(datetime.time().hour()) + QLatin1Char(':')
+ + QString::number(datetime.time().minute()) + QLatin1Char(':')
+ + QString::number(datetime.time().second())
+ + QLatin1String("','YYYY-MM-DD HH24:MI:SS')");
+ } else {
+ datestring = QLatin1String("NULL");
+ }
+ return datestring;
+ }
+ case QVariant::Time: {
+ QDateTime datetime = field.value().toDateTime();
+ QString datestring;
+ if (datetime.isValid()) {
+ datestring = QLatin1String("TO_DATE('")
+ + QString::number(datetime.time().hour()) + QLatin1Char(':')
+ + QString::number(datetime.time().minute()) + QLatin1Char(':')
+ + QString::number(datetime.time().second())
+ + QLatin1String("','HH24:MI:SS')");
+ } else {
+ datestring = QLatin1String("NULL");
+ }
+ return datestring;
+ }
+ case QVariant::Date: {
+ QDate date = field.value().toDate();
+ QString datestring;
+ if (date.isValid()) {
+ datestring = QLatin1String("TO_DATE('") + QString::number(date.year()) +
+ QLatin1Char('-') +
+ QString::number(date.month()) + QLatin1Char('-') +
+ QString::number(date.day()) + QLatin1String("','YYYY-MM-DD')");
+ } else {
+ datestring = QLatin1String("NULL");
+ }
+ return datestring;
+ }
+ default:
+ break;
+ }
+ return QSqlDriver::formatValue(field, trimStrings);
+}
+
+QVariant QOCIDriver::handle() const
+{
+ Q_D(const QOCIDriver);
+ return QVariant::fromValue(d->env);
+}
+
+QString QOCIDriver::escapeIdentifier(const QString &identifier, IdentifierType type) const
+{
+ QString res = identifier;
+ if(!identifier.isEmpty() && !isIdentifierEscaped(identifier, type)) {
+ res.replace(QLatin1Char('"'), QLatin1String("\"\""));
+ res.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
+ res.replace(QLatin1Char('.'), QLatin1String("\".\""));
+ }
+ return res;
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/sqldrivers/oci/qsql_oci_p.h b/src/plugins/sqldrivers/oci/qsql_oci_p.h
new file mode 100644
index 0000000000..69911f4bee
--- /dev/null
+++ b/src/plugins/sqldrivers/oci/qsql_oci_p.h
@@ -0,0 +1,106 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSQL_OCI_H
+#define QSQL_OCI_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtSql/qsqldriver.h>
+
+#ifdef QT_PLUGIN
+#define Q_EXPORT_SQLDRIVER_OCI
+#else
+#define Q_EXPORT_SQLDRIVER_OCI Q_SQL_EXPORT
+#endif
+
+typedef struct OCIEnv OCIEnv;
+typedef struct OCISvcCtx OCISvcCtx;
+
+QT_BEGIN_NAMESPACE
+
+class QSqlResult;
+class QOCIDriverPrivate;
+
+class Q_EXPORT_SQLDRIVER_OCI QOCIDriver : public QSqlDriver
+{
+ Q_DECLARE_PRIVATE(QOCIDriver)
+ Q_OBJECT
+ friend class QOCICols;
+ friend class QOCIResultPrivate;
+
+public:
+ explicit QOCIDriver(QObject* parent = 0);
+ QOCIDriver(OCIEnv* env, OCISvcCtx* ctx, QObject* parent = 0);
+ ~QOCIDriver();
+ bool hasFeature(DriverFeature f) const;
+ bool open(const QString &db,
+ const QString &user,
+ const QString &password,
+ const QString &host,
+ int port,
+ const QString &connOpts) Q_DECL_OVERRIDE;
+ void close() Q_DECL_OVERRIDE;
+ QSqlResult *createResult() const Q_DECL_OVERRIDE;
+ QStringList tables(QSql::TableType) const Q_DECL_OVERRIDE;
+ QSqlRecord record(const QString &tablename) const Q_DECL_OVERRIDE;
+ QSqlIndex primaryIndex(const QString& tablename) const Q_DECL_OVERRIDE;
+ QString formatValue(const QSqlField &field,
+ bool trimStrings) const Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+ QString escapeIdentifier(const QString &identifier, IdentifierType) const Q_DECL_OVERRIDE;
+
+protected:
+ bool beginTransaction() Q_DECL_OVERRIDE;
+ bool commitTransaction() Q_DECL_OVERRIDE;
+ bool rollbackTransaction() Q_DECL_OVERRIDE;
+};
+
+QT_END_NAMESPACE
+
+#endif // QSQL_OCI_H
diff --git a/src/plugins/sqldrivers/odbc/main.cpp b/src/plugins/sqldrivers/odbc/main.cpp
index 69ea7b1f8e..ac63941a82 100644
--- a/src/plugins/sqldrivers/odbc/main.cpp
+++ b/src/plugins/sqldrivers/odbc/main.cpp
@@ -39,7 +39,7 @@
#include <qsqldriverplugin.h>
#include <qstringlist.h>
-#include "../../../sql/drivers/odbc/qsql_odbc_p.h"
+#include "qsql_odbc_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/sqldrivers/odbc/odbc.pro b/src/plugins/sqldrivers/odbc/odbc.pro
index c0020c065f..17844f27d2 100644
--- a/src/plugins/sqldrivers/odbc/odbc.pro
+++ b/src/plugins/sqldrivers/odbc/odbc.pro
@@ -1,8 +1,12 @@
TARGET = qsqlodbc
-SOURCES = main.cpp
+HEADERS += $$PWD/qsql_odbc_p.h
+SOURCES += $$PWD/qsql_odbc.cpp $$PWD/main.cpp
+
+QMAKE_USE += odbc
+unix: DEFINES += UNICODE
+
OTHER_FILES += odbc.json
-include(../../../sql/drivers/odbc/qsql_odbc.pri)
PLUGIN_CLASS_NAME = QODBCDriverPlugin
include(../qsqldriverbase.pri)
diff --git a/src/plugins/sqldrivers/odbc/qsql_odbc.cpp b/src/plugins/sqldrivers/odbc/qsql_odbc.cpp
new file mode 100644
index 0000000000..59ef42d609
--- /dev/null
+++ b/src/plugins/sqldrivers/odbc/qsql_odbc.cpp
@@ -0,0 +1,2639 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsql_odbc_p.h"
+#include <qsqlrecord.h>
+
+#if defined (Q_OS_WIN32)
+#include <qt_windows.h>
+#endif
+#include <qcoreapplication.h>
+#include <qvariant.h>
+#include <qdatetime.h>
+#include <qsqlerror.h>
+#include <qsqlfield.h>
+#include <qsqlindex.h>
+#include <qstringlist.h>
+#include <qvarlengtharray.h>
+#include <qvector.h>
+#include <qmath.h>
+#include <QDebug>
+#include <QSqlQuery>
+#include <QtSql/private/qsqldriver_p.h>
+#include <QtSql/private/qsqlresult_p.h>
+
+QT_BEGIN_NAMESPACE
+
+// undefine this to prevent initial check of the ODBC driver
+#define ODBC_CHECK_DRIVER
+
+static const int COLNAMESIZE = 256;
+//Map Qt parameter types to ODBC types
+static const SQLSMALLINT qParamType[4] = { SQL_PARAM_INPUT, SQL_PARAM_INPUT, SQL_PARAM_OUTPUT, SQL_PARAM_INPUT_OUTPUT };
+
+inline static QString fromSQLTCHAR(const QVarLengthArray<SQLTCHAR>& input, int size=-1)
+{
+ QString result;
+
+ int realsize = qMin(size, input.size());
+ if(realsize > 0 && input[realsize-1] == 0)
+ realsize--;
+ switch(sizeof(SQLTCHAR)) {
+ case 1:
+ result=QString::fromUtf8((const char *)input.constData(), realsize);
+ break;
+ case 2:
+ result=QString::fromUtf16((const ushort *)input.constData(), realsize);
+ break;
+ case 4:
+ result=QString::fromUcs4((const uint *)input.constData(), realsize);
+ break;
+ default:
+ qCritical("sizeof(SQLTCHAR) is %d. Don't know how to handle this.", int(sizeof(SQLTCHAR)));
+ }
+ return result;
+}
+
+inline static QVarLengthArray<SQLTCHAR> toSQLTCHAR(const QString &input)
+{
+ QVarLengthArray<SQLTCHAR> result;
+ result.resize(input.size());
+ switch(sizeof(SQLTCHAR)) {
+ case 1:
+ memcpy(result.data(), input.toUtf8().data(), input.size());
+ break;
+ case 2:
+ memcpy(result.data(), input.unicode(), input.size() * 2);
+ break;
+ case 4:
+ memcpy(result.data(), input.toUcs4().data(), input.size() * 4);
+ break;
+ default:
+ qCritical("sizeof(SQLTCHAR) is %d. Don't know how to handle this.", int(sizeof(SQLTCHAR)));
+ }
+ result.append(0); // make sure it's null terminated, doesn't matter if it already is, it does if it isn't.
+ return result;
+}
+
+class QODBCDriverPrivate : public QSqlDriverPrivate
+{
+ Q_DECLARE_PUBLIC(QODBCDriver)
+
+public:
+ enum DefaultCase{Lower, Mixed, Upper, Sensitive};
+ QODBCDriverPrivate()
+ : QSqlDriverPrivate(), hEnv(0), hDbc(0), unicode(false), useSchema(false), disconnectCount(0), datetime_precision(19),
+ isFreeTDSDriver(false), hasSQLFetchScroll(true), hasMultiResultSets(false), isQuoteInitialized(false), quote(QLatin1Char('"'))
+ {
+ }
+
+ SQLHANDLE hEnv;
+ SQLHANDLE hDbc;
+
+ bool unicode;
+ bool useSchema;
+ int disconnectCount;
+ int datetime_precision;
+ bool isFreeTDSDriver;
+ bool hasSQLFetchScroll;
+ bool hasMultiResultSets;
+
+ bool checkDriver() const;
+ void checkUnicode();
+ void checkDBMS();
+ void checkHasSQLFetchScroll();
+ void checkHasMultiResults();
+ void checkSchemaUsage();
+ void checkDateTimePrecision();
+ bool setConnectionOptions(const QString& connOpts);
+ void splitTableQualifier(const QString &qualifier, QString &catalog,
+ QString &schema, QString &table);
+ DefaultCase defaultCase() const;
+ QString adjustCase(const QString&) const;
+ QChar quoteChar();
+private:
+ bool isQuoteInitialized;
+ QChar quote;
+};
+
+class QODBCResultPrivate;
+
+class QODBCResult: public QSqlResult
+{
+ Q_DECLARE_PRIVATE(QODBCResult)
+
+public:
+ QODBCResult(const QODBCDriver *db);
+ virtual ~QODBCResult();
+
+ bool prepare(const QString &query) Q_DECL_OVERRIDE;
+ bool exec() Q_DECL_OVERRIDE;
+
+ QVariant lastInsertId() const Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+protected:
+ bool fetchNext() Q_DECL_OVERRIDE;
+ bool fetchFirst() Q_DECL_OVERRIDE;
+ bool fetchLast() Q_DECL_OVERRIDE;
+ bool fetchPrevious() Q_DECL_OVERRIDE;
+ bool fetch(int i) Q_DECL_OVERRIDE;
+ bool reset(const QString &query) Q_DECL_OVERRIDE;
+ QVariant data(int field) Q_DECL_OVERRIDE;
+ bool isNull(int field) Q_DECL_OVERRIDE;
+ int size() Q_DECL_OVERRIDE;
+ int numRowsAffected() Q_DECL_OVERRIDE;
+ QSqlRecord record() const Q_DECL_OVERRIDE;
+ void virtual_hook(int id, void *data) Q_DECL_OVERRIDE;
+ void detachFromResultSet() Q_DECL_OVERRIDE;
+ bool nextResult() Q_DECL_OVERRIDE;
+};
+
+class QODBCResultPrivate: public QSqlResultPrivate
+{
+ Q_DECLARE_PUBLIC(QODBCResult)
+
+public:
+ Q_DECLARE_SQLDRIVER_PRIVATE(QODBCDriver)
+ QODBCResultPrivate(QODBCResult *q, const QODBCDriver *db)
+ : QSqlResultPrivate(q, db),
+ hStmt(0),
+ useSchema(false),
+ hasSQLFetchScroll(true)
+ {
+ unicode = drv_d_func()->unicode;
+ useSchema = drv_d_func()->useSchema;
+ disconnectCount = drv_d_func()->disconnectCount;
+ hasSQLFetchScroll = drv_d_func()->hasSQLFetchScroll;
+ }
+
+ inline void clearValues()
+ { fieldCache.fill(QVariant()); fieldCacheIdx = 0; }
+
+ SQLHANDLE dpEnv() const { return drv_d_func() ? drv_d_func()->hEnv : 0;}
+ SQLHANDLE dpDbc() const { return drv_d_func() ? drv_d_func()->hDbc : 0;}
+ SQLHANDLE hStmt;
+
+ bool unicode;
+ bool useSchema;
+
+ QSqlRecord rInf;
+ QVector<QVariant> fieldCache;
+ int fieldCacheIdx;
+ int disconnectCount;
+ bool hasSQLFetchScroll;
+
+ bool isStmtHandleValid();
+ void updateStmtHandleState();
+};
+
+bool QODBCResultPrivate::isStmtHandleValid()
+{
+ return disconnectCount == drv_d_func()->disconnectCount;
+}
+
+void QODBCResultPrivate::updateStmtHandleState()
+{
+ disconnectCount = drv_d_func()->disconnectCount;
+}
+
+static QString qWarnODBCHandle(int handleType, SQLHANDLE handle, int *nativeCode = 0)
+{
+ SQLINTEGER nativeCode_ = 0;
+ SQLSMALLINT msgLen = 0;
+ SQLRETURN r = SQL_NO_DATA;
+ SQLTCHAR state_[SQL_SQLSTATE_SIZE+1];
+ QVarLengthArray<SQLTCHAR> description_(SQL_MAX_MESSAGE_LENGTH);
+ QString result;
+ int i = 1;
+
+ description_[0] = 0;
+ do {
+ r = SQLGetDiagRec(handleType,
+ handle,
+ i,
+ state_,
+ &nativeCode_,
+ 0,
+ 0,
+ &msgLen);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && msgLen > 0)
+ description_.resize(msgLen+1);
+ r = SQLGetDiagRec(handleType,
+ handle,
+ i,
+ state_,
+ &nativeCode_,
+ description_.data(),
+ description_.size(),
+ &msgLen);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) {
+ if (nativeCode)
+ *nativeCode = nativeCode_;
+ const QString tmpstore = fromSQLTCHAR(description_, msgLen);
+ if(result != tmpstore) {
+ if(!result.isEmpty())
+ result += QLatin1Char(' ');
+ result += tmpstore;
+ }
+ } else if (r == SQL_ERROR || r == SQL_INVALID_HANDLE) {
+ return result;
+ }
+ ++i;
+ } while (r != SQL_NO_DATA);
+ return result;
+}
+
+static QString qODBCWarn(const SQLHANDLE hStmt, const SQLHANDLE envHandle = 0,
+ const SQLHANDLE pDbC = 0, int *nativeCode = 0)
+{
+ QString result;
+ if (envHandle)
+ result += qWarnODBCHandle(SQL_HANDLE_ENV, envHandle, nativeCode);
+ if (pDbC) {
+ const QString dMessage = qWarnODBCHandle(SQL_HANDLE_DBC, pDbC, nativeCode);
+ if (!dMessage.isEmpty()) {
+ if (!result.isEmpty())
+ result += QLatin1Char(' ');
+ result += dMessage;
+ }
+ }
+ if (hStmt) {
+ const QString hMessage = qWarnODBCHandle(SQL_HANDLE_STMT, hStmt, nativeCode);
+ if (!hMessage.isEmpty()) {
+ if (!result.isEmpty())
+ result += QLatin1Char(' ');
+ result += hMessage;
+ }
+ }
+ return result;
+}
+
+static QString qODBCWarn(const QODBCResultPrivate* odbc, int *nativeCode = 0)
+{
+ return qODBCWarn(odbc->hStmt, odbc->dpEnv(), odbc->dpDbc(), nativeCode);
+}
+
+static QString qODBCWarn(const QODBCDriverPrivate* odbc, int *nativeCode = 0)
+{
+ return qODBCWarn(0, odbc->hEnv, odbc->hDbc, nativeCode);
+}
+
+static void qSqlWarning(const QString& message, const QODBCResultPrivate* odbc)
+{
+ qWarning() << message << "\tError:" << qODBCWarn(odbc);
+}
+
+static void qSqlWarning(const QString &message, const QODBCDriverPrivate *odbc)
+{
+ qWarning() << message << "\tError:" << qODBCWarn(odbc);
+}
+
+static void qSqlWarning(const QString &message, const SQLHANDLE hStmt)
+{
+ qWarning() << message << "\tError:" << qODBCWarn(hStmt);
+}
+
+static QSqlError qMakeError(const QString& err, QSqlError::ErrorType type, const QODBCResultPrivate* p)
+{
+ int nativeCode = -1;
+ QString message = qODBCWarn(p, &nativeCode);
+ return QSqlError(QLatin1String("QODBC3: ") + err, message, type, nativeCode);
+}
+
+static QSqlError qMakeError(const QString& err, QSqlError::ErrorType type,
+ const QODBCDriverPrivate* p)
+{
+ int nativeCode = -1;
+ QString message = qODBCWarn(p, &nativeCode);
+ return QSqlError(QLatin1String("QODBC3: ") + err, qODBCWarn(p), type, nativeCode);
+}
+
+static QVariant::Type qDecodeODBCType(SQLSMALLINT sqltype, bool isSigned = true)
+{
+ QVariant::Type type = QVariant::Invalid;
+ switch (sqltype) {
+ case SQL_DECIMAL:
+ case SQL_NUMERIC:
+ case SQL_REAL:
+ case SQL_FLOAT:
+ case SQL_DOUBLE:
+ type = QVariant::Double;
+ break;
+ case SQL_SMALLINT:
+ case SQL_INTEGER:
+ case SQL_BIT:
+ type = isSigned ? QVariant::Int : QVariant::UInt;
+ break;
+ case SQL_TINYINT:
+ type = QVariant::UInt;
+ break;
+ case SQL_BIGINT:
+ type = isSigned ? QVariant::LongLong : QVariant::ULongLong;
+ break;
+ case SQL_BINARY:
+ case SQL_VARBINARY:
+ case SQL_LONGVARBINARY:
+ type = QVariant::ByteArray;
+ break;
+ case SQL_DATE:
+ case SQL_TYPE_DATE:
+ type = QVariant::Date;
+ break;
+ case SQL_TIME:
+ case SQL_TYPE_TIME:
+ type = QVariant::Time;
+ break;
+ case SQL_TIMESTAMP:
+ case SQL_TYPE_TIMESTAMP:
+ type = QVariant::DateTime;
+ break;
+ case SQL_WCHAR:
+ case SQL_WVARCHAR:
+ case SQL_WLONGVARCHAR:
+ type = QVariant::String;
+ break;
+ case SQL_CHAR:
+ case SQL_VARCHAR:
+#if (ODBCVER >= 0x0350)
+ case SQL_GUID:
+#endif
+ case SQL_LONGVARCHAR:
+ type = QVariant::String;
+ break;
+ default:
+ type = QVariant::ByteArray;
+ break;
+ }
+ return type;
+}
+
+static QString qGetStringData(SQLHANDLE hStmt, int column, int colSize, bool unicode = false)
+{
+ QString fieldVal;
+ SQLRETURN r = SQL_ERROR;
+ SQLLEN lengthIndicator = 0;
+
+ // NB! colSize must be a multiple of 2 for unicode enabled DBs
+ if (colSize <= 0) {
+ colSize = 256;
+ } else if (colSize > 65536) { // limit buffer size to 64 KB
+ colSize = 65536;
+ } else {
+ colSize++; // make sure there is room for more than the 0 termination
+ }
+ if(unicode) {
+ r = SQLGetData(hStmt,
+ column+1,
+ SQL_C_TCHAR,
+ NULL,
+ 0,
+ &lengthIndicator);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && lengthIndicator > 0)
+ colSize = int(lengthIndicator / sizeof(SQLTCHAR) + 1);
+ QVarLengthArray<SQLTCHAR> buf(colSize);
+ memset(buf.data(), 0, colSize*sizeof(SQLTCHAR));
+ while (true) {
+ r = SQLGetData(hStmt,
+ column+1,
+ SQL_C_TCHAR,
+ (SQLPOINTER)buf.data(),
+ colSize*sizeof(SQLTCHAR),
+ &lengthIndicator);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) {
+ if (lengthIndicator == SQL_NULL_DATA) {
+ fieldVal.clear();
+ break;
+ }
+ // starting with ODBC Native Client 2012, SQL_NO_TOTAL is returned
+ // instead of the length (which sometimes was wrong in older versions)
+ // see link for more info: http://msdn.microsoft.com/en-us/library/jj219209.aspx
+ // if length indicator equals SQL_NO_TOTAL, indicating that
+ // more data can be fetched, but size not known, collect data
+ // and fetch next block
+ if (lengthIndicator == SQL_NO_TOTAL) {
+ fieldVal += fromSQLTCHAR(buf, colSize);
+ continue;
+ }
+ // if SQL_SUCCESS_WITH_INFO is returned, indicating that
+ // more data can be fetched, the length indicator does NOT
+ // contain the number of bytes returned - it contains the
+ // total number of bytes that CAN be fetched
+ // colSize-1: remove 0 termination when there is more data to fetch
+ int rSize = (r == SQL_SUCCESS_WITH_INFO) ? colSize : int(lengthIndicator / sizeof(SQLTCHAR));
+ fieldVal += fromSQLTCHAR(buf, rSize);
+ if (lengthIndicator < SQLLEN(colSize*sizeof(SQLTCHAR))) {
+ // workaround for Drivermanagers that don't return SQL_NO_DATA
+ break;
+ }
+ } else if (r == SQL_NO_DATA) {
+ break;
+ } else {
+ qWarning() << "qGetStringData: Error while fetching data (" << qWarnODBCHandle(SQL_HANDLE_STMT, hStmt) << ')';
+ fieldVal.clear();
+ break;
+ }
+ }
+ } else {
+ r = SQLGetData(hStmt,
+ column+1,
+ SQL_C_CHAR,
+ NULL,
+ 0,
+ &lengthIndicator);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && lengthIndicator > 0)
+ colSize = lengthIndicator + 1;
+ QVarLengthArray<SQLCHAR> buf(colSize);
+ while (true) {
+ r = SQLGetData(hStmt,
+ column+1,
+ SQL_C_CHAR,
+ (SQLPOINTER)buf.data(),
+ colSize,
+ &lengthIndicator);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) {
+ if (lengthIndicator == SQL_NULL_DATA || lengthIndicator == SQL_NO_TOTAL) {
+ fieldVal.clear();
+ break;
+ }
+ // if SQL_SUCCESS_WITH_INFO is returned, indicating that
+ // more data can be fetched, the length indicator does NOT
+ // contain the number of bytes returned - it contains the
+ // total number of bytes that CAN be fetched
+ // colSize-1: remove 0 termination when there is more data to fetch
+ int rSize = (r == SQL_SUCCESS_WITH_INFO) ? colSize : lengthIndicator;
+ fieldVal += QString::fromUtf8((const char *)buf.constData(), rSize);
+ if (lengthIndicator < SQLLEN(colSize)) {
+ // workaround for Drivermanagers that don't return SQL_NO_DATA
+ break;
+ }
+ } else if (r == SQL_NO_DATA) {
+ break;
+ } else {
+ qWarning() << "qGetStringData: Error while fetching data (" << qWarnODBCHandle(SQL_HANDLE_STMT, hStmt) << ')';
+ fieldVal.clear();
+ break;
+ }
+ }
+ }
+ return fieldVal;
+}
+
+static QVariant qGetBinaryData(SQLHANDLE hStmt, int column)
+{
+ QByteArray fieldVal;
+ SQLSMALLINT colNameLen;
+ SQLSMALLINT colType;
+ SQLULEN colSize;
+ SQLSMALLINT colScale;
+ SQLSMALLINT nullable;
+ SQLLEN lengthIndicator = 0;
+ SQLRETURN r = SQL_ERROR;
+
+ QVarLengthArray<SQLTCHAR> colName(COLNAMESIZE);
+
+ r = SQLDescribeCol(hStmt,
+ column + 1,
+ colName.data(),
+ COLNAMESIZE,
+ &colNameLen,
+ &colType,
+ &colSize,
+ &colScale,
+ &nullable);
+ if (r != SQL_SUCCESS)
+ qWarning() << "qGetBinaryData: Unable to describe column" << column;
+ // SQLDescribeCol may return 0 if size cannot be determined
+ if (!colSize)
+ colSize = 255;
+ else if (colSize > 65536) // read the field in 64 KB chunks
+ colSize = 65536;
+ fieldVal.resize(colSize);
+ ulong read = 0;
+ while (true) {
+ r = SQLGetData(hStmt,
+ column+1,
+ SQL_C_BINARY,
+ const_cast<char *>(fieldVal.constData() + read),
+ colSize,
+ &lengthIndicator);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO)
+ break;
+ if (lengthIndicator == SQL_NULL_DATA)
+ return QVariant(QVariant::ByteArray);
+ if (lengthIndicator > SQLLEN(colSize) || lengthIndicator == SQL_NO_TOTAL) {
+ read += colSize;
+ colSize = 65536;
+ } else {
+ read += lengthIndicator;
+ }
+ if (r == SQL_SUCCESS) { // the whole field was read in one chunk
+ fieldVal.resize(read);
+ break;
+ }
+ fieldVal.resize(fieldVal.size() + colSize);
+ }
+ return fieldVal;
+}
+
+static QVariant qGetIntData(SQLHANDLE hStmt, int column, bool isSigned = true)
+{
+ SQLINTEGER intbuf = 0;
+ SQLLEN lengthIndicator = 0;
+ SQLRETURN r = SQLGetData(hStmt,
+ column+1,
+ isSigned ? SQL_C_SLONG : SQL_C_ULONG,
+ (SQLPOINTER)&intbuf,
+ sizeof(intbuf),
+ &lengthIndicator);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO)
+ return QVariant(QVariant::Invalid);
+ if (lengthIndicator == SQL_NULL_DATA)
+ return QVariant(QVariant::Int);
+ if (isSigned)
+ return int(intbuf);
+ else
+ return uint(intbuf);
+}
+
+static QVariant qGetDoubleData(SQLHANDLE hStmt, int column)
+{
+ SQLDOUBLE dblbuf;
+ SQLLEN lengthIndicator = 0;
+ SQLRETURN r = SQLGetData(hStmt,
+ column+1,
+ SQL_C_DOUBLE,
+ (SQLPOINTER) &dblbuf,
+ 0,
+ &lengthIndicator);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ return QVariant(QVariant::Invalid);
+ }
+ if(lengthIndicator == SQL_NULL_DATA)
+ return QVariant(QVariant::Double);
+
+ return (double) dblbuf;
+}
+
+
+static QVariant qGetBigIntData(SQLHANDLE hStmt, int column, bool isSigned = true)
+{
+ SQLBIGINT lngbuf = 0;
+ SQLLEN lengthIndicator = 0;
+ SQLRETURN r = SQLGetData(hStmt,
+ column+1,
+ isSigned ? SQL_C_SBIGINT : SQL_C_UBIGINT,
+ (SQLPOINTER) &lngbuf,
+ sizeof(lngbuf),
+ &lengthIndicator);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO)
+ return QVariant(QVariant::Invalid);
+ if (lengthIndicator == SQL_NULL_DATA)
+ return QVariant(QVariant::LongLong);
+
+ if (isSigned)
+ return qint64(lngbuf);
+ else
+ return quint64(lngbuf);
+}
+
+static bool isAutoValue(const SQLHANDLE hStmt, int column)
+{
+ SQLLEN nNumericAttribute = 0; // Check for auto-increment
+ const SQLRETURN r = ::SQLColAttribute(hStmt, column + 1, SQL_DESC_AUTO_UNIQUE_VALUE,
+ 0, 0, 0, &nNumericAttribute);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ qSqlWarning(QStringLiteral("qMakeField: Unable to get autovalue attribute for column ")
+ + QString::number(column), hStmt);
+ return false;
+ }
+ return nNumericAttribute != SQL_FALSE;
+}
+
+static QSqlField qMakeFieldInfo(const SQLHANDLE hStmt, int i, QString *errorMessage);
+
+// creates a QSqlField from a valid hStmt generated
+// by SQLColumns. The hStmt has to point to a valid position.
+static QSqlField qMakeFieldInfo(const SQLHANDLE hStmt, const QODBCDriverPrivate* p)
+{
+ QString fname = qGetStringData(hStmt, 3, -1, p->unicode);
+ int type = qGetIntData(hStmt, 4).toInt(); // column type
+ QSqlField f(fname, qDecodeODBCType(type, p));
+ QVariant var = qGetIntData(hStmt, 6);
+ f.setLength(var.isNull() ? -1 : var.toInt()); // column size
+ var = qGetIntData(hStmt, 8).toInt();
+ f.setPrecision(var.isNull() ? -1 : var.toInt()); // precision
+ f.setSqlType(type);
+ int required = qGetIntData(hStmt, 10).toInt(); // nullable-flag
+ // required can be SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
+ if (required == SQL_NO_NULLS)
+ f.setRequired(true);
+ else if (required == SQL_NULLABLE)
+ f.setRequired(false);
+ // else we don't know
+ return f;
+}
+
+static QSqlField qMakeFieldInfo(const QODBCResultPrivate* p, int i )
+{
+ QString errorMessage;
+ const QSqlField result = qMakeFieldInfo(p->hStmt, i, &errorMessage);
+ if (!errorMessage.isEmpty())
+ qSqlWarning(errorMessage, p);
+ return result;
+}
+
+static QSqlField qMakeFieldInfo(const SQLHANDLE hStmt, int i, QString *errorMessage)
+{
+ SQLSMALLINT colNameLen;
+ SQLSMALLINT colType;
+ SQLULEN colSize;
+ SQLSMALLINT colScale;
+ SQLSMALLINT nullable;
+ SQLRETURN r = SQL_ERROR;
+ QVarLengthArray<SQLTCHAR> colName(COLNAMESIZE);
+ errorMessage->clear();
+ r = SQLDescribeCol(hStmt,
+ i+1,
+ colName.data(),
+ (SQLSMALLINT)COLNAMESIZE,
+ &colNameLen,
+ &colType,
+ &colSize,
+ &colScale,
+ &nullable);
+
+ if (r != SQL_SUCCESS) {
+ *errorMessage = QStringLiteral("qMakeField: Unable to describe column ") + QString::number(i);
+ return QSqlField();
+ }
+
+ SQLLEN unsignedFlag = SQL_FALSE;
+ r = SQLColAttribute (hStmt,
+ i + 1,
+ SQL_DESC_UNSIGNED,
+ 0,
+ 0,
+ 0,
+ &unsignedFlag);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QStringLiteral("qMakeField: Unable to get column attributes for column ")
+ + QString::number(i), hStmt);
+ }
+
+ const QString qColName(fromSQLTCHAR(colName, colNameLen));
+ // nullable can be SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
+ QVariant::Type type = qDecodeODBCType(colType, unsignedFlag == SQL_FALSE);
+ QSqlField f(qColName, type);
+ f.setSqlType(colType);
+ f.setLength(colSize == 0 ? -1 : int(colSize));
+ f.setPrecision(colScale == 0 ? -1 : int(colScale));
+ if (nullable == SQL_NO_NULLS)
+ f.setRequired(true);
+ else if (nullable == SQL_NULLABLE)
+ f.setRequired(false);
+ // else we don't know
+ f.setAutoValue(isAutoValue(hStmt, i));
+ return f;
+}
+
+static size_t qGetODBCVersion(const QString &connOpts)
+{
+ if (connOpts.contains(QLatin1String("SQL_ATTR_ODBC_VERSION=SQL_OV_ODBC3"), Qt::CaseInsensitive))
+ return SQL_OV_ODBC3;
+ return SQL_OV_ODBC2;
+}
+
+QChar QODBCDriverPrivate::quoteChar()
+{
+ if (!isQuoteInitialized) {
+ SQLTCHAR driverResponse[4];
+ SQLSMALLINT length;
+ int r = SQLGetInfo(hDbc,
+ SQL_IDENTIFIER_QUOTE_CHAR,
+ &driverResponse,
+ sizeof(driverResponse),
+ &length);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO)
+ quote = QChar(driverResponse[0]);
+ else
+ quote = QLatin1Char('"');
+ isQuoteInitialized = true;
+ }
+ return quote;
+}
+
+
+bool QODBCDriverPrivate::setConnectionOptions(const QString& connOpts)
+{
+ // Set any connection attributes
+ const QStringList opts(connOpts.split(QLatin1Char(';'), QString::SkipEmptyParts));
+ SQLRETURN r = SQL_SUCCESS;
+ for (int i = 0; i < opts.count(); ++i) {
+ const QString tmp(opts.at(i));
+ int idx;
+ if ((idx = tmp.indexOf(QLatin1Char('='))) == -1) {
+ qWarning() << "QODBCDriver::open: Illegal connect option value '" << tmp << '\'';
+ continue;
+ }
+ const QString opt(tmp.left(idx));
+ const QString val(tmp.mid(idx + 1).simplified());
+ SQLUINTEGER v = 0;
+
+ r = SQL_SUCCESS;
+ if (opt.toUpper() == QLatin1String("SQL_ATTR_ACCESS_MODE")) {
+ if (val.toUpper() == QLatin1String("SQL_MODE_READ_ONLY")) {
+ v = SQL_MODE_READ_ONLY;
+ } else if (val.toUpper() == QLatin1String("SQL_MODE_READ_WRITE")) {
+ v = SQL_MODE_READ_WRITE;
+ } else {
+ qWarning() << "QODBCDriver::open: Unknown option value '" << val << '\'';
+ continue;
+ }
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_ACCESS_MODE, (SQLPOINTER) size_t(v), 0);
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_CONNECTION_TIMEOUT")) {
+ v = val.toUInt();
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER) size_t(v), 0);
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_LOGIN_TIMEOUT")) {
+ v = val.toUInt();
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_LOGIN_TIMEOUT, (SQLPOINTER) size_t(v), 0);
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_CURRENT_CATALOG")) {
+ val.utf16(); // 0 terminate
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_CURRENT_CATALOG,
+ toSQLTCHAR(val).data(),
+ val.length()*sizeof(SQLTCHAR));
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_METADATA_ID")) {
+ if (val.toUpper() == QLatin1String("SQL_TRUE")) {
+ v = SQL_TRUE;
+ } else if (val.toUpper() == QLatin1String("SQL_FALSE")) {
+ v = SQL_FALSE;
+ } else {
+ qWarning() << "QODBCDriver::open: Unknown option value '" << val << '\'';
+ continue;
+ }
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_METADATA_ID, (SQLPOINTER) size_t(v), 0);
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_PACKET_SIZE")) {
+ v = val.toUInt();
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_PACKET_SIZE, (SQLPOINTER) size_t(v), 0);
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_TRACEFILE")) {
+ val.utf16(); // 0 terminate
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_TRACEFILE,
+ toSQLTCHAR(val).data(),
+ val.length()*sizeof(SQLTCHAR));
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_TRACE")) {
+ if (val.toUpper() == QLatin1String("SQL_OPT_TRACE_OFF")) {
+ v = SQL_OPT_TRACE_OFF;
+ } else if (val.toUpper() == QLatin1String("SQL_OPT_TRACE_ON")) {
+ v = SQL_OPT_TRACE_ON;
+ } else {
+ qWarning() << "QODBCDriver::open: Unknown option value '" << val << '\'';
+ continue;
+ }
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_TRACE, (SQLPOINTER) size_t(v), 0);
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_CONNECTION_POOLING")) {
+ if (val == QLatin1String("SQL_CP_OFF"))
+ v = SQL_CP_OFF;
+ else if (val.toUpper() == QLatin1String("SQL_CP_ONE_PER_DRIVER"))
+ v = SQL_CP_ONE_PER_DRIVER;
+ else if (val.toUpper() == QLatin1String("SQL_CP_ONE_PER_HENV"))
+ v = SQL_CP_ONE_PER_HENV;
+ else if (val.toUpper() == QLatin1String("SQL_CP_DEFAULT"))
+ v = SQL_CP_DEFAULT;
+ else {
+ qWarning() << "QODBCDriver::open: Unknown option value '" << val << '\'';
+ continue;
+ }
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_CONNECTION_POOLING, (SQLPOINTER) size_t(v), 0);
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_CP_MATCH")) {
+ if (val.toUpper() == QLatin1String("SQL_CP_STRICT_MATCH"))
+ v = SQL_CP_STRICT_MATCH;
+ else if (val.toUpper() == QLatin1String("SQL_CP_RELAXED_MATCH"))
+ v = SQL_CP_RELAXED_MATCH;
+ else if (val.toUpper() == QLatin1String("SQL_CP_MATCH_DEFAULT"))
+ v = SQL_CP_MATCH_DEFAULT;
+ else {
+ qWarning() << "QODBCDriver::open: Unknown option value '" << val << '\'';
+ continue;
+ }
+ r = SQLSetConnectAttr(hDbc, SQL_ATTR_CP_MATCH, (SQLPOINTER) size_t(v), 0);
+ } else if (opt.toUpper() == QLatin1String("SQL_ATTR_ODBC_VERSION")) {
+ // Already handled in QODBCDriver::open()
+ continue;
+ } else {
+ qWarning() << "QODBCDriver::open: Unknown connection attribute '" << opt << '\'';
+ }
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO)
+ qSqlWarning(QString::fromLatin1("QODBCDriver::open: Unable to set connection attribute'%1'").arg(
+ opt), this);
+ }
+ return true;
+}
+
+void QODBCDriverPrivate::splitTableQualifier(const QString & qualifier, QString &catalog,
+ QString &schema, QString &table)
+{
+ if (!useSchema) {
+ table = qualifier;
+ return;
+ }
+ QStringList l = qualifier.split(QLatin1Char('.'));
+ if (l.count() > 3)
+ return; // can't possibly be a valid table qualifier
+ int i = 0, n = l.count();
+ if (n == 1) {
+ table = qualifier;
+ } else {
+ for (QStringList::Iterator it = l.begin(); it != l.end(); ++it) {
+ if (n == 3) {
+ if (i == 0) {
+ catalog = *it;
+ } else if (i == 1) {
+ schema = *it;
+ } else if (i == 2) {
+ table = *it;
+ }
+ } else if (n == 2) {
+ if (i == 0) {
+ schema = *it;
+ } else if (i == 1) {
+ table = *it;
+ }
+ }
+ i++;
+ }
+ }
+}
+
+QODBCDriverPrivate::DefaultCase QODBCDriverPrivate::defaultCase() const
+{
+ DefaultCase ret;
+ SQLUSMALLINT casing;
+ int r = SQLGetInfo(hDbc,
+ SQL_IDENTIFIER_CASE,
+ &casing,
+ sizeof(casing),
+ NULL);
+ if ( r != SQL_SUCCESS)
+ ret = Mixed;//arbitrary case if driver cannot be queried
+ else {
+ switch (casing) {
+ case (SQL_IC_UPPER):
+ ret = Upper;
+ break;
+ case (SQL_IC_LOWER):
+ ret = Lower;
+ break;
+ case (SQL_IC_SENSITIVE):
+ ret = Sensitive;
+ break;
+ case (SQL_IC_MIXED):
+ default:
+ ret = Mixed;
+ break;
+ }
+ }
+ return ret;
+}
+
+/*
+ Adjust the casing of an identifier to match what the
+ database engine would have done to it.
+*/
+QString QODBCDriverPrivate::adjustCase(const QString &identifier) const
+{
+ QString ret = identifier;
+ switch(defaultCase()) {
+ case (Lower):
+ ret = identifier.toLower();
+ break;
+ case (Upper):
+ ret = identifier.toUpper();
+ break;
+ case(Mixed):
+ case(Sensitive):
+ default:
+ ret = identifier;
+ }
+ return ret;
+}
+
+////////////////////////////////////////////////////////////////////////////
+
+QODBCResult::QODBCResult(const QODBCDriver *db)
+ : QSqlResult(*new QODBCResultPrivate(this, db))
+{
+}
+
+QODBCResult::~QODBCResult()
+{
+ Q_D(QODBCResult);
+ if (d->hStmt && d->isStmtHandleValid() && driver()->isOpen()) {
+ SQLRETURN r = SQLFreeHandle(SQL_HANDLE_STMT, d->hStmt);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QODBCDriver: Unable to free statement handle ")
+ + QString::number(r), d);
+ }
+}
+
+bool QODBCResult::reset (const QString& query)
+{
+ Q_D(QODBCResult);
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+ d->rInf.clear();
+ d->fieldCache.clear();
+ d->fieldCacheIdx = 0;
+
+ // Always reallocate the statement handle - the statement attributes
+ // are not reset if SQLFreeStmt() is called which causes some problems.
+ SQLRETURN r;
+ if (d->hStmt && d->isStmtHandleValid()) {
+ r = SQLFreeHandle(SQL_HANDLE_STMT, d->hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCResult::reset: Unable to free statement handle"), d);
+ return false;
+ }
+ }
+ r = SQLAllocHandle(SQL_HANDLE_STMT,
+ d->dpDbc(),
+ &d->hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCResult::reset: Unable to allocate statement handle"), d);
+ return false;
+ }
+
+ d->updateStmtHandleState();
+
+ if (isForwardOnly()) {
+ r = SQLSetStmtAttr(d->hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER)SQL_CURSOR_FORWARD_ONLY,
+ SQL_IS_UINTEGER);
+ } else {
+ r = SQLSetStmtAttr(d->hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER)SQL_CURSOR_STATIC,
+ SQL_IS_UINTEGER);
+ }
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "QODBCResult::reset: Unable to set 'SQL_CURSOR_STATIC' as statement attribute. "
+ "Please check your ODBC driver configuration"), QSqlError::StatementError, d));
+ return false;
+ }
+
+ r = SQLExecDirect(d->hStmt,
+ toSQLTCHAR(query).data(),
+ (SQLINTEGER) query.length());
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO && r!= SQL_NO_DATA) {
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to execute statement"), QSqlError::StatementError, d));
+ return false;
+ }
+
+ SQLULEN isScrollable = 0;
+ r = SQLGetStmtAttr(d->hStmt, SQL_ATTR_CURSOR_SCROLLABLE, &isScrollable, SQL_IS_INTEGER, 0);
+ if(r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO)
+ setForwardOnly(isScrollable == SQL_NONSCROLLABLE);
+
+ SQLSMALLINT count = 0;
+ SQLNumResultCols(d->hStmt, &count);
+ if (count) {
+ setSelect(true);
+ for (int i = 0; i < count; ++i) {
+ d->rInf.append(qMakeFieldInfo(d, i));
+ }
+ d->fieldCache.resize(count);
+ } else {
+ setSelect(false);
+ }
+ setActive(true);
+
+ return true;
+}
+
+bool QODBCResult::fetch(int i)
+{
+ Q_D(QODBCResult);
+ if (!driver()->isOpen())
+ return false;
+
+ if (isForwardOnly() && i < at())
+ return false;
+ if (i == at())
+ return true;
+ d->clearValues();
+ int actualIdx = i + 1;
+ if (actualIdx <= 0) {
+ setAt(QSql::BeforeFirstRow);
+ return false;
+ }
+ SQLRETURN r;
+ if (isForwardOnly()) {
+ bool ok = true;
+ while (ok && i > at())
+ ok = fetchNext();
+ return ok;
+ } else {
+ r = SQLFetchScroll(d->hStmt,
+ SQL_FETCH_ABSOLUTE,
+ actualIdx);
+ }
+ if (r != SQL_SUCCESS) {
+ if (r != SQL_NO_DATA)
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to fetch"), QSqlError::ConnectionError, d));
+ return false;
+ }
+ setAt(i);
+ return true;
+}
+
+bool QODBCResult::fetchNext()
+{
+ Q_D(QODBCResult);
+ SQLRETURN r;
+ d->clearValues();
+
+ if (d->hasSQLFetchScroll)
+ r = SQLFetchScroll(d->hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ else
+ r = SQLFetch(d->hStmt);
+
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ if (r != SQL_NO_DATA)
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to fetch next"), QSqlError::ConnectionError, d));
+ return false;
+ }
+ setAt(at() + 1);
+ return true;
+}
+
+bool QODBCResult::fetchFirst()
+{
+ Q_D(QODBCResult);
+ if (isForwardOnly() && at() != QSql::BeforeFirstRow)
+ return false;
+ SQLRETURN r;
+ d->clearValues();
+ if (isForwardOnly()) {
+ return fetchNext();
+ }
+ r = SQLFetchScroll(d->hStmt,
+ SQL_FETCH_FIRST,
+ 0);
+ if (r != SQL_SUCCESS) {
+ if (r != SQL_NO_DATA)
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to fetch first"), QSqlError::ConnectionError, d));
+ return false;
+ }
+ setAt(0);
+ return true;
+}
+
+bool QODBCResult::fetchPrevious()
+{
+ Q_D(QODBCResult);
+ if (isForwardOnly())
+ return false;
+ SQLRETURN r;
+ d->clearValues();
+ r = SQLFetchScroll(d->hStmt,
+ SQL_FETCH_PRIOR,
+ 0);
+ if (r != SQL_SUCCESS) {
+ if (r != SQL_NO_DATA)
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to fetch previous"), QSqlError::ConnectionError, d));
+ return false;
+ }
+ setAt(at() - 1);
+ return true;
+}
+
+bool QODBCResult::fetchLast()
+{
+ Q_D(QODBCResult);
+ SQLRETURN r;
+ d->clearValues();
+
+ if (isForwardOnly()) {
+ // cannot seek to last row in forwardOnly mode, so we have to use brute force
+ int i = at();
+ if (i == QSql::AfterLastRow)
+ return false;
+ if (i == QSql::BeforeFirstRow)
+ i = 0;
+ while (fetchNext())
+ ++i;
+ setAt(i);
+ return true;
+ }
+
+ r = SQLFetchScroll(d->hStmt,
+ SQL_FETCH_LAST,
+ 0);
+ if (r != SQL_SUCCESS) {
+ if (r != SQL_NO_DATA)
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to fetch last"), QSqlError::ConnectionError, d));
+ return false;
+ }
+ SQLULEN currRow = 0;
+ r = SQLGetStmtAttr(d->hStmt,
+ SQL_ROW_NUMBER,
+ &currRow,
+ SQL_IS_INTEGER,
+ 0);
+ if (r != SQL_SUCCESS)
+ return false;
+ setAt(currRow-1);
+ return true;
+}
+
+QVariant QODBCResult::data(int field)
+{
+ Q_D(QODBCResult);
+ if (field >= d->rInf.count() || field < 0) {
+ qWarning() << "QODBCResult::data: column" << field << "out of range";
+ return QVariant();
+ }
+ if (field < d->fieldCacheIdx)
+ return d->fieldCache.at(field);
+
+ SQLRETURN r(0);
+ SQLLEN lengthIndicator = 0;
+
+ for (int i = d->fieldCacheIdx; i <= field; ++i) {
+ // some servers do not support fetching column n after we already
+ // fetched column n+1, so cache all previous columns here
+ const QSqlField info = d->rInf.field(i);
+ switch (info.type()) {
+ case QVariant::LongLong:
+ d->fieldCache[i] = qGetBigIntData(d->hStmt, i);
+ break;
+ case QVariant::ULongLong:
+ d->fieldCache[i] = qGetBigIntData(d->hStmt, i, false);
+ break;
+ case QVariant::Int:
+ d->fieldCache[i] = qGetIntData(d->hStmt, i);
+ break;
+ case QVariant::UInt:
+ d->fieldCache[i] = qGetIntData(d->hStmt, i, false);
+ break;
+ case QVariant::Date:
+ DATE_STRUCT dbuf;
+ r = SQLGetData(d->hStmt,
+ i + 1,
+ SQL_C_DATE,
+ (SQLPOINTER)&dbuf,
+ 0,
+ &lengthIndicator);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && (lengthIndicator != SQL_NULL_DATA))
+ d->fieldCache[i] = QVariant(QDate(dbuf.year, dbuf.month, dbuf.day));
+ else
+ d->fieldCache[i] = QVariant(QVariant::Date);
+ break;
+ case QVariant::Time:
+ TIME_STRUCT tbuf;
+ r = SQLGetData(d->hStmt,
+ i + 1,
+ SQL_C_TIME,
+ (SQLPOINTER)&tbuf,
+ 0,
+ &lengthIndicator);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && (lengthIndicator != SQL_NULL_DATA))
+ d->fieldCache[i] = QVariant(QTime(tbuf.hour, tbuf.minute, tbuf.second));
+ else
+ d->fieldCache[i] = QVariant(QVariant::Time);
+ break;
+ case QVariant::DateTime:
+ TIMESTAMP_STRUCT dtbuf;
+ r = SQLGetData(d->hStmt,
+ i + 1,
+ SQL_C_TIMESTAMP,
+ (SQLPOINTER)&dtbuf,
+ 0,
+ &lengthIndicator);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && (lengthIndicator != SQL_NULL_DATA))
+ d->fieldCache[i] = QVariant(QDateTime(QDate(dtbuf.year, dtbuf.month, dtbuf.day),
+ QTime(dtbuf.hour, dtbuf.minute, dtbuf.second, dtbuf.fraction / 1000000)));
+ else
+ d->fieldCache[i] = QVariant(QVariant::DateTime);
+ break;
+ case QVariant::ByteArray:
+ d->fieldCache[i] = qGetBinaryData(d->hStmt, i);
+ break;
+ case QVariant::String:
+ d->fieldCache[i] = qGetStringData(d->hStmt, i, info.length(), d->unicode);
+ break;
+ case QVariant::Double:
+ switch(numericalPrecisionPolicy()) {
+ case QSql::LowPrecisionInt32:
+ d->fieldCache[i] = qGetIntData(d->hStmt, i);
+ break;
+ case QSql::LowPrecisionInt64:
+ d->fieldCache[i] = qGetBigIntData(d->hStmt, i);
+ break;
+ case QSql::LowPrecisionDouble:
+ d->fieldCache[i] = qGetDoubleData(d->hStmt, i);
+ break;
+ case QSql::HighPrecision:
+ d->fieldCache[i] = qGetStringData(d->hStmt, i, info.length(), false);
+ break;
+ }
+ break;
+ default:
+ d->fieldCache[i] = QVariant(qGetStringData(d->hStmt, i, info.length(), false));
+ break;
+ }
+ d->fieldCacheIdx = field + 1;
+ }
+ return d->fieldCache[field];
+}
+
+bool QODBCResult::isNull(int field)
+{
+ Q_D(const QODBCResult);
+ if (field < 0 || field > d->fieldCache.size())
+ return true;
+ if (field <= d->fieldCacheIdx) {
+ // since there is no good way to find out whether the value is NULL
+ // without fetching the field we'll fetch it here.
+ // (data() also sets the NULL flag)
+ data(field);
+ }
+ return d->fieldCache.at(field).isNull();
+}
+
+int QODBCResult::size()
+{
+ return -1;
+}
+
+int QODBCResult::numRowsAffected()
+{
+ Q_D(QODBCResult);
+ SQLLEN affectedRowCount = 0;
+ SQLRETURN r = SQLRowCount(d->hStmt, &affectedRowCount);
+ if (r == SQL_SUCCESS)
+ return affectedRowCount;
+ else
+ qSqlWarning(QLatin1String("QODBCResult::numRowsAffected: Unable to count affected rows"), d);
+ return -1;
+}
+
+bool QODBCResult::prepare(const QString& query)
+{
+ Q_D(QODBCResult);
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+ SQLRETURN r;
+
+ d->rInf.clear();
+ if (d->hStmt && d->isStmtHandleValid()) {
+ r = SQLFreeHandle(SQL_HANDLE_STMT, d->hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCResult::prepare: Unable to close statement"), d);
+ return false;
+ }
+ }
+ r = SQLAllocHandle(SQL_HANDLE_STMT,
+ d->dpDbc(),
+ &d->hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCResult::prepare: Unable to allocate statement handle"), d);
+ return false;
+ }
+
+ d->updateStmtHandleState();
+
+ if (isForwardOnly()) {
+ r = SQLSetStmtAttr(d->hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER)SQL_CURSOR_FORWARD_ONLY,
+ SQL_IS_UINTEGER);
+ } else {
+ r = SQLSetStmtAttr(d->hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER)SQL_CURSOR_STATIC,
+ SQL_IS_UINTEGER);
+ }
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "QODBCResult::reset: Unable to set 'SQL_CURSOR_STATIC' as statement attribute. "
+ "Please check your ODBC driver configuration"), QSqlError::StatementError, d));
+ return false;
+ }
+
+ r = SQLPrepare(d->hStmt,
+ toSQLTCHAR(query).data(),
+ (SQLINTEGER) query.length());
+
+ if (r != SQL_SUCCESS) {
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to prepare statement"), QSqlError::StatementError, d));
+ return false;
+ }
+ return true;
+}
+
+bool QODBCResult::exec()
+{
+ Q_D(QODBCResult);
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+ d->rInf.clear();
+ d->fieldCache.clear();
+ d->fieldCacheIdx = 0;
+
+ if (!d->hStmt) {
+ qSqlWarning(QLatin1String("QODBCResult::exec: No statement handle available"), d);
+ return false;
+ }
+
+ if (isSelect())
+ SQLCloseCursor(d->hStmt);
+
+ QVector<QVariant>& values = boundValues();
+ QVector<QByteArray> tmpStorage(values.count(), QByteArray()); // holds temporary buffers
+ QVarLengthArray<SQLLEN, 32> indicators(values.count());
+ memset(indicators.data(), 0, indicators.size() * sizeof(SQLLEN));
+
+ // bind parameters - only positional binding allowed
+ int i;
+ SQLRETURN r;
+ for (i = 0; i < values.count(); ++i) {
+ if (bindValueType(i) & QSql::Out)
+ values[i].detach();
+ const QVariant &val = values.at(i);
+ SQLLEN *ind = &indicators[i];
+ if (val.isNull())
+ *ind = SQL_NULL_DATA;
+ switch (val.type()) {
+ case QVariant::Date: {
+ QByteArray &ba = tmpStorage[i];
+ ba.resize(sizeof(DATE_STRUCT));
+ DATE_STRUCT *dt = (DATE_STRUCT *)const_cast<char *>(ba.constData());
+ QDate qdt = val.toDate();
+ dt->year = qdt.year();
+ dt->month = qdt.month();
+ dt->day = qdt.day();
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_DATE,
+ SQL_DATE,
+ 0,
+ 0,
+ (void *) dt,
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break; }
+ case QVariant::Time: {
+ QByteArray &ba = tmpStorage[i];
+ ba.resize(sizeof(TIME_STRUCT));
+ TIME_STRUCT *dt = (TIME_STRUCT *)const_cast<char *>(ba.constData());
+ QTime qdt = val.toTime();
+ dt->hour = qdt.hour();
+ dt->minute = qdt.minute();
+ dt->second = qdt.second();
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_TIME,
+ SQL_TIME,
+ 0,
+ 0,
+ (void *) dt,
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break; }
+ case QVariant::DateTime: {
+ QByteArray &ba = tmpStorage[i];
+ ba.resize(sizeof(TIMESTAMP_STRUCT));
+ TIMESTAMP_STRUCT * dt = (TIMESTAMP_STRUCT *)const_cast<char *>(ba.constData());
+ QDateTime qdt = val.toDateTime();
+ dt->year = qdt.date().year();
+ dt->month = qdt.date().month();
+ dt->day = qdt.date().day();
+ dt->hour = qdt.time().hour();
+ dt->minute = qdt.time().minute();
+ dt->second = qdt.time().second();
+
+ int precision = d->drv_d_func()->datetime_precision - 20; // (20 includes a separating period)
+ if (precision <= 0) {
+ dt->fraction = 0;
+ } else {
+ dt->fraction = qdt.time().msec() * 1000000;
+
+ // (How many leading digits do we want to keep? With SQL Server 2005, this should be 3: 123000000)
+ int keep = (int)qPow(10.0, 9 - qMin(9, precision));
+ dt->fraction = (dt->fraction / keep) * keep;
+ }
+
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_TIMESTAMP,
+ SQL_TIMESTAMP,
+ d->drv_d_func()->datetime_precision,
+ precision,
+ (void *) dt,
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break; }
+ case QVariant::Int:
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_SLONG,
+ SQL_INTEGER,
+ 0,
+ 0,
+ const_cast<void *>(val.constData()),
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break;
+ case QVariant::UInt:
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_ULONG,
+ SQL_NUMERIC,
+ 15,
+ 0,
+ const_cast<void *>(val.constData()),
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break;
+ case QVariant::Double:
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_DOUBLE,
+ SQL_DOUBLE,
+ 0,
+ 0,
+ const_cast<void *>(val.constData()),
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break;
+ case QVariant::LongLong:
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_SBIGINT,
+ SQL_BIGINT,
+ 0,
+ 0,
+ const_cast<void *>(val.constData()),
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break;
+ case QVariant::ULongLong:
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_UBIGINT,
+ SQL_BIGINT,
+ 0,
+ 0,
+ const_cast<void *>(val.constData()),
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break;
+ case QVariant::ByteArray:
+ if (*ind != SQL_NULL_DATA) {
+ *ind = val.toByteArray().size();
+ }
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_BINARY,
+ SQL_LONGVARBINARY,
+ val.toByteArray().size(),
+ 0,
+ const_cast<char *>(val.toByteArray().constData()),
+ val.toByteArray().size(),
+ ind);
+ break;
+ case QVariant::Bool:
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_BIT,
+ SQL_BIT,
+ 0,
+ 0,
+ const_cast<void *>(val.constData()),
+ 0,
+ *ind == SQL_NULL_DATA ? ind : NULL);
+ break;
+ case QVariant::String:
+ if (d->unicode) {
+ QByteArray &ba = tmpStorage[i];
+ QString str = val.toString();
+ if (*ind != SQL_NULL_DATA)
+ *ind = str.length() * sizeof(SQLTCHAR);
+ int strSize = str.length() * sizeof(SQLTCHAR);
+
+ if (bindValueType(i) & QSql::Out) {
+ const QVarLengthArray<SQLTCHAR> a(toSQLTCHAR(str));
+ ba = QByteArray((const char *)a.constData(), a.size() * sizeof(SQLTCHAR));
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_TCHAR,
+ strSize > 254 ? SQL_WLONGVARCHAR : SQL_WVARCHAR,
+ 0, // god knows... don't change this!
+ 0,
+ ba.data(),
+ ba.size(),
+ ind);
+ break;
+ }
+ ba = QByteArray ((const char *)toSQLTCHAR(str).constData(), str.size()*sizeof(SQLTCHAR));
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_TCHAR,
+ strSize > 254 ? SQL_WLONGVARCHAR : SQL_WVARCHAR,
+ strSize,
+ 0,
+ const_cast<char *>(ba.constData()),
+ ba.size(),
+ ind);
+ break;
+ }
+ else
+ {
+ QByteArray &str = tmpStorage[i];
+ str = val.toString().toUtf8();
+ if (*ind != SQL_NULL_DATA)
+ *ind = str.length();
+ int strSize = str.length();
+
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_CHAR,
+ strSize > 254 ? SQL_LONGVARCHAR : SQL_VARCHAR,
+ strSize,
+ 0,
+ const_cast<char *>(str.constData()),
+ strSize,
+ ind);
+ break;
+ }
+ // fall through
+ default: {
+ QByteArray &ba = tmpStorage[i];
+ if (*ind != SQL_NULL_DATA)
+ *ind = ba.size();
+ r = SQLBindParameter(d->hStmt,
+ i + 1,
+ qParamType[bindValueType(i) & QSql::InOut],
+ SQL_C_BINARY,
+ SQL_VARBINARY,
+ ba.length() + 1,
+ 0,
+ const_cast<char *>(ba.constData()),
+ ba.length() + 1,
+ ind);
+ break; }
+ }
+ if (r != SQL_SUCCESS) {
+ qWarning() << "QODBCResult::exec: unable to bind variable:" << qODBCWarn(d);
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to bind variable"), QSqlError::StatementError, d));
+ return false;
+ }
+ }
+ r = SQLExecute(d->hStmt);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO && r != SQL_NO_DATA) {
+ qWarning() << "QODBCResult::exec: Unable to execute statement:" << qODBCWarn(d);
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to execute statement"), QSqlError::StatementError, d));
+ return false;
+ }
+
+ SQLULEN isScrollable = 0;
+ r = SQLGetStmtAttr(d->hStmt, SQL_ATTR_CURSOR_SCROLLABLE, &isScrollable, SQL_IS_INTEGER, 0);
+ if(r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO)
+ setForwardOnly(isScrollable == SQL_NONSCROLLABLE);
+
+ SQLSMALLINT count = 0;
+ SQLNumResultCols(d->hStmt, &count);
+ if (count) {
+ setSelect(true);
+ for (int i = 0; i < count; ++i) {
+ d->rInf.append(qMakeFieldInfo(d, i));
+ }
+ d->fieldCache.resize(count);
+ } else {
+ setSelect(false);
+ }
+ setActive(true);
+
+
+ //get out parameters
+ if (!hasOutValues())
+ return true;
+
+ for (i = 0; i < values.count(); ++i) {
+ switch (values.at(i).type()) {
+ case QVariant::Date: {
+ DATE_STRUCT ds = *((DATE_STRUCT *)const_cast<char *>(tmpStorage.at(i).constData()));
+ values[i] = QVariant(QDate(ds.year, ds.month, ds.day));
+ break; }
+ case QVariant::Time: {
+ TIME_STRUCT dt = *((TIME_STRUCT *)const_cast<char *>(tmpStorage.at(i).constData()));
+ values[i] = QVariant(QTime(dt.hour, dt.minute, dt.second));
+ break; }
+ case QVariant::DateTime: {
+ TIMESTAMP_STRUCT dt = *((TIMESTAMP_STRUCT*)
+ const_cast<char *>(tmpStorage.at(i).constData()));
+ values[i] = QVariant(QDateTime(QDate(dt.year, dt.month, dt.day),
+ QTime(dt.hour, dt.minute, dt.second, dt.fraction / 1000000)));
+ break; }
+ case QVariant::Bool:
+ case QVariant::Int:
+ case QVariant::UInt:
+ case QVariant::Double:
+ case QVariant::ByteArray:
+ case QVariant::LongLong:
+ case QVariant::ULongLong:
+ //nothing to do
+ break;
+ case QVariant::String:
+ if (d->unicode) {
+ if (bindValueType(i) & QSql::Out) {
+ const QByteArray &first = tmpStorage.at(i);
+ QVarLengthArray<SQLTCHAR> array;
+ array.append((const SQLTCHAR *)first.constData(), first.size());
+ values[i] = fromSQLTCHAR(array, first.size()/sizeof(SQLTCHAR));
+ }
+ break;
+ }
+ // fall through
+ default: {
+ if (bindValueType(i) & QSql::Out)
+ values[i] = tmpStorage.at(i);
+ break; }
+ }
+ if (indicators[i] == SQL_NULL_DATA)
+ values[i] = QVariant(values[i].type());
+ }
+ return true;
+}
+
+QSqlRecord QODBCResult::record() const
+{
+ Q_D(const QODBCResult);
+ if (!isActive() || !isSelect())
+ return QSqlRecord();
+ return d->rInf;
+}
+
+QVariant QODBCResult::lastInsertId() const
+{
+ Q_D(const QODBCResult);
+ QString sql;
+
+ switch (driver()->dbmsType()) {
+ case QSqlDriver::MSSqlServer:
+ case QSqlDriver::Sybase:
+ sql = QLatin1String("SELECT @@IDENTITY;");
+ break;
+ case QSqlDriver::MySqlServer:
+ sql = QLatin1String("SELECT LAST_INSERT_ID();");
+ break;
+ case QSqlDriver::PostgreSQL:
+ sql = QLatin1String("SELECT lastval();");
+ break;
+ default:
+ break;
+ }
+
+ if (!sql.isEmpty()) {
+ QSqlQuery qry(driver()->createResult());
+ if (qry.exec(sql) && qry.next())
+ return qry.value(0);
+
+ qSqlWarning(QLatin1String("QODBCResult::lastInsertId: Unable to get lastInsertId"), d);
+ } else {
+ qSqlWarning(QLatin1String("QODBCResult::lastInsertId: not implemented for this DBMS"), d);
+ }
+
+ return QVariant();
+}
+
+QVariant QODBCResult::handle() const
+{
+ Q_D(const QODBCResult);
+ return QVariant(qRegisterMetaType<SQLHANDLE>("SQLHANDLE"), &d->hStmt);
+}
+
+bool QODBCResult::nextResult()
+{
+ Q_D(QODBCResult);
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+ d->rInf.clear();
+ d->fieldCache.clear();
+ d->fieldCacheIdx = 0;
+ setSelect(false);
+
+ SQLRETURN r = SQLMoreResults(d->hStmt);
+ if (r != SQL_SUCCESS) {
+ if (r == SQL_SUCCESS_WITH_INFO) {
+ int nativeCode = -1;
+ QString message = qODBCWarn(d, &nativeCode);
+ qWarning() << "QODBCResult::nextResult():" << message;
+ } else {
+ if (r != SQL_NO_DATA)
+ setLastError(qMakeError(QCoreApplication::translate("QODBCResult",
+ "Unable to fetch last"), QSqlError::ConnectionError, d));
+ return false;
+ }
+ }
+
+ SQLSMALLINT count = 0;
+ SQLNumResultCols(d->hStmt, &count);
+ if (count) {
+ setSelect(true);
+ for (int i = 0; i < count; ++i) {
+ d->rInf.append(qMakeFieldInfo(d, i));
+ }
+ d->fieldCache.resize(count);
+ } else {
+ setSelect(false);
+ }
+ setActive(true);
+
+ return true;
+}
+
+void QODBCResult::virtual_hook(int id, void *data)
+{
+ QSqlResult::virtual_hook(id, data);
+}
+
+void QODBCResult::detachFromResultSet()
+{
+ Q_D(QODBCResult);
+ if (d->hStmt)
+ SQLCloseCursor(d->hStmt);
+}
+
+////////////////////////////////////////
+
+
+QODBCDriver::QODBCDriver(QObject *parent)
+ : QSqlDriver(*new QODBCDriverPrivate, parent)
+{
+}
+
+QODBCDriver::QODBCDriver(SQLHANDLE env, SQLHANDLE con, QObject *parent)
+ : QSqlDriver(*new QODBCDriverPrivate, parent)
+{
+ Q_D(QODBCDriver);
+ d->hEnv = env;
+ d->hDbc = con;
+ if (env && con) {
+ setOpen(true);
+ setOpenError(false);
+ }
+}
+
+QODBCDriver::~QODBCDriver()
+{
+ cleanup();
+}
+
+bool QODBCDriver::hasFeature(DriverFeature f) const
+{
+ Q_D(const QODBCDriver);
+ switch (f) {
+ case Transactions: {
+ if (!d->hDbc)
+ return false;
+ SQLUSMALLINT txn;
+ SQLSMALLINT t;
+ int r = SQLGetInfo(d->hDbc,
+ (SQLUSMALLINT)SQL_TXN_CAPABLE,
+ &txn,
+ sizeof(txn),
+ &t);
+ if (r != SQL_SUCCESS || txn == SQL_TC_NONE)
+ return false;
+ else
+ return true;
+ }
+ case Unicode:
+ return d->unicode;
+ case PreparedQueries:
+ case PositionalPlaceholders:
+ case FinishQuery:
+ case LowPrecisionNumbers:
+ return true;
+ case QuerySize:
+ case NamedPlaceholders:
+ case BatchOperations:
+ case SimpleLocking:
+ case EventNotifications:
+ case CancelQuery:
+ return false;
+ case LastInsertId:
+ return (d->dbmsType == MSSqlServer)
+ || (d->dbmsType == Sybase)
+ || (d->dbmsType == MySqlServer)
+ || (d->dbmsType == PostgreSQL);
+ case MultipleResultSets:
+ return d->hasMultiResultSets;
+ case BLOB: {
+ if (d->dbmsType == MySqlServer)
+ return true;
+ else
+ return false;
+ }
+ }
+ return false;
+}
+
+bool QODBCDriver::open(const QString & db,
+ const QString & user,
+ const QString & password,
+ const QString &,
+ int,
+ const QString& connOpts)
+{
+ Q_D(QODBCDriver);
+ if (isOpen())
+ close();
+ SQLRETURN r;
+ r = SQLAllocHandle(SQL_HANDLE_ENV,
+ SQL_NULL_HANDLE,
+ &d->hEnv);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ qSqlWarning(QLatin1String("QODBCDriver::open: Unable to allocate environment"), d);
+ setOpenError(true);
+ return false;
+ }
+ r = SQLSetEnvAttr(d->hEnv,
+ SQL_ATTR_ODBC_VERSION,
+ (SQLPOINTER)qGetODBCVersion(connOpts),
+ SQL_IS_UINTEGER);
+ r = SQLAllocHandle(SQL_HANDLE_DBC,
+ d->hEnv,
+ &d->hDbc);
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ qSqlWarning(QLatin1String("QODBCDriver::open: Unable to allocate connection"), d);
+ setOpenError(true);
+ cleanup();
+ return false;
+ }
+
+ if (!d->setConnectionOptions(connOpts)) {
+ cleanup();
+ return false;
+ }
+
+ // Create the connection string
+ QString connQStr;
+ // support the "DRIVER={SQL SERVER};SERVER=blah" syntax
+ if (db.contains(QLatin1String(".dsn"), Qt::CaseInsensitive))
+ connQStr = QLatin1String("FILEDSN=") + db;
+ else if (db.contains(QLatin1String("DRIVER="), Qt::CaseInsensitive)
+ || db.contains(QLatin1String("SERVER="), Qt::CaseInsensitive))
+ connQStr = db;
+ else
+ connQStr = QLatin1String("DSN=") + db;
+
+ if (!user.isEmpty())
+ connQStr += QLatin1String(";UID=") + user;
+ if (!password.isEmpty())
+ connQStr += QLatin1String(";PWD=") + password;
+
+ SQLSMALLINT cb;
+ QVarLengthArray<SQLTCHAR> connOut(1024);
+ memset(connOut.data(), 0, connOut.size() * sizeof(SQLTCHAR));
+ r = SQLDriverConnect(d->hDbc,
+ NULL,
+ toSQLTCHAR(connQStr).data(),
+ (SQLSMALLINT)connQStr.length(),
+ connOut.data(),
+ 1024,
+ &cb,
+ /*SQL_DRIVER_NOPROMPT*/0);
+
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) {
+ setLastError(qMakeError(tr("Unable to connect"), QSqlError::ConnectionError, d));
+ setOpenError(true);
+ cleanup();
+ return false;
+ }
+
+ if (!d->checkDriver()) {
+ setLastError(qMakeError(tr("Unable to connect - Driver doesn't support all "
+ "functionality required"), QSqlError::ConnectionError, d));
+ setOpenError(true);
+ cleanup();
+ return false;
+ }
+
+ d->checkUnicode();
+ d->checkSchemaUsage();
+ d->checkDBMS();
+ d->checkHasSQLFetchScroll();
+ d->checkHasMultiResults();
+ d->checkDateTimePrecision();
+ setOpen(true);
+ setOpenError(false);
+ if (d->dbmsType == MSSqlServer) {
+ QSqlQuery i(createResult());
+ i.exec(QLatin1String("SET QUOTED_IDENTIFIER ON"));
+ }
+ return true;
+}
+
+void QODBCDriver::close()
+{
+ cleanup();
+ setOpen(false);
+ setOpenError(false);
+}
+
+void QODBCDriver::cleanup()
+{
+ Q_D(QODBCDriver);
+ SQLRETURN r;
+
+ if(d->hDbc) {
+ // Open statements/descriptors handles are automatically cleaned up by SQLDisconnect
+ if (isOpen()) {
+ r = SQLDisconnect(d->hDbc);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QODBCDriver::disconnect: Unable to disconnect datasource"), d);
+ else
+ d->disconnectCount++;
+ }
+
+ r = SQLFreeHandle(SQL_HANDLE_DBC, d->hDbc);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QODBCDriver::cleanup: Unable to free connection handle"), d);
+ d->hDbc = 0;
+ }
+
+ if (d->hEnv) {
+ r = SQLFreeHandle(SQL_HANDLE_ENV, d->hEnv);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QODBCDriver::cleanup: Unable to free environment handle"), d);
+ d->hEnv = 0;
+ }
+}
+
+// checks whether the server can return char, varchar and longvarchar
+// as two byte unicode characters
+void QODBCDriverPrivate::checkUnicode()
+{
+ SQLRETURN r;
+ SQLUINTEGER fFunc;
+
+ unicode = false;
+ r = SQLGetInfo(hDbc,
+ SQL_CONVERT_CHAR,
+ (SQLPOINTER)&fFunc,
+ sizeof(fFunc),
+ NULL);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && (fFunc & SQL_CVT_WCHAR)) {
+ unicode = true;
+ return;
+ }
+
+ r = SQLGetInfo(hDbc,
+ SQL_CONVERT_VARCHAR,
+ (SQLPOINTER)&fFunc,
+ sizeof(fFunc),
+ NULL);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && (fFunc & SQL_CVT_WVARCHAR)) {
+ unicode = true;
+ return;
+ }
+
+ r = SQLGetInfo(hDbc,
+ SQL_CONVERT_LONGVARCHAR,
+ (SQLPOINTER)&fFunc,
+ sizeof(fFunc),
+ NULL);
+ if ((r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) && (fFunc & SQL_CVT_WLONGVARCHAR)) {
+ unicode = true;
+ return;
+ }
+ SQLHANDLE hStmt;
+ r = SQLAllocHandle(SQL_HANDLE_STMT,
+ hDbc,
+ &hStmt);
+
+ r = SQLExecDirect(hStmt, toSQLTCHAR(QLatin1String("select 'test'")).data(), SQL_NTS);
+ if(r == SQL_SUCCESS) {
+ r = SQLFetch(hStmt);
+ if(r == SQL_SUCCESS) {
+ QVarLengthArray<SQLWCHAR> buffer(10);
+ r = SQLGetData(hStmt, 1, SQL_C_WCHAR, buffer.data(), buffer.size() * sizeof(SQLWCHAR), NULL);
+ if(r == SQL_SUCCESS && fromSQLTCHAR(buffer) == QLatin1String("test")) {
+ unicode = true;
+ }
+ }
+ }
+ r = SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
+}
+
+bool QODBCDriverPrivate::checkDriver() const
+{
+#ifdef ODBC_CHECK_DRIVER
+ static const SQLUSMALLINT reqFunc[] = {
+ SQL_API_SQLDESCRIBECOL, SQL_API_SQLGETDATA, SQL_API_SQLCOLUMNS,
+ SQL_API_SQLGETSTMTATTR, SQL_API_SQLGETDIAGREC, SQL_API_SQLEXECDIRECT,
+ SQL_API_SQLGETINFO, SQL_API_SQLTABLES, 0
+ };
+
+ // these functions are optional
+ static const SQLUSMALLINT optFunc[] = {
+ SQL_API_SQLNUMRESULTCOLS, SQL_API_SQLROWCOUNT, 0
+ };
+
+ SQLRETURN r;
+ SQLUSMALLINT sup;
+
+ int i;
+ // check the required functions
+ for (i = 0; reqFunc[i] != 0; ++i) {
+
+ r = SQLGetFunctions(hDbc, reqFunc[i], &sup);
+
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCDriver::checkDriver: Cannot get list of supported functions"), this);
+ return false;
+ }
+ if (sup == SQL_FALSE) {
+ qWarning () << "QODBCDriver::open: Warning - Driver doesn't support all needed functionality (" << reqFunc[i] <<
+ ").\nPlease look at the Qt SQL Module Driver documentation for more information.";
+ return false;
+ }
+ }
+
+ // these functions are optional and just generate a warning
+ for (i = 0; optFunc[i] != 0; ++i) {
+
+ r = SQLGetFunctions(hDbc, optFunc[i], &sup);
+
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCDriver::checkDriver: Cannot get list of supported functions"), this);
+ return false;
+ }
+ if (sup == SQL_FALSE) {
+ qWarning() << "QODBCDriver::checkDriver: Warning - Driver doesn't support some non-critical functions (" << optFunc[i] << ')';
+ return true;
+ }
+ }
+#endif //ODBC_CHECK_DRIVER
+
+ return true;
+}
+
+void QODBCDriverPrivate::checkSchemaUsage()
+{
+ SQLRETURN r;
+ SQLUINTEGER val;
+
+ r = SQLGetInfo(hDbc,
+ SQL_SCHEMA_USAGE,
+ (SQLPOINTER) &val,
+ sizeof(val),
+ NULL);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO)
+ useSchema = (val != 0);
+}
+
+void QODBCDriverPrivate::checkDBMS()
+{
+ SQLRETURN r;
+ QVarLengthArray<SQLTCHAR> serverString(200);
+ SQLSMALLINT t;
+ memset(serverString.data(), 0, serverString.size() * sizeof(SQLTCHAR));
+
+ r = SQLGetInfo(hDbc,
+ SQL_DBMS_NAME,
+ serverString.data(),
+ SQLSMALLINT(serverString.size() * sizeof(SQLTCHAR)),
+ &t);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) {
+ const QString serverType = fromSQLTCHAR(serverString, t / sizeof(SQLTCHAR));
+ if (serverType.contains(QLatin1String("PostgreSQL"), Qt::CaseInsensitive))
+ dbmsType = QSqlDriver::PostgreSQL;
+ else if (serverType.contains(QLatin1String("Oracle"), Qt::CaseInsensitive))
+ dbmsType = QSqlDriver::Oracle;
+ else if (serverType.contains(QLatin1String("MySql"), Qt::CaseInsensitive))
+ dbmsType = QSqlDriver::MySqlServer;
+ else if (serverType.contains(QLatin1String("Microsoft SQL Server"), Qt::CaseInsensitive))
+ dbmsType = QSqlDriver::MSSqlServer;
+ else if (serverType.contains(QLatin1String("Sybase"), Qt::CaseInsensitive))
+ dbmsType = QSqlDriver::Sybase;
+ }
+ r = SQLGetInfo(hDbc,
+ SQL_DRIVER_NAME,
+ serverString.data(),
+ SQLSMALLINT(serverString.size() * sizeof(SQLTCHAR)),
+ &t);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) {
+ const QString serverType = fromSQLTCHAR(serverString, t / sizeof(SQLTCHAR));
+ isFreeTDSDriver = serverType.contains(QLatin1String("tdsodbc"), Qt::CaseInsensitive);
+ unicode = unicode && !isFreeTDSDriver;
+ }
+}
+
+void QODBCDriverPrivate::checkHasSQLFetchScroll()
+{
+ SQLUSMALLINT sup;
+ SQLRETURN r = SQLGetFunctions(hDbc, SQL_API_SQLFETCHSCROLL, &sup);
+ if ((r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) || sup != SQL_TRUE) {
+ hasSQLFetchScroll = false;
+ qWarning("QODBCDriver::checkHasSQLFetchScroll: Warning - Driver doesn't support scrollable result sets, use forward only mode for queries");
+ }
+}
+
+void QODBCDriverPrivate::checkHasMultiResults()
+{
+ QVarLengthArray<SQLTCHAR> driverResponse(2);
+ SQLSMALLINT length;
+ SQLRETURN r = SQLGetInfo(hDbc,
+ SQL_MULT_RESULT_SETS,
+ driverResponse.data(),
+ SQLSMALLINT(driverResponse.size() * sizeof(SQLTCHAR)),
+ &length);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO)
+ hasMultiResultSets = fromSQLTCHAR(driverResponse, length/sizeof(SQLTCHAR)).startsWith(QLatin1Char('Y'));
+}
+
+void QODBCDriverPrivate::checkDateTimePrecision()
+{
+ SQLINTEGER columnSize;
+ SQLHANDLE hStmt;
+
+ SQLRETURN r = SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt);
+ if (r != SQL_SUCCESS) {
+ return;
+ }
+
+ r = SQLGetTypeInfo(hStmt, SQL_TIMESTAMP);
+ if (r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO) {
+ r = SQLFetch(hStmt);
+ if ( r == SQL_SUCCESS || r == SQL_SUCCESS_WITH_INFO )
+ {
+ if (SQLGetData(hStmt, 3, SQL_INTEGER, &columnSize, sizeof(columnSize), 0) == SQL_SUCCESS) {
+ datetime_precision = (int)columnSize;
+ }
+ }
+ }
+ SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
+}
+
+QSqlResult *QODBCDriver::createResult() const
+{
+ return new QODBCResult(this);
+}
+
+bool QODBCDriver::beginTransaction()
+{
+ Q_D(QODBCDriver);
+ if (!isOpen()) {
+ qWarning("QODBCDriver::beginTransaction: Database not open");
+ return false;
+ }
+ SQLUINTEGER ac(SQL_AUTOCOMMIT_OFF);
+ SQLRETURN r = SQLSetConnectAttr(d->hDbc,
+ SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER)size_t(ac),
+ sizeof(ac));
+ if (r != SQL_SUCCESS) {
+ setLastError(qMakeError(tr("Unable to disable autocommit"),
+ QSqlError::TransactionError, d));
+ return false;
+ }
+ return true;
+}
+
+bool QODBCDriver::commitTransaction()
+{
+ Q_D(QODBCDriver);
+ if (!isOpen()) {
+ qWarning("QODBCDriver::commitTransaction: Database not open");
+ return false;
+ }
+ SQLRETURN r = SQLEndTran(SQL_HANDLE_DBC,
+ d->hDbc,
+ SQL_COMMIT);
+ if (r != SQL_SUCCESS) {
+ setLastError(qMakeError(tr("Unable to commit transaction"),
+ QSqlError::TransactionError, d));
+ return false;
+ }
+ return endTrans();
+}
+
+bool QODBCDriver::rollbackTransaction()
+{
+ Q_D(QODBCDriver);
+ if (!isOpen()) {
+ qWarning("QODBCDriver::rollbackTransaction: Database not open");
+ return false;
+ }
+ SQLRETURN r = SQLEndTran(SQL_HANDLE_DBC,
+ d->hDbc,
+ SQL_ROLLBACK);
+ if (r != SQL_SUCCESS) {
+ setLastError(qMakeError(tr("Unable to rollback transaction"),
+ QSqlError::TransactionError, d));
+ return false;
+ }
+ return endTrans();
+}
+
+bool QODBCDriver::endTrans()
+{
+ Q_D(QODBCDriver);
+ SQLUINTEGER ac(SQL_AUTOCOMMIT_ON);
+ SQLRETURN r = SQLSetConnectAttr(d->hDbc,
+ SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER)size_t(ac),
+ sizeof(ac));
+ if (r != SQL_SUCCESS) {
+ setLastError(qMakeError(tr("Unable to enable autocommit"), QSqlError::TransactionError, d));
+ return false;
+ }
+ return true;
+}
+
+QStringList QODBCDriver::tables(QSql::TableType type) const
+{
+ Q_D(const QODBCDriver);
+ QStringList tl;
+ if (!isOpen())
+ return tl;
+ SQLHANDLE hStmt;
+
+ SQLRETURN r = SQLAllocHandle(SQL_HANDLE_STMT,
+ d->hDbc,
+ &hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCDriver::tables: Unable to allocate handle"), d);
+ return tl;
+ }
+ r = SQLSetStmtAttr(hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER)SQL_CURSOR_FORWARD_ONLY,
+ SQL_IS_UINTEGER);
+ QStringList tableType;
+ if (type & QSql::Tables)
+ tableType += QLatin1String("TABLE");
+ if (type & QSql::Views)
+ tableType += QLatin1String("VIEW");
+ if (type & QSql::SystemTables)
+ tableType += QLatin1String("SYSTEM TABLE");
+ if (tableType.isEmpty())
+ return tl;
+
+ QString joinedTableTypeString = tableType.join(QLatin1Char(','));
+
+ r = SQLTables(hStmt,
+ NULL,
+ 0,
+ NULL,
+ 0,
+ NULL,
+ 0,
+ toSQLTCHAR(joinedTableTypeString).data(),
+ joinedTableTypeString.length() /* characters, not bytes */);
+
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QODBCDriver::tables Unable to execute table list"), d);
+
+ if (d->hasSQLFetchScroll)
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ else
+ r = SQLFetch(hStmt);
+
+ if (r != SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO && r != SQL_NO_DATA) {
+ qWarning() << "QODBCDriver::tables failed to retrieve table/view list: (" << r << "," << qWarnODBCHandle(SQL_HANDLE_STMT, hStmt) << ")";
+ return QStringList();
+ }
+
+ while (r == SQL_SUCCESS) {
+ QString fieldVal = qGetStringData(hStmt, 2, -1, false);
+ tl.append(fieldVal);
+
+ if (d->hasSQLFetchScroll)
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ else
+ r = SQLFetch(hStmt);
+ }
+
+ r = SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
+ if (r!= SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QODBCDriver: Unable to free statement handle") + QString::number(r), d);
+ return tl;
+}
+
+QSqlIndex QODBCDriver::primaryIndex(const QString& tablename) const
+{
+ Q_D(const QODBCDriver);
+ QSqlIndex index(tablename);
+ if (!isOpen())
+ return index;
+ bool usingSpecialColumns = false;
+ QSqlRecord rec = record(tablename);
+
+ SQLHANDLE hStmt;
+ SQLRETURN r = SQLAllocHandle(SQL_HANDLE_STMT,
+ d->hDbc,
+ &hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCDriver::primaryIndex: Unable to list primary key"), d);
+ return index;
+ }
+ QString catalog, schema, table;
+ const_cast<QODBCDriverPrivate*>(d)->splitTableQualifier(tablename, catalog, schema, table);
+
+ if (isIdentifierEscaped(catalog, QSqlDriver::TableName))
+ catalog = stripDelimiters(catalog, QSqlDriver::TableName);
+ else
+ catalog = d->adjustCase(catalog);
+
+ if (isIdentifierEscaped(schema, QSqlDriver::TableName))
+ schema = stripDelimiters(schema, QSqlDriver::TableName);
+ else
+ schema = d->adjustCase(schema);
+
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+ else
+ table = d->adjustCase(table);
+
+ r = SQLSetStmtAttr(hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER)SQL_CURSOR_FORWARD_ONLY,
+ SQL_IS_UINTEGER);
+ r = SQLPrimaryKeys(hStmt,
+ catalog.length() == 0 ? NULL : toSQLTCHAR(catalog).data(),
+ catalog.length(),
+ schema.length() == 0 ? NULL : toSQLTCHAR(schema).data(),
+ schema.length(),
+ toSQLTCHAR(table).data(),
+ table.length() /* in characters, not in bytes */);
+
+ // if the SQLPrimaryKeys() call does not succeed (e.g the driver
+ // does not support it) - try an alternative method to get hold of
+ // the primary index (e.g MS Access and FoxPro)
+ if (r != SQL_SUCCESS) {
+ r = SQLSpecialColumns(hStmt,
+ SQL_BEST_ROWID,
+ catalog.length() == 0 ? NULL : toSQLTCHAR(catalog).data(),
+ catalog.length(),
+ schema.length() == 0 ? NULL : toSQLTCHAR(schema).data(),
+ schema.length(),
+ toSQLTCHAR(table).data(),
+ table.length(),
+ SQL_SCOPE_CURROW,
+ SQL_NULLABLE);
+
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCDriver::primaryIndex: Unable to execute primary key list"), d);
+ } else {
+ usingSpecialColumns = true;
+ }
+ }
+
+ if (d->hasSQLFetchScroll)
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ else
+ r = SQLFetch(hStmt);
+
+ int fakeId = 0;
+ QString cName, idxName;
+ // Store all fields in a StringList because some drivers can't detail fields in this FETCH loop
+ while (r == SQL_SUCCESS) {
+ if (usingSpecialColumns) {
+ cName = qGetStringData(hStmt, 1, -1, d->unicode); // column name
+ idxName = QString::number(fakeId++); // invent a fake index name
+ } else {
+ cName = qGetStringData(hStmt, 3, -1, d->unicode); // column name
+ idxName = qGetStringData(hStmt, 5, -1, d->unicode); // pk index name
+ }
+ index.append(rec.field(cName));
+ index.setName(idxName);
+
+ if (d->hasSQLFetchScroll)
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ else
+ r = SQLFetch(hStmt);
+
+ }
+ r = SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
+ if (r!= SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QODBCDriver: Unable to free statement handle") + QString::number(r), d);
+ return index;
+}
+
+QSqlRecord QODBCDriver::record(const QString& tablename) const
+{
+ Q_D(const QODBCDriver);
+ QSqlRecord fil;
+ if (!isOpen())
+ return fil;
+
+ SQLHANDLE hStmt;
+ QString catalog, schema, table;
+ const_cast<QODBCDriverPrivate*>(d)->splitTableQualifier(tablename, catalog, schema, table);
+
+ if (isIdentifierEscaped(catalog, QSqlDriver::TableName))
+ catalog = stripDelimiters(catalog, QSqlDriver::TableName);
+ else
+ catalog = d->adjustCase(catalog);
+
+ if (isIdentifierEscaped(schema, QSqlDriver::TableName))
+ schema = stripDelimiters(schema, QSqlDriver::TableName);
+ else
+ schema = d->adjustCase(schema);
+
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+ else
+ table = d->adjustCase(table);
+
+ SQLRETURN r = SQLAllocHandle(SQL_HANDLE_STMT,
+ d->hDbc,
+ &hStmt);
+ if (r != SQL_SUCCESS) {
+ qSqlWarning(QLatin1String("QODBCDriver::record: Unable to allocate handle"), d);
+ return fil;
+ }
+ r = SQLSetStmtAttr(hStmt,
+ SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER)SQL_CURSOR_FORWARD_ONLY,
+ SQL_IS_UINTEGER);
+ r = SQLColumns(hStmt,
+ catalog.length() == 0 ? NULL : toSQLTCHAR(catalog).data(),
+ catalog.length(),
+ schema.length() == 0 ? NULL : toSQLTCHAR(schema).data(),
+ schema.length(),
+ toSQLTCHAR(table).data(),
+ table.length(),
+ NULL,
+ 0);
+ if (r != SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QODBCDriver::record: Unable to execute column list"), d);
+
+ if (d->hasSQLFetchScroll)
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ else
+ r = SQLFetch(hStmt);
+
+ // Store all fields in a StringList because some drivers can't detail fields in this FETCH loop
+ while (r == SQL_SUCCESS) {
+
+ fil.append(qMakeFieldInfo(hStmt, d));
+
+ if (d->hasSQLFetchScroll)
+ r = SQLFetchScroll(hStmt,
+ SQL_FETCH_NEXT,
+ 0);
+ else
+ r = SQLFetch(hStmt);
+ }
+
+ r = SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
+ if (r!= SQL_SUCCESS)
+ qSqlWarning(QLatin1String("QODBCDriver: Unable to free statement handle ") + QString::number(r), d);
+
+ return fil;
+}
+
+QString QODBCDriver::formatValue(const QSqlField &field,
+ bool trimStrings) const
+{
+ QString r;
+ if (field.isNull()) {
+ r = QLatin1String("NULL");
+ } else if (field.type() == QVariant::DateTime) {
+ // Use an escape sequence for the datetime fields
+ if (field.value().toDateTime().isValid()){
+ QDate dt = field.value().toDateTime().date();
+ QTime tm = field.value().toDateTime().time();
+ // Dateformat has to be "yyyy-MM-dd hh:mm:ss", with leading zeroes if month or day < 10
+ r = QLatin1String("{ ts '") +
+ QString::number(dt.year()) + QLatin1Char('-') +
+ QString::number(dt.month()).rightJustified(2, QLatin1Char('0'), true) +
+ QLatin1Char('-') +
+ QString::number(dt.day()).rightJustified(2, QLatin1Char('0'), true) +
+ QLatin1Char(' ') +
+ tm.toString() +
+ QLatin1String("' }");
+ } else
+ r = QLatin1String("NULL");
+ } else if (field.type() == QVariant::ByteArray) {
+ QByteArray ba = field.value().toByteArray();
+ QString res;
+ static const char hexchars[] = "0123456789abcdef";
+ for (int i = 0; i < ba.size(); ++i) {
+ uchar s = (uchar) ba[i];
+ res += QLatin1Char(hexchars[s >> 4]);
+ res += QLatin1Char(hexchars[s & 0x0f]);
+ }
+ r = QLatin1String("0x") + res;
+ } else {
+ r = QSqlDriver::formatValue(field, trimStrings);
+ }
+ return r;
+}
+
+QVariant QODBCDriver::handle() const
+{
+ Q_D(const QODBCDriver);
+ return QVariant(qRegisterMetaType<SQLHANDLE>("SQLHANDLE"), &d->hDbc);
+}
+
+QString QODBCDriver::escapeIdentifier(const QString &identifier, IdentifierType) const
+{
+ Q_D(const QODBCDriver);
+ QChar quote = const_cast<QODBCDriverPrivate*>(d)->quoteChar();
+ QString res = identifier;
+ if(!identifier.isEmpty() && !identifier.startsWith(quote) && !identifier.endsWith(quote) ) {
+ res.replace(quote, QString(quote)+QString(quote));
+ res.prepend(quote).append(quote);
+ res.replace(QLatin1Char('.'), QString(quote)+QLatin1Char('.')+QString(quote));
+ }
+ return res;
+}
+
+bool QODBCDriver::isIdentifierEscaped(const QString &identifier, IdentifierType) const
+{
+ Q_D(const QODBCDriver);
+ QChar quote = const_cast<QODBCDriverPrivate*>(d)->quoteChar();
+ return identifier.size() > 2
+ && identifier.startsWith(quote) //left delimited
+ && identifier.endsWith(quote); //right delimited
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/sqldrivers/odbc/qsql_odbc_p.h b/src/plugins/sqldrivers/odbc/qsql_odbc_p.h
new file mode 100644
index 0000000000..f4ce8bc243
--- /dev/null
+++ b/src/plugins/sqldrivers/odbc/qsql_odbc_p.h
@@ -0,0 +1,127 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSQL_ODBC_H
+#define QSQL_ODBC_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtSql/qsqldriver.h>
+
+#if defined (Q_OS_WIN32)
+#include <QtCore/qt_windows.h>
+#endif
+
+#ifdef QT_PLUGIN
+#define Q_EXPORT_SQLDRIVER_ODBC
+#else
+#define Q_EXPORT_SQLDRIVER_ODBC Q_SQL_EXPORT
+#endif
+
+#ifdef Q_OS_UNIX
+#define HAVE_LONG_LONG 1 // force UnixODBC NOT to fall back to a struct for BIGINTs
+#endif
+
+#if defined(Q_CC_BOR)
+// workaround for Borland to make sure that SQLBIGINT is defined
+# define _MSC_VER 900
+#endif
+#include <sql.h>
+#if defined(Q_CC_BOR)
+# undef _MSC_VER
+#endif
+
+#include <sqlext.h>
+
+QT_BEGIN_NAMESPACE
+
+class QODBCDriverPrivate;
+
+class Q_EXPORT_SQLDRIVER_ODBC QODBCDriver : public QSqlDriver
+{
+ Q_DECLARE_PRIVATE(QODBCDriver)
+ Q_OBJECT
+ friend class QODBCResultPrivate;
+
+public:
+ explicit QODBCDriver(QObject *parent=0);
+ QODBCDriver(SQLHANDLE env, SQLHANDLE con, QObject * parent=0);
+ virtual ~QODBCDriver();
+ bool hasFeature(DriverFeature f) const Q_DECL_OVERRIDE;
+ void close() Q_DECL_OVERRIDE;
+ QSqlResult *createResult() const Q_DECL_OVERRIDE;
+ QStringList tables(QSql::TableType) const Q_DECL_OVERRIDE;
+ QSqlRecord record(const QString &tablename) const Q_DECL_OVERRIDE;
+ QSqlIndex primaryIndex(const QString &tablename) const Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+ QString formatValue(const QSqlField &field,
+ bool trimStrings) const Q_DECL_OVERRIDE;
+ bool open(const QString &db,
+ const QString &user,
+ const QString &password,
+ const QString &host,
+ int port,
+ const QString &connOpts) Q_DECL_OVERRIDE;
+
+ QString escapeIdentifier(const QString &identifier, IdentifierType type) const Q_DECL_OVERRIDE;
+
+ bool isIdentifierEscaped(const QString &identifier, IdentifierType type) const Q_DECL_OVERRIDE;
+
+protected:
+ bool beginTransaction() Q_DECL_OVERRIDE;
+ bool commitTransaction() Q_DECL_OVERRIDE;
+ bool rollbackTransaction() Q_DECL_OVERRIDE;
+
+private:
+ bool endTrans();
+ void cleanup();
+};
+
+QT_END_NAMESPACE
+
+#endif // QSQL_ODBC_H
diff --git a/src/plugins/sqldrivers/psql/main.cpp b/src/plugins/sqldrivers/psql/main.cpp
index eae1c1c554..7657fcbfdf 100644
--- a/src/plugins/sqldrivers/psql/main.cpp
+++ b/src/plugins/sqldrivers/psql/main.cpp
@@ -39,7 +39,7 @@
#include <qsqldriverplugin.h>
#include <qstringlist.h>
-#include "../../../sql/drivers/psql/qsql_psql_p.h"
+#include "qsql_psql_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/sqldrivers/psql/psql.pro b/src/plugins/sqldrivers/psql/psql.pro
index 0fabe0e616..c44a6319c3 100644
--- a/src/plugins/sqldrivers/psql/psql.pro
+++ b/src/plugins/sqldrivers/psql/psql.pro
@@ -1,8 +1,11 @@
TARGET = qsqlpsql
-SOURCES = main.cpp
+HEADERS += $$PWD/qsql_psql_p.h
+SOURCES += $$PWD/qsql_psql.cpp $$PWD/main.cpp
+
+QMAKE_USE += psql
+
OTHER_FILES += psql.json
-include(../../../sql/drivers/psql/qsql_psql.pri)
PLUGIN_CLASS_NAME = QPSQLDriverPlugin
include(../qsqldriverbase.pri)
diff --git a/src/plugins/sqldrivers/psql/qsql_psql.cpp b/src/plugins/sqldrivers/psql/qsql_psql.cpp
new file mode 100644
index 0000000000..968b71a27d
--- /dev/null
+++ b/src/plugins/sqldrivers/psql/qsql_psql.cpp
@@ -0,0 +1,1508 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsql_psql_p.h"
+
+#include <qcoreapplication.h>
+#include <qvariant.h>
+#include <qdatetime.h>
+#include <qregexp.h>
+#include <qsqlerror.h>
+#include <qsqlfield.h>
+#include <qsqlindex.h>
+#include <qsqlrecord.h>
+#include <qsqlquery.h>
+#include <qsocketnotifier.h>
+#include <qstringlist.h>
+#include <qmutex.h>
+#include <QtSql/private/qsqlresult_p.h>
+#include <QtSql/private/qsqldriver_p.h>
+
+#include <libpq-fe.h>
+#include <pg_config.h>
+
+#include <stdlib.h>
+#include <math.h>
+// below code taken from an example at http://www.gnu.org/software/hello/manual/autoconf/Function-Portability.html
+#ifndef isnan
+ # define isnan(x) \
+ (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
+ : sizeof (x) == sizeof (double) ? isnan_d (x) \
+ : isnan_f (x))
+ static inline int isnan_f (float x) { return x != x; }
+ static inline int isnan_d (double x) { return x != x; }
+ static inline int isnan_ld (long double x) { return x != x; }
+#endif
+
+#ifndef isinf
+ # define isinf(x) \
+ (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
+ : sizeof (x) == sizeof (double) ? isinf_d (x) \
+ : isinf_f (x))
+ static inline int isinf_f (float x) { return isnan (x - x); }
+ static inline int isinf_d (double x) { return isnan (x - x); }
+ static inline int isinf_ld (long double x) { return isnan (x - x); }
+#endif
+
+
+// workaround for postgres defining their OIDs in a private header file
+#define QBOOLOID 16
+#define QINT8OID 20
+#define QINT2OID 21
+#define QINT4OID 23
+#define QNUMERICOID 1700
+#define QFLOAT4OID 700
+#define QFLOAT8OID 701
+#define QABSTIMEOID 702
+#define QRELTIMEOID 703
+#define QDATEOID 1082
+#define QTIMEOID 1083
+#define QTIMETZOID 1266
+#define QTIMESTAMPOID 1114
+#define QTIMESTAMPTZOID 1184
+#define QOIDOID 2278
+#define QBYTEAOID 17
+#define QREGPROCOID 24
+#define QXIDOID 28
+#define QCIDOID 29
+
+#define QBITOID 1560
+#define QVARBITOID 1562
+
+#define VARHDRSZ 4
+
+/* This is a compile time switch - if PQfreemem is declared, the compiler will use that one,
+ otherwise it'll run in this template */
+template <typename T>
+inline void PQfreemem(T *t, int = 0) { free(t); }
+
+Q_DECLARE_OPAQUE_POINTER(PGconn*)
+Q_DECLARE_METATYPE(PGconn*)
+
+Q_DECLARE_OPAQUE_POINTER(PGresult*)
+Q_DECLARE_METATYPE(PGresult*)
+
+QT_BEGIN_NAMESPACE
+
+inline void qPQfreemem(void *buffer)
+{
+ PQfreemem(buffer);
+}
+
+class QPSQLResultPrivate;
+
+class QPSQLResult: public QSqlResult
+{
+ Q_DECLARE_PRIVATE(QPSQLResult)
+
+public:
+ QPSQLResult(const QPSQLDriver *db);
+ ~QPSQLResult();
+
+ QVariant handle() const Q_DECL_OVERRIDE;
+ void virtual_hook(int id, void *data) Q_DECL_OVERRIDE;
+
+protected:
+ void cleanup();
+ bool fetch(int i) Q_DECL_OVERRIDE;
+ bool fetchFirst() Q_DECL_OVERRIDE;
+ bool fetchLast() Q_DECL_OVERRIDE;
+ QVariant data(int i) Q_DECL_OVERRIDE;
+ bool isNull(int field) Q_DECL_OVERRIDE;
+ bool reset (const QString &query) Q_DECL_OVERRIDE;
+ int size() Q_DECL_OVERRIDE;
+ int numRowsAffected() Q_DECL_OVERRIDE;
+ QSqlRecord record() const Q_DECL_OVERRIDE;
+ QVariant lastInsertId() const Q_DECL_OVERRIDE;
+ bool prepare(const QString &query) Q_DECL_OVERRIDE;
+ bool exec() Q_DECL_OVERRIDE;
+};
+
+class QPSQLDriverPrivate : public QSqlDriverPrivate
+{
+ Q_DECLARE_PUBLIC(QPSQLDriver)
+public:
+ QPSQLDriverPrivate() : QSqlDriverPrivate(),
+ connection(0),
+ isUtf8(false),
+ pro(QPSQLDriver::Version6),
+ sn(0),
+ pendingNotifyCheck(false),
+ hasBackslashEscape(false)
+ { dbmsType = QSqlDriver::PostgreSQL; }
+
+ PGconn *connection;
+ bool isUtf8;
+ QPSQLDriver::Protocol pro;
+ QSocketNotifier *sn;
+ QStringList seid;
+ mutable bool pendingNotifyCheck;
+ bool hasBackslashEscape;
+
+ void appendTables(QStringList &tl, QSqlQuery &t, QChar type);
+ PGresult * exec(const char * stmt) const;
+ PGresult * exec(const QString & stmt) const;
+ QPSQLDriver::Protocol getPSQLVersion();
+ bool setEncodingUtf8();
+ void setDatestyle();
+ void detectBackslashEscape();
+};
+
+void QPSQLDriverPrivate::appendTables(QStringList &tl, QSqlQuery &t, QChar type)
+{
+ QString query;
+ if (pro >= QPSQLDriver::Version73) {
+ query = QString::fromLatin1("select pg_class.relname, pg_namespace.nspname from pg_class "
+ "left join pg_namespace on (pg_class.relnamespace = pg_namespace.oid) "
+ "where (pg_class.relkind = '%1') and (pg_class.relname !~ '^Inv') "
+ "and (pg_class.relname !~ '^pg_') "
+ "and (pg_namespace.nspname != 'information_schema') ").arg(type);
+ } else {
+ query = QString::fromLatin1("select relname, null from pg_class where (relkind = '%1') "
+ "and (relname !~ '^Inv') "
+ "and (relname !~ '^pg_') ").arg(type);
+ }
+ t.exec(query);
+ while (t.next()) {
+ QString schema = t.value(1).toString();
+ if (schema.isEmpty() || schema == QLatin1String("public"))
+ tl.append(t.value(0).toString());
+ else
+ tl.append(t.value(0).toString().prepend(QLatin1Char('.')).prepend(schema));
+ }
+}
+
+PGresult * QPSQLDriverPrivate::exec(const char * stmt) const
+{
+ Q_Q(const QPSQLDriver);
+ PGresult *result = PQexec(connection, stmt);
+ if (seid.size() && !pendingNotifyCheck) {
+ pendingNotifyCheck = true;
+ QMetaObject::invokeMethod(const_cast<QPSQLDriver*>(q), "_q_handleNotification", Qt::QueuedConnection, Q_ARG(int,0));
+ }
+ return result;
+}
+
+PGresult * QPSQLDriverPrivate::exec(const QString & stmt) const
+{
+ return exec(isUtf8 ? stmt.toUtf8().constData() : stmt.toLocal8Bit().constData());
+}
+
+class QPSQLResultPrivate : public QSqlResultPrivate
+{
+ Q_DECLARE_PUBLIC(QPSQLResult)
+public:
+ Q_DECLARE_SQLDRIVER_PRIVATE(QPSQLDriver);
+ QPSQLResultPrivate(QPSQLResult *q, const QPSQLDriver *drv)
+ : QSqlResultPrivate(q, drv),
+ result(0),
+ currentSize(-1),
+ preparedQueriesEnabled(false)
+ { }
+
+ QString fieldSerial(int i) const Q_DECL_OVERRIDE { return QLatin1Char('$') + QString::number(i + 1); }
+ void deallocatePreparedStmt();
+
+ PGresult *result;
+ int currentSize;
+ bool preparedQueriesEnabled;
+ QString preparedStmtId;
+
+ bool processResults();
+};
+
+static QSqlError qMakeError(const QString& err, QSqlError::ErrorType type,
+ const QPSQLDriverPrivate *p, PGresult* result = 0)
+{
+ const char *s = PQerrorMessage(p->connection);
+ QString msg = p->isUtf8 ? QString::fromUtf8(s) : QString::fromLocal8Bit(s);
+ QString errorCode;
+ if (result) {
+ errorCode = QString::fromLatin1(PQresultErrorField(result, PG_DIAG_SQLSTATE));
+ msg += QString::fromLatin1("(%1)").arg(errorCode);
+ }
+ return QSqlError(QLatin1String("QPSQL: ") + err, msg, type, errorCode);
+}
+
+bool QPSQLResultPrivate::processResults()
+{
+ Q_Q(QPSQLResult);
+ if (!result)
+ return false;
+
+ int status = PQresultStatus(result);
+ if (status == PGRES_TUPLES_OK) {
+ q->setSelect(true);
+ q->setActive(true);
+ currentSize = PQntuples(result);
+ return true;
+ } else if (status == PGRES_COMMAND_OK) {
+ q->setSelect(false);
+ q->setActive(true);
+ currentSize = -1;
+ return true;
+ }
+ q->setLastError(qMakeError(QCoreApplication::translate("QPSQLResult",
+ "Unable to create query"), QSqlError::StatementError, drv_d_func(), result));
+ return false;
+}
+
+static QVariant::Type qDecodePSQLType(int t)
+{
+ QVariant::Type type = QVariant::Invalid;
+ switch (t) {
+ case QBOOLOID:
+ type = QVariant::Bool;
+ break;
+ case QINT8OID:
+ type = QVariant::LongLong;
+ break;
+ case QINT2OID:
+ case QINT4OID:
+ case QOIDOID:
+ case QREGPROCOID:
+ case QXIDOID:
+ case QCIDOID:
+ type = QVariant::Int;
+ break;
+ case QNUMERICOID:
+ case QFLOAT4OID:
+ case QFLOAT8OID:
+ type = QVariant::Double;
+ break;
+ case QABSTIMEOID:
+ case QRELTIMEOID:
+ case QDATEOID:
+ type = QVariant::Date;
+ break;
+ case QTIMEOID:
+ case QTIMETZOID:
+ type = QVariant::Time;
+ break;
+ case QTIMESTAMPOID:
+ case QTIMESTAMPTZOID:
+ type = QVariant::DateTime;
+ break;
+ case QBYTEAOID:
+ type = QVariant::ByteArray;
+ break;
+ default:
+ type = QVariant::String;
+ break;
+ }
+ return type;
+}
+
+void QPSQLResultPrivate::deallocatePreparedStmt()
+{
+ const QString stmt = QLatin1String("DEALLOCATE ") + preparedStmtId;
+ PGresult *result = drv_d_func()->exec(stmt);
+
+ if (PQresultStatus(result) != PGRES_COMMAND_OK)
+ qWarning("Unable to free statement: %s", PQerrorMessage(drv_d_func()->connection));
+ PQclear(result);
+ preparedStmtId.clear();
+}
+
+QPSQLResult::QPSQLResult(const QPSQLDriver* db)
+ : QSqlResult(*new QPSQLResultPrivate(this, db))
+{
+ Q_D(QPSQLResult);
+ d->preparedQueriesEnabled = db->hasFeature(QSqlDriver::PreparedQueries);
+}
+
+QPSQLResult::~QPSQLResult()
+{
+ Q_D(QPSQLResult);
+ cleanup();
+
+ if (d->preparedQueriesEnabled && !d->preparedStmtId.isNull())
+ d->deallocatePreparedStmt();
+}
+
+QVariant QPSQLResult::handle() const
+{
+ Q_D(const QPSQLResult);
+ return QVariant::fromValue(d->result);
+}
+
+void QPSQLResult::cleanup()
+{
+ Q_D(QPSQLResult);
+ if (d->result)
+ PQclear(d->result);
+ d->result = 0;
+ setAt(QSql::BeforeFirstRow);
+ d->currentSize = -1;
+ setActive(false);
+}
+
+bool QPSQLResult::fetch(int i)
+{
+ Q_D(const QPSQLResult);
+ if (!isActive())
+ return false;
+ if (i < 0)
+ return false;
+ if (i >= d->currentSize)
+ return false;
+ if (at() == i)
+ return true;
+ setAt(i);
+ return true;
+}
+
+bool QPSQLResult::fetchFirst()
+{
+ return fetch(0);
+}
+
+bool QPSQLResult::fetchLast()
+{
+ Q_D(const QPSQLResult);
+ return fetch(PQntuples(d->result) - 1);
+}
+
+QVariant QPSQLResult::data(int i)
+{
+ Q_D(const QPSQLResult);
+ if (i >= PQnfields(d->result)) {
+ qWarning("QPSQLResult::data: column %d out of range", i);
+ return QVariant();
+ }
+ int ptype = PQftype(d->result, i);
+ QVariant::Type type = qDecodePSQLType(ptype);
+ const char *val = PQgetvalue(d->result, at(), i);
+ if (PQgetisnull(d->result, at(), i))
+ return QVariant(type);
+ switch (type) {
+ case QVariant::Bool:
+ return QVariant((bool)(val[0] == 't'));
+ case QVariant::String:
+ return d->drv_d_func()->isUtf8 ? QString::fromUtf8(val) : QString::fromLatin1(val);
+ case QVariant::LongLong:
+ if (val[0] == '-')
+ return QString::fromLatin1(val).toLongLong();
+ else
+ return QString::fromLatin1(val).toULongLong();
+ case QVariant::Int:
+ return atoi(val);
+ case QVariant::Double:
+ if (ptype == QNUMERICOID) {
+ if (numericalPrecisionPolicy() != QSql::HighPrecision) {
+ QVariant retval;
+ bool convert;
+ double dbl=QString::fromLatin1(val).toDouble(&convert);
+ if (numericalPrecisionPolicy() == QSql::LowPrecisionInt64)
+ retval = (qlonglong)dbl;
+ else if (numericalPrecisionPolicy() == QSql::LowPrecisionInt32)
+ retval = (int)dbl;
+ else if (numericalPrecisionPolicy() == QSql::LowPrecisionDouble)
+ retval = dbl;
+ if (!convert)
+ return QVariant();
+ return retval;
+ }
+ return QString::fromLatin1(val);
+ }
+ return QString::fromLatin1(val).toDouble();
+ case QVariant::Date:
+ if (val[0] == '\0') {
+ return QVariant(QDate());
+ } else {
+#ifndef QT_NO_DATESTRING
+ return QVariant(QDate::fromString(QString::fromLatin1(val), Qt::ISODate));
+#else
+ return QVariant(QString::fromLatin1(val));
+#endif
+ }
+ case QVariant::Time: {
+ const QString str = QString::fromLatin1(val);
+#ifndef QT_NO_DATESTRING
+ if (str.isEmpty())
+ return QVariant(QTime());
+ else
+ return QVariant(QTime::fromString(str, Qt::ISODate));
+#else
+ return QVariant(str);
+#endif
+ }
+ case QVariant::DateTime: {
+ QString dtval = QString::fromLatin1(val);
+#ifndef QT_NO_DATESTRING
+ if (dtval.length() < 10) {
+ return QVariant(QDateTime());
+ } else {
+ QChar sign = dtval[dtval.size() - 3];
+ if (sign == QLatin1Char('-') || sign == QLatin1Char('+')) dtval += QLatin1String(":00");
+ return QVariant(QDateTime::fromString(dtval, Qt::ISODate).toLocalTime());
+ }
+#else
+ return QVariant(dtval);
+#endif
+ }
+ case QVariant::ByteArray: {
+ size_t len;
+ unsigned char *data = PQunescapeBytea((const unsigned char*)val, &len);
+ QByteArray ba(reinterpret_cast<const char *>(data), int(len));
+ qPQfreemem(data);
+ return QVariant(ba);
+ }
+ default:
+ case QVariant::Invalid:
+ qWarning("QPSQLResult::data: unknown data type");
+ }
+ return QVariant();
+}
+
+bool QPSQLResult::isNull(int field)
+{
+ Q_D(const QPSQLResult);
+ PQgetvalue(d->result, at(), field);
+ return PQgetisnull(d->result, at(), field);
+}
+
+bool QPSQLResult::reset (const QString& query)
+{
+ Q_D(QPSQLResult);
+ cleanup();
+ if (!driver())
+ return false;
+ if (!driver()->isOpen() || driver()->isOpenError())
+ return false;
+ d->result = d->drv_d_func()->exec(query);
+ return d->processResults();
+}
+
+int QPSQLResult::size()
+{
+ Q_D(const QPSQLResult);
+ return d->currentSize;
+}
+
+int QPSQLResult::numRowsAffected()
+{
+ Q_D(const QPSQLResult);
+ return QString::fromLatin1(PQcmdTuples(d->result)).toInt();
+}
+
+QVariant QPSQLResult::lastInsertId() const
+{
+ Q_D(const QPSQLResult);
+ if (d->drv_d_func()->pro >= QPSQLDriver::Version81) {
+ QSqlQuery qry(driver()->createResult());
+ // Most recent sequence value obtained from nextval
+ if (qry.exec(QLatin1String("SELECT lastval();")) && qry.next())
+ return qry.value(0);
+ } else if (isActive()) {
+ Oid id = PQoidValue(d->result);
+ if (id != InvalidOid)
+ return QVariant(id);
+ }
+ return QVariant();
+}
+
+QSqlRecord QPSQLResult::record() const
+{
+ Q_D(const QPSQLResult);
+ QSqlRecord info;
+ if (!isActive() || !isSelect())
+ return info;
+
+ int count = PQnfields(d->result);
+ for (int i = 0; i < count; ++i) {
+ QSqlField f;
+ if (d->drv_d_func()->isUtf8)
+ f.setName(QString::fromUtf8(PQfname(d->result, i)));
+ else
+ f.setName(QString::fromLocal8Bit(PQfname(d->result, i)));
+ int ptype = PQftype(d->result, i);
+ f.setType(qDecodePSQLType(ptype));
+ int len = PQfsize(d->result, i);
+ int precision = PQfmod(d->result, i);
+
+ switch (ptype) {
+ case QTIMESTAMPOID:
+ case QTIMESTAMPTZOID:
+ precision = 3;
+ break;
+
+ case QNUMERICOID:
+ if (precision != -1) {
+ len = (precision >> 16);
+ precision = ((precision - VARHDRSZ) & 0xffff);
+ }
+ break;
+ case QBITOID:
+ case QVARBITOID:
+ len = precision;
+ precision = -1;
+ break;
+ default:
+ if (len == -1 && precision >= VARHDRSZ) {
+ len = precision - VARHDRSZ;
+ precision = -1;
+ }
+ }
+
+ f.setLength(len);
+ f.setPrecision(precision);
+ f.setSqlType(ptype);
+ info.append(f);
+ }
+ return info;
+}
+
+void QPSQLResult::virtual_hook(int id, void *data)
+{
+ Q_ASSERT(data);
+
+ QSqlResult::virtual_hook(id, data);
+}
+
+static QString qCreateParamString(const QVector<QVariant> &boundValues, const QSqlDriver *driver)
+{
+ if (boundValues.isEmpty())
+ return QString();
+
+ QString params;
+ QSqlField f;
+ for (int i = 0; i < boundValues.count(); ++i) {
+ const QVariant &val = boundValues.at(i);
+
+ f.setType(val.type());
+ if (val.isNull())
+ f.clear();
+ else
+ f.setValue(val);
+ if(!params.isNull())
+ params.append(QLatin1String(", "));
+ params.append(driver->formatValue(f));
+ }
+ return params;
+}
+
+Q_GLOBAL_STATIC(QMutex, qMutex)
+QString qMakePreparedStmtId()
+{
+ qMutex()->lock();
+ static unsigned int qPreparedStmtCount = 0;
+ QString id = QLatin1String("qpsqlpstmt_") + QString::number(++qPreparedStmtCount, 16);
+ qMutex()->unlock();
+ return id;
+}
+
+bool QPSQLResult::prepare(const QString &query)
+{
+ Q_D(QPSQLResult);
+ if (!d->preparedQueriesEnabled)
+ return QSqlResult::prepare(query);
+
+ cleanup();
+
+ if (!d->preparedStmtId.isEmpty())
+ d->deallocatePreparedStmt();
+
+ const QString stmtId = qMakePreparedStmtId();
+ const QString stmt = QString::fromLatin1("PREPARE %1 AS ").arg(stmtId).append(d->positionalToNamedBinding(query));
+
+ PGresult *result = d->drv_d_func()->exec(stmt);
+
+ if (PQresultStatus(result) != PGRES_COMMAND_OK) {
+ setLastError(qMakeError(QCoreApplication::translate("QPSQLResult",
+ "Unable to prepare statement"), QSqlError::StatementError, d->drv_d_func(), result));
+ PQclear(result);
+ d->preparedStmtId.clear();
+ return false;
+ }
+
+ PQclear(result);
+ d->preparedStmtId = stmtId;
+ return true;
+}
+
+bool QPSQLResult::exec()
+{
+ Q_D(QPSQLResult);
+ if (!d->preparedQueriesEnabled)
+ return QSqlResult::exec();
+
+ cleanup();
+
+ QString stmt;
+ const QString params = qCreateParamString(boundValues(), driver());
+ if (params.isEmpty())
+ stmt = QString::fromLatin1("EXECUTE %1").arg(d->preparedStmtId);
+ else
+ stmt = QString::fromLatin1("EXECUTE %1 (%2)").arg(d->preparedStmtId).arg(params);
+
+ d->result = d->drv_d_func()->exec(stmt);
+
+ return d->processResults();
+}
+
+///////////////////////////////////////////////////////////////////
+
+bool QPSQLDriverPrivate::setEncodingUtf8()
+{
+ PGresult* result = exec("SET CLIENT_ENCODING TO 'UNICODE'");
+ int status = PQresultStatus(result);
+ PQclear(result);
+ return status == PGRES_COMMAND_OK;
+}
+
+void QPSQLDriverPrivate::setDatestyle()
+{
+ PGresult* result = exec("SET DATESTYLE TO 'ISO'");
+ int status = PQresultStatus(result);
+ if (status != PGRES_COMMAND_OK)
+ qWarning("%s", PQerrorMessage(connection));
+ PQclear(result);
+}
+
+void QPSQLDriverPrivate::detectBackslashEscape()
+{
+ // standard_conforming_strings option introduced in 8.2
+ // http://www.postgresql.org/docs/8.2/static/runtime-config-compatible.html
+ if (pro < QPSQLDriver::Version82) {
+ hasBackslashEscape = true;
+ } else {
+ hasBackslashEscape = false;
+ PGresult* result = exec(QLatin1String("SELECT '\\\\' x"));
+ int status = PQresultStatus(result);
+ if (status == PGRES_COMMAND_OK || status == PGRES_TUPLES_OK)
+ if (QString::fromLatin1(PQgetvalue(result, 0, 0)) == QLatin1String("\\"))
+ hasBackslashEscape = true;
+ PQclear(result);
+ }
+}
+
+static QPSQLDriver::Protocol qMakePSQLVersion(int vMaj, int vMin)
+{
+ switch (vMaj) {
+ case 6:
+ return QPSQLDriver::Version6;
+ case 7:
+ {
+ switch (vMin) {
+ case 1:
+ return QPSQLDriver::Version71;
+ case 3:
+ return QPSQLDriver::Version73;
+ case 4:
+ return QPSQLDriver::Version74;
+ default:
+ return QPSQLDriver::Version7;
+ }
+ break;
+ }
+ case 8:
+ {
+ switch (vMin) {
+ case 1:
+ return QPSQLDriver::Version81;
+ case 2:
+ return QPSQLDriver::Version82;
+ case 3:
+ return QPSQLDriver::Version83;
+ case 4:
+ return QPSQLDriver::Version84;
+ default:
+ return QPSQLDriver::Version8;
+ }
+ break;
+ }
+ case 9:
+ return QPSQLDriver::Version9;
+ break;
+ default:
+ break;
+ }
+ return QPSQLDriver::VersionUnknown;
+}
+
+QPSQLDriver::Protocol QPSQLDriverPrivate::getPSQLVersion()
+{
+ QPSQLDriver::Protocol serverVersion = QPSQLDriver::Version6;
+ PGresult* result = exec("select version()");
+ int status = PQresultStatus(result);
+ if (status == PGRES_COMMAND_OK || status == PGRES_TUPLES_OK) {
+ QString val = QString::fromLatin1(PQgetvalue(result, 0, 0));
+
+ QRegExp rx(QLatin1String("(\\d+)\\.(\\d+)"));
+ rx.setMinimal(true); // enforce non-greedy RegExp
+
+ if (rx.indexIn(val) != -1) {
+ int vMaj = rx.cap(1).toInt();
+ int vMin = rx.cap(2).toInt();
+ serverVersion = qMakePSQLVersion(vMaj, vMin);
+#if defined(PG_MAJORVERSION)
+ if (rx.indexIn(QLatin1String(PG_MAJORVERSION)) != -1)
+#elif defined(PG_VERSION)
+ if (rx.indexIn(QLatin1String(PG_VERSION)) != -1)
+#else
+ if (0)
+#endif
+ {
+ vMaj = rx.cap(1).toInt();
+ vMin = rx.cap(2).toInt();
+ QPSQLDriver::Protocol clientVersion = qMakePSQLVersion(vMaj, vMin);
+
+ if (serverVersion >= QPSQLDriver::Version9 && clientVersion < QPSQLDriver::Version9) {
+ //Client version before QPSQLDriver::Version9 only supports escape mode for bytea type,
+ //but bytea format is set to hex by default in PSQL 9 and above. So need to force the
+ //server use the old escape mode when connects to the new server with old client library.
+ PQclear(result);
+ result = exec("SET bytea_output=escape; ");
+ status = PQresultStatus(result);
+ } else if (serverVersion == QPSQLDriver::VersionUnknown) {
+ serverVersion = clientVersion;
+ if (serverVersion != QPSQLDriver::VersionUnknown)
+ qWarning("The server version of this PostgreSQL is unknown, falling back to the client version.");
+ }
+ }
+ }
+ }
+ PQclear(result);
+
+ //keep the old behavior unchanged
+ if (serverVersion == QPSQLDriver::VersionUnknown)
+ serverVersion = QPSQLDriver::Version6;
+
+ if (serverVersion < QPSQLDriver::Version71) {
+ qWarning("This version of PostgreSQL is not supported and may not work.");
+ }
+
+ return serverVersion;
+}
+
+QPSQLDriver::QPSQLDriver(QObject *parent)
+ : QSqlDriver(*new QPSQLDriverPrivate, parent)
+{
+}
+
+QPSQLDriver::QPSQLDriver(PGconn *conn, QObject *parent)
+ : QSqlDriver(*new QPSQLDriverPrivate, parent)
+{
+ Q_D(QPSQLDriver);
+ d->connection = conn;
+ if (conn) {
+ d->pro = d->getPSQLVersion();
+ d->detectBackslashEscape();
+ setOpen(true);
+ setOpenError(false);
+ }
+}
+
+QPSQLDriver::~QPSQLDriver()
+{
+ Q_D(QPSQLDriver);
+ if (d->connection)
+ PQfinish(d->connection);
+}
+
+QVariant QPSQLDriver::handle() const
+{
+ Q_D(const QPSQLDriver);
+ return QVariant::fromValue(d->connection);
+}
+
+bool QPSQLDriver::hasFeature(DriverFeature f) const
+{
+ Q_D(const QPSQLDriver);
+ switch (f) {
+ case Transactions:
+ case QuerySize:
+ case LastInsertId:
+ case LowPrecisionNumbers:
+ case EventNotifications:
+ return true;
+ case PreparedQueries:
+ case PositionalPlaceholders:
+ return d->pro >= QPSQLDriver::Version82;
+ case BatchOperations:
+ case NamedPlaceholders:
+ case SimpleLocking:
+ case FinishQuery:
+ case MultipleResultSets:
+ case CancelQuery:
+ return false;
+ case BLOB:
+ return d->pro >= QPSQLDriver::Version71;
+ case Unicode:
+ return d->isUtf8;
+ }
+ return false;
+}
+
+/*
+ Quote a string for inclusion into the connection string
+ \ -> \\
+ ' -> \'
+ surround string by single quotes
+ */
+static QString qQuote(QString s)
+{
+ s.replace(QLatin1Char('\\'), QLatin1String("\\\\"));
+ s.replace(QLatin1Char('\''), QLatin1String("\\'"));
+ s.append(QLatin1Char('\'')).prepend(QLatin1Char('\''));
+ return s;
+}
+
+bool QPSQLDriver::open(const QString & db,
+ const QString & user,
+ const QString & password,
+ const QString & host,
+ int port,
+ const QString& connOpts)
+{
+ Q_D(QPSQLDriver);
+ if (isOpen())
+ close();
+ QString connectString;
+ if (!host.isEmpty())
+ connectString.append(QLatin1String("host=")).append(qQuote(host));
+ if (!db.isEmpty())
+ connectString.append(QLatin1String(" dbname=")).append(qQuote(db));
+ if (!user.isEmpty())
+ connectString.append(QLatin1String(" user=")).append(qQuote(user));
+ if (!password.isEmpty())
+ connectString.append(QLatin1String(" password=")).append(qQuote(password));
+ if (port != -1)
+ connectString.append(QLatin1String(" port=")).append(qQuote(QString::number(port)));
+
+ // add any connect options - the server will handle error detection
+ if (!connOpts.isEmpty()) {
+ QString opt = connOpts;
+ opt.replace(QLatin1Char(';'), QLatin1Char(' '), Qt::CaseInsensitive);
+ connectString.append(QLatin1Char(' ')).append(opt);
+ }
+
+ d->connection = PQconnectdb(connectString.toLocal8Bit().constData());
+ if (PQstatus(d->connection) == CONNECTION_BAD) {
+ setLastError(qMakeError(tr("Unable to connect"), QSqlError::ConnectionError, d));
+ setOpenError(true);
+ PQfinish(d->connection);
+ d->connection = 0;
+ return false;
+ }
+
+ d->pro = d->getPSQLVersion();
+ d->detectBackslashEscape();
+ d->isUtf8 = d->setEncodingUtf8();
+ d->setDatestyle();
+
+ setOpen(true);
+ setOpenError(false);
+ return true;
+}
+
+void QPSQLDriver::close()
+{
+ Q_D(QPSQLDriver);
+ if (isOpen()) {
+
+ d->seid.clear();
+ if (d->sn) {
+ disconnect(d->sn, SIGNAL(activated(int)), this, SLOT(_q_handleNotification(int)));
+ delete d->sn;
+ d->sn = 0;
+ }
+
+ if (d->connection)
+ PQfinish(d->connection);
+ d->connection = 0;
+ setOpen(false);
+ setOpenError(false);
+ }
+}
+
+QSqlResult *QPSQLDriver::createResult() const
+{
+ return new QPSQLResult(this);
+}
+
+bool QPSQLDriver::beginTransaction()
+{
+ Q_D(const QPSQLDriver);
+ if (!isOpen()) {
+ qWarning("QPSQLDriver::beginTransaction: Database not open");
+ return false;
+ }
+ PGresult* res = d->exec("BEGIN");
+ if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
+ setLastError(qMakeError(tr("Could not begin transaction"),
+ QSqlError::TransactionError, d, res));
+ PQclear(res);
+ return false;
+ }
+ PQclear(res);
+ return true;
+}
+
+bool QPSQLDriver::commitTransaction()
+{
+ Q_D(QPSQLDriver);
+ if (!isOpen()) {
+ qWarning("QPSQLDriver::commitTransaction: Database not open");
+ return false;
+ }
+ PGresult* res = d->exec("COMMIT");
+
+ bool transaction_failed = false;
+
+ // XXX
+ // This hack is used to tell if the transaction has succeeded for the protocol versions of
+ // PostgreSQL below. For 7.x and other protocol versions we are left in the dark.
+ // This hack can dissapear once there is an API to query this sort of information.
+ if (d->pro == QPSQLDriver::Version8 ||
+ d->pro == QPSQLDriver::Version81 ||
+ d->pro == QPSQLDriver::Version82 ||
+ d->pro == QPSQLDriver::Version83 ||
+ d->pro == QPSQLDriver::Version84 ||
+ d->pro == QPSQLDriver::Version9) {
+ transaction_failed = qstrcmp(PQcmdStatus(res), "ROLLBACK") == 0;
+ }
+
+ if (!res || PQresultStatus(res) != PGRES_COMMAND_OK || transaction_failed) {
+ setLastError(qMakeError(tr("Could not commit transaction"),
+ QSqlError::TransactionError, d, res));
+ PQclear(res);
+ return false;
+ }
+ PQclear(res);
+ return true;
+}
+
+bool QPSQLDriver::rollbackTransaction()
+{
+ Q_D(QPSQLDriver);
+ if (!isOpen()) {
+ qWarning("QPSQLDriver::rollbackTransaction: Database not open");
+ return false;
+ }
+ PGresult* res = d->exec("ROLLBACK");
+ if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
+ setLastError(qMakeError(tr("Could not rollback transaction"),
+ QSqlError::TransactionError, d, res));
+ PQclear(res);
+ return false;
+ }
+ PQclear(res);
+ return true;
+}
+
+QStringList QPSQLDriver::tables(QSql::TableType type) const
+{
+ Q_D(const QPSQLDriver);
+ QStringList tl;
+ if (!isOpen())
+ return tl;
+ QSqlQuery t(createResult());
+ t.setForwardOnly(true);
+
+ if (type & QSql::Tables)
+ const_cast<QPSQLDriverPrivate*>(d)->appendTables(tl, t, QLatin1Char('r'));
+ if (type & QSql::Views)
+ const_cast<QPSQLDriverPrivate*>(d)->appendTables(tl, t, QLatin1Char('v'));
+ if (type & QSql::SystemTables) {
+ t.exec(QLatin1String("select relname from pg_class where (relkind = 'r') "
+ "and (relname like 'pg_%') "));
+ while (t.next())
+ tl.append(t.value(0).toString());
+ }
+
+ return tl;
+}
+
+static void qSplitTableName(QString &tablename, QString &schema)
+{
+ int dot = tablename.indexOf(QLatin1Char('.'));
+ if (dot == -1)
+ return;
+ schema = tablename.left(dot);
+ tablename = tablename.mid(dot + 1);
+}
+
+QSqlIndex QPSQLDriver::primaryIndex(const QString& tablename) const
+{
+ Q_D(const QPSQLDriver);
+ QSqlIndex idx(tablename);
+ if (!isOpen())
+ return idx;
+ QSqlQuery i(createResult());
+ QString stmt;
+
+ QString tbl = tablename;
+ QString schema;
+ qSplitTableName(tbl, schema);
+
+ if (isIdentifierEscaped(tbl, QSqlDriver::TableName))
+ tbl = stripDelimiters(tbl, QSqlDriver::TableName);
+ else
+ tbl = tbl.toLower();
+
+ if (isIdentifierEscaped(schema, QSqlDriver::TableName))
+ schema = stripDelimiters(schema, QSqlDriver::TableName);
+ else
+ schema = schema.toLower();
+
+ switch(d->pro) {
+ case QPSQLDriver::Version6:
+ stmt = QLatin1String("select pg_att1.attname, int(pg_att1.atttypid), pg_cl.relname "
+ "from pg_attribute pg_att1, pg_attribute pg_att2, pg_class pg_cl, pg_index pg_ind "
+ "where pg_cl.relname = '%1_pkey' "
+ "and pg_cl.oid = pg_ind.indexrelid "
+ "and pg_att2.attrelid = pg_ind.indexrelid "
+ "and pg_att1.attrelid = pg_ind.indrelid "
+ "and pg_att1.attnum = pg_ind.indkey[pg_att2.attnum-1] "
+ "order by pg_att2.attnum");
+ break;
+ case QPSQLDriver::Version7:
+ case QPSQLDriver::Version71:
+ stmt = QLatin1String("select pg_att1.attname, pg_att1.atttypid::int, pg_cl.relname "
+ "from pg_attribute pg_att1, pg_attribute pg_att2, pg_class pg_cl, pg_index pg_ind "
+ "where pg_cl.relname = '%1_pkey' "
+ "and pg_cl.oid = pg_ind.indexrelid "
+ "and pg_att2.attrelid = pg_ind.indexrelid "
+ "and pg_att1.attrelid = pg_ind.indrelid "
+ "and pg_att1.attnum = pg_ind.indkey[pg_att2.attnum-1] "
+ "order by pg_att2.attnum");
+ break;
+ case QPSQLDriver::Version73:
+ case QPSQLDriver::Version74:
+ case QPSQLDriver::Version8:
+ case QPSQLDriver::Version81:
+ case QPSQLDriver::Version82:
+ case QPSQLDriver::Version83:
+ case QPSQLDriver::Version84:
+ case QPSQLDriver::Version9:
+ stmt = QLatin1String("SELECT pg_attribute.attname, pg_attribute.atttypid::int, "
+ "pg_class.relname "
+ "FROM pg_attribute, pg_class "
+ "WHERE %1 pg_class.oid IN "
+ "(SELECT indexrelid FROM pg_index WHERE indisprimary = true AND indrelid IN "
+ " (SELECT oid FROM pg_class WHERE relname = '%2')) "
+ "AND pg_attribute.attrelid = pg_class.oid "
+ "AND pg_attribute.attisdropped = false "
+ "ORDER BY pg_attribute.attnum");
+ if (schema.isEmpty())
+ stmt = stmt.arg(QLatin1String("pg_table_is_visible(pg_class.oid) AND"));
+ else
+ stmt = stmt.arg(QString::fromLatin1("pg_class.relnamespace = (select oid from "
+ "pg_namespace where pg_namespace.nspname = '%1') AND ").arg(schema));
+ break;
+ case QPSQLDriver::VersionUnknown:
+ qFatal("PSQL version is unknown");
+ break;
+ }
+
+ i.exec(stmt.arg(tbl));
+ while (i.isActive() && i.next()) {
+ QSqlField f(i.value(0).toString(), qDecodePSQLType(i.value(1).toInt()));
+ idx.append(f);
+ idx.setName(i.value(2).toString());
+ }
+ return idx;
+}
+
+QSqlRecord QPSQLDriver::record(const QString& tablename) const
+{
+ Q_D(const QPSQLDriver);
+ QSqlRecord info;
+ if (!isOpen())
+ return info;
+
+ QString tbl = tablename;
+ QString schema;
+ qSplitTableName(tbl, schema);
+
+ if (isIdentifierEscaped(tbl, QSqlDriver::TableName))
+ tbl = stripDelimiters(tbl, QSqlDriver::TableName);
+ else
+ tbl = tbl.toLower();
+
+ if (isIdentifierEscaped(schema, QSqlDriver::TableName))
+ schema = stripDelimiters(schema, QSqlDriver::TableName);
+ else
+ schema = schema.toLower();
+
+ QString stmt;
+ switch(d->pro) {
+ case QPSQLDriver::Version6:
+ stmt = QLatin1String("select pg_attribute.attname, int(pg_attribute.atttypid), "
+ "pg_attribute.attnotnull, pg_attribute.attlen, pg_attribute.atttypmod, "
+ "int(pg_attribute.attrelid), pg_attribute.attnum "
+ "from pg_class, pg_attribute "
+ "where pg_class.relname = '%1' "
+ "and pg_attribute.attnum > 0 "
+ "and pg_attribute.attrelid = pg_class.oid ");
+ break;
+ case QPSQLDriver::Version7:
+ stmt = QLatin1String("select pg_attribute.attname, pg_attribute.atttypid::int, "
+ "pg_attribute.attnotnull, pg_attribute.attlen, pg_attribute.atttypmod, "
+ "pg_attribute.attrelid::int, pg_attribute.attnum "
+ "from pg_class, pg_attribute "
+ "where pg_class.relname = '%1' "
+ "and pg_attribute.attnum > 0 "
+ "and pg_attribute.attrelid = pg_class.oid ");
+ break;
+ case QPSQLDriver::Version71:
+ stmt = QLatin1String("select pg_attribute.attname, pg_attribute.atttypid::int, "
+ "pg_attribute.attnotnull, pg_attribute.attlen, pg_attribute.atttypmod, "
+ "pg_attrdef.adsrc "
+ "from pg_class, pg_attribute "
+ "left join pg_attrdef on (pg_attrdef.adrelid = "
+ "pg_attribute.attrelid and pg_attrdef.adnum = pg_attribute.attnum) "
+ "where pg_class.relname = '%1' "
+ "and pg_attribute.attnum > 0 "
+ "and pg_attribute.attrelid = pg_class.oid "
+ "order by pg_attribute.attnum ");
+ break;
+ case QPSQLDriver::Version73:
+ case QPSQLDriver::Version74:
+ case QPSQLDriver::Version8:
+ case QPSQLDriver::Version81:
+ case QPSQLDriver::Version82:
+ case QPSQLDriver::Version83:
+ case QPSQLDriver::Version84:
+ case QPSQLDriver::Version9:
+ stmt = QLatin1String("select pg_attribute.attname, pg_attribute.atttypid::int, "
+ "pg_attribute.attnotnull, pg_attribute.attlen, pg_attribute.atttypmod, "
+ "pg_attrdef.adsrc "
+ "from pg_class, pg_attribute "
+ "left join pg_attrdef on (pg_attrdef.adrelid = "
+ "pg_attribute.attrelid and pg_attrdef.adnum = pg_attribute.attnum) "
+ "where %1 "
+ "and pg_class.relname = '%2' "
+ "and pg_attribute.attnum > 0 "
+ "and pg_attribute.attrelid = pg_class.oid "
+ "and pg_attribute.attisdropped = false "
+ "order by pg_attribute.attnum ");
+ if (schema.isEmpty())
+ stmt = stmt.arg(QLatin1String("pg_table_is_visible(pg_class.oid)"));
+ else
+ stmt = stmt.arg(QString::fromLatin1("pg_class.relnamespace = (select oid from "
+ "pg_namespace where pg_namespace.nspname = '%1')").arg(schema));
+ break;
+ case QPSQLDriver::VersionUnknown:
+ qFatal("PSQL version is unknown");
+ break;
+ }
+
+ QSqlQuery query(createResult());
+ query.exec(stmt.arg(tbl));
+ if (d->pro >= QPSQLDriver::Version71) {
+ while (query.next()) {
+ int len = query.value(3).toInt();
+ int precision = query.value(4).toInt();
+ // swap length and precision if length == -1
+ if (len == -1 && precision > -1) {
+ len = precision - 4;
+ precision = -1;
+ }
+ QString defVal = query.value(5).toString();
+ if (!defVal.isEmpty() && defVal.at(0) == QLatin1Char('\''))
+ defVal = defVal.mid(1, defVal.length() - 2);
+ QSqlField f(query.value(0).toString(), qDecodePSQLType(query.value(1).toInt()));
+ f.setRequired(query.value(2).toBool());
+ f.setLength(len);
+ f.setPrecision(precision);
+ f.setDefaultValue(defVal);
+ f.setSqlType(query.value(1).toInt());
+ info.append(f);
+ }
+ } else {
+ // Postgres < 7.1 cannot handle outer joins
+ while (query.next()) {
+ QString defVal;
+ QString stmt2 = QLatin1String("select pg_attrdef.adsrc from pg_attrdef where "
+ "pg_attrdef.adrelid = %1 and pg_attrdef.adnum = %2 ");
+ QSqlQuery query2(createResult());
+ query2.exec(stmt2.arg(query.value(5).toInt()).arg(query.value(6).toInt()));
+ if (query2.isActive() && query2.next())
+ defVal = query2.value(0).toString();
+ if (!defVal.isEmpty() && defVal.at(0) == QLatin1Char('\''))
+ defVal = defVal.mid(1, defVal.length() - 2);
+ int len = query.value(3).toInt();
+ int precision = query.value(4).toInt();
+ // swap length and precision if length == -1
+ if (len == -1 && precision > -1) {
+ len = precision - 4;
+ precision = -1;
+ }
+ QSqlField f(query.value(0).toString(), qDecodePSQLType(query.value(1).toInt()));
+ f.setRequired(query.value(2).toBool());
+ f.setLength(len);
+ f.setPrecision(precision);
+ f.setDefaultValue(defVal);
+ f.setSqlType(query.value(1).toInt());
+ info.append(f);
+ }
+ }
+
+ return info;
+}
+
+template <class FloatType>
+inline void assignSpecialPsqlFloatValue(FloatType val, QString *target)
+{
+ if (isnan(val)) {
+ *target = QLatin1String("'NaN'");
+ } else {
+ switch (isinf(val)) {
+ case 1:
+ *target = QLatin1String("'Infinity'");
+ break;
+ case -1:
+ *target = QLatin1String("'-Infinity'");
+ break;
+ }
+ }
+}
+
+QString QPSQLDriver::formatValue(const QSqlField &field, bool trimStrings) const
+{
+ Q_D(const QPSQLDriver);
+ QString r;
+ if (field.isNull()) {
+ r = QLatin1String("NULL");
+ } else {
+ switch (int(field.type())) {
+ case QVariant::DateTime:
+#ifndef QT_NO_DATESTRING
+ if (field.value().toDateTime().isValid()) {
+ // we force the value to be considered with a timezone information, and we force it to be UTC
+ // this is safe since postgresql stores only the UTC value and not the timezone offset (only used
+ // while parsing), so we have correct behavior in both case of with timezone and without tz
+ r = QLatin1String("TIMESTAMP WITH TIME ZONE ") + QLatin1Char('\'') + field.value().toDateTime().toUTC().toString(QLatin1String("yyyy-MM-ddThh:mm:ss.zzz")) + QLatin1Char('Z') + QLatin1Char('\'');
+ } else {
+ r = QLatin1String("NULL");
+ }
+#else
+ r = QLatin1String("NULL");
+#endif // QT_NO_DATESTRING
+ break;
+ case QVariant::Time:
+#ifndef QT_NO_DATESTRING
+ if (field.value().toTime().isValid()) {
+ r = QLatin1Char('\'') + field.value().toTime().toString(QLatin1String("hh:mm:ss.zzz")) + QLatin1Char('\'');
+ } else
+#endif
+ {
+ r = QLatin1String("NULL");
+ }
+ break;
+ case QVariant::String:
+ r = QSqlDriver::formatValue(field, trimStrings);
+ if (d->hasBackslashEscape)
+ r.replace(QLatin1String("\\"), QLatin1String("\\\\"));
+ break;
+ case QVariant::Bool:
+ if (field.value().toBool())
+ r = QLatin1String("TRUE");
+ else
+ r = QLatin1String("FALSE");
+ break;
+ case QVariant::ByteArray: {
+ QByteArray ba(field.value().toByteArray());
+ size_t len;
+#if defined PG_VERSION_NUM && PG_VERSION_NUM-0 >= 80200
+ unsigned char *data = PQescapeByteaConn(d->connection, (const unsigned char*)ba.constData(), ba.size(), &len);
+#else
+ unsigned char *data = PQescapeBytea((const unsigned char*)ba.constData(), ba.size(), &len);
+#endif
+ r += QLatin1Char('\'');
+ r += QLatin1String((const char*)data);
+ r += QLatin1Char('\'');
+ qPQfreemem(data);
+ break;
+ }
+ case QMetaType::Float:
+ assignSpecialPsqlFloatValue(field.value().toFloat(), &r);
+ if (r.isEmpty())
+ r = QSqlDriver::formatValue(field, trimStrings);
+ break;
+ case QVariant::Double:
+ assignSpecialPsqlFloatValue(field.value().toDouble(), &r);
+ if (r.isEmpty())
+ r = QSqlDriver::formatValue(field, trimStrings);
+ break;
+ case QVariant::Uuid:
+ r = QLatin1Char('\'') + field.value().toString() + QLatin1Char('\'');
+ break;
+ default:
+ r = QSqlDriver::formatValue(field, trimStrings);
+ break;
+ }
+ }
+ return r;
+}
+
+QString QPSQLDriver::escapeIdentifier(const QString &identifier, IdentifierType) const
+{
+ QString res = identifier;
+ if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) {
+ res.replace(QLatin1Char('"'), QLatin1String("\"\""));
+ res.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
+ res.replace(QLatin1Char('.'), QLatin1String("\".\""));
+ }
+ return res;
+}
+
+bool QPSQLDriver::isOpen() const
+{
+ Q_D(const QPSQLDriver);
+ return PQstatus(d->connection) == CONNECTION_OK;
+}
+
+QPSQLDriver::Protocol QPSQLDriver::protocol() const
+{
+ Q_D(const QPSQLDriver);
+ return d->pro;
+}
+
+bool QPSQLDriver::subscribeToNotification(const QString &name)
+{
+ Q_D(QPSQLDriver);
+ if (!isOpen()) {
+ qWarning("QPSQLDriver::subscribeToNotificationImplementation: database not open.");
+ return false;
+ }
+
+ if (d->seid.contains(name)) {
+ qWarning("QPSQLDriver::subscribeToNotificationImplementation: already subscribing to '%s'.",
+ qPrintable(name));
+ return false;
+ }
+
+ int socket = PQsocket(d->connection);
+ if (socket) {
+ // Add the name to the list of subscriptions here so that QSQLDriverPrivate::exec knows
+ // to check for notifications immediately after executing the LISTEN
+ d->seid << name;
+ QString query = QLatin1String("LISTEN ") + escapeIdentifier(name, QSqlDriver::TableName);
+ PGresult *result = d->exec(query);
+ if (PQresultStatus(result) != PGRES_COMMAND_OK) {
+ setLastError(qMakeError(tr("Unable to subscribe"), QSqlError::StatementError, d, result));
+ PQclear(result);
+ return false;
+ }
+ PQclear(result);
+
+ if (!d->sn) {
+ d->sn = new QSocketNotifier(socket, QSocketNotifier::Read);
+ connect(d->sn, SIGNAL(activated(int)), this, SLOT(_q_handleNotification(int)));
+ }
+ } else {
+ qWarning("QPSQLDriver::subscribeToNotificationImplementation: PQsocket didn't return a valid socket to listen on");
+ return false;
+ }
+
+ return true;
+}
+
+bool QPSQLDriver::unsubscribeFromNotification(const QString &name)
+{
+ Q_D(QPSQLDriver);
+ if (!isOpen()) {
+ qWarning("QPSQLDriver::unsubscribeFromNotificationImplementation: database not open.");
+ return false;
+ }
+
+ if (!d->seid.contains(name)) {
+ qWarning("QPSQLDriver::unsubscribeFromNotificationImplementation: not subscribed to '%s'.",
+ qPrintable(name));
+ return false;
+ }
+
+ QString query = QLatin1String("UNLISTEN ") + escapeIdentifier(name, QSqlDriver::TableName);
+ PGresult *result = d->exec(query);
+ if (PQresultStatus(result) != PGRES_COMMAND_OK) {
+ setLastError(qMakeError(tr("Unable to unsubscribe"), QSqlError::StatementError, d, result));
+ PQclear(result);
+ return false;
+ }
+ PQclear(result);
+
+ d->seid.removeAll(name);
+
+ if (d->seid.isEmpty()) {
+ disconnect(d->sn, SIGNAL(activated(int)), this, SLOT(_q_handleNotification(int)));
+ delete d->sn;
+ d->sn = 0;
+ }
+
+ return true;
+}
+
+QStringList QPSQLDriver::subscribedToNotifications() const
+{
+ Q_D(const QPSQLDriver);
+ return d->seid;
+}
+
+void QPSQLDriver::_q_handleNotification(int)
+{
+ Q_D(QPSQLDriver);
+ d->pendingNotifyCheck = false;
+ PQconsumeInput(d->connection);
+
+ PGnotify *notify = 0;
+ while((notify = PQnotifies(d->connection)) != 0) {
+ QString name(QLatin1String(notify->relname));
+ if (d->seid.contains(name)) {
+ QString payload;
+#if defined PG_VERSION_NUM && PG_VERSION_NUM-0 >= 70400
+ if (notify->extra)
+ payload = d->isUtf8 ? QString::fromUtf8(notify->extra) : QString::fromLatin1(notify->extra);
+#endif
+ emit notification(name);
+ QSqlDriver::NotificationSource source = (notify->be_pid == PQbackendPID(d->connection)) ? QSqlDriver::SelfSource : QSqlDriver::OtherSource;
+ emit notification(name, source, payload);
+ }
+ else
+ qWarning("QPSQLDriver: received notification for '%s' which isn't subscribed to.",
+ qPrintable(name));
+
+ qPQfreemem(notify);
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/sqldrivers/psql/qsql_psql_p.h b/src/plugins/sqldrivers/psql/qsql_psql_p.h
new file mode 100644
index 0000000000..8468b9af93
--- /dev/null
+++ b/src/plugins/sqldrivers/psql/qsql_psql_p.h
@@ -0,0 +1,128 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSQL_PSQL_H
+#define QSQL_PSQL_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtSql/qsqldriver.h>
+
+#ifdef QT_PLUGIN
+#define Q_EXPORT_SQLDRIVER_PSQL
+#else
+#define Q_EXPORT_SQLDRIVER_PSQL Q_SQL_EXPORT
+#endif
+
+typedef struct pg_conn PGconn;
+typedef struct pg_result PGresult;
+
+QT_BEGIN_NAMESPACE
+
+class QPSQLDriverPrivate;
+
+class Q_EXPORT_SQLDRIVER_PSQL QPSQLDriver : public QSqlDriver
+{
+ friend class QPSQLResultPrivate;
+ Q_DECLARE_PRIVATE(QPSQLDriver)
+ Q_OBJECT
+public:
+ enum Protocol {
+ VersionUnknown = -1,
+ Version6 = 6,
+ Version7 = 7,
+ Version71 = 8,
+ Version73 = 9,
+ Version74 = 10,
+ Version8 = 11,
+ Version81 = 12,
+ Version82 = 13,
+ Version83 = 14,
+ Version84 = 15,
+ Version9 = 16
+ };
+
+ explicit QPSQLDriver(QObject *parent=0);
+ explicit QPSQLDriver(PGconn *conn, QObject *parent=0);
+ ~QPSQLDriver();
+ bool hasFeature(DriverFeature f) const Q_DECL_OVERRIDE;
+ bool open(const QString & db,
+ const QString & user,
+ const QString & password,
+ const QString & host,
+ int port,
+ const QString& connOpts) Q_DECL_OVERRIDE;
+ bool isOpen() const Q_DECL_OVERRIDE;
+ void close() Q_DECL_OVERRIDE;
+ QSqlResult *createResult() const Q_DECL_OVERRIDE;
+ QStringList tables(QSql::TableType) const Q_DECL_OVERRIDE;
+ QSqlIndex primaryIndex(const QString& tablename) const Q_DECL_OVERRIDE;
+ QSqlRecord record(const QString& tablename) const Q_DECL_OVERRIDE;
+
+ Protocol protocol() const;
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+ QString escapeIdentifier(const QString &identifier, IdentifierType type) const Q_DECL_OVERRIDE;
+ QString formatValue(const QSqlField &field, bool trimStrings) const Q_DECL_OVERRIDE;
+
+ bool subscribeToNotification(const QString &name) Q_DECL_OVERRIDE;
+ bool unsubscribeFromNotification(const QString &name) Q_DECL_OVERRIDE;
+ QStringList subscribedToNotifications() const Q_DECL_OVERRIDE;
+
+protected:
+ bool beginTransaction() Q_DECL_OVERRIDE;
+ bool commitTransaction() Q_DECL_OVERRIDE;
+ bool rollbackTransaction() Q_DECL_OVERRIDE;
+
+private Q_SLOTS:
+ void _q_handleNotification(int);
+};
+
+QT_END_NAMESPACE
+
+#endif // QSQL_PSQL_H
diff --git a/src/plugins/sqldrivers/sqldrivers.pro b/src/plugins/sqldrivers/sqldrivers.pro
index 39c58d4f2b..30fb6019ce 100644
--- a/src/plugins/sqldrivers/sqldrivers.pro
+++ b/src/plugins/sqldrivers/sqldrivers.pro
@@ -1,11 +1,12 @@
TEMPLATE = subdirs
+QT_FOR_CONFIG += sql
-contains(sql-plugins, psql) : SUBDIRS += psql
-contains(sql-plugins, mysql) : SUBDIRS += mysql
-contains(sql-plugins, odbc) : SUBDIRS += odbc
-contains(sql-plugins, tds) : SUBDIRS += tds
-contains(sql-plugins, oci) : SUBDIRS += oci
-contains(sql-plugins, db2) : SUBDIRS += db2
-contains(sql-plugins, sqlite) : SUBDIRS += sqlite
-contains(sql-plugins, sqlite2) : SUBDIRS += sqlite2
-contains(sql-plugins, ibase) : SUBDIRS += ibase
+qtConfig(sql-psql) : SUBDIRS += psql
+qtConfig(sql-mysql) : SUBDIRS += mysql
+qtConfig(sql-odbc) : SUBDIRS += odbc
+qtConfig(sql-tds) : SUBDIRS += tds
+qtConfig(sql-oci) : SUBDIRS += oci
+qtConfig(sql-db2) : SUBDIRS += db2
+qtConfig(sql-sqlite) : SUBDIRS += sqlite
+qtConfig(sql-sqlite2) : SUBDIRS += sqlite2
+qtConfig(sql-ibase) : SUBDIRS += ibase
diff --git a/src/plugins/sqldrivers/sqlite/qsql_sqlite.cpp b/src/plugins/sqldrivers/sqlite/qsql_sqlite.cpp
new file mode 100644
index 0000000000..1cb0f10494
--- /dev/null
+++ b/src/plugins/sqldrivers/sqlite/qsql_sqlite.cpp
@@ -0,0 +1,903 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsql_sqlite_p.h"
+
+#include <qcoreapplication.h>
+#include <qdatetime.h>
+#include <qvariant.h>
+#include <qsqlerror.h>
+#include <qsqlfield.h>
+#include <qsqlindex.h>
+#include <qsqlquery.h>
+#include <QtSql/private/qsqlcachedresult_p.h>
+#include <QtSql/private/qsqldriver_p.h>
+#include <qstringlist.h>
+#include <qvector.h>
+#include <qdebug.h>
+
+#if defined Q_OS_WIN
+# include <qt_windows.h>
+#else
+# include <unistd.h>
+#endif
+
+#include <sqlite3.h>
+#include <functional>
+
+Q_DECLARE_OPAQUE_POINTER(sqlite3*)
+Q_DECLARE_METATYPE(sqlite3*)
+
+Q_DECLARE_OPAQUE_POINTER(sqlite3_stmt*)
+Q_DECLARE_METATYPE(sqlite3_stmt*)
+
+QT_BEGIN_NAMESPACE
+
+static QString _q_escapeIdentifier(const QString &identifier)
+{
+ QString res = identifier;
+ if (!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"'))) {
+ res.replace(QLatin1Char('"'), QLatin1String("\"\""));
+ res.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
+ res.replace(QLatin1Char('.'), QLatin1String("\".\""));
+ }
+ return res;
+}
+
+static QVariant::Type qGetColumnType(const QString &tpName)
+{
+ const QString typeName = tpName.toLower();
+
+ if (typeName == QLatin1String("integer")
+ || typeName == QLatin1String("int"))
+ return QVariant::Int;
+ if (typeName == QLatin1String("double")
+ || typeName == QLatin1String("float")
+ || typeName == QLatin1String("real")
+ || typeName.startsWith(QLatin1String("numeric")))
+ return QVariant::Double;
+ if (typeName == QLatin1String("blob"))
+ return QVariant::ByteArray;
+ if (typeName == QLatin1String("boolean")
+ || typeName == QLatin1String("bool"))
+ return QVariant::Bool;
+ return QVariant::String;
+}
+
+static QSqlError qMakeError(sqlite3 *access, const QString &descr, QSqlError::ErrorType type,
+ int errorCode = -1)
+{
+ return QSqlError(descr,
+ QString(reinterpret_cast<const QChar *>(sqlite3_errmsg16(access))),
+ type, QString::number(errorCode));
+}
+
+class QSQLiteResultPrivate;
+
+class QSQLiteResult : public QSqlCachedResult
+{
+ Q_DECLARE_PRIVATE(QSQLiteResult)
+ friend class QSQLiteDriver;
+
+public:
+ explicit QSQLiteResult(const QSQLiteDriver* db);
+ ~QSQLiteResult();
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+protected:
+ bool gotoNext(QSqlCachedResult::ValueCache& row, int idx) Q_DECL_OVERRIDE;
+ bool reset(const QString &query) Q_DECL_OVERRIDE;
+ bool prepare(const QString &query) Q_DECL_OVERRIDE;
+ bool exec() Q_DECL_OVERRIDE;
+ int size() Q_DECL_OVERRIDE;
+ int numRowsAffected() Q_DECL_OVERRIDE;
+ QVariant lastInsertId() const Q_DECL_OVERRIDE;
+ QSqlRecord record() const Q_DECL_OVERRIDE;
+ void detachFromResultSet() Q_DECL_OVERRIDE;
+ void virtual_hook(int id, void *data) Q_DECL_OVERRIDE;
+};
+
+class QSQLiteDriverPrivate : public QSqlDriverPrivate
+{
+ Q_DECLARE_PUBLIC(QSQLiteDriver)
+
+public:
+ inline QSQLiteDriverPrivate() : QSqlDriverPrivate(), access(0) { dbmsType = QSqlDriver::SQLite; }
+ sqlite3 *access;
+ QList <QSQLiteResult *> results;
+ QStringList notificationid;
+};
+
+
+class QSQLiteResultPrivate: public QSqlCachedResultPrivate
+{
+ Q_DECLARE_PUBLIC(QSQLiteResult)
+
+public:
+ Q_DECLARE_SQLDRIVER_PRIVATE(QSQLiteDriver)
+ QSQLiteResultPrivate(QSQLiteResult *q, const QSQLiteDriver *drv);
+ void cleanup();
+ bool fetchNext(QSqlCachedResult::ValueCache &values, int idx, bool initialFetch);
+ // initializes the recordInfo and the cache
+ void initColumns(bool emptyResultset);
+ void finalize();
+
+ sqlite3_stmt *stmt;
+
+ bool skippedStatus; // the status of the fetchNext() that's skipped
+ bool skipRow; // skip the next fetchNext()?
+ QSqlRecord rInf;
+ QVector<QVariant> firstRow;
+};
+
+QSQLiteResultPrivate::QSQLiteResultPrivate(QSQLiteResult *q, const QSQLiteDriver *drv)
+ : QSqlCachedResultPrivate(q, drv),
+ stmt(0),
+ skippedStatus(false),
+ skipRow(false)
+{
+}
+
+void QSQLiteResultPrivate::cleanup()
+{
+ Q_Q(QSQLiteResult);
+ finalize();
+ rInf.clear();
+ skippedStatus = false;
+ skipRow = false;
+ q->setAt(QSql::BeforeFirstRow);
+ q->setActive(false);
+ q->cleanup();
+}
+
+void QSQLiteResultPrivate::finalize()
+{
+ if (!stmt)
+ return;
+
+ sqlite3_finalize(stmt);
+ stmt = 0;
+}
+
+void QSQLiteResultPrivate::initColumns(bool emptyResultset)
+{
+ Q_Q(QSQLiteResult);
+ int nCols = sqlite3_column_count(stmt);
+ if (nCols <= 0)
+ return;
+
+ q->init(nCols);
+
+ for (int i = 0; i < nCols; ++i) {
+ QString colName = QString(reinterpret_cast<const QChar *>(
+ sqlite3_column_name16(stmt, i))
+ ).remove(QLatin1Char('"'));
+
+ // must use typeName for resolving the type to match QSqliteDriver::record
+ QString typeName = QString(reinterpret_cast<const QChar *>(
+ sqlite3_column_decltype16(stmt, i)));
+ // sqlite3_column_type is documented to have undefined behavior if the result set is empty
+ int stp = emptyResultset ? -1 : sqlite3_column_type(stmt, i);
+
+ QVariant::Type fieldType;
+
+ if (!typeName.isEmpty()) {
+ fieldType = qGetColumnType(typeName);
+ } else {
+ // Get the proper type for the field based on stp value
+ switch (stp) {
+ case SQLITE_INTEGER:
+ fieldType = QVariant::Int;
+ break;
+ case SQLITE_FLOAT:
+ fieldType = QVariant::Double;
+ break;
+ case SQLITE_BLOB:
+ fieldType = QVariant::ByteArray;
+ break;
+ case SQLITE_TEXT:
+ fieldType = QVariant::String;
+ break;
+ case SQLITE_NULL:
+ default:
+ fieldType = QVariant::Invalid;
+ break;
+ }
+ }
+
+ QSqlField fld(colName, fieldType);
+ fld.setSqlType(stp);
+ rInf.append(fld);
+ }
+}
+
+bool QSQLiteResultPrivate::fetchNext(QSqlCachedResult::ValueCache &values, int idx, bool initialFetch)
+{
+ Q_Q(QSQLiteResult);
+ int res;
+ int i;
+
+ if (skipRow) {
+ // already fetched
+ Q_ASSERT(!initialFetch);
+ skipRow = false;
+ for(int i=0;i<firstRow.count();i++)
+ values[i]=firstRow[i];
+ return skippedStatus;
+ }
+ skipRow = initialFetch;
+
+ if(initialFetch) {
+ firstRow.clear();
+ firstRow.resize(sqlite3_column_count(stmt));
+ }
+
+ if (!stmt) {
+ q->setLastError(QSqlError(QCoreApplication::translate("QSQLiteResult", "Unable to fetch row"),
+ QCoreApplication::translate("QSQLiteResult", "No query"), QSqlError::ConnectionError));
+ q->setAt(QSql::AfterLastRow);
+ return false;
+ }
+ res = sqlite3_step(stmt);
+
+ switch(res) {
+ case SQLITE_ROW:
+ // check to see if should fill out columns
+ if (rInf.isEmpty())
+ // must be first call.
+ initColumns(false);
+ if (idx < 0 && !initialFetch)
+ return true;
+ for (i = 0; i < rInf.count(); ++i) {
+ switch (sqlite3_column_type(stmt, i)) {
+ case SQLITE_BLOB:
+ values[i + idx] = QByteArray(static_cast<const char *>(
+ sqlite3_column_blob(stmt, i)),
+ sqlite3_column_bytes(stmt, i));
+ break;
+ case SQLITE_INTEGER:
+ values[i + idx] = sqlite3_column_int64(stmt, i);
+ break;
+ case SQLITE_FLOAT:
+ switch(q->numericalPrecisionPolicy()) {
+ case QSql::LowPrecisionInt32:
+ values[i + idx] = sqlite3_column_int(stmt, i);
+ break;
+ case QSql::LowPrecisionInt64:
+ values[i + idx] = sqlite3_column_int64(stmt, i);
+ break;
+ case QSql::LowPrecisionDouble:
+ case QSql::HighPrecision:
+ default:
+ values[i + idx] = sqlite3_column_double(stmt, i);
+ break;
+ };
+ break;
+ case SQLITE_NULL:
+ values[i + idx] = QVariant(QVariant::String);
+ break;
+ default:
+ values[i + idx] = QString(reinterpret_cast<const QChar *>(
+ sqlite3_column_text16(stmt, i)),
+ sqlite3_column_bytes16(stmt, i) / sizeof(QChar));
+ break;
+ }
+ }
+ return true;
+ case SQLITE_DONE:
+ if (rInf.isEmpty())
+ // must be first call.
+ initColumns(true);
+ q->setAt(QSql::AfterLastRow);
+ sqlite3_reset(stmt);
+ return false;
+ case SQLITE_CONSTRAINT:
+ case SQLITE_ERROR:
+ // SQLITE_ERROR is a generic error code and we must call sqlite3_reset()
+ // to get the specific error message.
+ res = sqlite3_reset(stmt);
+ q->setLastError(qMakeError(drv_d_func()->access, QCoreApplication::translate("QSQLiteResult",
+ "Unable to fetch row"), QSqlError::ConnectionError, res));
+ q->setAt(QSql::AfterLastRow);
+ return false;
+ case SQLITE_MISUSE:
+ case SQLITE_BUSY:
+ default:
+ // something wrong, don't get col info, but still return false
+ q->setLastError(qMakeError(drv_d_func()->access, QCoreApplication::translate("QSQLiteResult",
+ "Unable to fetch row"), QSqlError::ConnectionError, res));
+ sqlite3_reset(stmt);
+ q->setAt(QSql::AfterLastRow);
+ return false;
+ }
+ return false;
+}
+
+QSQLiteResult::QSQLiteResult(const QSQLiteDriver* db)
+ : QSqlCachedResult(*new QSQLiteResultPrivate(this, db))
+{
+ Q_D(QSQLiteResult);
+ const_cast<QSQLiteDriverPrivate*>(d->drv_d_func())->results.append(this);
+}
+
+QSQLiteResult::~QSQLiteResult()
+{
+ Q_D(QSQLiteResult);
+ if (d->drv_d_func())
+ const_cast<QSQLiteDriverPrivate*>(d->drv_d_func())->results.removeOne(this);
+ d->cleanup();
+}
+
+void QSQLiteResult::virtual_hook(int id, void *data)
+{
+ QSqlCachedResult::virtual_hook(id, data);
+}
+
+bool QSQLiteResult::reset(const QString &query)
+{
+ if (!prepare(query))
+ return false;
+ return exec();
+}
+
+bool QSQLiteResult::prepare(const QString &query)
+{
+ Q_D(QSQLiteResult);
+ if (!driver() || !driver()->isOpen() || driver()->isOpenError())
+ return false;
+
+ d->cleanup();
+
+ setSelect(false);
+
+ const void *pzTail = NULL;
+
+#if (SQLITE_VERSION_NUMBER >= 3003011)
+ int res = sqlite3_prepare16_v2(d->drv_d_func()->access, query.constData(), (query.size() + 1) * sizeof(QChar),
+ &d->stmt, &pzTail);
+#else
+ int res = sqlite3_prepare16(d->access, query.constData(), (query.size() + 1) * sizeof(QChar),
+ &d->stmt, &pzTail);
+#endif
+
+ if (res != SQLITE_OK) {
+ setLastError(qMakeError(d->drv_d_func()->access, QCoreApplication::translate("QSQLiteResult",
+ "Unable to execute statement"), QSqlError::StatementError, res));
+ d->finalize();
+ return false;
+ } else if (pzTail && !QString(reinterpret_cast<const QChar *>(pzTail)).trimmed().isEmpty()) {
+ setLastError(qMakeError(d->drv_d_func()->access, QCoreApplication::translate("QSQLiteResult",
+ "Unable to execute multiple statements at a time"), QSqlError::StatementError, SQLITE_MISUSE));
+ d->finalize();
+ return false;
+ }
+ return true;
+}
+
+bool QSQLiteResult::exec()
+{
+ Q_D(QSQLiteResult);
+ const QVector<QVariant> values = boundValues();
+
+ d->skippedStatus = false;
+ d->skipRow = false;
+ d->rInf.clear();
+ clearValues();
+ setLastError(QSqlError());
+
+ int res = sqlite3_reset(d->stmt);
+ if (res != SQLITE_OK) {
+ setLastError(qMakeError(d->drv_d_func()->access, QCoreApplication::translate("QSQLiteResult",
+ "Unable to reset statement"), QSqlError::StatementError, res));
+ d->finalize();
+ return false;
+ }
+ int paramCount = sqlite3_bind_parameter_count(d->stmt);
+ if (paramCount == values.count()) {
+ for (int i = 0; i < paramCount; ++i) {
+ res = SQLITE_OK;
+ const QVariant value = values.at(i);
+
+ if (value.isNull()) {
+ res = sqlite3_bind_null(d->stmt, i + 1);
+ } else {
+ switch (value.type()) {
+ case QVariant::ByteArray: {
+ const QByteArray *ba = static_cast<const QByteArray*>(value.constData());
+ res = sqlite3_bind_blob(d->stmt, i + 1, ba->constData(),
+ ba->size(), SQLITE_STATIC);
+ break; }
+ case QVariant::Int:
+ case QVariant::Bool:
+ res = sqlite3_bind_int(d->stmt, i + 1, value.toInt());
+ break;
+ case QVariant::Double:
+ res = sqlite3_bind_double(d->stmt, i + 1, value.toDouble());
+ break;
+ case QVariant::UInt:
+ case QVariant::LongLong:
+ res = sqlite3_bind_int64(d->stmt, i + 1, value.toLongLong());
+ break;
+ case QVariant::DateTime: {
+ const QDateTime dateTime = value.toDateTime();
+ const QString str = dateTime.toString(QStringLiteral("yyyy-MM-ddThh:mm:ss.zzz"));
+ res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
+ str.size() * sizeof(ushort), SQLITE_TRANSIENT);
+ break;
+ }
+ case QVariant::Time: {
+ const QTime time = value.toTime();
+ const QString str = time.toString(QStringLiteral("hh:mm:ss.zzz"));
+ res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
+ str.size() * sizeof(ushort), SQLITE_TRANSIENT);
+ break;
+ }
+ case QVariant::String: {
+ // lifetime of string == lifetime of its qvariant
+ const QString *str = static_cast<const QString*>(value.constData());
+ res = sqlite3_bind_text16(d->stmt, i + 1, str->utf16(),
+ (str->size()) * sizeof(QChar), SQLITE_STATIC);
+ break; }
+ default: {
+ QString str = value.toString();
+ // SQLITE_TRANSIENT makes sure that sqlite buffers the data
+ res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
+ (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
+ break; }
+ }
+ }
+ if (res != SQLITE_OK) {
+ setLastError(qMakeError(d->drv_d_func()->access, QCoreApplication::translate("QSQLiteResult",
+ "Unable to bind parameters"), QSqlError::StatementError, res));
+ d->finalize();
+ return false;
+ }
+ }
+ } else {
+ setLastError(QSqlError(QCoreApplication::translate("QSQLiteResult",
+ "Parameter count mismatch"), QString(), QSqlError::StatementError));
+ return false;
+ }
+ d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
+ if (lastError().isValid()) {
+ setSelect(false);
+ setActive(false);
+ return false;
+ }
+ setSelect(!d->rInf.isEmpty());
+ setActive(true);
+ return true;
+}
+
+bool QSQLiteResult::gotoNext(QSqlCachedResult::ValueCache& row, int idx)
+{
+ Q_D(QSQLiteResult);
+ return d->fetchNext(row, idx, false);
+}
+
+int QSQLiteResult::size()
+{
+ return -1;
+}
+
+int QSQLiteResult::numRowsAffected()
+{
+ Q_D(const QSQLiteResult);
+ return sqlite3_changes(d->drv_d_func()->access);
+}
+
+QVariant QSQLiteResult::lastInsertId() const
+{
+ Q_D(const QSQLiteResult);
+ if (isActive()) {
+ qint64 id = sqlite3_last_insert_rowid(d->drv_d_func()->access);
+ if (id)
+ return id;
+ }
+ return QVariant();
+}
+
+QSqlRecord QSQLiteResult::record() const
+{
+ Q_D(const QSQLiteResult);
+ if (!isActive() || !isSelect())
+ return QSqlRecord();
+ return d->rInf;
+}
+
+void QSQLiteResult::detachFromResultSet()
+{
+ Q_D(QSQLiteResult);
+ if (d->stmt)
+ sqlite3_reset(d->stmt);
+}
+
+QVariant QSQLiteResult::handle() const
+{
+ Q_D(const QSQLiteResult);
+ return QVariant::fromValue(d->stmt);
+}
+
+/////////////////////////////////////////////////////////
+
+QSQLiteDriver::QSQLiteDriver(QObject * parent)
+ : QSqlDriver(*new QSQLiteDriverPrivate, parent)
+{
+}
+
+QSQLiteDriver::QSQLiteDriver(sqlite3 *connection, QObject *parent)
+ : QSqlDriver(*new QSQLiteDriverPrivate, parent)
+{
+ Q_D(QSQLiteDriver);
+ d->access = connection;
+ setOpen(true);
+ setOpenError(false);
+}
+
+
+QSQLiteDriver::~QSQLiteDriver()
+{
+ close();
+}
+
+bool QSQLiteDriver::hasFeature(DriverFeature f) const
+{
+ switch (f) {
+ case BLOB:
+ case Transactions:
+ case Unicode:
+ case LastInsertId:
+ case PreparedQueries:
+ case PositionalPlaceholders:
+ case SimpleLocking:
+ case FinishQuery:
+ case LowPrecisionNumbers:
+ case EventNotifications:
+ return true;
+ case QuerySize:
+ case NamedPlaceholders:
+ case BatchOperations:
+ case MultipleResultSets:
+ case CancelQuery:
+ return false;
+ }
+ return false;
+}
+
+/*
+ SQLite dbs have no user name, passwords, hosts or ports.
+ just file names.
+*/
+bool QSQLiteDriver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &conOpts)
+{
+ Q_D(QSQLiteDriver);
+ if (isOpen())
+ close();
+
+
+ int timeOut = 5000;
+ bool sharedCache = false;
+ bool openReadOnlyOption = false;
+ bool openUriOption = false;
+
+ const auto opts = conOpts.splitRef(QLatin1Char(';'));
+ for (auto option : opts) {
+ option = option.trimmed();
+ if (option.startsWith(QLatin1String("QSQLITE_BUSY_TIMEOUT"))) {
+ option = option.mid(20).trimmed();
+ if (option.startsWith(QLatin1Char('='))) {
+ bool ok;
+ const int nt = option.mid(1).trimmed().toInt(&ok);
+ if (ok)
+ timeOut = nt;
+ }
+ } else if (option == QLatin1String("QSQLITE_OPEN_READONLY")) {
+ openReadOnlyOption = true;
+ } else if (option == QLatin1String("QSQLITE_OPEN_URI")) {
+ openUriOption = true;
+ } else if (option == QLatin1String("QSQLITE_ENABLE_SHARED_CACHE")) {
+ sharedCache = true;
+ }
+ }
+
+ int openMode = (openReadOnlyOption ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE));
+ if (openUriOption)
+ openMode |= SQLITE_OPEN_URI;
+
+ sqlite3_enable_shared_cache(sharedCache);
+
+ if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) {
+ sqlite3_busy_timeout(d->access, timeOut);
+ setOpen(true);
+ setOpenError(false);
+ return true;
+ } else {
+ if (d->access) {
+ sqlite3_close(d->access);
+ d->access = 0;
+ }
+
+ setLastError(qMakeError(d->access, tr("Error opening database"),
+ QSqlError::ConnectionError));
+ setOpenError(true);
+ return false;
+ }
+}
+
+void QSQLiteDriver::close()
+{
+ Q_D(QSQLiteDriver);
+ if (isOpen()) {
+ for (QSQLiteResult *result : qAsConst(d->results))
+ result->d_func()->finalize();
+
+ if (d->access && (d->notificationid.count() > 0)) {
+ d->notificationid.clear();
+ sqlite3_update_hook(d->access, NULL, NULL);
+ }
+
+ if (sqlite3_close(d->access) != SQLITE_OK)
+ setLastError(qMakeError(d->access, tr("Error closing database"), QSqlError::ConnectionError));
+ d->access = 0;
+ setOpen(false);
+ setOpenError(false);
+ }
+}
+
+QSqlResult *QSQLiteDriver::createResult() const
+{
+ return new QSQLiteResult(this);
+}
+
+bool QSQLiteDriver::beginTransaction()
+{
+ if (!isOpen() || isOpenError())
+ return false;
+
+ QSqlQuery q(createResult());
+ if (!q.exec(QLatin1String("BEGIN"))) {
+ setLastError(QSqlError(tr("Unable to begin transaction"),
+ q.lastError().databaseText(), QSqlError::TransactionError));
+ return false;
+ }
+
+ return true;
+}
+
+bool QSQLiteDriver::commitTransaction()
+{
+ if (!isOpen() || isOpenError())
+ return false;
+
+ QSqlQuery q(createResult());
+ if (!q.exec(QLatin1String("COMMIT"))) {
+ setLastError(QSqlError(tr("Unable to commit transaction"),
+ q.lastError().databaseText(), QSqlError::TransactionError));
+ return false;
+ }
+
+ return true;
+}
+
+bool QSQLiteDriver::rollbackTransaction()
+{
+ if (!isOpen() || isOpenError())
+ return false;
+
+ QSqlQuery q(createResult());
+ if (!q.exec(QLatin1String("ROLLBACK"))) {
+ setLastError(QSqlError(tr("Unable to rollback transaction"),
+ q.lastError().databaseText(), QSqlError::TransactionError));
+ return false;
+ }
+
+ return true;
+}
+
+QStringList QSQLiteDriver::tables(QSql::TableType type) const
+{
+ QStringList res;
+ if (!isOpen())
+ return res;
+
+ QSqlQuery q(createResult());
+ q.setForwardOnly(true);
+
+ QString sql = QLatin1String("SELECT name FROM sqlite_master WHERE %1 "
+ "UNION ALL SELECT name FROM sqlite_temp_master WHERE %1");
+ if ((type & QSql::Tables) && (type & QSql::Views))
+ sql = sql.arg(QLatin1String("type='table' OR type='view'"));
+ else if (type & QSql::Tables)
+ sql = sql.arg(QLatin1String("type='table'"));
+ else if (type & QSql::Views)
+ sql = sql.arg(QLatin1String("type='view'"));
+ else
+ sql.clear();
+
+ if (!sql.isEmpty() && q.exec(sql)) {
+ while(q.next())
+ res.append(q.value(0).toString());
+ }
+
+ if (type & QSql::SystemTables) {
+ // there are no internal tables beside this one:
+ res.append(QLatin1String("sqlite_master"));
+ }
+
+ return res;
+}
+
+static QSqlIndex qGetTableInfo(QSqlQuery &q, const QString &tableName, bool onlyPIndex = false)
+{
+ QString schema;
+ QString table(tableName);
+ int indexOfSeparator = tableName.indexOf(QLatin1Char('.'));
+ if (indexOfSeparator > -1) {
+ schema = tableName.left(indexOfSeparator).append(QLatin1Char('.'));
+ table = tableName.mid(indexOfSeparator + 1);
+ }
+ q.exec(QLatin1String("PRAGMA ") + schema + QLatin1String("table_info (") + _q_escapeIdentifier(table) + QLatin1Char(')'));
+
+ QSqlIndex ind;
+ while (q.next()) {
+ bool isPk = q.value(5).toInt();
+ if (onlyPIndex && !isPk)
+ continue;
+ QString typeName = q.value(2).toString().toLower();
+ QSqlField fld(q.value(1).toString(), qGetColumnType(typeName));
+ if (isPk && (typeName == QLatin1String("integer")))
+ // INTEGER PRIMARY KEY fields are auto-generated in sqlite
+ // INT PRIMARY KEY is not the same as INTEGER PRIMARY KEY!
+ fld.setAutoValue(true);
+ fld.setRequired(q.value(3).toInt() != 0);
+ fld.setDefaultValue(q.value(4));
+ ind.append(fld);
+ }
+ return ind;
+}
+
+QSqlIndex QSQLiteDriver::primaryIndex(const QString &tblname) const
+{
+ if (!isOpen())
+ return QSqlIndex();
+
+ QString table = tblname;
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+
+ QSqlQuery q(createResult());
+ q.setForwardOnly(true);
+ return qGetTableInfo(q, table, true);
+}
+
+QSqlRecord QSQLiteDriver::record(const QString &tbl) const
+{
+ if (!isOpen())
+ return QSqlRecord();
+
+ QString table = tbl;
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+
+ QSqlQuery q(createResult());
+ q.setForwardOnly(true);
+ return qGetTableInfo(q, table);
+}
+
+QVariant QSQLiteDriver::handle() const
+{
+ Q_D(const QSQLiteDriver);
+ return QVariant::fromValue(d->access);
+}
+
+QString QSQLiteDriver::escapeIdentifier(const QString &identifier, IdentifierType type) const
+{
+ Q_UNUSED(type);
+ return _q_escapeIdentifier(identifier);
+}
+
+static void handle_sqlite_callback(void *qobj,int aoperation, char const *adbname, char const *atablename,
+ sqlite3_int64 arowid)
+{
+ Q_UNUSED(aoperation);
+ Q_UNUSED(adbname);
+ QSQLiteDriver *driver = static_cast<QSQLiteDriver *>(qobj);
+ if (driver) {
+ QMetaObject::invokeMethod(driver, "handleNotification", Qt::QueuedConnection,
+ Q_ARG(QString, QString::fromUtf8(atablename)), Q_ARG(qint64, arowid));
+ }
+}
+
+bool QSQLiteDriver::subscribeToNotification(const QString &name)
+{
+ Q_D(QSQLiteDriver);
+ if (!isOpen()) {
+ qWarning("Database not open.");
+ return false;
+ }
+
+ if (d->notificationid.contains(name)) {
+ qWarning("Already subscribing to '%s'.", qPrintable(name));
+ return false;
+ }
+
+ //sqlite supports only one notification callback, so only the first is registered
+ d->notificationid << name;
+ if (d->notificationid.count() == 1)
+ sqlite3_update_hook(d->access, &handle_sqlite_callback, reinterpret_cast<void *> (this));
+
+ return true;
+}
+
+bool QSQLiteDriver::unsubscribeFromNotification(const QString &name)
+{
+ Q_D(QSQLiteDriver);
+ if (!isOpen()) {
+ qWarning("Database not open.");
+ return false;
+ }
+
+ if (!d->notificationid.contains(name)) {
+ qWarning("Not subscribed to '%s'.", qPrintable(name));
+ return false;
+ }
+
+ d->notificationid.removeAll(name);
+ if (d->notificationid.isEmpty())
+ sqlite3_update_hook(d->access, NULL, NULL);
+
+ return true;
+}
+
+QStringList QSQLiteDriver::subscribedToNotifications() const
+{
+ Q_D(const QSQLiteDriver);
+ return d->notificationid;
+}
+
+void QSQLiteDriver::handleNotification(const QString &tableName, qint64 rowid)
+{
+ Q_D(const QSQLiteDriver);
+ if (d->notificationid.contains(tableName)) {
+ emit notification(tableName);
+ emit notification(tableName, QSqlDriver::UnknownSource, QVariant(rowid));
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/sqldrivers/sqlite/qsql_sqlite_p.h b/src/plugins/sqldrivers/sqlite/qsql_sqlite_p.h
new file mode 100644
index 0000000000..ca969a4b53
--- /dev/null
+++ b/src/plugins/sqldrivers/sqlite/qsql_sqlite_p.h
@@ -0,0 +1,106 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSQL_SQLITE_H
+#define QSQL_SQLITE_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtSql/qsqldriver.h>
+
+struct sqlite3;
+
+#ifdef QT_PLUGIN
+#define Q_EXPORT_SQLDRIVER_SQLITE
+#else
+#define Q_EXPORT_SQLDRIVER_SQLITE Q_SQL_EXPORT
+#endif
+
+QT_BEGIN_NAMESPACE
+
+class QSqlResult;
+class QSQLiteDriverPrivate;
+
+class Q_EXPORT_SQLDRIVER_SQLITE QSQLiteDriver : public QSqlDriver
+{
+ Q_DECLARE_PRIVATE(QSQLiteDriver)
+ Q_OBJECT
+ friend class QSQLiteResultPrivate;
+public:
+ explicit QSQLiteDriver(QObject *parent = 0);
+ explicit QSQLiteDriver(sqlite3 *connection, QObject *parent = 0);
+ ~QSQLiteDriver();
+ bool hasFeature(DriverFeature f) const Q_DECL_OVERRIDE;
+ bool open(const QString & db,
+ const QString & user,
+ const QString & password,
+ const QString & host,
+ int port,
+ const QString & connOpts) Q_DECL_OVERRIDE;
+ void close() Q_DECL_OVERRIDE;
+ QSqlResult *createResult() const Q_DECL_OVERRIDE;
+ bool beginTransaction() Q_DECL_OVERRIDE;
+ bool commitTransaction() Q_DECL_OVERRIDE;
+ bool rollbackTransaction() Q_DECL_OVERRIDE;
+ QStringList tables(QSql::TableType) const Q_DECL_OVERRIDE;
+
+ QSqlRecord record(const QString& tablename) const Q_DECL_OVERRIDE;
+ QSqlIndex primaryIndex(const QString &table) const Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+ QString escapeIdentifier(const QString &identifier, IdentifierType) const Q_DECL_OVERRIDE;
+
+ bool subscribeToNotification(const QString &name) Q_DECL_OVERRIDE;
+ bool unsubscribeFromNotification(const QString &name) Q_DECL_OVERRIDE;
+ QStringList subscribedToNotifications() const Q_DECL_OVERRIDE;
+private Q_SLOTS:
+ void handleNotification(const QString &tableName, qint64 rowid);
+};
+
+QT_END_NAMESPACE
+
+#endif // QSQL_SQLITE_H
diff --git a/src/plugins/sqldrivers/sqlite/smain.cpp b/src/plugins/sqldrivers/sqlite/smain.cpp
index 94b41c9878..2ad466a61e 100644
--- a/src/plugins/sqldrivers/sqlite/smain.cpp
+++ b/src/plugins/sqldrivers/sqlite/smain.cpp
@@ -39,7 +39,7 @@
#include <qsqldriverplugin.h>
#include <qstringlist.h>
-#include "../../../../src/sql/drivers/sqlite/qsql_sqlite_p.h"
+#include "qsql_sqlite_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/sqldrivers/sqlite/sqlite.pro b/src/plugins/sqldrivers/sqlite/sqlite.pro
index cc6d02cbe8..1066bf7f51 100644
--- a/src/plugins/sqldrivers/sqlite/sqlite.pro
+++ b/src/plugins/sqldrivers/sqlite/sqlite.pro
@@ -1,8 +1,17 @@
TARGET = qsqlite
-SOURCES = smain.cpp
+QT_FOR_CONFIG += sql-private
+
+HEADERS += $$PWD/qsql_sqlite_p.h
+SOURCES += $$PWD/qsql_sqlite.cpp $$PWD/smain.cpp
+
+qtConfig(system-sqlite) {
+ QMAKE_USE += sqlite
+} else {
+ include($$PWD/../../../3rdparty/sqlite.pri)
+}
+
OTHER_FILES += sqlite.json
-include(../../../sql/drivers/sqlite/qsql_sqlite.pri)
PLUGIN_CLASS_NAME = QSQLiteDriverPlugin
include(../qsqldriverbase.pri)
diff --git a/src/plugins/sqldrivers/sqlite2/qsql_sqlite2.cpp b/src/plugins/sqldrivers/sqlite2/qsql_sqlite2.cpp
new file mode 100644
index 0000000000..67c24e4168
--- /dev/null
+++ b/src/plugins/sqldrivers/sqlite2/qsql_sqlite2.cpp
@@ -0,0 +1,615 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsql_sqlite2_p.h"
+
+#include <qcoreapplication.h>
+#include <qvariant.h>
+#include <qdatetime.h>
+#include <qfile.h>
+#include <qregexp.h>
+#include <qsqlerror.h>
+#include <qsqlfield.h>
+#include <qsqlindex.h>
+#include <qsqlquery.h>
+#include <QtSql/private/qsqlcachedresult_p.h>
+#include <QtSql/private/qsqldriver_p.h>
+#include <qstringlist.h>
+#include <qvector.h>
+
+#if !defined Q_OS_WIN
+# include <unistd.h>
+#endif
+#include <sqlite.h>
+
+typedef struct sqlite_vm sqlite_vm;
+
+Q_DECLARE_OPAQUE_POINTER(sqlite_vm*)
+Q_DECLARE_METATYPE(sqlite_vm*)
+
+Q_DECLARE_OPAQUE_POINTER(sqlite*)
+Q_DECLARE_METATYPE(sqlite*)
+
+QT_BEGIN_NAMESPACE
+
+static QVariant::Type nameToType(const QString& typeName)
+{
+ QString tName = typeName.toUpper();
+ if (tName.startsWith(QLatin1String("INT")))
+ return QVariant::Int;
+ if (tName.startsWith(QLatin1String("FLOAT")) || tName.startsWith(QLatin1String("NUMERIC")))
+ return QVariant::Double;
+ if (tName.startsWith(QLatin1String("BOOL")))
+ return QVariant::Bool;
+ // SQLite is typeless - consider everything else as string
+ return QVariant::String;
+}
+
+class QSQLite2DriverPrivate : public QSqlDriverPrivate
+{
+ Q_DECLARE_PUBLIC(QSQLite2Driver)
+
+public:
+ QSQLite2DriverPrivate();
+ sqlite *access;
+ bool utf8;
+};
+
+QSQLite2DriverPrivate::QSQLite2DriverPrivate() : QSqlDriverPrivate(), access(0)
+{
+ utf8 = (qstrcmp(sqlite_encoding, "UTF-8") == 0);
+ dbmsType = QSqlDriver::SQLite;
+}
+
+class QSQLite2ResultPrivate;
+
+class QSQLite2Result : public QSqlCachedResult
+{
+ Q_DECLARE_PRIVATE(QSQLite2Result)
+ friend class QSQLite2Driver;
+
+public:
+ explicit QSQLite2Result(const QSQLite2Driver* db);
+ ~QSQLite2Result();
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+protected:
+ bool gotoNext(QSqlCachedResult::ValueCache &row, int idx) Q_DECL_OVERRIDE;
+ bool reset(const QString &query) Q_DECL_OVERRIDE;
+ int size() Q_DECL_OVERRIDE;
+ int numRowsAffected() Q_DECL_OVERRIDE;
+ QSqlRecord record() const Q_DECL_OVERRIDE;
+ void detachFromResultSet() Q_DECL_OVERRIDE;
+ void virtual_hook(int id, void *data) Q_DECL_OVERRIDE;
+};
+
+class QSQLite2ResultPrivate: public QSqlCachedResultPrivate
+{
+ Q_DECLARE_PUBLIC(QSQLite2Result)
+
+public:
+ Q_DECLARE_SQLDRIVER_PRIVATE(QSQLite2Driver);
+ QSQLite2ResultPrivate(QSQLite2Result *q, const QSQLite2Driver *drv);
+ void cleanup();
+ bool fetchNext(QSqlCachedResult::ValueCache &values, int idx, bool initialFetch);
+ bool isSelect();
+ // initializes the recordInfo and the cache
+ void init(const char **cnames, int numCols);
+ void finalize();
+
+ // and we have too keep our own struct for the data (sqlite works via
+ // callback.
+ const char *currentTail;
+ sqlite_vm *currentMachine;
+
+ bool skippedStatus; // the status of the fetchNext() that's skipped
+ bool skipRow; // skip the next fetchNext()?
+ QSqlRecord rInf;
+ QVector<QVariant> firstRow;
+};
+
+QSQLite2ResultPrivate::QSQLite2ResultPrivate(QSQLite2Result *q, const QSQLite2Driver *drv)
+ : QSqlCachedResultPrivate(q, drv),
+ currentTail(0),
+ currentMachine(0),
+ skippedStatus(false),
+ skipRow(false)
+{
+}
+
+void QSQLite2ResultPrivate::cleanup()
+{
+ Q_Q(QSQLite2Result);
+ finalize();
+ rInf.clear();
+ currentTail = 0;
+ currentMachine = 0;
+ skippedStatus = false;
+ skipRow = false;
+ q->setAt(QSql::BeforeFirstRow);
+ q->setActive(false);
+ q->cleanup();
+}
+
+void QSQLite2ResultPrivate::finalize()
+{
+ Q_Q(QSQLite2Result);
+ if (!currentMachine)
+ return;
+
+ char* err = 0;
+ int res = sqlite_finalize(currentMachine, &err);
+ if (err) {
+ q->setLastError(QSqlError(QCoreApplication::translate("QSQLite2Result",
+ "Unable to fetch results"), QString::fromLatin1(err),
+ QSqlError::StatementError, res));
+ sqlite_freemem(err);
+ }
+ currentMachine = 0;
+}
+
+// called on first fetch
+void QSQLite2ResultPrivate::init(const char **cnames, int numCols)
+{
+ Q_Q(QSQLite2Result);
+ if (!cnames)
+ return;
+
+ rInf.clear();
+ if (numCols <= 0)
+ return;
+ q->init(numCols);
+
+ for (int i = 0; i < numCols; ++i) {
+ const char* lastDot = strrchr(cnames[i], '.');
+ const char* fieldName = lastDot ? lastDot + 1 : cnames[i];
+
+ //remove quotations around the field name if any
+ QString fieldStr = QString::fromLatin1(fieldName);
+ QLatin1Char quote('\"');
+ if ( fieldStr.length() > 2 && fieldStr.startsWith(quote) && fieldStr.endsWith(quote)) {
+ fieldStr = fieldStr.mid(1);
+ fieldStr.chop(1);
+ }
+ rInf.append(QSqlField(fieldStr,
+ nameToType(QString::fromLatin1(cnames[i+numCols]))));
+ }
+}
+
+bool QSQLite2ResultPrivate::fetchNext(QSqlCachedResult::ValueCache &values, int idx, bool initialFetch)
+{
+ Q_Q(QSQLite2Result);
+ // may be caching.
+ const char **fvals;
+ const char **cnames;
+ int colNum;
+ int res;
+ int i;
+
+ if (skipRow) {
+ // already fetched
+ Q_ASSERT(!initialFetch);
+ skipRow = false;
+ for(int i=0;i<firstRow.count(); i++)
+ values[i] = firstRow[i];
+ return skippedStatus;
+ }
+ skipRow = initialFetch;
+
+ if (!currentMachine)
+ return false;
+
+ // keep trying while busy, wish I could implement this better.
+ while ((res = sqlite_step(currentMachine, &colNum, &fvals, &cnames)) == SQLITE_BUSY) {
+ // sleep instead requesting result again immidiately.
+#if defined Q_OS_WIN
+ Sleep(1000);
+#else
+ sleep(1);
+#endif
+ }
+
+ if(initialFetch) {
+ firstRow.clear();
+ firstRow.resize(colNum);
+ }
+
+ switch(res) {
+ case SQLITE_ROW:
+ // check to see if should fill out columns
+ if (rInf.isEmpty())
+ // must be first call.
+ init(cnames, colNum);
+ if (!fvals)
+ return false;
+ if (idx < 0 && !initialFetch)
+ return true;
+ for (i = 0; i < colNum; ++i)
+ values[i + idx] = drv_d_func()->utf8 ? QString::fromUtf8(fvals[i]) : QString::fromLatin1(fvals[i]);
+ return true;
+ case SQLITE_DONE:
+ if (rInf.isEmpty())
+ // must be first call.
+ init(cnames, colNum);
+ q->setAt(QSql::AfterLastRow);
+ return false;
+ case SQLITE_ERROR:
+ case SQLITE_MISUSE:
+ default:
+ // something wrong, don't get col info, but still return false
+ finalize(); // finalize to get the error message.
+ q->setAt(QSql::AfterLastRow);
+ return false;
+ }
+ return false;
+}
+
+QSQLite2Result::QSQLite2Result(const QSQLite2Driver* db)
+ : QSqlCachedResult(*new QSQLite2ResultPrivate(this, db))
+{
+}
+
+QSQLite2Result::~QSQLite2Result()
+{
+ Q_D(QSQLite2Result);
+ d->cleanup();
+}
+
+void QSQLite2Result::virtual_hook(int id, void *data)
+{
+ QSqlCachedResult::virtual_hook(id, data);
+}
+
+/*
+ Execute \a query.
+*/
+bool QSQLite2Result::reset (const QString& query)
+{
+ Q_D(QSQLite2Result);
+ // this is where we build a query.
+ if (!driver())
+ return false;
+ if (!driver()-> isOpen() || driver()->isOpenError())
+ return false;
+
+ d->cleanup();
+
+ // Um, ok. callback based so.... pass private static function for this.
+ setSelect(false);
+ char *err = 0;
+ int res = sqlite_compile(d->drv_d_func()->access,
+ d->drv_d_func()->utf8 ? query.toUtf8().constData()
+ : query.toLatin1().constData(),
+ &(d->currentTail),
+ &(d->currentMachine),
+ &err);
+ if (res != SQLITE_OK || err) {
+ setLastError(QSqlError(QCoreApplication::translate("QSQLite2Result",
+ "Unable to execute statement"), QString::fromLatin1(err),
+ QSqlError::StatementError, res));
+ sqlite_freemem(err);
+ }
+ //if (*d->currentTail != '\000' then there is more sql to eval
+ if (!d->currentMachine) {
+ setActive(false);
+ return false;
+ }
+ // we have to fetch one row to find out about
+ // the structure of the result set
+ d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
+ if (lastError().isValid()) {
+ setSelect(false);
+ setActive(false);
+ return false;
+ }
+ setSelect(!d->rInf.isEmpty());
+ setActive(true);
+ return true;
+}
+
+bool QSQLite2Result::gotoNext(QSqlCachedResult::ValueCache& row, int idx)
+{
+ Q_D(QSQLite2Result);
+ return d->fetchNext(row, idx, false);
+}
+
+int QSQLite2Result::size()
+{
+ return -1;
+}
+
+int QSQLite2Result::numRowsAffected()
+{
+ Q_D(QSQLite2Result);
+ return sqlite_changes(d->drv_d_func()->access);
+}
+
+QSqlRecord QSQLite2Result::record() const
+{
+ Q_D(const QSQLite2Result);
+ if (!isActive() || !isSelect())
+ return QSqlRecord();
+ return d->rInf;
+}
+
+void QSQLite2Result::detachFromResultSet()
+{
+ Q_D(QSQLite2Result);
+ d->finalize();
+}
+
+QVariant QSQLite2Result::handle() const
+{
+ Q_D(const QSQLite2Result);
+ return QVariant::fromValue(d->currentMachine);
+}
+
+/////////////////////////////////////////////////////////
+
+QSQLite2Driver::QSQLite2Driver(QObject *parent)
+ : QSqlDriver(*new QSQLite2DriverPrivate, parent)
+{
+}
+
+QSQLite2Driver::QSQLite2Driver(sqlite *connection, QObject *parent)
+ : QSqlDriver(*new QSQLite2DriverPrivate, parent)
+{
+ Q_D(QSQLite2Driver);
+ d->access = connection;
+ setOpen(true);
+ setOpenError(false);
+}
+
+
+QSQLite2Driver::~QSQLite2Driver()
+{
+}
+
+bool QSQLite2Driver::hasFeature(DriverFeature f) const
+{
+ Q_D(const QSQLite2Driver);
+ switch (f) {
+ case Transactions:
+ case SimpleLocking:
+ return true;
+ case Unicode:
+ return d->utf8;
+ default:
+ return false;
+ }
+}
+
+/*
+ SQLite dbs have no user name, passwords, hosts or ports.
+ just file names.
+*/
+bool QSQLite2Driver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &)
+{
+ Q_D(QSQLite2Driver);
+ if (isOpen())
+ close();
+
+ if (db.isEmpty())
+ return false;
+
+ char* err = 0;
+ d->access = sqlite_open(QFile::encodeName(db), 0, &err);
+ if (err) {
+ setLastError(QSqlError(tr("Error opening database"), QString::fromLatin1(err),
+ QSqlError::ConnectionError));
+ sqlite_freemem(err);
+ err = 0;
+ }
+
+ if (d->access) {
+ setOpen(true);
+ setOpenError(false);
+ return true;
+ }
+ setOpenError(true);
+ return false;
+}
+
+void QSQLite2Driver::close()
+{
+ Q_D(QSQLite2Driver);
+ if (isOpen()) {
+ sqlite_close(d->access);
+ d->access = 0;
+ setOpen(false);
+ setOpenError(false);
+ }
+}
+
+QSqlResult *QSQLite2Driver::createResult() const
+{
+ return new QSQLite2Result(this);
+}
+
+bool QSQLite2Driver::beginTransaction()
+{
+ Q_D(QSQLite2Driver);
+ if (!isOpen() || isOpenError())
+ return false;
+
+ char* err;
+ int res = sqlite_exec(d->access, "BEGIN", 0, this, &err);
+
+ if (res == SQLITE_OK)
+ return true;
+
+ setLastError(QSqlError(tr("Unable to begin transaction"),
+ QString::fromLatin1(err), QSqlError::TransactionError, res));
+ sqlite_freemem(err);
+ return false;
+}
+
+bool QSQLite2Driver::commitTransaction()
+{
+ Q_D(QSQLite2Driver);
+ if (!isOpen() || isOpenError())
+ return false;
+
+ char* err;
+ int res = sqlite_exec(d->access, "COMMIT", 0, this, &err);
+
+ if (res == SQLITE_OK)
+ return true;
+
+ setLastError(QSqlError(tr("Unable to commit transaction"),
+ QString::fromLatin1(err), QSqlError::TransactionError, res));
+ sqlite_freemem(err);
+ return false;
+}
+
+bool QSQLite2Driver::rollbackTransaction()
+{
+ Q_D(QSQLite2Driver);
+ if (!isOpen() || isOpenError())
+ return false;
+
+ char* err;
+ int res = sqlite_exec(d->access, "ROLLBACK", 0, this, &err);
+
+ if (res == SQLITE_OK)
+ return true;
+
+ setLastError(QSqlError(tr("Unable to rollback transaction"),
+ QString::fromLatin1(err), QSqlError::TransactionError, res));
+ sqlite_freemem(err);
+ return false;
+}
+
+QStringList QSQLite2Driver::tables(QSql::TableType type) const
+{
+ QStringList res;
+ if (!isOpen())
+ return res;
+
+ QSqlQuery q(createResult());
+ q.setForwardOnly(true);
+ if ((type & QSql::Tables) && (type & QSql::Views))
+ q.exec(QLatin1String("SELECT name FROM sqlite_master WHERE type='table' OR type='view'"));
+ else if (type & QSql::Tables)
+ q.exec(QLatin1String("SELECT name FROM sqlite_master WHERE type='table'"));
+ else if (type & QSql::Views)
+ q.exec(QLatin1String("SELECT name FROM sqlite_master WHERE type='view'"));
+
+ if (q.isActive()) {
+ while(q.next())
+ res.append(q.value(0).toString());
+ }
+
+ if (type & QSql::SystemTables) {
+ // there are no internal tables beside this one:
+ res.append(QLatin1String("sqlite_master"));
+ }
+
+ return res;
+}
+
+QSqlIndex QSQLite2Driver::primaryIndex(const QString &tblname) const
+{
+ QSqlRecord rec(record(tblname)); // expensive :(
+
+ if (!isOpen())
+ return QSqlIndex();
+
+ QSqlQuery q(createResult());
+ q.setForwardOnly(true);
+ QString table = tblname;
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+ // finrst find a UNIQUE INDEX
+ q.exec(QLatin1String("PRAGMA index_list('") + table + QLatin1String("');"));
+ QString indexname;
+ while(q.next()) {
+ if (q.value(2).toInt()==1) {
+ indexname = q.value(1).toString();
+ break;
+ }
+ }
+ if (indexname.isEmpty())
+ return QSqlIndex();
+
+ q.exec(QLatin1String("PRAGMA index_info('") + indexname + QLatin1String("');"));
+
+ QSqlIndex index(table, indexname);
+ while(q.next()) {
+ QString name = q.value(2).toString();
+ QVariant::Type type = QVariant::Invalid;
+ if (rec.contains(name))
+ type = rec.field(name).type();
+ index.append(QSqlField(name, type));
+ }
+ return index;
+}
+
+QSqlRecord QSQLite2Driver::record(const QString &tbl) const
+{
+ if (!isOpen())
+ return QSqlRecord();
+ QString table = tbl;
+ if (isIdentifierEscaped(tbl, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+
+ QSqlQuery q(createResult());
+ q.setForwardOnly(true);
+ q.exec(QLatin1String("SELECT * FROM ") + tbl + QLatin1String(" LIMIT 1"));
+ return q.record();
+}
+
+QVariant QSQLite2Driver::handle() const
+{
+ Q_D(const QSQLite2Driver);
+ return QVariant::fromValue(d->access);
+}
+
+QString QSQLite2Driver::escapeIdentifier(const QString &identifier, IdentifierType /*type*/) const
+{
+ QString res = identifier;
+ if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) {
+ res.replace(QLatin1Char('"'), QLatin1String("\"\""));
+ res.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
+ res.replace(QLatin1Char('.'), QLatin1String("\".\""));
+ }
+ return res;
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/sqldrivers/sqlite2/qsql_sqlite2_p.h b/src/plugins/sqldrivers/sqlite2/qsql_sqlite2_p.h
new file mode 100644
index 0000000000..83b248ec6a
--- /dev/null
+++ b/src/plugins/sqldrivers/sqlite2/qsql_sqlite2_p.h
@@ -0,0 +1,109 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSQL_SQLITE2_H
+#define QSQL_SQLITE2_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtSql/qsqldriver.h>
+
+#if defined (Q_OS_WIN32)
+# include <QtCore/qt_windows.h>
+#endif
+
+struct sqlite;
+
+#ifdef QT_PLUGIN
+#define Q_EXPORT_SQLDRIVER_SQLITE2
+#else
+#define Q_EXPORT_SQLDRIVER_SQLITE2 Q_SQL_EXPORT
+#endif
+
+QT_BEGIN_NAMESPACE
+
+class QSqlResult;
+class QSQLite2DriverPrivate;
+
+class Q_EXPORT_SQLDRIVER_SQLITE2 QSQLite2Driver : public QSqlDriver
+{
+ friend class QSQLite2ResultPrivate;
+ Q_DECLARE_PRIVATE(QSQLite2Driver)
+ Q_OBJECT
+public:
+ explicit QSQLite2Driver(QObject *parent = 0);
+ explicit QSQLite2Driver(sqlite *connection, QObject *parent = 0);
+ ~QSQLite2Driver();
+ bool hasFeature(DriverFeature f) const Q_DECL_OVERRIDE;
+ bool open(const QString &db,
+ const QString &user,
+ const QString &password,
+ const QString &host,
+ int port,
+ const QString &connOpts) Q_DECL_OVERRIDE;
+ bool open(const QString &db,
+ const QString &user,
+ const QString &password,
+ const QString &host,
+ int port) { return open(db, user, password, host, port, QString()); }
+ void close() Q_DECL_OVERRIDE;
+ QSqlResult *createResult() const Q_DECL_OVERRIDE;
+ bool beginTransaction() Q_DECL_OVERRIDE;
+ bool commitTransaction() Q_DECL_OVERRIDE;
+ bool rollbackTransaction() Q_DECL_OVERRIDE;
+ QStringList tables(QSql::TableType) const Q_DECL_OVERRIDE;
+
+ QSqlRecord record(const QString &tablename) const Q_DECL_OVERRIDE;
+ QSqlIndex primaryIndex(const QString &table) const Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+ QString escapeIdentifier(const QString &identifier, IdentifierType) const Q_DECL_OVERRIDE;
+};
+
+QT_END_NAMESPACE
+
+#endif // QSQL_SQLITE2_H
diff --git a/src/plugins/sqldrivers/sqlite2/smain.cpp b/src/plugins/sqldrivers/sqlite2/smain.cpp
index 06b428c8ef..3a5734f8c9 100644
--- a/src/plugins/sqldrivers/sqlite2/smain.cpp
+++ b/src/plugins/sqldrivers/sqlite2/smain.cpp
@@ -39,7 +39,7 @@
#include <qsqldriverplugin.h>
#include <qstringlist.h>
-#include "../../../../src/sql/drivers/sqlite2/qsql_sqlite2_p.h"
+#include "qsql_sqlite2_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/sqldrivers/sqlite2/sqlite2.pro b/src/plugins/sqldrivers/sqlite2/sqlite2.pro
index d69afc119f..721facb5b8 100644
--- a/src/plugins/sqldrivers/sqlite2/sqlite2.pro
+++ b/src/plugins/sqldrivers/sqlite2/sqlite2.pro
@@ -1,8 +1,11 @@
TARGET = qsqlite2
-SOURCES = smain.cpp
+HEADERS += $$PWD/qsql_sqlite2_p.h
+SOURCES += $$PWD/qsql_sqlite2.cpp $$PWD/smain.cpp
+
+QMAKE_USE += sqlite2
+
OTHER_FILES += sqlite2.json
-include(../../../sql/drivers/sqlite2/qsql_sqlite2.pri)
PLUGIN_CLASS_NAME = QSQLite2DriverPlugin
include(../qsqldriverbase.pri)
diff --git a/src/plugins/sqldrivers/tds/main.cpp b/src/plugins/sqldrivers/tds/main.cpp
index ffb31ae179..4aa1444608 100644
--- a/src/plugins/sqldrivers/tds/main.cpp
+++ b/src/plugins/sqldrivers/tds/main.cpp
@@ -45,7 +45,7 @@
#define _WINSCARD_H_
#include <windows.h>
#endif
-#include "../../../sql/drivers/tds/qsql_tds_p.h"
+#include "qsql_tds_p.h"
QT_BEGIN_NAMESPACE
diff --git a/src/plugins/sqldrivers/tds/qsql_tds.cpp b/src/plugins/sqldrivers/tds/qsql_tds.cpp
new file mode 100644
index 0000000000..940fd05c74
--- /dev/null
+++ b/src/plugins/sqldrivers/tds/qsql_tds.cpp
@@ -0,0 +1,881 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsql_tds_p.h"
+
+#include <qglobal.h>
+#ifdef Q_OS_WIN32 // We assume that MS SQL Server is used. Set Q_USE_SYBASE to force Sybase.
+// Conflicting declarations of LPCBYTE in sqlfront.h and winscard.h
+#define _WINSCARD_H_
+#include <windows.h>
+#else
+#define Q_USE_SYBASE
+#endif
+
+#include <qvariant.h>
+#include <qdatetime.h>
+#include <qhash.h>
+#include <qregexp.h>
+#include <qsqlerror.h>
+#include <qsqlfield.h>
+#include <qsqlindex.h>
+#include <qsqlquery.h>
+#include <QtSql/private/qsqlcachedresult_p.h>
+#include <QtSql/private/qsqldriver_p.h>
+#include <qstringlist.h>
+#include <qvector.h>
+
+#include <stdlib.h>
+
+Q_DECLARE_OPAQUE_POINTER(LOGINREC*)
+Q_DECLARE_OPAQUE_POINTER(DBPROCESS*)
+
+QT_BEGIN_NAMESPACE
+
+#ifdef DBNTWIN32
+#define QMSGHANDLE DBMSGHANDLE_PROC
+#define QERRHANDLE DBERRHANDLE_PROC
+#define QTDSCHAR SQLCHAR
+#define QTDSDATETIME4 SQLDATETIM4
+#define QTDSDATETIME SQLDATETIME
+#define QTDSDATETIME_N SQLDATETIMN
+#define QTDSDECIMAL SQLDECIMAL
+#define QTDSFLT4 SQLFLT4
+#define QTDSFLT8 SQLFLT8
+#define QTDSFLT8_N SQLFLTN
+#define QTDSINT1 SQLINT1
+#define QTDSINT2 SQLINT2
+#define QTDSINT4 SQLINT4
+#define QTDSINT4_N SQLINTN
+#define QTDSMONEY4 SQLMONEY4
+#define QTDSMONEY SQLMONEY
+#define QTDSMONEY_N SQLMONEYN
+#define QTDSNUMERIC SQLNUMERIC
+#define QTDSTEXT SQLTEXT
+#define QTDSVARCHAR SQLVARCHAR
+#define QTDSBIT SQLBIT
+#define QTDSBINARY SQLBINARY
+#define QTDSVARBINARY SQLVARBINARY
+#define QTDSIMAGE SQLIMAGE
+#else
+#define QMSGHANDLE MHANDLEFUNC
+#define QERRHANDLE EHANDLEFUNC
+#define QTDSCHAR SYBCHAR
+#define QTDSDATETIME4 SYBDATETIME4
+#define QTDSDATETIME SYBDATETIME
+#define QTDSDATETIME_N SYBDATETIMN
+#define QTDSDECIMAL SYBDECIMAL
+#define QTDSFLT8 SYBFLT8
+#define QTDSFLT8_N SYBFLTN
+#define QTDSFLT4 SYBREAL
+#define QTDSINT1 SYBINT1
+#define QTDSINT2 SYBINT2
+#define QTDSINT4 SYBINT4
+#define QTDSINT4_N SYBINTN
+#define QTDSMONEY4 SYBMONEY4
+#define QTDSMONEY SYBMONEY
+#define QTDSMONEY_N SYBMONEYN
+#define QTDSNUMERIC SYBNUMERIC
+#define QTDSTEXT SYBTEXT
+#define QTDSVARCHAR SYBVARCHAR
+#define QTDSBIT SYBBIT
+#define QTDSBINARY SYBBINARY
+#define QTDSVARBINARY SYBVARBINARY
+#define QTDSIMAGE SYBIMAGE
+// magic numbers not defined anywhere in Sybase headers
+#define QTDSDECIMAL_2 55
+#define QTDSNUMERIC_2 63
+#endif //DBNTWIN32
+
+#define TDS_CURSOR_SIZE 50
+
+// workaround for FreeTDS
+#ifndef CS_PUBLIC
+#define CS_PUBLIC
+#endif
+
+QSqlError qMakeError(const QString& err, QSqlError::ErrorType type, int errNo = -1)
+{
+ return QSqlError(QLatin1String("QTDS: ") + err, QString(), type, errNo);
+}
+
+class QTDSDriverPrivate : public QSqlDriverPrivate
+{
+ Q_DECLARE_PUBLIC(QTDSDriver)
+
+public:
+ QTDSDriverPrivate() : QSqlDriverPrivate(), login(0), initialized(false) { dbmsType = QSqlDriver::Sybase; }
+ LOGINREC* login; // login information
+ QString hostName;
+ QString db;
+ bool initialized;
+};
+
+struct QTDSColumnData
+{
+ void *data;
+ DBINT nullbind;
+};
+Q_DECLARE_TYPEINFO(QTDSColumnData, Q_MOVABLE_TYPE);
+
+class QTDSResultPrivate;
+
+class QTDSResult : public QSqlCachedResult
+{
+ Q_DECLARE_PRIVATE(QTDSResult)
+
+public:
+ explicit QTDSResult(const QTDSDriver* db);
+ ~QTDSResult();
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+protected:
+ void cleanup();
+ bool reset(const QString &query) Q_DECL_OVERRIDE;
+ int size() Q_DECL_OVERRIDE;
+ int numRowsAffected() Q_DECL_OVERRIDE;
+ bool gotoNext(QSqlCachedResult::ValueCache &values, int index) Q_DECL_OVERRIDE;
+ QSqlRecord record() const Q_DECL_OVERRIDE;
+};
+
+class QTDSResultPrivate: public QSqlCachedResultPrivate
+{
+ Q_DECLARE_PUBLIC(QTDSResult)
+
+public:
+ Q_DECLARE_SQLDRIVER_PRIVATE(QTDSDriver)
+ QTDSResultPrivate(QTDSResult *q, const QTDSDriver *drv)
+ : QSqlCachedResultPrivate(q, drv),
+ login(0),
+ dbproc(0) {}
+ LOGINREC* login; // login information
+ DBPROCESS* dbproc; // connection from app to server
+ QSqlError lastError;
+ void addErrorMsg(QString& errMsg) { errorMsgs.append(errMsg); }
+ QString getErrorMsgs() { return errorMsgs.join(QLatin1String("\n")); }
+ void clearErrorMsgs() { errorMsgs.clear(); }
+ QVector<QTDSColumnData> buffer;
+ QSqlRecord rec;
+
+private:
+ QStringList errorMsgs;
+};
+
+typedef QHash<DBPROCESS *, QTDSResultPrivate *> QTDSErrorHash;
+Q_GLOBAL_STATIC(QTDSErrorHash, errs)
+
+extern "C" {
+static int CS_PUBLIC qTdsMsgHandler (DBPROCESS* dbproc,
+ DBINT msgno,
+ int msgstate,
+ int severity,
+ char* msgtext,
+ char* srvname,
+ char* /*procname*/,
+ int line)
+{
+ QTDSResultPrivate* p = errs()->value(dbproc);
+
+ if (!p) {
+// ### umm... temporary disabled since this throws a lot of warnings...
+// qWarning("QTDSDriver warning (%d): [%s] from server [%s]", msgstate, msgtext, srvname);
+ return INT_CANCEL;
+ }
+
+ if (severity > 0) {
+ QString errMsg = QString::fromLatin1("%1 (Msg %2, Level %3, State %4, Server %5, Line %6)")
+ .arg(QString::fromLatin1(msgtext))
+ .arg(msgno)
+ .arg(severity)
+ .arg(msgstate)
+ .arg(QString::fromLatin1(srvname))
+ .arg(line);
+ p->addErrorMsg(errMsg);
+ if (severity > 10) {
+ // Severe messages are really errors in the sense of lastError
+ errMsg = p->getErrorMsgs();
+ p->lastError = qMakeError(errMsg, QSqlError::UnknownError, msgno);
+ p->clearErrorMsgs();
+ }
+ }
+
+ return INT_CANCEL;
+}
+
+static int CS_PUBLIC qTdsErrHandler(DBPROCESS* dbproc,
+ int /*severity*/,
+ int dberr,
+ int /*oserr*/,
+ char* dberrstr,
+ char* oserrstr)
+{
+ QTDSResultPrivate* p = errs()->value(dbproc);
+ if (!p) {
+ qWarning("QTDSDriver error (%d): [%s] [%s]", dberr, dberrstr, oserrstr);
+ return INT_CANCEL;
+ }
+ /*
+ * If the process is dead or NULL and
+ * we are not in the middle of logging in...
+ */
+ if((dbproc == NULL || DBDEAD(dbproc))) {
+ qWarning("QTDSDriver error (%d): [%s] [%s]", dberr, dberrstr, oserrstr);
+ return INT_CANCEL;
+ }
+
+
+ QString errMsg = QString::fromLatin1("%1 %2\n").arg(QLatin1String(dberrstr)).arg(
+ QLatin1String(oserrstr));
+ errMsg += p->getErrorMsgs();
+ p->lastError = qMakeError(errMsg, QSqlError::UnknownError, dberr);
+ p->clearErrorMsgs();
+
+ return INT_CANCEL ;
+}
+
+} //extern "C"
+
+
+QVariant::Type qDecodeTDSType(int type)
+{
+ QVariant::Type t = QVariant::Invalid;
+ switch (type) {
+ case QTDSCHAR:
+ case QTDSTEXT:
+ case QTDSVARCHAR:
+ t = QVariant::String;
+ break;
+ case QTDSINT1:
+ case QTDSINT2:
+ case QTDSINT4:
+ case QTDSINT4_N:
+ case QTDSBIT:
+ t = QVariant::Int;
+ break;
+ case QTDSFLT4:
+ case QTDSFLT8:
+ case QTDSFLT8_N:
+ case QTDSMONEY4:
+ case QTDSMONEY:
+ case QTDSDECIMAL:
+ case QTDSNUMERIC:
+#ifdef QTDSNUMERIC_2
+ case QTDSNUMERIC_2:
+#endif
+#ifdef QTDSDECIMAL_2
+ case QTDSDECIMAL_2:
+#endif
+ case QTDSMONEY_N:
+ t = QVariant::Double;
+ break;
+ case QTDSDATETIME4:
+ case QTDSDATETIME:
+ case QTDSDATETIME_N:
+ t = QVariant::DateTime;
+ break;
+ case QTDSBINARY:
+ case QTDSVARBINARY:
+ case QTDSIMAGE:
+ t = QVariant::ByteArray;
+ break;
+ default:
+ t = QVariant::Invalid;
+ break;
+ }
+ return t;
+}
+
+QVariant::Type qFieldType(QTDSResultPrivate* d, int i)
+{
+ QVariant::Type type = qDecodeTDSType(dbcoltype(d->dbproc, i+1));
+ return type;
+}
+
+
+QTDSResult::QTDSResult(const QTDSDriver* db)
+ : QSqlCachedResult(*new QTDSResultPrivate(this, db))
+{
+ Q_D(QTDSResult);
+ d->login = d->drv_d_func()->login;
+
+ d->dbproc = dbopen(d->login, const_cast<char*>(d->drv_d_func()->hostName.toLatin1().constData()));
+ if (!d->dbproc)
+ return;
+ if (dbuse(d->dbproc, const_cast<char*>(d->drv_d_func()->db.toLatin1().constData())) == FAIL)
+ return;
+
+ // insert d in error handler dict
+ errs()->insert(d->dbproc, d);
+ dbcmd(d->dbproc, "set quoted_identifier on");
+ dbsqlexec(d->dbproc);
+}
+
+QTDSResult::~QTDSResult()
+{
+ Q_D(QTDSResult);
+ cleanup();
+ if (d->dbproc)
+ dbclose(d->dbproc);
+ errs()->remove(d->dbproc);
+}
+
+void QTDSResult::cleanup()
+{
+ Q_D(QTDSResult);
+ d->clearErrorMsgs();
+ d->rec.clear();
+ for (int i = 0; i < d->buffer.size(); ++i)
+ free(d->buffer.at(i).data);
+ d->buffer.clear();
+ // "can" stands for "cancel"... very clever.
+ dbcanquery(d->dbproc);
+ dbfreebuf(d->dbproc);
+
+ QSqlCachedResult::cleanup();
+}
+
+QVariant QTDSResult::handle() const
+{
+ Q_D(const QTDSResult);
+ return QVariant(qRegisterMetaType<DBPROCESS *>("DBPROCESS*"), &d->dbproc);
+}
+
+static inline bool qIsNull(const QTDSColumnData &p)
+{
+ return p.nullbind == -1;
+}
+
+bool QTDSResult::gotoNext(QSqlCachedResult::ValueCache &values, int index)
+{
+ Q_D(QTDSResult);
+ STATUS stat = dbnextrow(d->dbproc);
+ if (stat == NO_MORE_ROWS) {
+ setAt(QSql::AfterLastRow);
+ return false;
+ }
+ if ((stat == FAIL) || (stat == BUF_FULL)) {
+ setLastError(d->lastError);
+ return false;
+ }
+
+ if (index < 0)
+ return true;
+
+ for (int i = 0; i < d->rec.count(); ++i) {
+ int idx = index + i;
+ switch (d->rec.field(i).type()) {
+ case QVariant::DateTime:
+ if (qIsNull(d->buffer.at(i))) {
+ values[idx] = QVariant(QVariant::DateTime);
+ } else {
+ DBDATETIME *bdt = (DBDATETIME*) d->buffer.at(i).data;
+ QDate date = QDate::fromString(QLatin1String("1900-01-01"), Qt::ISODate);
+ QTime time = QTime::fromString(QLatin1String("00:00:00"), Qt::ISODate);
+ values[idx] = QDateTime(date.addDays(bdt->dtdays), time.addMSecs(int(bdt->dttime / 0.3)));
+ }
+ break;
+ case QVariant::Int:
+ if (qIsNull(d->buffer.at(i)))
+ values[idx] = QVariant(QVariant::Int);
+ else
+ values[idx] = *((int*)d->buffer.at(i).data);
+ break;
+ case QVariant::Double:
+ case QVariant::String:
+ if (qIsNull(d->buffer.at(i)))
+ values[idx] = QVariant(QVariant::String);
+ else
+ values[idx] = QString::fromLocal8Bit((const char*)d->buffer.at(i).data).trimmed();
+ break;
+ case QVariant::ByteArray: {
+ if (qIsNull(d->buffer.at(i)))
+ values[idx] = QVariant(QVariant::ByteArray);
+ else
+ values[idx] = QByteArray((const char*)d->buffer.at(i).data);
+ break;
+ }
+ default:
+ // should never happen, and we already fired
+ // a warning while binding.
+ values[idx] = QVariant();
+ break;
+ }
+ }
+
+ return true;
+}
+
+bool QTDSResult::reset (const QString& query)
+{
+ Q_D(QTDSResult);
+ cleanup();
+ if (!driver() || !driver()-> isOpen() || driver()->isOpenError())
+ return false;
+ setActive(false);
+ setAt(QSql::BeforeFirstRow);
+ if (dbcmd(d->dbproc, const_cast<char*>(query.toLocal8Bit().constData())) == FAIL) {
+ setLastError(d->lastError);
+ return false;
+ }
+
+ if (dbsqlexec(d->dbproc) == FAIL) {
+ setLastError(d->lastError);
+ dbfreebuf(d->dbproc);
+ return false;
+ }
+ if (dbresults(d->dbproc) != SUCCEED) {
+ setLastError(d->lastError);
+ dbfreebuf(d->dbproc);
+ return false;
+ }
+
+ setSelect((DBCMDROW(d->dbproc) == SUCCEED)); // decide whether or not we are dealing with a SELECT query
+ int numCols = dbnumcols(d->dbproc);
+ if (numCols > 0) {
+ d->buffer.resize(numCols);
+ init(numCols);
+ }
+ for (int i = 0; i < numCols; ++i) {
+ int dbType = dbcoltype(d->dbproc, i+1);
+ QVariant::Type vType = qDecodeTDSType(dbType);
+ QSqlField f(QString::fromLatin1(dbcolname(d->dbproc, i+1)), vType);
+ f.setSqlType(dbType);
+ f.setLength(dbcollen(d->dbproc, i+1));
+ d->rec.append(f);
+
+ RETCODE ret = -1;
+ void* p = 0;
+ switch (vType) {
+ case QVariant::Int:
+ p = malloc(4);
+ ret = dbbind(d->dbproc, i+1, INTBIND, (DBINT) 4, (unsigned char *)p);
+ break;
+ case QVariant::Double:
+ // use string binding to prevent loss of precision
+ p = malloc(50);
+ ret = dbbind(d->dbproc, i+1, STRINGBIND, 50, (unsigned char *)p);
+ break;
+ case QVariant::String:
+ p = malloc(dbcollen(d->dbproc, i+1) + 1);
+ ret = dbbind(d->dbproc, i+1, STRINGBIND, DBINT(dbcollen(d->dbproc, i+1) + 1), (unsigned char *)p);
+ break;
+ case QVariant::DateTime:
+ p = malloc(8);
+ ret = dbbind(d->dbproc, i+1, DATETIMEBIND, (DBINT) 8, (unsigned char *)p);
+ break;
+ case QVariant::ByteArray:
+ p = malloc(dbcollen(d->dbproc, i+1) + 1);
+ ret = dbbind(d->dbproc, i+1, BINARYBIND, DBINT(dbcollen(d->dbproc, i+1) + 1), (unsigned char *)p);
+ break;
+ default: //don't bind the field since we do not support it
+ qWarning("QTDSResult::reset: Unsupported type for field \"%s\"", dbcolname(d->dbproc, i+1));
+ break;
+ }
+ if (ret == SUCCEED) {
+ d->buffer[i].data = p;
+ ret = dbnullbind(d->dbproc, i+1, &d->buffer[i].nullbind);
+ } else {
+ d->buffer[i].data = 0;
+ d->buffer[i].nullbind = 0;
+ free(p);
+ }
+ if ((ret != SUCCEED) && (ret != -1)) {
+ setLastError(d->lastError);
+ return false;
+ }
+ }
+
+ setActive(true);
+ return true;
+}
+
+int QTDSResult::size()
+{
+ return -1;
+}
+
+int QTDSResult::numRowsAffected()
+{
+ Q_D(const QTDSResult);
+#ifdef DBNTWIN32
+ if (dbiscount(d->dbproc)) {
+ return DBCOUNT(d->dbproc);
+ }
+ return -1;
+#else
+ return DBCOUNT(d->dbproc);
+#endif
+}
+
+QSqlRecord QTDSResult::record() const
+{
+ Q_D(const QTDSResult);
+ return d->rec;
+}
+
+///////////////////////////////////////////////////////////////////
+
+QTDSDriver::QTDSDriver(QObject* parent)
+ : QSqlDriver(*new QTDSDriverPrivate, parent)
+{
+ init();
+}
+
+QTDSDriver::QTDSDriver(LOGINREC* rec, const QString& host, const QString &db, QObject* parent)
+ : QSqlDriver(*new QTDSDriverPrivate, parent)
+{
+ Q_D(QTDSDriver);
+ init();
+ d->login = rec;
+ d->hostName = host;
+ d->db = db;
+ if (rec) {
+ setOpen(true);
+ setOpenError(false);
+ }
+}
+
+QVariant QTDSDriver::handle() const
+{
+ Q_D(const QTDSDriver);
+ return QVariant(qRegisterMetaType<LOGINREC *>("LOGINREC*"), &d->login);
+}
+
+void QTDSDriver::init()
+{
+ Q_D(QTDSDriver);
+ d->initialized = (dbinit() == SUCCEED);
+ // the following two code-lines will fail compilation on some FreeTDS versions
+ // just comment them out if you have FreeTDS (you won't get any errors and warnings then)
+ dberrhandle((QERRHANDLE)qTdsErrHandler);
+ dbmsghandle((QMSGHANDLE)qTdsMsgHandler);
+}
+
+QTDSDriver::~QTDSDriver()
+{
+ dberrhandle(0);
+ dbmsghandle(0);
+ // dbexit also calls dbclose if necessary
+ dbexit();
+}
+
+bool QTDSDriver::hasFeature(DriverFeature f) const
+{
+ switch (f) {
+ case Transactions:
+ case QuerySize:
+ case Unicode:
+ case SimpleLocking:
+ case EventNotifications:
+ case MultipleResultSets:
+ return false;
+ case BLOB:
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool QTDSDriver::open(const QString & db,
+ const QString & user,
+ const QString & password,
+ const QString & host,
+ int /*port*/,
+ const QString& /*connOpts*/)
+{
+ Q_D(QTDSDriver);
+ if (isOpen())
+ close();
+ if (!d->initialized) {
+ setOpenError(true);
+ return false;
+ }
+ d->login = dblogin();
+ if (!d->login) {
+ setOpenError(true);
+ return false;
+ }
+ DBSETLPWD(d->login, const_cast<char*>(password.toLocal8Bit().constData()));
+ DBSETLUSER(d->login, const_cast<char*>(user.toLocal8Bit().constData()));
+
+ // Now, try to open and use the database. If this fails, return false.
+ DBPROCESS* dbproc;
+
+ dbproc = dbopen(d->login, const_cast<char*>(host.toLatin1().constData()));
+ if (!dbproc) {
+ setLastError(qMakeError(tr("Unable to open connection"), QSqlError::ConnectionError, -1));
+ setOpenError(true);
+ return false;
+ }
+ if (dbuse(dbproc, const_cast<char*>(db.toLatin1().constData())) == FAIL) {
+ setLastError(qMakeError(tr("Unable to use database"), QSqlError::ConnectionError, -1));
+ setOpenError(true);
+ return false;
+ }
+ dbclose( dbproc );
+
+ setOpen(true);
+ setOpenError(false);
+ d->hostName = host;
+ d->db = db;
+ return true;
+}
+
+void QTDSDriver::close()
+{
+ Q_D(QTDSDriver);
+ if (isOpen()) {
+#ifdef Q_USE_SYBASE
+ dbloginfree(d->login);
+#else
+ dbfreelogin(d->login);
+#endif
+ d->login = 0;
+ setOpen(false);
+ setOpenError(false);
+ }
+}
+
+QSqlResult *QTDSDriver::createResult() const
+{
+ return new QTDSResult(this);
+}
+
+bool QTDSDriver::beginTransaction()
+{
+ return false;
+/*
+ if (!isOpen()) {
+ qWarning("QTDSDriver::beginTransaction: Database not open");
+ return false;
+ }
+ if (dbcmd(d->dbproc, "BEGIN TRANSACTION") == FAIL) {
+ setLastError(d->lastError);
+ dbfreebuf(d->dbproc);
+ return false;
+ }
+ if (dbsqlexec(d->dbproc) == FAIL) {
+ setLastError(d->lastError);
+ dbfreebuf(d->dbproc);
+ return false;
+ }
+ while(dbresults(d->dbproc) == NO_MORE_RESULTS) {}
+ dbfreebuf(d->dbproc);
+ inTransaction = true;
+ return true;
+*/
+}
+
+bool QTDSDriver::commitTransaction()
+{
+ return false;
+/*
+ if (!isOpen()) {
+ qWarning("QTDSDriver::commitTransaction: Database not open");
+ return false;
+ }
+ if (dbcmd(d->dbproc, "COMMIT TRANSACTION") == FAIL) {
+ setLastError(d->lastError);
+ dbfreebuf(d->dbproc);
+ return false;
+ }
+ if (dbsqlexec(d->dbproc) == FAIL) {
+ setLastError(d->lastError);
+ dbfreebuf(d->dbproc);
+ return false;
+ }
+ while(dbresults(d->dbproc) == NO_MORE_RESULTS) {}
+ dbfreebuf(d->dbproc);
+ inTransaction = false;
+ return true;
+*/
+}
+
+bool QTDSDriver::rollbackTransaction()
+{
+ return false;
+/*
+ if (!isOpen()) {
+ qWarning("QTDSDriver::rollbackTransaction: Database not open");
+ return false;
+ }
+ if (dbcmd(d->dbproc, "ROLLBACK TRANSACTION") == FAIL) {
+ setLastError(d->lastError);
+ dbfreebuf(d->dbproc);
+ return false;
+ }
+ if (dbsqlexec(d->dbproc) == FAIL) {
+ setLastError(d->lastError);
+ dbfreebuf(d->dbproc);
+ return false;
+ }
+ while(dbresults(d->dbproc) == NO_MORE_RESULTS) {}
+ dbfreebuf(d->dbproc);
+ inTransaction = false;
+ return true;
+*/
+}
+
+QSqlRecord QTDSDriver::record(const QString& tablename) const
+{
+ QSqlRecord info;
+ if (!isOpen())
+ return info;
+ QSqlQuery t(createResult());
+ t.setForwardOnly(true);
+
+ QString table = tablename;
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+
+ QString stmt (QLatin1String("select name, type, length, prec from syscolumns "
+ "where id = (select id from sysobjects where name = '%1')"));
+ t.exec(stmt.arg(table));
+ while (t.next()) {
+ QSqlField f(t.value(0).toString().simplified(), qDecodeTDSType(t.value(1).toInt()));
+ f.setLength(t.value(2).toInt());
+ f.setPrecision(t.value(3).toInt());
+ f.setSqlType(t.value(1).toInt());
+ info.append(f);
+ }
+ return info;
+}
+
+QStringList QTDSDriver::tables(QSql::TableType type) const
+{
+ QStringList list;
+
+ if (!isOpen())
+ return list;
+
+ QStringList typeFilter;
+
+ if (type & QSql::Tables)
+ typeFilter += QLatin1String("type='U'");
+ if (type & QSql::SystemTables)
+ typeFilter += QLatin1String("type='S'");
+ if (type & QSql::Views)
+ typeFilter += QLatin1String("type='V'");
+
+ if (typeFilter.isEmpty())
+ return list;
+
+ QSqlQuery t(createResult());
+ t.setForwardOnly(true);
+ t.exec(QLatin1String("select name from sysobjects where ") + typeFilter.join(QLatin1String(" or ")));
+ while (t.next())
+ list.append(t.value(0).toString().simplified());
+
+ return list;
+}
+
+QString QTDSDriver::formatValue(const QSqlField &field,
+ bool trim) const
+{
+ QString r;
+ if (field.isNull())
+ r = QLatin1String("NULL");
+ else if (field.type() == QVariant::DateTime) {
+ if (field.value().toDateTime().isValid()){
+ r = field.value().toDateTime().toString(QLatin1String("yyyyMMdd hh:mm:ss"));
+ r.prepend(QLatin1String("'"));
+ r.append(QLatin1String("'"));
+ } else
+ r = QLatin1String("NULL");
+ } else if (field.type() == QVariant::ByteArray) {
+ QByteArray ba = field.value().toByteArray();
+ QString res;
+ static const char hexchars[] = "0123456789abcdef";
+ for (int i = 0; i < ba.size(); ++i) {
+ uchar s = (uchar) ba[i];
+ res += QLatin1Char(hexchars[s >> 4]);
+ res += QLatin1Char(hexchars[s & 0x0f]);
+ }
+ r = QLatin1String("0x") + res;
+ } else {
+ r = QSqlDriver::formatValue(field, trim);
+ }
+ return r;
+}
+
+QSqlIndex QTDSDriver::primaryIndex(const QString& tablename) const
+{
+ QSqlRecord rec = record(tablename);
+
+ QString table = tablename;
+ if (isIdentifierEscaped(table, QSqlDriver::TableName))
+ table = stripDelimiters(table, QSqlDriver::TableName);
+
+ QSqlIndex idx(table);
+ if ((!isOpen()) || (table.isEmpty()))
+ return QSqlIndex();
+
+ QSqlQuery t(createResult());
+ t.setForwardOnly(true);
+ t.exec(QString::fromLatin1("sp_helpindex '%1'").arg(table));
+ if (t.next()) {
+ QStringList fNames = t.value(2).toString().simplified().split(QLatin1Char(','));
+ QRegExp regx(QLatin1String("\\s*(\\S+)(?:\\s+(DESC|desc))?\\s*"));
+ for(QStringList::Iterator it = fNames.begin(); it != fNames.end(); ++it) {
+ regx.indexIn(*it);
+ QSqlField f(regx.cap(1), rec.field(regx.cap(1)).type());
+ if (regx.cap(2).toLower() == QLatin1String("desc")) {
+ idx.append(f, true);
+ } else {
+ idx.append(f, false);
+ }
+ }
+ idx.setName(t.value(0).toString().simplified());
+ }
+ return idx;
+}
+
+QString QTDSDriver::escapeIdentifier(const QString &identifier, IdentifierType type) const
+{
+ Q_UNUSED(type)
+ QString res = identifier;
+ if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) {
+ res.replace(QLatin1Char('"'), QLatin1String("\"\""));
+ res.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
+ res.replace(QLatin1Char('.'), QLatin1String("\".\""));
+ }
+ return res;
+}
+
+QT_END_NAMESPACE
diff --git a/src/plugins/sqldrivers/tds/qsql_tds_p.h b/src/plugins/sqldrivers/tds/qsql_tds_p.h
new file mode 100644
index 0000000000..d0914455a2
--- /dev/null
+++ b/src/plugins/sqldrivers/tds/qsql_tds_p.h
@@ -0,0 +1,120 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtSql module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSQL_TDS_H
+#define QSQL_TDS_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtSql/qsqldriver.h>
+
+#ifdef Q_OS_WIN32
+#define WIN32_LEAN_AND_MEAN
+#ifndef Q_USE_SYBASE
+#define DBNTWIN32 // indicates 32bit windows dblib
+#endif
+#include <winsock2.h>
+#include <QtCore/qt_windows.h>
+#include <sqlfront.h>
+#include <sqldb.h>
+#define CS_PUBLIC
+#else
+#include <sybfront.h>
+#include <sybdb.h>
+#endif //Q_OS_WIN32
+
+#ifdef QT_PLUGIN
+#define Q_EXPORT_SQLDRIVER_TDS
+#else
+#define Q_EXPORT_SQLDRIVER_TDS Q_SQL_EXPORT
+#endif
+
+QT_BEGIN_NAMESPACE
+
+class QSqlResult;
+class QTDSDriverPrivate;
+
+class Q_EXPORT_SQLDRIVER_TDS QTDSDriver : public QSqlDriver
+{
+ Q_DECLARE_PRIVATE(QTDSDriver)
+ Q_OBJECT
+ friend class QTDSResultPrivate;
+public:
+ explicit QTDSDriver(QObject* parent = 0);
+ QTDSDriver(LOGINREC* rec, const QString& host, const QString &db, QObject* parent = 0);
+ ~QTDSDriver();
+ bool hasFeature(DriverFeature f) const Q_DECL_OVERRIDE;
+ bool open(const QString &db,
+ const QString &user,
+ const QString &password,
+ const QString &host,
+ int port,
+ const QString &connOpts) Q_DECL_OVERRIDE;
+ void close() Q_DECL_OVERRIDE;
+ QStringList tables(QSql::TableType) const Q_DECL_OVERRIDE;
+ QSqlResult *createResult() const Q_DECL_OVERRIDE;
+ QSqlRecord record(const QString &tablename) const Q_DECL_OVERRIDE;
+ QSqlIndex primaryIndex(const QString &tablename) const Q_DECL_OVERRIDE;
+
+ QString formatValue(const QSqlField &field,
+ bool trimStrings) const Q_DECL_OVERRIDE;
+ QVariant handle() const Q_DECL_OVERRIDE;
+
+ QString escapeIdentifier(const QString &identifier, IdentifierType type) const Q_DECL_OVERRIDE;
+
+protected:
+ bool beginTransaction() Q_DECL_OVERRIDE;
+ bool commitTransaction() Q_DECL_OVERRIDE;
+ bool rollbackTransaction() Q_DECL_OVERRIDE;
+private:
+ void init();
+};
+
+QT_END_NAMESPACE
+
+#endif // QSQL_TDS_H
diff --git a/src/plugins/sqldrivers/tds/tds.pro b/src/plugins/sqldrivers/tds/tds.pro
index 88f4b7c451..67bc0f5c48 100644
--- a/src/plugins/sqldrivers/tds/tds.pro
+++ b/src/plugins/sqldrivers/tds/tds.pro
@@ -1,8 +1,11 @@
TARGET = qsqltds
-SOURCES = main.cpp
+HEADERS += $$PWD/qsql_tds_p.h
+SOURCES += $$PWD/qsql_tds.cpp $$PWD/main.cpp
+
+QMAKE_USE += tds
+
OTHER_FILES += tds.json
-include(../../../sql/drivers/tds/qsql_tds.pri)
PLUGIN_CLASS_NAME = QTDSDriverPlugin
include(../qsqldriverbase.pri)