summaryrefslogtreecommitdiff
path: root/apps
diff options
context:
space:
mode:
authorFranklin Wei <git@fwei.tk>2018-02-07 20:04:46 -0500
committerFranklin Wei <git@fwei.tk>2018-03-12 20:52:01 -0400
commit6039eb05ba6d82ef56f2868c96654c552d117bf9 (patch)
tree9db7016bcbf66cfdf7b9bc998d84c6eaff9c8378 /apps
parentef373c03b96b0be08babca581d9f10bccfd4931f (diff)
downloadrockbox-6039eb05ba6d82ef56f2868c96654c552d117bf9.tar.gz
rockbox-6039eb05ba6d82ef56f2868c96654c552d117bf9.zip
sdl: remove non-rockbox drivers
We never use any of these other drivers, so having them around just takes up space. Change-Id: Iced812162df1fef3fd55522b7e700acb6c3bcd41
Diffstat (limited to 'apps')
-rw-r--r--apps/plugins/sdl/src/audio/alsa/SDL_alsa_audio.c619
-rw-r--r--apps/plugins/sdl/src/audio/alsa/SDL_alsa_audio.h48
-rw-r--r--apps/plugins/sdl/src/audio/arts/SDL_artsaudio.c362
-rw-r--r--apps/plugins/sdl/src/audio/arts/SDL_artsaudio.h60
-rw-r--r--apps/plugins/sdl/src/audio/baudio/SDL_beaudio.cc225
-rw-r--r--apps/plugins/sdl/src/audio/baudio/SDL_beaudio.h39
-rw-r--r--apps/plugins/sdl/src/audio/bsd/SDL_bsdaudio.c404
-rw-r--r--apps/plugins/sdl/src/audio/bsd/SDL_bsdaudio.h58
-rw-r--r--apps/plugins/sdl/src/audio/dart/SDL_dart.c441
-rw-r--r--apps/plugins/sdl/src/audio/dart/SDL_dart.h63
-rw-r--r--apps/plugins/sdl/src/audio/dc/SDL_dcaudio.c246
-rw-r--r--apps/plugins/sdl/src/audio/dc/SDL_dcaudio.h41
-rw-r--r--apps/plugins/sdl/src/audio/dc/aica.c271
-rw-r--r--apps/plugins/sdl/src/audio/dc/aica.h40
-rw-r--r--apps/plugins/sdl/src/audio/disk/SDL_diskaudio.c186
-rw-r--r--apps/plugins/sdl/src/audio/disk/SDL_diskaudio.h41
-rw-r--r--apps/plugins/sdl/src/audio/dma/SDL_dmaaudio.c455
-rw-r--r--apps/plugins/sdl/src/audio/dma/SDL_dmaaudio.h59
-rw-r--r--apps/plugins/sdl/src/audio/dmedia/SDL_irixaudio.c242
-rw-r--r--apps/plugins/sdl/src/audio/dmedia/SDL_irixaudio.h45
-rw-r--r--apps/plugins/sdl/src/audio/dsp/SDL_dspaudio.c340
-rw-r--r--apps/plugins/sdl/src/audio/dsp/SDL_dspaudio.h53
-rw-r--r--apps/plugins/sdl/src/audio/esd/SDL_esdaudio.c323
-rw-r--r--apps/plugins/sdl/src/audio/esd/SDL_esdaudio.h57
-rw-r--r--apps/plugins/sdl/src/audio/macosx/SDL_coreaudio.c291
-rw-r--r--apps/plugins/sdl/src/audio/macosx/SDL_coreaudio.h45
-rw-r--r--apps/plugins/sdl/src/audio/macrom/SDL_romaudio.c496
-rw-r--r--apps/plugins/sdl/src/audio/macrom/SDL_romaudio.h50
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio.c215
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio.h121
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_dma8.c357
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_dma8.h85
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_gsxb.c436
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_gsxb.h104
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_it.S386
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_mcsn.c405
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_mcsn.h59
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_stfa.c326
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_stfa.h97
-rw-r--r--apps/plugins/sdl/src/audio/mint/SDL_mintaudio_xbios.c490
-rw-r--r--apps/plugins/sdl/src/audio/mme/SDL_mmeaudio.c264
-rw-r--r--apps/plugins/sdl/src/audio/mme/SDL_mmeaudio.h51
-rw-r--r--apps/plugins/sdl/src/audio/nas/SDL_nasaudio.c423
-rw-r--r--apps/plugins/sdl/src/audio/nas/SDL_nasaudio.h62
-rw-r--r--apps/plugins/sdl/src/audio/nds/SDL_ndsaudio.c335
-rw-r--r--apps/plugins/sdl/src/audio/nds/SDL_ndsaudio.h40
-rw-r--r--apps/plugins/sdl/src/audio/nds/sound9.c61
-rw-r--r--apps/plugins/sdl/src/audio/nds/soundcommon.h80
-rw-r--r--apps/plugins/sdl/src/audio/nto/SDL_nto_audio.c507
-rw-r--r--apps/plugins/sdl/src/audio/nto/SDL_nto_audio.h68
-rw-r--r--apps/plugins/sdl/src/audio/paudio/SDL_paudio.c511
-rw-r--r--apps/plugins/sdl/src/audio/paudio/SDL_paudio.h57
-rw-r--r--apps/plugins/sdl/src/audio/pulse/SDL_pulseaudio.c570
-rw-r--r--apps/plugins/sdl/src/audio/pulse/SDL_pulseaudio.h73
-rw-r--r--apps/plugins/sdl/src/audio/sun/SDL_sunaudio.c432
-rw-r--r--apps/plugins/sdl/src/audio/sun/SDL_sunaudio.h55
-rw-r--r--apps/plugins/sdl/src/audio/symbian/SDL_epocaudio.cpp614
-rw-r--r--apps/plugins/sdl/src/audio/symbian/SDL_epocaudio.h37
-rw-r--r--apps/plugins/sdl/src/audio/symbian/streamplayer.cpp279
-rw-r--r--apps/plugins/sdl/src/audio/symbian/streamplayer.h89
-rw-r--r--apps/plugins/sdl/src/audio/ums/SDL_umsaudio.c547
-rw-r--r--apps/plugins/sdl/src/audio/ums/SDL_umsaudio.h50
-rw-r--r--apps/plugins/sdl/src/audio/windib/SDL_dibaudio.c322
-rw-r--r--apps/plugins/sdl/src/audio/windib/SDL_dibaudio.h49
-rw-r--r--apps/plugins/sdl/src/audio/windx5/SDL_dx5audio.c705
-rw-r--r--apps/plugins/sdl/src/audio/windx5/SDL_dx5audio.h55
-rw-r--r--apps/plugins/sdl/src/audio/windx5/directx.h81
-rw-r--r--apps/plugins/sdl/src/cdrom/aix/SDL_syscdrom.c660
-rw-r--r--apps/plugins/sdl/src/cdrom/beos/SDL_syscdrom.cc410
-rw-r--r--apps/plugins/sdl/src/cdrom/bsdi/SDL_syscdrom.c542
-rw-r--r--apps/plugins/sdl/src/cdrom/dc/SDL_syscdrom.c167
-rw-r--r--apps/plugins/sdl/src/cdrom/freebsd/SDL_syscdrom.c406
-rw-r--r--apps/plugins/sdl/src/cdrom/linux/SDL_syscdrom.c564
-rw-r--r--apps/plugins/sdl/src/cdrom/macos/SDL_syscdrom.c525
-rw-r--r--apps/plugins/sdl/src/cdrom/macos/SDL_syscdrom_c.h140
-rw-r--r--apps/plugins/sdl/src/cdrom/macosx/AudioFilePlayer.c360
-rw-r--r--apps/plugins/sdl/src/cdrom/macosx/AudioFilePlayer.h178
-rw-r--r--apps/plugins/sdl/src/cdrom/macosx/AudioFileReaderThread.c610
-rw-r--r--apps/plugins/sdl/src/cdrom/macosx/CDPlayer.c636
-rw-r--r--apps/plugins/sdl/src/cdrom/macosx/CDPlayer.h69
-rw-r--r--apps/plugins/sdl/src/cdrom/macosx/SDLOSXCAGuard.c199
-rw-r--r--apps/plugins/sdl/src/cdrom/macosx/SDLOSXCAGuard.h116
-rw-r--r--apps/plugins/sdl/src/cdrom/macosx/SDL_syscdrom.c514
-rw-r--r--apps/plugins/sdl/src/cdrom/macosx/SDL_syscdrom_c.h136
-rw-r--r--apps/plugins/sdl/src/cdrom/mint/SDL_syscdrom.c317
-rw-r--r--apps/plugins/sdl/src/cdrom/openbsd/SDL_syscdrom.c416
-rw-r--r--apps/plugins/sdl/src/cdrom/os2/SDL_syscdrom.c393
-rw-r--r--apps/plugins/sdl/src/cdrom/osf/SDL_syscdrom.c444
-rw-r--r--apps/plugins/sdl/src/cdrom/qnx/SDL_syscdrom.c551
-rw-r--r--apps/plugins/sdl/src/cdrom/win32/SDL_syscdrom.c386
-rw-r--r--apps/plugins/sdl/src/hermes/COPYING.LIB438
-rw-r--r--apps/plugins/sdl/src/hermes/HeadMMX.h100
-rw-r--r--apps/plugins/sdl/src/hermes/HeadX86.h186
-rw-r--r--apps/plugins/sdl/src/hermes/README13
-rw-r--r--apps/plugins/sdl/src/hermes/common.inc9
-rw-r--r--apps/plugins/sdl/src/hermes/mmx_main.asm74
-rw-r--r--apps/plugins/sdl/src/hermes/mmxp2_32.asm405
-rw-r--r--apps/plugins/sdl/src/hermes/x86_main.asm75
-rw-r--r--apps/plugins/sdl/src/hermes/x86p_16.asm490
-rw-r--r--apps/plugins/sdl/src/hermes/x86p_32.asm1044
-rw-r--r--apps/plugins/sdl/src/joystick/beos/SDL_bejoystick.cc237
-rw-r--r--apps/plugins/sdl/src/joystick/bsd/SDL_sysjoystick.c608
-rw-r--r--apps/plugins/sdl/src/joystick/darwin/SDL_sysjoystick.c842
-rw-r--r--apps/plugins/sdl/src/joystick/dc/SDL_sysjoystick.c193
-rw-r--r--apps/plugins/sdl/src/joystick/linux/SDL_sysjoystick.c1218
-rw-r--r--apps/plugins/sdl/src/joystick/macos/SDL_sysjoystick.c320
-rw-r--r--apps/plugins/sdl/src/joystick/mint/SDL_sysjoystick.c826
-rw-r--r--apps/plugins/sdl/src/joystick/nds/SDL_sysjoystick.c150
-rw-r--r--apps/plugins/sdl/src/joystick/riscos/SDL_sysjoystick.c176
-rw-r--r--apps/plugins/sdl/src/joystick/win32/SDL_mmjoystick.c407
-rw-r--r--apps/plugins/sdl/src/loadso/beos/SDL_sysloadso.c72
-rw-r--r--apps/plugins/sdl/src/loadso/dlopen/SDL_sysloadso.c69
-rw-r--r--apps/plugins/sdl/src/loadso/macos/SDL_sysloadso.c106
-rw-r--r--apps/plugins/sdl/src/loadso/macosx/SDL_dlcompat.c1407
-rw-r--r--apps/plugins/sdl/src/loadso/mint/SDL_sysloadso.c62
-rw-r--r--apps/plugins/sdl/src/loadso/os2/SDL_sysloadso.c71
-rw-r--r--apps/plugins/sdl/src/loadso/win32/SDL_sysloadso.c139
-rw-r--r--apps/plugins/sdl/src/main/beos/SDL_BeApp.cc111
-rw-r--r--apps/plugins/sdl/src/main/beos/SDL_BeApp.h33
-rw-r--r--apps/plugins/sdl/src/main/macos/SDL.r1
-rw-r--r--apps/plugins/sdl/src/main/macos/SDL.shlib.r1
-rw-r--r--apps/plugins/sdl/src/main/macos/SDL_main.c610
-rw-r--r--apps/plugins/sdl/src/main/macos/SIZE.r1
-rw-r--r--apps/plugins/sdl/src/main/macos/exports/Makefile39
-rw-r--r--apps/plugins/sdl/src/main/macos/exports/SDL.x1
-rw-r--r--apps/plugins/sdl/src/main/macos/exports/gendef.pl43
-rw-r--r--apps/plugins/sdl/src/main/macosx/Info.plist.in24
-rw-r--r--apps/plugins/sdl/src/main/macosx/SDLMain.h16
-rw-r--r--apps/plugins/sdl/src/main/macosx/SDLMain.m381
-rw-r--r--apps/plugins/sdl/src/main/macosx/SDLMain.nib/classes.nib12
-rw-r--r--apps/plugins/sdl/src/main/macosx/SDLMain.nib/info.nib12
-rw-r--r--apps/plugins/sdl/src/main/macosx/SDLMain.nib/objects.nibbin1701 -> 0 bytes
-rw-r--r--apps/plugins/sdl/src/main/macosx/info.nib1
-rw-r--r--apps/plugins/sdl/src/main/qtopia/SDL_qtopia_main.cc47
-rw-r--r--apps/plugins/sdl/src/main/symbian/EKA1/SDL_main.cpp152
-rw-r--r--apps/plugins/sdl/src/main/symbian/EKA2/SDL_main.cpp1035
-rw-r--r--apps/plugins/sdl/src/main/symbian/EKA2/sdlexe.cpp809
-rw-r--r--apps/plugins/sdl/src/main/symbian/EKA2/sdllib.cpp12
-rw-r--r--apps/plugins/sdl/src/main/symbian/EKA2/vectorbuffer.cpp62
-rw-r--r--apps/plugins/sdl/src/main/symbian/EKA2/vectorbuffer.h240
-rw-r--r--apps/plugins/sdl/src/main/win32/SDL_win32_main.c402
-rw-r--r--apps/plugins/sdl/src/main/win32/version.rc38
-rw-r--r--apps/plugins/sdl/src/thread/beos/SDL_syssem.c142
-rw-r--r--apps/plugins/sdl/src/thread/beos/SDL_systhread.c96
-rw-r--r--apps/plugins/sdl/src/thread/beos/SDL_systhread_c.h31
-rw-r--r--apps/plugins/sdl/src/thread/dc/SDL_syscond.c215
-rw-r--r--apps/plugins/sdl/src/thread/dc/SDL_syscond_c.h23
-rw-r--r--apps/plugins/sdl/src/thread/dc/SDL_sysmutex.c122
-rw-r--r--apps/plugins/sdl/src/thread/dc/SDL_sysmutex_c.h23
-rw-r--r--apps/plugins/sdl/src/thread/dc/SDL_syssem.c173
-rw-r--r--apps/plugins/sdl/src/thread/dc/SDL_syssem_c.h23
-rw-r--r--apps/plugins/sdl/src/thread/dc/SDL_systhread.c60
-rw-r--r--apps/plugins/sdl/src/thread/dc/SDL_systhread_c.h24
-rw-r--r--apps/plugins/sdl/src/thread/irix/SDL_syssem.c219
-rw-r--r--apps/plugins/sdl/src/thread/irix/SDL_systhread.c85
-rw-r--r--apps/plugins/sdl/src/thread/irix/SDL_systhread_c.h27
-rw-r--r--apps/plugins/sdl/src/thread/os2/SDL_syscond.c215
-rw-r--r--apps/plugins/sdl/src/thread/os2/SDL_syscond_c.h23
-rw-r--r--apps/plugins/sdl/src/thread/os2/SDL_sysmutex.c108
-rw-r--r--apps/plugins/sdl/src/thread/os2/SDL_syssem.c192
-rw-r--r--apps/plugins/sdl/src/thread/os2/SDL_systhread.c108
-rw-r--r--apps/plugins/sdl/src/thread/os2/SDL_systhread_c.h28
-rw-r--r--apps/plugins/sdl/src/thread/pth/SDL_syscond.c164
-rw-r--r--apps/plugins/sdl/src/thread/pth/SDL_sysmutex.c87
-rw-r--r--apps/plugins/sdl/src/thread/pth/SDL_sysmutex_c.h31
-rw-r--r--apps/plugins/sdl/src/thread/pth/SDL_systhread.c103
-rw-r--r--apps/plugins/sdl/src/thread/pth/SDL_systhread_c.h31
-rw-r--r--apps/plugins/sdl/src/thread/pthread/SDL_syscond.c155
-rw-r--r--apps/plugins/sdl/src/thread/pthread/SDL_sysmutex.c153
-rw-r--r--apps/plugins/sdl/src/thread/pthread/SDL_sysmutex_c.h31
-rw-r--r--apps/plugins/sdl/src/thread/pthread/SDL_syssem.c190
-rw-r--r--apps/plugins/sdl/src/thread/pthread/SDL_systhread.c120
-rw-r--r--apps/plugins/sdl/src/thread/pthread/SDL_systhread_c.h26
-rw-r--r--apps/plugins/sdl/src/thread/riscos/SDL_syscond.c160
-rw-r--r--apps/plugins/sdl/src/thread/riscos/SDL_sysmutex.c153
-rw-r--r--apps/plugins/sdl/src/thread/riscos/SDL_sysmutex_c.h34
-rw-r--r--apps/plugins/sdl/src/thread/riscos/SDL_syssem.c203
-rw-r--r--apps/plugins/sdl/src/thread/riscos/SDL_systhread.c144
-rw-r--r--apps/plugins/sdl/src/thread/riscos/SDL_systhread_c.h34
-rw-r--r--apps/plugins/sdl/src/thread/symbian/SDL_sysmutex.cpp130
-rw-r--r--apps/plugins/sdl/src/thread/symbian/SDL_syssem.cpp214
-rw-r--r--apps/plugins/sdl/src/thread/symbian/SDL_systhread.cpp146
-rw-r--r--apps/plugins/sdl/src/thread/symbian/SDL_systhread_c.h30
-rw-r--r--apps/plugins/sdl/src/thread/win32/SDL_sysmutex.c95
-rw-r--r--apps/plugins/sdl/src/thread/win32/SDL_syssem.c164
-rw-r--r--apps/plugins/sdl/src/thread/win32/SDL_systhread.c162
-rw-r--r--apps/plugins/sdl/src/thread/win32/SDL_systhread_c.h28
-rw-r--r--apps/plugins/sdl/src/thread/win32/win_ce_semaphore.c216
-rw-r--r--apps/plugins/sdl/src/thread/win32/win_ce_semaphore.h22
-rw-r--r--apps/plugins/sdl/src/timer/beos/SDL_systimer.c95
-rw-r--r--apps/plugins/sdl/src/timer/dc/SDL_systimer.c100
-rw-r--r--apps/plugins/sdl/src/timer/macos/FastTimes.c352
-rw-r--r--apps/plugins/sdl/src/timer/macos/FastTimes.h27
-rw-r--r--apps/plugins/sdl/src/timer/macos/SDL_MPWtimer.c152
-rw-r--r--apps/plugins/sdl/src/timer/macos/SDL_systimer.c186
-rw-r--r--apps/plugins/sdl/src/timer/mint/SDL_systimer.c149
-rw-r--r--apps/plugins/sdl/src/timer/mint/SDL_vbltimer.S228
-rw-r--r--apps/plugins/sdl/src/timer/mint/SDL_vbltimer_s.h35
-rw-r--r--apps/plugins/sdl/src/timer/nds/SDL_systimer.c73
-rw-r--r--apps/plugins/sdl/src/timer/os2/SDL_systimer.c227
-rw-r--r--apps/plugins/sdl/src/timer/riscos/SDL_systimer.c233
-rw-r--r--apps/plugins/sdl/src/timer/symbian/SDL_systimer.cpp114
-rw-r--r--apps/plugins/sdl/src/timer/unix/SDL_systimer.c240
-rw-r--r--apps/plugins/sdl/src/timer/win32/SDL_systimer.c160
-rw-r--r--apps/plugins/sdl/src/timer/wince/SDL_systimer.c198
-rw-r--r--apps/plugins/sdl/src/video/Xext/README10
-rw-r--r--apps/plugins/sdl/src/video/Xext/XME/xme.c410
-rw-r--r--apps/plugins/sdl/src/video/Xext/Xinerama/Xinerama.c324
-rw-r--r--apps/plugins/sdl/src/video/Xext/Xv/Xv.c1151
-rw-r--r--apps/plugins/sdl/src/video/Xext/Xv/Xvlibint.h81
-rw-r--r--apps/plugins/sdl/src/video/Xext/Xxf86dga/XF86DGA.c721
-rw-r--r--apps/plugins/sdl/src/video/Xext/Xxf86dga/XF86DGA2.c993
-rw-r--r--apps/plugins/sdl/src/video/Xext/Xxf86vm/XF86VMode.c1226
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/Xext.h50
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/Xinerama.h46
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/Xv.h129
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/Xvlib.h433
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/Xvproto.h604
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/extutil.h226
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/panoramiXext.h52
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/panoramiXproto.h192
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/xf86dga.h265
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/xf86dga1.h169
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/xf86dga1str.h194
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/xf86dgastr.h344
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/xf86vmode.h314
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/xf86vmstr.h546
-rw-r--r--apps/plugins/sdl/src/video/Xext/extensions/xme.h45
-rw-r--r--apps/plugins/sdl/src/video/aalib/SDL_aaevents.c202
-rw-r--r--apps/plugins/sdl/src/video/aalib/SDL_aaevents_c.h35
-rw-r--r--apps/plugins/sdl/src/video/aalib/SDL_aamouse.c35
-rw-r--r--apps/plugins/sdl/src/video/aalib/SDL_aamouse_c.h26
-rw-r--r--apps/plugins/sdl/src/video/aalib/SDL_aavideo.c388
-rw-r--r--apps/plugins/sdl/src/video/aalib/SDL_aavideo.h66
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_ataric2p.S452
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_ataric2p_s.h75
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_ataridevmouse.c159
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_ataridevmouse_c.h42
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarieddi.S42
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarieddi_s.h54
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarievents.c234
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarievents_c.h52
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarigl.c1086
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarigl_c.h109
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarikeys.h140
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarimxalloc.c52
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarimxalloc_c.h37
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_atarisuper.h61
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_biosevents.c131
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_biosevents_c.h42
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_gemdosevents.c132
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_gemdosevents_c.h42
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_ikbdevents.c124
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_ikbdevents_c.h42
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_ikbdinterrupt.S404
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_ikbdinterrupt_s.h61
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_xbiosevents.c155
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_xbiosevents_c.h48
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_xbiosinterrupt.S212
-rw-r--r--apps/plugins/sdl/src/video/ataricommon/SDL_xbiosinterrupt_s.h52
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_BView.h116
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_BWin.h290
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_lowvideo.h58
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_sysevents.cc415
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_sysevents_c.h31
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_sysmouse.cc153
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_sysmouse_c.h33
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_sysvideo.cc841
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_syswm.cc92
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_syswm_c.h32
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_sysyuv.cc314
-rw-r--r--apps/plugins/sdl/src/video/bwindow/SDL_sysyuv.h73
-rw-r--r--apps/plugins/sdl/src/video/caca/SDL_cacaevents.c101
-rw-r--r--apps/plugins/sdl/src/video/caca/SDL_cacaevents_c.h35
-rw-r--r--apps/plugins/sdl/src/video/caca/SDL_cacavideo.c304
-rw-r--r--apps/plugins/sdl/src/video/caca/SDL_cacavideo.h76
-rw-r--r--apps/plugins/sdl/src/video/dc/SDL_dcevents.c152
-rw-r--r--apps/plugins/sdl/src/video/dc/SDL_dcevents_c.h33
-rw-r--r--apps/plugins/sdl/src/video/dc/SDL_dcmouse.c35
-rw-r--r--apps/plugins/sdl/src/video/dc/SDL_dcmouse_c.h26
-rw-r--r--apps/plugins/sdl/src/video/dc/SDL_dcvideo.c445
-rw-r--r--apps/plugins/sdl/src/video/dc/SDL_dcvideo.h42
-rw-r--r--apps/plugins/sdl/src/video/dga/SDL_dgaevents.c163
-rw-r--r--apps/plugins/sdl/src/video/dga/SDL_dgaevents_c.h28
-rw-r--r--apps/plugins/sdl/src/video/dga/SDL_dgamouse.c35
-rw-r--r--apps/plugins/sdl/src/video/dga/SDL_dgamouse_c.h26
-rw-r--r--apps/plugins/sdl/src/video/dga/SDL_dgavideo.c1101
-rw-r--r--apps/plugins/sdl/src/video/dga/SDL_dgavideo.h124
-rw-r--r--apps/plugins/sdl/src/video/directfb/SDL_DirectFB_events.c219
-rw-r--r--apps/plugins/sdl/src/video/directfb/SDL_DirectFB_events.h29
-rw-r--r--apps/plugins/sdl/src/video/directfb/SDL_DirectFB_keys.h135
-rw-r--r--apps/plugins/sdl/src/video/directfb/SDL_DirectFB_video.c1171
-rw-r--r--apps/plugins/sdl/src/video/directfb/SDL_DirectFB_video.h62
-rw-r--r--apps/plugins/sdl/src/video/directfb/SDL_DirectFB_yuv.c290
-rw-r--r--apps/plugins/sdl/src/video/directfb/SDL_DirectFB_yuv.h38
-rw-r--r--apps/plugins/sdl/src/video/fbcon/3dfx_mmio.h56
-rw-r--r--apps/plugins/sdl/src/video/fbcon/3dfx_regs.h83
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fb3dfx.c215
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fb3dfx.h29
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbelo.c442
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbelo.h55
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbevents.c1254
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbevents_c.h38
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbkeys.h139
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbmatrox.c280
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbmatrox.h29
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbmouse.c33
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbmouse_c.h26
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbriva.c222
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbriva.h36
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbvideo.c1982
-rw-r--r--apps/plugins/sdl/src/video/fbcon/SDL_fbvideo.h200
-rw-r--r--apps/plugins/sdl/src/video/fbcon/matrox_mmio.h51
-rw-r--r--apps/plugins/sdl/src/video/fbcon/matrox_regs.h376
-rw-r--r--apps/plugins/sdl/src/video/fbcon/riva_mmio.h449
-rw-r--r--apps/plugins/sdl/src/video/fbcon/riva_regs.h43
-rw-r--r--apps/plugins/sdl/src/video/gapi/SDL_gapivideo.c1287
-rw-r--r--apps/plugins/sdl/src/video/gapi/SDL_gapivideo.h160
-rw-r--r--apps/plugins/sdl/src/video/gem/SDL_gemevents.c375
-rw-r--r--apps/plugins/sdl/src/video/gem/SDL_gemevents_c.h33
-rw-r--r--apps/plugins/sdl/src/video/gem/SDL_gemmouse.c205
-rw-r--r--apps/plugins/sdl/src/video/gem/SDL_gemmouse_c.h34
-rw-r--r--apps/plugins/sdl/src/video/gem/SDL_gemvideo.c1337
-rw-r--r--apps/plugins/sdl/src/video/gem/SDL_gemvideo.h191
-rw-r--r--apps/plugins/sdl/src/video/gem/SDL_gemwm.c116
-rw-r--r--apps/plugins/sdl/src/video/gem/SDL_gemwm_c.h37
-rw-r--r--apps/plugins/sdl/src/video/ggi/SDL_ggievents.c264
-rwxr-xr-xapps/plugins/sdl/src/video/ggi/SDL_ggievents_c.h29
-rw-r--r--apps/plugins/sdl/src/video/ggi/SDL_ggikeys.h135
-rw-r--r--apps/plugins/sdl/src/video/ggi/SDL_ggimouse.c32
-rwxr-xr-xapps/plugins/sdl/src/video/ggi/SDL_ggimouse_c.h26
-rw-r--r--apps/plugins/sdl/src/video/ggi/SDL_ggivideo.c378
-rw-r--r--apps/plugins/sdl/src/video/ggi/SDL_ggivideo.h48
-rw-r--r--apps/plugins/sdl/src/video/ipod/SDL_ipodvideo.c733
-rw-r--r--apps/plugins/sdl/src/video/ipod/SDL_ipodvideo.h38
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_lowvideo.h102
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_macevents.c746
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_macevents_c.h32
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_macgl.c197
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_macgl_c.h47
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_mackeys.h140
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_macmouse.c129
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_macmouse_c.h34
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_macwm.c442
-rw-r--r--apps/plugins/sdl/src/video/maccommon/SDL_macwm_c.h41
-rw-r--r--apps/plugins/sdl/src/video/macdsp/SDL_dspvideo.c1422
-rw-r--r--apps/plugins/sdl/src/video/macdsp/SDL_dspvideo.h54
-rw-r--r--apps/plugins/sdl/src/video/macrom/SDL_romvideo.c745
-rw-r--r--apps/plugins/sdl/src/video/macrom/SDL_romvideo.h29
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxevents.c382
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxevents_c.h32
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nximage.c230
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nximage_c.h35
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxmodes.c84
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxmodes_c.h34
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxmouse.c79
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxmouse_c.h29
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxvideo.c544
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxvideo.h96
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxwm.c61
-rw-r--r--apps/plugins/sdl/src/video/nanox/SDL_nxwm_c.h32
-rw-r--r--apps/plugins/sdl/src/video/nds/SDL_ndsevents.c83
-rw-r--r--apps/plugins/sdl/src/video/nds/SDL_ndsevents_c.h51
-rw-r--r--apps/plugins/sdl/src/video/nds/SDL_ndsmouse.c34
-rw-r--r--apps/plugins/sdl/src/video/nds/SDL_ndsmouse_c.h26
-rw-r--r--apps/plugins/sdl/src/video/nds/SDL_ndsvideo.c500
-rw-r--r--apps/plugins/sdl/src/video/nds/SDL_ndsvideo.h61
-rw-r--r--apps/plugins/sdl/src/video/os2fslib/SDL_os2fslib.c3018
-rw-r--r--apps/plugins/sdl/src/video/os2fslib/SDL_os2fslib.h71
-rw-r--r--apps/plugins/sdl/src/video/os2fslib/SDL_vkeys.h74
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_events.c624
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_events_c.h37
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_gl.c406
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_gl.h41
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_image.c1059
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_image_c.h59
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_modes.c390
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_modes_c.h43
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_mouse.c220
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_mouse_c.h39
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_video.c648
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_video.h157
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_wm.c118
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_ph_wm_c.h37
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_phyuv.c504
-rw-r--r--apps/plugins/sdl/src/video/photon/SDL_phyuv_c.h62
-rw-r--r--apps/plugins/sdl/src/video/picogui/SDL_pgevents.c117
-rw-r--r--apps/plugins/sdl/src/video/picogui/SDL_pgevents_c.h37
-rw-r--r--apps/plugins/sdl/src/video/picogui/SDL_pgvideo.c364
-rw-r--r--apps/plugins/sdl/src/video/picogui/SDL_pgvideo.h50
-rw-r--r--apps/plugins/sdl/src/video/ps2gs/SDL_gsevents.c977
-rw-r--r--apps/plugins/sdl/src/video/ps2gs/SDL_gsevents_c.h38
-rw-r--r--apps/plugins/sdl/src/video/ps2gs/SDL_gskeys.h139
-rw-r--r--apps/plugins/sdl/src/video/ps2gs/SDL_gsmouse.c146
-rw-r--r--apps/plugins/sdl/src/video/ps2gs/SDL_gsmouse_c.h37
-rw-r--r--apps/plugins/sdl/src/video/ps2gs/SDL_gsvideo.c689
-rw-r--r--apps/plugins/sdl/src/video/ps2gs/SDL_gsvideo.h95
-rw-r--r--apps/plugins/sdl/src/video/ps2gs/SDL_gsyuv.c461
-rw-r--r--apps/plugins/sdl/src/video/ps2gs/SDL_gsyuv_c.h37
-rw-r--r--apps/plugins/sdl/src/video/ps3/SDL_ps3events.c44
-rw-r--r--apps/plugins/sdl/src/video/ps3/SDL_ps3events_c.h41
-rw-r--r--apps/plugins/sdl/src/video/ps3/SDL_ps3video.c621
-rw-r--r--apps/plugins/sdl/src/video/ps3/SDL_ps3video.h165
-rw-r--r--apps/plugins/sdl/src/video/ps3/SDL_ps3yuv.c340
-rw-r--r--apps/plugins/sdl/src/video/ps3/SDL_ps3yuv_c.h44
-rw-r--r--apps/plugins/sdl/src/video/ps3/spulibs/Makefile83
-rw-r--r--apps/plugins/sdl/src/video/ps3/spulibs/bilin_scaler.c2050
-rw-r--r--apps/plugins/sdl/src/video/ps3/spulibs/fb_writer.c193
-rw-r--r--apps/plugins/sdl/src/video/ps3/spulibs/spu_common.h108
-rw-r--r--apps/plugins/sdl/src/video/ps3/spulibs/yuv2rgb_converter.c629
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_QPEApp.cc63
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_QPEApp.h33
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_QWin.cc527
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_QWin.h110
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_lowvideo.h65
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_sysevents.cc269
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_sysevents_c.h31
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_sysmouse.cc56
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_sysmouse_c.h32
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_sysvideo.cc403
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_syswm.cc35
-rw-r--r--apps/plugins/sdl/src/video/qtopia/SDL_syswm_c.h28
-rw-r--r--apps/plugins/sdl/src/video/quartz/CGS.h84
-rw-r--r--apps/plugins/sdl/src/video/quartz/SDL_QuartzEvents.m1063
-rw-r--r--apps/plugins/sdl/src/video/quartz/SDL_QuartzGL.m292
-rw-r--r--apps/plugins/sdl/src/video/quartz/SDL_QuartzKeys.h146
-rw-r--r--apps/plugins/sdl/src/video/quartz/SDL_QuartzVideo.h229
-rw-r--r--apps/plugins/sdl/src/video/quartz/SDL_QuartzVideo.m1689
-rw-r--r--apps/plugins/sdl/src/video/quartz/SDL_QuartzWM.h27
-rw-r--r--apps/plugins/sdl/src/video/quartz/SDL_QuartzWM.m444
-rw-r--r--apps/plugins/sdl/src/video/quartz/SDL_QuartzWindow.h51
-rw-r--r--apps/plugins/sdl/src/video/quartz/SDL_QuartzWindow.m231
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscosASM.S116
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscosFullScreenVideo.c777
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscosevents.c549
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscosevents_c.h34
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscosmouse.c371
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscosmouse_c.h44
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscossprite.c265
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscostask.c350
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscostask.h39
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscosvideo.c316
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_riscosvideo.h62
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_wimppoll.c330
-rw-r--r--apps/plugins/sdl/src/video/riscos/SDL_wimpvideo.c501
-rw-r--r--apps/plugins/sdl/src/video/svga/SDL_svgaevents.c412
-rw-r--r--apps/plugins/sdl/src/video/svga/SDL_svgaevents_c.h35
-rw-r--r--apps/plugins/sdl/src/video/svga/SDL_svgamouse.c33
-rw-r--r--apps/plugins/sdl/src/video/svga/SDL_svgamouse_c.h26
-rw-r--r--apps/plugins/sdl/src/video/svga/SDL_svgavideo.c584
-rw-r--r--apps/plugins/sdl/src/video/svga/SDL_svgavideo.h58
-rw-r--r--apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocevents.cpp626
-rw-r--r--apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocvideo.cpp1356
-rw-r--r--apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocvideo.h34
-rw-r--r--apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocevents.cpp521
-rw-r--r--apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocvideo.cpp594
-rw-r--r--apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocvideo.h51
-rw-r--r--apps/plugins/sdl/src/video/symbian/EKA2/dsa.cpp1505
-rw-r--r--apps/plugins/sdl/src/video/symbian/EKA2/dsa_new.cpp1443
-rw-r--r--apps/plugins/sdl/src/video/symbian/EKA2/dsa_old.cpp1075
-rw-r--r--apps/plugins/sdl/src/video/symbian/SDL_epocevents_c.h60
-rw-r--r--apps/plugins/sdl/src/video/vgl/SDL_vglevents.c299
-rw-r--r--apps/plugins/sdl/src/video/vgl/SDL_vglevents_c.h155
-rw-r--r--apps/plugins/sdl/src/video/vgl/SDL_vglmouse.c56
-rw-r--r--apps/plugins/sdl/src/video/vgl/SDL_vglmouse_c.h32
-rw-r--r--apps/plugins/sdl/src/video/vgl/SDL_vglvideo.c624
-rw-r--r--apps/plugins/sdl/src/video/vgl/SDL_vglvideo.h65
-rw-r--r--apps/plugins/sdl/src/video/wincommon/SDL_lowvideo.h152
-rw-r--r--apps/plugins/sdl/src/video/wincommon/SDL_sysevents.c855
-rw-r--r--apps/plugins/sdl/src/video/wincommon/SDL_sysmouse.c259
-rw-r--r--apps/plugins/sdl/src/video/wincommon/SDL_sysmouse_c.h33
-rw-r--r--apps/plugins/sdl/src/video/wincommon/SDL_syswm.c297
-rw-r--r--apps/plugins/sdl/src/video/wincommon/SDL_syswm_c.h35
-rw-r--r--apps/plugins/sdl/src/video/wincommon/SDL_wingl.c659
-rw-r--r--apps/plugins/sdl/src/video/wincommon/SDL_wingl_c.h135
-rw-r--r--apps/plugins/sdl/src/video/wincommon/wmmsg.h1030
-rw-r--r--apps/plugins/sdl/src/video/windib/SDL_dibevents.c704
-rw-r--r--apps/plugins/sdl/src/video/windib/SDL_dibevents_c.h35
-rw-r--r--apps/plugins/sdl/src/video/windib/SDL_dibvideo.c1323
-rw-r--r--apps/plugins/sdl/src/video/windib/SDL_dibvideo.h59
-rw-r--r--apps/plugins/sdl/src/video/windib/SDL_gapidibvideo.h56
-rw-r--r--apps/plugins/sdl/src/video/windib/SDL_vkeys.h75
-rw-r--r--apps/plugins/sdl/src/video/windx5/SDL_dx5events.c1005
-rw-r--r--apps/plugins/sdl/src/video/windx5/SDL_dx5events_c.h37
-rw-r--r--apps/plugins/sdl/src/video/windx5/SDL_dx5video.c2537
-rw-r--r--apps/plugins/sdl/src/video/windx5/SDL_dx5video.h61
-rw-r--r--apps/plugins/sdl/src/video/windx5/SDL_dx5yuv.c296
-rw-r--r--apps/plugins/sdl/src/video/windx5/SDL_dx5yuv_c.h38
-rw-r--r--apps/plugins/sdl/src/video/windx5/directx.h97
-rw-r--r--apps/plugins/sdl/src/video/wscons/SDL_wsconsevents.c233
-rw-r--r--apps/plugins/sdl/src/video/wscons/SDL_wsconsevents_c.h36
-rw-r--r--apps/plugins/sdl/src/video/wscons/SDL_wsconsmouse.c33
-rw-r--r--apps/plugins/sdl/src/video/wscons/SDL_wsconsmouse_c.h26
-rw-r--r--apps/plugins/sdl/src/video/wscons/SDL_wsconsvideo.c609
-rw-r--r--apps/plugins/sdl/src/video/wscons/SDL_wsconsvideo.h76
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11dga.c90
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11dga_c.h33
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11dyn.c222
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11dyn.h93
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11events.c1414
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11events_c.h34
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11gamma.c142
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11gamma_c.h32
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11gl.c577
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11gl_c.h99
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11image.c316
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11image_c.h38
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11modes.c1143
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11modes_c.h43
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11mouse.c288
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11mouse_c.h33
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11sym.h201
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11video.c1571
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11video.h214
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11wm.c434
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11wm_c.h34
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11yuv.c538
-rw-r--r--apps/plugins/sdl/src/video/x11/SDL_x11yuv_c.h41
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios.c1116
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios.h111
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_blowup.c77
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_blowup.h86
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_centscreen.c104
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_centscreen.h114
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_milan.c106
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_milan.h129
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_sb3.c83
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_sb3.h82
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_tveille.c63
-rw-r--r--apps/plugins/sdl/src/video/xbios/SDL_xbios_tveille.h64
530 files changed, 0 insertions, 138647 deletions
diff --git a/apps/plugins/sdl/src/audio/alsa/SDL_alsa_audio.c b/apps/plugins/sdl/src/audio/alsa/SDL_alsa_audio.c
deleted file mode 100644
index f10733e432..0000000000
--- a/apps/plugins/sdl/src/audio/alsa/SDL_alsa_audio.c
+++ /dev/null
@@ -1,619 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer */
25
26#include <sys/types.h>
27#include <signal.h> /* For kill() */
28
29#include "SDL_timer.h"
30#include "SDL_audio.h"
31#include "../SDL_audiomem.h"
32#include "../SDL_audio_c.h"
33#include "SDL_alsa_audio.h"
34
35#ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC
36#include "SDL_name.h"
37#include "SDL_loadso.h"
38#else
39#define SDL_NAME(X) X
40#endif
41
42
43/* The tag name used by ALSA audio */
44#define DRIVER_NAME "alsa"
45
46/* Audio driver functions */
47static int ALSA_OpenAudio(_THIS, SDL_AudioSpec *spec);
48static void ALSA_WaitAudio(_THIS);
49static void ALSA_PlayAudio(_THIS);
50static Uint8 *ALSA_GetAudioBuf(_THIS);
51static void ALSA_CloseAudio(_THIS);
52
53#ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC
54
55static const char *alsa_library = SDL_AUDIO_DRIVER_ALSA_DYNAMIC;
56static void *alsa_handle = NULL;
57static int alsa_loaded = 0;
58
59static int (*SDL_NAME(snd_pcm_open))(snd_pcm_t **pcm, const char *name, snd_pcm_stream_t stream, int mode);
60static int (*SDL_NAME(snd_pcm_close))(snd_pcm_t *pcm);
61static snd_pcm_sframes_t (*SDL_NAME(snd_pcm_writei))(snd_pcm_t *pcm, const void *buffer, snd_pcm_uframes_t size);
62static int (*SDL_NAME(snd_pcm_recover))(snd_pcm_t *pcm, int err, int silent);
63static int (*SDL_NAME(snd_pcm_prepare))(snd_pcm_t *pcm);
64static int (*SDL_NAME(snd_pcm_drain))(snd_pcm_t *pcm);
65static const char *(*SDL_NAME(snd_strerror))(int errnum);
66static size_t (*SDL_NAME(snd_pcm_hw_params_sizeof))(void);
67static size_t (*SDL_NAME(snd_pcm_sw_params_sizeof))(void);
68static void (*SDL_NAME(snd_pcm_hw_params_copy))(snd_pcm_hw_params_t *dst, const snd_pcm_hw_params_t *src);
69static int (*SDL_NAME(snd_pcm_hw_params_any))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params);
70static int (*SDL_NAME(snd_pcm_hw_params_set_access))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_access_t access);
71static int (*SDL_NAME(snd_pcm_hw_params_set_format))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_format_t val);
72static int (*SDL_NAME(snd_pcm_hw_params_set_channels))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int val);
73static int (*SDL_NAME(snd_pcm_hw_params_get_channels))(const snd_pcm_hw_params_t *params, unsigned int *val);
74static int (*SDL_NAME(snd_pcm_hw_params_set_rate_near))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
75static int (*SDL_NAME(snd_pcm_hw_params_set_period_size_near))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val, int *dir);
76static int (*SDL_NAME(snd_pcm_hw_params_get_period_size))(const snd_pcm_hw_params_t *params, snd_pcm_uframes_t *frames, int *dir);
77static int (*SDL_NAME(snd_pcm_hw_params_set_periods_near))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
78static int (*SDL_NAME(snd_pcm_hw_params_get_periods))(const snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
79static int (*SDL_NAME(snd_pcm_hw_params_set_buffer_size_near))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val);
80static int (*SDL_NAME(snd_pcm_hw_params_get_buffer_size))(const snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val);
81static int (*SDL_NAME(snd_pcm_hw_params))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params);
82/*
83*/
84static int (*SDL_NAME(snd_pcm_sw_params_set_avail_min))(snd_pcm_t *pcm, snd_pcm_sw_params_t *swparams, snd_pcm_uframes_t val);
85static int (*SDL_NAME(snd_pcm_sw_params_current))(snd_pcm_t *pcm, snd_pcm_sw_params_t *swparams);
86static int (*SDL_NAME(snd_pcm_sw_params_set_start_threshold))(snd_pcm_t *pcm, snd_pcm_sw_params_t *params, snd_pcm_uframes_t val);
87static int (*SDL_NAME(snd_pcm_sw_params))(snd_pcm_t *pcm, snd_pcm_sw_params_t *params);
88static int (*SDL_NAME(snd_pcm_nonblock))(snd_pcm_t *pcm, int nonblock);
89static int (*SDL_NAME(snd_pcm_wait))(snd_pcm_t *pcm, int timeout);
90#define snd_pcm_hw_params_sizeof SDL_NAME(snd_pcm_hw_params_sizeof)
91#define snd_pcm_sw_params_sizeof SDL_NAME(snd_pcm_sw_params_sizeof)
92
93/* cast funcs to char* first, to please GCC's strict aliasing rules. */
94static struct {
95 const char *name;
96 void **func;
97} alsa_functions[] = {
98 { "snd_pcm_open", (void**)(char*)&SDL_NAME(snd_pcm_open) },
99 { "snd_pcm_close", (void**)(char*)&SDL_NAME(snd_pcm_close) },
100 { "snd_pcm_writei", (void**)(char*)&SDL_NAME(snd_pcm_writei) },
101 { "snd_pcm_recover", (void**)(char*)&SDL_NAME(snd_pcm_recover) },
102 { "snd_pcm_prepare", (void**)(char*)&SDL_NAME(snd_pcm_prepare) },
103 { "snd_pcm_drain", (void**)(char*)&SDL_NAME(snd_pcm_drain) },
104 { "snd_strerror", (void**)(char*)&SDL_NAME(snd_strerror) },
105 { "snd_pcm_hw_params_sizeof", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_sizeof) },
106 { "snd_pcm_sw_params_sizeof", (void**)(char*)&SDL_NAME(snd_pcm_sw_params_sizeof) },
107 { "snd_pcm_hw_params_copy", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_copy) },
108 { "snd_pcm_hw_params_any", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_any) },
109 { "snd_pcm_hw_params_set_access", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_access) },
110 { "snd_pcm_hw_params_set_format", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_format) },
111 { "snd_pcm_hw_params_set_channels", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_channels) },
112 { "snd_pcm_hw_params_get_channels", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_get_channels) },
113 { "snd_pcm_hw_params_set_rate_near", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_rate_near) },
114 { "snd_pcm_hw_params_set_period_size_near", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_period_size_near) },
115 { "snd_pcm_hw_params_get_period_size", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_get_period_size) },
116 { "snd_pcm_hw_params_set_periods_near", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_periods_near) },
117 { "snd_pcm_hw_params_get_periods", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_get_periods) },
118 { "snd_pcm_hw_params_set_buffer_size_near", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_buffer_size_near) },
119 { "snd_pcm_hw_params_get_buffer_size", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_get_buffer_size) },
120 { "snd_pcm_hw_params", (void**)(char*)&SDL_NAME(snd_pcm_hw_params) },
121 { "snd_pcm_sw_params_set_avail_min", (void**)(char*)&SDL_NAME(snd_pcm_sw_params_set_avail_min) },
122 { "snd_pcm_sw_params_current", (void**)(char*)&SDL_NAME(snd_pcm_sw_params_current) },
123 { "snd_pcm_sw_params_set_start_threshold", (void**)(char*)&SDL_NAME(snd_pcm_sw_params_set_start_threshold) },
124 { "snd_pcm_sw_params", (void**)(char*)&SDL_NAME(snd_pcm_sw_params) },
125 { "snd_pcm_nonblock", (void**)(char*)&SDL_NAME(snd_pcm_nonblock) },
126 { "snd_pcm_wait", (void**)(char*)&SDL_NAME(snd_pcm_wait) },
127};
128
129static void UnloadALSALibrary(void) {
130 if (alsa_loaded) {
131 SDL_UnloadObject(alsa_handle);
132 alsa_handle = NULL;
133 alsa_loaded = 0;
134 }
135}
136
137static int LoadALSALibrary(void) {
138 int i, retval = -1;
139
140 alsa_handle = SDL_LoadObject(alsa_library);
141 if (alsa_handle) {
142 alsa_loaded = 1;
143 retval = 0;
144 for (i = 0; i < SDL_arraysize(alsa_functions); i++) {
145 *alsa_functions[i].func = SDL_LoadFunction(alsa_handle,alsa_functions[i].name);
146 if (!*alsa_functions[i].func) {
147 retval = -1;
148 UnloadALSALibrary();
149 break;
150 }
151 }
152 }
153 return retval;
154}
155
156#else
157
158static void UnloadALSALibrary(void) {
159 return;
160}
161
162static int LoadALSALibrary(void) {
163 return 0;
164}
165
166#endif /* SDL_AUDIO_DRIVER_ALSA_DYNAMIC */
167
168static const char *get_audio_device(int channels)
169{
170 const char *device;
171
172 device = SDL_getenv("AUDIODEV"); /* Is there a standard variable name? */
173 if ( device == NULL ) {
174 switch (channels) {
175 case 6:
176 device = "plug:surround51";
177 break;
178 case 4:
179 device = "plug:surround40";
180 break;
181 default:
182 device = "default";
183 break;
184 }
185 }
186 return device;
187}
188
189/* Audio driver bootstrap functions */
190
191static int Audio_Available(void)
192{
193 int available;
194 int status;
195 snd_pcm_t *handle;
196
197 available = 0;
198 if (LoadALSALibrary() < 0) {
199 return available;
200 }
201 status = SDL_NAME(snd_pcm_open)(&handle, get_audio_device(2), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
202 if ( status >= 0 ) {
203 available = 1;
204 SDL_NAME(snd_pcm_close)(handle);
205 }
206 UnloadALSALibrary();
207 return(available);
208}
209
210static void Audio_DeleteDevice(SDL_AudioDevice *device)
211{
212 SDL_free(device->hidden);
213 SDL_free(device);
214 UnloadALSALibrary();
215}
216
217static SDL_AudioDevice *Audio_CreateDevice(int devindex)
218{
219 SDL_AudioDevice *this;
220
221 /* Initialize all variables that we clean on shutdown */
222 LoadALSALibrary();
223 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
224 if ( this ) {
225 SDL_memset(this, 0, (sizeof *this));
226 this->hidden = (struct SDL_PrivateAudioData *)
227 SDL_malloc((sizeof *this->hidden));
228 }
229 if ( (this == NULL) || (this->hidden == NULL) ) {
230 SDL_OutOfMemory();
231 if ( this ) {
232 SDL_free(this);
233 }
234 return(0);
235 }
236 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
237
238 /* Set the function pointers */
239 this->OpenAudio = ALSA_OpenAudio;
240 this->WaitAudio = ALSA_WaitAudio;
241 this->PlayAudio = ALSA_PlayAudio;
242 this->GetAudioBuf = ALSA_GetAudioBuf;
243 this->CloseAudio = ALSA_CloseAudio;
244
245 this->free = Audio_DeleteDevice;
246
247 return this;
248}
249
250AudioBootStrap ALSA_bootstrap = {
251 DRIVER_NAME, "ALSA PCM audio",
252 Audio_Available, Audio_CreateDevice
253};
254
255/* This function waits until it is possible to write a full sound buffer */
256static void ALSA_WaitAudio(_THIS)
257{
258 /* We're in blocking mode, so there's nothing to do here */
259}
260
261
262/*
263 * http://bugzilla.libsdl.org/show_bug.cgi?id=110
264 * "For Linux ALSA, this is FL-FR-RL-RR-C-LFE
265 * and for Windows DirectX [and CoreAudio], this is FL-FR-C-LFE-RL-RR"
266 */
267#define SWIZ6(T) \
268 T *ptr = (T *) mixbuf; \
269 Uint32 i; \
270 for (i = 0; i < this->spec.samples; i++, ptr += 6) { \
271 T tmp; \
272 tmp = ptr[2]; ptr[2] = ptr[4]; ptr[4] = tmp; \
273 tmp = ptr[3]; ptr[3] = ptr[5]; ptr[5] = tmp; \
274 }
275
276static __inline__ void swizzle_alsa_channels_6_64bit(_THIS) { SWIZ6(Uint64); }
277static __inline__ void swizzle_alsa_channels_6_32bit(_THIS) { SWIZ6(Uint32); }
278static __inline__ void swizzle_alsa_channels_6_16bit(_THIS) { SWIZ6(Uint16); }
279static __inline__ void swizzle_alsa_channels_6_8bit(_THIS) { SWIZ6(Uint8); }
280
281#undef SWIZ6
282
283
284/*
285 * Called right before feeding this->mixbuf to the hardware. Swizzle channels
286 * from Windows/Mac order to the format alsalib will want.
287 */
288static __inline__ void swizzle_alsa_channels(_THIS)
289{
290 if (this->spec.channels == 6) {
291 const Uint16 fmtsize = (this->spec.format & 0xFF); /* bits/channel. */
292 if (fmtsize == 16)
293 swizzle_alsa_channels_6_16bit(this);
294 else if (fmtsize == 8)
295 swizzle_alsa_channels_6_8bit(this);
296 else if (fmtsize == 32)
297 swizzle_alsa_channels_6_32bit(this);
298 else if (fmtsize == 64)
299 swizzle_alsa_channels_6_64bit(this);
300 }
301
302 /* !!! FIXME: update this for 7.1 if needed, later. */
303}
304
305
306static void ALSA_PlayAudio(_THIS)
307{
308 int status;
309 snd_pcm_uframes_t frames_left;
310 const Uint8 *sample_buf = (const Uint8 *) mixbuf;
311 const int frame_size = (((int) (this->spec.format & 0xFF)) / 8) * this->spec.channels;
312
313 swizzle_alsa_channels(this);
314
315 frames_left = ((snd_pcm_uframes_t) this->spec.samples);
316
317 while ( frames_left > 0 && this->enabled ) {
318 /* This works, but needs more testing before going live */
319 /*SDL_NAME(snd_pcm_wait)(pcm_handle, -1);*/
320
321 status = SDL_NAME(snd_pcm_writei)(pcm_handle, sample_buf, frames_left);
322 if ( status < 0 ) {
323 if ( status == -EAGAIN ) {
324 /* Apparently snd_pcm_recover() doesn't handle this case - does it assume snd_pcm_wait() above? */
325 SDL_Delay(1);
326 continue;
327 }
328 status = SDL_NAME(snd_pcm_recover)(pcm_handle, status, 0);
329 if ( status < 0 ) {
330 /* Hmm, not much we can do - abort */
331 fprintf(stderr, "ALSA write failed (unrecoverable): %s\n", SDL_NAME(snd_strerror)(status));
332 this->enabled = 0;
333 return;
334 }
335 continue;
336 }
337 sample_buf += status * frame_size;
338 frames_left -= status;
339 }
340}
341
342static Uint8 *ALSA_GetAudioBuf(_THIS)
343{
344 return(mixbuf);
345}
346
347static void ALSA_CloseAudio(_THIS)
348{
349 if ( mixbuf != NULL ) {
350 SDL_FreeAudioMem(mixbuf);
351 mixbuf = NULL;
352 }
353 if ( pcm_handle ) {
354 SDL_NAME(snd_pcm_drain)(pcm_handle);
355 SDL_NAME(snd_pcm_close)(pcm_handle);
356 pcm_handle = NULL;
357 }
358}
359
360static int ALSA_finalize_hardware(_THIS, SDL_AudioSpec *spec, snd_pcm_hw_params_t *hwparams, int override)
361{
362 int status;
363 snd_pcm_uframes_t bufsize;
364
365 /* "set" the hardware with the desired parameters */
366 status = SDL_NAME(snd_pcm_hw_params)(pcm_handle, hwparams);
367 if ( status < 0 ) {
368 return(-1);
369 }
370
371 /* Get samples for the actual buffer size */
372 status = SDL_NAME(snd_pcm_hw_params_get_buffer_size)(hwparams, &bufsize);
373 if ( status < 0 ) {
374 return(-1);
375 }
376 if ( !override && bufsize != spec->samples * 2 ) {
377 return(-1);
378 }
379
380 /* FIXME: Is this safe to do? */
381 spec->samples = bufsize / 2;
382
383 /* This is useful for debugging */
384 if ( getenv("SDL_AUDIO_ALSA_DEBUG") ) {
385 snd_pcm_uframes_t persize = 0;
386 unsigned int periods = 0;
387
388 SDL_NAME(snd_pcm_hw_params_get_period_size)(hwparams, &persize, NULL);
389 SDL_NAME(snd_pcm_hw_params_get_periods)(hwparams, &periods, NULL);
390
391 fprintf(stderr, "ALSA: period size = %ld, periods = %u, buffer size = %lu\n", persize, periods, bufsize);
392 }
393 return(0);
394}
395
396static int ALSA_set_period_size(_THIS, SDL_AudioSpec *spec, snd_pcm_hw_params_t *params, int override)
397{
398 const char *env;
399 int status;
400 snd_pcm_hw_params_t *hwparams;
401 snd_pcm_uframes_t frames;
402 unsigned int periods;
403
404 /* Copy the hardware parameters for this setup */
405 snd_pcm_hw_params_alloca(&hwparams);
406 SDL_NAME(snd_pcm_hw_params_copy)(hwparams, params);
407
408 if ( !override ) {
409 env = getenv("SDL_AUDIO_ALSA_SET_PERIOD_SIZE");
410 if ( env ) {
411 override = SDL_atoi(env);
412 if ( override == 0 ) {
413 return(-1);
414 }
415 }
416 }
417
418 frames = spec->samples;
419 status = SDL_NAME(snd_pcm_hw_params_set_period_size_near)(pcm_handle, hwparams, &frames, NULL);
420 if ( status < 0 ) {
421 return(-1);
422 }
423
424 periods = 2;
425 status = SDL_NAME(snd_pcm_hw_params_set_periods_near)(pcm_handle, hwparams, &periods, NULL);
426 if ( status < 0 ) {
427 return(-1);
428 }
429
430 return ALSA_finalize_hardware(this, spec, hwparams, override);
431}
432
433static int ALSA_set_buffer_size(_THIS, SDL_AudioSpec *spec, snd_pcm_hw_params_t *params, int override)
434{
435 const char *env;
436 int status;
437 snd_pcm_hw_params_t *hwparams;
438 snd_pcm_uframes_t frames;
439
440 /* Copy the hardware parameters for this setup */
441 snd_pcm_hw_params_alloca(&hwparams);
442 SDL_NAME(snd_pcm_hw_params_copy)(hwparams, params);
443
444 if ( !override ) {
445 env = getenv("SDL_AUDIO_ALSA_SET_BUFFER_SIZE");
446 if ( env ) {
447 override = SDL_atoi(env);
448 if ( override == 0 ) {
449 return(-1);
450 }
451 }
452 }
453
454 frames = spec->samples * 2;
455 status = SDL_NAME(snd_pcm_hw_params_set_buffer_size_near)(pcm_handle, hwparams, &frames);
456 if ( status < 0 ) {
457 return(-1);
458 }
459
460 return ALSA_finalize_hardware(this, spec, hwparams, override);
461}
462
463static int ALSA_OpenAudio(_THIS, SDL_AudioSpec *spec)
464{
465 int status;
466 snd_pcm_hw_params_t *hwparams;
467 snd_pcm_sw_params_t *swparams;
468 snd_pcm_format_t format;
469 unsigned int rate;
470 unsigned int channels;
471 Uint16 test_format;
472
473 /* Open the audio device */
474 /* Name of device should depend on # channels in spec */
475 status = SDL_NAME(snd_pcm_open)(&pcm_handle, get_audio_device(spec->channels), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
476
477 if ( status < 0 ) {
478 SDL_SetError("Couldn't open audio device: %s", SDL_NAME(snd_strerror)(status));
479 return(-1);
480 }
481
482 /* Figure out what the hardware is capable of */
483 snd_pcm_hw_params_alloca(&hwparams);
484 status = SDL_NAME(snd_pcm_hw_params_any)(pcm_handle, hwparams);
485 if ( status < 0 ) {
486 SDL_SetError("Couldn't get hardware config: %s", SDL_NAME(snd_strerror)(status));
487 ALSA_CloseAudio(this);
488 return(-1);
489 }
490
491 /* SDL only uses interleaved sample output */
492 status = SDL_NAME(snd_pcm_hw_params_set_access)(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED);
493 if ( status < 0 ) {
494 SDL_SetError("Couldn't set interleaved access: %s", SDL_NAME(snd_strerror)(status));
495 ALSA_CloseAudio(this);
496 return(-1);
497 }
498
499 /* Try for a closest match on audio format */
500 status = -1;
501 for ( test_format = SDL_FirstAudioFormat(spec->format);
502 test_format && (status < 0); ) {
503 switch ( test_format ) {
504 case AUDIO_U8:
505 format = SND_PCM_FORMAT_U8;
506 break;
507 case AUDIO_S8:
508 format = SND_PCM_FORMAT_S8;
509 break;
510 case AUDIO_S16LSB:
511 format = SND_PCM_FORMAT_S16_LE;
512 break;
513 case AUDIO_S16MSB:
514 format = SND_PCM_FORMAT_S16_BE;
515 break;
516 case AUDIO_U16LSB:
517 format = SND_PCM_FORMAT_U16_LE;
518 break;
519 case AUDIO_U16MSB:
520 format = SND_PCM_FORMAT_U16_BE;
521 break;
522 default:
523 format = 0;
524 break;
525 }
526 if ( format != 0 ) {
527 status = SDL_NAME(snd_pcm_hw_params_set_format)(pcm_handle, hwparams, format);
528 }
529 if ( status < 0 ) {
530 test_format = SDL_NextAudioFormat();
531 }
532 }
533 if ( status < 0 ) {
534 SDL_SetError("Couldn't find any hardware audio formats");
535 ALSA_CloseAudio(this);
536 return(-1);
537 }
538 spec->format = test_format;
539
540 /* Set the number of channels */
541 status = SDL_NAME(snd_pcm_hw_params_set_channels)(pcm_handle, hwparams, spec->channels);
542 channels = spec->channels;
543 if ( status < 0 ) {
544 status = SDL_NAME(snd_pcm_hw_params_get_channels)(hwparams, &channels);
545 if ( status < 0 ) {
546 SDL_SetError("Couldn't set audio channels");
547 ALSA_CloseAudio(this);
548 return(-1);
549 }
550 spec->channels = channels;
551 }
552
553 /* Set the audio rate */
554 rate = spec->freq;
555
556 status = SDL_NAME(snd_pcm_hw_params_set_rate_near)(pcm_handle, hwparams, &rate, NULL);
557 if ( status < 0 ) {
558 SDL_SetError("Couldn't set audio frequency: %s", SDL_NAME(snd_strerror)(status));
559 ALSA_CloseAudio(this);
560 return(-1);
561 }
562 spec->freq = rate;
563
564 /* Set the buffer size, in samples */
565 if ( ALSA_set_period_size(this, spec, hwparams, 0) < 0 &&
566 ALSA_set_buffer_size(this, spec, hwparams, 0) < 0 ) {
567 /* Failed to set desired buffer size, do the best you can... */
568 if ( ALSA_set_period_size(this, spec, hwparams, 1) < 0 ) {
569 SDL_SetError("Couldn't set hardware audio parameters: %s", SDL_NAME(snd_strerror)(status));
570 ALSA_CloseAudio(this);
571 return(-1);
572 }
573 }
574
575 /* Set the software parameters */
576 snd_pcm_sw_params_alloca(&swparams);
577 status = SDL_NAME(snd_pcm_sw_params_current)(pcm_handle, swparams);
578 if ( status < 0 ) {
579 SDL_SetError("Couldn't get software config: %s", SDL_NAME(snd_strerror)(status));
580 ALSA_CloseAudio(this);
581 return(-1);
582 }
583 status = SDL_NAME(snd_pcm_sw_params_set_avail_min)(pcm_handle, swparams, spec->samples);
584 if ( status < 0 ) {
585 SDL_SetError("Couldn't set minimum available samples: %s", SDL_NAME(snd_strerror)(status));
586 ALSA_CloseAudio(this);
587 return(-1);
588 }
589 status = SDL_NAME(snd_pcm_sw_params_set_start_threshold)(pcm_handle, swparams, 1);
590 if ( status < 0 ) {
591 SDL_SetError("Couldn't set start threshold: %s", SDL_NAME(snd_strerror)(status));
592 ALSA_CloseAudio(this);
593 return(-1);
594 }
595 status = SDL_NAME(snd_pcm_sw_params)(pcm_handle, swparams);
596 if ( status < 0 ) {
597 SDL_SetError("Couldn't set software audio parameters: %s", SDL_NAME(snd_strerror)(status));
598 ALSA_CloseAudio(this);
599 return(-1);
600 }
601
602 /* Calculate the final parameters for this audio specification */
603 SDL_CalculateAudioSpec(spec);
604
605 /* Allocate mixing buffer */
606 mixlen = spec->size;
607 mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen);
608 if ( mixbuf == NULL ) {
609 ALSA_CloseAudio(this);
610 return(-1);
611 }
612 SDL_memset(mixbuf, spec->silence, spec->size);
613
614 /* Switch to blocking mode for playback */
615 SDL_NAME(snd_pcm_nonblock)(pcm_handle, 0);
616
617 /* We're ready to rock and roll. :-) */
618 return(0);
619}
diff --git a/apps/plugins/sdl/src/audio/alsa/SDL_alsa_audio.h b/apps/plugins/sdl/src/audio/alsa/SDL_alsa_audio.h
deleted file mode 100644
index 55ae87b8ac..0000000000
--- a/apps/plugins/sdl/src/audio/alsa/SDL_alsa_audio.h
+++ /dev/null
@@ -1,48 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _ALSA_PCM_audio_h
25#define _ALSA_PCM_audio_h
26
27#include <alsa/asoundlib.h>
28
29#include "../SDL_sysaudio.h"
30
31/* Hidden "this" pointer for the video functions */
32#define _THIS SDL_AudioDevice *this
33
34struct SDL_PrivateAudioData {
35 /* The audio device handle */
36 snd_pcm_t *pcm_handle;
37
38 /* Raw mixing buffer */
39 Uint8 *mixbuf;
40 int mixlen;
41};
42
43/* Old variable names */
44#define pcm_handle (this->hidden->pcm_handle)
45#define mixbuf (this->hidden->mixbuf)
46#define mixlen (this->hidden->mixlen)
47
48#endif /* _ALSA_PCM_audio_h */
diff --git a/apps/plugins/sdl/src/audio/arts/SDL_artsaudio.c b/apps/plugins/sdl/src/audio/arts/SDL_artsaudio.c
deleted file mode 100644
index 373f8c1677..0000000000
--- a/apps/plugins/sdl/src/audio/arts/SDL_artsaudio.c
+++ /dev/null
@@ -1,362 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer */
25
26#ifdef HAVE_SIGNAL_H
27#include <signal.h>
28#endif
29#include <unistd.h>
30
31#include "SDL_timer.h"
32#include "SDL_audio.h"
33#include "../SDL_audiomem.h"
34#include "../SDL_audio_c.h"
35#include "../SDL_audiodev_c.h"
36#include "SDL_artsaudio.h"
37
38#ifdef SDL_AUDIO_DRIVER_ARTS_DYNAMIC
39#include "SDL_name.h"
40#include "SDL_loadso.h"
41#else
42#define SDL_NAME(X) X
43#endif
44
45/* The tag name used by artsc audio */
46#define ARTS_DRIVER_NAME "arts"
47
48/* Audio driver functions */
49static int ARTS_OpenAudio(_THIS, SDL_AudioSpec *spec);
50static void ARTS_WaitAudio(_THIS);
51static void ARTS_PlayAudio(_THIS);
52static Uint8 *ARTS_GetAudioBuf(_THIS);
53static void ARTS_CloseAudio(_THIS);
54
55#ifdef SDL_AUDIO_DRIVER_ARTS_DYNAMIC
56
57static const char *arts_library = SDL_AUDIO_DRIVER_ARTS_DYNAMIC;
58static void *arts_handle = NULL;
59static int arts_loaded = 0;
60
61static int (*SDL_NAME(arts_init))(void);
62static void (*SDL_NAME(arts_free))(void);
63static arts_stream_t (*SDL_NAME(arts_play_stream))(int rate, int bits, int channels, const char *name);
64static int (*SDL_NAME(arts_stream_set))(arts_stream_t s, arts_parameter_t param, int value);
65static int (*SDL_NAME(arts_stream_get))(arts_stream_t s, arts_parameter_t param);
66static int (*SDL_NAME(arts_write))(arts_stream_t s, const void *buffer, int count);
67static void (*SDL_NAME(arts_close_stream))(arts_stream_t s);
68static int (*SDL_NAME(arts_suspend))(void);
69static int (*SDL_NAME(arts_suspended))(void);
70static const char *(*SDL_NAME(arts_error_text))(int errorcode);
71
72static struct {
73 const char *name;
74 void **func;
75} arts_functions[] = {
76 { "arts_init", (void **)&SDL_NAME(arts_init) },
77 { "arts_free", (void **)&SDL_NAME(arts_free) },
78 { "arts_play_stream", (void **)&SDL_NAME(arts_play_stream) },
79 { "arts_stream_set", (void **)&SDL_NAME(arts_stream_set) },
80 { "arts_stream_get", (void **)&SDL_NAME(arts_stream_get) },
81 { "arts_write", (void **)&SDL_NAME(arts_write) },
82 { "arts_close_stream", (void **)&SDL_NAME(arts_close_stream) },
83 { "arts_suspend", (void **)&SDL_NAME(arts_suspend) },
84 { "arts_suspended", (void **)&SDL_NAME(arts_suspended) },
85 { "arts_error_text", (void **)&SDL_NAME(arts_error_text) },
86};
87
88static void UnloadARTSLibrary()
89{
90 if ( arts_loaded ) {
91 SDL_UnloadObject(arts_handle);
92 arts_handle = NULL;
93 arts_loaded = 0;
94 }
95}
96
97static int LoadARTSLibrary(void)
98{
99 int i, retval = -1;
100
101 arts_handle = SDL_LoadObject(arts_library);
102 if ( arts_handle ) {
103 arts_loaded = 1;
104 retval = 0;
105 for ( i=0; i<SDL_arraysize(arts_functions); ++i ) {
106 *arts_functions[i].func = SDL_LoadFunction(arts_handle, arts_functions[i].name);
107 if ( !*arts_functions[i].func ) {
108 retval = -1;
109 UnloadARTSLibrary();
110 break;
111 }
112 }
113 }
114 return retval;
115}
116
117#else
118
119static void UnloadARTSLibrary()
120{
121 return;
122}
123
124static int LoadARTSLibrary(void)
125{
126 return 0;
127}
128
129#endif /* SDL_AUDIO_DRIVER_ARTS_DYNAMIC */
130
131/* Audio driver bootstrap functions */
132
133static int ARTS_Suspend(void)
134{
135 const Uint32 abortms = SDL_GetTicks() + 3000; /* give up after 3 secs */
136 while ( (!SDL_NAME(arts_suspended)()) && (SDL_GetTicks() < abortms) ) {
137 if ( SDL_NAME(arts_suspend)() ) {
138 break;
139 }
140 }
141
142 return SDL_NAME(arts_suspended)();
143}
144
145static int Audio_Available(void)
146{
147 int available = 0;
148
149 if ( LoadARTSLibrary() < 0 ) {
150 return available;
151 }
152 if ( SDL_NAME(arts_init)() == 0 ) {
153 if ( ARTS_Suspend() ) {
154 /* Play a stream so aRts doesn't crash */
155 arts_stream_t stream2;
156 stream2=SDL_NAME(arts_play_stream)(44100, 16, 2, "SDL");
157 SDL_NAME(arts_write)(stream2, "", 0);
158 SDL_NAME(arts_close_stream)(stream2);
159 available = 1;
160 }
161 SDL_NAME(arts_free)();
162 }
163 UnloadARTSLibrary();
164
165 return available;
166}
167
168static void Audio_DeleteDevice(SDL_AudioDevice *device)
169{
170 SDL_free(device->hidden);
171 SDL_free(device);
172 UnloadARTSLibrary();
173}
174
175static SDL_AudioDevice *Audio_CreateDevice(int devindex)
176{
177 SDL_AudioDevice *this;
178
179 /* Initialize all variables that we clean on shutdown */
180 LoadARTSLibrary();
181 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
182 if ( this ) {
183 SDL_memset(this, 0, (sizeof *this));
184 this->hidden = (struct SDL_PrivateAudioData *)
185 SDL_malloc((sizeof *this->hidden));
186 }
187 if ( (this == NULL) || (this->hidden == NULL) ) {
188 SDL_OutOfMemory();
189 if ( this ) {
190 SDL_free(this);
191 }
192 return(0);
193 }
194 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
195 stream = 0;
196
197 /* Set the function pointers */
198 this->OpenAudio = ARTS_OpenAudio;
199 this->WaitAudio = ARTS_WaitAudio;
200 this->PlayAudio = ARTS_PlayAudio;
201 this->GetAudioBuf = ARTS_GetAudioBuf;
202 this->CloseAudio = ARTS_CloseAudio;
203
204 this->free = Audio_DeleteDevice;
205
206 return this;
207}
208
209AudioBootStrap ARTS_bootstrap = {
210 ARTS_DRIVER_NAME, "Analog Realtime Synthesizer",
211 Audio_Available, Audio_CreateDevice
212};
213
214/* This function waits until it is possible to write a full sound buffer */
215static void ARTS_WaitAudio(_THIS)
216{
217 Sint32 ticks;
218
219 /* Check to see if the thread-parent process is still alive */
220 { static int cnt = 0;
221 /* Note that this only works with thread implementations
222 that use a different process id for each thread.
223 */
224 if (parent && (((++cnt)%10) == 0)) { /* Check every 10 loops */
225 if ( kill(parent, 0) < 0 ) {
226 this->enabled = 0;
227 }
228 }
229 }
230
231 /* Use timer for general audio synchronization */
232 ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS;
233 if ( ticks > 0 ) {
234 SDL_Delay(ticks);
235 }
236}
237
238static void ARTS_PlayAudio(_THIS)
239{
240 int written;
241
242 /* Write the audio data */
243 written = SDL_NAME(arts_write)(stream, mixbuf, mixlen);
244
245 /* If timer synchronization is enabled, set the next write frame */
246 if ( frame_ticks ) {
247 next_frame += frame_ticks;
248 }
249
250 /* If we couldn't write, assume fatal error for now */
251 if ( written < 0 ) {
252 this->enabled = 0;
253 }
254#ifdef DEBUG_AUDIO
255 fprintf(stderr, "Wrote %d bytes of audio data\n", written);
256#endif
257}
258
259static Uint8 *ARTS_GetAudioBuf(_THIS)
260{
261 return(mixbuf);
262}
263
264static void ARTS_CloseAudio(_THIS)
265{
266 if ( mixbuf != NULL ) {
267 SDL_FreeAudioMem(mixbuf);
268 mixbuf = NULL;
269 }
270 if ( stream ) {
271 SDL_NAME(arts_close_stream)(stream);
272 stream = 0;
273 }
274 SDL_NAME(arts_free)();
275}
276
277static int ARTS_OpenAudio(_THIS, SDL_AudioSpec *spec)
278{
279 int bits, frag_spec;
280 Uint16 test_format, format;
281 int error_code;
282
283 /* Reset the timer synchronization flag */
284 frame_ticks = 0.0;
285
286 mixbuf = NULL;
287
288 /* Try for a closest match on audio format */
289 format = 0;
290 bits = 0;
291 for ( test_format = SDL_FirstAudioFormat(spec->format);
292 ! format && test_format; ) {
293#ifdef DEBUG_AUDIO
294 fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
295#endif
296 switch ( test_format ) {
297 case AUDIO_U8:
298 bits = 8;
299 format = 1;
300 break;
301 case AUDIO_S16LSB:
302 bits = 16;
303 format = 1;
304 break;
305 default:
306 format = 0;
307 break;
308 }
309 if ( ! format ) {
310 test_format = SDL_NextAudioFormat();
311 }
312 }
313 if ( format == 0 ) {
314 SDL_SetError("Couldn't find any hardware audio formats");
315 return(-1);
316 }
317 spec->format = test_format;
318
319 error_code = SDL_NAME(arts_init)();
320 if ( error_code != 0 ) {
321 SDL_SetError("Unable to initialize ARTS: %s", SDL_NAME(arts_error_text)(error_code));
322 return(-1);
323 }
324 if ( ! ARTS_Suspend() ) {
325 SDL_SetError("ARTS can not open audio device");
326 return(-1);
327 }
328 stream = SDL_NAME(arts_play_stream)(spec->freq, bits, spec->channels, "SDL");
329
330 /* Calculate the final parameters for this audio specification */
331 SDL_CalculateAudioSpec(spec);
332
333 /* Determine the power of two of the fragment size */
334 for ( frag_spec = 0; (0x01<<frag_spec) < spec->size; ++frag_spec );
335 if ( (0x01<<frag_spec) != spec->size ) {
336 SDL_SetError("Fragment size must be a power of two");
337 return(-1);
338 }
339 frag_spec |= 0x00020000; /* two fragments, for low latency */
340
341#ifdef ARTS_P_PACKET_SETTINGS
342 SDL_NAME(arts_stream_set)(stream, ARTS_P_PACKET_SETTINGS, frag_spec);
343#else
344 SDL_NAME(arts_stream_set)(stream, ARTS_P_PACKET_SIZE, frag_spec&0xffff);
345 SDL_NAME(arts_stream_set)(stream, ARTS_P_PACKET_COUNT, frag_spec>>16);
346#endif
347 spec->size = SDL_NAME(arts_stream_get)(stream, ARTS_P_PACKET_SIZE);
348
349 /* Allocate mixing buffer */
350 mixlen = spec->size;
351 mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen);
352 if ( mixbuf == NULL ) {
353 return(-1);
354 }
355 SDL_memset(mixbuf, spec->silence, spec->size);
356
357 /* Get the parent process id (we're the parent of the audio thread) */
358 parent = getpid();
359
360 /* We're ready to rock and roll. :-) */
361 return(0);
362}
diff --git a/apps/plugins/sdl/src/audio/arts/SDL_artsaudio.h b/apps/plugins/sdl/src/audio/arts/SDL_artsaudio.h
deleted file mode 100644
index de3b22822c..0000000000
--- a/apps/plugins/sdl/src/audio/arts/SDL_artsaudio.h
+++ /dev/null
@@ -1,60 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_artscaudio_h
25#define _SDL_artscaudio_h
26
27#include <artsc.h>
28
29#include "../SDL_sysaudio.h"
30
31/* Hidden "this" pointer for the video functions */
32#define _THIS SDL_AudioDevice *this
33
34struct SDL_PrivateAudioData {
35 /* The stream descriptor for the audio device */
36 arts_stream_t stream;
37
38 /* The parent process id, to detect when application quits */
39 pid_t parent;
40
41 /* Raw mixing buffer */
42 Uint8 *mixbuf;
43 int mixlen;
44
45 /* Support for audio timing using a timer, in addition to select() */
46 float frame_ticks;
47 float next_frame;
48};
49#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
50
51/* Old variable names */
52#define stream (this->hidden->stream)
53#define parent (this->hidden->parent)
54#define mixbuf (this->hidden->mixbuf)
55#define mixlen (this->hidden->mixlen)
56#define frame_ticks (this->hidden->frame_ticks)
57#define next_frame (this->hidden->next_frame)
58
59#endif /* _SDL_artscaudio_h */
60
diff --git a/apps/plugins/sdl/src/audio/baudio/SDL_beaudio.cc b/apps/plugins/sdl/src/audio/baudio/SDL_beaudio.cc
deleted file mode 100644
index de635f8bad..0000000000
--- a/apps/plugins/sdl/src/audio/baudio/SDL_beaudio.cc
+++ /dev/null
@@ -1,225 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to the audio stream on BeOS */
25
26#include <SoundPlayer.h>
27
28#include "../../main/beos/SDL_BeApp.h"
29
30extern "C" {
31
32#include "SDL_audio.h"
33#include "../SDL_audio_c.h"
34#include "../SDL_sysaudio.h"
35#include "../../thread/beos/SDL_systhread_c.h"
36#include "SDL_beaudio.h"
37
38
39/* Audio driver functions */
40static int BE_OpenAudio(_THIS, SDL_AudioSpec *spec);
41static void BE_WaitAudio(_THIS);
42static void BE_PlayAudio(_THIS);
43static Uint8 *BE_GetAudioBuf(_THIS);
44static void BE_CloseAudio(_THIS);
45
46/* Audio driver bootstrap functions */
47
48static int Audio_Available(void)
49{
50 return(1);
51}
52
53static void Audio_DeleteDevice(SDL_AudioDevice *device)
54{
55 SDL_free(device->hidden);
56 SDL_free(device);
57}
58
59static SDL_AudioDevice *Audio_CreateDevice(int devindex)
60{
61 SDL_AudioDevice *device;
62
63 /* Initialize all variables that we clean on shutdown */
64 device = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
65 if ( device ) {
66 SDL_memset(device, 0, (sizeof *device));
67 device->hidden = (struct SDL_PrivateAudioData *)
68 SDL_malloc((sizeof *device->hidden));
69 }
70 if ( (device == NULL) || (device->hidden == NULL) ) {
71 SDL_OutOfMemory();
72 if ( device ) {
73 SDL_free(device);
74 }
75 return(0);
76 }
77 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
78
79 /* Set the function pointers */
80 device->OpenAudio = BE_OpenAudio;
81 device->WaitAudio = BE_WaitAudio;
82 device->PlayAudio = BE_PlayAudio;
83 device->GetAudioBuf = BE_GetAudioBuf;
84 device->CloseAudio = BE_CloseAudio;
85
86 device->free = Audio_DeleteDevice;
87
88 return device;
89}
90
91AudioBootStrap BAUDIO_bootstrap = {
92 "baudio", "BeOS BSoundPlayer",
93 Audio_Available, Audio_CreateDevice
94};
95
96/* The BeOS callback for handling the audio buffer */
97static void FillSound(void *device, void *stream, size_t len,
98 const media_raw_audio_format &format)
99{
100 SDL_AudioDevice *audio = (SDL_AudioDevice *)device;
101
102 /* Silence the buffer, since it's ours */
103 SDL_memset(stream, audio->spec.silence, len);
104
105 /* Only do soemthing if audio is enabled */
106 if ( ! audio->enabled )
107 return;
108
109 if ( ! audio->paused ) {
110 if ( audio->convert.needed ) {
111 SDL_mutexP(audio->mixer_lock);
112 (*audio->spec.callback)(audio->spec.userdata,
113 (Uint8 *)audio->convert.buf,audio->convert.len);
114 SDL_mutexV(audio->mixer_lock);
115 SDL_ConvertAudio(&audio->convert);
116 SDL_memcpy(stream,audio->convert.buf,audio->convert.len_cvt);
117 } else {
118 SDL_mutexP(audio->mixer_lock);
119 (*audio->spec.callback)(audio->spec.userdata,
120 (Uint8 *)stream, len);
121 SDL_mutexV(audio->mixer_lock);
122 }
123 }
124 return;
125}
126
127/* Dummy functions -- we don't use thread-based audio */
128void BE_WaitAudio(_THIS)
129{
130 return;
131}
132void BE_PlayAudio(_THIS)
133{
134 return;
135}
136Uint8 *BE_GetAudioBuf(_THIS)
137{
138 return(NULL);
139}
140
141void BE_CloseAudio(_THIS)
142{
143 if ( audio_obj ) {
144 audio_obj->Stop();
145 delete audio_obj;
146 audio_obj = NULL;
147 }
148
149 /* Quit the Be Application, if there's nothing left to do */
150 SDL_QuitBeApp();
151}
152
153int BE_OpenAudio(_THIS, SDL_AudioSpec *spec)
154{
155 int valid_datatype = 0;
156 media_raw_audio_format format;
157 Uint16 test_format = SDL_FirstAudioFormat(spec->format);
158
159 /* Parse the audio format and fill the Be raw audio format */
160 memset(&format, '\0', sizeof (media_raw_audio_format));
161 format.byte_order = B_MEDIA_LITTLE_ENDIAN;
162 format.frame_rate = (float) spec->freq;
163 format.channel_count = spec->channels; /* !!! FIXME: support > 2? */
164 while ((!valid_datatype) && (test_format)) {
165 valid_datatype = 1;
166 spec->format = test_format;
167 switch (test_format) {
168 case AUDIO_S8:
169 format.format = media_raw_audio_format::B_AUDIO_CHAR;
170 break;
171
172 case AUDIO_U8:
173 format.format = media_raw_audio_format::B_AUDIO_UCHAR;
174 break;
175
176 case AUDIO_S16LSB:
177 format.format = media_raw_audio_format::B_AUDIO_SHORT;
178 break;
179
180 case AUDIO_S16MSB:
181 format.format = media_raw_audio_format::B_AUDIO_SHORT;
182 format.byte_order = B_MEDIA_BIG_ENDIAN;
183 break;
184
185 default:
186 valid_datatype = 0;
187 test_format = SDL_NextAudioFormat();
188 break;
189 }
190 }
191
192 if (!valid_datatype) { /* shouldn't happen, but just in case... */
193 SDL_SetError("Unsupported audio format");
194 return (-1);
195 }
196
197 /* Initialize the Be Application, if it's not already started */
198 if (SDL_InitBeApp() < 0) {
199 return (-1);
200 }
201
202 format.buffer_size = spec->samples;
203
204 /* Calculate the final parameters for this audio specification */
205 SDL_CalculateAudioSpec(spec);
206
207 /* Subscribe to the audio stream (creates a new thread) */
208 { sigset_t omask;
209 SDL_MaskSignals(&omask);
210 audio_obj = new BSoundPlayer(&format, "SDL Audio", FillSound,
211 NULL, _this);
212 SDL_UnmaskSignals(&omask);
213 }
214 if ( audio_obj->Start() == B_NO_ERROR ) {
215 audio_obj->SetHasData(true);
216 } else {
217 SDL_SetError("Unable to start Be audio");
218 return(-1);
219 }
220
221 /* We're running! */
222 return(1);
223}
224
225}; /* Extern C */
diff --git a/apps/plugins/sdl/src/audio/baudio/SDL_beaudio.h b/apps/plugins/sdl/src/audio/baudio/SDL_beaudio.h
deleted file mode 100644
index adaf1dee5d..0000000000
--- a/apps/plugins/sdl/src/audio/baudio/SDL_beaudio.h
+++ /dev/null
@@ -1,39 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowaudio_h
25#define _SDL_lowaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the video functions */
30#define _THIS SDL_AudioDevice *_this
31
32struct SDL_PrivateAudioData {
33 BSoundPlayer *audio_obj;
34};
35
36/* Old variable names */
37#define audio_obj (_this->hidden->audio_obj)
38
39#endif /* _SDL_lowaudio_h */
diff --git a/apps/plugins/sdl/src/audio/bsd/SDL_bsdaudio.c b/apps/plugins/sdl/src/audio/bsd/SDL_bsdaudio.c
deleted file mode 100644
index e5e0d9480a..0000000000
--- a/apps/plugins/sdl/src/audio/bsd/SDL_bsdaudio.c
+++ /dev/null
@@ -1,404 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Driver for native OpenBSD/NetBSD audio(4).
26 * vedge@vedge.com.ar.
27 */
28
29#include <errno.h>
30#include <unistd.h>
31#include <fcntl.h>
32#include <sys/time.h>
33#include <sys/ioctl.h>
34#include <sys/stat.h>
35#include <sys/types.h>
36#include <sys/audioio.h>
37
38#include "SDL_timer.h"
39#include "SDL_audio.h"
40#include "../SDL_audiomem.h"
41#include "../SDL_audio_c.h"
42#include "../SDL_audiodev_c.h"
43#include "SDL_bsdaudio.h"
44
45/* The tag name used by NetBSD/OpenBSD audio */
46#ifdef __NetBSD__
47#define BSD_AUDIO_DRIVER_NAME "netbsd"
48#define BSD_AUDIO_DRIVER_DESC "Native NetBSD audio"
49#else
50#define BSD_AUDIO_DRIVER_NAME "openbsd"
51#define BSD_AUDIO_DRIVER_DESC "Native OpenBSD audio"
52#endif
53
54/* Open the audio device for playback, and don't block if busy */
55/* #define USE_BLOCKING_WRITES */
56
57/* Use timer for synchronization */
58/* #define USE_TIMER_SYNC */
59
60/* #define DEBUG_AUDIO */
61/* #define DEBUG_AUDIO_STREAM */
62
63#ifdef USE_BLOCKING_WRITES
64#define OPEN_FLAGS O_WRONLY
65#else
66#define OPEN_FLAGS (O_WRONLY|O_NONBLOCK)
67#endif
68
69/* Audio driver functions */
70static void OBSD_WaitAudio(_THIS);
71static int OBSD_OpenAudio(_THIS, SDL_AudioSpec *spec);
72static void OBSD_PlayAudio(_THIS);
73static Uint8 *OBSD_GetAudioBuf(_THIS);
74static void OBSD_CloseAudio(_THIS);
75
76#ifdef DEBUG_AUDIO
77static void OBSD_Status(_THIS);
78#endif
79
80/* Audio driver bootstrap functions */
81
82static int
83Audio_Available(void)
84{
85 int fd;
86 int available;
87
88 available = 0;
89 fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0);
90 if(fd >= 0) {
91 available = 1;
92 close(fd);
93 }
94 return(available);
95}
96
97static void
98Audio_DeleteDevice(SDL_AudioDevice *device)
99{
100 SDL_free(device->hidden);
101 SDL_free(device);
102}
103
104static SDL_AudioDevice
105*Audio_CreateDevice(int devindex)
106{
107 SDL_AudioDevice *this;
108
109 /* Initialize all variables that we clean on shutdown */
110 this = (SDL_AudioDevice*)SDL_malloc(sizeof(SDL_AudioDevice));
111 if(this) {
112 SDL_memset(this, 0, (sizeof *this));
113 this->hidden =
114 (struct SDL_PrivateAudioData*)SDL_malloc((sizeof *this->hidden));
115 }
116 if((this == NULL) || (this->hidden == NULL)) {
117 SDL_OutOfMemory();
118 if(this) SDL_free(this);
119 return(0);
120 }
121 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
122 audio_fd = -1;
123
124 /* Set the function pointers */
125 this->OpenAudio = OBSD_OpenAudio;
126 this->WaitAudio = OBSD_WaitAudio;
127 this->PlayAudio = OBSD_PlayAudio;
128 this->GetAudioBuf = OBSD_GetAudioBuf;
129 this->CloseAudio = OBSD_CloseAudio;
130
131 this->free = Audio_DeleteDevice;
132
133 return this;
134}
135
136AudioBootStrap BSD_AUDIO_bootstrap = {
137 BSD_AUDIO_DRIVER_NAME, BSD_AUDIO_DRIVER_DESC,
138 Audio_Available, Audio_CreateDevice
139};
140
141/* This function waits until it is possible to write a full sound buffer */
142static void
143OBSD_WaitAudio(_THIS)
144{
145#ifndef USE_BLOCKING_WRITES /* Not necessary when using blocking writes */
146 /* See if we need to use timed audio synchronization */
147 if ( frame_ticks ) {
148 /* Use timer for general audio synchronization */
149 Sint32 ticks;
150
151 ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS;
152 if ( ticks > 0 ) {
153 SDL_Delay(ticks);
154 }
155 } else {
156 /* Use select() for audio synchronization */
157 fd_set fdset;
158 struct timeval timeout;
159
160 FD_ZERO(&fdset);
161 FD_SET(audio_fd, &fdset);
162 timeout.tv_sec = 10;
163 timeout.tv_usec = 0;
164#ifdef DEBUG_AUDIO
165 fprintf(stderr, "Waiting for audio to get ready\n");
166#endif
167 if ( select(audio_fd+1, NULL, &fdset, NULL, &timeout) <= 0 ) {
168 const char *message =
169 "Audio timeout - buggy audio driver? (disabled)";
170 /* In general we should never print to the screen,
171 but in this case we have no other way of letting
172 the user know what happened.
173 */
174 fprintf(stderr, "SDL: %s\n", message);
175 this->enabled = 0;
176 /* Don't try to close - may hang */
177 audio_fd = -1;
178#ifdef DEBUG_AUDIO
179 fprintf(stderr, "Done disabling audio\n");
180#endif
181 }
182#ifdef DEBUG_AUDIO
183 fprintf(stderr, "Ready!\n");
184#endif
185 }
186#endif /* !USE_BLOCKING_WRITES */
187}
188
189static void
190OBSD_PlayAudio(_THIS)
191{
192 int written, p=0;
193
194 /* Write the audio data, checking for EAGAIN on broken audio drivers */
195 do {
196 written = write(audio_fd, &mixbuf[p], mixlen-p);
197 if (written>0)
198 p += written;
199 if (written == -1 && errno != 0 && errno != EAGAIN && errno != EINTR)
200 {
201 /* Non recoverable error has occurred. It should be reported!!! */
202 perror("audio");
203 break;
204 }
205
206 if ( p < written || ((written < 0) && ((errno == 0) || (errno == EAGAIN))) ) {
207 SDL_Delay(1); /* Let a little CPU time go by */
208 }
209 } while ( p < written );
210
211 /* If timer synchronization is enabled, set the next write frame */
212 if ( frame_ticks ) {
213 next_frame += frame_ticks;
214 }
215
216 /* If we couldn't write, assume fatal error for now */
217 if ( written < 0 ) {
218 this->enabled = 0;
219 }
220#ifdef DEBUG_AUDIO
221 fprintf(stderr, "Wrote %d bytes of audio data\n", written);
222#endif
223}
224
225static Uint8
226*OBSD_GetAudioBuf(_THIS)
227{
228 return(mixbuf);
229}
230
231static void
232OBSD_CloseAudio(_THIS)
233{
234 if(mixbuf != NULL) {
235 SDL_FreeAudioMem(mixbuf);
236 mixbuf = NULL;
237 }
238 if(audio_fd >= 0) {
239 close(audio_fd);
240 audio_fd = -1;
241 }
242}
243
244#ifdef DEBUG_AUDIO
245void
246OBSD_Status(_THIS)
247{
248 audio_info_t info;
249
250 if(ioctl(audio_fd, AUDIO_GETINFO, &info) < 0) {
251 fprintf(stderr,"AUDIO_GETINFO failed.\n");
252 return;
253 }
254
255 fprintf(stderr,"\n"
256"[play/record info]\n"
257"buffer size : %d bytes\n"
258"sample rate : %i Hz\n"
259"channels : %i\n"
260"precision : %i-bit\n"
261"encoding : 0x%x\n"
262"seek : %i\n"
263"sample count : %i\n"
264"EOF count : %i\n"
265"paused : %s\n"
266"error occured : %s\n"
267"waiting : %s\n"
268"active : %s\n"
269"",
270 info.play.buffer_size,
271 info.play.sample_rate,
272 info.play.channels,
273 info.play.precision,
274 info.play.encoding,
275 info.play.seek,
276 info.play.samples,
277 info.play.eof,
278 info.play.pause ? "yes" : "no",
279 info.play.error ? "yes" : "no",
280 info.play.waiting ? "yes" : "no",
281 info.play.active ? "yes": "no");
282
283 fprintf(stderr,"\n"
284"[audio info]\n"
285"monitor_gain : %i\n"
286"hw block size : %d bytes\n"
287"hi watermark : %i\n"
288"lo watermark : %i\n"
289"audio mode : %s\n"
290"",
291 info.monitor_gain,
292 info.blocksize,
293 info.hiwat, info.lowat,
294 (info.mode == AUMODE_PLAY) ? "PLAY"
295 : (info.mode = AUMODE_RECORD) ? "RECORD"
296 : (info.mode == AUMODE_PLAY_ALL ? "PLAY_ALL"
297 : "?"));
298}
299#endif /* DEBUG_AUDIO */
300
301static int
302OBSD_OpenAudio(_THIS, SDL_AudioSpec *spec)
303{
304 char audiodev[64];
305 Uint16 format;
306 audio_info_t info;
307
308 AUDIO_INITINFO(&info);
309
310 /* Calculate the final parameters for this audio specification */
311 SDL_CalculateAudioSpec(spec);
312
313#ifdef USE_TIMER_SYNC
314 frame_ticks = 0.0;
315#endif
316
317 /* Open the audio device */
318 audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0);
319 if(audio_fd < 0) {
320 SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
321 return(-1);
322 }
323
324 /* Set to play mode */
325 info.mode = AUMODE_PLAY;
326 if(ioctl(audio_fd, AUDIO_SETINFO, &info) < 0) {
327 SDL_SetError("Couldn't put device into play mode");
328 return(-1);
329 }
330
331 mixbuf = NULL;
332 AUDIO_INITINFO(&info);
333 for (format = SDL_FirstAudioFormat(spec->format);
334 format; format = SDL_NextAudioFormat())
335 {
336 switch(format) {
337 case AUDIO_U8:
338 info.play.encoding = AUDIO_ENCODING_ULINEAR;
339 info.play.precision = 8;
340 break;
341 case AUDIO_S8:
342 info.play.encoding = AUDIO_ENCODING_SLINEAR;
343 info.play.precision = 8;
344 break;
345 case AUDIO_S16LSB:
346 info.play.encoding = AUDIO_ENCODING_SLINEAR_LE;
347 info.play.precision = 16;
348 break;
349 case AUDIO_S16MSB:
350 info.play.encoding = AUDIO_ENCODING_SLINEAR_BE;
351 info.play.precision = 16;
352 break;
353 case AUDIO_U16LSB:
354 info.play.encoding = AUDIO_ENCODING_ULINEAR_LE;
355 info.play.precision = 16;
356 break;
357 case AUDIO_U16MSB:
358 info.play.encoding = AUDIO_ENCODING_ULINEAR_BE;
359 info.play.precision = 16;
360 break;
361 default:
362 continue;
363 }
364 if (ioctl(audio_fd, AUDIO_SETINFO, &info) == 0)
365 break;
366 }
367
368 if(!format) {
369 SDL_SetError("No supported encoding for 0x%x", spec->format);
370 return(-1);
371 }
372
373 spec->format = format;
374
375 AUDIO_INITINFO(&info);
376 info.play.channels = spec->channels;
377 if (ioctl(audio_fd, AUDIO_SETINFO, &info) == -1)
378 spec->channels = 1;
379 AUDIO_INITINFO(&info);
380 info.play.sample_rate = spec->freq;
381 info.blocksize = spec->size;
382 info.hiwat = 5;
383 info.lowat = 3;
384 (void)ioctl(audio_fd, AUDIO_SETINFO, &info);
385 (void)ioctl(audio_fd, AUDIO_GETINFO, &info);
386 spec->freq = info.play.sample_rate;
387 /* Allocate mixing buffer */
388 mixlen = spec->size;
389 mixbuf = (Uint8*)SDL_AllocAudioMem(mixlen);
390 if(mixbuf == NULL) {
391 return(-1);
392 }
393 SDL_memset(mixbuf, spec->silence, spec->size);
394
395 /* Get the parent process id (we're the parent of the audio thread) */
396 parent = getpid();
397
398#ifdef DEBUG_AUDIO
399 OBSD_Status(this);
400#endif
401
402 /* We're ready to rock and roll. :-) */
403 return(0);
404}
diff --git a/apps/plugins/sdl/src/audio/bsd/SDL_bsdaudio.h b/apps/plugins/sdl/src/audio/bsd/SDL_bsdaudio.h
deleted file mode 100644
index c9f69cf544..0000000000
--- a/apps/plugins/sdl/src/audio/bsd/SDL_bsdaudio.h
+++ /dev/null
@@ -1,58 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_openbsdaudio_h
25#define _SDL_openbsdaudio_h
26
27#include "../SDL_sysaudio.h"
28
29#define _THIS SDL_AudioDevice *this
30
31struct SDL_PrivateAudioData
32{
33 /* The file descriptor for the audio device */
34 int audio_fd;
35
36 /* The parent process id, to detect when application quits */
37 pid_t parent;
38
39 /* Raw mixing buffer */
40 Uint8 *mixbuf;
41 int mixlen;
42
43 /* Support for audio timing using a timer, in addition to select() */
44 float frame_ticks;
45 float next_frame;
46};
47
48#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
49
50/* Old variable names */
51#define audio_fd (this->hidden->audio_fd)
52#define parent (this->hidden->parent)
53#define mixbuf (this->hidden->mixbuf)
54#define mixlen (this->hidden->mixlen)
55#define frame_ticks (this->hidden->frame_ticks)
56#define next_frame (this->hidden->next_frame)
57
58#endif /* _SDL_openbsdaudio_h */
diff --git a/apps/plugins/sdl/src/audio/dart/SDL_dart.c b/apps/plugins/sdl/src/audio/dart/SDL_dart.c
deleted file mode 100644
index 77e530db51..0000000000
--- a/apps/plugins/sdl/src/audio/dart/SDL_dart.c
+++ /dev/null
@@ -1,441 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer */
25
26#include "SDL_timer.h"
27#include "SDL_audio.h"
28#include "../SDL_audio_c.h"
29#include "SDL_dart.h"
30
31// Buffer states:
32#define BUFFER_EMPTY 0
33#define BUFFER_USED 1
34
35typedef struct _tMixBufferDesc {
36 int iBufferUsage; // BUFFER_EMPTY or BUFFER_USED
37 SDL_AudioDevice *pSDLAudioDevice;
38} tMixBufferDesc, *pMixBufferDesc;
39
40
41//---------------------------------------------------------------------
42// DARTEventFunc
43//
44// This function is called by DART, when an event occures, like end of
45// playback of a buffer, etc...
46//---------------------------------------------------------------------
47LONG APIENTRY DARTEventFunc(ULONG ulStatus,
48 PMCI_MIX_BUFFER pBuffer,
49 ULONG ulFlags)
50{
51 if (ulFlags && MIX_WRITE_COMPLETE)
52 { // Playback of buffer completed!
53
54 // Get pointer to buffer description
55 pMixBufferDesc pBufDesc;
56
57 if (pBuffer)
58 {
59 pBufDesc = (pMixBufferDesc) (*pBuffer).ulUserParm;
60
61 if (pBufDesc)
62 {
63 SDL_AudioDevice *pSDLAudioDevice = pBufDesc->pSDLAudioDevice;
64 // Set the buffer to be empty
65 pBufDesc->iBufferUsage = BUFFER_EMPTY;
66 // And notify DART feeder thread that it will have to work a bit.
67 if (pSDLAudioDevice)
68 DosPostEventSem(pSDLAudioDevice->hidden->hevAudioBufferPlayed);
69 }
70 }
71 }
72 return TRUE;
73}
74
75
76int DART_OpenAudio(_THIS, SDL_AudioSpec *spec)
77{
78 Uint16 test_format = SDL_FirstAudioFormat(spec->format);
79 int valid_datatype = 0;
80 MCI_AMP_OPEN_PARMS AmpOpenParms;
81 MCI_GENERIC_PARMS GenericParms;
82 int iDeviceOrd = 0; // Default device to be used
83 int bOpenShared = 1; // Try opening it shared
84 int iBits = 16; // Default is 16 bits signed
85 int iFreq = 44100; // Default is 44KHz
86 int iChannels = 2; // Default is 2 channels (Stereo)
87 int iNumBufs = 2; // Number of audio buffers: 2
88 int iBufSize;
89 int iOpenMode;
90 int iSilence;
91 int rc;
92
93 // First thing is to try to open a given DART device!
94 SDL_memset(&AmpOpenParms, 0, sizeof(MCI_AMP_OPEN_PARMS));
95 // pszDeviceType should contain the device type in low word, and device ordinal in high word!
96 AmpOpenParms.pszDeviceType = (PSZ) (MCI_DEVTYPE_AUDIO_AMPMIX | (iDeviceOrd << 16));
97
98 iOpenMode = MCI_WAIT | MCI_OPEN_TYPE_ID;
99 if (bOpenShared) iOpenMode |= MCI_OPEN_SHAREABLE;
100
101 rc = mciSendCommand( 0, MCI_OPEN,
102 iOpenMode,
103 (PVOID) &AmpOpenParms, 0);
104 if (rc!=MCIERR_SUCCESS) // No audio available??
105 return (-1);
106 // Save the device ID we got from DART!
107 // We will use this in the next calls!
108 iDeviceOrd = AmpOpenParms.usDeviceID;
109
110 // Determine the audio parameters from the AudioSpec
111 if (spec->channels > 2)
112 spec->channels = 2; // !!! FIXME: more than stereo support in OS/2?
113
114 while ((!valid_datatype) && (test_format)) {
115 spec->format = test_format;
116 valid_datatype = 1;
117 switch (test_format) {
118 case AUDIO_U8:
119 // Unsigned 8 bit audio data
120 iSilence = 0x80;
121 iBits = 8;
122 break;
123
124 case AUDIO_S16LSB:
125 // Signed 16 bit audio data
126 iSilence = 0x00;
127 iBits = 16;
128 break;
129
130 default:
131 valid_datatype = 0;
132 test_format = SDL_NextAudioFormat();
133 break;
134 }
135 }
136
137 if (!valid_datatype) { // shouldn't happen, but just in case...
138 // Close DART, and exit with error code!
139 mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0);
140 SDL_SetError("Unsupported audio format");
141 return (-1);
142 }
143
144 iFreq = spec->freq;
145 iChannels = spec->channels;
146 /* Update the fragment size as size in bytes */
147 SDL_CalculateAudioSpec(spec);
148 iBufSize = spec->size;
149
150 // Now query this device if it supports the given freq/bits/channels!
151 SDL_memset(&(_this->hidden->MixSetupParms), 0, sizeof(MCI_MIXSETUP_PARMS));
152 _this->hidden->MixSetupParms.ulBitsPerSample = iBits;
153 _this->hidden->MixSetupParms.ulFormatTag = MCI_WAVE_FORMAT_PCM;
154 _this->hidden->MixSetupParms.ulSamplesPerSec = iFreq;
155 _this->hidden->MixSetupParms.ulChannels = iChannels;
156 _this->hidden->MixSetupParms.ulFormatMode = MCI_PLAY;
157 _this->hidden->MixSetupParms.ulDeviceType = MCI_DEVTYPE_WAVEFORM_AUDIO;
158 _this->hidden->MixSetupParms.pmixEvent = DARTEventFunc;
159 rc = mciSendCommand (iDeviceOrd, MCI_MIXSETUP,
160 MCI_WAIT | MCI_MIXSETUP_QUERYMODE,
161 &(_this->hidden->MixSetupParms), 0);
162 if (rc!=MCIERR_SUCCESS)
163 { // The device cannot handle this format!
164 // Close DART, and exit with error code!
165 mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0);
166 SDL_SetError("Audio device doesn't support requested audio format");
167 return(-1);
168 }
169 // The device can handle this format, so initialize!
170 rc = mciSendCommand(iDeviceOrd, MCI_MIXSETUP,
171 MCI_WAIT | MCI_MIXSETUP_INIT,
172 &(_this->hidden->MixSetupParms), 0);
173 if (rc!=MCIERR_SUCCESS)
174 { // The device could not be opened!
175 // Close DART, and exit with error code!
176 mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0);
177 SDL_SetError("Audio device could not be set up");
178 return(-1);
179 }
180 // Ok, the device is initialized.
181 // Now we should allocate buffers. For this, we need a place where
182 // the buffer descriptors will be:
183 _this->hidden->pMixBuffers = (MCI_MIX_BUFFER *) SDL_malloc(sizeof(MCI_MIX_BUFFER)*iNumBufs);
184 if (!(_this->hidden->pMixBuffers))
185 { // Not enough memory!
186 // Close DART, and exit with error code!
187 mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0);
188 SDL_SetError("Not enough memory for audio buffer descriptors");
189 return(-1);
190 }
191 // Now that we have the place for buffer list, we can ask DART for the
192 // buffers!
193 _this->hidden->BufferParms.ulNumBuffers = iNumBufs; // Number of buffers
194 _this->hidden->BufferParms.ulBufferSize = iBufSize; // each with this size
195 _this->hidden->BufferParms.pBufList = _this->hidden->pMixBuffers; // getting descriptorts into this list
196 // Allocate buffers!
197 rc = mciSendCommand(iDeviceOrd, MCI_BUFFER,
198 MCI_WAIT | MCI_ALLOCATE_MEMORY,
199 &(_this->hidden->BufferParms), 0);
200 if ((rc!=MCIERR_SUCCESS) || (iNumBufs != _this->hidden->BufferParms.ulNumBuffers) || (_this->hidden->BufferParms.ulBufferSize==0))
201 { // Could not allocate memory!
202 // Close DART, and exit with error code!
203 SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL;
204 mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0);
205 SDL_SetError("DART could not allocate buffers");
206 return(-1);
207 }
208 // Ok, we have all the buffers allocated, let's mark them!
209 {
210 int i;
211 for (i=0; i<iNumBufs; i++)
212 {
213 pMixBufferDesc pBufferDesc = (pMixBufferDesc) SDL_malloc(sizeof(tMixBufferDesc));;
214 // Check if this buffer was really allocated by DART
215 if ((!(_this->hidden->pMixBuffers[i].pBuffer)) || (!pBufferDesc))
216 { // Wrong buffer!
217 // Close DART, and exit with error code!
218 // Free buffer descriptions
219 { int j;
220 for (j=0; j<i; j++) SDL_free((void *)(_this->hidden->pMixBuffers[j].ulUserParm));
221 }
222 // and cleanup
223 mciSendCommand(iDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_DEALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0);
224 SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL;
225 mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0);
226 SDL_SetError("Error at internal buffer check");
227 return(-1);
228 }
229 pBufferDesc->iBufferUsage = BUFFER_EMPTY;
230 pBufferDesc->pSDLAudioDevice = _this;
231
232 _this->hidden->pMixBuffers[i].ulBufferLength = _this->hidden->BufferParms.ulBufferSize;
233 _this->hidden->pMixBuffers[i].ulUserParm = (ULONG) pBufferDesc; // User parameter: Description of buffer
234 _this->hidden->pMixBuffers[i].ulFlags = 0; // Some stuff should be flagged here for DART, like end of
235 // audio data, but as we will continously send
236 // audio data, there will be no end.:)
237 SDL_memset(_this->hidden->pMixBuffers[i].pBuffer, iSilence, iBufSize);
238 }
239 }
240 _this->hidden->iNextFreeBuffer = 0;
241 _this->hidden->iLastPlayedBuf = -1;
242 // Create event semaphore
243 if (DosCreateEventSem(NULL, &(_this->hidden->hevAudioBufferPlayed), 0, FALSE)!=NO_ERROR)
244 {
245 // Could not create event semaphore!
246 {
247 int i;
248 for (i=0; i<iNumBufs; i++) SDL_free((void *)(_this->hidden->pMixBuffers[i].ulUserParm));
249 }
250 mciSendCommand(iDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_DEALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0);
251 SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL;
252 mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0);
253 SDL_SetError("Could not create event semaphore");
254 return(-1);
255 }
256
257 // Store the new settings in global variables
258 _this->hidden->iCurrDeviceOrd = iDeviceOrd;
259 _this->hidden->iCurrFreq = iFreq;
260 _this->hidden->iCurrBits = iBits;
261 _this->hidden->iCurrChannels = iChannels;
262 _this->hidden->iCurrNumBufs = iNumBufs;
263 _this->hidden->iCurrBufSize = iBufSize;
264
265 return (0);
266}
267
268
269
270void DART_ThreadInit(_THIS)
271{
272 return;
273}
274
275/* This function waits until it is possible to write a full sound buffer */
276void DART_WaitAudio(_THIS)
277{
278 int i;
279 pMixBufferDesc pBufDesc;
280 ULONG ulPostCount;
281
282 DosResetEventSem(_this->hidden->hevAudioBufferPlayed, &ulPostCount);
283 // If there is already an empty buffer, then return now!
284 for (i=0; i<_this->hidden->iCurrNumBufs; i++)
285 {
286 pBufDesc = (pMixBufferDesc) _this->hidden->pMixBuffers[i].ulUserParm;
287 if (pBufDesc->iBufferUsage == BUFFER_EMPTY)
288 return;
289 }
290 // If there is no empty buffer, wait for one to be empty!
291 DosWaitEventSem(_this->hidden->hevAudioBufferPlayed, 1000); // Wait max 1 sec!!! Important!
292 return;
293}
294
295void DART_PlayAudio(_THIS)
296{
297 int iFreeBuf = _this->hidden->iNextFreeBuffer;
298 pMixBufferDesc pBufDesc;
299
300 pBufDesc = (pMixBufferDesc) _this->hidden->pMixBuffers[iFreeBuf].ulUserParm;
301 pBufDesc->iBufferUsage = BUFFER_USED;
302 // Send it to DART to be queued
303 _this->hidden->MixSetupParms.pmixWrite(_this->hidden->MixSetupParms.ulMixHandle,
304 &(_this->hidden->pMixBuffers[iFreeBuf]), 1);
305
306 _this->hidden->iLastPlayedBuf = iFreeBuf;
307 iFreeBuf = (iFreeBuf+1) % _this->hidden->iCurrNumBufs;
308 _this->hidden->iNextFreeBuffer = iFreeBuf;
309}
310
311Uint8 *DART_GetAudioBuf(_THIS)
312{
313 int iFreeBuf;
314 Uint8 *pResult;
315 pMixBufferDesc pBufDesc;
316
317 if (_this)
318 {
319 if (_this->hidden)
320 {
321 iFreeBuf = _this->hidden->iNextFreeBuffer;
322 pBufDesc = (pMixBufferDesc) _this->hidden->pMixBuffers[iFreeBuf].ulUserParm;
323
324 if (pBufDesc)
325 {
326 if (pBufDesc->iBufferUsage == BUFFER_EMPTY)
327 {
328 pResult = _this->hidden->pMixBuffers[iFreeBuf].pBuffer;
329 return pResult;
330 }
331 } else
332 printf("[DART_GetAudioBuf] : ERROR! pBufDesc = %p\n", pBufDesc);
333 } else
334 printf("[DART_GetAudioBuf] : ERROR! _this->hidden = %p\n", _this->hidden);
335 } else
336 printf("[DART_GetAudioBuf] : ERROR! _this = %p\n", _this);
337 return NULL;
338}
339
340void DART_WaitDone(_THIS)
341{
342 pMixBufferDesc pBufDesc;
343 ULONG ulPostCount;
344 APIRET rc;
345
346 pBufDesc = (pMixBufferDesc) _this->hidden->pMixBuffers[_this->hidden->iLastPlayedBuf].ulUserParm;
347 rc = NO_ERROR;
348 while ((pBufDesc->iBufferUsage != BUFFER_EMPTY) && (rc==NO_ERROR))
349 {
350 DosResetEventSem(_this->hidden->hevAudioBufferPlayed, &ulPostCount);
351 rc = DosWaitEventSem(_this->hidden->hevAudioBufferPlayed, 1000); // 1 sec timeout! Important!
352 }
353}
354
355void DART_CloseAudio(_THIS)
356{
357 MCI_GENERIC_PARMS GenericParms;
358 int rc;
359
360 // Stop DART playback
361 rc = mciSendCommand(_this->hidden->iCurrDeviceOrd, MCI_STOP, MCI_WAIT, &GenericParms, 0);
362 if (rc!=MCIERR_SUCCESS)
363 {
364#ifdef SFX_DEBUG_BUILD
365 printf("Could not stop DART playback!\n");
366 fflush(stdout);
367#endif
368 }
369
370 // Close event semaphore
371 DosCloseEventSem(_this->hidden->hevAudioBufferPlayed);
372
373 // Free memory of buffer descriptions
374 {
375 int i;
376 for (i=0; i<_this->hidden->iCurrNumBufs; i++) SDL_free((void *)(_this->hidden->pMixBuffers[i].ulUserParm));
377 }
378
379 // Deallocate buffers
380 rc = mciSendCommand(_this->hidden->iCurrDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_DEALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0);
381
382 // Free bufferlist
383 SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL;
384
385 // Close dart
386 rc = mciSendCommand(_this->hidden->iCurrDeviceOrd, MCI_CLOSE, MCI_WAIT, &(GenericParms), 0);
387}
388
389/* Audio driver bootstrap functions */
390
391int Audio_Available(void)
392{
393 return(1);
394}
395
396void Audio_DeleteDevice(SDL_AudioDevice *device)
397{
398 SDL_free(device->hidden);
399 SDL_free(device);
400}
401
402SDL_AudioDevice *Audio_CreateDevice(int devindex)
403{
404 SDL_AudioDevice *this;
405
406 /* Initialize all variables that we clean on shutdown */
407 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
408 if ( this )
409 {
410 SDL_memset(this, 0, (sizeof *this));
411 this->hidden = (struct SDL_PrivateAudioData *)
412 SDL_malloc((sizeof *this->hidden));
413 }
414 if ( (this == NULL) || (this->hidden == NULL) )
415 {
416 SDL_OutOfMemory();
417 if ( this )
418 SDL_free(this);
419 return(0);
420 }
421 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
422
423 /* Set the function pointers */
424 this->OpenAudio = DART_OpenAudio;
425 this->ThreadInit = DART_ThreadInit;
426 this->WaitAudio = DART_WaitAudio;
427 this->PlayAudio = DART_PlayAudio;
428 this->GetAudioBuf = DART_GetAudioBuf;
429 this->WaitDone = DART_WaitDone;
430 this->CloseAudio = DART_CloseAudio;
431
432 this->free = Audio_DeleteDevice;
433
434 return this;
435}
436
437AudioBootStrap DART_bootstrap = {
438 "dart", "OS/2 Direct Audio RouTines (DART)",
439 Audio_Available, Audio_CreateDevice
440};
441
diff --git a/apps/plugins/sdl/src/audio/dart/SDL_dart.h b/apps/plugins/sdl/src/audio/dart/SDL_dart.h
deleted file mode 100644
index 68c27bd9d3..0000000000
--- a/apps/plugins/sdl/src/audio/dart/SDL_dart.h
+++ /dev/null
@@ -1,63 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowaudio_h
25#define _SDL_lowaudio_h
26
27#define INCL_TYPES
28#define INCL_DOSSEMAPHORES
29#define INCL_DOSRESOURCES
30#define INCL_DOSMISC
31#define INCL_DOSERRORS
32
33#define INCL_OS2MM
34#define INCL_MMIOOS2
35#define INCL_MCIOS2
36#include <os2.h>
37#include <os2me.h> // DART stuff and MMIO stuff
38
39#include "../SDL_sysaudio.h"
40
41/* Hidden "this" pointer for the audio functions */
42#define _THIS SDL_AudioDevice *_this
43
44/* The DirectSound objects */
45struct SDL_PrivateAudioData
46{
47 int iCurrDeviceOrd;
48 int iCurrFreq;
49 int iCurrBits;
50 int iCurrChannels;
51 int iCurrNumBufs;
52 int iCurrBufSize;
53
54 int iLastPlayedBuf;
55 int iNextFreeBuffer;
56
57 MCI_BUFFER_PARMS BufferParms; // Sound buffer parameters
58 MCI_MIX_BUFFER *pMixBuffers; // Sound buffers
59 MCI_MIXSETUP_PARMS MixSetupParms; // Mixer setup parameters
60 HEV hevAudioBufferPlayed; // Event semaphore to indicate that an audio buffer has been played by DART
61};
62
63#endif /* _SDL_lowaudio_h */
diff --git a/apps/plugins/sdl/src/audio/dc/SDL_dcaudio.c b/apps/plugins/sdl/src/audio/dc/SDL_dcaudio.c
deleted file mode 100644
index 88daa8723a..0000000000
--- a/apps/plugins/sdl/src/audio/dc/SDL_dcaudio.c
+++ /dev/null
@@ -1,246 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22*/
23#include "SDL_config.h"
24
25/* Output dreamcast aica */
26
27#include "SDL_timer.h"
28#include "SDL_audio.h"
29#include "../SDL_audiomem.h"
30#include "../SDL_audio_c.h"
31#include "../SDL_audiodev_c.h"
32#include "SDL_dcaudio.h"
33
34#include "aica.h"
35#include <dc/spu.h>
36
37/* Audio driver functions */
38static int DCAUD_OpenAudio(_THIS, SDL_AudioSpec *spec);
39static void DCAUD_WaitAudio(_THIS);
40static void DCAUD_PlayAudio(_THIS);
41static Uint8 *DCAUD_GetAudioBuf(_THIS);
42static void DCAUD_CloseAudio(_THIS);
43
44/* Audio driver bootstrap functions */
45static int DCAUD_Available(void)
46{
47 return 1;
48}
49
50static void DCAUD_DeleteDevice(SDL_AudioDevice *device)
51{
52 SDL_free(device->hidden);
53 SDL_free(device);
54}
55
56static SDL_AudioDevice *DCAUD_CreateDevice(int devindex)
57{
58 SDL_AudioDevice *this;
59
60 /* Initialize all variables that we clean on shutdown */
61 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
62 if ( this ) {
63 SDL_memset(this, 0, (sizeof *this));
64 this->hidden = (struct SDL_PrivateAudioData *)
65 SDL_malloc((sizeof *this->hidden));
66 }
67 if ( (this == NULL) || (this->hidden == NULL) ) {
68 SDL_OutOfMemory();
69 if ( this ) {
70 SDL_free(this);
71 }
72 return(0);
73 }
74 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
75
76 /* Set the function pointers */
77 this->OpenAudio = DCAUD_OpenAudio;
78 this->WaitAudio = DCAUD_WaitAudio;
79 this->PlayAudio = DCAUD_PlayAudio;
80 this->GetAudioBuf = DCAUD_GetAudioBuf;
81 this->CloseAudio = DCAUD_CloseAudio;
82
83 this->free = DCAUD_DeleteDevice;
84
85 spu_init();
86
87 return this;
88}
89
90AudioBootStrap DCAUD_bootstrap = {
91 "dcaudio", "Dreamcast AICA audio",
92 DCAUD_Available, DCAUD_CreateDevice
93};
94
95/* This function waits until it is possible to write a full sound buffer */
96static void DCAUD_WaitAudio(_THIS)
97{
98 if (this->hidden->playing) {
99 /* wait */
100 while(aica_get_pos(0)/this->spec.samples == this->hidden->nextbuf) {
101 thd_pass();
102 }
103 }
104}
105
106#define SPU_RAM_BASE 0xa0800000
107
108static void spu_memload_stereo8(int leftpos,int rightpos,void *src0,size_t size)
109{
110 uint8 *src = src0;
111 uint32 *left = (uint32*)(leftpos +SPU_RAM_BASE);
112 uint32 *right = (uint32*)(rightpos+SPU_RAM_BASE);
113 size = (size+7)/8;
114 while(size--) {
115 unsigned lval,rval;
116 lval = *src++;
117 rval = *src++;
118 lval|= (*src++)<<8;
119 rval|= (*src++)<<8;
120 lval|= (*src++)<<16;
121 rval|= (*src++)<<16;
122 lval|= (*src++)<<24;
123 rval|= (*src++)<<24;
124 g2_write_32(left++,lval);
125 g2_write_32(right++,rval);
126 g2_fifo_wait();
127 }
128}
129
130static void spu_memload_stereo16(int leftpos,int rightpos,void *src0,size_t size)
131{
132 uint16 *src = src0;
133 uint32 *left = (uint32*)(leftpos +SPU_RAM_BASE);
134 uint32 *right = (uint32*)(rightpos+SPU_RAM_BASE);
135 size = (size+7)/8;
136 while(size--) {
137 unsigned lval,rval;
138 lval = *src++;
139 rval = *src++;
140 lval|= (*src++)<<16;
141 rval|= (*src++)<<16;
142 g2_write_32(left++,lval);
143 g2_write_32(right++,rval);
144 g2_fifo_wait();
145 }
146}
147
148static void DCAUD_PlayAudio(_THIS)
149{
150 SDL_AudioSpec *spec = &this->spec;
151 unsigned int offset;
152
153 if (this->hidden->playing) {
154 /* wait */
155 while(aica_get_pos(0)/spec->samples == this->hidden->nextbuf) {
156 thd_pass();
157 }
158 }
159
160 offset = this->hidden->nextbuf*spec->size;
161 this->hidden->nextbuf^=1;
162 /* Write the audio data, checking for EAGAIN on broken audio drivers */
163 if (spec->channels==1) {
164 spu_memload(this->hidden->leftpos+offset,this->hidden->mixbuf,this->hidden->mixlen);
165 } else {
166 offset/=2;
167 if ((this->spec.format&255)==8) {
168 spu_memload_stereo8(this->hidden->leftpos+offset,this->hidden->rightpos+offset,this->hidden->mixbuf,this->hidden->mixlen);
169 } else {
170 spu_memload_stereo16(this->hidden->leftpos+offset,this->hidden->rightpos+offset,this->hidden->mixbuf,this->hidden->mixlen);
171 }
172 }
173
174 if (!this->hidden->playing) {
175 int mode;
176 this->hidden->playing = 1;
177 mode = (spec->format==AUDIO_S8)?SM_8BIT:SM_16BIT;
178 if (spec->channels==1) {
179 aica_play(0,mode,this->hidden->leftpos,0,spec->samples*2,spec->freq,255,128,1);
180 } else {
181 aica_play(0,mode,this->hidden->leftpos ,0,spec->samples*2,spec->freq,255,0,1);
182 aica_play(1,mode,this->hidden->rightpos,0,spec->samples*2,spec->freq,255,255,1);
183 }
184 }
185}
186
187static Uint8 *DCAUD_GetAudioBuf(_THIS)
188{
189 return(this->hidden->mixbuf);
190}
191
192static void DCAUD_CloseAudio(_THIS)
193{
194 aica_stop(0);
195 if (this->spec.channels==2) aica_stop(1);
196 if ( this->hidden->mixbuf != NULL ) {
197 SDL_FreeAudioMem(this->hidden->mixbuf);
198 this->hidden->mixbuf = NULL;
199 }
200}
201
202static int DCAUD_OpenAudio(_THIS, SDL_AudioSpec *spec)
203{
204 Uint16 test_format = SDL_FirstAudioFormat(spec->format);
205 int valid_datatype = 0;
206 while ((!valid_datatype) && (test_format)) {
207 spec->format = test_format;
208 switch (test_format) {
209 /* only formats Dreamcast accepts... */
210 case AUDIO_S8:
211 case AUDIO_S16LSB:
212 valid_datatype = 1;
213 break;
214
215 default:
216 test_format = SDL_NextAudioFormat();
217 break;
218 }
219 }
220
221 if (!valid_datatype) { /* shouldn't happen, but just in case... */
222 SDL_SetError("Unsupported audio format");
223 return (-1);
224 }
225
226 if (spec->channels > 2)
227 spec->channels = 2; /* no more than stereo on the Dreamcast. */
228
229 /* Update the fragment size as size in bytes */
230 SDL_CalculateAudioSpec(spec);
231
232 /* Allocate mixing buffer */
233 this->hidden->mixlen = spec->size;
234 this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen);
235 if ( this->hidden->mixbuf == NULL ) {
236 return(-1);
237 }
238 SDL_memset(this->hidden->mixbuf, spec->silence, spec->size);
239 this->hidden->leftpos = 0x11000;
240 this->hidden->rightpos = 0x11000+spec->size;
241 this->hidden->playing = 0;
242 this->hidden->nextbuf = 0;
243
244 /* We're ready to rock and roll. :-) */
245 return(0);
246}
diff --git a/apps/plugins/sdl/src/audio/dc/SDL_dcaudio.h b/apps/plugins/sdl/src/audio/dc/SDL_dcaudio.h
deleted file mode 100644
index fba95b3eda..0000000000
--- a/apps/plugins/sdl/src/audio/dc/SDL_dcaudio.h
+++ /dev/null
@@ -1,41 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_dcaudio_h
25#define _SDL_dcaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the video functions */
30#define _THIS SDL_AudioDevice *this
31
32struct SDL_PrivateAudioData {
33 /* The file descriptor for the audio device */
34 Uint8 *mixbuf;
35 Uint32 mixlen;
36 int playing;
37 int leftpos,rightpos;
38 int nextbuf;
39};
40
41#endif /* _SDL_dcaudio_h */
diff --git a/apps/plugins/sdl/src/audio/dc/aica.c b/apps/plugins/sdl/src/audio/dc/aica.c
deleted file mode 100644
index b6a1c93644..0000000000
--- a/apps/plugins/sdl/src/audio/dc/aica.c
+++ /dev/null
@@ -1,271 +0,0 @@
1/* This file is part of the Dreamcast function library.
2 * Please see libdream.c for further details.
3 *
4 * (c)2000 Dan Potter
5 * modify BERO
6 */
7#include "aica.h"
8
9#include <arch/irq.h>
10#include <dc/spu.h>
11
12/* #define dc_snd_base ((volatile unsigned char *)0x00800000) */ /* arm side */
13#define dc_snd_base ((volatile unsigned char *)0xa0700000) /* dc side */
14
15/* Some convienence macros */
16#define SNDREGADDR(x) (0xa0700000 + (x))
17#define CHNREGADDR(ch,x) SNDREGADDR(0x80*(ch)+(x))
18
19
20#define SNDREG32(x) (*(volatile unsigned long *)SNDREGADDR(x))
21#define SNDREG8(x) (*(volatile unsigned char *)SNDREGADDR(x))
22#define CHNREG32(ch, x) (*(volatile unsigned long *)CHNREGADDR(ch,x))
23#define CHNREG8(ch, x) (*(volatile unsigned long *)CHNREGADDR(ch,x))
24
25#define G2_LOCK(OLD) \
26 do { \
27 if (!irq_inside_int()) \
28 OLD = irq_disable(); \
29 /* suspend any G2 DMA here... */ \
30 while((*(volatile unsigned int *)0xa05f688c) & 0x20) \
31 ; \
32 } while(0)
33
34#define G2_UNLOCK(OLD) \
35 do { \
36 /* resume any G2 DMA here... */ \
37 if (!irq_inside_int()) \
38 irq_restore(OLD); \
39 } while(0)
40
41
42void aica_init() {
43 int i, j, old = 0;
44
45 /* Initialize AICA channels */
46 G2_LOCK(old);
47 SNDREG32(0x2800) = 0x0000;
48
49 for (i=0; i<64; i++) {
50 for (j=0; j<0x80; j+=4) {
51 if ((j&31)==0) g2_fifo_wait();
52 CHNREG32(i, j) = 0;
53 }
54 g2_fifo_wait();
55 CHNREG32(i,0) = 0x8000;
56 CHNREG32(i,20) = 0x1f;
57 }
58
59 SNDREG32(0x2800) = 0x000f;
60 g2_fifo_wait();
61 G2_UNLOCK(old);
62}
63
64/* Translates a volume from linear form to logarithmic form (required by
65 the AICA chip */
66/* int logs[] = {
67
680, 40, 50, 58, 63, 68, 73, 77, 80, 83, 86, 89, 92, 94, 97, 99, 101, 103,
69105, 107, 109, 111, 112, 114, 116, 117, 119, 120, 122, 123, 125, 126, 127,
70129, 130, 131, 133, 134, 135, 136, 137, 139, 140, 141, 142, 143, 144, 145,
71146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 156, 157, 158, 159,
72160, 161, 162, 162, 163, 164, 165, 166, 166, 167, 168, 169, 170, 170, 171,
73172, 172, 173, 174, 175, 175, 176, 177, 177, 178, 179, 180, 180, 181, 182,
74182, 183, 183, 184, 185, 185, 186, 187, 187, 188, 188, 189, 190, 190, 191,
75191, 192, 193, 193, 194, 194, 195, 196, 196, 197, 197, 198, 198, 199, 199,
76200, 201, 201, 202, 202, 203, 203, 204, 204, 205, 205, 206, 206, 207, 207,
77208, 208, 209, 209, 210, 210, 211, 211, 212, 212, 213, 213, 214, 214, 215,
78215, 216, 216, 217, 217, 217, 218, 218, 219, 219, 220, 220, 221, 221, 222,
79222, 222, 223, 223, 224, 224, 225, 225, 225, 226, 226, 227, 227, 228, 228,
80228, 229, 229, 230, 230, 230, 231, 231, 232, 232, 232, 233, 233, 234, 234,
81234, 235, 235, 236, 236, 236, 237, 237, 238, 238, 238, 239, 239, 240, 240,
82240, 241, 241, 241, 242, 242, 243, 243, 243, 244, 244, 244, 245, 245, 245,
83246, 246, 247, 247, 247, 248, 248, 248, 249, 249, 249, 250, 250, 250, 251,
84251, 251, 252, 252, 252, 253, 253, 253, 254, 254, 254, 255
85
86}; */
87
88const static unsigned char logs[] = {
89 0, 15, 22, 27, 31, 35, 39, 42, 45, 47, 50, 52, 55, 57, 59, 61,
90 63, 65, 67, 69, 71, 73, 74, 76, 78, 79, 81, 82, 84, 85, 87, 88,
91 90, 91, 92, 94, 95, 96, 98, 99, 100, 102, 103, 104, 105, 106,
92 108, 109, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121,
93 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
94 135, 136, 137, 138, 138, 139, 140, 141, 142, 143, 144, 145, 146,
95 146, 147, 148, 149, 150, 151, 152, 152, 153, 154, 155, 156, 156,
96 157, 158, 159, 160, 160, 161, 162, 163, 164, 164, 165, 166, 167,
97 167, 168, 169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176,
98 177, 178, 178, 179, 180, 181, 181, 182, 183, 183, 184, 185, 185,
99 186, 187, 187, 188, 189, 189, 190, 191, 191, 192, 193, 193, 194,
100 195, 195, 196, 197, 197, 198, 199, 199, 200, 200, 201, 202, 202,
101 203, 204, 204, 205, 205, 206, 207, 207, 208, 209, 209, 210, 210,
102 211, 212, 212, 213, 213, 214, 215, 215, 216, 216, 217, 217, 218,
103 219, 219, 220, 220, 221, 221, 222, 223, 223, 224, 224, 225, 225,
104 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 232, 232, 233,
105 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 239, 239, 240,
106 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246,
107 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 254, 255
108};
109
110/* For the moment this is going to have to suffice, until we really
111 figure out what these mean. */
112#define AICA_PAN(x) ((x)==0x80?(0):((x)<0x80?(0x1f):(0x0f)))
113#define AICA_VOL(x) (0xff - logs[128 + (((x) & 0xff) / 2)])
114//#define AICA_VOL(x) (0xff - logs[x&255])
115
116static inline unsigned AICA_FREQ(unsigned freq) {
117 unsigned long freq_lo, freq_base = 5644800;
118 int freq_hi = 7;
119
120 /* Need to convert frequency to floating point format
121 (freq_hi is exponent, freq_lo is mantissa)
122 Formula is ferq = 44100*2^freq_hi*(1+freq_lo/1024) */
123 while (freq < freq_base && freq_hi > -8) {
124 freq_base >>= 1;
125 --freq_hi;
126 }
127 while (freq < freq_base && freq_hi > -8) {
128 freq_base >>= 1;
129 freq_hi--;
130 }
131 freq_lo = (freq<<10) / freq_base;
132 return (freq_hi << 11) | (freq_lo & 1023);
133}
134
135/* Sets up a sound channel completely. This is generally good if you want
136 a quick and dirty way to play notes. If you want a more comprehensive
137 set of routines (more like PC wavetable cards) see below.
138
139 ch is the channel to play on (0 - 63)
140 smpptr is the pointer to the sound data; if you're running off the
141 SH4, then this ought to be (ptr - 0xa0800000); otherwise it's just
142 ptr. Basically, it's an offset into sound ram.
143 mode is one of the mode constants (16 bit, 8 bit, ADPCM)
144 nsamp is the number of samples to play (not number of bytes!)
145 freq is the sampling rate of the sound
146 vol is the volume, 0 to 0xff (0xff is louder)
147 pan is a panning constant -- 0 is left, 128 is center, 255 is right.
148
149 This routine (and the similar ones) owe a lot to Marcus' sound example --
150 I hadn't gotten quite this far into dissecting the individual regs yet. */
151void aica_play(int ch,int mode,unsigned long smpptr,int loopst,int loopend,int freq,int vol,int pan,int loopflag) {
152/* int i;
153*/
154 int val;
155 int old = 0;
156
157 /* Stop the channel (if it's already playing) */
158 aica_stop(ch);
159 /* doesn't seem to be needed, but it's here just in case */
160/*
161 for (i=0; i<256; i++) {
162 asm("nop");
163 asm("nop");
164 asm("nop");
165 asm("nop");
166 }
167*/
168 G2_LOCK(old);
169 /* Envelope setup. The first of these is the loop point,
170 e.g., where the sample starts over when it loops. The second
171 is the loop end. This is the full length of the sample when
172 you are not looping, or the loop end point when you are (though
173 storing more than that is a waste of memory if you're not doing
174 volume enveloping). */
175 CHNREG32(ch, 8) = loopst & 0xffff;
176 CHNREG32(ch, 12) = loopend & 0xffff;
177
178 /* Write resulting values */
179 CHNREG32(ch, 24) = AICA_FREQ(freq);
180
181 /* Set volume, pan, and some other things that we don't know what
182 they do =) */
183 CHNREG32(ch, 36) = AICA_PAN(pan) | (0xf<<8);
184 /* Convert the incoming volume and pan into hardware values */
185 /* Vol starts at zero so we can ramp */
186 vol = AICA_VOL(vol);
187 CHNREG32(ch, 40) = 0x24 | (vol<<8);
188 /* Convert the incoming volume and pan into hardware values */
189 /* Vol starts at zero so we can ramp */
190
191 /* If we supported volume envelopes (which we don't yet) then
192 this value would set that up. The top 4 bits determine the
193 envelope speed. f is the fastest, 1 is the slowest, and 0
194 seems to be an invalid value and does weird things). The
195 default (below) sets it into normal mode (play and terminate/loop).
196 CHNREG32(ch, 16) = 0xf010;
197 */
198 CHNREG32(ch, 16) = 0x1f; /* No volume envelope */
199
200
201 /* Set sample format, buffer address, and looping control. If
202 0x0200 mask is set on reg 0, the sample loops infinitely. If
203 it's not set, the sample plays once and terminates. We'll
204 also set the bits to start playback here. */
205 CHNREG32(ch, 4) = smpptr & 0xffff;
206 val = 0xc000 | 0x0000 | (mode<<7) | (smpptr >> 16);
207 if (loopflag) val|=0x200;
208
209 CHNREG32(ch, 0) = val;
210
211 G2_UNLOCK(old);
212
213 /* Enable playback */
214 /* CHNREG32(ch, 0) |= 0xc000; */
215 g2_fifo_wait();
216
217#if 0
218 for (i=0xff; i>=vol; i--) {
219 if ((i&7)==0) g2_fifo_wait();
220 CHNREG32(ch, 40) = 0x24 | (i<<8);;
221 }
222
223 g2_fifo_wait();
224#endif
225}
226
227/* Stop the sound on a given channel */
228void aica_stop(int ch) {
229 g2_write_32(CHNREGADDR(ch, 0),(g2_read_32(CHNREGADDR(ch, 0)) & ~0x4000) | 0x8000);
230 g2_fifo_wait();
231}
232
233
234/* The rest of these routines can change the channel in mid-stride so you
235 can do things like vibrato and panning effects. */
236
237/* Set channel volume */
238void aica_vol(int ch,int vol) {
239// g2_write_8(CHNREGADDR(ch, 41),AICA_VOL(vol));
240 g2_write_32(CHNREGADDR(ch, 40),(g2_read_32(CHNREGADDR(ch, 40))&0xffff00ff)|(AICA_VOL(vol)<<8) );
241 g2_fifo_wait();
242}
243
244/* Set channel pan */
245void aica_pan(int ch,int pan) {
246// g2_write_8(CHNREGADDR(ch, 36),AICA_PAN(pan));
247 g2_write_32(CHNREGADDR(ch, 36),(g2_read_32(CHNREGADDR(ch, 36))&0xffffff00)|(AICA_PAN(pan)) );
248 g2_fifo_wait();
249}
250
251/* Set channel frequency */
252void aica_freq(int ch,int freq) {
253 g2_write_32(CHNREGADDR(ch, 24),AICA_FREQ(freq));
254 g2_fifo_wait();
255}
256
257/* Get channel position */
258int aica_get_pos(int ch) {
259#if 1
260 /* Observe channel ch */
261 g2_write_32(SNDREGADDR(0x280c),(g2_read_32(SNDREGADDR(0x280c))&0xffff00ff) | (ch<<8));
262 g2_fifo_wait();
263 /* Update position counters */
264 return g2_read_32(SNDREGADDR(0x2814)) & 0xffff;
265#else
266 /* Observe channel ch */
267 g2_write_8(SNDREGADDR(0x280d),ch);
268 /* Update position counters */
269 return g2_read_32(SNDREGADDR(0x2814)) & 0xffff;
270#endif
271}
diff --git a/apps/plugins/sdl/src/audio/dc/aica.h b/apps/plugins/sdl/src/audio/dc/aica.h
deleted file mode 100644
index 2721e42821..0000000000
--- a/apps/plugins/sdl/src/audio/dc/aica.h
+++ /dev/null
@@ -1,40 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _AICA_H_
25#define _AICA_H_
26
27#define AICA_MEM 0xa0800000
28
29#define SM_8BIT 1
30#define SM_16BIT 0
31#define SM_ADPCM 2
32
33void aica_play(int ch,int mode,unsigned long smpptr,int looptst,int loopend,int freq,int vol,int pan,int loopflag);
34void aica_stop(int ch);
35void aica_vol(int ch,int vol);
36void aica_pan(int ch,int pan);
37void aica_freq(int ch,int freq);
38int aica_get_pos(int ch);
39
40#endif
diff --git a/apps/plugins/sdl/src/audio/disk/SDL_diskaudio.c b/apps/plugins/sdl/src/audio/disk/SDL_diskaudio.c
deleted file mode 100644
index c45d3f8c05..0000000000
--- a/apps/plugins/sdl/src/audio/disk/SDL_diskaudio.c
+++ /dev/null
@@ -1,186 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 This file written by Ryan C. Gordon (icculus@icculus.org)
23*/
24#include "SDL_config.h"
25
26/* Output raw audio data to a file. */
27
28#if HAVE_STDIO_H
29#include <stdio.h>
30#endif
31
32#include "SDL_rwops.h"
33#include "SDL_timer.h"
34#include "SDL_audio.h"
35#include "../SDL_audiomem.h"
36#include "../SDL_audio_c.h"
37#include "../SDL_audiodev_c.h"
38#include "SDL_diskaudio.h"
39
40/* The tag name used by DISK audio */
41#define DISKAUD_DRIVER_NAME "disk"
42
43/* environment variables and defaults. */
44#define DISKENVR_OUTFILE "SDL_DISKAUDIOFILE"
45#define DISKDEFAULT_OUTFILE "/sdlaudio.raw"
46#define DISKENVR_WRITEDELAY "SDL_DISKAUDIODELAY"
47#define DISKDEFAULT_WRITEDELAY 150
48
49/* Audio driver functions */
50static int DISKAUD_OpenAudio(_THIS, SDL_AudioSpec *spec);
51static void DISKAUD_WaitAudio(_THIS);
52static void DISKAUD_PlayAudio(_THIS);
53static Uint8 *DISKAUD_GetAudioBuf(_THIS);
54static void DISKAUD_CloseAudio(_THIS);
55
56static const char *DISKAUD_GetOutputFilename(void)
57{
58 const char *envr = SDL_getenv(DISKENVR_OUTFILE);
59 return((envr != NULL) ? envr : DISKDEFAULT_OUTFILE);
60}
61
62/* Audio driver bootstrap functions */
63static int DISKAUD_Available(void)
64{
65 //const char *envr = SDL_getenv("SDL_AUDIODRIVER");
66// if (envr && (SDL_strcmp(envr, DISKAUD_DRIVER_NAME) == 0)) {
67 return(1);
68// }
69// return(0);
70}
71
72static void DISKAUD_DeleteDevice(SDL_AudioDevice *device)
73{
74 SDL_free(device->hidden);
75 SDL_free(device);
76}
77
78static SDL_AudioDevice *DISKAUD_CreateDevice(int devindex)
79{
80 SDL_AudioDevice *this;
81 const char *envr;
82
83 /* Initialize all variables that we clean on shutdown */
84 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
85 if ( this ) {
86 SDL_memset(this, 0, (sizeof *this));
87 this->hidden = (struct SDL_PrivateAudioData *)
88 SDL_malloc((sizeof *this->hidden));
89 }
90 if ( (this == NULL) || (this->hidden == NULL) ) {
91 SDL_OutOfMemory();
92 if ( this ) {
93 SDL_free(this);
94 }
95 return(0);
96 }
97 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
98
99 envr = SDL_getenv(DISKENVR_WRITEDELAY);
100 this->hidden->write_delay = (envr) ? SDL_atoi(envr) : DISKDEFAULT_WRITEDELAY;
101
102 /* Set the function pointers */
103 this->OpenAudio = DISKAUD_OpenAudio;
104 this->WaitAudio = DISKAUD_WaitAudio;
105 this->PlayAudio = DISKAUD_PlayAudio;
106 this->GetAudioBuf = DISKAUD_GetAudioBuf;
107 this->CloseAudio = DISKAUD_CloseAudio;
108
109 this->free = DISKAUD_DeleteDevice;
110
111 return this;
112}
113
114AudioBootStrap DISKAUD_bootstrap = {
115 DISKAUD_DRIVER_NAME, "direct-to-disk audio",
116 DISKAUD_Available, DISKAUD_CreateDevice
117};
118
119/* This function waits until it is possible to write a full sound buffer */
120static void DISKAUD_WaitAudio(_THIS)
121{
122 SDL_Delay(this->hidden->write_delay);
123}
124
125static void DISKAUD_PlayAudio(_THIS)
126{
127 int written;
128
129 /* Write the audio data */
130 written = SDL_RWwrite(this->hidden->output,
131 this->hidden->mixbuf, 1,
132 this->hidden->mixlen);
133
134 /* If we couldn't write, assume fatal error for now */
135 if ( (Uint32)written != this->hidden->mixlen ) {
136 this->enabled = 0;
137 }
138#ifdef DEBUG_AUDIO
139 fprintf(stderr, "Wrote %d bytes of audio data\n", written);
140#endif
141}
142
143static Uint8 *DISKAUD_GetAudioBuf(_THIS)
144{
145 return(this->hidden->mixbuf);
146}
147
148static void DISKAUD_CloseAudio(_THIS)
149{
150 if ( this->hidden->mixbuf != NULL ) {
151 SDL_FreeAudioMem(this->hidden->mixbuf);
152 this->hidden->mixbuf = NULL;
153 }
154 if ( this->hidden->output != NULL ) {
155 SDL_RWclose(this->hidden->output);
156 this->hidden->output = NULL;
157 }
158}
159
160static int DISKAUD_OpenAudio(_THIS, SDL_AudioSpec *spec)
161{
162 const char *fname = DISKAUD_GetOutputFilename();
163
164 /* Open the audio device */
165 this->hidden->output = SDL_RWFromFile(fname, "wb");
166 if ( this->hidden->output == NULL ) {
167 return(-1);
168 }
169
170#if HAVE_STDIO_H
171 fprintf(stderr, "WARNING: You are using the SDL disk writer"
172 " audio driver!\n Writing to file [%s].\n", fname);
173#endif
174
175 /* Allocate mixing buffer */
176 this->hidden->mixlen = spec->size;
177 this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen);
178 if ( this->hidden->mixbuf == NULL ) {
179 return(-1);
180 }
181 SDL_memset(this->hidden->mixbuf, spec->silence, spec->size);
182
183 /* We're ready to rock and roll. :-) */
184 return(0);
185}
186
diff --git a/apps/plugins/sdl/src/audio/disk/SDL_diskaudio.h b/apps/plugins/sdl/src/audio/disk/SDL_diskaudio.h
deleted file mode 100644
index 24d7c9e34d..0000000000
--- a/apps/plugins/sdl/src/audio/disk/SDL_diskaudio.h
+++ /dev/null
@@ -1,41 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_diskaudio_h
25#define _SDL_diskaudio_h
26
27#include "SDL_rwops.h"
28#include "../SDL_sysaudio.h"
29
30/* Hidden "this" pointer for the video functions */
31#define _THIS SDL_AudioDevice *this
32
33struct SDL_PrivateAudioData {
34 /* The file descriptor for the audio device */
35 SDL_RWops *output;
36 Uint8 *mixbuf;
37 Uint32 mixlen;
38 Uint32 write_delay;
39};
40
41#endif /* _SDL_diskaudio_h */
diff --git a/apps/plugins/sdl/src/audio/dma/SDL_dmaaudio.c b/apps/plugins/sdl/src/audio/dma/SDL_dmaaudio.c
deleted file mode 100644
index 39f81d90ce..0000000000
--- a/apps/plugins/sdl/src/audio/dma/SDL_dmaaudio.c
+++ /dev/null
@@ -1,455 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer */
25
26#include <stdio.h>
27#include <string.h> /* For strerror() */
28#include <errno.h>
29#include <unistd.h>
30#include <fcntl.h>
31#include <signal.h>
32#include <sys/types.h>
33#include <sys/time.h>
34#include <sys/ioctl.h>
35#include <sys/stat.h>
36#include <sys/mman.h>
37
38#if SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H
39/* This is installed on some systems */
40#include <soundcard.h>
41#else
42/* This is recommended by OSS */
43#include <sys/soundcard.h>
44#endif
45
46#ifndef MAP_FAILED
47#define MAP_FAILED ((Uint8 *)-1)
48#endif
49
50#include "SDL_timer.h"
51#include "SDL_audio.h"
52#include "../SDL_audio_c.h"
53#include "../SDL_audiodev_c.h"
54#include "SDL_dmaaudio.h"
55
56/* The tag name used by DMA audio */
57#define DMA_DRIVER_NAME "dma"
58
59/* Open the audio device for playback, and don't block if busy */
60#define OPEN_FLAGS (O_RDWR|O_NONBLOCK)
61
62/* Audio driver functions */
63static int DMA_OpenAudio(_THIS, SDL_AudioSpec *spec);
64static void DMA_WaitAudio(_THIS);
65static void DMA_PlayAudio(_THIS);
66static Uint8 *DMA_GetAudioBuf(_THIS);
67static void DMA_CloseAudio(_THIS);
68
69/* Audio driver bootstrap functions */
70
71static int Audio_Available(void)
72{
73 int available;
74 int fd;
75
76 available = 0;
77
78 fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0);
79 if ( fd >= 0 ) {
80 int caps;
81 struct audio_buf_info info;
82
83 if ( (ioctl(fd, SNDCTL_DSP_GETCAPS, &caps) == 0) &&
84 (caps & DSP_CAP_TRIGGER) && (caps & DSP_CAP_MMAP) &&
85 (ioctl(fd, SNDCTL_DSP_GETOSPACE, &info) == 0) ) {
86 available = 1;
87 }
88 close(fd);
89 }
90 return(available);
91}
92
93static void Audio_DeleteDevice(SDL_AudioDevice *device)
94{
95 SDL_free(device->hidden);
96 SDL_free(device);
97}
98
99static SDL_AudioDevice *Audio_CreateDevice(int devindex)
100{
101 SDL_AudioDevice *this;
102
103 /* Initialize all variables that we clean on shutdown */
104 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
105 if ( this ) {
106 SDL_memset(this, 0, (sizeof *this));
107 this->hidden = (struct SDL_PrivateAudioData *)
108 SDL_malloc((sizeof *this->hidden));
109 }
110 if ( (this == NULL) || (this->hidden == NULL) ) {
111 SDL_OutOfMemory();
112 if ( this ) {
113 SDL_free(this);
114 }
115 return(0);
116 }
117 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
118 audio_fd = -1;
119
120 /* Set the function pointers */
121 this->OpenAudio = DMA_OpenAudio;
122 this->WaitAudio = DMA_WaitAudio;
123 this->PlayAudio = DMA_PlayAudio;
124 this->GetAudioBuf = DMA_GetAudioBuf;
125 this->CloseAudio = DMA_CloseAudio;
126
127 this->free = Audio_DeleteDevice;
128
129 return this;
130}
131
132AudioBootStrap DMA_bootstrap = {
133 DMA_DRIVER_NAME, "OSS /dev/dsp DMA audio",
134 Audio_Available, Audio_CreateDevice
135};
136
137/* This function waits until it is possible to write a full sound buffer */
138static void DMA_WaitAudio(_THIS)
139{
140 fd_set fdset;
141
142 /* Check to see if the thread-parent process is still alive */
143 { static int cnt = 0;
144 /* Note that this only works with thread implementations
145 that use a different process id for each thread.
146 */
147 if (parent && (((++cnt)%10) == 0)) { /* Check every 10 loops */
148 if ( kill(parent, 0) < 0 ) {
149 this->enabled = 0;
150 }
151 }
152 }
153
154 /* See if we need to use timed audio synchronization */
155 if ( frame_ticks ) {
156 /* Use timer for general audio synchronization */
157 Sint32 ticks;
158
159 ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS;
160 if ( ticks > 0 ) {
161 SDL_Delay(ticks);
162 }
163 } else {
164 /* Use select() for audio synchronization */
165 struct timeval timeout;
166 FD_ZERO(&fdset);
167 FD_SET(audio_fd, &fdset);
168 timeout.tv_sec = 10;
169 timeout.tv_usec = 0;
170#ifdef DEBUG_AUDIO
171 fprintf(stderr, "Waiting for audio to get ready\n");
172#endif
173 if ( select(audio_fd+1, NULL, &fdset, NULL, &timeout) <= 0 ) {
174 const char *message =
175#ifdef AUDIO_OSPACE_HACK
176 "Audio timeout - buggy audio driver? (trying ospace)";
177#else
178 "Audio timeout - buggy audio driver? (disabled)";
179#endif
180 /* In general we should never print to the screen,
181 but in this case we have no other way of letting
182 the user know what happened.
183 */
184 fprintf(stderr, "SDL: %s\n", message);
185#ifdef AUDIO_OSPACE_HACK
186 /* We may be able to use GET_OSPACE trick */
187 frame_ticks = (float)(this->spec->samples*1000) /
188 this->spec->freq;
189 next_frame = SDL_GetTicks()+frame_ticks;
190#else
191 this->enabled = 0;
192 /* Don't try to close - may hang */
193 audio_fd = -1;
194#ifdef DEBUG_AUDIO
195 fprintf(stderr, "Done disabling audio\n");
196#endif
197#endif /* AUDIO_OSPACE_HACK */
198 }
199#ifdef DEBUG_AUDIO
200 fprintf(stderr, "Ready!\n");
201#endif
202 }
203}
204
205static void DMA_PlayAudio(_THIS)
206{
207 /* If timer synchronization is enabled, set the next write frame */
208 if ( frame_ticks ) {
209 next_frame += frame_ticks;
210 }
211 return;
212}
213
214static Uint8 *DMA_GetAudioBuf(_THIS)
215{
216 count_info info;
217 int playing;
218 int filling;
219
220 /* Get number of blocks, looping if we're not using select() */
221 do {
222 if ( ioctl(audio_fd, SNDCTL_DSP_GETOPTR, &info) < 0 ) {
223 /* Uh oh... */
224 this->enabled = 0;
225 return(NULL);
226 }
227 } while ( frame_ticks && (info.blocks < 1) );
228#ifdef DEBUG_AUDIO
229 if ( info.blocks > 1 ) {
230 printf("Warning: audio underflow (%d frags)\n", info.blocks-1);
231 }
232#endif
233 playing = info.ptr / this->spec.size;
234 filling = (playing + 1)%num_buffers;
235 return (dma_buf + (filling * this->spec.size));
236}
237
238static void DMA_CloseAudio(_THIS)
239{
240 if ( dma_buf != NULL ) {
241 munmap(dma_buf, dma_len);
242 dma_buf = NULL;
243 }
244 if ( audio_fd >= 0 ) {
245 close(audio_fd);
246 audio_fd = -1;
247 }
248}
249
250static int DMA_ReopenAudio(_THIS, const char *audiodev, int format, int stereo,
251 SDL_AudioSpec *spec)
252{
253 int frag_spec;
254 int value;
255
256 /* Close and then reopen the audio device */
257 close(audio_fd);
258 audio_fd = open(audiodev, O_RDWR, 0);
259 if ( audio_fd < 0 ) {
260 SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
261 return(-1);
262 }
263
264 /* Calculate the final parameters for this audio specification */
265 SDL_CalculateAudioSpec(spec);
266
267 /* Determine the power of two of the fragment size */
268 for ( frag_spec = 0; (0x01<<frag_spec) < spec->size; ++frag_spec );
269 if ( (0x01<<frag_spec) != spec->size ) {
270 SDL_SetError("Fragment size must be a power of two");
271 return(-1);
272 }
273
274 /* Set the audio buffering parameters */
275 if ( ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0 ) {
276 SDL_SetError("Couldn't set audio fragment spec");
277 return(-1);
278 }
279
280 /* Set the audio format */
281 value = format;
282 if ( (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) ||
283 (value != format) ) {
284 SDL_SetError("Couldn't set audio format");
285 return(-1);
286 }
287
288 /* Set mono or stereo audio */
289 value = (spec->channels > 1);
290 if ( (ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo) < 0) ||
291 (value != stereo) ) {
292 SDL_SetError("Couldn't set audio channels");
293 return(-1);
294 }
295
296 /* Set the DSP frequency */
297 value = spec->freq;
298 if ( ioctl(audio_fd, SNDCTL_DSP_SPEED, &value) < 0 ) {
299 SDL_SetError("Couldn't set audio frequency");
300 return(-1);
301 }
302 spec->freq = value;
303
304 /* We successfully re-opened the audio */
305 return(0);
306}
307
308static int DMA_OpenAudio(_THIS, SDL_AudioSpec *spec)
309{
310 char audiodev[1024];
311 int format;
312 int stereo;
313 int value;
314 Uint16 test_format;
315 struct audio_buf_info info;
316
317 /* Reset the timer synchronization flag */
318 frame_ticks = 0.0;
319
320 /* Open the audio device */
321 audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0);
322 if ( audio_fd < 0 ) {
323 SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
324 return(-1);
325 }
326 dma_buf = NULL;
327 ioctl(audio_fd, SNDCTL_DSP_RESET, 0);
328
329 /* Get a list of supported hardware formats */
330 if ( ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0 ) {
331 SDL_SetError("Couldn't get audio format list");
332 return(-1);
333 }
334
335 /* Try for a closest match on audio format */
336 format = 0;
337 for ( test_format = SDL_FirstAudioFormat(spec->format);
338 ! format && test_format; ) {
339#ifdef DEBUG_AUDIO
340 fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
341#endif
342 switch ( test_format ) {
343 case AUDIO_U8:
344 if ( value & AFMT_U8 ) {
345 format = AFMT_U8;
346 }
347 break;
348 case AUDIO_S8:
349 if ( value & AFMT_S8 ) {
350 format = AFMT_S8;
351 }
352 break;
353 case AUDIO_S16LSB:
354 if ( value & AFMT_S16_LE ) {
355 format = AFMT_S16_LE;
356 }
357 break;
358 case AUDIO_S16MSB:
359 if ( value & AFMT_S16_BE ) {
360 format = AFMT_S16_BE;
361 }
362 break;
363 case AUDIO_U16LSB:
364 if ( value & AFMT_U16_LE ) {
365 format = AFMT_U16_LE;
366 }
367 break;
368 case AUDIO_U16MSB:
369 if ( value & AFMT_U16_BE ) {
370 format = AFMT_U16_BE;
371 }
372 break;
373 default:
374 format = 0;
375 break;
376 }
377 if ( ! format ) {
378 test_format = SDL_NextAudioFormat();
379 }
380 }
381 if ( format == 0 ) {
382 SDL_SetError("Couldn't find any hardware audio formats");
383 return(-1);
384 }
385 spec->format = test_format;
386
387 /* Set the audio format */
388 value = format;
389 if ( (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) ||
390 (value != format) ) {
391 SDL_SetError("Couldn't set audio format");
392 return(-1);
393 }
394
395 /* Set mono or stereo audio (currently only two channels supported) */
396 stereo = (spec->channels > 1);
397 ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo);
398 if ( stereo ) {
399 spec->channels = 2;
400 } else {
401 spec->channels = 1;
402 }
403
404 /* Because some drivers don't allow setting the buffer size
405 after setting the format, we must re-open the audio device
406 once we know what format and channels are supported
407 */
408 if ( DMA_ReopenAudio(this, audiodev, format, stereo, spec) < 0 ) {
409 /* Error is set by DMA_ReopenAudio() */
410 return(-1);
411 }
412
413 /* Memory map the audio buffer */
414 if ( ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info) < 0 ) {
415 SDL_SetError("Couldn't get OSPACE parameters");
416 return(-1);
417 }
418 spec->size = info.fragsize;
419 spec->samples = spec->size / ((spec->format & 0xFF) / 8);
420 spec->samples /= spec->channels;
421 num_buffers = info.fragstotal;
422 dma_len = num_buffers*spec->size;
423 dma_buf = (Uint8 *)mmap(NULL, dma_len, PROT_WRITE, MAP_SHARED,
424 audio_fd, 0);
425 if ( dma_buf == MAP_FAILED ) {
426 SDL_SetError("DMA memory map failed");
427 dma_buf = NULL;
428 return(-1);
429 }
430 SDL_memset(dma_buf, spec->silence, dma_len);
431
432 /* Check to see if we need to use select() workaround */
433 { char *workaround;
434 workaround = SDL_getenv("SDL_DSP_NOSELECT");
435 if ( workaround ) {
436 frame_ticks = (float)(spec->samples*1000)/spec->freq;
437 next_frame = SDL_GetTicks()+frame_ticks;
438 }
439 }
440
441 /* Trigger audio playback */
442 value = 0;
443 ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value);
444 value = PCM_ENABLE_OUTPUT;
445 if ( ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value) < 0 ) {
446 SDL_SetError("Couldn't trigger audio output");
447 return(-1);
448 }
449
450 /* Get the parent process id (we're the parent of the audio thread) */
451 parent = getpid();
452
453 /* We're ready to rock and roll. :-) */
454 return(0);
455}
diff --git a/apps/plugins/sdl/src/audio/dma/SDL_dmaaudio.h b/apps/plugins/sdl/src/audio/dma/SDL_dmaaudio.h
deleted file mode 100644
index 9a45f732a1..0000000000
--- a/apps/plugins/sdl/src/audio/dma/SDL_dmaaudio.h
+++ /dev/null
@@ -1,59 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_dspaudio_h
25#define _SDL_dspaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the video functions */
30#define _THIS SDL_AudioDevice *this
31
32struct SDL_PrivateAudioData {
33 /* The file descriptor for the audio device */
34 int audio_fd;
35
36 /* The parent process id, to detect when application quits */
37 pid_t parent;
38
39 /* Raw mixing buffer */
40 Uint8 *dma_buf;
41 int dma_len;
42 int num_buffers;
43
44 /* Support for audio timing using a timer, in addition to select() */
45 float frame_ticks;
46 float next_frame;
47};
48#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
49
50/* Old variable names */
51#define audio_fd (this->hidden->audio_fd)
52#define parent (this->hidden->parent)
53#define dma_buf (this->hidden->dma_buf)
54#define dma_len (this->hidden->dma_len)
55#define num_buffers (this->hidden->num_buffers)
56#define frame_ticks (this->hidden->frame_ticks)
57#define next_frame (this->hidden->next_frame)
58
59#endif /* _SDL_dspaudio_h */
diff --git a/apps/plugins/sdl/src/audio/dmedia/SDL_irixaudio.c b/apps/plugins/sdl/src/audio/dmedia/SDL_irixaudio.c
deleted file mode 100644
index 1dcd2421ec..0000000000
--- a/apps/plugins/sdl/src/audio/dmedia/SDL_irixaudio.c
+++ /dev/null
@@ -1,242 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer (For IRIX 6.5 and higher) */
25/* patch for IRIX 5 by Georg Schwarz 18/07/2004 */
26
27#include "SDL_timer.h"
28#include "SDL_audio.h"
29#include "../SDL_audiomem.h"
30#include "../SDL_audio_c.h"
31#include "SDL_irixaudio.h"
32
33
34#ifndef AL_RESOURCE /* as a test whether we use the old IRIX audio libraries */
35#define OLD_IRIX_AUDIO
36#define alClosePort(x) ALcloseport(x)
37#define alFreeConfig(x) ALfreeconfig(x)
38#define alGetFillable(x) ALgetfillable(x)
39#define alNewConfig() ALnewconfig()
40#define alOpenPort(x,y,z) ALopenport(x,y,z)
41#define alSetChannels(x,y) ALsetchannels(x,y)
42#define alSetQueueSize(x,y) ALsetqueuesize(x,y)
43#define alSetSampFmt(x,y) ALsetsampfmt(x,y)
44#define alSetWidth(x,y) ALsetwidth(x,y)
45#endif
46
47/* Audio driver functions */
48static int AL_OpenAudio(_THIS, SDL_AudioSpec *spec);
49static void AL_WaitAudio(_THIS);
50static void AL_PlayAudio(_THIS);
51static Uint8 *AL_GetAudioBuf(_THIS);
52static void AL_CloseAudio(_THIS);
53
54/* Audio driver bootstrap functions */
55
56static int Audio_Available(void)
57{
58 return 1;
59}
60
61static void Audio_DeleteDevice(SDL_AudioDevice *device)
62{
63 SDL_free(device->hidden);
64 SDL_free(device);
65}
66
67static SDL_AudioDevice *Audio_CreateDevice(int devindex)
68{
69 SDL_AudioDevice *this;
70
71 /* Initialize all variables that we clean on shutdown */
72 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
73 if ( this ) {
74 SDL_memset(this, 0, (sizeof *this));
75 this->hidden = (struct SDL_PrivateAudioData *)
76 SDL_malloc((sizeof *this->hidden));
77 }
78 if ( (this == NULL) || (this->hidden == NULL) ) {
79 SDL_OutOfMemory();
80 if ( this ) {
81 SDL_free(this);
82 }
83 return(0);
84 }
85 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
86
87 /* Set the function pointers */
88 this->OpenAudio = AL_OpenAudio;
89 this->WaitAudio = AL_WaitAudio;
90 this->PlayAudio = AL_PlayAudio;
91 this->GetAudioBuf = AL_GetAudioBuf;
92 this->CloseAudio = AL_CloseAudio;
93
94 this->free = Audio_DeleteDevice;
95
96 return this;
97}
98
99AudioBootStrap DMEDIA_bootstrap = {
100 "AL", "IRIX DMedia audio",
101 Audio_Available, Audio_CreateDevice
102};
103
104
105void static AL_WaitAudio(_THIS)
106{
107 Sint32 timeleft;
108
109 timeleft = this->spec.samples - alGetFillable(audio_port);
110 if ( timeleft > 0 ) {
111 timeleft /= (this->spec.freq/1000);
112 SDL_Delay((Uint32)timeleft);
113 }
114}
115
116static void AL_PlayAudio(_THIS)
117{
118 /* Write the audio data out */
119 if ( alWriteFrames(audio_port, mixbuf, this->spec.samples) < 0 ) {
120 /* Assume fatal error, for now */
121 this->enabled = 0;
122 }
123}
124
125static Uint8 *AL_GetAudioBuf(_THIS)
126{
127 return(mixbuf);
128}
129
130static void AL_CloseAudio(_THIS)
131{
132 if ( mixbuf != NULL ) {
133 SDL_FreeAudioMem(mixbuf);
134 mixbuf = NULL;
135 }
136 if ( audio_port != NULL ) {
137 alClosePort(audio_port);
138 audio_port = NULL;
139 }
140}
141
142static int AL_OpenAudio(_THIS, SDL_AudioSpec * spec)
143{
144 Uint16 test_format = SDL_FirstAudioFormat(spec->format);
145 long width = 0;
146 long fmt = 0;
147 int valid = 0;
148
149#ifdef OLD_IRIX_AUDIO
150 {
151 long audio_param[2];
152 audio_param[0] = AL_OUTPUT_RATE;
153 audio_param[1] = spec->freq;
154 valid = (ALsetparams(AL_DEFAULT_DEVICE, audio_param, 2) < 0);
155 }
156#else
157 {
158 ALpv audio_param;
159 audio_param.param = AL_RATE;
160 audio_param.value.i = spec->freq;
161 valid = (alSetParams(AL_DEFAULT_OUTPUT, &audio_param, 1) < 0);
162 }
163#endif
164
165 while ((!valid) && (test_format)) {
166 valid = 1;
167 spec->format = test_format;
168
169 switch (test_format) {
170 case AUDIO_S8:
171 width = AL_SAMPLE_8;
172 fmt = AL_SAMPFMT_TWOSCOMP;
173 break;
174
175 case AUDIO_S16SYS:
176 width = AL_SAMPLE_16;
177 fmt = AL_SAMPFMT_TWOSCOMP;
178 break;
179
180 default:
181 valid = 0;
182 test_format = SDL_NextAudioFormat();
183 break;
184 }
185
186 if (valid) {
187 ALconfig audio_config = alNewConfig();
188 valid = 0;
189 if (audio_config) {
190 if (alSetChannels(audio_config, spec->channels) < 0) {
191 if (spec->channels > 2) { /* can't handle > stereo? */
192 spec->channels = 2; /* try again below. */
193 }
194 }
195
196 if ((alSetSampFmt(audio_config, fmt) >= 0) &&
197 ((!width) || (alSetWidth(audio_config, width) >= 0)) &&
198 (alSetQueueSize(audio_config, spec->samples * 2) >= 0) &&
199 (alSetChannels(audio_config, spec->channels) >= 0)) {
200
201 audio_port = alOpenPort("SDL audio", "w", audio_config);
202 if (audio_port == NULL) {
203 /* docs say AL_BAD_CHANNELS happens here, too. */
204 int err = oserror();
205 if (err == AL_BAD_CHANNELS) {
206 spec->channels = 2;
207 alSetChannels(audio_config, spec->channels);
208 audio_port = alOpenPort("SDL audio", "w",
209 audio_config);
210 }
211 }
212
213 if (audio_port != NULL) {
214 valid = 1;
215 }
216 }
217
218 alFreeConfig(audio_config);
219 }
220 }
221 }
222
223 if (!valid) {
224 SDL_SetError("Unsupported audio format");
225 return (-1);
226 }
227
228 /* Update the fragment size as size in bytes */
229 SDL_CalculateAudioSpec(spec);
230
231 /* Allocate mixing buffer */
232 mixbuf = (Uint8 *) SDL_AllocAudioMem(spec->size);
233 if (mixbuf == NULL) {
234 SDL_OutOfMemory();
235 return (-1);
236 }
237 SDL_memset(mixbuf, spec->silence, spec->size);
238
239 /* We're ready to rock and roll. :-) */
240 return (0);
241}
242
diff --git a/apps/plugins/sdl/src/audio/dmedia/SDL_irixaudio.h b/apps/plugins/sdl/src/audio/dmedia/SDL_irixaudio.h
deleted file mode 100644
index c04f497cea..0000000000
--- a/apps/plugins/sdl/src/audio/dmedia/SDL_irixaudio.h
+++ /dev/null
@@ -1,45 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowaudio_h
25#define _SDL_lowaudio_h
26
27#include <dmedia/audio.h>
28
29#include "../SDL_sysaudio.h"
30
31/* Hidden "this" pointer for the audio functions */
32#define _THIS SDL_AudioDevice *this
33
34struct SDL_PrivateAudioData {
35 /* The handle for the audio device */
36 ALport audio_port;
37
38 Uint8 *mixbuf; /* The app mixing buffer */
39};
40
41/* Old variable names */
42#define audio_port (this->hidden->audio_port)
43#define mixbuf (this->hidden->mixbuf)
44
45#endif /* _SDL_lowaudio_h */
diff --git a/apps/plugins/sdl/src/audio/dsp/SDL_dspaudio.c b/apps/plugins/sdl/src/audio/dsp/SDL_dspaudio.c
deleted file mode 100644
index 256c547f9b..0000000000
--- a/apps/plugins/sdl/src/audio/dsp/SDL_dspaudio.c
+++ /dev/null
@@ -1,340 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 Modified in Oct 2004 by Hannu Savolainen
23 hannu@opensound.com
24*/
25#include "SDL_config.h"
26
27/* Allow access to a raw mixing buffer */
28
29#include <stdio.h> /* For perror() */
30#include <string.h> /* For strerror() */
31#include <errno.h>
32#include <unistd.h>
33#include <fcntl.h>
34#include <signal.h>
35#include <sys/time.h>
36#include <sys/ioctl.h>
37#include <sys/stat.h>
38
39#if SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H
40/* This is installed on some systems */
41#include <soundcard.h>
42#else
43/* This is recommended by OSS */
44#include <sys/soundcard.h>
45#endif
46
47#include "SDL_timer.h"
48#include "SDL_audio.h"
49#include "../SDL_audiomem.h"
50#include "../SDL_audio_c.h"
51#include "../SDL_audiodev_c.h"
52#include "SDL_dspaudio.h"
53
54/* The tag name used by DSP audio */
55#define DSP_DRIVER_NAME "dsp"
56
57/* Open the audio device for playback, and don't block if busy */
58#define OPEN_FLAGS (O_WRONLY|O_NONBLOCK)
59
60/* Audio driver functions */
61static int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec);
62static void DSP_WaitAudio(_THIS);
63static void DSP_PlayAudio(_THIS);
64static Uint8 *DSP_GetAudioBuf(_THIS);
65static void DSP_CloseAudio(_THIS);
66
67/* Audio driver bootstrap functions */
68
69static int Audio_Available(void)
70{
71 int fd;
72 int available;
73
74 available = 0;
75 fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0);
76 if ( fd >= 0 ) {
77 available = 1;
78 close(fd);
79 }
80 return(available);
81}
82
83static void Audio_DeleteDevice(SDL_AudioDevice *device)
84{
85 SDL_free(device->hidden);
86 SDL_free(device);
87}
88
89static SDL_AudioDevice *Audio_CreateDevice(int devindex)
90{
91 SDL_AudioDevice *this;
92
93 /* Initialize all variables that we clean on shutdown */
94 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
95 if ( this ) {
96 SDL_memset(this, 0, (sizeof *this));
97 this->hidden = (struct SDL_PrivateAudioData *)
98 SDL_malloc((sizeof *this->hidden));
99 }
100 if ( (this == NULL) || (this->hidden == NULL) ) {
101 SDL_OutOfMemory();
102 if ( this ) {
103 SDL_free(this);
104 }
105 return(0);
106 }
107 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
108 audio_fd = -1;
109
110 /* Set the function pointers */
111 this->OpenAudio = DSP_OpenAudio;
112 this->WaitAudio = DSP_WaitAudio;
113 this->PlayAudio = DSP_PlayAudio;
114 this->GetAudioBuf = DSP_GetAudioBuf;
115 this->CloseAudio = DSP_CloseAudio;
116
117 this->free = Audio_DeleteDevice;
118
119 return this;
120}
121
122AudioBootStrap DSP_bootstrap = {
123 DSP_DRIVER_NAME, "OSS /dev/dsp standard audio",
124 Audio_Available, Audio_CreateDevice
125};
126
127/* This function waits until it is possible to write a full sound buffer */
128static void DSP_WaitAudio(_THIS)
129{
130 /* Not needed at all since OSS handles waiting automagically */
131}
132
133static void DSP_PlayAudio(_THIS)
134{
135 if (write(audio_fd, mixbuf, mixlen)==-1)
136 {
137 perror("Audio write");
138 this->enabled = 0;
139 }
140
141#ifdef DEBUG_AUDIO
142 fprintf(stderr, "Wrote %d bytes of audio data\n", mixlen);
143#endif
144}
145
146static Uint8 *DSP_GetAudioBuf(_THIS)
147{
148 return(mixbuf);
149}
150
151static void DSP_CloseAudio(_THIS)
152{
153 if ( mixbuf != NULL ) {
154 SDL_FreeAudioMem(mixbuf);
155 mixbuf = NULL;
156 }
157 if ( audio_fd >= 0 ) {
158 close(audio_fd);
159 audio_fd = -1;
160 }
161}
162
163static int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec)
164{
165 char audiodev[1024];
166 int format;
167 int value;
168 int frag_spec;
169 Uint16 test_format;
170
171 /* Make sure fragment size stays a power of 2, or OSS fails. */
172 /* I don't know which of these are actually legal values, though... */
173 if (spec->channels > 8)
174 spec->channels = 8;
175 else if (spec->channels > 4)
176 spec->channels = 4;
177 else if (spec->channels > 2)
178 spec->channels = 2;
179
180 /* Open the audio device */
181 audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0);
182 if ( audio_fd < 0 ) {
183 SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
184 return(-1);
185 }
186 mixbuf = NULL;
187
188 /* Make the file descriptor use blocking writes with fcntl() */
189 { long flags;
190 flags = fcntl(audio_fd, F_GETFL);
191 flags &= ~O_NONBLOCK;
192 if ( fcntl(audio_fd, F_SETFL, flags) < 0 ) {
193 SDL_SetError("Couldn't set audio blocking mode");
194 DSP_CloseAudio(this);
195 return(-1);
196 }
197 }
198
199 /* Get a list of supported hardware formats */
200 if ( ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0 ) {
201 perror("SNDCTL_DSP_GETFMTS");
202 SDL_SetError("Couldn't get audio format list");
203 DSP_CloseAudio(this);
204 return(-1);
205 }
206
207 /* Try for a closest match on audio format */
208 format = 0;
209 for ( test_format = SDL_FirstAudioFormat(spec->format);
210 ! format && test_format; ) {
211#ifdef DEBUG_AUDIO
212 fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
213#endif
214 switch ( test_format ) {
215 case AUDIO_U8:
216 if ( value & AFMT_U8 ) {
217 format = AFMT_U8;
218 }
219 break;
220 case AUDIO_S16LSB:
221 if ( value & AFMT_S16_LE ) {
222 format = AFMT_S16_LE;
223 }
224 break;
225 case AUDIO_S16MSB:
226 if ( value & AFMT_S16_BE ) {
227 format = AFMT_S16_BE;
228 }
229 break;
230#if 0
231/*
232 * These formats are not used by any real life systems so they are not
233 * needed here.
234 */
235 case AUDIO_S8:
236 if ( value & AFMT_S8 ) {
237 format = AFMT_S8;
238 }
239 break;
240 case AUDIO_U16LSB:
241 if ( value & AFMT_U16_LE ) {
242 format = AFMT_U16_LE;
243 }
244 break;
245 case AUDIO_U16MSB:
246 if ( value & AFMT_U16_BE ) {
247 format = AFMT_U16_BE;
248 }
249 break;
250#endif
251 default:
252 format = 0;
253 break;
254 }
255 if ( ! format ) {
256 test_format = SDL_NextAudioFormat();
257 }
258 }
259 if ( format == 0 ) {
260 SDL_SetError("Couldn't find any hardware audio formats");
261 DSP_CloseAudio(this);
262 return(-1);
263 }
264 spec->format = test_format;
265
266 /* Set the audio format */
267 value = format;
268 if ( (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) ||
269 (value != format) ) {
270 perror("SNDCTL_DSP_SETFMT");
271 SDL_SetError("Couldn't set audio format");
272 DSP_CloseAudio(this);
273 return(-1);
274 }
275
276 /* Set the number of channels of output */
277 value = spec->channels;
278 if ( ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &value) < 0 ) {
279 perror("SNDCTL_DSP_CHANNELS");
280 SDL_SetError("Cannot set the number of channels");
281 DSP_CloseAudio(this);
282 return(-1);
283 }
284 spec->channels = value;
285
286 /* Set the DSP frequency */
287 value = spec->freq;
288 if ( ioctl(audio_fd, SNDCTL_DSP_SPEED, &value) < 0 ) {
289 perror("SNDCTL_DSP_SPEED");
290 SDL_SetError("Couldn't set audio frequency");
291 DSP_CloseAudio(this);
292 return(-1);
293 }
294 spec->freq = value;
295
296 /* Calculate the final parameters for this audio specification */
297 SDL_CalculateAudioSpec(spec);
298
299 /* Determine the power of two of the fragment size */
300 for ( frag_spec = 0; (0x01U<<frag_spec) < spec->size; ++frag_spec );
301 if ( (0x01U<<frag_spec) != spec->size ) {
302 SDL_SetError("Fragment size must be a power of two");
303 DSP_CloseAudio(this);
304 return(-1);
305 }
306 frag_spec |= 0x00020000; /* two fragments, for low latency */
307
308 /* Set the audio buffering parameters */
309#ifdef DEBUG_AUDIO
310 fprintf(stderr, "Requesting %d fragments of size %d\n",
311 (frag_spec >> 16), 1<<(frag_spec&0xFFFF));
312#endif
313 if ( ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0 ) {
314 perror("SNDCTL_DSP_SETFRAGMENT");
315 }
316#ifdef DEBUG_AUDIO
317 { audio_buf_info info;
318 ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info);
319 fprintf(stderr, "fragments = %d\n", info.fragments);
320 fprintf(stderr, "fragstotal = %d\n", info.fragstotal);
321 fprintf(stderr, "fragsize = %d\n", info.fragsize);
322 fprintf(stderr, "bytes = %d\n", info.bytes);
323 }
324#endif
325
326 /* Allocate mixing buffer */
327 mixlen = spec->size;
328 mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen);
329 if ( mixbuf == NULL ) {
330 DSP_CloseAudio(this);
331 return(-1);
332 }
333 SDL_memset(mixbuf, spec->silence, spec->size);
334
335 /* Get the parent process id (we're the parent of the audio thread) */
336 parent = getpid();
337
338 /* We're ready to rock and roll. :-) */
339 return(0);
340}
diff --git a/apps/plugins/sdl/src/audio/dsp/SDL_dspaudio.h b/apps/plugins/sdl/src/audio/dsp/SDL_dspaudio.h
deleted file mode 100644
index 382544f967..0000000000
--- a/apps/plugins/sdl/src/audio/dsp/SDL_dspaudio.h
+++ /dev/null
@@ -1,53 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_dspaudio_h
25#define _SDL_dspaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the video functions */
30#define _THIS SDL_AudioDevice *this
31
32struct SDL_PrivateAudioData {
33 /* The file descriptor for the audio device */
34 int audio_fd;
35
36 /* The parent process id, to detect when application quits */
37 pid_t parent;
38
39 /* Raw mixing buffer */
40 Uint8 *mixbuf;
41 int mixlen;
42};
43#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
44
45/* Old variable names */
46#define audio_fd (this->hidden->audio_fd)
47#define parent (this->hidden->parent)
48#define mixbuf (this->hidden->mixbuf)
49#define mixlen (this->hidden->mixlen)
50#define frame_ticks (this->hidden->frame_ticks)
51#define next_frame (this->hidden->next_frame)
52
53#endif /* _SDL_dspaudio_h */
diff --git a/apps/plugins/sdl/src/audio/esd/SDL_esdaudio.c b/apps/plugins/sdl/src/audio/esd/SDL_esdaudio.c
deleted file mode 100644
index f54b0ea9c5..0000000000
--- a/apps/plugins/sdl/src/audio/esd/SDL_esdaudio.c
+++ /dev/null
@@ -1,323 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to an ESD network stream mixing buffer */
25
26#include <sys/types.h>
27#include <unistd.h>
28#include <signal.h>
29#include <errno.h>
30#include <esd.h>
31
32#include "SDL_timer.h"
33#include "SDL_audio.h"
34#include "../SDL_audiomem.h"
35#include "../SDL_audio_c.h"
36#include "../SDL_audiodev_c.h"
37#include "SDL_esdaudio.h"
38
39#ifdef SDL_AUDIO_DRIVER_ESD_DYNAMIC
40#include "SDL_name.h"
41#include "SDL_loadso.h"
42#else
43#define SDL_NAME(X) X
44#endif
45
46/* The tag name used by ESD audio */
47#define ESD_DRIVER_NAME "esd"
48
49/* Audio driver functions */
50static int ESD_OpenAudio(_THIS, SDL_AudioSpec *spec);
51static void ESD_WaitAudio(_THIS);
52static void ESD_PlayAudio(_THIS);
53static Uint8 *ESD_GetAudioBuf(_THIS);
54static void ESD_CloseAudio(_THIS);
55
56#ifdef SDL_AUDIO_DRIVER_ESD_DYNAMIC
57
58static const char *esd_library = SDL_AUDIO_DRIVER_ESD_DYNAMIC;
59static void *esd_handle = NULL;
60static int esd_loaded = 0;
61
62static int (*SDL_NAME(esd_open_sound))( const char *host );
63static int (*SDL_NAME(esd_close))( int esd );
64static int (*SDL_NAME(esd_play_stream))( esd_format_t format, int rate,
65 const char *host, const char *name );
66static struct {
67 const char *name;
68 void **func;
69} esd_functions[] = {
70 { "esd_open_sound", (void **)&SDL_NAME(esd_open_sound) },
71 { "esd_close", (void **)&SDL_NAME(esd_close) },
72 { "esd_play_stream", (void **)&SDL_NAME(esd_play_stream) },
73};
74
75static void UnloadESDLibrary()
76{
77 if ( esd_loaded ) {
78 SDL_UnloadObject(esd_handle);
79 esd_handle = NULL;
80 esd_loaded = 0;
81 }
82}
83
84static int LoadESDLibrary(void)
85{
86 int i, retval = -1;
87
88 esd_handle = SDL_LoadObject(esd_library);
89 if ( esd_handle ) {
90 esd_loaded = 1;
91 retval = 0;
92 for ( i=0; i<SDL_arraysize(esd_functions); ++i ) {
93 *esd_functions[i].func = SDL_LoadFunction(esd_handle, esd_functions[i].name);
94 if ( !*esd_functions[i].func ) {
95 retval = -1;
96 UnloadESDLibrary();
97 break;
98 }
99 }
100 }
101 return retval;
102}
103
104#else
105
106static void UnloadESDLibrary()
107{
108 return;
109}
110
111static int LoadESDLibrary(void)
112{
113 return 0;
114}
115
116#endif /* SDL_AUDIO_DRIVER_ESD_DYNAMIC */
117
118/* Audio driver bootstrap functions */
119
120static int Audio_Available(void)
121{
122 int connection;
123 int available;
124
125 available = 0;
126 if ( LoadESDLibrary() < 0 ) {
127 return available;
128 }
129 connection = SDL_NAME(esd_open_sound)(NULL);
130 if ( connection >= 0 ) {
131 available = 1;
132 SDL_NAME(esd_close)(connection);
133 }
134 UnloadESDLibrary();
135 return(available);
136}
137
138static void Audio_DeleteDevice(SDL_AudioDevice *device)
139{
140 SDL_free(device->hidden);
141 SDL_free(device);
142 UnloadESDLibrary();
143}
144
145static SDL_AudioDevice *Audio_CreateDevice(int devindex)
146{
147 SDL_AudioDevice *this;
148
149 /* Initialize all variables that we clean on shutdown */
150 LoadESDLibrary();
151 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
152 if ( this ) {
153 SDL_memset(this, 0, (sizeof *this));
154 this->hidden = (struct SDL_PrivateAudioData *)
155 SDL_malloc((sizeof *this->hidden));
156 }
157 if ( (this == NULL) || (this->hidden == NULL) ) {
158 SDL_OutOfMemory();
159 if ( this ) {
160 SDL_free(this);
161 }
162 return(0);
163 }
164 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
165 audio_fd = -1;
166
167 /* Set the function pointers */
168 this->OpenAudio = ESD_OpenAudio;
169 this->WaitAudio = ESD_WaitAudio;
170 this->PlayAudio = ESD_PlayAudio;
171 this->GetAudioBuf = ESD_GetAudioBuf;
172 this->CloseAudio = ESD_CloseAudio;
173
174 this->free = Audio_DeleteDevice;
175
176 return this;
177}
178
179AudioBootStrap ESD_bootstrap = {
180 ESD_DRIVER_NAME, "Enlightened Sound Daemon",
181 Audio_Available, Audio_CreateDevice
182};
183
184/* This function waits until it is possible to write a full sound buffer */
185static void ESD_WaitAudio(_THIS)
186{
187 Sint32 ticks;
188
189 /* Check to see if the thread-parent process is still alive */
190 { static int cnt = 0;
191 /* Note that this only works with thread implementations
192 that use a different process id for each thread.
193 */
194 if (parent && (((++cnt)%10) == 0)) { /* Check every 10 loops */
195 if ( kill(parent, 0) < 0 ) {
196 this->enabled = 0;
197 }
198 }
199 }
200
201 /* Use timer for general audio synchronization */
202 ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS;
203 if ( ticks > 0 ) {
204 SDL_Delay(ticks);
205 }
206}
207
208static void ESD_PlayAudio(_THIS)
209{
210 int written;
211
212 /* Write the audio data, checking for EAGAIN on broken audio drivers */
213 do {
214 written = write(audio_fd, mixbuf, mixlen);
215 if ( (written < 0) && ((errno == 0) || (errno == EAGAIN)) ) {
216 SDL_Delay(1); /* Let a little CPU time go by */
217 }
218 } while ( (written < 0) &&
219 ((errno == 0) || (errno == EAGAIN) || (errno == EINTR)) );
220
221 /* Set the next write frame */
222 next_frame += frame_ticks;
223
224 /* If we couldn't write, assume fatal error for now */
225 if ( written < 0 ) {
226 this->enabled = 0;
227 }
228}
229
230static Uint8 *ESD_GetAudioBuf(_THIS)
231{
232 return(mixbuf);
233}
234
235static void ESD_CloseAudio(_THIS)
236{
237 if ( mixbuf != NULL ) {
238 SDL_FreeAudioMem(mixbuf);
239 mixbuf = NULL;
240 }
241 if ( audio_fd >= 0 ) {
242 SDL_NAME(esd_close)(audio_fd);
243 audio_fd = -1;
244 }
245}
246
247/* Try to get the name of the program */
248static char *get_progname(void)
249{
250 char *progname = NULL;
251#ifdef __LINUX__
252 FILE *fp;
253 static char temp[BUFSIZ];
254
255 SDL_snprintf(temp, SDL_arraysize(temp), "/proc/%d/cmdline", getpid());
256 fp = fopen(temp, "r");
257 if ( fp != NULL ) {
258 if ( fgets(temp, sizeof(temp)-1, fp) ) {
259 progname = SDL_strrchr(temp, '/');
260 if ( progname == NULL ) {
261 progname = temp;
262 } else {
263 progname = progname+1;
264 }
265 }
266 fclose(fp);
267 }
268#endif
269 return(progname);
270}
271
272static int ESD_OpenAudio(_THIS, SDL_AudioSpec *spec)
273{
274 esd_format_t format;
275
276 /* Convert audio spec to the ESD audio format */
277 format = (ESD_STREAM | ESD_PLAY);
278 switch ( spec->format & 0xFF ) {
279 case 8:
280 format |= ESD_BITS8;
281 break;
282 case 16:
283 format |= ESD_BITS16;
284 break;
285 default:
286 SDL_SetError("Unsupported ESD audio format");
287 return(-1);
288 }
289 if ( spec->channels == 1 ) {
290 format |= ESD_MONO;
291 } else {
292 format |= ESD_STEREO;
293 }
294#if 0
295 spec->samples = ESD_BUF_SIZE; /* Darn, no way to change this yet */
296#endif
297
298 /* Open a connection to the ESD audio server */
299 audio_fd = SDL_NAME(esd_play_stream)(format, spec->freq, NULL, get_progname());
300 if ( audio_fd < 0 ) {
301 SDL_SetError("Couldn't open ESD connection");
302 return(-1);
303 }
304
305 /* Calculate the final parameters for this audio specification */
306 SDL_CalculateAudioSpec(spec);
307 frame_ticks = (float)(spec->samples*1000)/spec->freq;
308 next_frame = SDL_GetTicks()+frame_ticks;
309
310 /* Allocate mixing buffer */
311 mixlen = spec->size;
312 mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen);
313 if ( mixbuf == NULL ) {
314 return(-1);
315 }
316 SDL_memset(mixbuf, spec->silence, spec->size);
317
318 /* Get the parent process id (we're the parent of the audio thread) */
319 parent = getpid();
320
321 /* We're ready to rock and roll. :-) */
322 return(0);
323}
diff --git a/apps/plugins/sdl/src/audio/esd/SDL_esdaudio.h b/apps/plugins/sdl/src/audio/esd/SDL_esdaudio.h
deleted file mode 100644
index da4ae6a04b..0000000000
--- a/apps/plugins/sdl/src/audio/esd/SDL_esdaudio.h
+++ /dev/null
@@ -1,57 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_esdaudio_h
25#define _SDL_esdaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the video functions */
30#define _THIS SDL_AudioDevice *this
31
32struct SDL_PrivateAudioData {
33 /* The file descriptor for the audio device */
34 int audio_fd;
35
36 /* The parent process id, to detect when application quits */
37 pid_t parent;
38
39 /* Raw mixing buffer */
40 Uint8 *mixbuf;
41 int mixlen;
42
43 /* Support for audio timing using a timer */
44 float frame_ticks;
45 float next_frame;
46};
47#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
48
49/* Old variable names */
50#define audio_fd (this->hidden->audio_fd)
51#define parent (this->hidden->parent)
52#define mixbuf (this->hidden->mixbuf)
53#define mixlen (this->hidden->mixlen)
54#define frame_ticks (this->hidden->frame_ticks)
55#define next_frame (this->hidden->next_frame)
56
57#endif /* _SDL_esdaudio_h */
diff --git a/apps/plugins/sdl/src/audio/macosx/SDL_coreaudio.c b/apps/plugins/sdl/src/audio/macosx/SDL_coreaudio.c
deleted file mode 100644
index 31316d1fd9..0000000000
--- a/apps/plugins/sdl/src/audio/macosx/SDL_coreaudio.c
+++ /dev/null
@@ -1,291 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <CoreAudio/CoreAudio.h>
25#include <CoreServices/CoreServices.h>
26#include <AudioUnit/AudioUnit.h>
27#if MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
28#include <AudioUnit/AUNTComponent.h>
29#endif
30
31#include "SDL_audio.h"
32#include "../SDL_audio_c.h"
33#include "../SDL_sysaudio.h"
34#include "SDL_coreaudio.h"
35
36
37/* Audio driver functions */
38
39static int Core_OpenAudio(_THIS, SDL_AudioSpec *spec);
40static void Core_WaitAudio(_THIS);
41static void Core_PlayAudio(_THIS);
42static Uint8 *Core_GetAudioBuf(_THIS);
43static void Core_CloseAudio(_THIS);
44
45/* Audio driver bootstrap functions */
46
47static int Audio_Available(void)
48{
49 return(1);
50}
51
52static void Audio_DeleteDevice(SDL_AudioDevice *device)
53{
54 SDL_free(device->hidden);
55 SDL_free(device);
56}
57
58static SDL_AudioDevice *Audio_CreateDevice(int devindex)
59{
60 SDL_AudioDevice *this;
61
62 /* Initialize all variables that we clean on shutdown */
63 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
64 if ( this ) {
65 SDL_memset(this, 0, (sizeof *this));
66 this->hidden = (struct SDL_PrivateAudioData *)
67 SDL_malloc((sizeof *this->hidden));
68 }
69 if ( (this == NULL) || (this->hidden == NULL) ) {
70 SDL_OutOfMemory();
71 if ( this ) {
72 SDL_free(this);
73 }
74 return(0);
75 }
76 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
77
78 /* Set the function pointers */
79 this->OpenAudio = Core_OpenAudio;
80 this->WaitAudio = Core_WaitAudio;
81 this->PlayAudio = Core_PlayAudio;
82 this->GetAudioBuf = Core_GetAudioBuf;
83 this->CloseAudio = Core_CloseAudio;
84
85 this->free = Audio_DeleteDevice;
86
87 return this;
88}
89
90AudioBootStrap COREAUDIO_bootstrap = {
91 "coreaudio", "Mac OS X CoreAudio",
92 Audio_Available, Audio_CreateDevice
93};
94
95/* The CoreAudio callback */
96static OSStatus audioCallback (void *inRefCon,
97 AudioUnitRenderActionFlags *ioActionFlags,
98 const AudioTimeStamp *inTimeStamp,
99 UInt32 inBusNumber,
100 UInt32 inNumberFrames,
101 AudioBufferList *ioData)
102{
103 SDL_AudioDevice *this = (SDL_AudioDevice *)inRefCon;
104 UInt32 remaining, len;
105 AudioBuffer *abuf;
106 void *ptr;
107 UInt32 i;
108
109 /* Only do anything if audio is enabled and not paused */
110 if ( ! this->enabled || this->paused ) {
111 for (i = 0; i < ioData->mNumberBuffers; i++) {
112 abuf = &ioData->mBuffers[i];
113 SDL_memset(abuf->mData, this->spec.silence, abuf->mDataByteSize);
114 }
115 return 0;
116 }
117
118 /* No SDL conversion should be needed here, ever, since we accept
119 any input format in OpenAudio, and leave the conversion to CoreAudio.
120 */
121 /*
122 assert(!this->convert.needed);
123 assert(this->spec.channels == ioData->mNumberChannels);
124 */
125
126 for (i = 0; i < ioData->mNumberBuffers; i++) {
127 abuf = &ioData->mBuffers[i];
128 remaining = abuf->mDataByteSize;
129 ptr = abuf->mData;
130 while (remaining > 0) {
131 if (bufferOffset >= bufferSize) {
132 /* Generate the data */
133 SDL_memset(buffer, this->spec.silence, bufferSize);
134 SDL_mutexP(this->mixer_lock);
135 (*this->spec.callback)(this->spec.userdata,
136 buffer, bufferSize);
137 SDL_mutexV(this->mixer_lock);
138 bufferOffset = 0;
139 }
140
141 len = bufferSize - bufferOffset;
142 if (len > remaining)
143 len = remaining;
144 SDL_memcpy(ptr, (char *)buffer + bufferOffset, len);
145 ptr = (char *)ptr + len;
146 remaining -= len;
147 bufferOffset += len;
148 }
149 }
150
151 return 0;
152}
153
154/* Dummy functions -- we don't use thread-based audio */
155void Core_WaitAudio(_THIS)
156{
157 return;
158}
159
160void Core_PlayAudio(_THIS)
161{
162 return;
163}
164
165Uint8 *Core_GetAudioBuf(_THIS)
166{
167 return(NULL);
168}
169
170void Core_CloseAudio(_THIS)
171{
172 OSStatus result;
173 struct AURenderCallbackStruct callback;
174
175 /* stop processing the audio unit */
176 result = AudioOutputUnitStop (outputAudioUnit);
177 if (result != noErr) {
178 SDL_SetError("Core_CloseAudio: AudioOutputUnitStop");
179 return;
180 }
181
182 /* Remove the input callback */
183 callback.inputProc = 0;
184 callback.inputProcRefCon = 0;
185 result = AudioUnitSetProperty (outputAudioUnit,
186 kAudioUnitProperty_SetRenderCallback,
187 kAudioUnitScope_Input,
188 0,
189 &callback,
190 sizeof(callback));
191 if (result != noErr) {
192 SDL_SetError("Core_CloseAudio: AudioUnitSetProperty (kAudioUnitProperty_SetInputCallback)");
193 return;
194 }
195
196 result = CloseComponent(outputAudioUnit);
197 if (result != noErr) {
198 SDL_SetError("Core_CloseAudio: CloseComponent");
199 return;
200 }
201
202 SDL_free(buffer);
203}
204
205#define CHECK_RESULT(msg) \
206 if (result != noErr) { \
207 SDL_SetError("Failed to start CoreAudio: " msg); \
208 return -1; \
209 }
210
211
212int Core_OpenAudio(_THIS, SDL_AudioSpec *spec)
213{
214 OSStatus result = noErr;
215 Component comp;
216 ComponentDescription desc;
217 struct AURenderCallbackStruct callback;
218 AudioStreamBasicDescription requestedDesc;
219
220 /* Setup a AudioStreamBasicDescription with the requested format */
221 requestedDesc.mFormatID = kAudioFormatLinearPCM;
222 requestedDesc.mFormatFlags = kLinearPCMFormatFlagIsPacked;
223 requestedDesc.mChannelsPerFrame = spec->channels;
224 requestedDesc.mSampleRate = spec->freq;
225
226 requestedDesc.mBitsPerChannel = spec->format & 0xFF;
227 if (spec->format & 0x8000)
228 requestedDesc.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
229 if (spec->format & 0x1000)
230 requestedDesc.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
231
232 requestedDesc.mFramesPerPacket = 1;
233 requestedDesc.mBytesPerFrame = requestedDesc.mBitsPerChannel * requestedDesc.mChannelsPerFrame / 8;
234 requestedDesc.mBytesPerPacket = requestedDesc.mBytesPerFrame * requestedDesc.mFramesPerPacket;
235
236
237 /* Locate the default output audio unit */
238 desc.componentType = kAudioUnitType_Output;
239 desc.componentSubType = kAudioUnitSubType_DefaultOutput;
240 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
241 desc.componentFlags = 0;
242 desc.componentFlagsMask = 0;
243
244 comp = FindNextComponent (NULL, &desc);
245 if (comp == NULL) {
246 SDL_SetError ("Failed to start CoreAudio: FindNextComponent returned NULL");
247 return -1;
248 }
249
250 /* Open & initialize the default output audio unit */
251 result = OpenAComponent (comp, &outputAudioUnit);
252 CHECK_RESULT("OpenAComponent")
253
254 result = AudioUnitInitialize (outputAudioUnit);
255 CHECK_RESULT("AudioUnitInitialize")
256
257 /* Set the input format of the audio unit. */
258 result = AudioUnitSetProperty (outputAudioUnit,
259 kAudioUnitProperty_StreamFormat,
260 kAudioUnitScope_Input,
261 0,
262 &requestedDesc,
263 sizeof (requestedDesc));
264 CHECK_RESULT("AudioUnitSetProperty (kAudioUnitProperty_StreamFormat)")
265
266 /* Set the audio callback */
267 callback.inputProc = audioCallback;
268 callback.inputProcRefCon = this;
269 result = AudioUnitSetProperty (outputAudioUnit,
270 kAudioUnitProperty_SetRenderCallback,
271 kAudioUnitScope_Input,
272 0,
273 &callback,
274 sizeof(callback));
275 CHECK_RESULT("AudioUnitSetProperty (kAudioUnitProperty_SetInputCallback)")
276
277 /* Calculate the final parameters for this audio specification */
278 SDL_CalculateAudioSpec(spec);
279
280 /* Allocate a sample buffer */
281 bufferOffset = bufferSize = this->spec.size;
282 buffer = SDL_malloc(bufferSize);
283
284 /* Finally, start processing of the audio unit */
285 result = AudioOutputUnitStart (outputAudioUnit);
286 CHECK_RESULT("AudioOutputUnitStart")
287
288
289 /* We're running! */
290 return(1);
291}
diff --git a/apps/plugins/sdl/src/audio/macosx/SDL_coreaudio.h b/apps/plugins/sdl/src/audio/macosx/SDL_coreaudio.h
deleted file mode 100644
index c11bc03a2b..0000000000
--- a/apps/plugins/sdl/src/audio/macosx/SDL_coreaudio.h
+++ /dev/null
@@ -1,45 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_coreaudio_h
25#define _SDL_coreaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the video functions */
30#define _THIS SDL_AudioDevice *this
31
32struct SDL_PrivateAudioData {
33 AudioUnit outputAudioUnit;
34 void *buffer;
35 UInt32 bufferOffset;
36 UInt32 bufferSize;
37};
38
39/* Old variable names */
40#define outputAudioUnit (this->hidden->outputAudioUnit)
41#define buffer (this->hidden->buffer)
42#define bufferOffset (this->hidden->bufferOffset)
43#define bufferSize (this->hidden->bufferSize)
44
45#endif /* _SDL_coreaudio_h */
diff --git a/apps/plugins/sdl/src/audio/macrom/SDL_romaudio.c b/apps/plugins/sdl/src/audio/macrom/SDL_romaudio.c
deleted file mode 100644
index 1b3d49e198..0000000000
--- a/apps/plugins/sdl/src/audio/macrom/SDL_romaudio.c
+++ /dev/null
@@ -1,496 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#if defined(__APPLE__) && defined(__MACH__)
25# include <Carbon/Carbon.h>
26#elif TARGET_API_MAC_CARBON && (UNIVERSAL_INTERFACES_VERSION > 0x0335)
27# include <Carbon.h>
28#else
29# include <Sound.h> /* SoundManager interface */
30# include <Gestalt.h>
31# include <DriverServices.h>
32#endif
33
34#if !defined(NewSndCallBackUPP) && (UNIVERSAL_INTERFACES_VERSION < 0x0335)
35#if !defined(NewSndCallBackProc) /* avoid circular redefinition... */
36#define NewSndCallBackUPP NewSndCallBackProc
37#endif
38#if !defined(NewSndCallBackUPP)
39#define NewSndCallBackUPP NewSndCallBackProc
40#endif
41#endif
42
43#include "SDL_audio.h"
44#include "../SDL_audio_c.h"
45#include "../SDL_sysaudio.h"
46#include "SDL_romaudio.h"
47
48/* Audio driver functions */
49
50static void Mac_CloseAudio(_THIS);
51static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec);
52static void Mac_LockAudio(_THIS);
53static void Mac_UnlockAudio(_THIS);
54
55/* Audio driver bootstrap functions */
56
57
58static int Audio_Available(void)
59{
60 return(1);
61}
62
63static void Audio_DeleteDevice(SDL_AudioDevice *device)
64{
65 SDL_free(device->hidden);
66 SDL_free(device);
67}
68
69static SDL_AudioDevice *Audio_CreateDevice(int devindex)
70{
71 SDL_AudioDevice *this;
72
73 /* Initialize all variables that we clean on shutdown */
74 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
75 if ( this ) {
76 SDL_memset(this, 0, (sizeof *this));
77 this->hidden = (struct SDL_PrivateAudioData *)
78 SDL_malloc((sizeof *this->hidden));
79 }
80 if ( (this == NULL) || (this->hidden == NULL) ) {
81 SDL_OutOfMemory();
82 if ( this ) {
83 SDL_free(this);
84 }
85 return(0);
86 }
87 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
88
89 /* Set the function pointers */
90 this->OpenAudio = Mac_OpenAudio;
91 this->CloseAudio = Mac_CloseAudio;
92 this->LockAudio = Mac_LockAudio;
93 this->UnlockAudio = Mac_UnlockAudio;
94 this->free = Audio_DeleteDevice;
95
96#ifdef __MACOSX__ /* Mac OS X uses threaded audio, so normal thread code is okay */
97 this->LockAudio = NULL;
98 this->UnlockAudio = NULL;
99#endif
100 return this;
101}
102
103AudioBootStrap SNDMGR_bootstrap = {
104 "sndmgr", "MacOS SoundManager 3.0",
105 Audio_Available, Audio_CreateDevice
106};
107
108#if defined(TARGET_API_MAC_CARBON) || defined(USE_RYANS_SOUNDCODE)
109/* This works correctly on Mac OS X */
110
111#pragma options align=power
112
113static volatile SInt32 audio_is_locked = 0;
114static volatile SInt32 need_to_mix = 0;
115
116static UInt8 *buffer[2];
117static volatile UInt32 running = 0;
118static CmpSoundHeader header;
119static volatile Uint32 fill_me = 0;
120
121static void mix_buffer(SDL_AudioDevice *audio, UInt8 *buffer)
122{
123 if ( ! audio->paused ) {
124#ifdef __MACOSX__
125 SDL_mutexP(audio->mixer_lock);
126#endif
127 if ( audio->convert.needed ) {
128 audio->spec.callback(audio->spec.userdata,
129 (Uint8 *)audio->convert.buf,audio->convert.len);
130 SDL_ConvertAudio(&audio->convert);
131 if ( audio->convert.len_cvt != audio->spec.size ) {
132 /* Uh oh... probably crashes here */;
133 }
134 SDL_memcpy(buffer, audio->convert.buf, audio->convert.len_cvt);
135 } else {
136 audio->spec.callback(audio->spec.userdata, buffer, audio->spec.size);
137 }
138#ifdef __MACOSX__
139 SDL_mutexV(audio->mixer_lock);
140#endif
141 }
142
143 DecrementAtomic((SInt32 *) &need_to_mix);
144}
145
146static void Mac_LockAudio(_THIS)
147{
148 IncrementAtomic((SInt32 *) &audio_is_locked);
149}
150
151static void Mac_UnlockAudio(_THIS)
152{
153 SInt32 oldval;
154
155 oldval = DecrementAtomic((SInt32 *) &audio_is_locked);
156 if ( oldval != 1 ) /* != 1 means audio is still locked. */
157 return;
158
159 /* Did we miss the chance to mix in an interrupt? Do it now. */
160 if ( BitAndAtomic (0xFFFFFFFF, (UInt32 *) &need_to_mix) ) {
161 /*
162 * Note that this could be a problem if you missed an interrupt
163 * while the audio was locked, and get preempted by a second
164 * interrupt here, but that means you locked for way too long anyhow.
165 */
166 mix_buffer (this, buffer[fill_me]);
167 }
168}
169
170static void callBackProc (SndChannel *chan, SndCommand *cmd_passed ) {
171 UInt32 play_me;
172 SndCommand cmd;
173 SDL_AudioDevice *audio = (SDL_AudioDevice *)chan->userInfo;
174
175 IncrementAtomic((SInt32 *) &need_to_mix);
176
177 fill_me = cmd_passed->param2; /* buffer that has just finished playing, so fill it */
178 play_me = ! fill_me; /* filled buffer to play _now_ */
179
180 if ( ! audio->enabled ) {
181 return;
182 }
183
184 /* queue previously mixed buffer for playback. */
185 header.samplePtr = (Ptr)buffer[play_me];
186 cmd.cmd = bufferCmd;
187 cmd.param1 = 0;
188 cmd.param2 = (long)&header;
189 SndDoCommand (chan, &cmd, 0);
190
191 memset (buffer[fill_me], 0, audio->spec.size);
192
193 /*
194 * if audio device isn't locked, mix the next buffer to be queued in
195 * the memory block that just finished playing.
196 */
197 if ( ! BitAndAtomic(0xFFFFFFFF, (UInt32 *) &audio_is_locked) ) {
198 mix_buffer (audio, buffer[fill_me]);
199 }
200
201 /* set this callback to run again when current buffer drains. */
202 if ( running ) {
203 cmd.cmd = callBackCmd;
204 cmd.param1 = 0;
205 cmd.param2 = play_me;
206
207 SndDoCommand (chan, &cmd, 0);
208 }
209}
210
211static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec) {
212
213 SndCallBackUPP callback;
214 int sample_bits;
215 int i;
216 long initOptions;
217
218 /* Very few conversions are required, but... */
219 switch (spec->format) {
220 case AUDIO_S8:
221 spec->format = AUDIO_U8;
222 break;
223 case AUDIO_U16LSB:
224 spec->format = AUDIO_S16LSB;
225 break;
226 case AUDIO_U16MSB:
227 spec->format = AUDIO_S16MSB;
228 break;
229 }
230 SDL_CalculateAudioSpec(spec);
231
232 /* initialize bufferCmd header */
233 memset (&header, 0, sizeof(header));
234 callback = (SndCallBackUPP) NewSndCallBackUPP (callBackProc);
235 sample_bits = spec->size / spec->samples / spec->channels * 8;
236
237#ifdef DEBUG_AUDIO
238 fprintf(stderr,
239 "Audio format 0x%x, channels = %d, sample_bits = %d, frequency = %d\n",
240 spec->format, spec->channels, sample_bits, spec->freq);
241#endif /* DEBUG_AUDIO */
242
243 header.numChannels = spec->channels;
244 header.sampleSize = sample_bits;
245 header.sampleRate = spec->freq << 16;
246 header.numFrames = spec->samples;
247 header.encode = cmpSH;
248
249 /* Note that we install the 16bitLittleEndian Converter if needed. */
250 if ( spec->format == 0x8010 ) {
251 header.compressionID = fixedCompression;
252 header.format = k16BitLittleEndianFormat;
253 }
254
255 /* allocate 2 buffers */
256 for (i=0; i<2; i++) {
257 buffer[i] = (UInt8*)malloc (sizeof(UInt8) * spec->size);
258 if (buffer[i] == NULL) {
259 SDL_OutOfMemory();
260 return (-1);
261 }
262 memset (buffer[i], 0, spec->size);
263 }
264
265 /* Create the sound manager channel */
266 channel = (SndChannelPtr)SDL_malloc(sizeof(*channel));
267 if ( channel == NULL ) {
268 SDL_OutOfMemory();
269 return(-1);
270 }
271 if ( spec->channels >= 2 ) {
272 initOptions = initStereo;
273 } else {
274 initOptions = initMono;
275 }
276 channel->userInfo = (long)this;
277 channel->qLength = 128;
278 if ( SndNewChannel(&channel, sampledSynth, initOptions, callback) != noErr ) {
279 SDL_SetError("Unable to create audio channel");
280 SDL_free(channel);
281 channel = NULL;
282 return(-1);
283 }
284
285 /* start playback */
286 {
287 SndCommand cmd;
288 cmd.cmd = callBackCmd;
289 cmd.param2 = 0;
290 running = 1;
291 SndDoCommand (channel, &cmd, 0);
292 }
293
294 return 1;
295}
296
297static void Mac_CloseAudio(_THIS) {
298
299 int i;
300
301 running = 0;
302
303 if (channel) {
304 SndDisposeChannel (channel, true);
305 channel = NULL;
306 }
307
308 for ( i=0; i<2; ++i ) {
309 if ( buffer[i] ) {
310 SDL_free(buffer[i]);
311 buffer[i] = NULL;
312 }
313 }
314}
315
316#else /* !TARGET_API_MAC_CARBON && !USE_RYANS_SOUNDCODE */
317
318static void Mac_LockAudio(_THIS)
319{
320 /* no-op. */
321}
322
323static void Mac_UnlockAudio(_THIS)
324{
325 /* no-op. */
326}
327
328
329/* This function is called by Sound Manager when it has exhausted one of
330 the buffers, so we'll zero it to silence and fill it with audio if
331 we're not paused.
332*/
333static pascal
334void sndDoubleBackProc (SndChannelPtr chan, SndDoubleBufferPtr newbuf)
335{
336 SDL_AudioDevice *audio = (SDL_AudioDevice *)newbuf->dbUserInfo[0];
337
338 /* If audio is quitting, don't do anything */
339 if ( ! audio->enabled ) {
340 return;
341 }
342 memset (newbuf->dbSoundData, 0, audio->spec.size);
343 newbuf->dbNumFrames = audio->spec.samples;
344 if ( ! audio->paused ) {
345 if ( audio->convert.needed ) {
346 audio->spec.callback(audio->spec.userdata,
347 (Uint8 *)audio->convert.buf,audio->convert.len);
348 SDL_ConvertAudio(&audio->convert);
349#if 0
350 if ( audio->convert.len_cvt != audio->spec.size ) {
351 /* Uh oh... probably crashes here */;
352 }
353#endif
354 SDL_memcpy(newbuf->dbSoundData, audio->convert.buf,
355 audio->convert.len_cvt);
356 } else {
357 audio->spec.callback(audio->spec.userdata,
358 (Uint8 *)newbuf->dbSoundData, audio->spec.size);
359 }
360 }
361 newbuf->dbFlags |= dbBufferReady;
362}
363
364static int DoubleBufferAudio_Available(void)
365{
366 int available;
367 NumVersion sndversion;
368 long response;
369
370 available = 0;
371 sndversion = SndSoundManagerVersion();
372 if ( sndversion.majorRev >= 3 ) {
373 if ( Gestalt(gestaltSoundAttr, &response) == noErr ) {
374 if ( (response & (1 << gestaltSndPlayDoubleBuffer)) ) {
375 available = 1;
376 }
377 }
378 } else {
379 if ( Gestalt(gestaltSoundAttr, &response) == noErr ) {
380 if ( (response & (1 << gestaltHasASC)) ) {
381 available = 1;
382 }
383 }
384 }
385 return(available);
386}
387
388static void Mac_CloseAudio(_THIS)
389{
390 int i;
391
392 if ( channel != NULL ) {
393 /* Clean up the audio channel */
394 SndDisposeChannel(channel, true);
395 channel = NULL;
396 }
397 for ( i=0; i<2; ++i ) {
398 if ( audio_buf[i] ) {
399 SDL_free(audio_buf[i]);
400 audio_buf[i] = NULL;
401 }
402 }
403}
404
405static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec)
406{
407 SndDoubleBufferHeader2 audio_dbh;
408 int i;
409 long initOptions;
410 int sample_bits;
411 SndDoubleBackUPP doubleBackProc;
412
413 /* Check to make sure double-buffered audio is available */
414 if ( ! DoubleBufferAudio_Available() ) {
415 SDL_SetError("Sound manager doesn't support double-buffering");
416 return(-1);
417 }
418
419 /* Very few conversions are required, but... */
420 switch (spec->format) {
421 case AUDIO_S8:
422 spec->format = AUDIO_U8;
423 break;
424 case AUDIO_U16LSB:
425 spec->format = AUDIO_S16LSB;
426 break;
427 case AUDIO_U16MSB:
428 spec->format = AUDIO_S16MSB;
429 break;
430 }
431 SDL_CalculateAudioSpec(spec);
432
433 /* initialize the double-back header */
434 SDL_memset(&audio_dbh, 0, sizeof(audio_dbh));
435 doubleBackProc = NewSndDoubleBackProc (sndDoubleBackProc);
436 sample_bits = spec->size / spec->samples / spec->channels * 8;
437
438 audio_dbh.dbhNumChannels = spec->channels;
439 audio_dbh.dbhSampleSize = sample_bits;
440 audio_dbh.dbhCompressionID = 0;
441 audio_dbh.dbhPacketSize = 0;
442 audio_dbh.dbhSampleRate = spec->freq << 16;
443 audio_dbh.dbhDoubleBack = doubleBackProc;
444 audio_dbh.dbhFormat = 0;
445
446 /* Note that we install the 16bitLittleEndian Converter if needed. */
447 if ( spec->format == 0x8010 ) {
448 audio_dbh.dbhCompressionID = fixedCompression;
449 audio_dbh.dbhFormat = k16BitLittleEndianFormat;
450 }
451
452 /* allocate the 2 double-back buffers */
453 for ( i=0; i<2; ++i ) {
454 audio_buf[i] = SDL_calloc(1, sizeof(SndDoubleBuffer)+spec->size);
455 if ( audio_buf[i] == NULL ) {
456 SDL_OutOfMemory();
457 return(-1);
458 }
459 audio_buf[i]->dbNumFrames = spec->samples;
460 audio_buf[i]->dbFlags = dbBufferReady;
461 audio_buf[i]->dbUserInfo[0] = (long)this;
462 audio_dbh.dbhBufferPtr[i] = audio_buf[i];
463 }
464
465 /* Create the sound manager channel */
466 channel = (SndChannelPtr)SDL_malloc(sizeof(*channel));
467 if ( channel == NULL ) {
468 SDL_OutOfMemory();
469 return(-1);
470 }
471 if ( spec->channels >= 2 ) {
472 initOptions = initStereo;
473 } else {
474 initOptions = initMono;
475 }
476 channel->userInfo = 0;
477 channel->qLength = 128;
478 if ( SndNewChannel(&channel, sampledSynth, initOptions, 0L) != noErr ) {
479 SDL_SetError("Unable to create audio channel");
480 SDL_free(channel);
481 channel = NULL;
482 return(-1);
483 }
484
485 /* Start playback */
486 if ( SndPlayDoubleBuffer(channel, (SndDoubleBufferHeaderPtr)&audio_dbh)
487 != noErr ) {
488 SDL_SetError("Unable to play double buffered audio");
489 return(-1);
490 }
491
492 return 1;
493}
494
495#endif /* TARGET_API_MAC_CARBON || USE_RYANS_SOUNDCODE */
496
diff --git a/apps/plugins/sdl/src/audio/macrom/SDL_romaudio.h b/apps/plugins/sdl/src/audio/macrom/SDL_romaudio.h
deleted file mode 100644
index 90e19c0695..0000000000
--- a/apps/plugins/sdl/src/audio/macrom/SDL_romaudio.h
+++ /dev/null
@@ -1,50 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_romaudio_h
25#define _SDL_romaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* This is Ryan's improved MacOS sound code, with locking support */
30#define USE_RYANS_SOUNDCODE
31
32/* Hidden "this" pointer for the video functions */
33#define _THIS SDL_AudioDevice *this
34
35struct SDL_PrivateAudioData {
36 /* Sound manager audio channel */
37 SndChannelPtr channel;
38#if defined(TARGET_API_MAC_CARBON) || defined(USE_RYANS_SOUNDCODE)
39 /* FIXME: Add Ryan's static data here */
40#else
41 /* Double buffering variables */
42 SndDoubleBufferPtr audio_buf[2];
43#endif
44};
45
46/* Old variable names */
47#define channel (this->hidden->channel)
48#define audio_buf (this->hidden->audio_buf)
49
50#endif /* _SDL_romaudio_h */
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio.c b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio.c
deleted file mode 100644
index 46ba690c3e..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio.c
+++ /dev/null
@@ -1,215 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Audio interrupt variables and callback function
26
27 Patrice Mandin
28*/
29
30#include <unistd.h>
31
32#include <mint/osbind.h>
33#include <mint/falcon.h>
34#include <mint/mintbind.h>
35#include <mint/cookie.h>
36
37#include "SDL_audio.h"
38#include "SDL_mintaudio.h"
39#include "SDL_mintaudio_stfa.h"
40
41/* The audio device */
42
43SDL_AudioDevice *SDL_MintAudio_device;
44Uint8 *SDL_MintAudio_audiobuf[2]; /* Pointers to buffers */
45unsigned long SDL_MintAudio_audiosize; /* Length of audio buffer=spec->size */
46volatile unsigned short SDL_MintAudio_numbuf; /* Buffer to play */
47volatile unsigned short SDL_MintAudio_mutex;
48volatile unsigned long SDL_MintAudio_clocktics;
49cookie_stfa_t *SDL_MintAudio_stfa;
50unsigned short SDL_MintAudio_hasfpu;
51
52/* MiNT thread variables */
53SDL_bool SDL_MintAudio_mint_present;
54SDL_bool SDL_MintAudio_quit_thread;
55SDL_bool SDL_MintAudio_thread_finished;
56long SDL_MintAudio_thread_pid;
57
58/* The callback function, called by each driver whenever needed */
59
60void SDL_MintAudio_Callback(void)
61{
62 Uint8 *buffer;
63 SDL_AudioDevice *audio = SDL_MintAudio_device;
64
65 buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf];
66 SDL_memset(buffer, audio->spec.silence, audio->spec.size);
67
68 if (audio->paused)
69 return;
70
71 if (audio->convert.needed) {
72 int silence;
73
74 if ( audio->convert.src_format == AUDIO_U8 ) {
75 silence = 0x80;
76 } else {
77 silence = 0;
78 }
79 SDL_memset(audio->convert.buf, silence, audio->convert.len);
80 audio->spec.callback(audio->spec.userdata,
81 (Uint8 *)audio->convert.buf,audio->convert.len);
82 SDL_ConvertAudio(&audio->convert);
83 SDL_memcpy(buffer, audio->convert.buf, audio->convert.len_cvt);
84 } else {
85 audio->spec.callback(audio->spec.userdata, buffer, audio->spec.size);
86 }
87}
88
89/* Add a new frequency/clock/predivisor to the current list */
90void SDL_MintAudio_AddFrequency(_THIS, Uint32 frequency, Uint32 clock,
91 Uint32 prediv, int gpio_bits)
92{
93 int i, p;
94
95 if (MINTAUDIO_freqcount==MINTAUDIO_maxfreqs) {
96 return;
97 }
98
99 /* Search where to insert the frequency (highest first) */
100 for (p=0; p<MINTAUDIO_freqcount; p++) {
101 if (frequency > MINTAUDIO_frequencies[p].frequency) {
102 break;
103 }
104 }
105
106 /* Put all following ones farer */
107 if (MINTAUDIO_freqcount>0) {
108 for (i=MINTAUDIO_freqcount; i>p; i--) {
109 SDL_memcpy(&MINTAUDIO_frequencies[i], &MINTAUDIO_frequencies[i-1], sizeof(mint_frequency_t));
110 }
111 }
112
113 /* And insert new one */
114 MINTAUDIO_frequencies[p].frequency = frequency;
115 MINTAUDIO_frequencies[p].masterclock = clock;
116 MINTAUDIO_frequencies[p].predivisor = prediv;
117 MINTAUDIO_frequencies[p].gpio_bits = gpio_bits;
118
119 MINTAUDIO_freqcount++;
120}
121
122/* Search for the nearest frequency */
123int SDL_MintAudio_SearchFrequency(_THIS, int desired_freq)
124{
125 int i;
126
127 /* Only 1 freq ? */
128 if (MINTAUDIO_freqcount==1) {
129 return 0;
130 }
131
132 /* Check the array */
133 for (i=0; i<MINTAUDIO_freqcount; i++) {
134 if (desired_freq >= ((MINTAUDIO_frequencies[i].frequency+
135 MINTAUDIO_frequencies[i+1].frequency)>>1)) {
136 return i;
137 }
138 }
139
140 /* Not in the array, give the latest */
141 return MINTAUDIO_freqcount-1;
142}
143
144/* Check if FPU is present */
145void SDL_MintAudio_CheckFpu(void)
146{
147 long cookie_fpu;
148
149 SDL_MintAudio_hasfpu = 0;
150 if (Getcookie(C__FPU, &cookie_fpu) != C_FOUND) {
151 return;
152 }
153 switch ((cookie_fpu>>16)&0xfffe) {
154 case 2:
155 case 4:
156 case 6:
157 case 8:
158 case 16:
159 SDL_MintAudio_hasfpu = 1;
160 break;
161 }
162}
163
164/* The thread function, used under MiNT with xbios */
165int SDL_MintAudio_Thread(long param)
166{
167 SndBufPtr pointers;
168 SDL_bool buffers_filled[2] = {SDL_FALSE, SDL_FALSE};
169
170 SDL_MintAudio_thread_finished = SDL_FALSE;
171 while (!SDL_MintAudio_quit_thread) {
172 if (Buffptr(&pointers)!=0)
173 continue;
174
175 if (( (unsigned long)pointers.play>=(unsigned long)SDL_MintAudio_audiobuf[0])
176 && ( (unsigned long)pointers.play<=(unsigned long)SDL_MintAudio_audiobuf[1]))
177 {
178 /* DMA is reading buffer #0, setup buffer #1 if not already done */
179 if (!buffers_filled[1]) {
180 SDL_MintAudio_numbuf = 1;
181 SDL_MintAudio_Callback();
182 Setbuffer(0, SDL_MintAudio_audiobuf[1], SDL_MintAudio_audiobuf[1] + SDL_MintAudio_audiosize);
183 buffers_filled[1]=SDL_TRUE;
184 buffers_filled[0]=SDL_FALSE;
185 }
186 } else {
187 /* DMA is reading buffer #1, setup buffer #0 if not already done */
188 if (!buffers_filled[0]) {
189 SDL_MintAudio_numbuf = 0;
190 SDL_MintAudio_Callback();
191 Setbuffer(0, SDL_MintAudio_audiobuf[0], SDL_MintAudio_audiobuf[0] + SDL_MintAudio_audiosize);
192 buffers_filled[0]=SDL_TRUE;
193 buffers_filled[1]=SDL_FALSE;
194 }
195 }
196
197 usleep(100);
198 }
199 SDL_MintAudio_thread_finished = SDL_TRUE;
200 return 0;
201}
202
203void SDL_MintAudio_WaitThread(void)
204{
205 if (!SDL_MintAudio_mint_present)
206 return;
207
208 if (SDL_MintAudio_thread_finished)
209 return;
210
211 SDL_MintAudio_quit_thread = SDL_TRUE;
212 while (!SDL_MintAudio_thread_finished) {
213 Syield();
214 }
215}
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio.h b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio.h
deleted file mode 100644
index ba6056ee3a..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio.h
+++ /dev/null
@@ -1,121 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 MiNT audio driver
26
27 Patrice Mandin
28*/
29
30#ifndef _SDL_mintaudio_h
31#define _SDL_mintaudio_h
32
33#include "../SDL_sysaudio.h"
34#include "SDL_mintaudio_stfa.h"
35
36/* Hidden "this" pointer for the audio functions */
37#define _THIS SDL_AudioDevice *this
38
39/* 16 predivisors with 3 clocks max. */
40#define MINTAUDIO_maxfreqs (16*3)
41
42typedef struct {
43 Uint32 frequency;
44 Uint32 masterclock;
45 Uint32 predivisor;
46 int gpio_bits; /* in case of external clock */
47} mint_frequency_t;
48
49struct SDL_PrivateAudioData {
50 mint_frequency_t frequencies[MINTAUDIO_maxfreqs];
51 int freq_count; /* Number of frequencies in the array */
52 int numfreq; /* Number of selected frequency */
53};
54
55/* Old variable names */
56
57#define MINTAUDIO_frequencies (this->hidden->frequencies)
58#define MINTAUDIO_freqcount (this->hidden->freq_count)
59#define MINTAUDIO_numfreq (this->hidden->numfreq)
60
61/* _MCH cookie (values>>16) */
62enum {
63 MCH_ST=0,
64 MCH_STE,
65 MCH_TT,
66 MCH_F30,
67 MCH_CLONE,
68 MCH_ARANYM
69};
70
71/* Master clocks for replay frequencies */
72#define MASTERCLOCK_STE 8010666 /* Not sure of this one */
73#define MASTERCLOCK_TT 16107953 /* Not sure of this one */
74#define MASTERCLOCK_FALCON1 25175000
75#define MASTERCLOCK_FALCON2 32000000 /* Only usable for DSP56K */
76#define MASTERCLOCK_FALCONEXT -1 /* Clock on DSP56K port, unknown */
77#define MASTERCLOCK_44K 22579200 /* Standard clock for 44.1 Khz */
78#define MASTERCLOCK_48K 24576000 /* Standard clock for 48 Khz */
79
80/* Master clock predivisors */
81#define MASTERPREDIV_STE 160
82#define MASTERPREDIV_TT 320
83#define MASTERPREDIV_FALCON 256
84#define MASTERPREDIV_MILAN 256
85
86/* Variables */
87extern SDL_AudioDevice *SDL_MintAudio_device;
88extern Uint8 *SDL_MintAudio_audiobuf[2]; /* Pointers to buffers */
89extern unsigned long SDL_MintAudio_audiosize; /* Length of audio buffer=spec->size */
90extern volatile unsigned short SDL_MintAudio_numbuf; /* Buffer to play */
91extern volatile unsigned short SDL_MintAudio_mutex;
92extern cookie_stfa_t *SDL_MintAudio_stfa;
93extern volatile unsigned long SDL_MintAudio_clocktics;
94extern unsigned short SDL_MintAudio_hasfpu; /* To preserve fpu registers if needed */
95
96/* MiNT thread variables */
97extern SDL_bool SDL_MintAudio_mint_present;
98extern SDL_bool SDL_MintAudio_quit_thread;
99extern SDL_bool SDL_MintAudio_thread_finished;
100extern long SDL_MintAudio_thread_pid;
101
102/* Functions */
103void SDL_MintAudio_Callback(void);
104void SDL_MintAudio_AddFrequency(_THIS, Uint32 frequency, Uint32 clock,
105 Uint32 prediv, int gpio_bits);
106int SDL_MintAudio_SearchFrequency(_THIS, int desired_freq);
107void SDL_MintAudio_CheckFpu(void);
108
109/* MiNT thread functions */
110int SDL_MintAudio_Thread(long param);
111void SDL_MintAudio_WaitThread(void);
112
113/* ASM interrupt functions */
114void SDL_MintAudio_GsxbInterrupt(void);
115void SDL_MintAudio_EmptyGsxbInterrupt(void);
116void SDL_MintAudio_XbiosInterruptMeasureClock(void);
117void SDL_MintAudio_XbiosInterrupt(void);
118void SDL_MintAudio_Dma8Interrupt(void);
119void SDL_MintAudio_StfaInterrupt(void);
120
121#endif /* _SDL_mintaudio_h */
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_dma8.c b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_dma8.c
deleted file mode 100644
index 61feba3d64..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_dma8.c
+++ /dev/null
@@ -1,357 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 MiNT audio driver
26 using DMA 8bits (hardware access)
27
28 Patrice Mandin
29*/
30
31/* Mint includes */
32#include <mint/osbind.h>
33#include <mint/falcon.h>
34#include <mint/cookie.h>
35
36#include "SDL_audio.h"
37#include "../SDL_audio_c.h"
38#include "../SDL_sysaudio.h"
39
40#include "../../video/ataricommon/SDL_atarimxalloc_c.h"
41
42#include "SDL_mintaudio.h"
43#include "SDL_mintaudio_dma8.h"
44
45/*--- Defines ---*/
46
47#define MINT_AUDIO_DRIVER_NAME "mint_dma8"
48
49/* Debug print info */
50#define DEBUG_NAME "audio:dma8: "
51#if 0
52#define DEBUG_PRINT(what) \
53 { \
54 printf what; \
55 }
56#else
57#define DEBUG_PRINT(what)
58#endif
59
60/*--- Static variables ---*/
61
62static long cookie_snd, cookie_mch;
63
64/*--- Audio driver functions ---*/
65
66static void Mint_CloseAudio(_THIS);
67static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec);
68static void Mint_LockAudio(_THIS);
69static void Mint_UnlockAudio(_THIS);
70
71/* To check/init hardware audio */
72static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec);
73
74/* Functions called in supervisor mode */
75static void Mint_InitDma(void);
76static void Mint_StopReplay(void);
77static void Mint_StartReplay(void);
78
79/*--- Audio driver bootstrap functions ---*/
80
81static int Audio_Available(void)
82{
83 const char *envr = SDL_getenv("SDL_AUDIODRIVER");
84
85 /* Check if user asked a different audio driver */
86 if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) {
87 DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n"));
88 return 0;
89 }
90
91 /* Cookie _MCH present ? if not, assume ST machine */
92 if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) {
93 cookie_mch = MCH_ST;
94 }
95
96 /* Cookie _SND present ? if not, assume ST machine */
97 if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) {
98 cookie_snd = SND_PSG;
99 }
100
101 /* Check if we have 8 bits audio */
102 if ((cookie_snd & SND_8BIT)==0) {
103 DEBUG_PRINT((DEBUG_NAME "no 8 bits sound\n"));
104 return(0);
105 }
106
107 /* Check if audio is lockable */
108 if (cookie_snd & SND_16BIT) {
109 if (Locksnd()!=1) {
110 DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n"));
111 return(0);
112 }
113
114 Unlocksnd();
115 }
116
117 DEBUG_PRINT((DEBUG_NAME "8 bits audio available!\n"));
118 return(1);
119}
120
121static void Audio_DeleteDevice(SDL_AudioDevice *device)
122{
123 SDL_free(device->hidden);
124 SDL_free(device);
125}
126
127static SDL_AudioDevice *Audio_CreateDevice(int devindex)
128{
129 SDL_AudioDevice *this;
130
131 /* Initialize all variables that we clean on shutdown */
132 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
133 if ( this ) {
134 SDL_memset(this, 0, (sizeof *this));
135 this->hidden = (struct SDL_PrivateAudioData *)
136 SDL_malloc((sizeof *this->hidden));
137 }
138 if ( (this == NULL) || (this->hidden == NULL) ) {
139 SDL_OutOfMemory();
140 if ( this ) {
141 SDL_free(this);
142 }
143 return(0);
144 }
145 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
146
147 /* Set the function pointers */
148 this->OpenAudio = Mint_OpenAudio;
149 this->CloseAudio = Mint_CloseAudio;
150 this->LockAudio = Mint_LockAudio;
151 this->UnlockAudio = Mint_UnlockAudio;
152 this->free = Audio_DeleteDevice;
153
154 return this;
155}
156
157AudioBootStrap MINTAUDIO_DMA8_bootstrap = {
158 MINT_AUDIO_DRIVER_NAME, "MiNT DMA 8 bits audio driver",
159 Audio_Available, Audio_CreateDevice
160};
161
162static void Mint_LockAudio(_THIS)
163{
164 Supexec(Mint_StopReplay);
165}
166
167static void Mint_UnlockAudio(_THIS)
168{
169 Supexec(Mint_StartReplay);
170}
171
172static void Mint_CloseAudio(_THIS)
173{
174 Supexec(Mint_StopReplay);
175
176 DEBUG_PRINT((DEBUG_NAME "closeaudio: replay stopped\n"));
177
178 /* Disable interrupt */
179 Jdisint(MFP_DMASOUND);
180
181 DEBUG_PRINT((DEBUG_NAME "closeaudio: interrupt disabled\n"));
182
183 /* Wait if currently playing sound */
184 while (SDL_MintAudio_mutex != 0) {
185 }
186
187 DEBUG_PRINT((DEBUG_NAME "closeaudio: no more interrupt running\n"));
188
189 /* Clear buffers */
190 if (SDL_MintAudio_audiobuf[0]) {
191 Mfree(SDL_MintAudio_audiobuf[0]);
192 SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL;
193 }
194
195 DEBUG_PRINT((DEBUG_NAME "closeaudio: buffers freed\n"));
196}
197
198static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec)
199{
200 int i, masterprediv, sfreq;
201 unsigned long masterclock;
202
203 DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ",spec->format & 0x00ff));
204 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
205 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
206 DEBUG_PRINT(("channels=%d, ", spec->channels));
207 DEBUG_PRINT(("freq=%d\n", spec->freq));
208
209 if (spec->channels > 2)
210 spec->channels = 2;
211
212 /* Check formats available */
213 spec->format = AUDIO_S8;
214
215 /* Calculate and select the closest frequency */
216 sfreq=0;
217 masterclock=MASTERCLOCK_STE;
218 masterprediv=MASTERPREDIV_STE;
219 switch(cookie_mch>>16) {
220/*
221 case MCH_STE:
222 masterclock=MASTERCLOCK_STE;
223 masterprediv=MASTERPREDIV_STE;
224 break;
225*/
226 case MCH_TT:
227 masterclock=MASTERCLOCK_TT;
228 masterprediv=MASTERPREDIV_TT;
229 break;
230 case MCH_F30:
231 case MCH_ARANYM:
232 masterclock=MASTERCLOCK_FALCON1;
233 masterprediv=MASTERPREDIV_FALCON;
234 sfreq=1;
235 break;
236 }
237
238 MINTAUDIO_freqcount=0;
239 for (i=sfreq;i<4;i++) {
240 SDL_MintAudio_AddFrequency(this, masterclock/(masterprediv*(1<<i)),
241 masterclock, i-sfreq, -1);
242 }
243
244#if 1
245 for (i=0; i<MINTAUDIO_freqcount; i++) {
246 DEBUG_PRINT((DEBUG_NAME "freq %d: %lu Hz, clock %lu, prediv %d\n",
247 i, MINTAUDIO_frequencies[i].frequency, MINTAUDIO_frequencies[i].masterclock,
248 MINTAUDIO_frequencies[i].predivisor
249 ));
250 }
251#endif
252
253 MINTAUDIO_numfreq=SDL_MintAudio_SearchFrequency(this, spec->freq);
254 spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency;
255
256 DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff));
257 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
258 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
259 DEBUG_PRINT(("channels=%d, ", spec->channels));
260 DEBUG_PRINT(("freq=%d\n", spec->freq));
261
262 return 0;
263}
264
265static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec)
266{
267 SDL_MintAudio_device = this;
268
269 /* Check audio capabilities */
270 if (Mint_CheckAudio(this, spec)==-1) {
271 return -1;
272 }
273
274 SDL_CalculateAudioSpec(spec);
275
276 /* Allocate memory for audio buffers in DMA-able RAM */
277 DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size));
278
279 SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM);
280 if (SDL_MintAudio_audiobuf[0]==NULL) {
281 SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer");
282 return (-1);
283 }
284 SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ;
285 SDL_MintAudio_numbuf=0;
286 SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2);
287 SDL_MintAudio_audiosize = spec->size;
288 SDL_MintAudio_mutex = 0;
289
290 DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0]));
291 DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1]));
292
293 SDL_MintAudio_CheckFpu();
294
295 /* Set replay tracks */
296 if (cookie_snd & SND_16BIT) {
297 Settracks(0,0);
298 Setmontracks(0);
299 }
300
301 Supexec(Mint_InitDma);
302
303 /* Set interrupt */
304 Jdisint(MFP_DMASOUND);
305 Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_Dma8Interrupt);
306 Jenabint(MFP_DMASOUND);
307
308 if (cookie_snd & SND_16BIT) {
309 if (Setinterrupt(SI_TIMERA, SI_PLAY)<0) {
310 DEBUG_PRINT((DEBUG_NAME "Setinterrupt() failed\n"));
311 }
312 }
313
314 Supexec(Mint_StartReplay);
315
316 return(1); /* We don't use threaded audio */
317}
318
319/* Functions called in supervisor mode */
320
321static void Mint_InitDma(void)
322{
323 unsigned long buffer;
324 unsigned char mode;
325 SDL_AudioDevice *this = SDL_MintAudio_device;
326
327 Mint_StopReplay();
328
329 /* Set buffer */
330 buffer = (unsigned long) SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf];
331 DMAAUDIO_IO.start_high = (buffer>>16) & 255;
332 DMAAUDIO_IO.start_mid = (buffer>>8) & 255;
333 DMAAUDIO_IO.start_low = buffer & 255;
334
335 buffer += SDL_MintAudio_audiosize;
336 DMAAUDIO_IO.end_high = (buffer>>16) & 255;
337 DMAAUDIO_IO.end_mid = (buffer>>8) & 255;
338 DMAAUDIO_IO.end_low = buffer & 255;
339
340 mode = 3-MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor;
341 if (this->spec.channels==1) {
342 mode |= 1<<7;
343 }
344 DMAAUDIO_IO.sound_ctrl = mode;
345}
346
347static void Mint_StopReplay(void)
348{
349 /* Stop replay */
350 DMAAUDIO_IO.control=0;
351}
352
353static void Mint_StartReplay(void)
354{
355 /* Start replay */
356 DMAAUDIO_IO.control=3;
357}
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_dma8.h b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_dma8.h
deleted file mode 100644
index a52e5db7a5..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_dma8.h
+++ /dev/null
@@ -1,85 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 DMA 8bits and Falcon Codec audio definitions
26
27 Patrice Mandin, Didier Méquignon
28*/
29
30#ifndef _SDL_mintaudio_dma8_h
31#define _SDL_mintaudio_dma8_h
32
33#define DMAAUDIO_IO_BASE (0xffff8900)
34struct DMAAUDIO_IO_S {
35 unsigned char int_ctrl;
36 unsigned char control;
37
38 unsigned char dummy1;
39 unsigned char start_high;
40 unsigned char dummy2;
41 unsigned char start_mid;
42 unsigned char dummy3;
43 unsigned char start_low;
44
45 unsigned char dummy4;
46 unsigned char cur_high;
47 unsigned char dummy5;
48 unsigned char cur_mid;
49 unsigned char dummy6;
50 unsigned char cur_low;
51
52 unsigned char dummy7;
53 unsigned char end_high;
54 unsigned char dummy8;
55 unsigned char end_mid;
56 unsigned char dummy9;
57 unsigned char end_low;
58
59 unsigned char dummy10[12];
60
61 unsigned char track_ctrl; /* CODEC only */
62 unsigned char sound_ctrl;
63 unsigned short sound_data;
64 unsigned short sound_mask;
65
66 unsigned char dummy11[10];
67
68 unsigned short dev_ctrl;
69 unsigned short dest_ctrl;
70 unsigned short sync_div;
71 unsigned char track_rec;
72 unsigned char adderin_input;
73 unsigned char channel_input;
74 unsigned char channel_amplification;
75 unsigned char channel_reduction;
76
77 unsigned char dummy12[6];
78
79 unsigned char data_direction;
80 unsigned char dummy13;
81 unsigned char dev_data;
82};
83#define DMAAUDIO_IO ((*(volatile struct DMAAUDIO_IO_S *)DMAAUDIO_IO_BASE))
84
85#endif /* _SDL_mintaudio_dma8_h */
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_gsxb.c b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_gsxb.c
deleted file mode 100644
index 8d7716a137..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_gsxb.c
+++ /dev/null
@@ -1,436 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 MiNT audio driver
26 using XBIOS functions (GSXB compatible driver)
27
28 Patrice Mandin
29*/
30
31/* Mint includes */
32#include <mint/osbind.h>
33#include <mint/falcon.h>
34#include <mint/cookie.h>
35
36#include "SDL_audio.h"
37#include "../SDL_audio_c.h"
38#include "../SDL_sysaudio.h"
39
40#include "../../video/ataricommon/SDL_atarimxalloc_c.h"
41
42#include "SDL_mintaudio.h"
43#include "SDL_mintaudio_gsxb.h"
44
45/*--- Defines ---*/
46
47#define MINT_AUDIO_DRIVER_NAME "mint_gsxb"
48
49/* Debug print info */
50#define DEBUG_NAME "audio:gsxb: "
51#if 0
52#define DEBUG_PRINT(what) \
53 { \
54 printf what; \
55 }
56#else
57#define DEBUG_PRINT(what)
58#endif
59
60/*--- Static variables ---*/
61
62static long cookie_snd, cookie_gsxb;
63
64/*--- Audio driver functions ---*/
65
66static void Mint_CloseAudio(_THIS);
67static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec);
68static void Mint_LockAudio(_THIS);
69static void Mint_UnlockAudio(_THIS);
70
71/* To check/init hardware audio */
72static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec);
73static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec);
74
75/* GSXB callbacks */
76static void Mint_GsxbInterrupt(void);
77static void Mint_GsxbNullInterrupt(void);
78
79/*--- Audio driver bootstrap functions ---*/
80
81static int Audio_Available(void)
82{
83 const char *envr = SDL_getenv("SDL_AUDIODRIVER");
84
85 /* Check if user asked a different audio driver */
86 if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) {
87 DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n"));
88 return(0);
89 }
90
91 /* Cookie _SND present ? if not, assume ST machine */
92 if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) {
93 cookie_snd = SND_PSG;
94 }
95
96 /* Check if we have 16 bits audio */
97 if ((cookie_snd & SND_16BIT)==0) {
98 DEBUG_PRINT((DEBUG_NAME "no 16 bits sound\n"));
99 return(0);
100 }
101
102 /* Cookie GSXB present ? */
103 cookie_gsxb = (Getcookie(C_GSXB, &cookie_gsxb) == C_FOUND);
104
105 /* Is it GSXB ? */
106 if (((cookie_snd & SND_GSXB)==0) || (cookie_gsxb==0)) {
107 DEBUG_PRINT((DEBUG_NAME "no GSXB audio\n"));
108 return(0);
109 }
110
111 /* Check if audio is lockable */
112 if (Locksnd()!=1) {
113 DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n"));
114 return(0);
115 }
116
117 Unlocksnd();
118
119 DEBUG_PRINT((DEBUG_NAME "GSXB audio available!\n"));
120 return(1);
121}
122
123static void Audio_DeleteDevice(SDL_AudioDevice *device)
124{
125 SDL_free(device->hidden);
126 SDL_free(device);
127}
128
129static SDL_AudioDevice *Audio_CreateDevice(int devindex)
130{
131 SDL_AudioDevice *this;
132
133 /* Initialize all variables that we clean on shutdown */
134 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
135 if ( this ) {
136 SDL_memset(this, 0, (sizeof *this));
137 this->hidden = (struct SDL_PrivateAudioData *)
138 SDL_malloc((sizeof *this->hidden));
139 }
140 if ( (this == NULL) || (this->hidden == NULL) ) {
141 SDL_OutOfMemory();
142 if ( this ) {
143 SDL_free(this);
144 }
145 return(0);
146 }
147 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
148
149 /* Set the function pointers */
150 this->OpenAudio = Mint_OpenAudio;
151 this->CloseAudio = Mint_CloseAudio;
152 this->LockAudio = Mint_LockAudio;
153 this->UnlockAudio = Mint_UnlockAudio;
154 this->free = Audio_DeleteDevice;
155
156 return this;
157}
158
159AudioBootStrap MINTAUDIO_GSXB_bootstrap = {
160 MINT_AUDIO_DRIVER_NAME, "MiNT GSXB audio driver",
161 Audio_Available, Audio_CreateDevice
162};
163
164static void Mint_LockAudio(_THIS)
165{
166 /* Stop replay */
167 Buffoper(0);
168}
169
170static void Mint_UnlockAudio(_THIS)
171{
172 /* Restart replay */
173 Buffoper(SB_PLA_ENA|SB_PLA_RPT);
174}
175
176static void Mint_CloseAudio(_THIS)
177{
178 /* Stop replay */
179 Buffoper(0);
180
181 /* Uninstall interrupt */
182 if (NSetinterrupt(2, SI_NONE, Mint_GsxbNullInterrupt)<0) {
183 DEBUG_PRINT((DEBUG_NAME "NSetinterrupt() failed in close\n"));
184 }
185
186 /* Wait if currently playing sound */
187 while (SDL_MintAudio_mutex != 0) {
188 }
189
190 /* Clear buffers */
191 if (SDL_MintAudio_audiobuf[0]) {
192 Mfree(SDL_MintAudio_audiobuf[0]);
193 SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL;
194 }
195
196 /* Unlock sound system */
197 Unlocksnd();
198}
199
200static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec)
201{
202 long snd_format = 0;
203 int i, resolution, format_signed, format_bigendian;
204 Uint16 test_format = SDL_FirstAudioFormat(spec->format);
205 int valid_datatype = 0;
206
207 resolution = spec->format & 0x00ff;
208 format_signed = ((spec->format & 0x8000)!=0);
209 format_bigendian = ((spec->format & 0x1000)!=0);
210
211 DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ",spec->format & 0x00ff));
212 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
213 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
214 DEBUG_PRINT(("channels=%d, ", spec->channels));
215 DEBUG_PRINT(("freq=%d\n", spec->freq));
216
217 if (spec->channels > 2) {
218 spec->channels = 2; /* no more than stereo! */
219 }
220
221 while ((!valid_datatype) && (test_format)) {
222 /* Check formats available */
223 snd_format = Sndstatus(SND_QUERYFORMATS);
224 spec->format = test_format;
225 resolution = spec->format & 0xff;
226 format_signed = (spec->format & (1<<15));
227 format_bigendian = (spec->format & (1<<12));
228 switch (test_format) {
229 case AUDIO_U8:
230 case AUDIO_S8:
231 if (snd_format & SND_FORMAT8) {
232 valid_datatype = 1;
233 snd_format = Sndstatus(SND_QUERY8BIT);
234 }
235 break;
236
237 case AUDIO_U16LSB:
238 case AUDIO_S16LSB:
239 case AUDIO_U16MSB:
240 case AUDIO_S16MSB:
241 if (snd_format & SND_FORMAT16) {
242 valid_datatype = 1;
243 snd_format = Sndstatus(SND_QUERY16BIT);
244 }
245 break;
246
247 default:
248 test_format = SDL_NextAudioFormat();
249 break;
250 }
251 }
252
253 if (!valid_datatype) {
254 SDL_SetError("Unsupported audio format");
255 return (-1);
256 }
257
258 /* Check signed/unsigned format */
259 if (format_signed) {
260 if (snd_format & SND_FORMATSIGNED) {
261 /* Ok */
262 } else if (snd_format & SND_FORMATUNSIGNED) {
263 /* Give unsigned format */
264 spec->format = spec->format & (~0x8000);
265 }
266 } else {
267 if (snd_format & SND_FORMATUNSIGNED) {
268 /* Ok */
269 } else if (snd_format & SND_FORMATSIGNED) {
270 /* Give signed format */
271 spec->format |= 0x8000;
272 }
273 }
274
275 if (format_bigendian) {
276 if (snd_format & SND_FORMATBIGENDIAN) {
277 /* Ok */
278 } else if (snd_format & SND_FORMATLITTLEENDIAN) {
279 /* Give little endian format */
280 spec->format = spec->format & (~0x1000);
281 }
282 } else {
283 if (snd_format & SND_FORMATLITTLEENDIAN) {
284 /* Ok */
285 } else if (snd_format & SND_FORMATBIGENDIAN) {
286 /* Give big endian format */
287 spec->format |= 0x1000;
288 }
289 }
290
291 /* Calculate and select the closest frequency */
292 MINTAUDIO_freqcount=0;
293 for (i=1;i<4;i++) {
294 SDL_MintAudio_AddFrequency(this,
295 MASTERCLOCK_44K/(MASTERPREDIV_MILAN*(1<<i)), MASTERCLOCK_44K,
296 (1<<i)-1, -1);
297 }
298
299#if 1
300 for (i=0; i<MINTAUDIO_freqcount; i++) {
301 DEBUG_PRINT((DEBUG_NAME "freq %d: %lu Hz, clock %lu, prediv %d\n",
302 i, MINTAUDIO_frequencies[i].frequency, MINTAUDIO_frequencies[i].masterclock,
303 MINTAUDIO_frequencies[i].predivisor
304 ));
305 }
306#endif
307
308 MINTAUDIO_numfreq=SDL_MintAudio_SearchFrequency(this, spec->freq);
309 spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency;
310
311 DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff));
312 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
313 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
314 DEBUG_PRINT(("channels=%d, ", spec->channels));
315 DEBUG_PRINT(("freq=%d\n", spec->freq));
316
317 return 0;
318}
319
320static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec)
321{
322 int channels_mode, prediv;
323 void *buffer;
324
325 /* Stop currently playing sound */
326 Buffoper(0);
327
328 /* Set replay tracks */
329 Settracks(0,0);
330 Setmontracks(0);
331
332 /* Select replay format */
333 switch (spec->format & 0xff) {
334 case 8:
335 if (spec->channels==2) {
336 channels_mode=STEREO8;
337 } else {
338 channels_mode=MONO8;
339 }
340 break;
341 case 16:
342 if (spec->channels==2) {
343 channels_mode=STEREO16;
344 } else {
345 channels_mode=MONO16;
346 }
347 break;
348 default:
349 channels_mode=STEREO16;
350 break;
351 }
352 if (Setmode(channels_mode)<0) {
353 DEBUG_PRINT((DEBUG_NAME "Setmode() failed\n"));
354 }
355
356 prediv = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor;
357 Devconnect(DMAPLAY, DAC, CLKEXT, prediv, 1);
358
359 /* Set buffer */
360 buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf];
361 if (Setbuffer(0, buffer, buffer + spec->size)<0) {
362 DEBUG_PRINT((DEBUG_NAME "Setbuffer() failed\n"));
363 }
364
365 /* Install interrupt */
366 if (NSetinterrupt(2, SI_PLAY, Mint_GsxbInterrupt)<0) {
367 DEBUG_PRINT((DEBUG_NAME "NSetinterrupt() failed\n"));
368 }
369
370 /* Go */
371 Buffoper(SB_PLA_ENA|SB_PLA_RPT);
372 DEBUG_PRINT((DEBUG_NAME "hardware initialized\n"));
373}
374
375static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec)
376{
377 /* Lock sound system */
378 if (Locksnd()!=1) {
379 SDL_SetError("Mint_OpenAudio: Audio system already in use");
380 return(-1);
381 }
382
383 SDL_MintAudio_device = this;
384
385 /* Check audio capabilities */
386 if (Mint_CheckAudio(this, spec)==-1) {
387 return -1;
388 }
389
390 SDL_CalculateAudioSpec(spec);
391
392 /* Allocate memory for audio buffers in DMA-able RAM */
393 DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size));
394
395 SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM);
396 if (SDL_MintAudio_audiobuf[0]==NULL) {
397 SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer");
398 return (-1);
399 }
400 SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ;
401 SDL_MintAudio_numbuf=0;
402 SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2);
403 SDL_MintAudio_audiosize = spec->size;
404 SDL_MintAudio_mutex = 0;
405
406 DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0]));
407 DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1]));
408
409 SDL_MintAudio_CheckFpu();
410
411 /* Setup audio hardware */
412 Mint_InitAudio(this, spec);
413
414 return(1); /* We don't use threaded audio */
415}
416
417static void Mint_GsxbInterrupt(void)
418{
419 Uint8 *newbuf;
420
421 if (SDL_MintAudio_mutex)
422 return;
423
424 SDL_MintAudio_mutex=1;
425
426 SDL_MintAudio_numbuf ^= 1;
427 SDL_MintAudio_Callback();
428 newbuf = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf];
429 Setbuffer(0, newbuf, newbuf + SDL_MintAudio_audiosize);
430
431 SDL_MintAudio_mutex=0;
432}
433
434static void Mint_GsxbNullInterrupt(void)
435{
436}
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_gsxb.h b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_gsxb.h
deleted file mode 100644
index aee26b7ee3..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_gsxb.h
+++ /dev/null
@@ -1,104 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * GSXB audio definitions
26 *
27 * Patrice Mandin
28 */
29
30#ifndef _SDL_mintaudio_gsxb_h
31#define _SDL_mintaudio_gsxb_h
32
33#include <mint/falcon.h> /* for trap_14_xxx macros */
34
35/* Bit 5 in cookie _SND */
36
37#define SND_GSXB (1<<5)
38
39/* NSoundcmd modes */
40
41#define SETRATE 7 /* Set sample rate */
42#define SET8BITFORMAT 8 /* 8 bits format */
43#define SET16BITFORMAT 9 /* 16 bits format */
44#define SET24BITFORMAT 10 /* 24 bits format */
45#define SET32BITFORMAT 11 /* 32 bits format */
46#define LTATTEN_MASTER 12 /* Attenuation */
47#define RTATTEN_MASTER 13
48#define LTATTEN_MICIN 14
49#define RTATTEN_MICIN 15
50#define LTATTEN_FMGEN 16
51#define RTATTEN_FMGEN 17
52#define LTATTEN_LINEIN 18
53#define RTATTEN_LINEIN 19
54#define LTATTEN_CDIN 20
55#define RTATTEN_CDIN 21
56#define LTATTEN_VIDIN 22
57#define RTATTEN_VIDIN 23
58#define LTATTEN_AUXIN 24
59#define RTATTEN_AUXIN 25
60
61/* Setmode modes */
62
63#define MONO16 3
64#define STEREO24 4
65#define STEREO32 5
66#define MONO24 6
67#define MONO32 7
68
69/* Sndstatus modes */
70
71#define SND_QUERYFORMATS 2
72#define SND_QUERYMIXERS 3
73#define SND_QUERYSOURCES 4
74#define SND_QUERYDUPLEX 5
75#define SND_QUERY8BIT 8
76#define SND_QUERY16BIT 9
77#define SND_QUERY24BIT 10
78#define SND_QUERY32BIT 11
79
80#define SND_FORMAT8 (1<<0)
81#define SND_FORMAT16 (1<<1)
82#define SND_FORMAT24 (1<<2)
83#define SND_FORMAT32 (1<<3)
84
85#define SND_FORMATSIGNED (1<<0)
86#define SND_FORMATUNSIGNED (1<<1)
87#define SND_FORMATBIGENDIAN (1<<2)
88#define SND_FORMATLITTLEENDIAN (1<<3)
89
90/* Devconnect prescalers */
91
92#define CLK_44K 1
93#define CLK_22K 3
94#define CLK_11K 7
95
96/* Extra xbios functions */
97
98#define NSoundcmd(mode,data,data2) \
99 (long)trap_14_wwl((short)130,(short)(mode),(short)(data),(long)(data2))
100#define NSetinterrupt(src_inter,cause,inth_addr) \
101 (long)trap_14_wwwl((short)135,(short)(src_inter),(short)(cause), \
102 (long)(inth_addr))
103
104#endif /* _SDL_mintaudio_gsxb_h */
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_it.S b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_it.S
deleted file mode 100644
index a2ecac4c65..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_it.S
+++ /dev/null
@@ -1,386 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/*
24 Audio interrupts
25
26 Patrice Mandin, Didier Méquignon
27 */
28
29 .text
30
31 .globl _SDL_MintAudio_Callback
32
33 .globl _SDL_MintAudio_XbiosInterrupt
34 .globl _SDL_MintAudio_XbiosInterruptMeasureClock
35 .globl _SDL_MintAudio_Dma8Interrupt
36 .globl _SDL_MintAudio_StfaInterrupt
37
38 .globl _SDL_MintAudio_mutex
39 .globl _SDL_MintAudio_audiobuf
40 .globl _SDL_MintAudio_numbuf
41 .globl _SDL_MintAudio_audiosize
42 .globl _SDL_MintAudio_clocktics
43 .globl _SDL_MintAudio_hasfpu
44
45 .globl _SDL_MintAudio_stfa
46
47/*
48 How it works:
49 - Audio is playing buffer #0 (resp. #1)
50 - We must calculate a sample in buffer #1 (resp. #0)
51 so we first call the callback to do it
52 - Then we swap the buffers
53*/
54
55#define savptr 0x4a2
56#define savamt 0x46
57
58/*--- Save/restore FPU context ---*/
59
60#if defined(__mcoldfire__)
61
62#define SAVE_FPU_CONTEXT \
63 lea sp@(-216),sp; \
64 fsave sp@; \
65 fmovel fpiar,sp@-; \
66 lea sp@(-64),sp; \
67 fmovemd fp0-fp7,sp@
68
69#define RESTORE_FPU_CONTEXT \
70 fmovemd sp@,fp0-fp7; \
71 lea sp@(64),sp; \
72 fmovel sp@+,fpiar; \
73 frestore sp@; \
74 lea sp@(216),sp
75
76#else
77
78#define SAVE_FPU_CONTEXT \
79 .chip 68k/68881; \
80 fsave sp@-; \
81 fmoveml fpcr/fpsr/fpiar,sp@-; \
82 fmovemx fp0-fp7,sp@-; \
83 .chip 68k
84
85#define RESTORE_FPU_CONTEXT \
86 .chip 68k/68881; \
87 fmovemx sp@+,fp0-fp7; \
88 fmoveml sp@+,fpcr/fpsr/fpiar; \
89 frestore sp@+; \
90 .chip 68k
91
92#endif
93
94/*--- Xbios interrupt vector to measure Falcon external clock ---*/
95
96_SDL_MintAudio_XbiosInterruptMeasureClock: /* 1 mS */
97#if defined(__mcoldfire__)
98 movel d0,sp@-
99
100 moveql #0,d0
101 btst d0,0xFFFF8901:w /* state DMA sound */
102#else
103 btst #0,0xFFFF8901:w /* state DMA sound */
104#endif
105 beqs SDL_MintAudio_EndIntMeasure
106 addql #1,_SDL_MintAudio_clocktics
107SDL_MintAudio_EndIntMeasure:
108#if defined(__mcoldfire__)
109 moveql #5,d0
110 bclr d0,0xFFFFFA0F:w /* Clear service bit */
111
112 movel sp@+,d0
113#else
114 bclr #5,0xFFFFFA0F:w /* Clear service bit */
115#endif
116 rte
117
118/*--- Xbios interrupt vector ---*/
119
120_SDL_MintAudio_XbiosInterrupt:
121#if defined(__mcoldfire__)
122 lea sp@(-60),sp
123 moveml d0-d7/a0-a6,sp@
124#else
125 moveml d0-d7/a0-a6,sp@-
126#endif
127
128 /* Reenable interrupts, so other interrupts can work */
129 movew #0x2300,sr
130
131 /* Clear service bit, so other MFP interrupts can work */
132#if defined(__mcoldfire__)
133 moveql #5,d0
134 bclr d0,0xfffffa0f:w
135#else
136 bclr #5,0xfffffa0f:w
137#endif
138
139 /* Check if we are not already running */
140 tstw _SDL_MintAudio_mutex
141 bne SDL_MintAudio_XbiosEnd
142
143#if defined(__mcoldfire__)
144 movew _SDL_MintAudio_mutex,d0
145 notl d0
146 movew d0,_SDL_MintAudio_mutex
147
148 movew _SDL_MintAudio_numbuf,d1
149 eorl #1,d1
150 movew d1,_SDL_MintAudio_numbuf
151#else
152 notw _SDL_MintAudio_mutex
153
154 /* Swap buffers */
155 eorw #1,_SDL_MintAudio_numbuf
156#endif
157
158 /* Save FPU if needed */
159 tstw _SDL_MintAudio_hasfpu
160 beqs SDL_MintAudio_Xbios_nofpu1
161 SAVE_FPU_CONTEXT
162SDL_MintAudio_Xbios_nofpu1:
163
164 /* Callback */
165 jsr _SDL_MintAudio_Callback
166
167 /* Restore FPU if needed */
168 tstw _SDL_MintAudio_hasfpu
169 beqs SDL_MintAudio_Xbios_nofpu2
170 RESTORE_FPU_CONTEXT
171SDL_MintAudio_Xbios_nofpu2:
172
173 /* Reserve space for registers */
174#if defined(__mcoldfire__)
175 movel #savamt,d0
176 subl d0,savptr
177#else
178 subl #savamt,savptr
179#endif
180
181 /* Set new buffer */
182
183 moveq #0,d0
184 movel _SDL_MintAudio_audiosize,d1
185
186 movew _SDL_MintAudio_numbuf,d0
187 lsll #2,d0
188 lea _SDL_MintAudio_audiobuf,a0
189 movel a0@(d0:l),a1
190
191 lea a1@(d1:l),a2
192
193 movel a2,sp@-
194 movel a1,sp@-
195 clrw sp@-
196 movew #131,sp@-
197 trap #14
198 lea sp@(12),sp
199
200 /* Restore registers space */
201#if defined(__mcoldfire__)
202 movel #savamt,d0
203 addl d0,savptr
204#else
205 addl #savamt,savptr
206#endif
207
208 clrw _SDL_MintAudio_mutex
209SDL_MintAudio_XbiosEnd:
210#if defined(__mcoldfire__)
211 moveml sp@,d0-d7/a0-a6
212 lea sp@(60),sp
213#else
214 moveml sp@+,d0-d7/a0-a6
215#endif
216 rte
217
218/*--- DMA 8 bits interrupt vector ---*/
219
220_SDL_MintAudio_Dma8Interrupt:
221#if defined(__mcoldfire__)
222 lea sp@(-16),sp
223 moveml d0-d1/a0-a1,sp@
224#else
225 moveml d0-d1/a0-a1,sp@-
226#endif
227
228 /* Reenable interrupts, so other interrupts can work */
229 movew #0x2300,sr
230
231 /* Clear service bit, so other MFP interrupts can work */
232#if defined(__mcoldfire__)
233 moveql #5,d0
234 bclr d0,0xfffffa0f:w
235#else
236 bclr #5,0xfffffa0f:w
237#endif
238 /* Check if we are not already running */
239 tstw _SDL_MintAudio_mutex
240 bne SDL_MintAudio_Dma8End
241
242#if defined(__mcoldfire__)
243 movew _SDL_MintAudio_mutex,d0
244 notl d0
245 movew d0,_SDL_MintAudio_mutex
246
247 movew _SDL_MintAudio_numbuf,d1
248 eorl #1,d1
249 movew d1,_SDL_MintAudio_numbuf
250#else
251 notw _SDL_MintAudio_mutex
252
253 /* Swap buffers */
254 eorw #1,_SDL_MintAudio_numbuf
255#endif
256
257 /* Save FPU if needed */
258 tstw _SDL_MintAudio_hasfpu
259 beqs SDL_MintAudio_Dma8_nofpu1
260 SAVE_FPU_CONTEXT
261SDL_MintAudio_Dma8_nofpu1:
262
263 /* Callback */
264 jsr _SDL_MintAudio_Callback
265
266 /* Restore FPU if needed */
267 tstw _SDL_MintAudio_hasfpu
268 beqs SDL_MintAudio_Dma8_nofpu2
269 RESTORE_FPU_CONTEXT
270SDL_MintAudio_Dma8_nofpu2:
271
272 /* Set new buffer */
273
274 moveq #0,d0
275
276 movew _SDL_MintAudio_numbuf,d0
277 lsll #2,d0
278 lea _SDL_MintAudio_audiobuf,a0
279 movel a0@(d0:l),d1
280
281 /* Modify DMA addresses */
282 lea 0xffff8900:w,a0
283
284 movel d1,d0
285
286 moveb d0,a0@(0x07) /* Start address */
287 lsrl #8,d0
288 moveb d0,a0@(0x05)
289 lsrl #8,d0
290 moveb d0,a0@(0x03)
291
292 addl _SDL_MintAudio_audiosize,d1
293
294 movel d1,d0
295
296 moveb d0,a0@(0x13) /* End address */
297 lsrl #8,d0
298 moveb d0,a0@(0x11)
299 lsrl #8,d0
300 moveb d0,a0@(0x0f)
301
302 clrw _SDL_MintAudio_mutex
303SDL_MintAudio_Dma8End:
304#if defined(__mcoldfire__)
305 moveml sp@,d0-d1/a0-a1
306 lea sp@(16),sp
307#else
308 moveml sp@+,d0-d1/a0-a1
309#endif
310 rte
311
312/*--- STFA interrupt vector ---*/
313
314STFA_SOUND_START = 6
315STFA_SOUND_END = STFA_SOUND_START+8
316
317_SDL_MintAudio_StfaInterrupt:
318 /* Reenable interrupts, so other interrupts can work */
319 movew #0x2300,sr
320
321 /* Check if we are not already running */
322 tstw _SDL_MintAudio_mutex
323
324#if defined(__mcoldfire__)
325 bne SDL_MintAudio_StfaEnd
326
327 lea sp@(-60),sp
328 moveml d0-d7/a0-a6,sp@
329
330 movew _SDL_MintAudio_mutex,d0
331 notl d0
332 movew d0,_SDL_MintAudio_mutex
333
334 movew _SDL_MintAudio_numbuf,d1
335 eorl #1,d1
336 movew d1,_SDL_MintAudio_numbuf
337#else
338 bnes SDL_MintAudio_StfaEnd
339
340 moveml d0-d7/a0-a6,sp@-
341
342 notw _SDL_MintAudio_mutex
343
344 /* Swap buffers */
345 eorw #1,_SDL_MintAudio_numbuf
346#endif
347
348 /* Save FPU if needed */
349 tstw _SDL_MintAudio_hasfpu
350 beqs SDL_MintAudio_Stfa_nofpu1
351 SAVE_FPU_CONTEXT
352SDL_MintAudio_Stfa_nofpu1:
353
354 /* Callback */
355 jsr _SDL_MintAudio_Callback
356
357 /* Restore FPU if needed */
358 tstw _SDL_MintAudio_hasfpu
359 beqs SDL_MintAudio_Stfa_nofpu2
360 RESTORE_FPU_CONTEXT
361SDL_MintAudio_Stfa_nofpu2:
362
363 /* Set new buffer */
364
365 moveq #0,d0
366 movel _SDL_MintAudio_stfa,a1
367
368 movew _SDL_MintAudio_numbuf,d0
369 lsll #2,d0
370 lea _SDL_MintAudio_audiobuf,a0
371 movel a0@(d0:l),d1
372
373 /* Modify STFA replay buffers */
374 movel d1,a1@(STFA_SOUND_START)
375 addl _SDL_MintAudio_audiosize,d1
376 movel d1,a1@(STFA_SOUND_END)
377
378#if defined(__mcoldfire__)
379 moveml sp@,d0-d7/a0-a6
380 lea sp@(60),sp
381#else
382 moveml sp@+,d0-d7/a0-a6
383#endif
384 clrw _SDL_MintAudio_mutex
385SDL_MintAudio_StfaEnd:
386 rte
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_mcsn.c b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_mcsn.c
deleted file mode 100644
index 387609b168..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_mcsn.c
+++ /dev/null
@@ -1,405 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 MiNT audio driver
26 using XBIOS functions (MacSound compatible driver)
27
28 Patrice Mandin
29*/
30
31#include <support.h>
32
33/* Mint includes */
34#include <mint/osbind.h>
35#include <mint/falcon.h>
36#include <mint/cookie.h>
37
38#include "SDL_audio.h"
39#include "../SDL_audio_c.h"
40#include "../SDL_sysaudio.h"
41
42#include "../../video/ataricommon/SDL_atarimxalloc_c.h"
43
44#include "SDL_mintaudio.h"
45#include "SDL_mintaudio_mcsn.h"
46
47/*--- Defines ---*/
48
49#define MINT_AUDIO_DRIVER_NAME "mint_mcsn"
50
51/* Debug print info */
52#define DEBUG_NAME "audio:mcsn: "
53#if 0
54#define DEBUG_PRINT(what) \
55 { \
56 printf what; \
57 }
58#else
59#define DEBUG_PRINT(what)
60#endif
61
62/*--- Static variables ---*/
63
64static long cookie_snd, cookie_mch;
65static cookie_mcsn_t *cookie_mcsn;
66
67/*--- Audio driver functions ---*/
68
69static void Mint_CloseAudio(_THIS);
70static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec);
71static void Mint_LockAudio(_THIS);
72static void Mint_UnlockAudio(_THIS);
73
74/* To check/init hardware audio */
75static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec);
76static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec);
77
78/*--- Audio driver bootstrap functions ---*/
79
80static int Audio_Available(void)
81{
82 long dummy;
83 const char *envr = SDL_getenv("SDL_AUDIODRIVER");
84
85 SDL_MintAudio_mint_present = (Getcookie(C_MiNT, &dummy) == C_FOUND);
86
87 /* We can't use XBIOS in interrupt with Magic, don't know about thread */
88 if (Getcookie(C_MagX, &dummy) == C_FOUND) {
89 return(0);
90 }
91
92 /* Check if user asked a different audio driver */
93 if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) {
94 DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n"));
95 return(0);
96 }
97
98 /* Cookie _MCH present ? if not, assume ST machine */
99 if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) {
100 cookie_mch = MCH_ST;
101 }
102
103 /* Cookie _SND present ? if not, assume ST machine */
104 if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) {
105 cookie_snd = SND_PSG;
106 }
107
108 /* Check if we have 16 bits audio */
109 if ((cookie_snd & SND_16BIT)==0) {
110 DEBUG_PRINT((DEBUG_NAME "no 16 bits sound\n"));
111 return(0);
112 }
113
114 /* Cookie MCSN present ? */
115 if (Getcookie(C_McSn, &dummy) != C_FOUND) {
116 DEBUG_PRINT((DEBUG_NAME "no MCSN audio\n"));
117 return(0);
118 }
119 cookie_mcsn = (cookie_mcsn_t *) dummy;
120
121 /* Check if interrupt at end of replay */
122 if (cookie_mcsn->pint == 0) {
123 DEBUG_PRINT((DEBUG_NAME "no interrupt at end of replay\n"));
124 return(0);
125 }
126
127 /* Check if audio is lockable */
128 if (Locksnd()!=1) {
129 DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n"));
130 return(0);
131 }
132
133 Unlocksnd();
134
135 DEBUG_PRINT((DEBUG_NAME "MCSN audio available!\n"));
136 return(1);
137}
138
139static void Audio_DeleteDevice(SDL_AudioDevice *device)
140{
141 SDL_free(device->hidden);
142 SDL_free(device);
143}
144
145static SDL_AudioDevice *Audio_CreateDevice(int devindex)
146{
147 SDL_AudioDevice *this;
148
149 /* Initialize all variables that we clean on shutdown */
150 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
151 if ( this ) {
152 SDL_memset(this, 0, (sizeof *this));
153 this->hidden = (struct SDL_PrivateAudioData *)
154 SDL_malloc((sizeof *this->hidden));
155 }
156 if ( (this == NULL) || (this->hidden == NULL) ) {
157 SDL_OutOfMemory();
158 if ( this ) {
159 SDL_free(this);
160 }
161 return(0);
162 }
163 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
164
165 /* Set the function pointers */
166 this->OpenAudio = Mint_OpenAudio;
167 this->CloseAudio = Mint_CloseAudio;
168 this->LockAudio = Mint_LockAudio;
169 this->UnlockAudio = Mint_UnlockAudio;
170 this->free = Audio_DeleteDevice;
171
172 return this;
173}
174
175AudioBootStrap MINTAUDIO_MCSN_bootstrap = {
176 MINT_AUDIO_DRIVER_NAME, "MiNT MCSN audio driver",
177 Audio_Available, Audio_CreateDevice
178};
179
180static void Mint_LockAudio(_THIS)
181{
182 /* Stop replay */
183 Buffoper(0);
184}
185
186static void Mint_UnlockAudio(_THIS)
187{
188 /* Restart replay */
189 Buffoper(SB_PLA_ENA|SB_PLA_RPT);
190}
191
192static void Mint_CloseAudio(_THIS)
193{
194 /* Stop replay */
195 SDL_MintAudio_WaitThread();
196 Buffoper(0);
197
198 if (!SDL_MintAudio_mint_present) {
199 /* Uninstall interrupt */
200 Jdisint(MFP_DMASOUND);
201 }
202
203 /* Wait if currently playing sound */
204 while (SDL_MintAudio_mutex != 0) {
205 }
206
207 /* Clear buffers */
208 if (SDL_MintAudio_audiobuf[0]) {
209 Mfree(SDL_MintAudio_audiobuf[0]);
210 SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL;
211 }
212
213 /* Unlock sound system */
214 Unlocksnd();
215}
216
217static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec)
218{
219 int i;
220 unsigned long masterclock, masterprediv;
221
222 DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ",spec->format & 0x00ff));
223 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
224 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
225 DEBUG_PRINT(("channels=%d, ", spec->channels));
226 DEBUG_PRINT(("freq=%d\n", spec->freq));
227
228 if (spec->channels > 2) {
229 spec->channels = 2; /* no more than stereo! */
230 }
231
232 /* Check formats available */
233 MINTAUDIO_freqcount=0;
234 switch(cookie_mcsn->play) {
235 case MCSN_ST:
236 spec->channels=1;
237 spec->format=8; /* FIXME: is it signed or unsigned ? */
238 SDL_MintAudio_AddFrequency(this, 12500, 0, 0, -1);
239 break;
240 case MCSN_TT: /* Also STE, Mega STE */
241 spec->format=AUDIO_S8;
242 masterclock=MASTERCLOCK_STE;
243 masterprediv=MASTERPREDIV_STE;
244 if ((cookie_mch>>16)==MCH_TT) {
245 masterclock=MASTERCLOCK_TT;
246 masterprediv=MASTERPREDIV_TT;
247 }
248 for (i=0; i<4; i++) {
249 SDL_MintAudio_AddFrequency(this, masterclock/(masterprediv*(1<<i)),
250 masterclock, 3-i, -1);
251 }
252 break;
253 case MCSN_FALCON: /* Also Mac */
254 for (i=1; i<12; i++) {
255 /* Remove unusable Falcon codec predivisors */
256 if ((i==6) || (i==8) || (i==10)) {
257 continue;
258 }
259 SDL_MintAudio_AddFrequency(this, MASTERCLOCK_FALCON1/(MASTERPREDIV_FALCON*(i+1)),
260 CLK25M, i+1, -1);
261 }
262 if (cookie_mcsn->res1 != 0) {
263 for (i=1; i<4; i++) {
264 SDL_MintAudio_AddFrequency(this, (cookie_mcsn->res1)/(MASTERPREDIV_FALCON*(1<<i)),
265 CLKEXT, (1<<i)-1, -1);
266 }
267 }
268 spec->format |= 0x8000; /* Audio is always signed */
269 if ((spec->format & 0x00ff)==16) {
270 spec->format |= 0x1000; /* Audio is always big endian */
271 spec->channels=2; /* 16 bits always stereo */
272 }
273 break;
274 }
275
276#if 0
277 for (i=0; i<MINTAUDIO_freqcount; i++) {
278 DEBUG_PRINT((DEBUG_NAME "freq %d: %lu Hz, clock %lu, prediv %d\n",
279 i, MINTAUDIO_frequencies[i].frequency, MINTAUDIO_frequencies[i].masterclock,
280 MINTAUDIO_frequencies[i].predivisor
281 ));
282 }
283#endif
284
285 MINTAUDIO_numfreq=SDL_MintAudio_SearchFrequency(this, spec->freq);
286 spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency;
287
288 DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff));
289 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
290 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
291 DEBUG_PRINT(("channels=%d, ", spec->channels));
292 DEBUG_PRINT(("freq=%d\n", spec->freq));
293
294 return 0;
295}
296
297static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec)
298{
299 int channels_mode, prediv, dmaclock;
300 void *buffer;
301
302 /* Stop currently playing sound */
303 SDL_MintAudio_quit_thread = SDL_FALSE;
304 SDL_MintAudio_thread_finished = SDL_TRUE;
305 SDL_MintAudio_WaitThread();
306 Buffoper(0);
307
308 /* Set replay tracks */
309 Settracks(0,0);
310 Setmontracks(0);
311
312 /* Select replay format */
313 channels_mode=STEREO16;
314 switch (spec->format & 0xff) {
315 case 8:
316 if (spec->channels==2) {
317 channels_mode=STEREO8;
318 } else {
319 channels_mode=MONO8;
320 }
321 break;
322 }
323 if (Setmode(channels_mode)<0) {
324 DEBUG_PRINT((DEBUG_NAME "Setmode() failed\n"));
325 }
326
327 dmaclock = MINTAUDIO_frequencies[MINTAUDIO_numfreq].masterclock;
328 prediv = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor;
329 switch(cookie_mcsn->play) {
330 case MCSN_TT:
331 Devconnect(DMAPLAY, DAC, CLK25M, CLKOLD, 1);
332 Soundcmd(SETPRESCALE, prediv);
333 DEBUG_PRINT((DEBUG_NAME "STE/TT prescaler selected\n"));
334 break;
335 case MCSN_FALCON:
336 Devconnect(DMAPLAY, DAC, dmaclock, prediv, 1);
337 DEBUG_PRINT((DEBUG_NAME "Falcon prescaler selected\n"));
338 break;
339 }
340
341 /* Set buffer */
342 buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf];
343 if (Setbuffer(0, buffer, buffer + spec->size)<0) {
344 DEBUG_PRINT((DEBUG_NAME "Setbuffer() failed\n"));
345 }
346
347 if (SDL_MintAudio_mint_present) {
348 SDL_MintAudio_thread_pid = tfork(SDL_MintAudio_Thread, 0);
349 } else {
350 /* Install interrupt */
351 Jdisint(MFP_DMASOUND);
352 Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_XbiosInterrupt);
353 Jenabint(MFP_DMASOUND);
354
355 if (Setinterrupt(SI_TIMERA, SI_PLAY)<0) {
356 DEBUG_PRINT((DEBUG_NAME "Setinterrupt() failed\n"));
357 }
358 }
359
360 /* Go */
361 Buffoper(SB_PLA_ENA|SB_PLA_RPT);
362 DEBUG_PRINT((DEBUG_NAME "hardware initialized\n"));
363}
364
365static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec)
366{
367 /* Lock sound system */
368 if (Locksnd()!=1) {
369 SDL_SetError("Mint_OpenAudio: Audio system already in use");
370 return(-1);
371 }
372
373 SDL_MintAudio_device = this;
374
375 /* Check audio capabilities */
376 if (Mint_CheckAudio(this, spec)==-1) {
377 return -1;
378 }
379
380 SDL_CalculateAudioSpec(spec);
381
382 /* Allocate memory for audio buffers in DMA-able RAM */
383 DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size));
384
385 SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM);
386 if (SDL_MintAudio_audiobuf[0]==NULL) {
387 SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer");
388 return (-1);
389 }
390 SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ;
391 SDL_MintAudio_numbuf=0;
392 SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2);
393 SDL_MintAudio_audiosize = spec->size;
394 SDL_MintAudio_mutex = 0;
395
396 DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0]));
397 DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1]));
398
399 SDL_MintAudio_CheckFpu();
400
401 /* Setup audio hardware */
402 Mint_InitAudio(this, spec);
403
404 return(1); /* We don't use SDL threaded audio */
405}
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_mcsn.h b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_mcsn.h
deleted file mode 100644
index b772fdab03..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_mcsn.h
+++ /dev/null
@@ -1,59 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 MCSN control structure
26
27 Patrice Mandin
28*/
29
30#ifndef _SDL_mintaudio_mcsh_h
31#define _SDL_mintaudio_mcsh_h
32
33typedef struct {
34 unsigned short version; /* Version */
35 unsigned short size; /* Size of structure */
36
37 unsigned short play; /* Replay capability */
38 unsigned short record; /* Record capability */
39 unsigned short dsp; /* DSP56K present */
40 unsigned short pint; /* Interrupt at end of replay */
41 unsigned short rint; /* Interrupt at end of record */
42
43 unsigned long res1; /* Frequency of external clock */
44 unsigned long res2;
45 unsigned long res3;
46 unsigned long res4;
47} cookie_mcsn_t;
48
49enum {
50 MCSN_ST=0,
51 MCSN_TT,
52 MCSN_STE=MCSN_TT,
53 MCSN_FALCON,
54 MCSN_MAC=MCSN_FALCON
55};
56
57#define SETSMPFREQ 7 /* Set sample frequency */
58
59#endif /* _SDL_mintaudio_mcsh_h */
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_stfa.c b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_stfa.c
deleted file mode 100644
index 4a581e0351..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_stfa.c
+++ /dev/null
@@ -1,326 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 MiNT audio driver
26 using XBIOS functions (STFA driver)
27
28 Patrice Mandin
29*/
30
31/* Mint includes */
32#include <mint/osbind.h>
33#include <mint/falcon.h>
34#include <mint/cookie.h>
35
36#include "SDL_audio.h"
37#include "../SDL_audio_c.h"
38#include "../SDL_sysaudio.h"
39
40#include "../../video/ataricommon/SDL_atarimxalloc_c.h"
41#include "../../video/ataricommon/SDL_atarisuper.h"
42
43#include "SDL_mintaudio.h"
44#include "SDL_mintaudio_stfa.h"
45
46/*--- Defines ---*/
47
48#define MINT_AUDIO_DRIVER_NAME "mint_stfa"
49
50/* Debug print info */
51#define DEBUG_NAME "audio:stfa: "
52#if 0
53#define DEBUG_PRINT(what) \
54 { \
55 printf what; \
56 }
57#else
58#define DEBUG_PRINT(what)
59#endif
60
61/*--- Static variables ---*/
62
63static long cookie_snd, cookie_mch;
64static cookie_stfa_t *cookie_stfa;
65
66static const int freqs[16]={
67 4995, 6269, 7493, 8192,
68 9830, 10971, 12538, 14985,
69 16384, 19819, 21943, 24576,
70 30720, 32336, 43885, 49152
71};
72
73/*--- Audio driver functions ---*/
74
75static void Mint_CloseAudio(_THIS);
76static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec);
77static void Mint_LockAudio(_THIS);
78static void Mint_UnlockAudio(_THIS);
79
80/* To check/init hardware audio */
81static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec);
82static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec);
83
84/*--- Audio driver bootstrap functions ---*/
85
86static int Audio_Available(void)
87{
88 long dummy;
89 const char *envr = SDL_getenv("SDL_AUDIODRIVER");
90
91 /* Check if user asked a different audio driver */
92 if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) {
93 DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n"));
94 return(0);
95 }
96
97 /* Cookie _MCH present ? if not, assume ST machine */
98 if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) {
99 cookie_mch = MCH_ST;
100 }
101
102 /* Cookie _SND present ? if not, assume ST machine */
103 if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) {
104 cookie_snd = SND_PSG;
105 }
106
107 /* Cookie STFA present ? */
108 if (Getcookie(C_STFA, &dummy) != C_FOUND) {
109 DEBUG_PRINT((DEBUG_NAME "no STFA audio\n"));
110 return(0);
111 }
112 cookie_stfa = (cookie_stfa_t *) dummy;
113
114 SDL_MintAudio_stfa = cookie_stfa;
115
116 DEBUG_PRINT((DEBUG_NAME "STFA audio available!\n"));
117 return(1);
118}
119
120static void Audio_DeleteDevice(SDL_AudioDevice *device)
121{
122 SDL_free(device->hidden);
123 SDL_free(device);
124}
125
126static SDL_AudioDevice *Audio_CreateDevice(int devindex)
127{
128 SDL_AudioDevice *this;
129
130 /* Initialize all variables that we clean on shutdown */
131 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
132 if ( this ) {
133 SDL_memset(this, 0, (sizeof *this));
134 this->hidden = (struct SDL_PrivateAudioData *)
135 SDL_malloc((sizeof *this->hidden));
136 }
137 if ( (this == NULL) || (this->hidden == NULL) ) {
138 SDL_OutOfMemory();
139 if ( this ) {
140 SDL_free(this);
141 }
142 return(0);
143 }
144 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
145
146 /* Set the function pointers */
147 this->OpenAudio = Mint_OpenAudio;
148 this->CloseAudio = Mint_CloseAudio;
149 this->LockAudio = Mint_LockAudio;
150 this->UnlockAudio = Mint_UnlockAudio;
151 this->free = Audio_DeleteDevice;
152
153 return this;
154}
155
156AudioBootStrap MINTAUDIO_STFA_bootstrap = {
157 MINT_AUDIO_DRIVER_NAME, "MiNT STFA audio driver",
158 Audio_Available, Audio_CreateDevice
159};
160
161static void Mint_LockAudio(_THIS)
162{
163 void *oldpile;
164
165 /* Stop replay */
166 oldpile=(void *)Super(0);
167 cookie_stfa->sound_enable=STFA_PLAY_DISABLE;
168 SuperToUser(oldpile);
169}
170
171static void Mint_UnlockAudio(_THIS)
172{
173 void *oldpile;
174
175 /* Restart replay */
176 oldpile=(void *)Super(0);
177 cookie_stfa->sound_enable=STFA_PLAY_ENABLE|STFA_PLAY_REPEAT;
178 SuperToUser(oldpile);
179}
180
181static void Mint_CloseAudio(_THIS)
182{
183 void *oldpile;
184
185 /* Stop replay */
186 oldpile=(void *)Super(0);
187 cookie_stfa->sound_enable=STFA_PLAY_DISABLE;
188 SuperToUser(oldpile);
189
190 /* Wait if currently playing sound */
191 while (SDL_MintAudio_mutex != 0) {
192 }
193
194 /* Clear buffers */
195 if (SDL_MintAudio_audiobuf[0]) {
196 Mfree(SDL_MintAudio_audiobuf[0]);
197 SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL;
198 }
199}
200
201static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec)
202{
203 int i;
204
205 DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ",spec->format & 0x00ff));
206 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
207 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
208 DEBUG_PRINT(("channels=%d, ", spec->channels));
209 DEBUG_PRINT(("freq=%d\n", spec->freq));
210
211 if (spec->channels > 2) {
212 spec->channels = 2; /* no more than stereo! */
213 }
214
215 /* Check formats available */
216 MINTAUDIO_freqcount=0;
217 for (i=0;i<16;i++) {
218 SDL_MintAudio_AddFrequency(this, freqs[i], 0, i, -1);
219 }
220
221#if 1
222 for (i=0; i<MINTAUDIO_freqcount; i++) {
223 DEBUG_PRINT((DEBUG_NAME "freq %d: %lu Hz, clock %lu, prediv %d\n",
224 i, MINTAUDIO_frequencies[i].frequency, MINTAUDIO_frequencies[i].masterclock,
225 MINTAUDIO_frequencies[i].predivisor
226 ));
227 }
228#endif
229
230 MINTAUDIO_numfreq=SDL_MintAudio_SearchFrequency(this, spec->freq);
231 spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency;
232
233 DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff));
234 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
235 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
236 DEBUG_PRINT(("channels=%d, ", spec->channels));
237 DEBUG_PRINT(("freq=%d\n", spec->freq));
238
239 return 0;
240}
241
242static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec)
243{
244 void *buffer;
245 void *oldpile;
246
247 buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf];
248
249 oldpile=(void *)Super(0);
250
251 /* Stop replay */
252 cookie_stfa->sound_enable=STFA_PLAY_DISABLE;
253
254 /* Select replay format */
255 cookie_stfa->sound_control = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor;
256 if ((spec->format & 0xff)==8) {
257 cookie_stfa->sound_control |= STFA_FORMAT_8BIT;
258 } else {
259 cookie_stfa->sound_control |= STFA_FORMAT_16BIT;
260 }
261 if (spec->channels==2) {
262 cookie_stfa->sound_control |= STFA_FORMAT_STEREO;
263 } else {
264 cookie_stfa->sound_control |= STFA_FORMAT_MONO;
265 }
266 if ((spec->format & 0x8000)!=0) {
267 cookie_stfa->sound_control |= STFA_FORMAT_SIGNED;
268 } else {
269 cookie_stfa->sound_control |= STFA_FORMAT_UNSIGNED;
270 }
271 if ((spec->format & 0x1000)!=0) {
272 cookie_stfa->sound_control |= STFA_FORMAT_BIGENDIAN;
273 } else {
274 cookie_stfa->sound_control |= STFA_FORMAT_LITENDIAN;
275 }
276
277 /* Set buffer */
278 cookie_stfa->sound_start = (unsigned long) buffer;
279 cookie_stfa->sound_end = (unsigned long) (buffer + spec->size);
280
281 /* Set interrupt */
282 cookie_stfa->stfa_it = SDL_MintAudio_StfaInterrupt;
283
284 /* Restart replay */
285 cookie_stfa->sound_enable=STFA_PLAY_ENABLE|STFA_PLAY_REPEAT;
286
287 SuperToUser(oldpile);
288
289 DEBUG_PRINT((DEBUG_NAME "hardware initialized\n"));
290}
291
292static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec)
293{
294 SDL_MintAudio_device = this;
295
296 /* Check audio capabilities */
297 if (Mint_CheckAudio(this, spec)==-1) {
298 return -1;
299 }
300
301 SDL_CalculateAudioSpec(spec);
302
303 /* Allocate memory for audio buffers in DMA-able RAM */
304 DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size));
305
306 SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM);
307 if (SDL_MintAudio_audiobuf[0]==NULL) {
308 SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer");
309 return (-1);
310 }
311 SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ;
312 SDL_MintAudio_numbuf=0;
313 SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2);
314 SDL_MintAudio_audiosize = spec->size;
315 SDL_MintAudio_mutex = 0;
316
317 DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0]));
318 DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1]));
319
320 SDL_MintAudio_CheckFpu();
321
322 /* Setup audio hardware */
323 Mint_InitAudio(this, spec);
324
325 return(1); /* We don't use threaded audio */
326}
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_stfa.h b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_stfa.h
deleted file mode 100644
index 1789b4bb41..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_stfa.h
+++ /dev/null
@@ -1,97 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 STFA control structure
26
27 Patrice Mandin
28*/
29
30#ifndef _SDL_mintaudio_stfa_h
31#define _SDL_mintaudio_stfa_h
32
33/*--- Defines ---*/
34
35#define STFA_PLAY_ENABLE (1<<0)
36#define STFA_PLAY_DISABLE (0<<0)
37#define STFA_PLAY_REPEAT (1<<1)
38#define STFA_PLAY_SINGLE (0<<1)
39
40#define STFA_FORMAT_SIGNED (1<<15)
41#define STFA_FORMAT_UNSIGNED (0<<15)
42#define STFA_FORMAT_STEREO (1<<14)
43#define STFA_FORMAT_MONO (0<<14)
44#define STFA_FORMAT_16BIT (1<<13)
45#define STFA_FORMAT_8BIT (0<<13)
46#define STFA_FORMAT_LITENDIAN (1<<9)
47#define STFA_FORMAT_BIGENDIAN (0<<9)
48#define STFA_FORMAT_FREQ_MASK 0x0f
49enum {
50 STFA_FORMAT_F4995=0,
51 STFA_FORMAT_F6269,
52 STFA_FORMAT_F7493,
53 STFA_FORMAT_F8192,
54
55 STFA_FORMAT_F9830,
56 STFA_FORMAT_F10971,
57 STFA_FORMAT_F12538,
58 STFA_FORMAT_F14985,
59
60 STFA_FORMAT_F16384,
61 STFA_FORMAT_F19819,
62 STFA_FORMAT_F21943,
63 STFA_FORMAT_F24576,
64
65 STFA_FORMAT_F30720,
66 STFA_FORMAT_F32336,
67 STFA_FORMAT_F43885,
68 STFA_FORMAT_F49152
69};
70
71/*--- Types ---*/
72
73typedef struct {
74 unsigned short sound_enable;
75 unsigned short sound_control;
76 unsigned short sound_output;
77 unsigned long sound_start;
78 unsigned long sound_current;
79 unsigned long sound_end;
80 unsigned short version;
81 void *old_vbl;
82 void *old_timera;
83 unsigned long old_mfp_status;
84 void *new_vbl;
85 void *drivers_list;
86 void *play_stop;
87 unsigned short frequency;
88 void *set_frequency;
89 unsigned short frequency_threshold;
90 unsigned short *custom_freq_table;
91 unsigned short stfa_on_off;
92 void *new_drivers_list;
93 unsigned long old_bit_2_of_cookie_snd;
94 void (*stfa_it)(void);
95} cookie_stfa_t;
96
97#endif /* _SDL_mintaudio_stfa_h */
diff --git a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_xbios.c b/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_xbios.c
deleted file mode 100644
index 42a0d4a2f9..0000000000
--- a/apps/plugins/sdl/src/audio/mint/SDL_mintaudio_xbios.c
+++ /dev/null
@@ -1,490 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 MiNT audio driver
26 using XBIOS functions (Falcon)
27
28 Patrice Mandin, Didier Méquignon
29*/
30
31#include <unistd.h>
32#include <support.h>
33
34/* Mint includes */
35#include <mint/osbind.h>
36#include <mint/falcon.h>
37#include <mint/cookie.h>
38
39#include "SDL_audio.h"
40#include "../SDL_audio_c.h"
41#include "../SDL_sysaudio.h"
42
43#include "../../video/ataricommon/SDL_atarimxalloc_c.h"
44#include "../../video/ataricommon/SDL_atarisuper.h"
45
46#include "SDL_mintaudio.h"
47#include "SDL_mintaudio_dma8.h"
48
49/*--- Defines ---*/
50
51#define MINT_AUDIO_DRIVER_NAME "mint_xbios"
52
53/* Debug print info */
54#define DEBUG_NAME "audio:xbios: "
55#if 0
56#define DEBUG_PRINT(what) \
57 { \
58 printf what; \
59 }
60#else
61#define DEBUG_PRINT(what)
62#endif
63
64/*--- Static variables ---*/
65
66static long cookie_snd;
67
68/*--- Audio driver functions ---*/
69
70static void Mint_CloseAudio(_THIS);
71static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec);
72static void Mint_LockAudio(_THIS);
73static void Mint_UnlockAudio(_THIS);
74
75/* To check/init hardware audio */
76static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec);
77static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec);
78
79/*--- Audio driver bootstrap functions ---*/
80
81static int Audio_Available(void)
82{
83/* unsigned long dummy;*/
84 const char *envr = SDL_getenv("SDL_AUDIODRIVER");
85
86 /*SDL_MintAudio_mint_present = (Getcookie(C_MiNT, &dummy) == C_FOUND);*/
87 SDL_MintAudio_mint_present = SDL_FALSE;
88
89 /* We can't use XBIOS in interrupt with Magic, don't know about thread */
90 /*if (Getcookie(C_MagX, &dummy) == C_FOUND) {
91 return(0);
92 }*/
93
94 /* Check if user asked a different audio driver */
95 if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) {
96 DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n"));
97 return(0);
98 }
99
100 /* Cookie _SND present ? if not, assume ST machine */
101 if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) {
102 cookie_snd = SND_PSG;
103 }
104
105 /* Check if we have 16 bits audio */
106 if ((cookie_snd & SND_16BIT)==0) {
107 DEBUG_PRINT((DEBUG_NAME "no 16 bits sound\n"));
108 return(0);
109 }
110
111 /* Check if audio is lockable */
112 if (Locksnd()!=1) {
113 DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n"));
114 return(0);
115 }
116
117 Unlocksnd();
118
119 DEBUG_PRINT((DEBUG_NAME "XBIOS audio available!\n"));
120 return(1);
121}
122
123static void Audio_DeleteDevice(SDL_AudioDevice *device)
124{
125 SDL_free(device->hidden);
126 SDL_free(device);
127}
128
129static SDL_AudioDevice *Audio_CreateDevice(int devindex)
130{
131 SDL_AudioDevice *this;
132
133 /* Initialize all variables that we clean on shutdown */
134 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
135 if ( this ) {
136 SDL_memset(this, 0, (sizeof *this));
137 this->hidden = (struct SDL_PrivateAudioData *)
138 SDL_malloc((sizeof *this->hidden));
139 }
140 if ( (this == NULL) || (this->hidden == NULL) ) {
141 SDL_OutOfMemory();
142 if ( this ) {
143 SDL_free(this);
144 }
145 return(0);
146 }
147 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
148
149 /* Set the function pointers */
150 this->OpenAudio = Mint_OpenAudio;
151 this->CloseAudio = Mint_CloseAudio;
152 this->LockAudio = Mint_LockAudio;
153 this->UnlockAudio = Mint_UnlockAudio;
154 this->free = Audio_DeleteDevice;
155
156 return this;
157}
158
159AudioBootStrap MINTAUDIO_XBIOS_bootstrap = {
160 MINT_AUDIO_DRIVER_NAME, "MiNT XBIOS audio driver",
161 Audio_Available, Audio_CreateDevice
162};
163
164static void Mint_LockAudio(_THIS)
165{
166 /* Stop replay */
167 Buffoper(0);
168}
169
170static void Mint_UnlockAudio(_THIS)
171{
172 /* Restart replay */
173 Buffoper(SB_PLA_ENA|SB_PLA_RPT);
174}
175
176static void Mint_CloseAudio(_THIS)
177{
178 /* Stop replay */
179 SDL_MintAudio_WaitThread();
180 Buffoper(0);
181
182 if (!SDL_MintAudio_mint_present) {
183 /* Uninstall interrupt */
184 Jdisint(MFP_DMASOUND);
185 }
186
187 /* Wait if currently playing sound */
188 while (SDL_MintAudio_mutex != 0) {
189 }
190
191 /* Clear buffers */
192 if (SDL_MintAudio_audiobuf[0]) {
193 Mfree(SDL_MintAudio_audiobuf[0]);
194 SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL;
195 }
196
197 /* Unlock sound system */
198 Unlocksnd();
199}
200
201/* Falcon XBIOS implementation of Devconnect() is buggy with external clock */
202static void Devconnect2(int src, int dst, int sclk, int pre)
203{
204 static const unsigned short MASK1[3] = { 0, 0x6000, 0 };
205 static const unsigned short MASK2[4] = { 0xFFF0, 0xFF8F, 0xF0FF, 0x0FFF };
206 static const unsigned short INDEX1[4] = { 1, 3, 5, 7 };
207 static const unsigned short INDEX2[4] = { 0, 2, 4, 6 };
208 unsigned short sync_div,dev_ctrl,dest_ctrl;
209 void *oldstack;
210
211 if (dst==0) {
212 return;
213 }
214
215 oldstack=(void *)Super(0);
216
217 dev_ctrl = DMAAUDIO_IO.dev_ctrl;
218 dest_ctrl = DMAAUDIO_IO.dest_ctrl;
219 dev_ctrl &= MASK2[src];
220
221 if (src==ADC) {
222 dev_ctrl |= MASK1[sclk];
223 } else {
224 dev_ctrl |= (INDEX1[sclk] << (src<<4));
225 }
226
227 if (dst & DMAREC) {
228 dest_ctrl &= 0xFFF0;
229 dest_ctrl |= INDEX1[src];
230 }
231
232 if (dst & DSPRECV) {
233 dest_ctrl &= 0xFF8F;
234 dest_ctrl |= (INDEX1[src]<<4);
235 }
236
237 if (dst & EXTOUT) {
238 dest_ctrl &= 0xF0FF;
239 dest_ctrl |= (INDEX1[src]<<8);
240 }
241
242 if (dst & DAC) {
243 dev_ctrl &= 0x0FFF;
244 dev_ctrl |= MASK1[sclk];
245 dest_ctrl &= 0x0FFF;
246 dest_ctrl |= (INDEX2[src]<<12);
247 }
248
249 sync_div = DMAAUDIO_IO.sync_div;
250 if (sclk==CLKEXT) {
251 pre<<=8;
252 sync_div &= 0xF0FF;
253 } else {
254 sync_div &= 0xFFF0;
255 }
256 sync_div |= pre;
257
258 DMAAUDIO_IO.dev_ctrl = dev_ctrl;
259 DMAAUDIO_IO.dest_ctrl = dest_ctrl;
260 DMAAUDIO_IO.sync_div = sync_div;
261
262 SuperToUser(oldstack);
263}
264
265static void Mint_CheckExternalClock(_THIS)
266{
267#define SIZE_BUF_CLOCK_MEASURE (44100/10)
268
269 char *buffer;
270 int i, j;
271
272 /* DSP present with its GPIO port ? */
273 if ((cookie_snd & SND_DSP)==0) {
274 return;
275 }
276
277 buffer = Atari_SysMalloc(SIZE_BUF_CLOCK_MEASURE, MX_STRAM);
278 if (buffer==NULL) {
279 DEBUG_PRINT((DEBUG_NAME "Not enough memory for the measure\n"));
280 return;
281 }
282 SDL_memset(buffer, 0, SIZE_BUF_CLOCK_MEASURE);
283
284 Buffoper(0);
285 Settracks(0,0);
286 Setmontracks(0);
287 Setmode(MONO8);
288 Jdisint(MFP_TIMERA);
289
290 for (i=0; i<2; i++) {
291 Gpio(GPIO_SET,7); /* DSP port gpio outputs */
292 Gpio(GPIO_WRITE,2+i); /* 22.5792/24.576 MHz for 44.1/48KHz */
293 Devconnect2(DMAPLAY, DAC, CLKEXT, CLK50K); /* Matrix and clock source */
294 Setbuffer(0, buffer, buffer + SIZE_BUF_CLOCK_MEASURE); /* Set buffer */
295 Xbtimer(XB_TIMERA, 5, 38, SDL_MintAudio_XbiosInterruptMeasureClock); /* delay mode timer A, prediv /64, 1KHz */
296 Jenabint(MFP_TIMERA);
297 SDL_MintAudio_clocktics = 0;
298 Buffoper(SB_PLA_ENA);
299 usleep(110000);
300
301 if((Buffoper(-1) & 1)==0) {
302 if (SDL_MintAudio_clocktics) {
303 unsigned long khz;
304
305 khz = ((SIZE_BUF_CLOCK_MEASURE/SDL_MintAudio_clocktics) +1) & 0xFFFFFFFE;
306 DEBUG_PRINT((DEBUG_NAME "measure %d: freq=%lu KHz\n", i+1, khz));
307
308 if(khz==44) {
309 for (j=1; j<4; j++) {
310 SDL_MintAudio_AddFrequency(this, MASTERCLOCK_44K/(MASTERPREDIV_FALCON*(1<<j)), MASTERCLOCK_44K, (1<<j)-1, 2+i);
311 }
312 } else if (khz==48) {
313 for (j=1; j<4; j++) {
314 SDL_MintAudio_AddFrequency(this, MASTERCLOCK_48K/(MASTERPREDIV_FALCON*(1<<j)), MASTERCLOCK_48K, (1<<j)-1, 2+i);
315 }
316 }
317 } else {
318 DEBUG_PRINT((DEBUG_NAME "No measure\n"));
319 }
320 } else {
321 DEBUG_PRINT((DEBUG_NAME "No SDMA clock\n"));
322 }
323
324 Buffoper(0); /* stop */
325 Jdisint(MFP_TIMERA); /* Uninstall interrupt */
326 }
327
328 Mfree(buffer);
329}
330
331static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec)
332{
333 int i;
334
335 DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ",spec->format & 0x00ff));
336 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
337 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
338 DEBUG_PRINT(("channels=%d, ", spec->channels));
339 DEBUG_PRINT(("freq=%d\n", spec->freq));
340
341 if (spec->channels > 2) {
342 spec->channels = 2; /* no more than stereo! */
343 }
344
345 spec->format |= 0x8000; /* Audio is always signed */
346 if ((spec->format & 0x00ff)==16) {
347 spec->format |= 0x1000; /* Audio is always big endian */
348 spec->channels=2; /* 16 bits always stereo */
349 }
350
351 MINTAUDIO_freqcount=0;
352
353 /* Add external clocks if present */
354 Mint_CheckExternalClock(this);
355
356 /* Standard clocks */
357 for (i=1;i<12;i++) {
358 /* Remove unusable Falcon codec predivisors */
359 if ((i==6) || (i==8) || (i==10)) {
360 continue;
361 }
362 SDL_MintAudio_AddFrequency(this, MASTERCLOCK_FALCON1/(MASTERPREDIV_FALCON*(i+1)), MASTERCLOCK_FALCON1, i, -1);
363 }
364
365#if 1
366 for (i=0; i<MINTAUDIO_freqcount; i++) {
367 DEBUG_PRINT((DEBUG_NAME "freq %d: %lu Hz, clock %lu, prediv %d\n",
368 i, MINTAUDIO_frequencies[i].frequency, MINTAUDIO_frequencies[i].masterclock,
369 MINTAUDIO_frequencies[i].predivisor
370 ));
371 }
372#endif
373
374 MINTAUDIO_numfreq=SDL_MintAudio_SearchFrequency(this, spec->freq);
375 spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency;
376
377 DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff));
378 DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0)));
379 DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0)));
380 DEBUG_PRINT(("channels=%d, ", spec->channels));
381 DEBUG_PRINT(("freq=%d\n", spec->freq));
382
383 return 0;
384}
385
386static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec)
387{
388 int channels_mode, prediv;
389 void *buffer;
390
391 /* Stop currently playing sound */
392 SDL_MintAudio_quit_thread = SDL_FALSE;
393 SDL_MintAudio_thread_finished = SDL_TRUE;
394 SDL_MintAudio_WaitThread();
395 Buffoper(0);
396
397 /* Set replay tracks */
398 Settracks(0,0);
399 Setmontracks(0);
400
401 /* Select replay format */
402 channels_mode=STEREO16;
403 switch (spec->format & 0xff) {
404 case 8:
405 if (spec->channels==2) {
406 channels_mode=STEREO8;
407 } else {
408 channels_mode=MONO8;
409 }
410 break;
411 }
412 if (Setmode(channels_mode)<0) {
413 DEBUG_PRINT((DEBUG_NAME "Setmode() failed\n"));
414 }
415
416 prediv = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor;
417 if (MINTAUDIO_frequencies[MINTAUDIO_numfreq].gpio_bits != -1) {
418 Gpio(GPIO_SET,7); /* DSP port gpio outputs */
419 Gpio(GPIO_WRITE, MINTAUDIO_frequencies[MINTAUDIO_numfreq].gpio_bits);
420 Devconnect2(DMAPLAY, DAC|EXTOUT, CLKEXT, prediv);
421 } else {
422 Devconnect2(DMAPLAY, DAC, CLK25M, prediv);
423 }
424
425 /* Set buffer */
426 buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf];
427 if (Setbuffer(0, buffer, buffer + spec->size)<0) {
428 DEBUG_PRINT((DEBUG_NAME "Setbuffer() failed\n"));
429 }
430
431 if (SDL_MintAudio_mint_present) {
432 SDL_MintAudio_thread_pid = tfork(SDL_MintAudio_Thread, 0);
433 } else {
434 /* Install interrupt */
435 Jdisint(MFP_DMASOUND);
436 /*Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_XbiosInterrupt);*/
437 Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_Dma8Interrupt);
438 Jenabint(MFP_DMASOUND);
439
440 if (Setinterrupt(SI_TIMERA, SI_PLAY)<0) {
441 DEBUG_PRINT((DEBUG_NAME "Setinterrupt() failed\n"));
442 }
443 }
444
445 /* Go */
446 Buffoper(SB_PLA_ENA|SB_PLA_RPT);
447 DEBUG_PRINT((DEBUG_NAME "hardware initialized\n"));
448}
449
450static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec)
451{
452 /* Lock sound system */
453 if (Locksnd()!=1) {
454 SDL_SetError("Mint_OpenAudio: Audio system already in use");
455 return(-1);
456 }
457
458 SDL_MintAudio_device = this;
459
460 /* Check audio capabilities */
461 if (Mint_CheckAudio(this, spec)==-1) {
462 return -1;
463 }
464
465 SDL_CalculateAudioSpec(spec);
466
467 /* Allocate memory for audio buffers in DMA-able RAM */
468 DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size));
469
470 SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM);
471 if (SDL_MintAudio_audiobuf[0]==NULL) {
472 SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer");
473 return (-1);
474 }
475 SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ;
476 SDL_MintAudio_numbuf=0;
477 SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2);
478 SDL_MintAudio_audiosize = spec->size;
479 SDL_MintAudio_mutex = 0;
480
481 DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0]));
482 DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1]));
483
484 SDL_MintAudio_CheckFpu();
485
486 /* Setup audio hardware */
487 Mint_InitAudio(this, spec);
488
489 return(1); /* We don't use SDL threaded audio */
490}
diff --git a/apps/plugins/sdl/src/audio/mme/SDL_mmeaudio.c b/apps/plugins/sdl/src/audio/mme/SDL_mmeaudio.c
deleted file mode 100644
index 64a0ecc36d..0000000000
--- a/apps/plugins/sdl/src/audio/mme/SDL_mmeaudio.c
+++ /dev/null
@@ -1,264 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Tru64 UNIX MME support */
25#include <mme_api.h>
26
27#include "SDL_timer.h"
28#include "SDL_audio.h"
29#include "../SDL_audio_c.h"
30#include "SDL_mmeaudio.h"
31
32static BOOL inUse[NUM_BUFFERS];
33
34/* Audio driver functions */
35static int MME_OpenAudio(_THIS, SDL_AudioSpec *spec);
36static void MME_WaitAudio(_THIS);
37static Uint8 *MME_GetAudioBuf(_THIS);
38static void MME_PlayAudio(_THIS);
39static void MME_WaitDone(_THIS);
40static void MME_CloseAudio(_THIS);
41
42/* Audio driver bootstrap functions */
43static int Audio_Available(void)
44{
45 return(1);
46}
47
48static void Audio_DeleteDevice(SDL_AudioDevice *device)
49{
50 if ( device ) {
51 if ( device->hidden ) {
52 SDL_free(device->hidden);
53 device->hidden = NULL;
54 }
55 SDL_free(device);
56 device = NULL;
57 }
58}
59
60static SDL_AudioDevice *Audio_CreateDevice(int devindex)
61{
62 SDL_AudioDevice *this;
63
64/* Initialize all variables that we clean on shutdown */
65 this = SDL_malloc(sizeof(SDL_AudioDevice));
66 if ( this ) {
67 SDL_memset(this, 0, (sizeof *this));
68 this->hidden = SDL_malloc((sizeof *this->hidden));
69 }
70 if ( (this == NULL) || (this->hidden == NULL) ) {
71 SDL_OutOfMemory();
72 if ( this ) {
73 SDL_free(this);
74 }
75 return(0);
76 }
77 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
78 /* Set the function pointers */
79 this->OpenAudio = MME_OpenAudio;
80 this->WaitAudio = MME_WaitAudio;
81 this->PlayAudio = MME_PlayAudio;
82 this->GetAudioBuf = MME_GetAudioBuf;
83 this->WaitDone = MME_WaitDone;
84 this->CloseAudio = MME_CloseAudio;
85 this->free = Audio_DeleteDevice;
86
87 return this;
88}
89
90AudioBootStrap MMEAUDIO_bootstrap = {
91 "waveout", "Tru64 MME WaveOut",
92 Audio_Available, Audio_CreateDevice
93};
94
95static void SetMMerror(char *function, MMRESULT code)
96{
97 int len;
98 char errbuf[MAXERRORLENGTH];
99
100 SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: ", function);
101 len = SDL_strlen(errbuf);
102 waveOutGetErrorText(code, errbuf+len, MAXERRORLENGTH-len);
103 SDL_SetError("%s",errbuf);
104}
105
106static void CALLBACK MME_CALLBACK(HWAVEOUT hwo,
107 UINT uMsg,
108 DWORD dwInstance,
109 LPARAM dwParam1,
110 LPARAM dwParam2)
111{
112 WAVEHDR *wp = (WAVEHDR *) dwParam1;
113
114 if ( uMsg == WOM_DONE )
115 inUse[wp->dwUser] = FALSE;
116}
117
118static int MME_OpenAudio(_THIS, SDL_AudioSpec *spec)
119{
120 MMRESULT result;
121 int i;
122
123 mixbuf = NULL;
124
125 /* Set basic WAVE format parameters */
126 shm = mmeAllocMem(sizeof(*shm));
127 if ( shm == NULL ) {
128 SDL_SetError("Out of memory: shm");
129 return(-1);
130 }
131 shm->sound = 0;
132 shm->wFmt.wf.wFormatTag = WAVE_FORMAT_PCM;
133
134 /* Determine the audio parameters from the AudioSpec */
135 switch ( spec->format & 0xFF ) {
136 case 8:
137 /* Unsigned 8 bit audio data */
138 spec->format = AUDIO_U8;
139 shm->wFmt.wBitsPerSample = 8;
140 break;
141 case 16:
142 /* Signed 16 bit audio data */
143 spec->format = AUDIO_S16;
144 shm->wFmt.wBitsPerSample = 16;
145 break;
146 default:
147 SDL_SetError("Unsupported audio format");
148 return(-1);
149 }
150
151 shm->wFmt.wf.nChannels = spec->channels;
152 shm->wFmt.wf.nSamplesPerSec = spec->freq;
153 shm->wFmt.wf.nBlockAlign =
154 shm->wFmt.wf.nChannels * shm->wFmt.wBitsPerSample / 8;
155 shm->wFmt.wf.nAvgBytesPerSec =
156 shm->wFmt.wf.nSamplesPerSec * shm->wFmt.wf.nBlockAlign;
157
158 /* Check the buffer size -- minimum of 1/4 second (word aligned) */
159 if ( spec->samples < (spec->freq/4) )
160 spec->samples = ((spec->freq/4)+3)&~3;
161
162 /* Update the fragment size as size in bytes */
163 SDL_CalculateAudioSpec(spec);
164
165 /* Open the audio device */
166 result = waveOutOpen(&(shm->sound),
167 WAVE_MAPPER,
168 &(shm->wFmt.wf),
169 MME_CALLBACK,
170 NULL,
171 (CALLBACK_FUNCTION|WAVE_OPEN_SHAREABLE));
172 if ( result != MMSYSERR_NOERROR ) {
173 SetMMerror("waveOutOpen()", result);
174 return(-1);
175 }
176
177 /* Create the sound buffers */
178 mixbuf = (Uint8 *)mmeAllocBuffer(NUM_BUFFERS * (spec->size));
179 if ( mixbuf == NULL ) {
180 SDL_SetError("Out of memory: mixbuf");
181 return(-1);
182 }
183
184 for (i = 0; i < NUM_BUFFERS; i++) {
185 shm->wHdr[i].lpData = &mixbuf[i * (spec->size)];
186 shm->wHdr[i].dwBufferLength = spec->size;
187 shm->wHdr[i].dwFlags = 0;
188 shm->wHdr[i].dwUser = i;
189 shm->wHdr[i].dwLoops = 0; /* loop control counter */
190 shm->wHdr[i].lpNext = NULL; /* reserved for driver */
191 shm->wHdr[i].reserved = 0;
192 inUse[i] = FALSE;
193 }
194 next_buffer = 0;
195 return 0;
196}
197
198static void MME_WaitAudio(_THIS)
199{
200 while ( inUse[next_buffer] ) {
201 mmeWaitForCallbacks();
202 mmeProcessCallbacks();
203 }
204}
205
206static Uint8 *MME_GetAudioBuf(_THIS)
207{
208 Uint8 *retval;
209
210 inUse[next_buffer] = TRUE;
211 retval = (Uint8 *)(shm->wHdr[next_buffer].lpData);
212 return retval;
213}
214
215static void MME_PlayAudio(_THIS)
216{
217 /* Queue it up */
218 waveOutWrite(shm->sound, &(shm->wHdr[next_buffer]), sizeof(WAVEHDR));
219 next_buffer = (next_buffer+1)%NUM_BUFFERS;
220}
221
222static void MME_WaitDone(_THIS)
223{
224 MMRESULT result;
225 int i;
226
227 if ( shm->sound ) {
228 for (i = 0; i < NUM_BUFFERS; i++)
229 while ( inUse[i] ) {
230 mmeWaitForCallbacks();
231 mmeProcessCallbacks();
232 }
233 result = waveOutReset(shm->sound);
234 if ( result != MMSYSERR_NOERROR )
235 SetMMerror("waveOutReset()", result);
236 mmeProcessCallbacks();
237 }
238}
239
240static void MME_CloseAudio(_THIS)
241{
242 MMRESULT result;
243
244 if ( mixbuf ) {
245 result = mmeFreeBuffer(mixbuf);
246 if (result != MMSYSERR_NOERROR )
247 SetMMerror("mmeFreeBuffer", result);
248 mixbuf = NULL;
249 }
250
251 if ( shm ) {
252 if ( shm->sound ) {
253 result = waveOutClose(shm->sound);
254 if (result != MMSYSERR_NOERROR )
255 SetMMerror("waveOutClose()", result);
256 mmeProcessCallbacks();
257 }
258 result = mmeFreeMem(shm);
259 if (result != MMSYSERR_NOERROR )
260 SetMMerror("mmeFreeMem()", result);
261 shm = NULL;
262 }
263}
264
diff --git a/apps/plugins/sdl/src/audio/mme/SDL_mmeaudio.h b/apps/plugins/sdl/src/audio/mme/SDL_mmeaudio.h
deleted file mode 100644
index 6bfaed32e0..0000000000
--- a/apps/plugins/sdl/src/audio/mme/SDL_mmeaudio.h
+++ /dev/null
@@ -1,51 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer */
25
26#ifndef _SDL_lowaudio_h
27#define _SDL_lowaudio_h
28
29#include "../SDL_sysaudio.h"
30
31/* Hidden "this" pointer for the video functions */
32#define _THIS SDL_AudioDevice *this
33#define NUM_BUFFERS 2
34
35struct SharedMem {
36 HWAVEOUT sound;
37 WAVEHDR wHdr[NUM_BUFFERS];
38 PCMWAVEFORMAT wFmt;
39};
40
41struct SDL_PrivateAudioData {
42 Uint8 *mixbuf; /* The raw allocated mixing buffer */
43 struct SharedMem *shm;
44 int next_buffer;
45};
46
47#define shm (this->hidden->shm)
48#define mixbuf (this->hidden->mixbuf)
49#define next_buffer (this->hidden->next_buffer)
50/* Old variable names */
51#endif /* _SDL_lowaudio_h */
diff --git a/apps/plugins/sdl/src/audio/nas/SDL_nasaudio.c b/apps/plugins/sdl/src/audio/nas/SDL_nasaudio.c
deleted file mode 100644
index a561e62984..0000000000
--- a/apps/plugins/sdl/src/audio/nas/SDL_nasaudio.c
+++ /dev/null
@@ -1,423 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 This driver was written by:
23 Erik Inge Bolsø
24 knan@mo.himolde.no
25*/
26#include "SDL_config.h"
27
28/* Allow access to a raw mixing buffer */
29
30#include <signal.h>
31#include <unistd.h>
32
33#include "SDL_timer.h"
34#include "SDL_audio.h"
35#include "../SDL_audiomem.h"
36#include "../SDL_audio_c.h"
37#include "../SDL_audiodev_c.h"
38#include "SDL_nasaudio.h"
39
40#ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC
41#include "SDL_loadso.h"
42#endif
43
44/* The tag name used by artsc audio */
45#define NAS_DRIVER_NAME "nas"
46
47static struct SDL_PrivateAudioData *this2 = NULL;
48
49static void (*NAS_AuCloseServer) (AuServer *);
50static void (*NAS_AuNextEvent) (AuServer *, AuBool, AuEvent *);
51static AuBool(*NAS_AuDispatchEvent) (AuServer *, AuEvent *);
52static AuFlowID(*NAS_AuCreateFlow) (AuServer *, AuStatus *);
53static void (*NAS_AuStartFlow) (AuServer *, AuFlowID, AuStatus *);
54static void (*NAS_AuSetElements)
55 (AuServer *, AuFlowID, AuBool, int, AuElement *, AuStatus *);
56static void (*NAS_AuWriteElement)
57 (AuServer *, AuFlowID, int, AuUint32, AuPointer, AuBool, AuStatus *);
58static AuServer *(*NAS_AuOpenServer)
59 (_AuConst char *, int, _AuConst char *, int, _AuConst char *, char **);
60static AuEventHandlerRec *(*NAS_AuRegisterEventHandler)
61 (AuServer *, AuMask, int, AuID, AuEventHandlerCallback, AuPointer);
62
63
64#ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC
65
66static const char *nas_library = SDL_AUDIO_DRIVER_NAS_DYNAMIC;
67static void *nas_handle = NULL;
68
69static int
70load_nas_sym(const char *fn, void **addr)
71{
72 *addr = SDL_LoadFunction(nas_handle, fn);
73 if (*addr == NULL) {
74 return 0;
75 }
76 return 1;
77}
78
79/* cast funcs to char* first, to please GCC's strict aliasing rules. */
80#define SDL_NAS_SYM(x) \
81 if (!load_nas_sym(#x, (void **) (char *) &NAS_##x)) return -1
82#else
83#define SDL_NAS_SYM(x) NAS_##x = x
84#endif
85
86static int
87load_nas_syms(void)
88{
89 SDL_NAS_SYM(AuCloseServer);
90 SDL_NAS_SYM(AuNextEvent);
91 SDL_NAS_SYM(AuDispatchEvent);
92 SDL_NAS_SYM(AuCreateFlow);
93 SDL_NAS_SYM(AuStartFlow);
94 SDL_NAS_SYM(AuSetElements);
95 SDL_NAS_SYM(AuWriteElement);
96 SDL_NAS_SYM(AuOpenServer);
97 SDL_NAS_SYM(AuRegisterEventHandler);
98 return 0;
99}
100
101#undef SDL_NAS_SYM
102
103#ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC
104
105static void
106UnloadNASLibrary(void)
107{
108 if (nas_handle != NULL) {
109 SDL_UnloadObject(nas_handle);
110 nas_handle = NULL;
111 }
112}
113
114static int
115LoadNASLibrary(void)
116{
117 int retval = 0;
118 if (nas_handle == NULL) {
119 nas_handle = SDL_LoadObject(nas_library);
120 if (nas_handle == NULL) {
121 /* Copy error string so we can use it in a new SDL_SetError(). */
122 char *origerr = SDL_GetError();
123 size_t len = SDL_strlen(origerr) + 1;
124 char *err = (char *) alloca(len);
125 SDL_strlcpy(err, origerr, len);
126 retval = -1;
127 SDL_SetError("NAS: SDL_LoadObject('%s') failed: %s\n",
128 nas_library, err);
129 } else {
130 retval = load_nas_syms();
131 if (retval < 0) {
132 UnloadNASLibrary();
133 }
134 }
135 }
136 return retval;
137}
138
139#else
140
141static void
142UnloadNASLibrary(void)
143{
144}
145
146static int
147LoadNASLibrary(void)
148{
149 load_nas_syms();
150 return 0;
151}
152
153#endif /* SDL_AUDIO_DRIVER_NAS_DYNAMIC */
154
155
156/* Audio driver functions */
157static int NAS_OpenAudio(_THIS, SDL_AudioSpec *spec);
158static void NAS_WaitAudio(_THIS);
159static void NAS_PlayAudio(_THIS);
160static Uint8 *NAS_GetAudioBuf(_THIS);
161static void NAS_CloseAudio(_THIS);
162
163/* Audio driver bootstrap functions */
164
165static int Audio_Available(void)
166{
167 if (LoadNASLibrary() == 0) {
168 AuServer *aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL);
169 if (!aud) {
170 UnloadNASLibrary();
171 return 0;
172 }
173 NAS_AuCloseServer(aud);
174 UnloadNASLibrary();
175 return 1;
176 }
177 return 0;
178}
179
180static void Audio_DeleteDevice(SDL_AudioDevice *device)
181{
182 UnloadNASLibrary();
183 SDL_free(device->hidden);
184 SDL_free(device);
185}
186
187static SDL_AudioDevice *Audio_CreateDevice(int devindex)
188{
189 SDL_AudioDevice *this;
190
191 if (LoadNASLibrary() < 0) {
192 return NULL;
193 }
194
195 /* Initialize all variables that we clean on shutdown */
196 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
197 if ( this ) {
198 SDL_memset(this, 0, (sizeof *this));
199 this->hidden = (struct SDL_PrivateAudioData *)
200 SDL_malloc((sizeof *this->hidden));
201 }
202 if ( (this == NULL) || (this->hidden == NULL) ) {
203 SDL_OutOfMemory();
204 if ( this ) {
205 SDL_free(this);
206 }
207 return NULL;
208 }
209 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
210
211 /* Set the function pointers */
212 this->OpenAudio = NAS_OpenAudio;
213 this->WaitAudio = NAS_WaitAudio;
214 this->PlayAudio = NAS_PlayAudio;
215 this->GetAudioBuf = NAS_GetAudioBuf;
216 this->CloseAudio = NAS_CloseAudio;
217
218 this->free = Audio_DeleteDevice;
219
220 return this;
221}
222
223AudioBootStrap NAS_bootstrap = {
224 NAS_DRIVER_NAME, "Network Audio System",
225 Audio_Available, Audio_CreateDevice
226};
227
228/* This function waits until it is possible to write a full sound buffer */
229static void NAS_WaitAudio(_THIS)
230{
231 while ( this->hidden->buf_free < this->hidden->mixlen ) {
232 AuEvent ev;
233 NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev);
234 NAS_AuDispatchEvent(this->hidden->aud, &ev);
235 }
236}
237
238static void NAS_PlayAudio(_THIS)
239{
240 while (this->hidden->mixlen > this->hidden->buf_free) { /* We think the buffer is full? Yikes! Ask the server for events,
241 in the hope that some of them is LowWater events telling us more
242 of the buffer is free now than what we think. */
243 AuEvent ev;
244 NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev);
245 NAS_AuDispatchEvent(this->hidden->aud, &ev);
246 }
247 this->hidden->buf_free -= this->hidden->mixlen;
248
249 /* Write the audio data */
250 NAS_AuWriteElement(this->hidden->aud, this->hidden->flow, 0, this->hidden->mixlen, this->hidden->mixbuf, AuFalse, NULL);
251
252 this->hidden->written += this->hidden->mixlen;
253
254#ifdef DEBUG_AUDIO
255 fprintf(stderr, "Wrote %d bytes of audio data\n", this->hidden->mixlen);
256#endif
257}
258
259static Uint8 *NAS_GetAudioBuf(_THIS)
260{
261 return(this->hidden->mixbuf);
262}
263
264static void NAS_CloseAudio(_THIS)
265{
266 if ( this->hidden->mixbuf != NULL ) {
267 SDL_FreeAudioMem(this->hidden->mixbuf);
268 this->hidden->mixbuf = NULL;
269 }
270 if ( this->hidden->aud ) {
271 NAS_AuCloseServer(this->hidden->aud);
272 this->hidden->aud = 0;
273 }
274}
275
276static unsigned char sdlformat_to_auformat(unsigned int fmt)
277{
278 switch (fmt)
279 {
280 case AUDIO_U8:
281 return AuFormatLinearUnsigned8;
282 case AUDIO_S8:
283 return AuFormatLinearSigned8;
284 case AUDIO_U16LSB:
285 return AuFormatLinearUnsigned16LSB;
286 case AUDIO_U16MSB:
287 return AuFormatLinearUnsigned16MSB;
288 case AUDIO_S16LSB:
289 return AuFormatLinearSigned16LSB;
290 case AUDIO_S16MSB:
291 return AuFormatLinearSigned16MSB;
292 }
293 return AuNone;
294}
295
296static AuBool
297event_handler(AuServer* aud, AuEvent* ev, AuEventHandlerRec* hnd)
298{
299 switch (ev->type) {
300 case AuEventTypeElementNotify: {
301 AuElementNotifyEvent* event = (AuElementNotifyEvent *)ev;
302
303 switch (event->kind) {
304 case AuElementNotifyKindLowWater:
305 if (this2->buf_free >= 0) {
306 this2->really += event->num_bytes;
307 gettimeofday(&this2->last_tv, 0);
308 this2->buf_free += event->num_bytes;
309 } else {
310 this2->buf_free = event->num_bytes;
311 }
312 break;
313 case AuElementNotifyKindState:
314 switch (event->cur_state) {
315 case AuStatePause:
316 if (event->reason != AuReasonUser) {
317 if (this2->buf_free >= 0) {
318 this2->really += event->num_bytes;
319 gettimeofday(&this2->last_tv, 0);
320 this2->buf_free += event->num_bytes;
321 } else {
322 this2->buf_free = event->num_bytes;
323 }
324 }
325 break;
326 }
327 }
328 }
329 }
330 return AuTrue;
331}
332
333static AuDeviceID
334find_device(_THIS, int nch)
335{
336 /* These "Au" things are all macros, not functions... */
337 int i;
338 for (i = 0; i < AuServerNumDevices(this->hidden->aud); i++) {
339 if ((AuDeviceKind(AuServerDevice(this->hidden->aud, i)) ==
340 AuComponentKindPhysicalOutput) &&
341 AuDeviceNumTracks(AuServerDevice(this->hidden->aud, i)) == nch) {
342 return AuDeviceIdentifier(AuServerDevice(this->hidden->aud, i));
343 }
344 }
345 return AuNone;
346}
347
348static int NAS_OpenAudio(_THIS, SDL_AudioSpec *spec)
349{
350 AuElement elms[3];
351 int buffer_size;
352 Uint16 test_format, format;
353
354 this->hidden->mixbuf = NULL;
355
356 /* Try for a closest match on audio format */
357 format = 0;
358 for ( test_format = SDL_FirstAudioFormat(spec->format);
359 ! format && test_format; ) {
360 format = sdlformat_to_auformat(test_format);
361
362 if (format == AuNone) {
363 test_format = SDL_NextAudioFormat();
364 }
365 }
366 if ( format == 0 ) {
367 SDL_SetError("Couldn't find any hardware audio formats");
368 return(-1);
369 }
370 spec->format = test_format;
371
372 this->hidden->aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL);
373 if (this->hidden->aud == 0)
374 {
375 SDL_SetError("Couldn't open connection to NAS server");
376 return (-1);
377 }
378
379 this->hidden->dev = find_device(this, spec->channels);
380 if ((this->hidden->dev == AuNone) || (!(this->hidden->flow = NAS_AuCreateFlow(this->hidden->aud, NULL)))) {
381 NAS_AuCloseServer(this->hidden->aud);
382 this->hidden->aud = 0;
383 SDL_SetError("Couldn't find a fitting playback device on NAS server");
384 return (-1);
385 }
386
387 buffer_size = spec->freq;
388 if (buffer_size < 4096)
389 buffer_size = 4096;
390
391 if (buffer_size > 32768)
392 buffer_size = 32768; /* So that the buffer won't get unmanageably big. */
393
394 /* Calculate the final parameters for this audio specification */
395 SDL_CalculateAudioSpec(spec);
396
397 this2 = this->hidden;
398
399 /* These "Au" things without a NAS_ prefix are macros, not functions... */
400 AuMakeElementImportClient(elms, spec->freq, format, spec->channels, AuTrue,
401 buffer_size, buffer_size / 4, 0, NULL);
402 AuMakeElementExportDevice(elms+1, 0, this->hidden->dev, spec->freq,
403 AuUnlimitedSamples, 0, NULL);
404 NAS_AuSetElements(this->hidden->aud, this->hidden->flow, AuTrue, 2, elms, NULL);
405 NAS_AuRegisterEventHandler(this->hidden->aud, AuEventHandlerIDMask, 0, this->hidden->flow,
406 event_handler, (AuPointer) NULL);
407
408 NAS_AuStartFlow(this->hidden->aud, this->hidden->flow, NULL);
409
410 /* Allocate mixing buffer */
411 this->hidden->mixlen = spec->size;
412 this->hidden->mixbuf = (Uint8 *)SDL_AllocAudioMem(this->hidden->mixlen);
413 if ( this->hidden->mixbuf == NULL ) {
414 return(-1);
415 }
416 SDL_memset(this->hidden->mixbuf, spec->silence, spec->size);
417
418 /* Get the parent process id (we're the parent of the audio thread) */
419 this->hidden->parent = getpid();
420
421 /* We're ready to rock and roll. :-) */
422 return(0);
423}
diff --git a/apps/plugins/sdl/src/audio/nas/SDL_nasaudio.h b/apps/plugins/sdl/src/audio/nas/SDL_nasaudio.h
deleted file mode 100644
index 1c09630880..0000000000
--- a/apps/plugins/sdl/src/audio/nas/SDL_nasaudio.h
+++ /dev/null
@@ -1,62 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 This driver was written by:
23 Erik Inge Bolsø
24 knan@mo.himolde.no
25*/
26#include "SDL_config.h"
27
28#ifndef _SDL_nasaudio_h
29#define _SDL_nasaudio_h
30
31#ifdef __sgi
32#include <nas/audiolib.h>
33#else
34#include <audio/audiolib.h>
35#endif
36#include <sys/time.h>
37
38#include "../SDL_sysaudio.h"
39
40/* Hidden "this" pointer for the video functions */
41#define _THIS SDL_AudioDevice *this
42
43struct SDL_PrivateAudioData {
44 AuServer* aud;
45 AuFlowID flow;
46 AuDeviceID dev;
47
48 /* The parent process id, to detect when application quits */
49 pid_t parent;
50
51 /* Raw mixing buffer */
52 Uint8 *mixbuf;
53 int mixlen;
54
55 int written;
56 int really;
57 int bps;
58 struct timeval last_tv;
59 int buf_free;
60};
61#endif /* _SDL_nasaudio_h */
62
diff --git a/apps/plugins/sdl/src/audio/nds/SDL_ndsaudio.c b/apps/plugins/sdl/src/audio/nds/SDL_ndsaudio.c
deleted file mode 100644
index afe141a567..0000000000
--- a/apps/plugins/sdl/src/audio/nds/SDL_ndsaudio.c
+++ /dev/null
@@ -1,335 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer */
25#include <nds.h>
26#include "SDL.h"
27#include "SDL_endian.h"
28#include "SDL_timer.h"
29#include "SDL_audio.h"
30#include "../SDL_audiomem.h"
31#include "../SDL_audio_c.h"
32#include "SDL_ndsaudio.h"
33#include "soundcommon.h"
34
35
36/* Audio driver functions */
37static int NDS_OpenAudio(_THIS, SDL_AudioSpec *spec);
38static void NDS_WaitAudio(_THIS);
39static void NDS_PlayAudio(_THIS);
40static Uint8 *NDS_GetAudioBuf(_THIS);
41static void NDS_CloseAudio(_THIS);
42
43/* Audio driver bootstrap functions */
44
45u32 framecounter = 0,soundoffset = 0;
46static SDL_AudioDevice *sdl_nds_audiodevice;
47
48//void SoundMixCallback(void *stream,u32 size)
49//{
50// //printf("SoundMixCallback\n");
51//
52// Uint8 *buffer;
53//
54// buffer = sdl_nds_audiodevice->hidden->mixbuf;
55// memset(buffer, sdl_nds_audiodevice->spec.silence, size);
56//
57// if (!sdl_nds_audiodevice->paused){
58//
59//
60// //if (sdl_nds_audiodevice->convert.needed) {
61// // int silence;
62//
63// // if (sdl_nds_audiodevice->convert.src_format == AUDIO_U8 ) {
64// // silence = 0x80;
65// // } else {
66// // silence = 0;
67// // }
68// // memset(sdl_nds_audiodevice->convert.buf, silence, sdl_nds_audiodevice->convert.len);
69// // sdl_nds_audiodevice->spec.callback(sdl_nds_audiodevice->spec.userdata,
70// // (Uint8 *)sdl_nds_audiodevice->convert.buf,sdl_nds_audiodevice->convert.len);
71// // SDL_ConvertAudio(&sdl_nds_audiodevice->convert);
72// // memcpy(buffer, sdl_nds_audiodevice->convert.buf, sdl_nds_audiodevice->convert.len_cvt);
73// //} else
74// {
75// sdl_nds_audiodevice->spec.callback(sdl_nds_audiodevice->spec.userdata, buffer, size);
76// //memcpy((Sint16 *)stream,buffer, size);
77// }
78//
79// }
80//
81// if(soundsystem->format == 8)
82// {
83// int i;
84// s32 *buffer32 = (s32 *)buffer;
85// s32 *stream32 = (s32 *)stream;
86// for(i=0;i<size/4;i++){ *stream32++ = buffer32[i] ^ 0x80808080;}
87// //for(i = 0; i < size; i++)
88// // ((s8*)stream)[i]=(buffer[i]^0x80);
89// }
90// else
91// {
92// int i;
93// for(i = 0; i < size; i++){
94// //((short*)stream)[i] =(short)buffer[i] << 8; // sound 8bit ---> buffer 16bit
95// //if (buffer[i] &0x80)
96// //((Sint16*)stream)[i] = 0xff00 | buffer[i];
97// ((Sint16*)stream)[i] = (buffer[i] - 128) << 8;
98//
99// //else
100// // ((Sint16*)stream)[i] = buffer[i];
101// }
102// //register signed char *pSrc =buffer;
103// //register short *pDest =stream;
104// //int x;
105// // for (x=size; x>0; x--)
106// // {
107// // register short temp = (((short)*pSrc)-128)<<8;
108// // pSrc++;
109// // *pDest++ = temp;
110// // }
111//
112// //memcpy((Sint16 *)stream,buffer, size);
113// }
114//}
115
116void SoundMixCallback(void *stream,u32 len)
117{
118 SDL_AudioDevice *audio = (SDL_AudioDevice *)sdl_nds_audiodevice;
119
120 /* Silence the buffer, since it's ours */
121 SDL_memset(stream, audio->spec.silence, len);
122
123 /* Only do soemthing if audio is enabled */
124 if ( ! audio->enabled )
125 return;
126
127 if ( ! audio->paused ) {
128 if ( audio->convert.needed ) {
129 //fprintf(stderr,"converting audio\n");
130 SDL_mutexP(audio->mixer_lock);
131 (*audio->spec.callback)(audio->spec.userdata,
132 (Uint8 *)audio->convert.buf,audio->convert.len);
133 SDL_mutexV(audio->mixer_lock);
134 SDL_ConvertAudio(&audio->convert);
135 SDL_memcpy(stream,audio->convert.buf,audio->convert.len_cvt);
136 } else {
137 SDL_mutexP(audio->mixer_lock);
138 (*audio->spec.callback)(audio->spec.userdata,
139 (Uint8 *)stream, len);
140 SDL_mutexV(audio->mixer_lock);
141 }
142 }
143 return;
144}
145void MixSound(void)
146{
147 int remain;
148
149 if(soundsystem->format == 8)
150 {
151 if((soundsystem->soundcursor + soundsystem->numsamples) > soundsystem->buffersize)
152 {
153 SoundMixCallback(&soundsystem->mixbuffer[soundsystem->soundcursor],soundsystem->buffersize - soundsystem->soundcursor);
154 remain = soundsystem->numsamples - (soundsystem->buffersize - soundsystem->soundcursor);
155 SoundMixCallback(soundsystem->mixbuffer,remain);
156 }
157 else
158 {
159 SoundMixCallback(&soundsystem->mixbuffer[soundsystem->soundcursor],soundsystem->numsamples);
160 }
161 }
162 else
163 {
164 if((soundsystem->soundcursor + soundsystem->numsamples) > (soundsystem->buffersize >> 1))
165 {
166 SoundMixCallback(&soundsystem->mixbuffer[soundsystem->soundcursor << 1],(soundsystem->buffersize >> 1) - soundsystem->soundcursor);
167 remain = soundsystem->numsamples - ((soundsystem->buffersize >> 1) - soundsystem->soundcursor);
168 SoundMixCallback(soundsystem->mixbuffer,remain);
169 }
170 else
171 {
172 SoundMixCallback(&soundsystem->mixbuffer[soundsystem->soundcursor << 1],soundsystem->numsamples);
173 }
174 }
175}
176
177void InterruptHandler(void)
178{
179 framecounter++;
180}
181void FiFoHandler(void)
182{
183 u32 command;
184 while ( !(REG_IPC_FIFO_CR & (IPC_FIFO_RECV_EMPTY)) )
185 {
186 command = REG_IPC_FIFO_RX;
187
188 switch(command)
189 {
190 case FIFO_NONE:
191 break;
192 case UPDATEON_ARM9:
193 REG_IME = 0;
194 MixSound();
195 REG_IME = 1;
196 SendCommandToArm7(MIXCOMPLETE_ONARM9);
197 break;
198 }
199 }
200}
201
202
203
204
205
206static int Audio_Available(void)
207{
208 return(1);
209}
210
211static void Audio_DeleteDevice(SDL_AudioDevice *device)
212{
213}
214
215static SDL_AudioDevice *Audio_CreateDevice(int devindex)
216{
217
218 SDL_AudioDevice *this;
219
220 /* Initialize all variables that we clean on shutdown */
221 this = (SDL_AudioDevice *)malloc(sizeof(SDL_AudioDevice));
222 if ( this ) {
223 SDL_memset(this, 0, (sizeof *this));
224 this->hidden = (struct SDL_PrivateAudioData *)
225 SDL_malloc((sizeof *this->hidden));
226 }
227 if ( (this == NULL) || (this->hidden == NULL) ) {
228 SDL_OutOfMemory();
229 if ( this ) {
230 SDL_free(this);
231 }
232 return(0);
233 }
234 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
235
236 /* Set the function pointers */
237 this->OpenAudio = NDS_OpenAudio;
238 this->WaitAudio = NDS_WaitAudio;
239 this->PlayAudio = NDS_PlayAudio;
240 this->GetAudioBuf = NDS_GetAudioBuf;
241 this->CloseAudio = NDS_CloseAudio;
242
243 this->free = Audio_DeleteDevice;
244//fprintf(stderr,"Audio_CreateDevice\n");
245 return this;
246}
247
248AudioBootStrap NDSAUD_bootstrap = {
249 "nds", "NDS audio",
250 Audio_Available, Audio_CreateDevice
251};
252
253
254void static NDS_WaitAudio(_THIS)
255{
256 //printf("NDS_WaitAudio\n");
257}
258
259static void NDS_PlayAudio(_THIS)
260{
261 //printf("playing audio\n");
262 if (this->paused)
263 return;
264
265}
266
267static Uint8 *NDS_GetAudioBuf(_THIS)
268{
269 return NULL;//(this->hidden->mixbuf);
270}
271
272static void NDS_CloseAudio(_THIS)
273{
274/* if ( this->hidden->mixbuf != NULL ) {
275 SDL_FreeAudioMem(this->hidden->mixbuf);
276 this->hidden->mixbuf = NULL;
277 }*/
278}
279
280static int NDS_OpenAudio(_THIS, SDL_AudioSpec *spec)
281{
282 //printf("NDS_OpenAudio\n");
283 int format = 0;
284 //switch(spec->format&0xff) {
285 //case 8: spec->format = AUDIO_S8;format=8; break;
286 //case 16: spec->format = AUDIO_S16LSB;format=16; break;
287 //default:
288 // SDL_SetError("Unsupported audio format");
289 // return(-1);
290 //}
291 switch (spec->format&~0x1000) {
292 case AUDIO_S8:
293 /* Signed 8-bit audio supported */
294 format=8;
295 break;
296 case AUDIO_U8:
297 spec->format ^= 0x80;format=8;
298 break;
299 case AUDIO_U16:
300 /* Unsigned 16-bit audio unsupported, convert to S16 */
301 spec->format ^=0x8000;format=16;
302 case AUDIO_S16:
303 /* Signed 16-bit audio supported */
304 format=16;
305 break;
306 }
307 /* Update the fragment size as size in bytes */
308 SDL_CalculateAudioSpec(spec);
309
310 /* Allocate mixing buffer */
311 //this->hidden->mixlen = spec->size;
312 //this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen);
313 //if ( this->hidden->mixbuf == NULL ) {
314 // SDL_SetError("Out of Memory");
315 // return(-1);
316 //}
317
318 SDL_NDSAudio_mutex = 0;
319 sdl_nds_audiodevice=this;
320
321 irqInit();
322 irqSet(IRQ_VBLANK,&InterruptHandler);
323 irqSet(IRQ_FIFO_NOT_EMPTY,&FiFoHandler);
324 irqEnable(IRQ_FIFO_NOT_EMPTY);
325
326 REG_IPC_FIFO_CR = IPC_FIFO_ENABLE | IPC_FIFO_SEND_CLEAR | IPC_FIFO_RECV_IRQ;
327
328
329
330 SoundSystemInit(spec->freq,spec->size,0,format);
331 SoundStartMixer();
332
333
334 return(1);
335}
diff --git a/apps/plugins/sdl/src/audio/nds/SDL_ndsaudio.h b/apps/plugins/sdl/src/audio/nds/SDL_ndsaudio.h
deleted file mode 100644
index cb6d1ea858..0000000000
--- a/apps/plugins/sdl/src/audio/nds/SDL_ndsaudio.h
+++ /dev/null
@@ -1,40 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowaudio_h
25#define _SDL_lowaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the audio functions */
30#define _THIS SDL_AudioDevice *this
31
32struct SDL_PrivateAudioData {
33 /* The file descriptor for the audio device */
34 //Uint8 *mixbuf;
35 //Uint32 mixlen;
36};
37unsigned short SDL_NDSAudio_mutex=0;
38
39
40#endif /* _SDL_lowaudio_h */
diff --git a/apps/plugins/sdl/src/audio/nds/sound9.c b/apps/plugins/sdl/src/audio/nds/sound9.c
deleted file mode 100644
index 59c1c219ae..0000000000
--- a/apps/plugins/sdl/src/audio/nds/sound9.c
+++ /dev/null
@@ -1,61 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23#include "SDL_stdinc.h"
24
25#include "soundcommon.h"
26
27void SoundSystemInit(u32 rate,u32 buffersize,u8 channel,u8 format)
28{
29 soundsystem->rate = rate;
30
31 if(format == 8)
32 soundsystem->buffersize = buffersize;
33 else if(format == 16)
34 soundsystem->buffersize = buffersize * sizeof(short);
35
36 soundsystem->mixbuffer = (s8*)SDL_malloc(soundsystem->buffersize);
37 //soundsystem->soundbuffer = soundsystem->mixbuffer;
38 soundsystem->format = format;
39 soundsystem->channel = channel;
40 soundsystem->prevtimer = 0;
41 soundsystem->soundcursor = 0;
42 soundsystem->numsamples = 0;
43 soundsystem->period = 0x1000000 / rate;
44 soundsystem->cmd = INIT;
45}
46
47void SoundStartMixer(void)
48{
49 soundsystem->cmd |= MIX;
50}
51
52void SendCommandToArm7(u32 command)
53{
54 while (REG_IPC_FIFO_CR & IPC_FIFO_SEND_FULL);
55 if (REG_IPC_FIFO_CR & IPC_FIFO_ERROR)
56 {
57 REG_IPC_FIFO_CR |= IPC_FIFO_SEND_CLEAR;
58 }
59
60 REG_IPC_FIFO_TX = command;
61}
diff --git a/apps/plugins/sdl/src/audio/nds/soundcommon.h b/apps/plugins/sdl/src/audio/nds/soundcommon.h
deleted file mode 100644
index d38e37cf68..0000000000
--- a/apps/plugins/sdl/src/audio/nds/soundcommon.h
+++ /dev/null
@@ -1,80 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SOUNDCOMMON_H
25#define __SOUNDCOMMON_H
26
27#include <nds.h>
28
29#define CLOCK (1 << 25)
30
31#ifdef __cplusplus
32extern "C" {
33#endif
34
35typedef enum
36{
37 NONE = 0,
38 INIT = 1,
39 MIX = 2,
40 MIXING = 4,
41 STOP = 8
42}CommandType;
43
44typedef enum
45{
46 FIFO_NONE = 0,
47 UPDATEON_ARM9 = 1,
48 MIXCOMPLETE_ONARM9 = 2,
49}FifoType;
50
51typedef struct
52{
53 s8 *mixbuffer;//,*soundbuffer;
54 u32 rate;
55 u32 buffersize;
56 u32 cmd;
57 u8 channel,format;
58 u32 soundcursor,numsamples;
59 s32 prevtimer;
60 s16 period;
61}S_SoundSystem;
62
63#define soundsystem ((S_SoundSystem*)((u32)(IPC)+sizeof(TransferRegion)))
64
65#ifdef ARM9
66extern void SoundSystemInit(u32 rate,u32 buffersize,u8 channel,u8 format);
67extern void SoundStartMixer(void);
68extern void SendCommandToArm7(u32 command);
69#else
70extern void SoundVBlankIrq(void);
71extern void SoundSwapAndMix(void);
72extern void SoundSetTimer(int period);
73extern void SoundFifoHandler(void);
74extern void SendCommandToArm9(u32 command);
75#endif
76
77#ifdef __cplusplus
78}
79#endif
80#endif
diff --git a/apps/plugins/sdl/src/audio/nto/SDL_nto_audio.c b/apps/plugins/sdl/src/audio/nto/SDL_nto_audio.c
deleted file mode 100644
index f951825460..0000000000
--- a/apps/plugins/sdl/src/audio/nto/SDL_nto_audio.c
+++ /dev/null
@@ -1,507 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <errno.h>
25#include <unistd.h>
26#include <fcntl.h>
27#include <signal.h>
28#include <sys/types.h>
29#include <sys/time.h>
30#include <sched.h>
31#include <sys/select.h>
32#include <sys/neutrino.h>
33#include <sys/asoundlib.h>
34
35#include "SDL_timer.h"
36#include "SDL_audio.h"
37#include "../SDL_audiomem.h"
38#include "../SDL_audio_c.h"
39#include "SDL_nto_audio.h"
40
41/* The tag name used by NTO audio */
42#define DRIVER_NAME "qsa-nto"
43
44/* default channel communication parameters */
45#define DEFAULT_CPARAMS_RATE 22050
46#define DEFAULT_CPARAMS_VOICES 1
47/* FIXME: need to add in the near future flexible logic with frag_size and frags count */
48#define DEFAULT_CPARAMS_FRAG_SIZE 4096
49#define DEFAULT_CPARAMS_FRAGS_MIN 1
50#define DEFAULT_CPARAMS_FRAGS_MAX 1
51
52/* Open the audio device for playback, and don't block if busy */
53#define OPEN_FLAGS SND_PCM_OPEN_PLAYBACK
54
55#define QSA_NO_WORKAROUNDS 0x00000000
56#define QSA_MMAP_WORKAROUND 0x00000001
57
58struct BuggyCards
59{
60 char* cardname;
61 unsigned long bugtype;
62};
63
64#define QSA_WA_CARDS 3
65
66struct BuggyCards buggycards[QSA_WA_CARDS]=
67{
68 {"Sound Blaster Live!", QSA_MMAP_WORKAROUND},
69 {"Vortex 8820", QSA_MMAP_WORKAROUND},
70 {"Vortex 8830", QSA_MMAP_WORKAROUND},
71};
72
73/* Audio driver functions */
74static void NTO_ThreadInit(_THIS);
75static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec);
76static void NTO_WaitAudio(_THIS);
77static void NTO_PlayAudio(_THIS);
78static Uint8* NTO_GetAudioBuf(_THIS);
79static void NTO_CloseAudio(_THIS);
80
81/* card names check to apply the workarounds */
82static int NTO_CheckBuggyCards(_THIS, unsigned long checkfor)
83{
84 char scardname[33];
85 int it;
86
87 if (snd_card_get_name(cardno, scardname, 32)<0)
88 {
89 return 0;
90 }
91
92 for (it=0; it<QSA_WA_CARDS; it++)
93 {
94 if (SDL_strcmp(buggycards[it].cardname, scardname)==0)
95 {
96 if (buggycards[it].bugtype==checkfor)
97 {
98 return 1;
99 }
100 }
101 }
102
103 return 0;
104}
105
106static void NTO_ThreadInit(_THIS)
107{
108 int status;
109 struct sched_param param;
110
111 /* increasing default 10 priority to 25 to avoid jerky sound */
112 status=SchedGet(0, 0, &param);
113 param.sched_priority=param.sched_curpriority+15;
114 status=SchedSet(0, 0, SCHED_NOCHANGE, &param);
115}
116
117/* PCM transfer channel parameters initialize function */
118static void NTO_InitAudioParams(snd_pcm_channel_params_t* cpars)
119{
120 SDL_memset(cpars, 0, sizeof(snd_pcm_channel_params_t));
121
122 cpars->channel = SND_PCM_CHANNEL_PLAYBACK;
123 cpars->mode = SND_PCM_MODE_BLOCK;
124 cpars->start_mode = SND_PCM_START_DATA;
125 cpars->stop_mode = SND_PCM_STOP_STOP;
126 cpars->format.format = SND_PCM_SFMT_S16_LE;
127 cpars->format.interleave = 1;
128 cpars->format.rate = DEFAULT_CPARAMS_RATE;
129 cpars->format.voices = DEFAULT_CPARAMS_VOICES;
130 cpars->buf.block.frag_size = DEFAULT_CPARAMS_FRAG_SIZE;
131 cpars->buf.block.frags_min = DEFAULT_CPARAMS_FRAGS_MIN;
132 cpars->buf.block.frags_max = DEFAULT_CPARAMS_FRAGS_MAX;
133}
134
135static int NTO_AudioAvailable(void)
136{
137 /* See if we can open a nonblocking channel.
138 Return value '1' means we can.
139 Return value '0' means we cannot. */
140
141 int available;
142 int rval;
143 snd_pcm_t* handle;
144
145 available = 0;
146 handle = NULL;
147
148 rval = snd_pcm_open_preferred(&handle, NULL, NULL, OPEN_FLAGS);
149
150 if (rval >= 0)
151 {
152 available = 1;
153
154 if ((rval = snd_pcm_close(handle)) < 0)
155 {
156 SDL_SetError("NTO_AudioAvailable(): snd_pcm_close failed: %s\n", snd_strerror(rval));
157 available = 0;
158 }
159 }
160 else
161 {
162 SDL_SetError("NTO_AudioAvailable(): there are no available audio devices.\n");
163 }
164
165 return (available);
166}
167
168static void NTO_DeleteAudioDevice(SDL_AudioDevice *device)
169{
170 if ((device)&&(device->hidden))
171 {
172 SDL_free(device->hidden);
173 }
174 if (device)
175 {
176 SDL_free(device);
177 }
178}
179
180static SDL_AudioDevice* NTO_CreateAudioDevice(int devindex)
181{
182 SDL_AudioDevice *this;
183
184 /* Initialize all variables that we clean on shutdown */
185 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
186 if (this)
187 {
188 SDL_memset(this, 0, sizeof(SDL_AudioDevice));
189 this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(struct SDL_PrivateAudioData));
190 }
191 if ((this == NULL) || (this->hidden == NULL))
192 {
193 SDL_OutOfMemory();
194 if (this)
195 {
196 SDL_free(this);
197 }
198 return (0);
199 }
200 SDL_memset(this->hidden, 0, sizeof(struct SDL_PrivateAudioData));
201 audio_handle = NULL;
202
203 /* Set the function pointers */
204 this->ThreadInit = NTO_ThreadInit;
205 this->OpenAudio = NTO_OpenAudio;
206 this->WaitAudio = NTO_WaitAudio;
207 this->PlayAudio = NTO_PlayAudio;
208 this->GetAudioBuf = NTO_GetAudioBuf;
209 this->CloseAudio = NTO_CloseAudio;
210
211 this->free = NTO_DeleteAudioDevice;
212
213 return this;
214}
215
216AudioBootStrap QNXNTOAUDIO_bootstrap =
217{
218 DRIVER_NAME, "QNX6 QSA-NTO Audio",
219 NTO_AudioAvailable,
220 NTO_CreateAudioDevice
221};
222
223/* This function waits until it is possible to write a full sound buffer */
224static void NTO_WaitAudio(_THIS)
225{
226 fd_set wfds;
227 int selectret;
228
229 FD_ZERO(&wfds);
230 FD_SET(audio_fd, &wfds);
231
232 do {
233 selectret=select(audio_fd + 1, NULL, &wfds, NULL, NULL);
234 switch (selectret)
235 {
236 case -1:
237 case 0: SDL_SetError("NTO_WaitAudio(): select() failed: %s\n", strerror(errno));
238 return;
239 default: if (FD_ISSET(audio_fd, &wfds))
240 {
241 return;
242 }
243 break;
244 }
245 } while(1);
246}
247
248static void NTO_PlayAudio(_THIS)
249{
250 int written, rval;
251 int towrite;
252 void* pcmbuffer;
253
254 if (!this->enabled)
255 {
256 return;
257 }
258
259 towrite = this->spec.size;
260 pcmbuffer = pcm_buf;
261
262 /* Write the audio data, checking for EAGAIN (buffer full) and underrun */
263 do {
264 written = snd_pcm_plugin_write(audio_handle, pcm_buf, towrite);
265 if (written != towrite)
266 {
267 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
268 {
269 /* Let a little CPU time go by and try to write again */
270 SDL_Delay(1);
271 /* if we wrote some data */
272 towrite -= written;
273 pcmbuffer += written * this->spec.channels;
274 continue;
275 }
276 else
277 {
278 if ((errno == EINVAL) || (errno == EIO))
279 {
280 SDL_memset(&cstatus, 0, sizeof(cstatus));
281 cstatus.channel = SND_PCM_CHANNEL_PLAYBACK;
282 if ((rval = snd_pcm_plugin_status(audio_handle, &cstatus)) < 0)
283 {
284 SDL_SetError("NTO_PlayAudio(): snd_pcm_plugin_status failed: %s\n", snd_strerror(rval));
285 return;
286 }
287 if ((cstatus.status == SND_PCM_STATUS_UNDERRUN) || (cstatus.status == SND_PCM_STATUS_READY))
288 {
289 if ((rval = snd_pcm_plugin_prepare(audio_handle, SND_PCM_CHANNEL_PLAYBACK)) < 0)
290 {
291 SDL_SetError("NTO_PlayAudio(): snd_pcm_plugin_prepare failed: %s\n", snd_strerror(rval));
292 return;
293 }
294 }
295 continue;
296 }
297 else
298 {
299 return;
300 }
301 }
302 }
303 else
304 {
305 /* we wrote all remaining data */
306 towrite -= written;
307 pcmbuffer += written * this->spec.channels;
308 }
309 } while ((towrite > 0) && (this->enabled));
310
311 /* If we couldn't write, assume fatal error for now */
312 if (towrite != 0)
313 {
314 this->enabled = 0;
315 }
316
317 return;
318}
319
320static Uint8* NTO_GetAudioBuf(_THIS)
321{
322 return pcm_buf;
323}
324
325static void NTO_CloseAudio(_THIS)
326{
327 int rval;
328
329 this->enabled = 0;
330
331 if (audio_handle != NULL)
332 {
333 if ((rval = snd_pcm_plugin_flush(audio_handle, SND_PCM_CHANNEL_PLAYBACK)) < 0)
334 {
335 SDL_SetError("NTO_CloseAudio(): snd_pcm_plugin_flush failed: %s\n", snd_strerror(rval));
336 return;
337 }
338 if ((rval = snd_pcm_close(audio_handle)) < 0)
339 {
340 SDL_SetError("NTO_CloseAudio(): snd_pcm_close failed: %s\n",snd_strerror(rval));
341 return;
342 }
343 audio_handle = NULL;
344 }
345}
346
347static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec)
348{
349 int rval;
350 int format;
351 Uint16 test_format;
352 int found;
353
354 audio_handle = NULL;
355 this->enabled = 0;
356
357 if (pcm_buf != NULL)
358 {
359 SDL_FreeAudioMem(pcm_buf);
360 pcm_buf = NULL;
361 }
362
363 /* initialize channel transfer parameters to default */
364 NTO_InitAudioParams(&cparams);
365
366 /* Open the audio device */
367 rval = snd_pcm_open_preferred(&audio_handle, &cardno, &deviceno, OPEN_FLAGS);
368 if (rval < 0)
369 {
370 SDL_SetError("NTO_OpenAudio(): snd_pcm_open failed: %s\n", snd_strerror(rval));
371 return (-1);
372 }
373
374 if (!NTO_CheckBuggyCards(this, QSA_MMAP_WORKAROUND))
375 {
376 /* enable count status parameter */
377 if ((rval = snd_pcm_plugin_set_disable(audio_handle, PLUGIN_DISABLE_MMAP)) < 0)
378 {
379 SDL_SetError("snd_pcm_plugin_set_disable failed: %s\n", snd_strerror(rval));
380 return (-1);
381 }
382 }
383
384 /* Try for a closest match on audio format */
385 format = 0;
386 /* can't use format as SND_PCM_SFMT_U8 = 0 in nto */
387 found = 0;
388
389 for (test_format=SDL_FirstAudioFormat(spec->format); !found ;)
390 {
391 /* if match found set format to equivalent ALSA format */
392 switch (test_format)
393 {
394 case AUDIO_U8:
395 format = SND_PCM_SFMT_U8;
396 found = 1;
397 break;
398 case AUDIO_S8:
399 format = SND_PCM_SFMT_S8;
400 found = 1;
401 break;
402 case AUDIO_S16LSB:
403 format = SND_PCM_SFMT_S16_LE;
404 found = 1;
405 break;
406 case AUDIO_S16MSB:
407 format = SND_PCM_SFMT_S16_BE;
408 found = 1;
409 break;
410 case AUDIO_U16LSB:
411 format = SND_PCM_SFMT_U16_LE;
412 found = 1;
413 break;
414 case AUDIO_U16MSB:
415 format = SND_PCM_SFMT_U16_BE;
416 found = 1;
417 break;
418 default:
419 break;
420 }
421
422 if (!found)
423 {
424 test_format = SDL_NextAudioFormat();
425 }
426 }
427
428 /* assumes test_format not 0 on success */
429 if (test_format == 0)
430 {
431 SDL_SetError("NTO_OpenAudio(): Couldn't find any hardware audio formats");
432 return (-1);
433 }
434
435 spec->format = test_format;
436
437 /* Set the audio format */
438 cparams.format.format = format;
439
440 /* Set mono or stereo audio (currently only two channels supported) */
441 cparams.format.voices = spec->channels;
442
443 /* Set rate */
444 cparams.format.rate = spec->freq;
445
446 /* Setup the transfer parameters according to cparams */
447 rval = snd_pcm_plugin_params(audio_handle, &cparams);
448 if (rval < 0)
449 {
450 SDL_SetError("NTO_OpenAudio(): snd_pcm_channel_params failed: %s\n", snd_strerror(rval));
451 return (-1);
452 }
453
454 /* Make sure channel is setup right one last time */
455 SDL_memset(&csetup, 0x00, sizeof(csetup));
456 csetup.channel = SND_PCM_CHANNEL_PLAYBACK;
457 if (snd_pcm_plugin_setup(audio_handle, &csetup) < 0)
458 {
459 SDL_SetError("NTO_OpenAudio(): Unable to setup playback channel\n");
460 return -1;
461 }
462
463
464 /* Calculate the final parameters for this audio specification */
465 SDL_CalculateAudioSpec(spec);
466
467 pcm_len = spec->size;
468
469 if (pcm_len==0)
470 {
471 pcm_len = csetup.buf.block.frag_size * spec->channels * (snd_pcm_format_width(format)/8);
472 }
473
474 /* Allocate memory to the audio buffer and initialize with silence (Note that
475 buffer size must be a multiple of fragment size, so find closest multiple)
476 */
477 pcm_buf = (Uint8*)SDL_AllocAudioMem(pcm_len);
478 if (pcm_buf == NULL)
479 {
480 SDL_SetError("NTO_OpenAudio(): pcm buffer allocation failed\n");
481 return (-1);
482 }
483 SDL_memset(pcm_buf, spec->silence, pcm_len);
484
485 /* get the file descriptor */
486 if ((audio_fd = snd_pcm_file_descriptor(audio_handle, SND_PCM_CHANNEL_PLAYBACK)) < 0)
487 {
488 SDL_SetError("NTO_OpenAudio(): snd_pcm_file_descriptor failed with error code: %s\n", snd_strerror(rval));
489 return (-1);
490 }
491
492 /* Trigger audio playback */
493 rval = snd_pcm_plugin_prepare(audio_handle, SND_PCM_CHANNEL_PLAYBACK);
494 if (rval < 0)
495 {
496 SDL_SetError("snd_pcm_plugin_prepare failed: %s\n", snd_strerror(rval));
497 return (-1);
498 }
499
500 this->enabled = 1;
501
502 /* Get the parent process id (we're the parent of the audio thread) */
503 parent = getpid();
504
505 /* We're really ready to rock and roll. :-) */
506 return (0);
507}
diff --git a/apps/plugins/sdl/src/audio/nto/SDL_nto_audio.h b/apps/plugins/sdl/src/audio/nto/SDL_nto_audio.h
deleted file mode 100644
index cfd592c96b..0000000000
--- a/apps/plugins/sdl/src/audio/nto/SDL_nto_audio.h
+++ /dev/null
@@ -1,68 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SDL_NTO_AUDIO_H__
25#define __SDL_NTO_AUDIO_H__
26
27#include <sys/asoundlib.h>
28
29#include "../SDL_sysaudio.h"
30
31/* Hidden "this" pointer for the audio functions */
32#define _THIS SDL_AudioDevice *this
33
34struct SDL_PrivateAudioData
35{
36 /* The audio device handle */
37 int cardno;
38 int deviceno;
39 snd_pcm_t* audio_handle;
40
41 /* The audio file descriptor */
42 int audio_fd;
43
44 /* The parent process id, to detect when application quits */
45 pid_t parent;
46
47 /* Raw mixing buffer */
48 Uint8* pcm_buf;
49 Uint32 pcm_len;
50
51 /* QSA parameters */
52 snd_pcm_channel_status_t cstatus;
53 snd_pcm_channel_params_t cparams;
54 snd_pcm_channel_setup_t csetup;
55};
56
57#define cardno (this->hidden->cardno)
58#define deviceno (this->hidden->deviceno)
59#define audio_handle (this->hidden->audio_handle)
60#define audio_fd (this->hidden->audio_fd)
61#define parent (this->hidden->parent)
62#define pcm_buf (this->hidden->pcm_buf)
63#define pcm_len (this->hidden->pcm_len)
64#define cstatus (this->hidden->cstatus)
65#define cparams (this->hidden->cparams)
66#define csetup (this->hidden->csetup)
67
68#endif /* __SDL_NTO_AUDIO_H__ */
diff --git a/apps/plugins/sdl/src/audio/paudio/SDL_paudio.c b/apps/plugins/sdl/src/audio/paudio/SDL_paudio.c
deleted file mode 100644
index 6270d8c0a8..0000000000
--- a/apps/plugins/sdl/src/audio/paudio/SDL_paudio.c
+++ /dev/null
@@ -1,511 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Carsten Griwodz
20 griff@kom.tu-darmstadt.de
21
22 based on linux/SDL_dspaudio.c by Sam Lantinga
23*/
24#include "SDL_config.h"
25
26/* Allow access to a raw mixing buffer */
27
28#include <errno.h>
29#include <unistd.h>
30#include <fcntl.h>
31#include <sys/time.h>
32#include <sys/ioctl.h>
33#include <sys/stat.h>
34
35#include "SDL_timer.h"
36#include "SDL_audio.h"
37#include "../SDL_audiomem.h"
38#include "../SDL_audio_c.h"
39#include "../SDL_audiodev_c.h"
40#include "SDL_paudio.h"
41
42#define DEBUG_AUDIO 1
43
44/* A conflict within AIX 4.3.3 <sys/> headers and probably others as well.
45 * I guess nobody ever uses audio... Shame over AIX header files. */
46#include <sys/machine.h>
47#undef BIG_ENDIAN
48#include <sys/audio.h>
49
50/* The tag name used by paud audio */
51#define Paud_DRIVER_NAME "paud"
52
53/* Open the audio device for playback, and don't block if busy */
54/* #define OPEN_FLAGS (O_WRONLY|O_NONBLOCK) */
55#define OPEN_FLAGS O_WRONLY
56
57/* Audio driver functions */
58static int Paud_OpenAudio(_THIS, SDL_AudioSpec *spec);
59static void Paud_WaitAudio(_THIS);
60static void Paud_PlayAudio(_THIS);
61static Uint8 *Paud_GetAudioBuf(_THIS);
62static void Paud_CloseAudio(_THIS);
63
64/* Audio driver bootstrap functions */
65
66static int Audio_Available(void)
67{
68 int fd;
69 int available;
70
71 available = 0;
72 fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0);
73 if ( fd >= 0 ) {
74 available = 1;
75 close(fd);
76 }
77 return(available);
78}
79
80static void Audio_DeleteDevice(SDL_AudioDevice *device)
81{
82 SDL_free(device->hidden);
83 SDL_free(device);
84}
85
86static SDL_AudioDevice *Audio_CreateDevice(int devindex)
87{
88 SDL_AudioDevice *this;
89
90 /* Initialize all variables that we clean on shutdown */
91 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
92 if ( this ) {
93 SDL_memset(this, 0, (sizeof *this));
94 this->hidden = (struct SDL_PrivateAudioData *)
95 SDL_malloc((sizeof *this->hidden));
96 }
97 if ( (this == NULL) || (this->hidden == NULL) ) {
98 SDL_OutOfMemory();
99 if ( this ) {
100 SDL_free(this);
101 }
102 return(0);
103 }
104 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
105 audio_fd = -1;
106
107 /* Set the function pointers */
108 this->OpenAudio = Paud_OpenAudio;
109 this->WaitAudio = Paud_WaitAudio;
110 this->PlayAudio = Paud_PlayAudio;
111 this->GetAudioBuf = Paud_GetAudioBuf;
112 this->CloseAudio = Paud_CloseAudio;
113
114 this->free = Audio_DeleteDevice;
115
116 return this;
117}
118
119AudioBootStrap Paud_bootstrap = {
120 Paud_DRIVER_NAME, "AIX Paudio",
121 Audio_Available, Audio_CreateDevice
122};
123
124/* This function waits until it is possible to write a full sound buffer */
125static void Paud_WaitAudio(_THIS)
126{
127 fd_set fdset;
128
129 /* See if we need to use timed audio synchronization */
130 if ( frame_ticks ) {
131 /* Use timer for general audio synchronization */
132 Sint32 ticks;
133
134 ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS;
135 if ( ticks > 0 ) {
136 SDL_Delay(ticks);
137 }
138 } else {
139 audio_buffer paud_bufinfo;
140
141 /* Use select() for audio synchronization */
142 struct timeval timeout;
143 FD_ZERO(&fdset);
144 FD_SET(audio_fd, &fdset);
145
146 if ( ioctl(audio_fd, AUDIO_BUFFER, &paud_bufinfo) < 0 ) {
147#ifdef DEBUG_AUDIO
148 fprintf(stderr, "Couldn't get audio buffer information\n");
149#endif
150 timeout.tv_sec = 10;
151 timeout.tv_usec = 0;
152 } else {
153 long ms_in_buf = paud_bufinfo.write_buf_time;
154 timeout.tv_sec = ms_in_buf/1000;
155 ms_in_buf = ms_in_buf - timeout.tv_sec*1000;
156 timeout.tv_usec = ms_in_buf*1000;
157#ifdef DEBUG_AUDIO
158 fprintf( stderr,
159 "Waiting for write_buf_time=%ld,%ld\n",
160 timeout.tv_sec,
161 timeout.tv_usec );
162#endif
163 }
164
165#ifdef DEBUG_AUDIO
166 fprintf(stderr, "Waiting for audio to get ready\n");
167#endif
168 if ( select(audio_fd+1, NULL, &fdset, NULL, &timeout) <= 0 ) {
169 const char *message = "Audio timeout - buggy audio driver? (disabled)";
170 /*
171 * In general we should never print to the screen,
172 * but in this case we have no other way of letting
173 * the user know what happened.
174 */
175 fprintf(stderr, "SDL: %s - %s\n", strerror(errno), message);
176 this->enabled = 0;
177 /* Don't try to close - may hang */
178 audio_fd = -1;
179#ifdef DEBUG_AUDIO
180 fprintf(stderr, "Done disabling audio\n");
181#endif
182 }
183#ifdef DEBUG_AUDIO
184 fprintf(stderr, "Ready!\n");
185#endif
186 }
187}
188
189static void Paud_PlayAudio(_THIS)
190{
191 int written;
192
193 /* Write the audio data, checking for EAGAIN on broken audio drivers */
194 do {
195 written = write(audio_fd, mixbuf, mixlen);
196 if ( (written < 0) && ((errno == 0) || (errno == EAGAIN)) ) {
197 SDL_Delay(1); /* Let a little CPU time go by */
198 }
199 } while ( (written < 0) &&
200 ((errno == 0) || (errno == EAGAIN) || (errno == EINTR)) );
201
202 /* If timer synchronization is enabled, set the next write frame */
203 if ( frame_ticks ) {
204 next_frame += frame_ticks;
205 }
206
207 /* If we couldn't write, assume fatal error for now */
208 if ( written < 0 ) {
209 this->enabled = 0;
210 }
211#ifdef DEBUG_AUDIO
212 fprintf(stderr, "Wrote %d bytes of audio data\n", written);
213#endif
214}
215
216static Uint8 *Paud_GetAudioBuf(_THIS)
217{
218 return mixbuf;
219}
220
221static void Paud_CloseAudio(_THIS)
222{
223 if ( mixbuf != NULL ) {
224 SDL_FreeAudioMem(mixbuf);
225 mixbuf = NULL;
226 }
227 if ( audio_fd >= 0 ) {
228 close(audio_fd);
229 audio_fd = -1;
230 }
231}
232
233static int Paud_OpenAudio(_THIS, SDL_AudioSpec *spec)
234{
235 char audiodev[1024];
236 int format;
237 int bytes_per_sample;
238 Uint16 test_format;
239 audio_init paud_init;
240 audio_buffer paud_bufinfo;
241 audio_status paud_status;
242 audio_control paud_control;
243 audio_change paud_change;
244
245 /* Reset the timer synchronization flag */
246 frame_ticks = 0.0;
247
248 /* Open the audio device */
249 audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0);
250 if ( audio_fd < 0 ) {
251 SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
252 return -1;
253 }
254
255 /*
256 * We can't set the buffer size - just ask the device for the maximum
257 * that we can have.
258 */
259 if ( ioctl(audio_fd, AUDIO_BUFFER, &paud_bufinfo) < 0 ) {
260 SDL_SetError("Couldn't get audio buffer information");
261 return -1;
262 }
263
264 mixbuf = NULL;
265
266 if ( spec->channels > 1 )
267 spec->channels = 2;
268 else
269 spec->channels = 1;
270
271 /*
272 * Fields in the audio_init structure:
273 *
274 * Ignored by us:
275 *
276 * paud.loadpath[LOAD_PATH]; * DSP code to load, MWave chip only?
277 * paud.slot_number; * slot number of the adapter
278 * paud.device_id; * adapter identification number
279 *
280 * Input:
281 *
282 * paud.srate; * the sampling rate in Hz
283 * paud.bits_per_sample; * 8, 16, 32, ...
284 * paud.bsize; * block size for this rate
285 * paud.mode; * ADPCM, PCM, MU_LAW, A_LAW, SOURCE_MIX
286 * paud.channels; * 1=mono, 2=stereo
287 * paud.flags; * FIXED - fixed length data
288 * * LEFT_ALIGNED, RIGHT_ALIGNED (var len only)
289 * * TWOS_COMPLEMENT - 2's complement data
290 * * SIGNED - signed? comment seems wrong in sys/audio.h
291 * * BIG_ENDIAN
292 * paud.operation; * PLAY, RECORD
293 *
294 * Output:
295 *
296 * paud.flags; * PITCH - pitch is supported
297 * * INPUT - input is supported
298 * * OUTPUT - output is supported
299 * * MONITOR - monitor is supported
300 * * VOLUME - volume is supported
301 * * VOLUME_DELAY - volume delay is supported
302 * * BALANCE - balance is supported
303 * * BALANCE_DELAY - balance delay is supported
304 * * TREBLE - treble control is supported
305 * * BASS - bass control is supported
306 * * BESTFIT_PROVIDED - best fit returned
307 * * LOAD_CODE - DSP load needed
308 * paud.rc; * NO_PLAY - DSP code can't do play requests
309 * * NO_RECORD - DSP code can't do record requests
310 * * INVALID_REQUEST - request was invalid
311 * * CONFLICT - conflict with open's flags
312 * * OVERLOADED - out of DSP MIPS or memory
313 * paud.position_resolution; * smallest increment for position
314 */
315
316 paud_init.srate = spec->freq;
317 paud_init.mode = PCM;
318 paud_init.operation = PLAY;
319 paud_init.channels = spec->channels;
320
321 /* Try for a closest match on audio format */
322 format = 0;
323 for ( test_format = SDL_FirstAudioFormat(spec->format);
324 ! format && test_format; ) {
325#ifdef DEBUG_AUDIO
326 fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
327#endif
328 switch ( test_format ) {
329 case AUDIO_U8:
330 bytes_per_sample = 1;
331 paud_init.bits_per_sample = 8;
332 paud_init.flags = TWOS_COMPLEMENT | FIXED;
333 format = 1;
334 break;
335 case AUDIO_S8:
336 bytes_per_sample = 1;
337 paud_init.bits_per_sample = 8;
338 paud_init.flags = SIGNED |
339 TWOS_COMPLEMENT | FIXED;
340 format = 1;
341 break;
342 case AUDIO_S16LSB:
343 bytes_per_sample = 2;
344 paud_init.bits_per_sample = 16;
345 paud_init.flags = SIGNED |
346 TWOS_COMPLEMENT | FIXED;
347 format = 1;
348 break;
349 case AUDIO_S16MSB:
350 bytes_per_sample = 2;
351 paud_init.bits_per_sample = 16;
352 paud_init.flags = BIG_ENDIAN |
353 SIGNED |
354 TWOS_COMPLEMENT | FIXED;
355 format = 1;
356 break;
357 case AUDIO_U16LSB:
358 bytes_per_sample = 2;
359 paud_init.bits_per_sample = 16;
360 paud_init.flags = TWOS_COMPLEMENT | FIXED;
361 format = 1;
362 break;
363 case AUDIO_U16MSB:
364 bytes_per_sample = 2;
365 paud_init.bits_per_sample = 16;
366 paud_init.flags = BIG_ENDIAN |
367 TWOS_COMPLEMENT | FIXED;
368 format = 1;
369 break;
370 default:
371 break;
372 }
373 if ( ! format ) {
374 test_format = SDL_NextAudioFormat();
375 }
376 }
377 if ( format == 0 ) {
378#ifdef DEBUG_AUDIO
379 fprintf(stderr, "Couldn't find any hardware audio formats\n");
380#endif
381 SDL_SetError("Couldn't find any hardware audio formats");
382 return -1;
383 }
384 spec->format = test_format;
385
386 /*
387 * We know the buffer size and the max number of subsequent writes
388 * that can be pending. If more than one can pend, allow the application
389 * to do something like double buffering between our write buffer and
390 * the device's own buffer that we are filling with write() anyway.
391 *
392 * We calculate spec->samples like this because SDL_CalculateAudioSpec()
393 * will give put paud_bufinfo.write_buf_cap (or paud_bufinfo.write_buf_cap/2)
394 * into spec->size in return.
395 */
396 if ( paud_bufinfo.request_buf_cap == 1 )
397 {
398 spec->samples = paud_bufinfo.write_buf_cap
399 / bytes_per_sample
400 / spec->channels;
401 }
402 else
403 {
404 spec->samples = paud_bufinfo.write_buf_cap
405 / bytes_per_sample
406 / spec->channels
407 / 2;
408 }
409 paud_init.bsize = bytes_per_sample * spec->channels;
410
411 SDL_CalculateAudioSpec(spec);
412
413 /*
414 * The AIX paud device init can't modify the values of the audio_init
415 * structure that we pass to it. So we don't need any recalculation
416 * of this stuff and no reinit call as in linux dsp and dma code.
417 *
418 * /dev/paud supports all of the encoding formats, so we don't need
419 * to do anything like reopening the device, either.
420 */
421 if ( ioctl(audio_fd, AUDIO_INIT, &paud_init) < 0 ) {
422 switch ( paud_init.rc )
423 {
424 case 1 :
425 SDL_SetError("Couldn't set audio format: DSP can't do play requests");
426 return -1;
427 break;
428 case 2 :
429 SDL_SetError("Couldn't set audio format: DSP can't do record requests");
430 return -1;
431 break;
432 case 4 :
433 SDL_SetError("Couldn't set audio format: request was invalid");
434 return -1;
435 break;
436 case 5 :
437 SDL_SetError("Couldn't set audio format: conflict with open's flags");
438 return -1;
439 break;
440 case 6 :
441 SDL_SetError("Couldn't set audio format: out of DSP MIPS or memory");
442 return -1;
443 break;
444 default :
445 SDL_SetError("Couldn't set audio format: not documented in sys/audio.h");
446 return -1;
447 break;
448 }
449 }
450
451 /* Allocate mixing buffer */
452 mixlen = spec->size;
453 mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen);
454 if ( mixbuf == NULL ) {
455 return -1;
456 }
457 SDL_memset(mixbuf, spec->silence, spec->size);
458
459 /*
460 * Set some paramters: full volume, first speaker that we can find.
461 * Ignore the other settings for now.
462 */
463 paud_change.input = AUDIO_IGNORE; /* the new input source */
464 paud_change.output = OUTPUT_1; /* EXTERNAL_SPEAKER,INTERNAL_SPEAKER,OUTPUT_1 */
465 paud_change.monitor = AUDIO_IGNORE; /* the new monitor state */
466 paud_change.volume = 0x7fffffff; /* volume level [0-0x7fffffff] */
467 paud_change.volume_delay = AUDIO_IGNORE; /* the new volume delay */
468 paud_change.balance = 0x3fffffff; /* the new balance */
469 paud_change.balance_delay = AUDIO_IGNORE; /* the new balance delay */
470 paud_change.treble = AUDIO_IGNORE; /* the new treble state */
471 paud_change.bass = AUDIO_IGNORE; /* the new bass state */
472 paud_change.pitch = AUDIO_IGNORE; /* the new pitch state */
473
474 paud_control.ioctl_request = AUDIO_CHANGE;
475 paud_control.request_info = (char*)&paud_change;
476 if ( ioctl(audio_fd, AUDIO_CONTROL, &paud_control) < 0 ) {
477#ifdef DEBUG_AUDIO
478 fprintf(stderr, "Can't change audio display settings\n" );
479#endif
480 }
481
482 /*
483 * Tell the device to expect data. Actual start will wait for
484 * the first write() call.
485 */
486 paud_control.ioctl_request = AUDIO_START;
487 paud_control.position = 0;
488 if ( ioctl(audio_fd, AUDIO_CONTROL, &paud_control) < 0 ) {
489#ifdef DEBUG_AUDIO
490 fprintf(stderr, "Can't start audio play\n" );
491#endif
492 SDL_SetError("Can't start audio play");
493 return -1;
494 }
495
496 /* Check to see if we need to use select() workaround */
497 { char *workaround;
498 workaround = SDL_getenv("SDL_DSP_NOSELECT");
499 if ( workaround ) {
500 frame_ticks = (float)(spec->samples*1000)/spec->freq;
501 next_frame = SDL_GetTicks()+frame_ticks;
502 }
503 }
504
505 /* Get the parent process id (we're the parent of the audio thread) */
506 parent = getpid();
507
508 /* We're ready to rock and roll. :-) */
509 return 0;
510}
511
diff --git a/apps/plugins/sdl/src/audio/paudio/SDL_paudio.h b/apps/plugins/sdl/src/audio/paudio/SDL_paudio.h
deleted file mode 100644
index 72eff1ddef..0000000000
--- a/apps/plugins/sdl/src/audio/paudio/SDL_paudio.h
+++ /dev/null
@@ -1,57 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_paudaudio_h
25#define _SDL_paudaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the video functions */
30#define _THIS SDL_AudioDevice *this
31
32struct SDL_PrivateAudioData {
33 /* The file descriptor for the audio device */
34 int audio_fd;
35
36 /* The parent process id, to detect when application quits */
37 pid_t parent;
38
39 /* Raw mixing buffer */
40 Uint8 *mixbuf;
41 int mixlen;
42
43 /* Support for audio timing using a timer, in addition to select() */
44 float frame_ticks;
45 float next_frame;
46};
47#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
48
49/* Old variable names */
50#define audio_fd (this->hidden->audio_fd)
51#define parent (this->hidden->parent)
52#define mixbuf (this->hidden->mixbuf)
53#define mixlen (this->hidden->mixlen)
54#define frame_ticks (this->hidden->frame_ticks)
55#define next_frame (this->hidden->next_frame)
56
57#endif /* _SDL_paudaudio_h */
diff --git a/apps/plugins/sdl/src/audio/pulse/SDL_pulseaudio.c b/apps/plugins/sdl/src/audio/pulse/SDL_pulseaudio.c
deleted file mode 100644
index 29373f37fd..0000000000
--- a/apps/plugins/sdl/src/audio/pulse/SDL_pulseaudio.c
+++ /dev/null
@@ -1,570 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Stéphan Kochen
20 stephan@kochen.nl
21
22 Based on parts of the ALSA and ESounD output drivers.
23*/
24#include "SDL_config.h"
25
26/* Allow access to an PulseAudio network stream mixing buffer */
27
28#include <sys/types.h>
29#include <unistd.h>
30#include <signal.h>
31#include <errno.h>
32#include <pulse/pulseaudio.h>
33#include <pulse/simple.h>
34
35#include "SDL_timer.h"
36#include "SDL_audio.h"
37#include "../SDL_audiomem.h"
38#include "../SDL_audio_c.h"
39#include "../SDL_audiodev_c.h"
40#include "../../../include/SDL_video.h" /* for SDL_WM_GetCaption(). */
41#include "SDL_pulseaudio.h"
42
43#ifdef SDL_AUDIO_DRIVER_PULSE_DYNAMIC
44#include "SDL_name.h"
45#include "SDL_loadso.h"
46#else
47#define SDL_NAME(X) X
48#endif
49
50/* The tag name used by the driver */
51#define PULSE_DRIVER_NAME "pulse"
52
53/* Audio driver functions */
54static int PULSE_OpenAudio(_THIS, SDL_AudioSpec *spec);
55static void PULSE_WaitAudio(_THIS);
56static void PULSE_PlayAudio(_THIS);
57static Uint8 *PULSE_GetAudioBuf(_THIS);
58static void PULSE_CloseAudio(_THIS);
59static void PULSE_WaitDone(_THIS);
60static void PULSE_SetCaption(_THIS, const char *str);
61
62#ifdef SDL_AUDIO_DRIVER_PULSE_DYNAMIC
63
64static const char *pulse_library = SDL_AUDIO_DRIVER_PULSE_DYNAMIC;
65static void *pulse_handle = NULL;
66static int pulse_loaded = 0;
67
68static pa_simple* (*SDL_NAME(pa_simple_new))(
69 const char *server,
70 const char *name,
71 pa_stream_direction_t dir,
72 const char *dev,
73 const char *stream_name,
74 const pa_sample_spec *ss,
75 const pa_channel_map *map,
76 const pa_buffer_attr *attr,
77 int *error
78);
79static void (*SDL_NAME(pa_simple_free))(pa_simple *s);
80
81static pa_channel_map* (*SDL_NAME(pa_channel_map_init_auto))(
82 pa_channel_map *m,
83 unsigned channels,
84 pa_channel_map_def_t def
85);
86
87static pa_mainloop * (*SDL_NAME(pa_mainloop_new))(void);
88static pa_mainloop_api * (*SDL_NAME(pa_mainloop_get_api))(pa_mainloop *m);
89static int (*SDL_NAME(pa_mainloop_iterate))(pa_mainloop *m, int block, int *retval);
90static void (*SDL_NAME(pa_mainloop_free))(pa_mainloop *m);
91
92static pa_operation_state_t (*SDL_NAME(pa_operation_get_state))(pa_operation *o);
93static void (*SDL_NAME(pa_operation_cancel))(pa_operation *o);
94static void (*SDL_NAME(pa_operation_unref))(pa_operation *o);
95
96static pa_context * (*SDL_NAME(pa_context_new))(
97 pa_mainloop_api *m, const char *name);
98static int (*SDL_NAME(pa_context_connect))(
99 pa_context *c, const char *server,
100 pa_context_flags_t flags, const pa_spawn_api *api);
101static pa_context_state_t (*SDL_NAME(pa_context_get_state))(pa_context *c);
102static void (*SDL_NAME(pa_context_disconnect))(pa_context *c);
103static void (*SDL_NAME(pa_context_unref))(pa_context *c);
104
105static pa_stream * (*SDL_NAME(pa_stream_new))(pa_context *c,
106 const char *name, const pa_sample_spec *ss, const pa_channel_map *map);
107static int (*SDL_NAME(pa_stream_connect_playback))(pa_stream *s, const char *dev,
108 const pa_buffer_attr *attr, pa_stream_flags_t flags,
109 pa_cvolume *volume, pa_stream *sync_stream);
110static pa_stream_state_t (*SDL_NAME(pa_stream_get_state))(pa_stream *s);
111static size_t (*SDL_NAME(pa_stream_writable_size))(pa_stream *s);
112static int (*SDL_NAME(pa_stream_write))(pa_stream *s, const void *data, size_t nbytes,
113 pa_free_cb_t free_cb, int64_t offset, pa_seek_mode_t seek);
114static pa_operation * (*SDL_NAME(pa_stream_drain))(pa_stream *s,
115 pa_stream_success_cb_t cb, void *userdata);
116static int (*SDL_NAME(pa_stream_disconnect))(pa_stream *s);
117static void (*SDL_NAME(pa_stream_unref))(pa_stream *s);
118static pa_operation* (*SDL_NAME(pa_context_set_name))(pa_context *c,
119 const char *name, pa_context_success_cb_t cb, void *userdata);
120
121static struct {
122 const char *name;
123 void **func;
124} pulse_functions[] = {
125 { "pa_simple_new",
126 (void **)&SDL_NAME(pa_simple_new) },
127 { "pa_simple_free",
128 (void **)&SDL_NAME(pa_simple_free) },
129 { "pa_channel_map_init_auto",
130 (void **)&SDL_NAME(pa_channel_map_init_auto) },
131 { "pa_mainloop_new",
132 (void **)&SDL_NAME(pa_mainloop_new) },
133 { "pa_mainloop_get_api",
134 (void **)&SDL_NAME(pa_mainloop_get_api) },
135 { "pa_mainloop_iterate",
136 (void **)&SDL_NAME(pa_mainloop_iterate) },
137 { "pa_mainloop_free",
138 (void **)&SDL_NAME(pa_mainloop_free) },
139 { "pa_operation_get_state",
140 (void **)&SDL_NAME(pa_operation_get_state) },
141 { "pa_operation_cancel",
142 (void **)&SDL_NAME(pa_operation_cancel) },
143 { "pa_operation_unref",
144 (void **)&SDL_NAME(pa_operation_unref) },
145 { "pa_context_new",
146 (void **)&SDL_NAME(pa_context_new) },
147 { "pa_context_connect",
148 (void **)&SDL_NAME(pa_context_connect) },
149 { "pa_context_get_state",
150 (void **)&SDL_NAME(pa_context_get_state) },
151 { "pa_context_disconnect",
152 (void **)&SDL_NAME(pa_context_disconnect) },
153 { "pa_context_unref",
154 (void **)&SDL_NAME(pa_context_unref) },
155 { "pa_stream_new",
156 (void **)&SDL_NAME(pa_stream_new) },
157 { "pa_stream_connect_playback",
158 (void **)&SDL_NAME(pa_stream_connect_playback) },
159 { "pa_stream_get_state",
160 (void **)&SDL_NAME(pa_stream_get_state) },
161 { "pa_stream_writable_size",
162 (void **)&SDL_NAME(pa_stream_writable_size) },
163 { "pa_stream_write",
164 (void **)&SDL_NAME(pa_stream_write) },
165 { "pa_stream_drain",
166 (void **)&SDL_NAME(pa_stream_drain) },
167 { "pa_stream_disconnect",
168 (void **)&SDL_NAME(pa_stream_disconnect) },
169 { "pa_stream_unref",
170 (void **)&SDL_NAME(pa_stream_unref) },
171 { "pa_context_set_name",
172 (void **)&SDL_NAME(pa_context_set_name) },
173};
174
175static void UnloadPulseLibrary()
176{
177 if ( pulse_loaded ) {
178 SDL_UnloadObject(pulse_handle);
179 pulse_handle = NULL;
180 pulse_loaded = 0;
181 }
182}
183
184static int LoadPulseLibrary(void)
185{
186 int i, retval = -1;
187
188 pulse_handle = SDL_LoadObject(pulse_library);
189 if ( pulse_handle ) {
190 pulse_loaded = 1;
191 retval = 0;
192 for ( i=0; i<SDL_arraysize(pulse_functions); ++i ) {
193 *pulse_functions[i].func = SDL_LoadFunction(pulse_handle, pulse_functions[i].name);
194 if ( !*pulse_functions[i].func ) {
195 retval = -1;
196 UnloadPulseLibrary();
197 break;
198 }
199 }
200 }
201 return retval;
202}
203
204#else
205
206static void UnloadPulseLibrary()
207{
208 return;
209}
210
211static int LoadPulseLibrary(void)
212{
213 return 0;
214}
215
216#endif /* SDL_AUDIO_DRIVER_PULSE_DYNAMIC */
217
218/* Audio driver bootstrap functions */
219
220static int Audio_Available(void)
221{
222 pa_sample_spec paspec;
223 pa_simple *connection;
224 int available;
225
226 available = 0;
227 if ( LoadPulseLibrary() < 0 ) {
228 return available;
229 }
230
231 /* Connect with a dummy format. */
232 paspec.format = PA_SAMPLE_U8;
233 paspec.rate = 11025;
234 paspec.channels = 1;
235 connection = SDL_NAME(pa_simple_new)(
236 NULL, /* server */
237 "Test stream", /* application name */
238 PA_STREAM_PLAYBACK, /* playback mode */
239 NULL, /* device on the server */
240 "Simple DirectMedia Layer", /* stream description */
241 &paspec, /* sample format spec */
242 NULL, /* channel map */
243 NULL, /* buffering attributes */
244 NULL /* error code */
245 );
246 if ( connection != NULL ) {
247 available = 1;
248 SDL_NAME(pa_simple_free)(connection);
249 }
250
251 UnloadPulseLibrary();
252 return(available);
253}
254
255static void Audio_DeleteDevice(SDL_AudioDevice *device)
256{
257 SDL_free(device->hidden->caption);
258 SDL_free(device->hidden);
259 SDL_free(device);
260 UnloadPulseLibrary();
261}
262
263static SDL_AudioDevice *Audio_CreateDevice(int devindex)
264{
265 SDL_AudioDevice *this;
266
267 /* Initialize all variables that we clean on shutdown */
268 LoadPulseLibrary();
269 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
270 if ( this ) {
271 SDL_memset(this, 0, (sizeof *this));
272 this->hidden = (struct SDL_PrivateAudioData *)
273 SDL_malloc((sizeof *this->hidden));
274 }
275 if ( (this == NULL) || (this->hidden == NULL) ) {
276 SDL_OutOfMemory();
277 if ( this ) {
278 SDL_free(this);
279 }
280 return(0);
281 }
282 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
283
284 /* Set the function pointers */
285 this->OpenAudio = PULSE_OpenAudio;
286 this->WaitAudio = PULSE_WaitAudio;
287 this->PlayAudio = PULSE_PlayAudio;
288 this->GetAudioBuf = PULSE_GetAudioBuf;
289 this->CloseAudio = PULSE_CloseAudio;
290 this->WaitDone = PULSE_WaitDone;
291 this->SetCaption = PULSE_SetCaption;
292
293 this->free = Audio_DeleteDevice;
294
295 return this;
296}
297
298AudioBootStrap PULSE_bootstrap = {
299 PULSE_DRIVER_NAME, "PulseAudio",
300 Audio_Available, Audio_CreateDevice
301};
302
303/* This function waits until it is possible to write a full sound buffer */
304static void PULSE_WaitAudio(_THIS)
305{
306 int size;
307 while(1) {
308 if (SDL_NAME(pa_context_get_state)(context) != PA_CONTEXT_READY ||
309 SDL_NAME(pa_stream_get_state)(stream) != PA_STREAM_READY ||
310 SDL_NAME(pa_mainloop_iterate)(mainloop, 1, NULL) < 0) {
311 this->enabled = 0;
312 return;
313 }
314 size = SDL_NAME(pa_stream_writable_size)(stream);
315 if (size >= mixlen)
316 return;
317 }
318}
319
320static void PULSE_PlayAudio(_THIS)
321{
322 /* Write the audio data */
323 if (SDL_NAME(pa_stream_write)(stream, mixbuf, mixlen, NULL, 0LL, PA_SEEK_RELATIVE) < 0)
324 this->enabled = 0;
325}
326
327static Uint8 *PULSE_GetAudioBuf(_THIS)
328{
329 return(mixbuf);
330}
331
332static void PULSE_CloseAudio(_THIS)
333{
334 if ( mixbuf != NULL ) {
335 SDL_FreeAudioMem(mixbuf);
336 mixbuf = NULL;
337 }
338 if ( stream != NULL ) {
339 SDL_NAME(pa_stream_disconnect)(stream);
340 SDL_NAME(pa_stream_unref)(stream);
341 stream = NULL;
342 }
343 if (context != NULL) {
344 SDL_NAME(pa_context_disconnect)(context);
345 SDL_NAME(pa_context_unref)(context);
346 context = NULL;
347 }
348 if (mainloop != NULL) {
349 SDL_NAME(pa_mainloop_free)(mainloop);
350 mainloop = NULL;
351 }
352}
353
354/* Try to get the name of the program */
355static char *get_progname(void)
356{
357#ifdef __LINUX__
358 char *progname = NULL;
359 FILE *fp;
360 static char temp[BUFSIZ];
361
362 SDL_snprintf(temp, SDL_arraysize(temp), "/proc/%d/cmdline", getpid());
363 fp = fopen(temp, "r");
364 if ( fp != NULL ) {
365 if ( fgets(temp, sizeof(temp)-1, fp) ) {
366 progname = SDL_strrchr(temp, '/');
367 if ( progname == NULL ) {
368 progname = temp;
369 } else {
370 progname = progname+1;
371 }
372 }
373 fclose(fp);
374 }
375 return(progname);
376#elif defined(__NetBSD__)
377 return getprogname();
378#else
379 return("unknown");
380#endif
381}
382
383static void caption_set_complete(pa_context *c, int success, void *userdata)
384{
385 /* no-op. */
386}
387
388static void PULSE_SetCaption(_THIS, const char *str)
389{
390 SDL_free(this->hidden->caption);
391 if ((str == NULL) || (*str == '\0')) {
392 str = get_progname(); /* set a default so SOMETHING shows up. */
393 }
394 this->hidden->caption = SDL_strdup(str);
395 if (context != NULL) {
396 SDL_NAME(pa_context_set_name)(context, this->hidden->caption,
397 caption_set_complete, 0);
398 }
399}
400
401static void stream_drain_complete(pa_stream *s, int success, void *userdata)
402{
403 /* no-op. */
404}
405
406static void PULSE_WaitDone(_THIS)
407{
408 pa_operation *o;
409
410 o = SDL_NAME(pa_stream_drain)(stream, stream_drain_complete, NULL);
411 if (!o)
412 return;
413
414 while (SDL_NAME(pa_operation_get_state)(o) != PA_OPERATION_DONE) {
415 if (SDL_NAME(pa_context_get_state)(context) != PA_CONTEXT_READY ||
416 SDL_NAME(pa_stream_get_state)(stream) != PA_STREAM_READY ||
417 SDL_NAME(pa_mainloop_iterate)(mainloop, 1, NULL) < 0) {
418 SDL_NAME(pa_operation_cancel)(o);
419 break;
420 }
421 }
422 SDL_NAME(pa_operation_unref)(o);
423}
424
425static int PULSE_OpenAudio(_THIS, SDL_AudioSpec *spec)
426{
427 int state;
428 Uint16 test_format;
429 pa_sample_spec paspec;
430 pa_buffer_attr paattr;
431 pa_channel_map pacmap;
432 pa_stream_flags_t flags = 0;
433
434 paspec.format = PA_SAMPLE_INVALID;
435 for ( test_format = SDL_FirstAudioFormat(spec->format); test_format; ) {
436 switch ( test_format ) {
437 case AUDIO_U8:
438 paspec.format = PA_SAMPLE_U8;
439 break;
440 case AUDIO_S16LSB:
441 paspec.format = PA_SAMPLE_S16LE;
442 break;
443 case AUDIO_S16MSB:
444 paspec.format = PA_SAMPLE_S16BE;
445 break;
446 }
447 if ( paspec.format != PA_SAMPLE_INVALID )
448 break;
449 test_format = SDL_NextAudioFormat();
450 }
451 if (paspec.format == PA_SAMPLE_INVALID ) {
452 SDL_SetError("Couldn't find any suitable audio formats");
453 return(-1);
454 }
455 spec->format = test_format;
456
457 paspec.channels = spec->channels;
458 paspec.rate = spec->freq;
459
460 /* Calculate the final parameters for this audio specification */
461#ifdef PA_STREAM_ADJUST_LATENCY
462 spec->samples /= 2; /* Mix in smaller chunck to avoid underruns */
463#endif
464 SDL_CalculateAudioSpec(spec);
465
466 /* Allocate mixing buffer */
467 mixlen = spec->size;
468 mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen);
469 if ( mixbuf == NULL ) {
470 return(-1);
471 }
472 SDL_memset(mixbuf, spec->silence, spec->size);
473
474 /* Reduced prebuffering compared to the defaults. */
475#ifdef PA_STREAM_ADJUST_LATENCY
476 paattr.tlength = mixlen * 4; /* 2x original requested bufsize */
477 paattr.prebuf = -1;
478 paattr.maxlength = -1;
479 paattr.minreq = mixlen; /* -1 can lead to pa_stream_writable_size()
480 >= mixlen never becoming true */
481 flags = PA_STREAM_ADJUST_LATENCY;
482#else
483 paattr.tlength = mixlen*2;
484 paattr.prebuf = mixlen*2;
485 paattr.maxlength = mixlen*2;
486 paattr.minreq = mixlen;
487#endif
488
489 /* The SDL ALSA output hints us that we use Windows' channel mapping */
490 /* http://bugzilla.libsdl.org/show_bug.cgi?id=110 */
491 SDL_NAME(pa_channel_map_init_auto)(
492 &pacmap, spec->channels, PA_CHANNEL_MAP_WAVEEX);
493
494 /* Set up a new main loop */
495 if (!(mainloop = SDL_NAME(pa_mainloop_new)())) {
496 PULSE_CloseAudio(this);
497 SDL_SetError("pa_mainloop_new() failed");
498 return(-1);
499 }
500
501 if (this->hidden->caption == NULL) {
502 char *title = NULL;
503 SDL_WM_GetCaption(&title, NULL);
504 PULSE_SetCaption(this, title);
505 }
506
507 mainloop_api = SDL_NAME(pa_mainloop_get_api)(mainloop);
508 if (!(context = SDL_NAME(pa_context_new)(mainloop_api,
509 this->hidden->caption))) {
510 PULSE_CloseAudio(this);
511 SDL_SetError("pa_context_new() failed");
512 return(-1);
513 }
514
515 /* Connect to the PulseAudio server */
516 if (SDL_NAME(pa_context_connect)(context, NULL, 0, NULL) < 0) {
517 PULSE_CloseAudio(this);
518 SDL_SetError("Could not setup connection to PulseAudio");
519 return(-1);
520 }
521
522 do {
523 if (SDL_NAME(pa_mainloop_iterate)(mainloop, 1, NULL) < 0) {
524 PULSE_CloseAudio(this);
525 SDL_SetError("pa_mainloop_iterate() failed");
526 return(-1);
527 }
528 state = SDL_NAME(pa_context_get_state)(context);
529 if (!PA_CONTEXT_IS_GOOD(state)) {
530 PULSE_CloseAudio(this);
531 SDL_SetError("Could not connect to PulseAudio");
532 return(-1);
533 }
534 } while (state != PA_CONTEXT_READY);
535
536 stream = SDL_NAME(pa_stream_new)(
537 context,
538 "Simple DirectMedia Layer", /* stream description */
539 &paspec, /* sample format spec */
540 &pacmap /* channel map */
541 );
542 if ( stream == NULL ) {
543 PULSE_CloseAudio(this);
544 SDL_SetError("Could not setup PulseAudio stream");
545 return(-1);
546 }
547
548 if (SDL_NAME(pa_stream_connect_playback)(stream, NULL, &paattr, flags,
549 NULL, NULL) < 0) {
550 PULSE_CloseAudio(this);
551 SDL_SetError("Could not connect PulseAudio stream");
552 return(-1);
553 }
554
555 do {
556 if (SDL_NAME(pa_mainloop_iterate)(mainloop, 1, NULL) < 0) {
557 PULSE_CloseAudio(this);
558 SDL_SetError("pa_mainloop_iterate() failed");
559 return(-1);
560 }
561 state = SDL_NAME(pa_stream_get_state)(stream);
562 if (!PA_STREAM_IS_GOOD(state)) {
563 PULSE_CloseAudio(this);
564 SDL_SetError("Could not create to PulseAudio stream");
565 return(-1);
566 }
567 } while (state != PA_STREAM_READY);
568
569 return(0);
570}
diff --git a/apps/plugins/sdl/src/audio/pulse/SDL_pulseaudio.h b/apps/plugins/sdl/src/audio/pulse/SDL_pulseaudio.h
deleted file mode 100644
index 63ee751ef6..0000000000
--- a/apps/plugins/sdl/src/audio/pulse/SDL_pulseaudio.h
+++ /dev/null
@@ -1,73 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Stéphan Kochen
20 stephan@kochen.nl
21
22 Based on parts of the ALSA and ESounD output drivers.
23*/
24#include "SDL_config.h"
25
26#ifndef _SDL_pulseaudio_h
27#define _SDL_pulseaudio_h
28
29#include "../SDL_sysaudio.h"
30
31/* Hidden "this" pointer for the video functions */
32#define _THIS SDL_AudioDevice *this
33
34struct SDL_PrivateAudioData {
35 pa_mainloop *mainloop;
36 pa_mainloop_api *mainloop_api;
37 pa_context *context;
38 pa_stream *stream;
39
40 char *caption;
41
42 /* Raw mixing buffer */
43 Uint8 *mixbuf;
44 int mixlen;
45};
46
47#if (PA_API_VERSION < 12)
48/** Return non-zero if the passed state is one of the connected states */
49static inline int PA_CONTEXT_IS_GOOD(pa_context_state_t x) {
50 return
51 x == PA_CONTEXT_CONNECTING ||
52 x == PA_CONTEXT_AUTHORIZING ||
53 x == PA_CONTEXT_SETTING_NAME ||
54 x == PA_CONTEXT_READY;
55}
56/** Return non-zero if the passed state is one of the connected states */
57static inline int PA_STREAM_IS_GOOD(pa_stream_state_t x) {
58 return
59 x == PA_STREAM_CREATING ||
60 x == PA_STREAM_READY;
61}
62#endif /* pulseaudio <= 0.9.10 */
63
64/* Old variable names */
65#define mainloop (this->hidden->mainloop)
66#define mainloop_api (this->hidden->mainloop_api)
67#define context (this->hidden->context)
68#define stream (this->hidden->stream)
69#define mixbuf (this->hidden->mixbuf)
70#define mixlen (this->hidden->mixlen)
71
72#endif /* _SDL_pulseaudio_h */
73
diff --git a/apps/plugins/sdl/src/audio/sun/SDL_sunaudio.c b/apps/plugins/sdl/src/audio/sun/SDL_sunaudio.c
deleted file mode 100644
index 7a39e71d1b..0000000000
--- a/apps/plugins/sdl/src/audio/sun/SDL_sunaudio.c
+++ /dev/null
@@ -1,432 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer */
25
26#include <fcntl.h>
27#include <errno.h>
28#ifdef __NETBSD__
29#include <sys/ioctl.h>
30#include <sys/audioio.h>
31#endif
32#ifdef __SVR4
33#include <sys/audioio.h>
34#else
35#include <sys/time.h>
36#include <sys/types.h>
37#endif
38#include <unistd.h>
39
40#include "SDL_timer.h"
41#include "SDL_audio.h"
42#include "../SDL_audiomem.h"
43#include "../SDL_audio_c.h"
44#include "../SDL_audiodev_c.h"
45#include "SDL_sunaudio.h"
46
47/* Open the audio device for playback, and don't block if busy */
48#define OPEN_FLAGS (O_WRONLY|O_NONBLOCK)
49
50/* Audio driver functions */
51static int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec);
52static void DSP_WaitAudio(_THIS);
53static void DSP_PlayAudio(_THIS);
54static Uint8 *DSP_GetAudioBuf(_THIS);
55static void DSP_CloseAudio(_THIS);
56
57static Uint8 snd2au(int sample);
58
59/* Audio driver bootstrap functions */
60
61static int Audio_Available(void)
62{
63 int fd;
64 int available;
65
66 available = 0;
67 fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 1);
68 if ( fd >= 0 ) {
69 available = 1;
70 close(fd);
71 }
72 return(available);
73}
74
75static void Audio_DeleteDevice(SDL_AudioDevice *device)
76{
77 SDL_free(device->hidden);
78 SDL_free(device);
79}
80
81static SDL_AudioDevice *Audio_CreateDevice(int devindex)
82{
83 SDL_AudioDevice *this;
84
85 /* Initialize all variables that we clean on shutdown */
86 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
87 if ( this ) {
88 SDL_memset(this, 0, (sizeof *this));
89 this->hidden = (struct SDL_PrivateAudioData *)
90 SDL_malloc((sizeof *this->hidden));
91 }
92 if ( (this == NULL) || (this->hidden == NULL) ) {
93 SDL_OutOfMemory();
94 if ( this ) {
95 SDL_free(this);
96 }
97 return(0);
98 }
99 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
100 audio_fd = -1;
101
102 /* Set the function pointers */
103 this->OpenAudio = DSP_OpenAudio;
104 this->WaitAudio = DSP_WaitAudio;
105 this->PlayAudio = DSP_PlayAudio;
106 this->GetAudioBuf = DSP_GetAudioBuf;
107 this->CloseAudio = DSP_CloseAudio;
108
109 this->free = Audio_DeleteDevice;
110
111 return this;
112}
113
114AudioBootStrap SUNAUDIO_bootstrap = {
115 "audio", "UNIX /dev/audio interface",
116 Audio_Available, Audio_CreateDevice
117};
118
119#ifdef DEBUG_AUDIO
120void CheckUnderflow(_THIS)
121{
122#ifdef AUDIO_GETINFO
123 audio_info_t info;
124 int left;
125
126 ioctl(audio_fd, AUDIO_GETINFO, &info);
127 left = (written - info.play.samples);
128 if ( written && (left == 0) ) {
129 fprintf(stderr, "audio underflow!\n");
130 }
131#endif
132}
133#endif
134
135void DSP_WaitAudio(_THIS)
136{
137#ifdef AUDIO_GETINFO
138#define SLEEP_FUDGE 10 /* 10 ms scheduling fudge factor */
139 audio_info_t info;
140 Sint32 left;
141
142 ioctl(audio_fd, AUDIO_GETINFO, &info);
143 left = (written - info.play.samples);
144 if ( left > fragsize ) {
145 Sint32 sleepy;
146
147 sleepy = ((left - fragsize)/frequency);
148 sleepy -= SLEEP_FUDGE;
149 if ( sleepy > 0 ) {
150 SDL_Delay(sleepy);
151 }
152 }
153#else
154 fd_set fdset;
155
156 FD_ZERO(&fdset);
157 FD_SET(audio_fd, &fdset);
158 select(audio_fd+1, NULL, &fdset, NULL, NULL);
159#endif
160}
161
162void DSP_PlayAudio(_THIS)
163{
164 /* Write the audio data */
165 if ( ulaw_only ) {
166 /* Assuming that this->spec.freq >= 8000 Hz */
167 int accum, incr, pos;
168 Uint8 *aubuf;
169
170 accum = 0;
171 incr = this->spec.freq/8;
172 aubuf = ulaw_buf;
173 switch (audio_fmt & 0xFF) {
174 case 8: {
175 Uint8 *sndbuf;
176
177 sndbuf = mixbuf;
178 for ( pos=0; pos < fragsize; ++pos ) {
179 *aubuf = snd2au((0x80-*sndbuf)*64);
180 accum += incr;
181 while ( accum > 0 ) {
182 accum -= 1000;
183 sndbuf += 1;
184 }
185 aubuf += 1;
186 }
187 }
188 break;
189 case 16: {
190 Sint16 *sndbuf;
191
192 sndbuf = (Sint16 *)mixbuf;
193 for ( pos=0; pos < fragsize; ++pos ) {
194 *aubuf = snd2au(*sndbuf/4);
195 accum += incr;
196 while ( accum > 0 ) {
197 accum -= 1000;
198 sndbuf += 1;
199 }
200 aubuf += 1;
201 }
202 }
203 break;
204 }
205#ifdef DEBUG_AUDIO
206 CheckUnderflow(this);
207#endif
208 if ( write(audio_fd, ulaw_buf, fragsize) < 0 ) {
209 /* Assume fatal error, for now */
210 this->enabled = 0;
211 }
212 written += fragsize;
213 } else {
214#ifdef DEBUG_AUDIO
215 CheckUnderflow(this);
216#endif
217 if ( write(audio_fd, mixbuf, this->spec.size) < 0 ) {
218 /* Assume fatal error, for now */
219 this->enabled = 0;
220 }
221 written += fragsize;
222 }
223}
224
225Uint8 *DSP_GetAudioBuf(_THIS)
226{
227 return(mixbuf);
228}
229
230void DSP_CloseAudio(_THIS)
231{
232 if ( mixbuf != NULL ) {
233 SDL_FreeAudioMem(mixbuf);
234 mixbuf = NULL;
235 }
236 if ( ulaw_buf != NULL ) {
237 SDL_free(ulaw_buf);
238 ulaw_buf = NULL;
239 }
240 close(audio_fd);
241}
242
243int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec)
244{
245 char audiodev[1024];
246#ifdef AUDIO_SETINFO
247 int enc;
248#endif
249 int desired_freq = spec->freq;
250
251 /* Initialize our freeable variables, in case we fail*/
252 audio_fd = -1;
253 mixbuf = NULL;
254 ulaw_buf = NULL;
255
256 /* Determine the audio parameters from the AudioSpec */
257 switch ( spec->format & 0xFF ) {
258
259 case 8: { /* Unsigned 8 bit audio data */
260 spec->format = AUDIO_U8;
261#ifdef AUDIO_SETINFO
262 enc = AUDIO_ENCODING_LINEAR8;
263#endif
264 }
265 break;
266
267 case 16: { /* Signed 16 bit audio data */
268 spec->format = AUDIO_S16SYS;
269#ifdef AUDIO_SETINFO
270 enc = AUDIO_ENCODING_LINEAR;
271#endif
272 }
273 break;
274
275 default: {
276 SDL_SetError("Unsupported audio format");
277 return(-1);
278 }
279 }
280 audio_fmt = spec->format;
281
282 /* Open the audio device */
283 audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 1);
284 if ( audio_fd < 0 ) {
285 SDL_SetError("Couldn't open %s: %s", audiodev,
286 strerror(errno));
287 return(-1);
288 }
289
290 ulaw_only = 0; /* modern Suns do support linear audio */
291#ifdef AUDIO_SETINFO
292 for(;;) {
293 audio_info_t info;
294 AUDIO_INITINFO(&info); /* init all fields to "no change" */
295
296 /* Try to set the requested settings */
297 info.play.sample_rate = spec->freq;
298 info.play.channels = spec->channels;
299 info.play.precision = (enc == AUDIO_ENCODING_ULAW)
300 ? 8 : spec->format & 0xff;
301 info.play.encoding = enc;
302 if( ioctl(audio_fd, AUDIO_SETINFO, &info) == 0 ) {
303
304 /* Check to be sure we got what we wanted */
305 if(ioctl(audio_fd, AUDIO_GETINFO, &info) < 0) {
306 SDL_SetError("Error getting audio parameters: %s",
307 strerror(errno));
308 return -1;
309 }
310 if(info.play.encoding == enc
311 && info.play.precision == (spec->format & 0xff)
312 && info.play.channels == spec->channels) {
313 /* Yow! All seems to be well! */
314 spec->freq = info.play.sample_rate;
315 break;
316 }
317 }
318
319 switch(enc) {
320 case AUDIO_ENCODING_LINEAR8:
321 /* unsigned 8bit apparently not supported here */
322 enc = AUDIO_ENCODING_LINEAR;
323 spec->format = AUDIO_S16SYS;
324 break; /* try again */
325
326 case AUDIO_ENCODING_LINEAR:
327 /* linear 16bit didn't work either, resort to µ-law */
328 enc = AUDIO_ENCODING_ULAW;
329 spec->channels = 1;
330 spec->freq = 8000;
331 spec->format = AUDIO_U8;
332 ulaw_only = 1;
333 break;
334
335 default:
336 /* oh well... */
337 SDL_SetError("Error setting audio parameters: %s",
338 strerror(errno));
339 return -1;
340 }
341 }
342#endif /* AUDIO_SETINFO */
343 written = 0;
344
345 /* We can actually convert on-the-fly to U-Law */
346 if ( ulaw_only ) {
347 spec->freq = desired_freq;
348 fragsize = (spec->samples*1000)/(spec->freq/8);
349 frequency = 8;
350 ulaw_buf = (Uint8 *)SDL_malloc(fragsize);
351 if ( ulaw_buf == NULL ) {
352 SDL_OutOfMemory();
353 return(-1);
354 }
355 spec->channels = 1;
356 } else {
357 fragsize = spec->samples;
358 frequency = spec->freq/1000;
359 }
360#ifdef DEBUG_AUDIO
361 fprintf(stderr, "Audio device %s U-Law only\n",
362 ulaw_only ? "is" : "is not");
363 fprintf(stderr, "format=0x%x chan=%d freq=%d\n",
364 spec->format, spec->channels, spec->freq);
365#endif
366
367 /* Update the fragment size as size in bytes */
368 SDL_CalculateAudioSpec(spec);
369
370 /* Allocate mixing buffer */
371 mixbuf = (Uint8 *)SDL_AllocAudioMem(spec->size);
372 if ( mixbuf == NULL ) {
373 SDL_OutOfMemory();
374 return(-1);
375 }
376 SDL_memset(mixbuf, spec->silence, spec->size);
377
378 /* We're ready to rock and roll. :-) */
379 return(0);
380}
381
382/************************************************************************/
383/* This function (snd2au()) copyrighted: */
384/************************************************************************/
385/* Copyright 1989 by Rich Gopstein and Harris Corporation */
386/* */
387/* Permission to use, copy, modify, and distribute this software */
388/* and its documentation for any purpose and without fee is */
389/* hereby granted, provided that the above copyright notice */
390/* appears in all copies and that both that copyright notice and */
391/* this permission notice appear in supporting documentation, and */
392/* that the name of Rich Gopstein and Harris Corporation not be */
393/* used in advertising or publicity pertaining to distribution */
394/* of the software without specific, written prior permission. */
395/* Rich Gopstein and Harris Corporation make no representations */
396/* about the suitability of this software for any purpose. It */
397/* provided "as is" without express or implied warranty. */
398/************************************************************************/
399
400static Uint8 snd2au(int sample)
401{
402
403 int mask;
404
405 if (sample < 0) {
406 sample = -sample;
407 mask = 0x7f;
408 } else {
409 mask = 0xff;
410 }
411
412 if (sample < 32) {
413 sample = 0xF0 | (15 - sample / 2);
414 } else if (sample < 96) {
415 sample = 0xE0 | (15 - (sample - 32) / 4);
416 } else if (sample < 224) {
417 sample = 0xD0 | (15 - (sample - 96) / 8);
418 } else if (sample < 480) {
419 sample = 0xC0 | (15 - (sample - 224) / 16);
420 } else if (sample < 992) {
421 sample = 0xB0 | (15 - (sample - 480) / 32);
422 } else if (sample < 2016) {
423 sample = 0xA0 | (15 - (sample - 992) / 64);
424 } else if (sample < 4064) {
425 sample = 0x90 | (15 - (sample - 2016) / 128);
426 } else if (sample < 8160) {
427 sample = 0x80 | (15 - (sample - 4064) / 256);
428 } else {
429 sample = 0x80;
430 }
431 return (mask & sample);
432}
diff --git a/apps/plugins/sdl/src/audio/sun/SDL_sunaudio.h b/apps/plugins/sdl/src/audio/sun/SDL_sunaudio.h
deleted file mode 100644
index e6be419376..0000000000
--- a/apps/plugins/sdl/src/audio/sun/SDL_sunaudio.h
+++ /dev/null
@@ -1,55 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowaudio_h
25#define _SDL_lowaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the video functions */
30#define _THIS SDL_AudioDevice *this
31
32struct SDL_PrivateAudioData {
33 /* The file descriptor for the audio device */
34 int audio_fd;
35
36 Uint16 audio_fmt; /* The app audio format */
37 Uint8 *mixbuf; /* The app mixing buffer */
38 int ulaw_only; /* Flag -- does hardware only output U-law? */
39 Uint8 *ulaw_buf; /* The U-law mixing buffer */
40 Sint32 written; /* The number of samples written */
41 int fragsize; /* The audio fragment size in samples */
42 int frequency; /* The audio frequency in KHz */
43};
44
45/* Old variable names */
46#define audio_fd (this->hidden->audio_fd)
47#define audio_fmt (this->hidden->audio_fmt)
48#define mixbuf (this->hidden->mixbuf)
49#define ulaw_only (this->hidden->ulaw_only)
50#define ulaw_buf (this->hidden->ulaw_buf)
51#define written (this->hidden->written)
52#define fragsize (this->hidden->fragsize)
53#define frequency (this->hidden->frequency)
54
55#endif /* _SDL_lowaudio_h */
diff --git a/apps/plugins/sdl/src/audio/symbian/SDL_epocaudio.cpp b/apps/plugins/sdl/src/audio/symbian/SDL_epocaudio.cpp
deleted file mode 100644
index 72a4eaf4e1..0000000000
--- a/apps/plugins/sdl/src/audio/symbian/SDL_epocaudio.cpp
+++ /dev/null
@@ -1,614 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_epocaudio.cpp
25 Epoc based SDL audio driver implementation
26
27 Markus Mertama
28*/
29
30#ifdef SAVE_RCSID
31static char rcsid =
32 "@(#) $Id: SDL_epocaudio.c,v 0.0.0.0 2001/06/19 17:19:56 hercules Exp $";
33#endif
34
35
36#include <stdlib.h>
37#include <stdio.h>
38#include <string.h>
39#include <errno.h>
40#include <unistd.h>
41#include <fcntl.h>
42#include <signal.h>
43#include <sys/time.h>
44#include <sys/ioctl.h>
45#include <sys/stat.h>
46
47#include "epoc_sdl.h"
48
49#include <e32hal.h>
50
51
52extern "C" {
53#include "SDL_audio.h"
54#include "SDL_error.h"
55#include "SDL_audiomem.h"
56#include "SDL_audio_c.h"
57#include "SDL_timer.h"
58#include "SDL_audiodev_c.h"
59}
60
61#include "SDL_epocaudio.h"
62
63#include "streamplayer.h"
64
65
66//#define DEBUG_AUDIO
67
68
69/* Audio driver functions */
70
71static int EPOC_OpenAudio(SDL_AudioDevice *thisdevice, SDL_AudioSpec *spec);
72static void EPOC_WaitAudio(SDL_AudioDevice *thisdevice);
73static void EPOC_PlayAudio(SDL_AudioDevice *thisdevice);
74static Uint8 *EPOC_GetAudioBuf(SDL_AudioDevice *thisdevice);
75static void EPOC_CloseAudio(SDL_AudioDevice *thisdevice);
76static void EPOC_ThreadInit(SDL_AudioDevice *thisdevice);
77
78static int Audio_Available(void);
79static SDL_AudioDevice *Audio_CreateDevice(int devindex);
80static void Audio_DeleteDevice(SDL_AudioDevice *device);
81
82
83//void sos_adump(SDL_AudioDevice* thisdevice, void* data, int len);
84
85#ifdef __WINS__
86#define DODUMP
87#endif
88
89#ifdef DODUMP
90NONSHARABLE_CLASS(TDump)
91 {
92 public:
93 TInt Open();
94 void Close();
95 void Dump(const TDesC8& aDes);
96 private:
97 RFile iFile;
98 RFs iFs;
99 };
100
101TInt TDump::Open()
102 {
103 TInt err = iFs.Connect();
104 if(err == KErrNone)
105 {
106#ifdef __WINS__
107_LIT(target, "C:\\sdlau.raw");
108#else
109_LIT(target, "E:\\sdlau.raw");
110#endif
111 err = iFile.Replace(iFs, target, EFileWrite);
112 }
113 return err;
114 }
115void TDump::Close()
116 {
117 iFile.Close();
118 iFs.Close();
119 }
120void TDump::Dump(const TDesC8& aDes)
121 {
122 iFile.Write(aDes);
123 }
124#endif
125
126
127NONSHARABLE_CLASS(CSimpleWait) : public CTimer
128 {
129 public:
130 void Wait(TTimeIntervalMicroSeconds32 aWait);
131 static CSimpleWait* NewL();
132 private:
133 CSimpleWait();
134 void RunL();
135 };
136
137
138CSimpleWait* CSimpleWait::NewL()
139 {
140 CSimpleWait* wait = new (ELeave) CSimpleWait();
141 CleanupStack::PushL(wait);
142 wait->ConstructL();
143 CleanupStack::Pop();
144 return wait;
145 }
146
147void CSimpleWait::Wait(TTimeIntervalMicroSeconds32 aWait)
148 {
149 After(aWait);
150 CActiveScheduler::Start();
151 }
152
153CSimpleWait::CSimpleWait() : CTimer(CActive::EPriorityStandard)
154 {
155 CActiveScheduler::Add(this);
156 }
157
158void CSimpleWait::RunL()
159 {
160 CActiveScheduler::Stop();
161 }
162
163const TInt KAudioBuffers(2);
164
165
166NONSHARABLE_CLASS(CEpocAudio) : public CBase, public MStreamObs, public MStreamProvider
167 {
168 public:
169 static void* NewL(TInt BufferSize, TInt aFill);
170 inline static CEpocAudio& Current(SDL_AudioDevice* thisdevice);
171
172 static void Free(SDL_AudioDevice* thisdevice);
173
174 void Wait();
175 void Play();
176 // void SetBuffer(const TDesC8& aBuffer);
177 void ThreadInitL(TAny* aDevice);
178 void Open(TInt iRate, TInt iChannels, TUint32 aType, TInt aBytes);
179 ~CEpocAudio();
180 TUint8* Buffer();
181 TBool SetPause(TBool aPause);
182 #ifdef DODUMP
183 void Dump(const TDesC8& aBuf) {iDump.Dump(aBuf);}
184 #endif
185 private:
186 CEpocAudio(TInt aBufferSize);
187 void Complete(TInt aState, TInt aError);
188 TPtrC8 Data();
189 void ConstructL(TInt aFill);
190 private:
191 TInt iBufferSize;
192 CStreamPlayer* iPlayer;
193 TInt iBufferRate;
194 TInt iRate;
195 TInt iChannels;
196 TUint32 iType;
197 TInt iPosition;
198 TThreadId iTid;
199 TUint8* iAudioPtr;
200 TUint8* iBuffer;
201 // TTimeIntervalMicroSeconds iStart;
202 TTime iStart;
203 TInt iTune;
204 CSimpleWait* iWait;
205 #ifdef DODUMP
206 TDump iDump;
207 #endif
208 };
209
210inline CEpocAudio& CEpocAudio::Current(SDL_AudioDevice* thisdevice)
211 {
212 return *static_cast<CEpocAudio*>((void*)thisdevice->hidden);
213 }
214
215/*
216
217TBool EndSc(TAny*)
218 {
219 CActiveScheduler::Stop();
220 }
221
222LOCAL_C void CleanScL()
223 {
224 CIdle* d = CIdle::NewLC(CActive:::EPriorityIdle);
225 d->Start(TCallBack(EndSc));
226 CActiveScheduler::Start();
227
228 }
229*/
230
231void CEpocAudio::Free(SDL_AudioDevice* thisdevice)
232 {
233 CEpocAudio* ea = static_cast<CEpocAudio*>((void*)thisdevice->hidden);
234 if(ea)
235 {
236 ASSERT(ea->iTid == RThread().Id());
237 delete ea;
238 thisdevice->hidden = NULL;
239
240 CActiveScheduler* as = CActiveScheduler::Current();
241 ASSERT(as->StackDepth() == 0);
242 delete as;
243 CActiveScheduler::Install(NULL);
244 }
245 ASSERT(thisdevice->hidden == NULL);
246 }
247
248CEpocAudio::CEpocAudio(TInt aBufferSize) : iBufferSize(aBufferSize), iPosition(-1)
249 {
250 }
251
252void* CEpocAudio::NewL(TInt aBufferSize, TInt aFill)
253 {
254 CEpocAudio* eAudioLib = new (ELeave) CEpocAudio(aBufferSize);
255 CleanupStack::PushL(eAudioLib);
256 eAudioLib->ConstructL(aFill);
257 CleanupStack::Pop();
258 return eAudioLib;
259 }
260
261void CEpocAudio::ConstructL(TInt aFill)
262 {
263 iBuffer = (TUint8*) User::AllocL(KAudioBuffers * iBufferSize);
264 memset(iBuffer, aFill, KAudioBuffers * iBufferSize);
265 iAudioPtr = iBuffer;
266 }
267
268
269TBool CEpocAudio::SetPause(TBool aPause)
270 {
271 if(aPause && iPosition >= 0)
272 {
273 iPosition = -1;
274 if(iPlayer != NULL)
275 iPlayer->Stop();
276 }
277 if(!aPause && iPosition < 0)
278 {
279 iPosition = 0;
280 if(iPlayer != NULL)
281 iPlayer->Start();
282 }
283 return iPosition < 0;
284 }
285
286void CEpocAudio::ThreadInitL(TAny* aDevice)
287 {
288 iTid = RThread().Id();
289 CActiveScheduler* as = new (ELeave) CActiveScheduler();
290 CActiveScheduler::Install(as);
291
292 EpocSdlEnv::AppendCleanupItem(TSdlCleanupItem((TSdlCleanupOperation)EPOC_CloseAudio, aDevice));
293
294 iWait = CSimpleWait::NewL();
295
296 iPlayer = new (ELeave) CStreamPlayer(*this, *this);
297 iPlayer->ConstructL();
298 iPlayer->OpenStream(iRate, iChannels, iType);
299
300 #ifdef DODUMP
301 User::LeaveIfError(iDump.Open());
302 #endif
303 }
304
305
306
307TUint8* CEpocAudio::Buffer()
308 {
309 iStart.UniversalTime();
310// iStart = iPlayer->Position();
311 return iAudioPtr;
312
313 }
314
315CEpocAudio::~CEpocAudio()
316 {
317 if(iWait != NULL)
318 iWait->Cancel();
319 delete iWait;
320 if(iPlayer != NULL)
321 iPlayer->Close();
322 delete iPlayer;
323 delete iBuffer;
324 }
325
326void CEpocAudio::Complete(TInt aState, TInt aError)
327 {
328 if(aState == MStreamObs::EClose)
329 {
330 }
331 if(iPlayer->Closed())
332 return;
333 switch(aError)
334 {
335 case KErrUnderflow:
336 case KErrInUse:
337 iPlayer->Start();
338 break;
339 case KErrAbort:
340 iPlayer->Open();
341 }
342 }
343
344
345void sos_adump(SDL_AudioDevice* thisdevice, void* data, int len)
346 {
347#ifdef DODUMP
348 const TPtrC8 buf((TUint8*)data, len);
349 CEpocAudio::Current(thisdevice).Dump(buf);
350#endif
351 }
352
353const TInt KClip(256);
354
355TPtrC8 CEpocAudio::Data()
356 {
357 if(iPosition < 0)
358 return KNullDesC8();
359
360 TPtrC8 data(iAudioPtr + iPosition, KClip);
361
362#ifdef DODUMP
363 iDump.Dump(data);
364#endif
365
366 iPosition += KClip;
367 if(iPosition >= iBufferSize)
368 {
369
370/* if(iAudioPtr == iBuffer)
371 iAudioPtr = iBuffer + iBufferSize;
372 else
373 iAudioPtr = iBuffer;
374*/
375 iAudioPtr += iBufferSize;
376
377 if((iAudioPtr - iBuffer) >= KAudioBuffers * iBufferSize)
378 iAudioPtr = iBuffer;
379
380 iPosition = -1;
381 if(iWait->IsActive())
382 {
383 iWait->Cancel();
384 CActiveScheduler::Stop();
385 }
386 }
387 return data;
388 }
389
390
391
392
393void CEpocAudio::Play()
394 {
395 iPosition = 0;
396 }
397
398void CEpocAudio::Wait()
399 {
400 if(iPosition >= 0 /*&& iPlayer->Playing()*/)
401 {
402 const TInt64 bufMs = TInt64(iBufferSize - KClip) * TInt64(1000000);
403 const TInt64 specTime = bufMs / TInt64(iRate * iChannels * 2);
404 iWait->After(specTime);
405
406 CActiveScheduler::Start();
407 TTime end;
408 end.UniversalTime();
409 const TTimeIntervalMicroSeconds delta = end.MicroSecondsFrom(iStart);
410
411
412// const TTimeIntervalMicroSeconds end = iPlayer->Position();
413
414
415
416
417 const TInt diff = specTime - delta.Int64();
418
419 if(diff > 0 && diff < 200000)
420 {
421 User::After(diff);
422 }
423
424 }
425 else
426 {
427 User::After(10000);
428// iWait->Wait(10000); //just give some time...
429 }
430 }
431
432void CEpocAudio::Open(TInt aRate, TInt aChannels, TUint32 aType, TInt aBytes)
433 {
434 iRate = aRate;
435 iChannels = aChannels;
436 iType = aType;
437 iBufferRate = iRate * iChannels * aBytes; //1/x
438 }
439
440
441/* Audio driver bootstrap functions */
442
443AudioBootStrap EPOCAudio_bootstrap = {
444 "epoc\0\0\0",
445 "EPOC streaming audio\0\0\0",
446 Audio_Available,
447 Audio_CreateDevice
448};
449
450
451static SDL_AudioDevice *Audio_CreateDevice(int /*devindex*/)
452{
453 SDL_AudioDevice *thisdevice;
454
455 /* Initialize all variables that we clean on shutdown */
456 thisdevice = (SDL_AudioDevice *)malloc(sizeof(SDL_AudioDevice));
457 if ( thisdevice ) {
458 memset(thisdevice, 0, (sizeof *thisdevice));
459 thisdevice->hidden = NULL; /*(struct SDL_PrivateAudioData *)
460 malloc((sizeof thisdevice->hidden)); */
461 }
462 if ( (thisdevice == NULL) /*|| (thisdevice->hidden == NULL) */) {
463 SDL_OutOfMemory();
464 if ( thisdevice ) {
465 free(thisdevice);
466 }
467 return(0);
468 }
469// memset(thisdevice->hidden, 0, (sizeof *thisdevice->hidden));
470
471 /* Set the function pointers */
472 thisdevice->OpenAudio = EPOC_OpenAudio;
473 thisdevice->WaitAudio = EPOC_WaitAudio;
474 thisdevice->PlayAudio = EPOC_PlayAudio;
475 thisdevice->GetAudioBuf = EPOC_GetAudioBuf;
476 thisdevice->CloseAudio = EPOC_CloseAudio;
477 thisdevice->ThreadInit = EPOC_ThreadInit;
478 thisdevice->free = Audio_DeleteDevice;
479
480 return thisdevice;
481}
482
483
484static void Audio_DeleteDevice(SDL_AudioDevice *device)
485 {
486 //free(device->hidden);
487 free(device);
488 }
489
490static int Audio_Available(void)
491{
492 return(1); // Audio stream modules should be always there!
493}
494
495
496static int EPOC_OpenAudio(SDL_AudioDevice *thisdevice, SDL_AudioSpec *spec)
497{
498 SDL_TRACE("SDL:EPOC_OpenAudio");
499
500
501 TUint32 type = KMMFFourCCCodePCM16;
502 TInt bytes = 2;
503
504 switch(spec->format)
505 {
506 case AUDIO_U16LSB:
507 type = KMMFFourCCCodePCMU16;
508 break;
509 case AUDIO_S16LSB:
510 type = KMMFFourCCCodePCM16;
511 break;
512 case AUDIO_U16MSB:
513 type = KMMFFourCCCodePCMU16B;
514 break;
515 case AUDIO_S16MSB:
516 type = KMMFFourCCCodePCM16B;
517 break;
518 //8 bit not supported!
519 case AUDIO_U8:
520 case AUDIO_S8:
521 default:
522 spec->format = AUDIO_S16LSB;
523 };
524
525
526
527 if(spec->channels > 2)
528 spec->channels = 2;
529
530 spec->freq = CStreamPlayer::ClosestSupportedRate(spec->freq);
531
532
533 /* Allocate mixing buffer */
534 const TInt buflen = spec->size;// * bytes * spec->channels;
535// audiobuf = NULL;
536
537 TRAPD(err, thisdevice->hidden = static_cast<SDL_PrivateAudioData*>(CEpocAudio::NewL(buflen, spec->silence)));
538 if(err != KErrNone)
539 return -1;
540
541 CEpocAudio::Current(thisdevice).Open(spec->freq, spec->channels, type, bytes);
542
543 CEpocAudio::Current(thisdevice).SetPause(ETrue);
544
545 // isSDLAudioPaused = 1;
546
547 thisdevice->enabled = 0; /* enable only after audio engine has been initialized!*/
548
549 /* We're ready to rock and roll. :-) */
550 return(0);
551}
552
553
554static void EPOC_CloseAudio(SDL_AudioDevice* thisdevice)
555 {
556#ifdef DEBUG_AUDIO
557 SDL_TRACE("Close audio\n");
558#endif
559
560 CEpocAudio::Free(thisdevice);
561 }
562
563
564static void EPOC_ThreadInit(SDL_AudioDevice *thisdevice)
565 {
566 SDL_TRACE("SDL:EPOC_ThreadInit");
567 CEpocAudio::Current(thisdevice).ThreadInitL(thisdevice);
568 RThread().SetPriority(EPriorityMore);
569 thisdevice->enabled = 1;
570 }
571
572/* This function waits until it is possible to write a full sound buffer */
573static void EPOC_WaitAudio(SDL_AudioDevice* thisdevice)
574{
575#ifdef DEBUG_AUDIO
576 SDL_TRACE1("wait %d audio\n", CEpocAudio::AudioLib().StreamPlayer(KSfxChannel).SyncTime());
577 TInt tics = User::TickCount();
578#endif
579
580 CEpocAudio::Current(thisdevice).Wait();
581
582#ifdef DEBUG_AUDIO
583 TInt ntics = User::TickCount() - tics;
584 SDL_TRACE1("audio waited %d\n", ntics);
585 SDL_TRACE1("audio at %d\n", tics);
586#endif
587}
588
589
590
591static void EPOC_PlayAudio(SDL_AudioDevice* thisdevice)
592 {
593 if(CEpocAudio::Current(thisdevice).SetPause(SDL_GetAudioStatus() == SDL_AUDIO_PAUSED))
594 SDL_Delay(500); //hold on the busy loop
595 else
596 CEpocAudio::Current(thisdevice).Play();
597
598#ifdef DEBUG_AUDIO
599 SDL_TRACE("buffer has audio data\n");
600#endif
601
602
603#ifdef DEBUG_AUDIO
604 SDL_TRACE1("Wrote %d bytes of audio data\n", buflen);
605#endif
606}
607
608static Uint8 *EPOC_GetAudioBuf(SDL_AudioDevice* thisdevice)
609 {
610 return CEpocAudio::Current(thisdevice).Buffer();
611 }
612
613
614
diff --git a/apps/plugins/sdl/src/audio/symbian/SDL_epocaudio.h b/apps/plugins/sdl/src/audio/symbian/SDL_epocaudio.h
deleted file mode 100644
index 5c95c86158..0000000000
--- a/apps/plugins/sdl/src/audio/symbian/SDL_epocaudio.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23
24#ifdef SAVE_RCSID
25static char rcsid =
26 "@(#) $Id: SDL_epocaudio.h,v 1.1.2.2 2001/02/10 07:20:03 hercules Exp $";
27#endif
28
29#ifndef _SDL_EPOCAUDIO_H
30#define _SDL_EPOCAUDIO_H
31
32extern "C" {
33#include "SDL_sysaudio.h"
34}
35
36
37#endif /* _SDL_EPOCAUDIO_H */
diff --git a/apps/plugins/sdl/src/audio/symbian/streamplayer.cpp b/apps/plugins/sdl/src/audio/symbian/streamplayer.cpp
deleted file mode 100644
index dd733a1d17..0000000000
--- a/apps/plugins/sdl/src/audio/symbian/streamplayer.cpp
+++ /dev/null
@@ -1,279 +0,0 @@
1#include "streamplayer.h"
2#include<mda/common/audio.h>
3
4
5
6const TInt KMaxVolume(256);
7
8LOCAL_C TInt GetSampleRate(TInt aRate)
9 {
10 switch(aRate)
11 {
12 case 8000: return TMdaAudioDataSettings::ESampleRate8000Hz;
13 case 11025: return TMdaAudioDataSettings::ESampleRate11025Hz;
14 case 12000: return TMdaAudioDataSettings::ESampleRate12000Hz;
15 case 16000: return TMdaAudioDataSettings::ESampleRate16000Hz;
16 case 22050: return TMdaAudioDataSettings::ESampleRate22050Hz;
17 case 24000: return TMdaAudioDataSettings::ESampleRate24000Hz;
18 case 32000: return TMdaAudioDataSettings::ESampleRate32000Hz;
19 case 44100: return TMdaAudioDataSettings::ESampleRate44100Hz;
20 case 48000: return TMdaAudioDataSettings::ESampleRate48000Hz;
21 case 96000: return TMdaAudioDataSettings::ESampleRate96000Hz;
22 case 64000: return TMdaAudioDataSettings::ESampleRate64000Hz;
23 }
24 return KErrNotFound;
25 }
26
27LOCAL_C TInt GetChannels(TInt aChannels)
28 {
29 switch(aChannels)
30 {
31 case 1: return TMdaAudioDataSettings::EChannelsMono;
32 case 2: return TMdaAudioDataSettings::EChannelsStereo;
33 }
34 return KErrNotFound;
35 }
36
37TInt CStreamPlayer::ClosestSupportedRate(TInt aRate)
38 {
39 if(aRate > 96000)
40 return 96000;
41 TInt rate = aRate;
42 while(GetSampleRate(rate) == KErrNotFound)
43 {
44 ++rate;
45 }
46 return rate;
47 }
48
49CStreamPlayer::CStreamPlayer(MStreamProvider& aProvider, MStreamObs& aObs) :
50 iProvider(aProvider), iObs(aObs), iVolume(KMaxVolume)
51 {
52 }
53
54CStreamPlayer::~CStreamPlayer()
55 {
56 iState |= EDied;
57 if(iState & EInited)
58 Close();
59 User::After(100000); //wait buffer to be flushed
60 ASSERT(iPtr.Length() == 0);
61 delete iStream;
62 }
63
64
65void CStreamPlayer::ConstructL()
66 {
67 iStream = CMdaAudioOutputStream::NewL(*this, EMdaPriorityMax);
68 iSilence.SetMax();
69 iSilence.FillZ();
70 }
71
72
73TInt CStreamPlayer::OpenStream(TInt aRate, TInt aChannels, TUint32 aType)
74 {
75 Close();
76
77 iType = aType;
78
79 iRate = GetSampleRate(aRate);
80 if(iRate == KErrNotFound)
81 return KErrNotSupported;
82
83 iChannels = GetChannels(aChannels);
84 if(iChannels == KErrNotFound)
85 return KErrNotSupported;
86
87 Open();
88
89 return KErrNone;
90 }
91
92
93TInt CStreamPlayer::MaxVolume() const
94 {
95 return KMaxVolume;
96 }
97
98void CStreamPlayer::SetVolume(TInt aNew)
99 {
100
101 const TInt maxi = MaxVolume();
102 if(aNew > maxi)
103 return;
104 if(aNew < 0)
105 return;
106
107 iVolume = aNew;
108
109 iState |= EVolumeChange;
110 }
111
112 TInt CStreamPlayer::Volume() const
113 {
114 return iVolume;
115 }
116
117void CStreamPlayer::Open()
118 {
119 TMdaAudioDataSettings audioSettings;
120 audioSettings.Query();
121 audioSettings.iCaps = TMdaAudioDataSettings::ERealTime |
122 TMdaAudioDataSettings::ESampleRateFixed;
123 audioSettings.iSampleRate = iRate;
124 audioSettings.iChannels = iChannels;
125 audioSettings.iFlags = TMdaAudioDataSettings::ENoNetworkRouting;
126 audioSettings.iVolume = 0;
127
128 iState &= ~EStopped;
129 iStream->Open(&audioSettings);
130 }
131
132void CStreamPlayer::Stop()
133 {
134 if(iState & (EStarted | EInited))
135 {
136 Close();
137 iState |= EStopped;
138 }
139 }
140
141void CStreamPlayer::Start()
142 {
143 if(iPtr.Length() == 0)
144 {
145 iState |= EStarted;
146 if(iState & EInited)
147 {
148 Request();
149 }
150 else if(iState & EStopped)
151 {
152 Open();
153 }
154 }
155 }
156
157void CStreamPlayer::Close()
158 {
159 iState &= ~EInited;
160 iStream->Stop();
161 iState &= ~EStarted;
162 }
163
164void CStreamPlayer::Request()
165 {
166 if(iState & EInited)
167 {
168 iPtr.Set(KNullDesC8);
169
170 if(iState & EVolumeChange)
171 {
172 const TReal newVol = iVolume;
173 const TReal newMax = MaxVolume();
174 const TInt maxVol = iStream->MaxVolume();
175 const TReal max = static_cast<TReal>(maxVol);
176 const TReal newvolume = (newVol * max) / newMax;
177 const TInt vol = static_cast<TReal>(newvolume);
178 iStream->SetVolume(vol);
179 iState &= ~EVolumeChange;
180 }
181
182 if(iState & EStarted)
183 {
184 iPtr.Set(iProvider.Data());
185 }
186 if(iPtr.Length() == 0)
187 {
188 iPtr.Set(iSilence);
189 }
190 TRAPD(err, iStream->WriteL(iPtr));
191 if(err != KErrNone)
192 {
193 iObs.Complete(MStreamObs::EWrite, err);
194 }
195 /* else
196 {
197 iProvider.Written(iPtr.Length());
198 }*/
199 }
200 }
201
202
203void CStreamPlayer::SetCapsL()
204 {
205 iStream->SetDataTypeL(iType);
206 iStream->SetAudioPropertiesL(iRate, iChannels);
207 }
208
209void CStreamPlayer::MaoscOpenComplete(TInt aError)
210 {
211 if(aError == KErrNone)
212 {
213 TRAPD(err, SetCapsL());
214 if(err == KErrNone)
215 {
216 iStream->SetPriority(EPriorityNormal, EMdaPriorityPreferenceTime);
217 iState |= EInited;
218
219
220 SetVolume(Volume());
221
222 if(iState & EStarted)
223 {
224 Request();
225 }
226
227 }
228 aError = err;
229 }
230 if(!(iState & EDied))
231 iObs.Complete(MStreamObs::EInit, aError);
232 }
233
234void CStreamPlayer::MaoscBufferCopied(TInt aError, const TDesC8& /*aBuffer*/)
235 {
236 iPtr.Set(KNullDesC8);
237 if(aError == KErrNone)
238 {
239 if(iState & EInited)
240 Request();
241 else
242 iStream->Stop();
243 }
244 else if(!(iState & EDied))
245 iObs.Complete(MStreamObs::EPlay, aError);
246 }
247
248void CStreamPlayer::MaoscPlayComplete(TInt aError)
249 {
250 iPtr.Set(KNullDesC8);
251 iState &= ~EStarted;
252 if(!(iState & EDied))
253 iObs.Complete(MStreamObs::EClose, aError);
254 }
255
256TBool CStreamPlayer::Playing() const
257 {
258 return (iState & EInited) && (iState & EStarted);
259 }
260
261TBool CStreamPlayer::Closed() const
262 {
263 return !(iState & EInited) && !(iState & EDied);
264 }
265
266 /*
267void CStreamPlayer::Request()
268 {
269 SetActive();
270 TRequestStatus* s = &iStatus;
271 User::RequestComplete(s, KErrNone);
272 }
273 // iTimer.After(0);
274 */
275
276
277
278
279
diff --git a/apps/plugins/sdl/src/audio/symbian/streamplayer.h b/apps/plugins/sdl/src/audio/symbian/streamplayer.h
deleted file mode 100644
index 8c6e74f920..0000000000
--- a/apps/plugins/sdl/src/audio/symbian/streamplayer.h
+++ /dev/null
@@ -1,89 +0,0 @@
1#ifndef STREAMPLAYER_H
2#define STREAMPLAYER_H
3
4#include<MdaAudioOutputStream.h>
5
6const TInt KSilenceBuffer = 256;
7
8class MStreamObs
9 {
10 public:
11 enum
12 {
13 EInit,
14 EPlay,
15 EWrite,
16 EClose,
17 };
18 virtual void Complete(TInt aState, TInt aError) = 0;
19 };
20
21class MStreamProvider
22 {
23 public:
24 virtual TPtrC8 Data() = 0;
25 };
26
27NONSHARABLE_CLASS(CStreamPlayer) : public CBase, public MMdaAudioOutputStreamCallback
28 {
29 public:
30 CStreamPlayer(MStreamProvider& aProvider, MStreamObs& aObs);
31 ~CStreamPlayer();
32 void ConstructL();
33
34 static TInt ClosestSupportedRate(TInt aRate);
35
36 TInt OpenStream(TInt aRate, TInt aChannels, TUint32 aType = KMMFFourCCCodePCM16);
37
38 void SetVolume(TInt aNew);
39 TInt Volume() const;
40 TInt MaxVolume() const;
41
42 void Stop();
43 void Start();
44 void Open();
45 void Close();
46
47 TBool Playing() const;
48 TBool Closed() const;
49
50 private:
51
52 void MaoscOpenComplete(TInt aError) ;
53 void MaoscBufferCopied(TInt aError, const TDesC8& aBuffer);
54 void MaoscPlayComplete(TInt aError);
55
56 private:
57 void Request();
58 void SetCapsL();
59
60 private:
61 MStreamProvider& iProvider;
62 MStreamObs& iObs;
63 TInt iVolume;
64
65 CMdaAudioOutputStream* iStream;
66
67 TInt iRate;
68 TInt iChannels;
69 TUint32 iType;
70
71 enum
72 {
73 ENone = 0,
74 EInited = 0x1,
75 EStarted = 0x2,
76 EStopped = 0x4,
77 EVolumeChange = 0x8,
78 EDied = 0x10
79 };
80
81 TInt iState;
82 TBuf8<KSilenceBuffer> iSilence;
83 TPtrC8 iPtr;
84
85 };
86
87
88#endif
89
diff --git a/apps/plugins/sdl/src/audio/ums/SDL_umsaudio.c b/apps/plugins/sdl/src/audio/ums/SDL_umsaudio.c
deleted file mode 100644
index 9488911db6..0000000000
--- a/apps/plugins/sdl/src/audio/ums/SDL_umsaudio.c
+++ /dev/null
@@ -1,547 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Carsten Griwodz
20 griff@kom.tu-darmstadt.de
21
22 based on linux/SDL_dspaudio.c by Sam Lantinga
23*/
24#include "SDL_config.h"
25
26/* Allow access to a raw mixing buffer */
27
28#include <errno.h>
29#include <unistd.h>
30#include <fcntl.h>
31#include <sys/types.h>
32#include <sys/time.h>
33#include <sys/ioctl.h>
34#include <sys/stat.h>
35#include <sys/mman.h>
36
37#include "SDL_audio.h"
38#include "../SDL_audio_c.h"
39#include "../SDL_audiodev_c.h"
40#include "SDL_umsaudio.h"
41
42/* The tag name used by UMS audio */
43#define UMS_DRIVER_NAME "ums"
44
45#define DEBUG_AUDIO 1
46
47/* Audio driver functions */
48static int UMS_OpenAudio(_THIS, SDL_AudioSpec *spec);
49static void UMS_PlayAudio(_THIS);
50static Uint8 *UMS_GetAudioBuf(_THIS);
51static void UMS_CloseAudio(_THIS);
52
53static UMSAudioDevice_ReturnCode UADOpen(_THIS, string device, string mode, long flags);
54static UMSAudioDevice_ReturnCode UADClose(_THIS);
55static UMSAudioDevice_ReturnCode UADGetBitsPerSample(_THIS, long* bits);
56static UMSAudioDevice_ReturnCode UADSetBitsPerSample(_THIS, long bits);
57static UMSAudioDevice_ReturnCode UADSetSampleRate(_THIS, long rate, long* set_rate);
58static UMSAudioDevice_ReturnCode UADSetByteOrder(_THIS, string byte_order);
59static UMSAudioDevice_ReturnCode UADSetAudioFormatType(_THIS, string fmt);
60static UMSAudioDevice_ReturnCode UADSetNumberFormat(_THIS, string fmt);
61static UMSAudioDevice_ReturnCode UADInitialize(_THIS);
62static UMSAudioDevice_ReturnCode UADStart(_THIS);
63static UMSAudioDevice_ReturnCode UADStop(_THIS);
64static UMSAudioDevice_ReturnCode UADSetTimeFormat(_THIS, UMSAudioTypes_TimeFormat fmt );
65static UMSAudioDevice_ReturnCode UADWriteBuffSize(_THIS, long* buff_size );
66static UMSAudioDevice_ReturnCode UADWriteBuffRemain(_THIS, long* buff_size );
67static UMSAudioDevice_ReturnCode UADWriteBuffUsed(_THIS, long* buff_size );
68static UMSAudioDevice_ReturnCode UADSetDMABufferSize(_THIS, long bytes, long* bytes_ret );
69static UMSAudioDevice_ReturnCode UADSetVolume(_THIS, long volume );
70static UMSAudioDevice_ReturnCode UADSetBalance(_THIS, long balance );
71static UMSAudioDevice_ReturnCode UADSetChannels(_THIS, long channels );
72static UMSAudioDevice_ReturnCode UADPlayRemainingData(_THIS, boolean block );
73static UMSAudioDevice_ReturnCode UADEnableOutput(_THIS, string output, long* left_gain, long* right_gain);
74static UMSAudioDevice_ReturnCode UADWrite(_THIS, UMSAudioTypes_Buffer* buff, long samples, long* samples_written);
75
76/* Audio driver bootstrap functions */
77static int Audio_Available(void)
78{
79 return 1;
80}
81
82static void Audio_DeleteDevice(_THIS)
83{
84 if(this->hidden->playbuf._buffer) SDL_free(this->hidden->playbuf._buffer);
85 if(this->hidden->fillbuf._buffer) SDL_free(this->hidden->fillbuf._buffer);
86 _somFree( this->hidden->umsdev );
87 SDL_free(this->hidden);
88 SDL_free(this);
89}
90
91static SDL_AudioDevice *Audio_CreateDevice(int devindex)
92{
93 SDL_AudioDevice *this;
94
95 /*
96 * Allocate and initialize management storage and private management
97 * storage for this SDL-using library.
98 */
99 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
100 if ( this ) {
101 SDL_memset(this, 0, (sizeof *this));
102 this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc((sizeof *this->hidden));
103 }
104 if ( (this == NULL) || (this->hidden == NULL) ) {
105 SDL_OutOfMemory();
106 if ( this ) {
107 SDL_free(this);
108 }
109 return(0);
110 }
111 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
112#ifdef DEBUG_AUDIO
113 fprintf(stderr, "Creating UMS Audio device\n");
114#endif
115
116 /*
117 * Calls for UMS env initialization and audio object construction.
118 */
119 this->hidden->ev = somGetGlobalEnvironment();
120 this->hidden->umsdev = UMSAudioDeviceNew();
121
122 /*
123 * Set the function pointers.
124 */
125 this->OpenAudio = UMS_OpenAudio;
126 this->WaitAudio = NULL; /* we do blocking output */
127 this->PlayAudio = UMS_PlayAudio;
128 this->GetAudioBuf = UMS_GetAudioBuf;
129 this->CloseAudio = UMS_CloseAudio;
130 this->free = Audio_DeleteDevice;
131
132#ifdef DEBUG_AUDIO
133 fprintf(stderr, "done\n");
134#endif
135 return this;
136}
137
138AudioBootStrap UMS_bootstrap = {
139 UMS_DRIVER_NAME, "AIX UMS audio",
140 Audio_Available, Audio_CreateDevice
141};
142
143static Uint8 *UMS_GetAudioBuf(_THIS)
144{
145#ifdef DEBUG_AUDIO
146 fprintf(stderr, "enter UMS_GetAudioBuf\n");
147#endif
148 return this->hidden->fillbuf._buffer;
149/*
150 long bufSize;
151 UMSAudioDevice_ReturnCode rc;
152
153 rc = UADSetTimeFormat(this, UMSAudioTypes_Bytes );
154 rc = UADWriteBuffSize(this, bufSize );
155*/
156}
157
158static void UMS_CloseAudio(_THIS)
159{
160 UMSAudioDevice_ReturnCode rc;
161
162#ifdef DEBUG_AUDIO
163 fprintf(stderr, "enter UMS_CloseAudio\n");
164#endif
165 rc = UADPlayRemainingData(this, TRUE);
166 rc = UADStop(this);
167 rc = UADClose(this);
168}
169
170static void UMS_PlayAudio(_THIS)
171{
172 UMSAudioDevice_ReturnCode rc;
173 long samplesToWrite;
174 long samplesWritten;
175 UMSAudioTypes_Buffer swpbuf;
176
177#ifdef DEBUG_AUDIO
178 fprintf(stderr, "enter UMS_PlayAudio\n");
179#endif
180 samplesToWrite = this->hidden->playbuf._length/this->hidden->bytesPerSample;
181 do
182 {
183 rc = UADWrite(this, &this->hidden->playbuf,
184 samplesToWrite,
185 &samplesWritten );
186 samplesToWrite -= samplesWritten;
187
188 /* rc values: UMSAudioDevice_Success
189 * UMSAudioDevice_Failure
190 * UMSAudioDevice_Preempted
191 * UMSAudioDevice_Interrupted
192 * UMSAudioDevice_DeviceError
193 */
194 if ( rc == UMSAudioDevice_DeviceError ) {
195#ifdef DEBUG_AUDIO
196 fprintf(stderr, "Returning from PlayAudio with devices error\n");
197#endif
198 return;
199 }
200 }
201 while(samplesToWrite>0);
202
203 SDL_LockAudio();
204 SDL_memcpy( &swpbuf, &this->hidden->playbuf, sizeof(UMSAudioTypes_Buffer) );
205 SDL_memcpy( &this->hidden->playbuf, &this->hidden->fillbuf, sizeof(UMSAudioTypes_Buffer) );
206 SDL_memcpy( &this->hidden->fillbuf, &swpbuf, sizeof(UMSAudioTypes_Buffer) );
207 SDL_UnlockAudio();
208
209#ifdef DEBUG_AUDIO
210 fprintf(stderr, "Wrote audio data and swapped buffer\n");
211#endif
212}
213
214#if 0
215// /* Set the DSP frequency */
216// value = spec->freq;
217// if ( ioctl(this->hidden->audio_fd, SOUND_PCM_WRITE_RATE, &value) < 0 ) {
218// SDL_SetError("Couldn't set audio frequency");
219// return(-1);
220// }
221// spec->freq = value;
222#endif
223
224static int UMS_OpenAudio(_THIS, SDL_AudioSpec *spec)
225{
226 char* audiodev = "/dev/paud0";
227 long lgain;
228 long rgain;
229 long outRate;
230 long outBufSize;
231 long bitsPerSample;
232 long samplesPerSec;
233 long success;
234 Uint16 test_format;
235 int frag_spec;
236 UMSAudioDevice_ReturnCode rc;
237
238#ifdef DEBUG_AUDIO
239 fprintf(stderr, "enter UMS_OpenAudio\n");
240#endif
241 rc = UADOpen(this, audiodev,"PLAY", UMSAudioDevice_BlockingIO);
242 if ( rc != UMSAudioDevice_Success ) {
243 SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
244 return -1;
245 }
246
247 rc = UADSetAudioFormatType(this, "PCM");
248
249 success = 0;
250 test_format = SDL_FirstAudioFormat(spec->format);
251 do
252 {
253#ifdef DEBUG_AUDIO
254 fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
255#endif
256 switch ( test_format )
257 {
258 case AUDIO_U8:
259/* from the mac code: better ? */
260/* sample_bits = spec->size / spec->samples / spec->channels * 8; */
261 success = 1;
262 bitsPerSample = 8;
263 rc = UADSetSampleRate(this, spec->freq << 16, &outRate );
264 rc = UADSetByteOrder(this, "MSB"); /* irrelevant */
265 rc = UADSetNumberFormat(this, "UNSIGNED");
266 break;
267 case AUDIO_S8:
268 success = 1;
269 bitsPerSample = 8;
270 rc = UADSetSampleRate(this, spec->freq << 16, &outRate );
271 rc = UADSetByteOrder(this, "MSB"); /* irrelevant */
272 rc = UADSetNumberFormat(this, "SIGNED");
273 break;
274 case AUDIO_S16LSB:
275 success = 1;
276 bitsPerSample = 16;
277 rc = UADSetSampleRate(this, spec->freq << 16, &outRate );
278 rc = UADSetByteOrder(this, "LSB");
279 rc = UADSetNumberFormat(this, "SIGNED");
280 break;
281 case AUDIO_S16MSB:
282 success = 1;
283 bitsPerSample = 16;
284 rc = UADSetSampleRate(this, spec->freq << 16, &outRate );
285 rc = UADSetByteOrder(this, "MSB");
286 rc = UADSetNumberFormat(this, "SIGNED");
287 break;
288 case AUDIO_U16LSB:
289 success = 1;
290 bitsPerSample = 16;
291 rc = UADSetSampleRate(this, spec->freq << 16, &outRate );
292 rc = UADSetByteOrder(this, "LSB");
293 rc = UADSetNumberFormat(this, "UNSIGNED");
294 break;
295 case AUDIO_U16MSB:
296 success = 1;
297 bitsPerSample = 16;
298 rc = UADSetSampleRate(this, spec->freq << 16, &outRate );
299 rc = UADSetByteOrder(this, "MSB");
300 rc = UADSetNumberFormat(this, "UNSIGNED");
301 break;
302 default:
303 break;
304 }
305 if ( ! success ) {
306 test_format = SDL_NextAudioFormat();
307 }
308 }
309 while ( ! success && test_format );
310
311 if ( success == 0 ) {
312 SDL_SetError("Couldn't find any hardware audio formats");
313 return -1;
314 }
315
316 spec->format = test_format;
317
318 for ( frag_spec = 0; (0x01<<frag_spec) < spec->size; ++frag_spec );
319 if ( (0x01<<frag_spec) != spec->size ) {
320 SDL_SetError("Fragment size must be a power of two");
321 return -1;
322 }
323 if ( frag_spec > 2048 ) frag_spec = 2048;
324
325 this->hidden->bytesPerSample = (bitsPerSample / 8) * spec->channels;
326 samplesPerSec = this->hidden->bytesPerSample * outRate;
327
328 this->hidden->playbuf._length = 0;
329 this->hidden->playbuf._maximum = spec->size;
330 this->hidden->playbuf._buffer = (unsigned char*)SDL_malloc(spec->size);
331 this->hidden->fillbuf._length = 0;
332 this->hidden->fillbuf._maximum = spec->size;
333 this->hidden->fillbuf._buffer = (unsigned char*)SDL_malloc(spec->size);
334
335 rc = UADSetBitsPerSample(this, bitsPerSample );
336 rc = UADSetDMABufferSize(this, frag_spec, &outBufSize );
337 rc = UADSetChannels(this, spec->channels); /* functions reduces to mono or stereo */
338
339 lgain = 100; /*maximum left input gain*/
340 rgain = 100; /*maimum right input gain*/
341 rc = UADEnableOutput(this, "LINE_OUT",&lgain,&rgain);
342 rc = UADInitialize(this);
343 rc = UADStart(this);
344 rc = UADSetVolume(this, 100);
345 rc = UADSetBalance(this, 0);
346
347 /* We're ready to rock and roll. :-) */
348 return 0;
349}
350
351
352static UMSAudioDevice_ReturnCode UADGetBitsPerSample(_THIS, long* bits)
353{
354 return UMSAudioDevice_get_bits_per_sample( this->hidden->umsdev,
355 this->hidden->ev,
356 bits );
357}
358
359static UMSAudioDevice_ReturnCode UADSetBitsPerSample(_THIS, long bits)
360{
361 return UMSAudioDevice_set_bits_per_sample( this->hidden->umsdev,
362 this->hidden->ev,
363 bits );
364}
365
366static UMSAudioDevice_ReturnCode UADSetSampleRate(_THIS, long rate, long* set_rate)
367{
368 /* from the mac code: sample rate = spec->freq << 16; */
369 return UMSAudioDevice_set_sample_rate( this->hidden->umsdev,
370 this->hidden->ev,
371 rate,
372 set_rate );
373}
374
375static UMSAudioDevice_ReturnCode UADSetByteOrder(_THIS, string byte_order)
376{
377 return UMSAudioDevice_set_byte_order( this->hidden->umsdev,
378 this->hidden->ev,
379 byte_order );
380}
381
382static UMSAudioDevice_ReturnCode UADSetAudioFormatType(_THIS, string fmt)
383{
384 /* possible PCM, A_LAW or MU_LAW */
385 return UMSAudioDevice_set_audio_format_type( this->hidden->umsdev,
386 this->hidden->ev,
387 fmt );
388}
389
390static UMSAudioDevice_ReturnCode UADSetNumberFormat(_THIS, string fmt)
391{
392 /* possible SIGNED, UNSIGNED, or TWOS_COMPLEMENT */
393 return UMSAudioDevice_set_number_format( this->hidden->umsdev,
394 this->hidden->ev,
395 fmt );
396}
397
398static UMSAudioDevice_ReturnCode UADInitialize(_THIS)
399{
400 return UMSAudioDevice_initialize( this->hidden->umsdev,
401 this->hidden->ev );
402}
403
404static UMSAudioDevice_ReturnCode UADStart(_THIS)
405{
406 return UMSAudioDevice_start( this->hidden->umsdev,
407 this->hidden->ev );
408}
409
410static UMSAudioDevice_ReturnCode UADSetTimeFormat(_THIS, UMSAudioTypes_TimeFormat fmt )
411{
412 /*
413 * Switches the time format to the new format, immediately.
414 * possible UMSAudioTypes_Msecs, UMSAudioTypes_Bytes or UMSAudioTypes_Samples
415 */
416 return UMSAudioDevice_set_time_format( this->hidden->umsdev,
417 this->hidden->ev,
418 fmt );
419}
420
421static UMSAudioDevice_ReturnCode UADWriteBuffSize(_THIS, long* buff_size )
422{
423 /*
424 * returns write buffer size in the current time format
425 */
426 return UMSAudioDevice_write_buff_size( this->hidden->umsdev,
427 this->hidden->ev,
428 buff_size );
429}
430
431static UMSAudioDevice_ReturnCode UADWriteBuffRemain(_THIS, long* buff_size )
432{
433 /*
434 * returns amount of available space in the write buffer
435 * in the current time format
436 */
437 return UMSAudioDevice_write_buff_remain( this->hidden->umsdev,
438 this->hidden->ev,
439 buff_size );
440}
441
442static UMSAudioDevice_ReturnCode UADWriteBuffUsed(_THIS, long* buff_size )
443{
444 /*
445 * returns amount of filled space in the write buffer
446 * in the current time format
447 */
448 return UMSAudioDevice_write_buff_used( this->hidden->umsdev,
449 this->hidden->ev,
450 buff_size );
451}
452
453static UMSAudioDevice_ReturnCode UADSetDMABufferSize(_THIS, long bytes, long* bytes_ret )
454{
455 /*
456 * Request a new DMA buffer size, maximum requested size 2048.
457 * Takes effect with next initialize() call.
458 * Devices may or may not support DMA.
459 */
460 return UMSAudioDevice_set_DMA_buffer_size( this->hidden->umsdev,
461 this->hidden->ev,
462 bytes,
463 bytes_ret );
464}
465
466static UMSAudioDevice_ReturnCode UADSetVolume(_THIS, long volume )
467{
468 /*
469 * Set the volume.
470 * Takes effect immediately.
471 */
472 return UMSAudioDevice_set_volume( this->hidden->umsdev,
473 this->hidden->ev,
474 volume );
475}
476
477static UMSAudioDevice_ReturnCode UADSetBalance(_THIS, long balance )
478{
479 /*
480 * Set the balance.
481 * Takes effect immediately.
482 */
483 return UMSAudioDevice_set_balance( this->hidden->umsdev,
484 this->hidden->ev,
485 balance );
486}
487
488static UMSAudioDevice_ReturnCode UADSetChannels(_THIS, long channels )
489{
490 /*
491 * Set mono or stereo.
492 * Takes effect with next initialize() call.
493 */
494 if ( channels != 1 ) channels = 2;
495 return UMSAudioDevice_set_number_of_channels( this->hidden->umsdev,
496 this->hidden->ev,
497 channels );
498}
499
500static UMSAudioDevice_ReturnCode UADOpen(_THIS, string device, string mode, long flags)
501{
502 return UMSAudioDevice_open( this->hidden->umsdev,
503 this->hidden->ev,
504 device,
505 mode,
506 flags );
507}
508
509static UMSAudioDevice_ReturnCode UADWrite(_THIS, UMSAudioTypes_Buffer* buff,
510 long samples,
511 long* samples_written)
512{
513 return UMSAudioDevice_write( this->hidden->umsdev,
514 this->hidden->ev,
515 buff,
516 samples,
517 samples_written );
518}
519
520static UMSAudioDevice_ReturnCode UADPlayRemainingData(_THIS, boolean block )
521{
522 return UMSAudioDevice_play_remaining_data( this->hidden->umsdev,
523 this->hidden->ev,
524 block);
525}
526
527static UMSAudioDevice_ReturnCode UADStop(_THIS)
528{
529 return UMSAudioDevice_stop( this->hidden->umsdev,
530 this->hidden->ev );
531}
532
533static UMSAudioDevice_ReturnCode UADClose(_THIS)
534{
535 return UMSAudioDevice_close( this->hidden->umsdev,
536 this->hidden->ev );
537}
538
539static UMSAudioDevice_ReturnCode UADEnableOutput(_THIS, string output, long* left_gain, long* right_gain)
540{
541 return UMSAudioDevice_enable_output( this->hidden->umsdev,
542 this->hidden->ev,
543 output,
544 left_gain,
545 right_gain );
546}
547
diff --git a/apps/plugins/sdl/src/audio/ums/SDL_umsaudio.h b/apps/plugins/sdl/src/audio/ums/SDL_umsaudio.h
deleted file mode 100644
index 367fe853b6..0000000000
--- a/apps/plugins/sdl/src/audio/ums/SDL_umsaudio.h
+++ /dev/null
@@ -1,50 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Carsten Griwodz
20 griff@kom.tu-darmstadt.de
21
22 based on linux/SDL_dspaudio.h by Sam Lantinga
23*/
24#include "SDL_config.h"
25
26#ifndef _SDL_UMSaudio_h
27#define _SDL_UMSaudio_h
28
29#include <UMS/UMSAudioDevice.h>
30
31#include "../SDL_sysaudio.h"
32
33/* Hidden "this" pointer for the video functions */
34#define _THIS SDL_AudioDevice *this
35
36struct SDL_PrivateAudioData
37{
38 /* Pointer to the (open) UMS audio device */
39 Environment* ev;
40 UMSAudioDevice umsdev;
41
42 /* Raw mixing buffer */
43 UMSAudioTypes_Buffer playbuf;
44 UMSAudioTypes_Buffer fillbuf;
45
46 long bytesPerSample;
47};
48
49#endif /* _SDL_UMSaudio_h */
50
diff --git a/apps/plugins/sdl/src/audio/windib/SDL_dibaudio.c b/apps/plugins/sdl/src/audio/windib/SDL_dibaudio.c
deleted file mode 100644
index 51a9a4d60a..0000000000
--- a/apps/plugins/sdl/src/audio/windib/SDL_dibaudio.c
+++ /dev/null
@@ -1,322 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer */
25
26#define WIN32_LEAN_AND_MEAN
27#include <windows.h>
28#include <mmsystem.h>
29
30#include "SDL_timer.h"
31#include "SDL_audio.h"
32#include "../SDL_audio_c.h"
33#include "SDL_dibaudio.h"
34#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
35#include "win_ce_semaphore.h"
36#endif
37
38
39/* Audio driver functions */
40static int DIB_OpenAudio(_THIS, SDL_AudioSpec *spec);
41static void DIB_ThreadInit(_THIS);
42static void DIB_WaitAudio(_THIS);
43static Uint8 *DIB_GetAudioBuf(_THIS);
44static void DIB_PlayAudio(_THIS);
45static void DIB_WaitDone(_THIS);
46static void DIB_CloseAudio(_THIS);
47
48/* Audio driver bootstrap functions */
49
50static int Audio_Available(void)
51{
52 return(1);
53}
54
55static void Audio_DeleteDevice(SDL_AudioDevice *device)
56{
57 SDL_free(device->hidden);
58 SDL_free(device);
59}
60
61static SDL_AudioDevice *Audio_CreateDevice(int devindex)
62{
63 SDL_AudioDevice *this;
64
65 /* Initialize all variables that we clean on shutdown */
66 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
67 if ( this ) {
68 SDL_memset(this, 0, (sizeof *this));
69 this->hidden = (struct SDL_PrivateAudioData *)
70 SDL_malloc((sizeof *this->hidden));
71 }
72 if ( (this == NULL) || (this->hidden == NULL) ) {
73 SDL_OutOfMemory();
74 if ( this ) {
75 SDL_free(this);
76 }
77 return(0);
78 }
79 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
80
81 /* Set the function pointers */
82 this->OpenAudio = DIB_OpenAudio;
83 this->ThreadInit = DIB_ThreadInit;
84 this->WaitAudio = DIB_WaitAudio;
85 this->PlayAudio = DIB_PlayAudio;
86 this->GetAudioBuf = DIB_GetAudioBuf;
87 this->WaitDone = DIB_WaitDone;
88 this->CloseAudio = DIB_CloseAudio;
89
90 this->free = Audio_DeleteDevice;
91
92 return this;
93}
94
95AudioBootStrap WAVEOUT_bootstrap = {
96 "waveout", "Win95/98/NT/2000 WaveOut",
97 Audio_Available, Audio_CreateDevice
98};
99
100
101/* The Win32 callback for filling the WAVE device */
102static void CALLBACK FillSound(HWAVEOUT hwo, UINT uMsg, DWORD_PTR dwInstance,
103 DWORD dwParam1, DWORD dwParam2)
104{
105 SDL_AudioDevice *this = (SDL_AudioDevice *)dwInstance;
106
107 /* Only service "buffer done playing" messages */
108 if ( uMsg != WOM_DONE )
109 return;
110
111 /* Signal that we are done playing a buffer */
112#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
113 ReleaseSemaphoreCE(audio_sem, 1, NULL);
114#else
115 ReleaseSemaphore(audio_sem, 1, NULL);
116#endif
117}
118
119static void SetMMerror(char *function, MMRESULT code)
120{
121 size_t len;
122 char errbuf[MAXERRORLENGTH];
123#ifdef _WIN32_WCE
124 wchar_t werrbuf[MAXERRORLENGTH];
125#endif
126
127 SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: ", function);
128 len = SDL_strlen(errbuf);
129
130#ifdef _WIN32_WCE
131 /* UNICODE version */
132 waveOutGetErrorText(code, werrbuf, MAXERRORLENGTH-len);
133 WideCharToMultiByte(CP_ACP,0,werrbuf,-1,errbuf+len,MAXERRORLENGTH-len,NULL,NULL);
134#else
135 waveOutGetErrorText(code, errbuf+len, (UINT)(MAXERRORLENGTH-len));
136#endif
137
138 SDL_SetError("%s",errbuf);
139}
140
141/* Set high priority for the audio thread */
142static void DIB_ThreadInit(_THIS)
143{
144 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
145}
146
147void DIB_WaitAudio(_THIS)
148{
149 /* Wait for an audio chunk to finish */
150#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
151 WaitForSemaphoreCE(audio_sem, INFINITE);
152#else
153 WaitForSingleObject(audio_sem, INFINITE);
154#endif
155}
156
157Uint8 *DIB_GetAudioBuf(_THIS)
158{
159 Uint8 *retval;
160
161 retval = (Uint8 *)(wavebuf[next_buffer].lpData);
162 return retval;
163}
164
165void DIB_PlayAudio(_THIS)
166{
167 /* Queue it up */
168 waveOutWrite(sound, &wavebuf[next_buffer], sizeof(wavebuf[0]));
169 next_buffer = (next_buffer+1)%NUM_BUFFERS;
170}
171
172void DIB_WaitDone(_THIS)
173{
174 int i, left;
175
176 do {
177 left = NUM_BUFFERS;
178 for ( i=0; i<NUM_BUFFERS; ++i ) {
179 if ( wavebuf[i].dwFlags & WHDR_DONE ) {
180 --left;
181 }
182 }
183 if ( left > 0 ) {
184 SDL_Delay(100);
185 }
186 } while ( left > 0 );
187}
188
189void DIB_CloseAudio(_THIS)
190{
191 int i;
192
193 /* Close up audio */
194 if ( audio_sem ) {
195#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
196 CloseSynchHandle(audio_sem);
197#else
198 CloseHandle(audio_sem);
199#endif
200 }
201 if ( sound ) {
202 waveOutClose(sound);
203 }
204
205 /* Clean up mixing buffers */
206 for ( i=0; i<NUM_BUFFERS; ++i ) {
207 if ( wavebuf[i].dwUser != 0xFFFF ) {
208 waveOutUnprepareHeader(sound, &wavebuf[i],
209 sizeof(wavebuf[i]));
210 wavebuf[i].dwUser = 0xFFFF;
211 }
212 }
213 /* Free raw mixing buffer */
214 if ( mixbuf != NULL ) {
215 SDL_free(mixbuf);
216 mixbuf = NULL;
217 }
218}
219
220int DIB_OpenAudio(_THIS, SDL_AudioSpec *spec)
221{
222 MMRESULT result;
223 int i;
224 WAVEFORMATEX waveformat;
225
226 /* Initialize the wavebuf structures for closing */
227 sound = NULL;
228 audio_sem = NULL;
229 for ( i = 0; i < NUM_BUFFERS; ++i )
230 wavebuf[i].dwUser = 0xFFFF;
231 mixbuf = NULL;
232
233 /* Set basic WAVE format parameters */
234 SDL_memset(&waveformat, 0, sizeof(waveformat));
235 waveformat.wFormatTag = WAVE_FORMAT_PCM;
236
237 /* Determine the audio parameters from the AudioSpec */
238 switch ( spec->format & 0xFF ) {
239 case 8:
240 /* Unsigned 8 bit audio data */
241 spec->format = AUDIO_U8;
242 waveformat.wBitsPerSample = 8;
243 break;
244 case 16:
245 /* Signed 16 bit audio data */
246 spec->format = AUDIO_S16;
247 waveformat.wBitsPerSample = 16;
248 break;
249 default:
250 SDL_SetError("Unsupported audio format");
251 return(-1);
252 }
253 waveformat.nChannels = spec->channels;
254 waveformat.nSamplesPerSec = spec->freq;
255 waveformat.nBlockAlign =
256 waveformat.nChannels * (waveformat.wBitsPerSample/8);
257 waveformat.nAvgBytesPerSec =
258 waveformat.nSamplesPerSec * waveformat.nBlockAlign;
259
260 /* Check the buffer size -- minimum of 1/4 second (word aligned) */
261 if ( spec->samples < (spec->freq/4) )
262 spec->samples = ((spec->freq/4)+3)&~3;
263
264 /* Update the fragment size as size in bytes */
265 SDL_CalculateAudioSpec(spec);
266
267 /* Open the audio device */
268 result = waveOutOpen(&sound, WAVE_MAPPER, &waveformat,
269 (DWORD_PTR)FillSound, (DWORD_PTR)this, CALLBACK_FUNCTION);
270 if ( result != MMSYSERR_NOERROR ) {
271 SetMMerror("waveOutOpen()", result);
272 return(-1);
273 }
274
275#ifdef SOUND_DEBUG
276 /* Check the sound device we retrieved */
277 {
278 WAVEOUTCAPS caps;
279
280 result = waveOutGetDevCaps((UINT)sound, &caps, sizeof(caps));
281 if ( result != MMSYSERR_NOERROR ) {
282 SetMMerror("waveOutGetDevCaps()", result);
283 return(-1);
284 }
285 printf("Audio device: %s\n", caps.szPname);
286 }
287#endif
288
289 /* Create the audio buffer semaphore */
290#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
291 audio_sem = CreateSemaphoreCE(NULL, NUM_BUFFERS-1, NUM_BUFFERS, NULL);
292#else
293 audio_sem = CreateSemaphore(NULL, NUM_BUFFERS-1, NUM_BUFFERS, NULL);
294#endif
295 if ( audio_sem == NULL ) {
296 SDL_SetError("Couldn't create semaphore");
297 return(-1);
298 }
299
300 /* Create the sound buffers */
301 mixbuf = (Uint8 *)SDL_malloc(NUM_BUFFERS*spec->size);
302 if ( mixbuf == NULL ) {
303 SDL_SetError("Out of memory");
304 return(-1);
305 }
306 for ( i = 0; i < NUM_BUFFERS; ++i ) {
307 SDL_memset(&wavebuf[i], 0, sizeof(wavebuf[i]));
308 wavebuf[i].lpData = (LPSTR) &mixbuf[i*spec->size];
309 wavebuf[i].dwBufferLength = spec->size;
310 wavebuf[i].dwFlags = WHDR_DONE;
311 result = waveOutPrepareHeader(sound, &wavebuf[i],
312 sizeof(wavebuf[i]));
313 if ( result != MMSYSERR_NOERROR ) {
314 SetMMerror("waveOutPrepareHeader()", result);
315 return(-1);
316 }
317 }
318
319 /* Ready to go! */
320 next_buffer = 0;
321 return(0);
322}
diff --git a/apps/plugins/sdl/src/audio/windib/SDL_dibaudio.h b/apps/plugins/sdl/src/audio/windib/SDL_dibaudio.h
deleted file mode 100644
index d2c62280b5..0000000000
--- a/apps/plugins/sdl/src/audio/windib/SDL_dibaudio.h
+++ /dev/null
@@ -1,49 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowaudio_h
25#define _SDL_lowaudio_h
26
27#include "../SDL_sysaudio.h"
28
29/* Hidden "this" pointer for the video functions */
30#define _THIS SDL_AudioDevice *this
31
32#define NUM_BUFFERS 2 /* -- Don't lower this! */
33
34struct SDL_PrivateAudioData {
35 HWAVEOUT sound;
36 HANDLE audio_sem;
37 Uint8 *mixbuf; /* The raw allocated mixing buffer */
38 WAVEHDR wavebuf[NUM_BUFFERS]; /* Wave audio fragments */
39 int next_buffer;
40};
41
42/* Old variable names */
43#define sound (this->hidden->sound)
44#define audio_sem (this->hidden->audio_sem)
45#define mixbuf (this->hidden->mixbuf)
46#define wavebuf (this->hidden->wavebuf)
47#define next_buffer (this->hidden->next_buffer)
48
49#endif /* _SDL_lowaudio_h */
diff --git a/apps/plugins/sdl/src/audio/windx5/SDL_dx5audio.c b/apps/plugins/sdl/src/audio/windx5/SDL_dx5audio.c
deleted file mode 100644
index c3d42aeda1..0000000000
--- a/apps/plugins/sdl/src/audio/windx5/SDL_dx5audio.c
+++ /dev/null
@@ -1,705 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Allow access to a raw mixing buffer */
25
26#include "SDL_timer.h"
27#include "SDL_audio.h"
28#include "../SDL_audio_c.h"
29#include "SDL_dx5audio.h"
30
31/* Define this if you want to use DirectX 6 DirectSoundNotify interface */
32//#define USE_POSITION_NOTIFY
33
34/* DirectX function pointers for audio */
35HRESULT (WINAPI *DSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
36
37/* Audio driver functions */
38static int DX5_OpenAudio(_THIS, SDL_AudioSpec *spec);
39static void DX5_ThreadInit(_THIS);
40static void DX5_WaitAudio_BusyWait(_THIS);
41#ifdef USE_POSITION_NOTIFY
42static void DX6_WaitAudio_EventWait(_THIS);
43#endif
44static void DX5_PlayAudio(_THIS);
45static Uint8 *DX5_GetAudioBuf(_THIS);
46static void DX5_WaitDone(_THIS);
47static void DX5_CloseAudio(_THIS);
48
49/* Audio driver bootstrap functions */
50
51static int Audio_Available(void)
52{
53 HINSTANCE DSoundDLL;
54 int dsound_ok;
55
56 /* Version check DSOUND.DLL (Is DirectX okay?) */
57 dsound_ok = 0;
58 DSoundDLL = LoadLibrary(TEXT("DSOUND.DLL"));
59 if ( DSoundDLL != NULL ) {
60 /* We just use basic DirectSound, we're okay */
61 /* Yay! */
62 /* Unfortunately, the sound drivers on NT have
63 higher latencies than the audio buffers used
64 by many SDL applications, so there are gaps
65 in the audio - it sounds terrible. Punt for now.
66 */
67 OSVERSIONINFO ver;
68 ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
69 GetVersionEx(&ver);
70 switch (ver.dwPlatformId) {
71 case VER_PLATFORM_WIN32_NT:
72 if ( ver.dwMajorVersion > 4 ) {
73 /* Win2K */
74 dsound_ok = 1;
75 } else {
76 /* WinNT */
77 dsound_ok = 0;
78 }
79 break;
80 default:
81 /* Win95 or Win98 */
82 dsound_ok = 1;
83 break;
84 }
85 /* Now check for DirectX 5 or better - otherwise
86 * we will fail later in DX5_OpenAudio without a chance
87 * to fall back to the DIB driver. */
88 if (dsound_ok) {
89 /* DirectSoundCaptureCreate was added in DX5 */
90 if (!GetProcAddress(DSoundDLL, TEXT("DirectSoundCaptureCreate")))
91 dsound_ok = 0;
92
93 }
94 /* Clean up.. */
95 FreeLibrary(DSoundDLL);
96 }
97 return(dsound_ok);
98}
99
100/* Functions for loading the DirectX functions dynamically */
101static HINSTANCE DSoundDLL = NULL;
102
103static void DX5_Unload(void)
104{
105 if ( DSoundDLL != NULL ) {
106 FreeLibrary(DSoundDLL);
107 DSoundCreate = NULL;
108 DSoundDLL = NULL;
109 }
110}
111static int DX5_Load(void)
112{
113 int status;
114
115 DX5_Unload();
116 DSoundDLL = LoadLibrary(TEXT("DSOUND.DLL"));
117 if ( DSoundDLL != NULL ) {
118 DSoundCreate = (void *)GetProcAddress(DSoundDLL,
119 TEXT("DirectSoundCreate"));
120 }
121 if ( DSoundDLL && DSoundCreate ) {
122 status = 0;
123 } else {
124 DX5_Unload();
125 status = -1;
126 }
127 return status;
128}
129
130static void Audio_DeleteDevice(SDL_AudioDevice *device)
131{
132 DX5_Unload();
133 SDL_free(device->hidden);
134 SDL_free(device);
135}
136
137static SDL_AudioDevice *Audio_CreateDevice(int devindex)
138{
139 SDL_AudioDevice *this;
140
141 /* Load DirectX */
142 if ( DX5_Load() < 0 ) {
143 return(NULL);
144 }
145
146 /* Initialize all variables that we clean on shutdown */
147 this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
148 if ( this ) {
149 SDL_memset(this, 0, (sizeof *this));
150 this->hidden = (struct SDL_PrivateAudioData *)
151 SDL_malloc((sizeof *this->hidden));
152 }
153 if ( (this == NULL) || (this->hidden == NULL) ) {
154 SDL_OutOfMemory();
155 if ( this ) {
156 SDL_free(this);
157 }
158 return(0);
159 }
160 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
161
162 /* Set the function pointers */
163 this->OpenAudio = DX5_OpenAudio;
164 this->ThreadInit = DX5_ThreadInit;
165 this->WaitAudio = DX5_WaitAudio_BusyWait;
166 this->PlayAudio = DX5_PlayAudio;
167 this->GetAudioBuf = DX5_GetAudioBuf;
168 this->WaitDone = DX5_WaitDone;
169 this->CloseAudio = DX5_CloseAudio;
170
171 this->free = Audio_DeleteDevice;
172
173 return this;
174}
175
176AudioBootStrap DSOUND_bootstrap = {
177 "dsound", "Win95/98/2000 DirectSound",
178 Audio_Available, Audio_CreateDevice
179};
180
181static void SetDSerror(const char *function, int code)
182{
183 static const char *error;
184 static char errbuf[1024];
185
186 errbuf[0] = 0;
187 switch (code) {
188 case E_NOINTERFACE:
189 error =
190 "Unsupported interface\n-- Is DirectX 5.0 or later installed?";
191 break;
192 case DSERR_ALLOCATED:
193 error = "Audio device in use";
194 break;
195 case DSERR_BADFORMAT:
196 error = "Unsupported audio format";
197 break;
198 case DSERR_BUFFERLOST:
199 error = "Mixing buffer was lost";
200 break;
201 case DSERR_CONTROLUNAVAIL:
202 error = "Control requested is not available";
203 break;
204 case DSERR_INVALIDCALL:
205 error = "Invalid call for the current state";
206 break;
207 case DSERR_INVALIDPARAM:
208 error = "Invalid parameter";
209 break;
210 case DSERR_NODRIVER:
211 error = "No audio device found";
212 break;
213 case DSERR_OUTOFMEMORY:
214 error = "Out of memory";
215 break;
216 case DSERR_PRIOLEVELNEEDED:
217 error = "Caller doesn't have priority";
218 break;
219 case DSERR_UNSUPPORTED:
220 error = "Function not supported";
221 break;
222 default:
223 SDL_snprintf(errbuf, SDL_arraysize(errbuf),
224 "%s: Unknown DirectSound error: 0x%x",
225 function, code);
226 break;
227 }
228 if ( ! errbuf[0] ) {
229 SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error);
230 }
231 SDL_SetError("%s", errbuf);
232 return;
233}
234
235/* DirectSound needs to be associated with a window */
236static HWND mainwin = NULL;
237/* */
238void DX5_SoundFocus(HWND hwnd)
239{
240 mainwin = hwnd;
241}
242
243static void DX5_ThreadInit(_THIS)
244{
245 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
246}
247
248static void DX5_WaitAudio_BusyWait(_THIS)
249{
250 DWORD status;
251 DWORD cursor, junk;
252 HRESULT result;
253
254 /* Semi-busy wait, since we have no way of getting play notification
255 on a primary mixing buffer located in hardware (DirectX 5.0)
256 */
257 result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, &junk, &cursor);
258 if ( result != DS_OK ) {
259 if ( result == DSERR_BUFFERLOST ) {
260 IDirectSoundBuffer_Restore(mixbuf);
261 }
262#ifdef DEBUG_SOUND
263 SetDSerror("DirectSound GetCurrentPosition", result);
264#endif
265 return;
266 }
267
268 while ( (cursor/mixlen) == lastchunk ) {
269 /* FIXME: find out how much time is left and sleep that long */
270 SDL_Delay(1);
271
272 /* Try to restore a lost sound buffer */
273 IDirectSoundBuffer_GetStatus(mixbuf, &status);
274 if ( (status&DSBSTATUS_BUFFERLOST) ) {
275 IDirectSoundBuffer_Restore(mixbuf);
276 IDirectSoundBuffer_GetStatus(mixbuf, &status);
277 if ( (status&DSBSTATUS_BUFFERLOST) ) {
278 break;
279 }
280 }
281 if ( ! (status&DSBSTATUS_PLAYING) ) {
282 result = IDirectSoundBuffer_Play(mixbuf, 0, 0, DSBPLAY_LOOPING);
283 if ( result == DS_OK ) {
284 continue;
285 }
286#ifdef DEBUG_SOUND
287 SetDSerror("DirectSound Play", result);
288#endif
289 return;
290 }
291
292 /* Find out where we are playing */
293 result = IDirectSoundBuffer_GetCurrentPosition(mixbuf,
294 &junk, &cursor);
295 if ( result != DS_OK ) {
296 SetDSerror("DirectSound GetCurrentPosition", result);
297 return;
298 }
299 }
300}
301
302#ifdef USE_POSITION_NOTIFY
303static void DX6_WaitAudio_EventWait(_THIS)
304{
305 DWORD status;
306 HRESULT result;
307
308 /* Try to restore a lost sound buffer */
309 IDirectSoundBuffer_GetStatus(mixbuf, &status);
310 if ( (status&DSBSTATUS_BUFFERLOST) ) {
311 IDirectSoundBuffer_Restore(mixbuf);
312 IDirectSoundBuffer_GetStatus(mixbuf, &status);
313 if ( (status&DSBSTATUS_BUFFERLOST) ) {
314 return;
315 }
316 }
317 if ( ! (status&DSBSTATUS_PLAYING) ) {
318 result = IDirectSoundBuffer_Play(mixbuf, 0, 0, DSBPLAY_LOOPING);
319 if ( result != DS_OK ) {
320#ifdef DEBUG_SOUND
321 SetDSerror("DirectSound Play", result);
322#endif
323 return;
324 }
325 }
326 WaitForSingleObject(audio_event, INFINITE);
327}
328#endif /* USE_POSITION_NOTIFY */
329
330static void DX5_PlayAudio(_THIS)
331{
332 /* Unlock the buffer, allowing it to play */
333 if ( locked_buf ) {
334 IDirectSoundBuffer_Unlock(mixbuf, locked_buf, mixlen, NULL, 0);
335 }
336
337}
338
339static Uint8 *DX5_GetAudioBuf(_THIS)
340{
341 DWORD cursor, junk;
342 HRESULT result;
343 DWORD rawlen;
344
345 /* Figure out which blocks to fill next */
346 locked_buf = NULL;
347 result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, &junk, &cursor);
348 if ( result == DSERR_BUFFERLOST ) {
349 IDirectSoundBuffer_Restore(mixbuf);
350 result = IDirectSoundBuffer_GetCurrentPosition(mixbuf,
351 &junk, &cursor);
352 }
353 if ( result != DS_OK ) {
354 SetDSerror("DirectSound GetCurrentPosition", result);
355 return(NULL);
356 }
357 cursor /= mixlen;
358#ifdef DEBUG_SOUND
359 /* Detect audio dropouts */
360 { DWORD spot = cursor;
361 if ( spot < lastchunk ) {
362 spot += NUM_BUFFERS;
363 }
364 if ( spot > lastchunk+1 ) {
365 fprintf(stderr, "Audio dropout, missed %d fragments\n",
366 (spot - (lastchunk+1)));
367 }
368 }
369#endif
370 lastchunk = cursor;
371 cursor = (cursor+1)%NUM_BUFFERS;
372 cursor *= mixlen;
373
374 /* Lock the audio buffer */
375 result = IDirectSoundBuffer_Lock(mixbuf, cursor, mixlen,
376 (LPVOID *)&locked_buf, &rawlen, NULL, &junk, 0);
377 if ( result == DSERR_BUFFERLOST ) {
378 IDirectSoundBuffer_Restore(mixbuf);
379 result = IDirectSoundBuffer_Lock(mixbuf, cursor, mixlen,
380 (LPVOID *)&locked_buf, &rawlen, NULL, &junk, 0);
381 }
382 if ( result != DS_OK ) {
383 SetDSerror("DirectSound Lock", result);
384 return(NULL);
385 }
386 return(locked_buf);
387}
388
389static void DX5_WaitDone(_THIS)
390{
391 Uint8 *stream;
392
393 /* Wait for the playing chunk to finish */
394 stream = this->GetAudioBuf(this);
395 if ( stream != NULL ) {
396 SDL_memset(stream, silence, mixlen);
397 this->PlayAudio(this);
398 }
399 this->WaitAudio(this);
400
401 /* Stop the looping sound buffer */
402 IDirectSoundBuffer_Stop(mixbuf);
403}
404
405static void DX5_CloseAudio(_THIS)
406{
407 if ( sound != NULL ) {
408 if ( mixbuf != NULL ) {
409 /* Clean up the audio buffer */
410 IDirectSoundBuffer_Release(mixbuf);
411 mixbuf = NULL;
412 }
413 if ( audio_event != NULL ) {
414 CloseHandle(audio_event);
415 audio_event = NULL;
416 }
417 IDirectSound_Release(sound);
418 sound = NULL;
419 }
420}
421
422#ifdef USE_PRIMARY_BUFFER
423/* This function tries to create a primary audio buffer, and returns the
424 number of audio chunks available in the created buffer.
425*/
426static int CreatePrimary(LPDIRECTSOUND sndObj, HWND focus,
427 LPDIRECTSOUNDBUFFER *sndbuf, WAVEFORMATEX *wavefmt, Uint32 chunksize)
428{
429 HRESULT result;
430 DSBUFFERDESC format;
431 DSBCAPS caps;
432 int numchunks;
433
434 /* Try to set primary mixing privileges */
435 result = IDirectSound_SetCooperativeLevel(sndObj, focus,
436 DSSCL_WRITEPRIMARY);
437 if ( result != DS_OK ) {
438#ifdef DEBUG_SOUND
439 SetDSerror("DirectSound SetCooperativeLevel", result);
440#endif
441 return(-1);
442 }
443
444 /* Try to create the primary buffer */
445 SDL_memset(&format, 0, sizeof(format));
446 format.dwSize = sizeof(format);
447 format.dwFlags=(DSBCAPS_PRIMARYBUFFER|DSBCAPS_GETCURRENTPOSITION2);
448 format.dwFlags |= DSBCAPS_STICKYFOCUS;
449#ifdef USE_POSITION_NOTIFY
450 format.dwFlags |= DSBCAPS_CTRLPOSITIONNOTIFY;
451#endif
452 result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL);
453 if ( result != DS_OK ) {
454#ifdef DEBUG_SOUND
455 SetDSerror("DirectSound CreateSoundBuffer", result);
456#endif
457 return(-1);
458 }
459
460 /* Check the size of the fragment buffer */
461 SDL_memset(&caps, 0, sizeof(caps));
462 caps.dwSize = sizeof(caps);
463 result = IDirectSoundBuffer_GetCaps(*sndbuf, &caps);
464 if ( result != DS_OK ) {
465#ifdef DEBUG_SOUND
466 SetDSerror("DirectSound GetCaps", result);
467#endif
468 IDirectSoundBuffer_Release(*sndbuf);
469 return(-1);
470 }
471 if ( (chunksize > caps.dwBufferBytes) ||
472 ((caps.dwBufferBytes%chunksize) != 0) ) {
473 /* The primary buffer size is not a multiple of 'chunksize'
474 -- this hopefully doesn't happen when 'chunksize' is a
475 power of 2.
476 */
477 IDirectSoundBuffer_Release(*sndbuf);
478 SDL_SetError(
479"Primary buffer size is: %d, cannot break it into chunks of %d bytes\n",
480 caps.dwBufferBytes, chunksize);
481 return(-1);
482 }
483 numchunks = (caps.dwBufferBytes/chunksize);
484
485 /* Set the primary audio format */
486 result = IDirectSoundBuffer_SetFormat(*sndbuf, wavefmt);
487 if ( result != DS_OK ) {
488#ifdef DEBUG_SOUND
489 SetDSerror("DirectSound SetFormat", result);
490#endif
491 IDirectSoundBuffer_Release(*sndbuf);
492 return(-1);
493 }
494 return(numchunks);
495}
496#endif /* USE_PRIMARY_BUFFER */
497
498/* This function tries to create a secondary audio buffer, and returns the
499 number of audio chunks available in the created buffer.
500*/
501static int CreateSecondary(LPDIRECTSOUND sndObj, HWND focus,
502 LPDIRECTSOUNDBUFFER *sndbuf, WAVEFORMATEX *wavefmt, Uint32 chunksize)
503{
504 const int numchunks = 8;
505 HRESULT result;
506 DSBUFFERDESC format;
507 LPVOID pvAudioPtr1, pvAudioPtr2;
508 DWORD dwAudioBytes1, dwAudioBytes2;
509
510 /* Try to set primary mixing privileges */
511 if ( focus ) {
512 result = IDirectSound_SetCooperativeLevel(sndObj,
513 focus, DSSCL_PRIORITY);
514 } else {
515 result = IDirectSound_SetCooperativeLevel(sndObj,
516 GetDesktopWindow(), DSSCL_NORMAL);
517 }
518 if ( result != DS_OK ) {
519#ifdef DEBUG_SOUND
520 SetDSerror("DirectSound SetCooperativeLevel", result);
521#endif
522 return(-1);
523 }
524
525 /* Try to create the secondary buffer */
526 SDL_memset(&format, 0, sizeof(format));
527 format.dwSize = sizeof(format);
528 format.dwFlags = DSBCAPS_GETCURRENTPOSITION2;
529#ifdef USE_POSITION_NOTIFY
530 format.dwFlags |= DSBCAPS_CTRLPOSITIONNOTIFY;
531#endif
532 if ( ! focus ) {
533 format.dwFlags |= DSBCAPS_GLOBALFOCUS;
534 } else {
535 format.dwFlags |= DSBCAPS_STICKYFOCUS;
536 }
537 format.dwBufferBytes = numchunks*chunksize;
538 if ( (format.dwBufferBytes < DSBSIZE_MIN) ||
539 (format.dwBufferBytes > DSBSIZE_MAX) ) {
540 SDL_SetError("Sound buffer size must be between %d and %d",
541 DSBSIZE_MIN/numchunks, DSBSIZE_MAX/numchunks);
542 return(-1);
543 }
544 format.dwReserved = 0;
545 format.lpwfxFormat = wavefmt;
546 result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL);
547 if ( result != DS_OK ) {
548 SetDSerror("DirectSound CreateSoundBuffer", result);
549 return(-1);
550 }
551 IDirectSoundBuffer_SetFormat(*sndbuf, wavefmt);
552
553 /* Silence the initial audio buffer */
554 result = IDirectSoundBuffer_Lock(*sndbuf, 0, format.dwBufferBytes,
555 (LPVOID *)&pvAudioPtr1, &dwAudioBytes1,
556 (LPVOID *)&pvAudioPtr2, &dwAudioBytes2,
557 DSBLOCK_ENTIREBUFFER);
558 if ( result == DS_OK ) {
559 if ( wavefmt->wBitsPerSample == 8 ) {
560 SDL_memset(pvAudioPtr1, 0x80, dwAudioBytes1);
561 } else {
562 SDL_memset(pvAudioPtr1, 0x00, dwAudioBytes1);
563 }
564 IDirectSoundBuffer_Unlock(*sndbuf,
565 (LPVOID)pvAudioPtr1, dwAudioBytes1,
566 (LPVOID)pvAudioPtr2, dwAudioBytes2);
567 }
568
569 /* We're ready to go */
570 return(numchunks);
571}
572
573/* This function tries to set position notify events on the mixing buffer */
574#ifdef USE_POSITION_NOTIFY
575static int CreateAudioEvent(_THIS)
576{
577 LPDIRECTSOUNDNOTIFY notify;
578 DSBPOSITIONNOTIFY *notify_positions;
579 int i, retval;
580 HRESULT result;
581
582 /* Default to fail on exit */
583 retval = -1;
584 notify = NULL;
585
586 /* Query for the interface */
587 result = IDirectSoundBuffer_QueryInterface(mixbuf,
588 &IID_IDirectSoundNotify, (void *)&notify);
589 if ( result != DS_OK ) {
590 goto done;
591 }
592
593 /* Allocate the notify structures */
594 notify_positions = (DSBPOSITIONNOTIFY *)SDL_malloc(NUM_BUFFERS*
595 sizeof(*notify_positions));
596 if ( notify_positions == NULL ) {
597 goto done;
598 }
599
600 /* Create the notify event */
601 audio_event = CreateEvent(NULL, FALSE, FALSE, NULL);
602 if ( audio_event == NULL ) {
603 goto done;
604 }
605
606 /* Set up the notify structures */
607 for ( i=0; i<NUM_BUFFERS; ++i ) {
608 notify_positions[i].dwOffset = i*mixlen;
609 notify_positions[i].hEventNotify = audio_event;
610 }
611 result = IDirectSoundNotify_SetNotificationPositions(notify,
612 NUM_BUFFERS, notify_positions);
613 if ( result == DS_OK ) {
614 retval = 0;
615 }
616done:
617 if ( notify != NULL ) {
618 IDirectSoundNotify_Release(notify);
619 }
620 return(retval);
621}
622#endif /* USE_POSITION_NOTIFY */
623
624static int DX5_OpenAudio(_THIS, SDL_AudioSpec *spec)
625{
626 HRESULT result;
627 WAVEFORMATEX waveformat;
628
629 /* Set basic WAVE format parameters */
630 SDL_memset(&waveformat, 0, sizeof(waveformat));
631 waveformat.wFormatTag = WAVE_FORMAT_PCM;
632
633 /* Determine the audio parameters from the AudioSpec */
634 switch ( spec->format & 0xFF ) {
635 case 8:
636 /* Unsigned 8 bit audio data */
637 spec->format = AUDIO_U8;
638 silence = 0x80;
639 waveformat.wBitsPerSample = 8;
640 break;
641 case 16:
642 /* Signed 16 bit audio data */
643 spec->format = AUDIO_S16;
644 silence = 0x00;
645 waveformat.wBitsPerSample = 16;
646 break;
647 default:
648 SDL_SetError("Unsupported audio format");
649 return(-1);
650 }
651 waveformat.nChannels = spec->channels;
652 waveformat.nSamplesPerSec = spec->freq;
653 waveformat.nBlockAlign =
654 waveformat.nChannels * (waveformat.wBitsPerSample/8);
655 waveformat.nAvgBytesPerSec =
656 waveformat.nSamplesPerSec * waveformat.nBlockAlign;
657
658 /* Update the fragment size as size in bytes */
659 SDL_CalculateAudioSpec(spec);
660
661 /* Open the audio device */
662 result = DSoundCreate(NULL, &sound, NULL);
663 if ( result != DS_OK ) {
664 SetDSerror("DirectSoundCreate", result);
665 return(-1);
666 }
667
668 /* Create the audio buffer to which we write */
669 NUM_BUFFERS = -1;
670#ifdef USE_PRIMARY_BUFFER
671 if ( mainwin ) {
672 NUM_BUFFERS = CreatePrimary(sound, mainwin, &mixbuf,
673 &waveformat, spec->size);
674 }
675#endif /* USE_PRIMARY_BUFFER */
676 if ( NUM_BUFFERS < 0 ) {
677 NUM_BUFFERS = CreateSecondary(sound, mainwin, &mixbuf,
678 &waveformat, spec->size);
679 if ( NUM_BUFFERS < 0 ) {
680 return(-1);
681 }
682#ifdef DEBUG_SOUND
683 fprintf(stderr, "Using secondary audio buffer\n");
684#endif
685 }
686#ifdef DEBUG_SOUND
687 else
688 fprintf(stderr, "Using primary audio buffer\n");
689#endif
690
691 /* The buffer will auto-start playing in DX5_WaitAudio() */
692 lastchunk = 0;
693 mixlen = spec->size;
694
695#ifdef USE_POSITION_NOTIFY
696 /* See if we can use DirectX 6 event notification */
697 if ( CreateAudioEvent(this) == 0 ) {
698 this->WaitAudio = DX6_WaitAudio_EventWait;
699 } else {
700 this->WaitAudio = DX5_WaitAudio_BusyWait;
701 }
702#endif
703 return(0);
704}
705
diff --git a/apps/plugins/sdl/src/audio/windx5/SDL_dx5audio.h b/apps/plugins/sdl/src/audio/windx5/SDL_dx5audio.h
deleted file mode 100644
index bc4022fc9c..0000000000
--- a/apps/plugins/sdl/src/audio/windx5/SDL_dx5audio.h
+++ /dev/null
@@ -1,55 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowaudio_h
25#define _SDL_lowaudio_h
26
27#include "directx.h"
28
29#include "../SDL_sysaudio.h"
30
31/* Hidden "this" pointer for the video functions */
32#define _THIS SDL_AudioDevice *this
33
34/* The DirectSound objects */
35struct SDL_PrivateAudioData {
36 LPDIRECTSOUND sound;
37 LPDIRECTSOUNDBUFFER mixbuf;
38 int NUM_BUFFERS;
39 int mixlen, silence;
40 DWORD lastchunk;
41 Uint8 *locked_buf;
42 HANDLE audio_event;
43};
44
45/* Old variable names */
46#define sound (this->hidden->sound)
47#define mixbuf (this->hidden->mixbuf)
48#define NUM_BUFFERS (this->hidden->NUM_BUFFERS)
49#define mixlen (this->hidden->mixlen)
50#define silence (this->hidden->silence)
51#define lastchunk (this->hidden->lastchunk)
52#define locked_buf (this->hidden->locked_buf)
53#define audio_event (this->hidden->audio_event)
54
55#endif /* _SDL_lowaudio_h */
diff --git a/apps/plugins/sdl/src/audio/windx5/directx.h b/apps/plugins/sdl/src/audio/windx5/directx.h
deleted file mode 100644
index 5f339f2de8..0000000000
--- a/apps/plugins/sdl/src/audio/windx5/directx.h
+++ /dev/null
@@ -1,81 +0,0 @@
1
2#ifndef _directx_h
3#define _directx_h
4
5/* Include all of the DirectX 5.0 headers and adds any necessary tweaks */
6
7#define WIN32_LEAN_AND_MEAN
8#include <windows.h>
9#include <mmsystem.h>
10#ifndef WIN32
11#define WIN32
12#endif
13#undef WINNT
14
15/* Far pointers don't exist in 32-bit code */
16#ifndef FAR
17#define FAR
18#endif
19
20/* Error codes not yet included in Win32 API header files */
21#ifndef MAKE_HRESULT
22#define MAKE_HRESULT(sev,fac,code) \
23 ((HRESULT)(((unsigned long)(sev)<<31) | ((unsigned long)(fac)<<16) | ((unsigned long)(code))))
24#endif
25
26#ifndef S_OK
27#define S_OK (HRESULT)0x00000000L
28#endif
29
30#ifndef SUCCEEDED
31#define SUCCEEDED(x) ((HRESULT)(x) >= 0)
32#endif
33#ifndef FAILED
34#define FAILED(x) ((HRESULT)(x)<0)
35#endif
36
37#ifndef E_FAIL
38#define E_FAIL (HRESULT)0x80000008L
39#endif
40#ifndef E_NOINTERFACE
41#define E_NOINTERFACE (HRESULT)0x80004002L
42#endif
43#ifndef E_OUTOFMEMORY
44#define E_OUTOFMEMORY (HRESULT)0x8007000EL
45#endif
46#ifndef E_INVALIDARG
47#define E_INVALIDARG (HRESULT)0x80070057L
48#endif
49#ifndef E_NOTIMPL
50#define E_NOTIMPL (HRESULT)0x80004001L
51#endif
52#ifndef REGDB_E_CLASSNOTREG
53#define REGDB_E_CLASSNOTREG (HRESULT)0x80040154L
54#endif
55
56/* Severity codes */
57#ifndef SEVERITY_ERROR
58#define SEVERITY_ERROR 1
59#endif
60
61/* Error facility codes */
62#ifndef FACILITY_WIN32
63#define FACILITY_WIN32 7
64#endif
65
66#ifndef FIELD_OFFSET
67#define FIELD_OFFSET(type, field) ((LONG)&(((type *)0)->field))
68#endif
69
70/* DirectX headers (if it isn't included, I haven't tested it yet)
71 */
72/* We need these defines to mark what version of DirectX API we use */
73#define DIRECTDRAW_VERSION 0x0700
74#define DIRECTSOUND_VERSION 0x0500
75#define DIRECTINPUT_VERSION 0x0500
76
77#include <ddraw.h>
78#include <dsound.h>
79#include <dinput.h>
80
81#endif /* _directx_h */
diff --git a/apps/plugins/sdl/src/cdrom/aix/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/aix/SDL_syscdrom.c
deleted file mode 100644
index e7e05585e3..0000000000
--- a/apps/plugins/sdl/src/cdrom/aix/SDL_syscdrom.c
+++ /dev/null
@@ -1,660 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Carsten Griwodz
20 griff@kom.tu-darmstadt.de
21
22 based on linux/SDL_syscdrom.c by Sam Lantinga
23*/
24#include "SDL_config.h"
25
26#ifdef SDL_CDROM_AIX
27
28/* Functions for system-level CD-ROM audio control */
29
30/*#define DEBUG_CDROM 1*/
31
32#include <sys/types.h>
33#include <sys/stat.h>
34#include <fcntl.h>
35#include <errno.h>
36#include <unistd.h>
37
38#include <sys/ioctl.h>
39#include <sys/devinfo.h>
40#include <sys/mntctl.h>
41#include <sys/statfs.h>
42#include <sys/vmount.h>
43#include <fstab.h>
44#include <sys/scdisk.h>
45
46#include "SDL_cdrom.h"
47#include "../SDL_syscdrom.h"
48
49/* The maximum number of CD-ROM drives we'll detect */
50#define MAX_DRIVES 16
51
52/* A list of available CD-ROM drives */
53static char *SDL_cdlist[MAX_DRIVES];
54static dev_t SDL_cdmode[MAX_DRIVES];
55
56/* The system-dependent CD control functions */
57static const char *SDL_SYS_CDName(int drive);
58static int SDL_SYS_CDOpen(int drive);
59static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
60static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
61static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
62static int SDL_SYS_CDPause(SDL_CD *cdrom);
63static int SDL_SYS_CDResume(SDL_CD *cdrom);
64static int SDL_SYS_CDStop(SDL_CD *cdrom);
65static int SDL_SYS_CDEject(SDL_CD *cdrom);
66static void SDL_SYS_CDClose(SDL_CD *cdrom);
67static int SDL_SYS_CDioctl(int id, int command, void *arg);
68
69/* Check a drive to see if it is a CD-ROM */
70static int CheckDrive(char *drive, struct stat *stbuf)
71{
72 int is_cd;
73 int cdfd;
74 int ret;
75 struct devinfo info;
76
77 /* If it doesn't exist, return -1 */
78 if ( stat(drive, stbuf) < 0 ) {
79 return -1;
80 }
81
82 /* If it does exist, verify that it's an available CD-ROM */
83 is_cd = 0;
84 if ( S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode) ) {
85 cdfd = open(drive, (O_RDONLY|O_EXCL|O_NONBLOCK), 0);
86 if ( cdfd >= 0 ) {
87 ret = SDL_SYS_CDioctl( cdfd, IOCINFO, &info );
88 if ( ret < 0 ) {
89 /* Some kind of error */
90 is_cd = 0;
91 } else {
92 if ( info.devtype == DD_CDROM ) {
93 is_cd = 1;
94 } else {
95 is_cd = 0;
96 }
97 }
98 close(cdfd);
99 }
100#ifdef DEBUG_CDROM
101 else
102 {
103 fprintf(stderr, "Could not open drive %s (%s)\n", drive, strerror(errno));
104 }
105#endif
106 }
107 return is_cd;
108}
109
110/* Add a CD-ROM drive to our list of valid drives */
111static void AddDrive(char *drive, struct stat *stbuf)
112{
113 int i;
114
115 if ( SDL_numcds < MAX_DRIVES ) {
116 /* Check to make sure it's not already in our list.
117 This can happen when we see a drive via symbolic link.
118 */
119 for ( i=0; i<SDL_numcds; ++i ) {
120 if ( stbuf->st_rdev == SDL_cdmode[i] ) {
121#ifdef DEBUG_CDROM
122 fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]);
123#endif
124 return;
125 }
126 }
127
128 /* Add this drive to our list */
129 i = SDL_numcds;
130 SDL_cdlist[i] = SDL_strdup(drive);
131 if ( SDL_cdlist[i] == NULL ) {
132 SDL_OutOfMemory();
133 return;
134 }
135 SDL_cdmode[i] = stbuf->st_rdev;
136 ++SDL_numcds;
137#ifdef DEBUG_CDROM
138 fprintf(stderr, "Added CD-ROM drive: %s\n", drive);
139#endif
140 }
141}
142
143static void CheckMounts()
144{
145 char* buffer;
146 int bufsz;
147 struct vmount* ptr;
148 int ret;
149
150 buffer = (char*)SDL_malloc(10);
151 bufsz = 10;
152 if ( buffer==NULL )
153 {
154 fprintf(stderr, "Could not allocate 10 bytes in aix/SDL_syscdrom.c:CheckMounts\n" );
155 exit ( -10 );
156 }
157
158 do
159 {
160 /* mntctrl() returns an array of all mounted filesystems */
161 ret = mntctl ( MCTL_QUERY, bufsz, buffer );
162 if ( ret == 0 )
163 {
164 /* Buffer was too small, realloc. */
165 bufsz = *(int*)buffer; /* Required size is in first word. */
166 /* (whatever a word is in AIX 4.3.3) */
167 /* int seems to be OK in 32bit mode. */
168 SDL_free(buffer);
169 buffer = (char*)SDL_malloc(bufsz);
170 if ( buffer==NULL )
171 {
172 fprintf(stderr,
173 "Could not allocate %d bytes in aix/SDL_syscdrom.c:CheckMounts\n",
174 bufsz );
175 exit ( -10 );
176 }
177 }
178 else if ( ret < 0 )
179 {
180#ifdef DEBUG_CDROM
181 fprintf(stderr, "Error reading vmount structures\n");
182#endif
183 return;
184 }
185 }
186 while ( ret == 0 );
187
188#ifdef DEBUG_CDROM
189 fprintf ( stderr, "Read %d vmount structures\n",ret );
190#endif
191 ptr = (struct vmount*)buffer;
192 do
193 {
194 switch(ptr->vmt_gfstype)
195 {
196 case MNT_CDROM :
197 {
198 struct stat stbuf;
199 char* text;
200
201 text = (char*)ptr + ptr->vmt_data[VMT_OBJECT].vmt_off;
202#ifdef DEBUG_CDROM
203 fprintf(stderr, "Checking mount path: %s mounted on %s\n",
204 text, (char*)ptr + ptr->vmt_data[VMT_STUB].vmt_off );
205#endif
206 if ( CheckDrive( text, &stbuf) > 0)
207 {
208 AddDrive( text, &stbuf);
209 }
210 }
211 break;
212 default :
213 break;
214 }
215 ptr = (struct vmount*)((char*)ptr + ptr->vmt_length);
216 ret--;
217 }
218 while ( ret > 0 );
219
220 free ( buffer );
221}
222
223static int CheckNonmounts()
224{
225#ifdef _THREAD_SAFE
226 AFILE_t fsFile = NULL;
227 int passNo = 0;
228 int ret;
229 struct fstab entry;
230 struct stat stbuf;
231
232 ret = setfsent_r( &fsFile, &passNo );
233 if ( ret != 0 ) return -1;
234 do
235 {
236 ret = getfsent_r ( &entry, &fsFile, &passNo );
237 if ( ret == 0 ) {
238 char* l = SDL_strrchr(entry.fs_spec,'/');
239 if ( l != NULL ) {
240 if ( !SDL_strncmp("cd",++l,2) ) {
241#ifdef DEBUG_CDROM
242 fprintf(stderr,
243 "Found unmounted CD ROM drive with device name %s\n",
244 entry.fs_spec);
245#endif
246 if ( CheckDrive( entry.fs_spec, &stbuf) > 0)
247 {
248 AddDrive( entry.fs_spec, &stbuf);
249 }
250 }
251 }
252 }
253 }
254 while ( ret == 0 );
255 ret = endfsent_r ( &fsFile );
256 if ( ret != 0 ) return -1;
257 return 0;
258#else
259 struct fstab* entry;
260 struct stat stbuf;
261
262 setfsent();
263 do
264 {
265 entry = getfsent();
266 if ( entry != NULL ) {
267 char* l = SDL_strrchr(entry->fs_spec,'/');
268 if ( l != NULL ) {
269 if ( !SDL_strncmp("cd",++l,2) ) {
270#ifdef DEBUG_CDROM
271 fprintf(stderr,"Found unmounted CD ROM drive with device name %s", entry->fs_spec);
272#endif
273 if ( CheckDrive( entry->fs_spec, &stbuf) > 0)
274 {
275 AddDrive( entry->fs_spec, &stbuf);
276 }
277 }
278 }
279 }
280 }
281 while ( entry != NULL );
282 endfsent();
283#endif
284}
285
286int SDL_SYS_CDInit(void)
287{
288 char *SDLcdrom;
289 struct stat stbuf;
290
291 /* Fill in our driver capabilities */
292 SDL_CDcaps.Name = SDL_SYS_CDName;
293 SDL_CDcaps.Open = SDL_SYS_CDOpen;
294 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
295 SDL_CDcaps.Status = SDL_SYS_CDStatus;
296 SDL_CDcaps.Play = SDL_SYS_CDPlay;
297 SDL_CDcaps.Pause = SDL_SYS_CDPause;
298 SDL_CDcaps.Resume = SDL_SYS_CDResume;
299 SDL_CDcaps.Stop = SDL_SYS_CDStop;
300 SDL_CDcaps.Eject = SDL_SYS_CDEject;
301 SDL_CDcaps.Close = SDL_SYS_CDClose;
302
303 /* Look in the environment for our CD-ROM drive list */
304 SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */
305 if ( SDLcdrom != NULL ) {
306 char *cdpath, *delim;
307 size_t len = SDL_strlen(SDLcdrom)+1;
308 cdpath = SDL_stack_alloc(char, len);
309 if ( cdpath != NULL ) {
310 SDL_strlcpy(cdpath, SDLcdrom, len);
311 SDLcdrom = cdpath;
312 do {
313 delim = SDL_strchr(SDLcdrom, ':');
314 if ( delim ) {
315 *delim++ = '\0';
316 }
317#ifdef DEBUG_CDROM
318 fprintf(stderr, "Checking CD-ROM drive from SDL_CDROM: %s\n", SDLcdrom);
319#endif
320 if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) {
321 AddDrive(SDLcdrom, &stbuf);
322 }
323 if ( delim ) {
324 SDLcdrom = delim;
325 } else {
326 SDLcdrom = NULL;
327 }
328 } while ( SDLcdrom );
329 SDL_stack_free(cdpath);
330 }
331
332 /* If we found our drives, there's nothing left to do */
333 if ( SDL_numcds > 0 ) {
334 return(0);
335 }
336 }
337
338 CheckMounts();
339 CheckNonmounts();
340
341 return 0;
342}
343
344/* General ioctl() CD-ROM command function */
345static int SDL_SYS_CDioctl(int id, int command, void *arg)
346{
347 int retval;
348
349 retval = ioctl(id, command, arg);
350 if ( retval < 0 ) {
351 SDL_SetError("ioctl() error: %s", strerror(errno));
352 }
353 return retval;
354}
355
356static const char *SDL_SYS_CDName(int drive)
357{
358 return(SDL_cdlist[drive]);
359}
360
361static int SDL_SYS_CDOpen(int drive)
362{
363 int fd;
364 char* lastsl;
365 char* cdromname;
366 size_t len;
367
368 /*
369 * We found /dev/cd? drives and that is in our list. But we can
370 * open only the /dev/rcd? versions of those devices for Audio CD.
371 */
372 len = SDL_strlen(SDL_cdlist[drive])+2;
373 cdromname = (char*)SDL_malloc(len);
374 SDL_strlcpy(cdromname,SDL_cdlist[drive],len);
375 lastsl = SDL_strrchr(cdromname,'/');
376 if (lastsl) {
377 *lastsl = 0;
378 SDL_strlcat(cdromname,"/r",len);
379 lastsl = SDL_strrchr(SDL_cdlist[drive],'/');
380 if (lastsl) {
381 lastsl++;
382 SDL_strlcat(cdromname,lastsl,len);
383 }
384 }
385
386#ifdef DEBUG_CDROM
387 fprintf(stderr, "Should open drive %s, opening %s\n", SDL_cdlist[drive], cdromname);
388#endif
389
390 /*
391 * Use exclusive access. Don't use SC_DIAGNOSTICS as xmcd does because they
392 * require root priviledges, and we don't want that. SC_SINGLE provides
393 * exclusive access with less trouble.
394 */
395 fd = openx(cdromname, O_RDONLY, NULL, SC_SINGLE);
396 if ( fd < 0 )
397 {
398#ifdef DEBUG_CDROM
399 fprintf(stderr, "Could not open drive %s (%s)\n", cdromname, strerror(errno));
400#endif
401 }
402 else
403 {
404 struct mode_form_op cdMode;
405 int ret;
406#ifdef DEBUG_CDROM
407 cdMode.action = CD_GET_MODE;
408 ret = SDL_SYS_CDioctl(fd, DK_CD_MODE, &cdMode);
409 if ( ret < 0 ) {
410 fprintf(stderr,
411 "Could not get drive mode for %s (%s)\n",
412 cdromname, strerror(errno));
413 } else {
414 switch(cdMode.cd_mode_form) {
415 case CD_MODE1 :
416 fprintf(stderr,
417 "Drive mode for %s is %s\n",
418 cdromname, "CD-ROM Data Mode 1");
419 break;
420 case CD_MODE2_FORM1 :
421 fprintf(stderr,
422 "Drive mode for %s is %s\n",
423 cdromname, "CD-ROM XA Data Mode 2 Form 1");
424 break;
425 case CD_MODE2_FORM2 :
426 fprintf(stderr,
427 "Drive mode for %s is %s\n",
428 cdromname, "CD-ROM XA Data Mode 2 Form 2");
429 break;
430 case CD_DA :
431 fprintf(stderr,
432 "Drive mode for %s is %s\n",
433 cdromname, "CD-DA");
434 break;
435 default :
436 fprintf(stderr,
437 "Drive mode for %s is %s\n",
438 cdromname, "unknown");
439 break;
440 }
441 }
442#endif
443
444 cdMode.action = CD_CHG_MODE;
445 cdMode.cd_mode_form = CD_DA;
446 ret = SDL_SYS_CDioctl(fd, DK_CD_MODE, &cdMode);
447 if ( ret < 0 ) {
448#ifdef DEBUG_CDROM
449 fprintf(stderr,
450 "Could not set drive mode for %s (%s)\n",
451 cdromname, strerror(errno));
452#endif
453 SDL_SetError("ioctl() error: Could not set CD drive mode, %s",
454 strerror(errno));
455 } else {
456#ifdef DEBUG_CDROM
457 fprintf(stderr,
458 "Drive mode for %s set to CD_DA\n",
459 cdromname);
460#endif
461 }
462 }
463 SDL_free(cdromname);
464 return fd;
465}
466
467static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
468{
469 struct cd_audio_cmd cmd;
470 struct cd_audio_cmd entry;
471 int i;
472 int okay;
473
474 cmd.audio_cmds = CD_TRK_INFO_AUDIO;
475 cmd.msf_flag = FALSE;
476 if ( SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd) < 0 ) {
477 return -1;
478 }
479
480 okay = 0;
481 cdrom->numtracks = cmd.indexing.track_index.last_track
482 - cmd.indexing.track_index.first_track+1;
483 if ( cdrom->numtracks > SDL_MAX_TRACKS ) {
484 cdrom->numtracks = SDL_MAX_TRACKS;
485 }
486
487 /* Read all the track TOC entries */
488 for ( i=0; i<=cdrom->numtracks; ++i ) {
489 if ( i == cdrom->numtracks ) {
490 cdrom->track[i].id = 0xAA;;
491 } else {
492 cdrom->track[i].id = cmd.indexing.track_index.first_track+i;
493 }
494 entry.audio_cmds = CD_GET_TRK_MSF;
495 entry.indexing.track_msf.track = cdrom->track[i].id;
496 if ( SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &entry) < 0 ) {
497 break;
498 } else {
499 cdrom->track[i].type = 0; /* don't know how to detect 0x04 data track */
500 cdrom->track[i].offset = MSF_TO_FRAMES(
501 entry.indexing.track_msf.mins,
502 entry.indexing.track_msf.secs,
503 entry.indexing.track_msf.frames);
504 cdrom->track[i].length = 0;
505 if ( i > 0 ) {
506 cdrom->track[i-1].length = cdrom->track[i].offset
507 - cdrom->track[i-1].offset;
508 }
509 }
510 }
511 if ( i == (cdrom->numtracks+1) ) {
512 okay = 1;
513 }
514 return(okay ? 0 : -1);
515}
516
517/* Get CD-ROM status */
518static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
519{
520 CDstatus status;
521 struct cd_audio_cmd cmd;
522 cmd.audio_cmds = CD_INFO_AUDIO;
523
524 if ( SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd) < 0 ) {
525#ifdef DEBUG_CDROM
526 fprintf(stderr, "ioctl failed in SDL_SYS_CDStatus (%s)\n", SDL_GetError());
527#endif
528 status = CD_ERROR;
529 } else {
530 switch (cmd.status) {
531 case CD_NO_AUDIO:
532 case CD_COMPLETED:
533 status = CD_STOPPED;
534 break;
535 case CD_PLAY_AUDIO:
536 status = CD_PLAYING;
537 break;
538 case CD_PAUSE_AUDIO:
539 status = CD_PAUSED;
540 break;
541 case CD_NOT_VALID:
542#ifdef DEBUG_CDROM
543 fprintf(stderr, "cdStatus failed with CD_NOT_VALID\n");
544#endif
545 status = CD_ERROR;
546 break;
547 case CD_STATUS_ERROR:
548#ifdef DEBUG_CDROM
549 fprintf(stderr, "cdStatus failed with CD_STATUS_ERROR\n");
550#endif
551 status = CD_ERROR;
552 break;
553 default:
554#ifdef DEBUG_CDROM
555 fprintf(stderr, "cdStatus failed with unknown error\n");
556#endif
557 status = CD_ERROR;
558 break;
559 }
560 }
561 if ( position ) {
562 if ( status == CD_PLAYING || (status == CD_PAUSED) ) {
563 *position = MSF_TO_FRAMES( cmd.indexing.info_audio.current_mins,
564 cmd.indexing.info_audio.current_secs,
565 cmd.indexing.info_audio.current_frames);
566 } else {
567 *position = 0;
568 }
569 }
570 return status;
571}
572
573/* Start play */
574static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
575{
576 struct cd_audio_cmd cmd;
577
578 /*
579 * My CD Rom is muted by default. I think I read that this is new with
580 * AIX 4.3. SDL does not change the volume, so I need a kludge. Maybe
581 * its better to do this elsewhere?
582 */
583 cmd.audio_cmds = CD_PLAY_AUDIO | CD_SET_VOLUME;
584 cmd.msf_flag = TRUE;
585 FRAMES_TO_MSF(start,
586 &cmd.indexing.msf.first_mins,
587 &cmd.indexing.msf.first_secs,
588 &cmd.indexing.msf.first_frames);
589 FRAMES_TO_MSF(start+length,
590 &cmd.indexing.msf.last_mins,
591 &cmd.indexing.msf.last_secs,
592 &cmd.indexing.msf.last_frames);
593 cmd.volume_type = CD_VOLUME_ALL;
594 cmd.all_channel_vol = 255; /* This is a uchar. What is a good value? No docu! */
595 cmd.out_port_0_sel = CD_AUDIO_CHNL_0;
596 cmd.out_port_1_sel = CD_AUDIO_CHNL_1;
597 cmd.out_port_2_sel = CD_AUDIO_CHNL_2;
598 cmd.out_port_3_sel = CD_AUDIO_CHNL_3;
599
600#ifdef DEBUG_CDROM
601 fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n",
602 cmd.indexing.msf.first_mins,
603 cmd.indexing.msf.first_secs,
604 cmd.indexing.msf.first_frames,
605 cmd.indexing.msf.last_mins,
606 cmd.indexing.msf.last_secs,
607 cmd.indexing.msf.last_frames);
608#endif
609 return(SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd));
610}
611
612/* Pause play */
613static int SDL_SYS_CDPause(SDL_CD *cdrom)
614{
615 struct cd_audio_cmd cmd;
616 cmd.audio_cmds = CD_PAUSE_AUDIO;
617 return(SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd));
618}
619
620/* Resume play */
621static int SDL_SYS_CDResume(SDL_CD *cdrom)
622{
623 struct cd_audio_cmd cmd;
624 cmd.audio_cmds = CD_RESUME_AUDIO;
625 return(SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd));
626}
627
628/* Stop play */
629static int SDL_SYS_CDStop(SDL_CD *cdrom)
630{
631 struct cd_audio_cmd cmd;
632 cmd.audio_cmds = CD_STOP_AUDIO;
633 return(SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd));
634}
635
636/* Eject the CD-ROM */
637static int SDL_SYS_CDEject(SDL_CD *cdrom)
638{
639 return(SDL_SYS_CDioctl(cdrom->id, DKEJECT, 0));
640}
641
642/* Close the CD-ROM handle */
643static void SDL_SYS_CDClose(SDL_CD *cdrom)
644{
645 close(cdrom->id);
646}
647
648void SDL_SYS_CDQuit(void)
649{
650 int i;
651
652 if ( SDL_numcds > 0 ) {
653 for ( i=0; i<SDL_numcds; ++i ) {
654 SDL_free(SDL_cdlist[i]);
655 }
656 SDL_numcds = 0;
657 }
658}
659
660#endif /* SDL_CDROM_AIX */
diff --git a/apps/plugins/sdl/src/cdrom/beos/SDL_syscdrom.cc b/apps/plugins/sdl/src/cdrom/beos/SDL_syscdrom.cc
deleted file mode 100644
index 9a62c38399..0000000000
--- a/apps/plugins/sdl/src/cdrom/beos/SDL_syscdrom.cc
+++ /dev/null
@@ -1,410 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_BEOS
25
26/* Functions for system-level CD-ROM audio control on BeOS
27 (not completely implemented yet)
28 */
29
30#include <sys/types.h>
31#include <sys/stat.h>
32#include <unistd.h>
33
34#include <scsi.h>
35#include <Directory.h>
36#include <Entry.h>
37#include <Path.h>
38
39#include "SDL_cdrom.h"
40extern "C" {
41#include "../SDL_syscdrom.h"
42}
43
44/* Constants to help us get at the SCSI table-of-contents info */
45#define CD_NUMTRACKS(toc) toc.toc_data[3]
46#define CD_TRACK(toc, track) (&toc.toc_data[6+(track)*8])
47#define CD_TRACK_N(toc, track) CD_TRACK(toc, track)[0]
48#define CD_TRACK_M(toc, track) CD_TRACK(toc, track)[3]
49#define CD_TRACK_S(toc, track) CD_TRACK(toc, track)[4]
50#define CD_TRACK_F(toc, track) CD_TRACK(toc, track)[5]
51
52/* Constants to help us get at the SCSI position info */
53#define POS_TRACK(pos) pos.position[6]
54#define POS_ABS_M(pos) pos.position[9]
55#define POS_ABS_S(pos) pos.position[10]
56#define POS_ABS_F(pos) pos.position[11]
57#define POS_REL_M(pos) pos.position[13]
58#define POS_REL_S(pos) pos.position[14]
59#define POS_REL_F(pos) pos.position[15]
60
61/* The maximum number of CD-ROM drives we'll detect */
62#define MAX_DRIVES 16
63
64/* A list of available CD-ROM drives */
65static char *SDL_cdlist[MAX_DRIVES];
66
67/* The system-dependent CD control functions */
68static const char *SDL_SYS_CDName(int drive);
69static int SDL_SYS_CDOpen(int drive);
70static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
71static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
72static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
73static int SDL_SYS_CDPause(SDL_CD *cdrom);
74static int SDL_SYS_CDResume(SDL_CD *cdrom);
75static int SDL_SYS_CDStop(SDL_CD *cdrom);
76static int SDL_SYS_CDEject(SDL_CD *cdrom);
77static void SDL_SYS_CDClose(SDL_CD *cdrom);
78int try_dir(const char *directory);
79
80
81/* Check a drive to see if it is a CD-ROM */
82static int CheckDrive(char *drive)
83{
84 struct stat stbuf;
85 int is_cd, cdfd;
86 device_geometry info;
87
88 /* If it doesn't exist, return -1 */
89 if ( stat(drive, &stbuf) < 0 ) {
90 return(-1);
91 }
92
93 /* If it does exist, verify that it's an available CD-ROM */
94 is_cd = 0;
95 cdfd = open(drive, 0);
96 if ( cdfd >= 0 ) {
97 if ( ioctl(cdfd, B_GET_GEOMETRY, &info) == B_NO_ERROR ) {
98 if ( info.device_type == B_CD ) {
99 is_cd = 1;
100 }
101 }
102 close(cdfd);
103 } else {
104 /* This can happen when the drive is open .. (?) */;
105 is_cd = 1;
106 }
107 return(is_cd);
108}
109
110/* Add a CD-ROM drive to our list of valid drives */
111static void AddDrive(char *drive)
112{
113 int i;
114 size_t len;
115
116 if ( SDL_numcds < MAX_DRIVES ) {
117 /* Add this drive to our list */
118 i = SDL_numcds;
119 len = SDL_strlen(drive)+1;
120 SDL_cdlist[i] = (char *)SDL_malloc(len);
121 if ( SDL_cdlist[i] == NULL ) {
122 SDL_OutOfMemory();
123 return;
124 }
125 SDL_strlcpy(SDL_cdlist[i], drive, len);
126 ++SDL_numcds;
127#ifdef CDROM_DEBUG
128 fprintf(stderr, "Added CD-ROM drive: %s\n", drive);
129#endif
130 }
131}
132
133/* IDE bus scanning magic */
134enum {
135 IDE_GET_DEVICES_INFO = B_DEVICE_OP_CODES_END + 50,
136};
137struct ide_ctrl_info {
138 bool ide_0_present;
139 bool ide_0_master_present;
140 bool ide_0_slave_present;
141 int ide_0_master_type;
142 int ide_0_slave_type;
143 bool ide_1_present;
144 bool ide_1_master_present;
145 bool ide_1_slave_present;
146 int ide_1_master_type;
147 int ide_1_slave_type;
148};
149
150int SDL_SYS_CDInit(void)
151{
152 char *SDLcdrom;
153
154 /* Fill in our driver capabilities */
155 SDL_CDcaps.Name = SDL_SYS_CDName;
156 SDL_CDcaps.Open = SDL_SYS_CDOpen;
157 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
158 SDL_CDcaps.Status = SDL_SYS_CDStatus;
159 SDL_CDcaps.Play = SDL_SYS_CDPlay;
160 SDL_CDcaps.Pause = SDL_SYS_CDPause;
161 SDL_CDcaps.Resume = SDL_SYS_CDResume;
162 SDL_CDcaps.Stop = SDL_SYS_CDStop;
163 SDL_CDcaps.Eject = SDL_SYS_CDEject;
164 SDL_CDcaps.Close = SDL_SYS_CDClose;
165
166 /* Look in the environment for our CD-ROM drive list */
167 SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */
168 if ( SDLcdrom != NULL ) {
169 char *cdpath, *delim;
170 size_t len = SDL_strlen(SDLcdrom)+1;
171 cdpath = SDL_stack_alloc(char, len);
172 if ( cdpath != NULL ) {
173 SDL_strlcpy(cdpath, SDLcdrom, len);
174 SDLcdrom = cdpath;
175 do {
176 delim = SDL_strchr(SDLcdrom, ':');
177 if ( delim ) {
178 *delim++ = '\0';
179 }
180 if ( CheckDrive(SDLcdrom) > 0 ) {
181 AddDrive(SDLcdrom);
182 }
183 if ( delim ) {
184 SDLcdrom = delim;
185 } else {
186 SDLcdrom = NULL;
187 }
188 } while ( SDLcdrom );
189 SDL_stack_free(cdpath);
190 }
191
192 /* If we found our drives, there's nothing left to do */
193 if ( SDL_numcds > 0 ) {
194 return(0);
195 }
196 }
197
198 /* Scan the system for CD-ROM drives */
199 try_dir("/dev/disk");
200 return 0;
201}
202
203
204int try_dir(const char *directory)
205{
206 BDirectory dir;
207 dir.SetTo(directory);
208 if(dir.InitCheck() != B_NO_ERROR) {
209 return false;
210 }
211 dir.Rewind();
212 BEntry entry;
213 while(dir.GetNextEntry(&entry) >= 0) {
214 BPath path;
215 const char *name;
216 entry_ref e;
217
218 if(entry.GetPath(&path) != B_NO_ERROR)
219 continue;
220 name = path.Path();
221
222 if(entry.GetRef(&e) != B_NO_ERROR)
223 continue;
224
225 if(entry.IsDirectory()) {
226 if(SDL_strcmp(e.name, "floppy") == 0)
227 continue; /* ignore floppy (it is not silent) */
228 int devfd = try_dir(name);
229 if(devfd >= 0)
230 return devfd;
231 }
232 else {
233 int devfd;
234 device_geometry g;
235
236 if(SDL_strcmp(e.name, "raw") != 0)
237 continue; /* ignore partitions */
238
239 devfd = open(name, O_RDONLY);
240 if(devfd < 0)
241 continue;
242
243 if(ioctl(devfd, B_GET_GEOMETRY, &g, sizeof(g)) >= 0) {
244 if(g.device_type == B_CD)
245 {
246 AddDrive(strdup(name));
247 }
248 }
249 close(devfd);
250 }
251 }
252 return B_ERROR;
253}
254
255
256/* General ioctl() CD-ROM command function */
257static int SDL_SYS_CDioctl(int index, int command, void *arg)
258{
259 int okay;
260 int fd;
261
262 okay = 0;
263 fd = open(SDL_cdlist[index], 0);
264 if ( fd >= 0 ) {
265 if ( ioctl(fd, command, arg) == B_NO_ERROR ) {
266 okay = 1;
267 }
268 close(fd);
269 }
270 return(okay ? 0 : -1);
271}
272
273static const char *SDL_SYS_CDName(int drive)
274{
275 return(SDL_cdlist[drive]);
276}
277
278static int SDL_SYS_CDOpen(int drive)
279{
280 return(drive);
281}
282
283static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
284{
285 int i;
286 scsi_toc toc;
287
288 if ( SDL_SYS_CDioctl(cdrom->id, B_SCSI_GET_TOC, &toc) == 0 ) {
289 cdrom->numtracks = CD_NUMTRACKS(toc);
290 if ( cdrom->numtracks > SDL_MAX_TRACKS ) {
291 cdrom->numtracks = SDL_MAX_TRACKS;
292 }
293 for ( i=0; i<=cdrom->numtracks; ++i ) {
294 cdrom->track[i].id = CD_TRACK_N(toc, i);
295 /* FIXME: How do we tell on BeOS? */
296 cdrom->track[i].type = SDL_AUDIO_TRACK;
297 cdrom->track[i].offset = MSF_TO_FRAMES(
298 CD_TRACK_M(toc, i),
299 CD_TRACK_S(toc, i),
300 CD_TRACK_F(toc, i));
301 cdrom->track[i].length = 0;
302 if ( i > 0 ) {
303 cdrom->track[i-1].length =
304 cdrom->track[i].offset-
305 cdrom->track[i-1].offset;
306 }
307 }
308 return(0);
309 } else {
310 return(-1);
311 }
312}
313
314/* Get CD-ROM status */
315static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
316{
317 CDstatus status;
318 int fd;
319 int cur_frame;
320 scsi_position pos;
321
322 fd = open(SDL_cdlist[cdrom->id], 0);
323 cur_frame = 0;
324 if ( fd >= 0 ) {
325 if ( ioctl(fd, B_SCSI_GET_POSITION, &pos) == B_NO_ERROR ) {
326 cur_frame = MSF_TO_FRAMES(
327 POS_ABS_M(pos), POS_ABS_S(pos), POS_ABS_F(pos));
328 }
329 if ( ! pos.position[1] || (pos.position[1] >= 0x13) ||
330 ((pos.position[1] == 0x12) && (!pos.position[6])) ) {
331 status = CD_STOPPED;
332 } else
333 if ( pos.position[1] == 0x11 ) {
334 status = CD_PLAYING;
335 } else {
336 status = CD_PAUSED;
337 }
338 close(fd);
339 } else {
340 status = CD_TRAYEMPTY;
341 }
342 if ( position ) {
343 *position = cur_frame;
344 }
345 return(status);
346}
347
348/* Start play */
349static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
350{
351 int okay;
352 int fd;
353 scsi_play_position pos;
354
355 okay = 0;
356 fd = open(SDL_cdlist[cdrom->id], 0);
357 if ( fd >= 0 ) {
358 FRAMES_TO_MSF(start, &pos.start_m, &pos.start_s, &pos.start_f);
359 FRAMES_TO_MSF(start+length, &pos.end_m, &pos.end_s, &pos.end_f);
360 if ( ioctl(fd, B_SCSI_PLAY_POSITION, &pos) == B_NO_ERROR ) {
361 okay = 1;
362 }
363 close(fd);
364 }
365 return(okay ? 0 : -1);
366}
367
368/* Pause play */
369static int SDL_SYS_CDPause(SDL_CD *cdrom)
370{
371 return(SDL_SYS_CDioctl(cdrom->id, B_SCSI_PAUSE_AUDIO, 0));
372}
373
374/* Resume play */
375static int SDL_SYS_CDResume(SDL_CD *cdrom)
376{
377 return(SDL_SYS_CDioctl(cdrom->id, B_SCSI_RESUME_AUDIO, 0));
378}
379
380/* Stop play */
381static int SDL_SYS_CDStop(SDL_CD *cdrom)
382{
383 return(SDL_SYS_CDioctl(cdrom->id, B_SCSI_STOP_AUDIO, 0));
384}
385
386/* Eject the CD-ROM */
387static int SDL_SYS_CDEject(SDL_CD *cdrom)
388{
389 return(SDL_SYS_CDioctl(cdrom->id, B_SCSI_EJECT, 0));
390}
391
392/* Close the CD-ROM handle */
393static void SDL_SYS_CDClose(SDL_CD *cdrom)
394{
395 close(cdrom->id);
396}
397
398void SDL_SYS_CDQuit(void)
399{
400 int i;
401
402 if ( SDL_numcds > 0 ) {
403 for ( i=0; i<SDL_numcds; ++i ) {
404 SDL_free(SDL_cdlist[i]);
405 }
406 SDL_numcds = 0;
407 }
408}
409
410#endif /* SDL_CDROM_BEOS */
diff --git a/apps/plugins/sdl/src/cdrom/bsdi/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/bsdi/SDL_syscdrom.c
deleted file mode 100644
index 61edb819d2..0000000000
--- a/apps/plugins/sdl/src/cdrom/bsdi/SDL_syscdrom.c
+++ /dev/null
@@ -1,542 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_BSDI
25
26/*
27 * Functions for system-level CD-ROM audio control for BSD/OS 4.x
28 * This started life out as a copy of the freebsd/SDL_cdrom.c file but was
29 * heavily modified. Works for standard (MMC) SCSI and ATAPI CDrom drives.
30 *
31 * Steven Schultz - sms@to.gd-es.com
32*/
33
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <fcntl.h>
37#include <err.h>
38#include <unistd.h>
39#include <sys/ioctl.h>
40#include </sys/dev/scsi/scsi.h>
41#include </sys/dev/scsi/scsi_ioctl.h>
42
43#include "SDL_cdrom.h"
44#include "../SDL_syscdrom.h"
45
46/*
47 * The msf_to_frame and frame_to_msf were yanked from libcdrom and inlined
48 * here so that -lcdrom doesn't have to be dragged in for something so simple.
49*/
50
51#define FRAMES_PER_SECOND 75
52#define FRAMES_PER_MINUTE (FRAMES_PER_SECOND * 60)
53
54int
55msf_to_frame(int minute, int second, int frame)
56 {
57 return(minute * FRAMES_PER_MINUTE + second * FRAMES_PER_SECOND + frame);
58 }
59
60void
61frame_to_msf(int frame, int *minp, int *secp, int *framep)
62 {
63 *minp = frame / FRAMES_PER_MINUTE;
64 *secp = (frame % FRAMES_PER_MINUTE) / FRAMES_PER_SECOND;
65 *framep = frame % FRAMES_PER_SECOND;
66 }
67
68/* The maximum number of CD-ROM drives we'll detect */
69#define MAX_DRIVES 16
70
71/* A list of available CD-ROM drives */
72static char *SDL_cdlist[MAX_DRIVES];
73static dev_t SDL_cdmode[MAX_DRIVES];
74
75/* The system-dependent CD control functions */
76static const char *SDL_SYS_CDName(int drive);
77static int SDL_SYS_CDOpen(int drive);
78static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
79static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
80static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
81static int SDL_SYS_CDPause(SDL_CD *cdrom);
82static int SDL_SYS_CDResume(SDL_CD *cdrom);
83static int SDL_SYS_CDStop(SDL_CD *cdrom);
84static int SDL_SYS_CDEject(SDL_CD *cdrom);
85static void SDL_SYS_CDClose(SDL_CD *cdrom);
86
87typedef struct scsi_cdb cdb_t;
88
89static int scsi_cmd(int fd,
90 struct scsi_cdb *cdb,
91 int cdblen,
92 int rw,
93 caddr_t data,
94 int datalen,
95 struct scsi_user_cdb *sus)
96 {
97 int scsistatus;
98 unsigned char *cp;
99 struct scsi_user_cdb suc;
100
101 /* safety checks */
102 if (!cdb) return(-1);
103 if (rw != SUC_READ && rw != SUC_WRITE) return(-1);
104
105 suc.suc_flags = rw;
106 suc.suc_cdblen = cdblen;
107 bcopy(cdb, suc.suc_cdb, cdblen);
108 suc.suc_datalen = datalen;
109 suc.suc_data = data;
110 suc.suc_timeout = 10; /* 10 secs max for TUR or SENSE */
111 if (ioctl(fd, SCSIRAWCDB, &suc) == -1)
112 return(-11);
113 scsistatus = suc.suc_sus.sus_status;
114 cp = suc.suc_sus.sus_sense;
115
116/*
117 * If a place to copy the sense data back to has been provided then the
118 * caller is responsible for checking the errors and printing any information
119 * out if the status was not successful.
120*/
121 if (scsistatus != 0 && !sus)
122 {
123 fprintf(stderr,"scsistatus = %x cmd = %x\n",
124 scsistatus, cdb[0]);
125 fprintf(stderr, "sense %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n",
126 cp[0], cp[1], cp[2], cp[3], cp[4], cp[5],
127 cp[6], cp[7], cp[8], cp[9], cp[10], cp[11],
128 cp[12], cp[13], cp[14], cp[15]);
129 return(1);
130 }
131 if (sus)
132 bcopy(&suc, sus, sizeof (struct scsi_user_cdb));
133 if (scsistatus)
134 return(1); /* Return non-zero for unsuccessful status */
135 return(0);
136 }
137
138/* request vendor brand and model */
139unsigned char *Inquiry(int fd)
140 {
141 static struct scsi_cdb6 cdb =
142 {
143 0x12,
144 0, 0, 0,
145 56,
146 0
147 };
148 static unsigned char Inqbuffer[56];
149
150 if (scsi_cmd(fd, (cdb_t *)&cdb, 6, SUC_READ, Inqbuffer,
151 sizeof(Inqbuffer), 0))
152 return("\377");
153 return(Inqbuffer);
154 }
155
156#define ADD_SENSECODE 12
157#define ADD_SC_QUALIFIER 13
158
159int TestForMedium(int fd)
160 {
161 int sts, asc, ascq;
162 struct scsi_user_cdb sus;
163 static struct scsi_cdb6 cdb =
164 {
165 CMD_TEST_UNIT_READY, /* command */
166 0, /* reserved */
167 0, /* reserved */
168 0, /* reserved */
169 0, /* reserved */
170 0 /* reserved */
171 };
172
173again: sts = scsi_cmd(fd, (cdb_t *)&cdb, 6, SUC_READ, 0, 0, &sus);
174 asc = sus.suc_sus.sus_sense[ADD_SENSECODE];
175 ascq = sus.suc_sus.sus_sense[ADD_SC_QUALIFIER];
176 if (asc == 0x3a && ascq == 0x0) /* no medium */
177 return(0);
178 if (asc == 0x28 && ascq == 0x0) /* medium changed */
179 goto again;
180 if (asc == 0x4 && ascq == 0x1 ) /* coming ready */
181 {
182 sleep(2);
183 goto again;
184 }
185 return(1);
186 }
187
188/* Check a drive to see if it is a CD-ROM */
189static int CheckDrive(char *drive, struct stat *stbuf)
190{
191 int is_cd = 0, cdfd;
192 char *p;
193
194 /* If it doesn't exist, return -1 */
195 if ( stat(drive, stbuf) < 0 ) {
196 return(-1);
197 }
198
199 /* If it does exist, verify that it's an available CD-ROM */
200 cdfd = open(drive, (O_RDONLY|O_EXCL|O_NONBLOCK), 0);
201 if ( cdfd >= 0 ) {
202 p = Inquiry(cdfd);
203 if (*p == TYPE_ROM)
204 is_cd = 1;
205 close(cdfd);
206 }
207 return(is_cd);
208}
209
210/* Add a CD-ROM drive to our list of valid drives */
211static void AddDrive(char *drive, struct stat *stbuf)
212{
213 int i;
214
215 if ( SDL_numcds < MAX_DRIVES ) {
216 /* Check to make sure it's not already in our list.
217 This can happen when we see a drive via symbolic link.
218 */
219 for ( i=0; i<SDL_numcds; ++i ) {
220 if ( stbuf->st_rdev == SDL_cdmode[i] ) {
221#ifdef DEBUG_CDROM
222 fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]);
223#endif
224 return;
225 }
226 }
227
228 /* Add this drive to our list */
229 i = SDL_numcds;
230 SDL_cdlist[i] = SDL_strdup(drive);
231 if ( SDL_cdlist[i] == NULL ) {
232 SDL_OutOfMemory();
233 return;
234 }
235 SDL_cdmode[i] = stbuf->st_rdev;
236 ++SDL_numcds;
237#ifdef DEBUG_CDROM
238 fprintf(stderr, "Added CD-ROM drive: %s\n", drive);
239#endif
240 }
241}
242
243int SDL_SYS_CDInit(void)
244{
245 /* checklist: /dev/rsr?c */
246 static char *checklist[] = {
247 "?0 rsr?", NULL
248 };
249 char *SDLcdrom;
250 int i, j, exists;
251 char drive[32];
252 struct stat stbuf;
253
254 /* Fill in our driver capabilities */
255 SDL_CDcaps.Name = SDL_SYS_CDName;
256 SDL_CDcaps.Open = SDL_SYS_CDOpen;
257 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
258 SDL_CDcaps.Status = SDL_SYS_CDStatus;
259 SDL_CDcaps.Play = SDL_SYS_CDPlay;
260 SDL_CDcaps.Pause = SDL_SYS_CDPause;
261 SDL_CDcaps.Resume = SDL_SYS_CDResume;
262 SDL_CDcaps.Stop = SDL_SYS_CDStop;
263 SDL_CDcaps.Eject = SDL_SYS_CDEject;
264 SDL_CDcaps.Close = SDL_SYS_CDClose;
265
266 /* Look in the environment for our CD-ROM drive list */
267 SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */
268 if ( SDLcdrom != NULL ) {
269 char *cdpath, *delim;
270 size_t len = SDL_strlen(SDLcdrom)+1;
271 cdpath = SDL_stack_alloc(char, len);
272 if ( cdpath != NULL ) {
273 SDL_strlcpy(cdpath, SDLcdrom, len);
274 SDLcdrom = cdpath;
275 do {
276 delim = SDL_strchr(SDLcdrom, ':');
277 if ( delim ) {
278 *delim++ = '\0';
279 }
280 if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) {
281 AddDrive(SDLcdrom, &stbuf);
282 }
283 if ( delim ) {
284 SDLcdrom = delim;
285 } else {
286 SDLcdrom = NULL;
287 }
288 } while ( SDLcdrom );
289 SDL_stack_free(cdpath);
290 }
291
292 /* If we found our drives, there's nothing left to do */
293 if ( SDL_numcds > 0 ) {
294 return(0);
295 }
296 }
297
298 /* Scan the system for CD-ROM drives */
299 for ( i=0; checklist[i]; ++i ) {
300 if ( checklist[i][0] == '?' ) {
301 char *insert;
302 exists = 1;
303 for ( j=checklist[i][1]; exists; ++j ) {
304 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%sc", &checklist[i][3]);
305 insert = SDL_strchr(drive, '?');
306 if ( insert != NULL ) {
307 *insert = j;
308 }
309 switch (CheckDrive(drive, &stbuf)) {
310 /* Drive exists and is a CD-ROM */
311 case 1:
312 AddDrive(drive, &stbuf);
313 break;
314 /* Drive exists, but isn't a CD-ROM */
315 case 0:
316 break;
317 /* Drive doesn't exist */
318 case -1:
319 exists = 0;
320 break;
321 }
322 }
323 } else {
324 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]);
325 if ( CheckDrive(drive, &stbuf) > 0 ) {
326 AddDrive(drive, &stbuf);
327 }
328 }
329 }
330 return(0);
331}
332
333static const char *SDL_SYS_CDName(int drive)
334{
335 return(SDL_cdlist[drive]);
336}
337
338static int SDL_SYS_CDOpen(int drive)
339{
340 return(open(SDL_cdlist[drive], O_RDONLY | O_NONBLOCK | O_EXCL, 0));
341}
342
343static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
344 {
345 u_char cdb[10], buf[4], *p, *toc;
346 struct scsi_user_cdb sus;
347 int i, sts, first_track, last_track, ntracks, toc_size;
348
349 bzero(cdb, sizeof (cdb));
350 cdb[0] = 0x43; /* Read TOC */
351 cdb[1] = 0x2; /* MSF */
352 cdb[8] = 4; /* size TOC header */
353 sts = scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, buf, 4, &sus);
354 if (sts < 0)
355 return(-1);
356 first_track = buf[2];
357 last_track = buf[3];
358 ntracks = last_track - first_track + 1;
359 cdrom->numtracks = ntracks;
360 toc_size = 4 + (ntracks + 1) * 8;
361 toc = (u_char *)SDL_malloc(toc_size);
362 if (toc == NULL)
363 return(-1);
364 bzero(cdb, sizeof (cdb));
365 cdb[0] = 0x43;
366 cdb[1] = 0x2;
367 cdb[6] = first_track;
368 cdb[7] = toc_size >> 8;
369 cdb[8] = toc_size & 0xff;
370 sts = scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, toc, toc_size,
371 &sus);
372 if (sts < 0)
373 {
374 SDL_free(toc);
375 return(-1);
376 }
377
378 for (i = 0, p = toc+4; i <= ntracks; i++, p+= 8)
379 {
380 if (i == ntracks)
381 cdrom->track[i].id = 0xAA; /* Leadout */
382 else
383 cdrom->track[i].id = first_track + i;
384 if (p[1] & 0x20)
385 cdrom->track[i].type = SDL_DATA_TRACK;
386 else
387 cdrom->track[i].type = SDL_AUDIO_TRACK;
388 cdrom->track[i].offset = msf_to_frame(p[5], p[6], p[7]);
389 cdrom->track[i].length = 0;
390 if (i > 0)
391 cdrom->track[i-1].length = cdrom->track[i].offset -
392 cdrom->track[i-1].offset;
393 }
394 SDL_free(toc);
395 return(0);
396 }
397
398/* Get CD-ROM status */
399static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
400 {
401 CDstatus status;
402 u_char cdb[10], buf[16];
403 int sts;
404 struct scsi_user_cdb sus;
405
406 bzero(cdb, sizeof (cdb));
407 cdb[0] = 0x42; /* read subq */
408 cdb[1] = 0x2; /* MSF */
409 cdb[2] = 0x40; /* q channel */
410 cdb[3] = 1; /* current pos */
411 cdb[7] = sizeof (buf) >> 8;
412 cdb[8] = sizeof (buf) & 0xff;
413 sts = scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, buf, sizeof (buf),
414 &sus);
415 if (sts < 0)
416 return(-1);
417 if (sts)
418 {
419 if (TestForMedium(cdrom->id) == 0)
420 status = CD_TRAYEMPTY;
421 else
422 status = CD_ERROR;
423 }
424 else
425 {
426 switch (buf[1])
427 {
428 case 0x11:
429 status = CD_PLAYING;
430 break;
431 case 0x12:
432 status = CD_PAUSED;
433 break;
434 case 0x13:
435 case 0x14:
436 case 0x15:
437 status = CD_STOPPED;
438 break;
439 default:
440 status = CD_ERROR;
441 break;
442 }
443 }
444 if (position)
445 {
446 if ( status == CD_PLAYING || (status == CD_PAUSED) )
447 *position = msf_to_frame(buf[9], buf[10], buf[11]);
448 else
449 *position = 0;
450 }
451 return(status);
452 }
453
454/* Start play */
455static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
456 {
457 u_char cdb[10];
458 int sts, minute, second, frame, eminute, esecond, eframe;
459 struct scsi_user_cdb sus;
460
461 bzero(cdb, sizeof(cdb));
462 cdb[0] = 0x47; /* Play */
463 frame_to_msf(start, &minute, &second, &frame);
464 frame_to_msf(start + length, &eminute, &esecond, &eframe);
465 cdb[3] = minute;
466 cdb[4] = second;
467 cdb[5] = frame;
468 cdb[6] = eminute;
469 cdb[7] = esecond;
470 cdb[8] = eframe;
471 sts = scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, 0, 0, &sus);
472 return(sts);
473 }
474
475static int
476pauseresume(SDL_CD *cdrom, int flag)
477 {
478 u_char cdb[10];
479 struct scsi_user_cdb sus;
480
481 bzero(cdb, sizeof (cdb));
482 cdb[0] = 0x4b;
483 cdb[8] = flag & 0x1;
484 return(scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, 0, 0, &sus));
485 }
486
487/* Pause play */
488static int SDL_SYS_CDPause(SDL_CD *cdrom)
489{
490 return(pauseresume(cdrom, 0));
491}
492
493/* Resume play */
494static int SDL_SYS_CDResume(SDL_CD *cdrom)
495{
496 return(pauseresume(cdrom, 1));
497}
498
499/* Stop play */
500static int SDL_SYS_CDStop(SDL_CD *cdrom)
501{
502 u_char cdb[6];
503 struct scsi_user_cdb sus;
504
505 bzero(cdb, sizeof (cdb));
506 cdb[0] = 0x1b; /* stop */
507 cdb[1] = 1; /* immediate */
508 return(scsi_cmd(cdrom->id, (cdb_t *)cdb, 6, SUC_READ, 0, 0, &sus));
509}
510
511/* Eject the CD-ROM */
512static int SDL_SYS_CDEject(SDL_CD *cdrom)
513{
514 u_char cdb[6];
515 struct scsi_user_cdb sus;
516
517 bzero(cdb, sizeof (cdb));
518 cdb[0] = 0x1b; /* stop */
519 cdb[1] = 1; /* immediate */
520 cdb[4] = 2; /* eject */
521 return(scsi_cmd(cdrom->id, (cdb_t *)cdb, 6, SUC_READ, 0, 0, &sus));
522}
523
524/* Close the CD-ROM handle */
525static void SDL_SYS_CDClose(SDL_CD *cdrom)
526 {
527 close(cdrom->id);
528 }
529
530void SDL_SYS_CDQuit(void)
531{
532 int i;
533
534 if ( SDL_numcds > 0 ) {
535 for ( i=0; i<SDL_numcds; ++i ) {
536 SDL_free(SDL_cdlist[i]);
537 }
538 }
539 SDL_numcds = 0;
540}
541
542#endif /* SDL_CDROM_BSDI */
diff --git a/apps/plugins/sdl/src/cdrom/dc/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/dc/SDL_syscdrom.c
deleted file mode 100644
index 445ad7c25a..0000000000
--- a/apps/plugins/sdl/src/cdrom/dc/SDL_syscdrom.c
+++ /dev/null
@@ -1,167 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_DC
25
26/* Functions for system-level CD-ROM audio control */
27
28#include <dc/cdrom.h>
29#include <dc/spu.h>
30
31#include "SDL_cdrom.h"
32#include "../SDL_syscdrom.h"
33
34/* The system-dependent CD control functions */
35static const char *SDL_SYS_CDName(int drive);
36static int SDL_SYS_CDOpen(int drive);
37static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
38static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
39static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
40static int SDL_SYS_CDPause(SDL_CD *cdrom);
41static int SDL_SYS_CDResume(SDL_CD *cdrom);
42static int SDL_SYS_CDStop(SDL_CD *cdrom);
43static int SDL_SYS_CDEject(SDL_CD *cdrom);
44static void SDL_SYS_CDClose(SDL_CD *cdrom);
45
46
47int SDL_SYS_CDInit(void)
48{
49 /* Fill in our driver capabilities */
50 SDL_CDcaps.Name = SDL_SYS_CDName;
51 SDL_CDcaps.Open = SDL_SYS_CDOpen;
52 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
53 SDL_CDcaps.Status = SDL_SYS_CDStatus;
54 SDL_CDcaps.Play = SDL_SYS_CDPlay;
55 SDL_CDcaps.Pause = SDL_SYS_CDPause;
56 SDL_CDcaps.Resume = SDL_SYS_CDResume;
57 SDL_CDcaps.Stop = SDL_SYS_CDStop;
58 SDL_CDcaps.Eject = SDL_SYS_CDEject;
59 SDL_CDcaps.Close = SDL_SYS_CDClose;
60
61 return(0);
62}
63
64static const char *SDL_SYS_CDName(int drive)
65{
66 return "/cd";
67}
68
69static int SDL_SYS_CDOpen(int drive)
70{
71 return(drive);
72}
73
74#define TRACK_CDDA 0
75static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
76{
77 CDROM_TOC toc;
78 int ret,i;
79
80 ret = cdrom_read_toc(&toc,0);
81 if (ret!=ERR_OK) {
82 return -1;
83 }
84
85 cdrom->numtracks = TOC_TRACK(toc.last)-TOC_TRACK(toc.first)+1;
86 for(i=0;i<cdrom->numtracks;i++) {
87 unsigned long entry = toc.entry[i];
88 cdrom->track[i].id = i+1;
89 cdrom->track[i].type = (TOC_CTRL(toc.entry[i])==TRACK_CDDA)?SDL_AUDIO_TRACK:SDL_DATA_TRACK;
90 cdrom->track[i].offset = TOC_LBA(entry)-150;
91 cdrom->track[i].length = TOC_LBA((i+1<toc.last)?toc.entry[i+1]:toc.leadout_sector)-TOC_LBA(entry);
92 }
93
94 return 0;
95}
96
97/* Get CD-ROM status */
98static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
99{
100 int ret,dc_status,disc_type;
101
102 ret = cdrom_get_status(&dc_status,&disc_type);
103 if (ret!=ERR_OK) return CD_ERROR;
104
105 switch(dc_status) {
106// case CD_STATUS_BUSY:
107 case CD_STATUS_PAUSED:
108 return CD_PAUSED;
109 case CD_STATUS_STANDBY:
110 return CD_STOPPED;
111 case CD_STATUS_PLAYING:
112 return CD_PLAYING;
113// case CD_STATUS_SEEKING:
114// case CD_STATUS_SCANING:
115 case CD_STATUS_OPEN:
116 case CD_STATUS_NO_DISC:
117 return CD_TRAYEMPTY;
118 default:
119 return CD_ERROR;
120 }
121}
122
123/* Start play */
124static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
125{
126 int ret = cdrom_cdda_play(start-150,start-150+length,1,CDDA_SECTORS);
127 return ret==ERR_OK?0:-1;
128}
129
130/* Pause play */
131static int SDL_SYS_CDPause(SDL_CD *cdrom)
132{
133 int ret=cdrom_cdda_pause();
134 return ret==ERR_OK?0:-1;
135}
136
137/* Resume play */
138static int SDL_SYS_CDResume(SDL_CD *cdrom)
139{
140 int ret=cdrom_cdda_resume();
141 return ret==ERR_OK?0:-1;
142}
143
144/* Stop play */
145static int SDL_SYS_CDStop(SDL_CD *cdrom)
146{
147 int ret=cdrom_spin_down();
148 return ret==ERR_OK?0:-1;
149}
150
151/* Eject the CD-ROM */
152static int SDL_SYS_CDEject(SDL_CD *cdrom)
153{
154 return -1;
155}
156
157/* Close the CD-ROM handle */
158static void SDL_SYS_CDClose(SDL_CD *cdrom)
159{
160}
161
162void SDL_SYS_CDQuit(void)
163{
164
165}
166
167#endif /* SDL_CDROM_DC */
diff --git a/apps/plugins/sdl/src/cdrom/freebsd/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/freebsd/SDL_syscdrom.c
deleted file mode 100644
index 0260c9489f..0000000000
--- a/apps/plugins/sdl/src/cdrom/freebsd/SDL_syscdrom.c
+++ /dev/null
@@ -1,406 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_FREEBSD
25
26/* Functions for system-level CD-ROM audio control */
27
28#include <sys/types.h>
29#include <sys/stat.h>
30#include <fcntl.h>
31#include <errno.h>
32#include <unistd.h>
33#include <sys/cdio.h>
34
35#include "SDL_cdrom.h"
36#include "../SDL_syscdrom.h"
37
38
39/* The maximum number of CD-ROM drives we'll detect */
40#define MAX_DRIVES 16
41
42/* A list of available CD-ROM drives */
43static char *SDL_cdlist[MAX_DRIVES];
44static dev_t SDL_cdmode[MAX_DRIVES];
45
46/* The system-dependent CD control functions */
47static const char *SDL_SYS_CDName(int drive);
48static int SDL_SYS_CDOpen(int drive);
49static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
50static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
51static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
52static int SDL_SYS_CDPause(SDL_CD *cdrom);
53static int SDL_SYS_CDResume(SDL_CD *cdrom);
54static int SDL_SYS_CDStop(SDL_CD *cdrom);
55static int SDL_SYS_CDEject(SDL_CD *cdrom);
56static void SDL_SYS_CDClose(SDL_CD *cdrom);
57
58/* Some ioctl() errno values which occur when the tray is empty */
59#define ERRNO_TRAYEMPTY(errno) \
60 ((errno == EIO) || (errno == ENOENT) || (errno == EINVAL))
61
62/* Check a drive to see if it is a CD-ROM */
63static int CheckDrive(char *drive, struct stat *stbuf)
64{
65 int is_cd, cdfd;
66 struct ioc_read_subchannel info;
67
68 /* If it doesn't exist, return -1 */
69 if ( stat(drive, stbuf) < 0 ) {
70 return(-1);
71 }
72
73 /* If it does exist, verify that it's an available CD-ROM */
74 is_cd = 0;
75 if ( S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode) ) {
76 cdfd = open(drive, (O_RDONLY|O_EXCL|O_NONBLOCK), 0);
77 if ( cdfd >= 0 ) {
78 info.address_format = CD_MSF_FORMAT;
79 info.data_format = CD_CURRENT_POSITION;
80 info.data_len = 0;
81 info.data = NULL;
82 /* Under Linux, EIO occurs when a disk is not present.
83 This isn't 100% reliable, so we use the USE_MNTENT
84 code above instead.
85 */
86 if ( (ioctl(cdfd, CDIOCREADSUBCHANNEL, &info) == 0) ||
87 ERRNO_TRAYEMPTY(errno) ) {
88 is_cd = 1;
89 }
90 close(cdfd);
91 }
92 }
93 return(is_cd);
94}
95
96/* Add a CD-ROM drive to our list of valid drives */
97static void AddDrive(char *drive, struct stat *stbuf)
98{
99 int i;
100
101 if ( SDL_numcds < MAX_DRIVES ) {
102 /* Check to make sure it's not already in our list.
103 This can happen when we see a drive via symbolic link.
104 */
105 for ( i=0; i<SDL_numcds; ++i ) {
106 if ( stbuf->st_rdev == SDL_cdmode[i] ) {
107#ifdef DEBUG_CDROM
108 fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]);
109#endif
110 return;
111 }
112 }
113
114 /* Add this drive to our list */
115 i = SDL_numcds;
116 SDL_cdlist[i] = SDL_strdup(drive);
117 if ( SDL_cdlist[i] == NULL ) {
118 SDL_OutOfMemory();
119 return;
120 }
121 SDL_cdmode[i] = stbuf->st_rdev;
122 ++SDL_numcds;
123#ifdef DEBUG_CDROM
124 fprintf(stderr, "Added CD-ROM drive: %s\n", drive);
125#endif
126 }
127}
128
129int SDL_SYS_CDInit(void)
130{
131 /* checklist: /dev/cdrom,/dev/cd?c /dev/acd?c
132 /dev/matcd?c /dev/mcd?c /dev/scd?c */
133 static char *checklist[] = {
134 "cdrom", "?0 cd?", "?0 acd?", "?0 matcd?", "?0 mcd?", "?0 scd?",NULL
135 };
136 char *SDLcdrom;
137 int i, j, exists;
138 char drive[32];
139 struct stat stbuf;
140
141 /* Fill in our driver capabilities */
142 SDL_CDcaps.Name = SDL_SYS_CDName;
143 SDL_CDcaps.Open = SDL_SYS_CDOpen;
144 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
145 SDL_CDcaps.Status = SDL_SYS_CDStatus;
146 SDL_CDcaps.Play = SDL_SYS_CDPlay;
147 SDL_CDcaps.Pause = SDL_SYS_CDPause;
148 SDL_CDcaps.Resume = SDL_SYS_CDResume;
149 SDL_CDcaps.Stop = SDL_SYS_CDStop;
150 SDL_CDcaps.Eject = SDL_SYS_CDEject;
151 SDL_CDcaps.Close = SDL_SYS_CDClose;
152
153 /* Look in the environment for our CD-ROM drive list */
154 SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */
155 if ( SDLcdrom != NULL ) {
156 char *cdpath, *delim;
157 size_t len = SDL_strlen(SDLcdrom)+1;
158 cdpath = SDL_stack_alloc(char, len);
159 if ( cdpath != NULL ) {
160 SDL_strlcpy(cdpath, SDLcdrom, len);
161 SDLcdrom = cdpath;
162 do {
163 delim = SDL_strchr(SDLcdrom, ':');
164 if ( delim ) {
165 *delim++ = '\0';
166 }
167 if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) {
168 AddDrive(SDLcdrom, &stbuf);
169 }
170 if ( delim ) {
171 SDLcdrom = delim;
172 } else {
173 SDLcdrom = NULL;
174 }
175 } while ( SDLcdrom );
176 SDL_stack_free(cdpath);
177 }
178
179 /* If we found our drives, there's nothing left to do */
180 if ( SDL_numcds > 0 ) {
181 return(0);
182 }
183 }
184
185 /* Scan the system for CD-ROM drives */
186 for ( i=0; checklist[i]; ++i ) {
187 if ( checklist[i][0] == '?' ) {
188 char *insert;
189 exists = 1;
190 for ( j=checklist[i][1]; exists; ++j ) {
191 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%sc", &checklist[i][3]);
192 insert = SDL_strchr(drive, '?');
193 if ( insert != NULL ) {
194 *insert = j;
195 }
196 switch (CheckDrive(drive, &stbuf)) {
197 /* Drive exists and is a CD-ROM */
198 case 1:
199 AddDrive(drive, &stbuf);
200 break;
201 /* Drive exists, but isn't a CD-ROM */
202 case 0:
203 break;
204 /* Drive doesn't exist */
205 case -1:
206 exists = 0;
207 break;
208 }
209 }
210 } else {
211 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]);
212 if ( CheckDrive(drive, &stbuf) > 0 ) {
213 AddDrive(drive, &stbuf);
214 }
215 }
216 }
217 return(0);
218}
219
220/* General ioctl() CD-ROM command function */
221static int SDL_SYS_CDioctl(int id, int command, void *arg)
222{
223 int retval;
224
225 retval = ioctl(id, command, arg);
226 if ( retval < 0 ) {
227 SDL_SetError("ioctl() error: %s", strerror(errno));
228 }
229 return(retval);
230}
231
232static const char *SDL_SYS_CDName(int drive)
233{
234 return(SDL_cdlist[drive]);
235}
236
237static int SDL_SYS_CDOpen(int drive)
238{
239 return(open(SDL_cdlist[drive], (O_RDONLY|O_EXCL|O_NONBLOCK), 0));
240}
241
242static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
243{
244 struct ioc_toc_header toc;
245 int i, okay;
246 struct ioc_read_toc_entry entry;
247 struct cd_toc_entry data;
248
249 okay = 0;
250 if ( SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCHEADER, &toc) == 0 ) {
251 cdrom->numtracks = toc.ending_track-toc.starting_track+1;
252 if ( cdrom->numtracks > SDL_MAX_TRACKS ) {
253 cdrom->numtracks = SDL_MAX_TRACKS;
254 }
255 /* Read all the track TOC entries */
256 for ( i=0; i<=cdrom->numtracks; ++i ) {
257 if ( i == cdrom->numtracks ) {
258 cdrom->track[i].id = 0xAA; /* CDROM_LEADOUT */
259 } else {
260 cdrom->track[i].id = toc.starting_track+i;
261 }
262 entry.starting_track = cdrom->track[i].id;
263 entry.address_format = CD_MSF_FORMAT;
264 entry.data_len = sizeof(data);
265 entry.data = &data;
266 if ( SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCENTRYS,
267 &entry) < 0 ) {
268 break;
269 } else {
270 cdrom->track[i].type = data.control;
271 cdrom->track[i].offset = MSF_TO_FRAMES(
272 data.addr.msf.minute,
273 data.addr.msf.second,
274 data.addr.msf.frame);
275 cdrom->track[i].length = 0;
276 if ( i > 0 ) {
277 cdrom->track[i-1].length =
278 cdrom->track[i].offset-
279 cdrom->track[i-1].offset;
280 }
281 }
282 }
283 if ( i == (cdrom->numtracks+1) ) {
284 okay = 1;
285 }
286 }
287 return(okay ? 0 : -1);
288}
289
290/* Get CD-ROM status */
291static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
292{
293 CDstatus status;
294 struct ioc_toc_header toc;
295 struct ioc_read_subchannel info;
296 struct cd_sub_channel_info data;
297
298 info.address_format = CD_MSF_FORMAT;
299 info.data_format = CD_CURRENT_POSITION;
300 info.track = 0;
301 info.data_len = sizeof(data);
302 info.data = &data;
303 if ( ioctl(cdrom->id, CDIOCREADSUBCHANNEL, &info) < 0 ) {
304 if ( ERRNO_TRAYEMPTY(errno) ) {
305 status = CD_TRAYEMPTY;
306 } else {
307 status = CD_ERROR;
308 }
309 } else {
310 switch (data.header.audio_status) {
311 case CD_AS_AUDIO_INVALID:
312 case CD_AS_NO_STATUS:
313 /* Try to determine if there's a CD available */
314 if (ioctl(cdrom->id,CDIOREADTOCHEADER,&toc)==0)
315 status = CD_STOPPED;
316 else
317 status = CD_TRAYEMPTY;
318 break;
319 case CD_AS_PLAY_COMPLETED:
320 status = CD_STOPPED;
321 break;
322 case CD_AS_PLAY_IN_PROGRESS:
323 status = CD_PLAYING;
324 break;
325 case CD_AS_PLAY_PAUSED:
326 status = CD_PAUSED;
327 break;
328 default:
329 status = CD_ERROR;
330 break;
331 }
332 }
333 if ( position ) {
334 if ( status == CD_PLAYING || (status == CD_PAUSED) ) {
335 *position = MSF_TO_FRAMES(
336 data.what.position.absaddr.msf.minute,
337 data.what.position.absaddr.msf.second,
338 data.what.position.absaddr.msf.frame);
339 } else {
340 *position = 0;
341 }
342 }
343 return(status);
344}
345
346/* Start play */
347static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
348{
349 struct ioc_play_msf playtime;
350
351 FRAMES_TO_MSF(start,
352 &playtime.start_m, &playtime.start_s, &playtime.start_f);
353 FRAMES_TO_MSF(start+length,
354 &playtime.end_m, &playtime.end_s, &playtime.end_f);
355#ifdef DEBUG_CDROM
356 fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n",
357 playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0,
358 playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1);
359#endif
360 ioctl(cdrom->id, CDIOCSTART, 0);
361 return(SDL_SYS_CDioctl(cdrom->id, CDIOCPLAYMSF, &playtime));
362}
363
364/* Pause play */
365static int SDL_SYS_CDPause(SDL_CD *cdrom)
366{
367 return(SDL_SYS_CDioctl(cdrom->id, CDIOCPAUSE, 0));
368}
369
370/* Resume play */
371static int SDL_SYS_CDResume(SDL_CD *cdrom)
372{
373 return(SDL_SYS_CDioctl(cdrom->id, CDIOCRESUME, 0));
374}
375
376/* Stop play */
377static int SDL_SYS_CDStop(SDL_CD *cdrom)
378{
379 return(SDL_SYS_CDioctl(cdrom->id, CDIOCSTOP, 0));
380}
381
382/* Eject the CD-ROM */
383static int SDL_SYS_CDEject(SDL_CD *cdrom)
384{
385 return(SDL_SYS_CDioctl(cdrom->id, CDIOCEJECT, 0));
386}
387
388/* Close the CD-ROM handle */
389static void SDL_SYS_CDClose(SDL_CD *cdrom)
390{
391 close(cdrom->id);
392}
393
394void SDL_SYS_CDQuit(void)
395{
396 int i;
397
398 if ( SDL_numcds > 0 ) {
399 for ( i=0; i<SDL_numcds; ++i ) {
400 SDL_free(SDL_cdlist[i]);
401 }
402 SDL_numcds = 0;
403 }
404}
405
406#endif /* SDL_CDROM_FREEBSD */
diff --git a/apps/plugins/sdl/src/cdrom/linux/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/linux/SDL_syscdrom.c
deleted file mode 100644
index 68040575b5..0000000000
--- a/apps/plugins/sdl/src/cdrom/linux/SDL_syscdrom.c
+++ /dev/null
@@ -1,564 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_LINUX
25
26/* Functions for system-level CD-ROM audio control */
27
28#include <string.h> /* For strerror() */
29#include <sys/types.h>
30#include <sys/stat.h>
31#include <sys/ioctl.h>
32#include <fcntl.h>
33#include <errno.h>
34#include <unistd.h>
35#ifdef __LINUX__
36#ifdef HAVE_LINUX_VERSION_H
37/* linux 2.6.9 workaround */
38#include <linux/version.h>
39#if LINUX_VERSION_CODE == KERNEL_VERSION(2,6,9)
40#include <asm/types.h>
41#define __le64 __u64
42#define __le32 __u32
43#define __le16 __u16
44#define __be64 __u64
45#define __be32 __u32
46#define __be16 __u16
47#endif /* linux 2.6.9 workaround */
48#endif /* HAVE_LINUX_VERSION_H */
49#include <linux/cdrom.h>
50#endif
51#ifdef __SVR4
52#include <sys/cdio.h>
53#endif
54
55/* Define this to use the alternative getmntent() code */
56#ifndef __SVR4
57#define USE_MNTENT
58#endif
59
60#ifdef USE_MNTENT
61#if defined(__USLC__)
62#include <sys/mntent.h>
63#else
64#include <mntent.h>
65#endif
66
67#ifndef _PATH_MNTTAB
68#ifdef MNTTAB
69#define _PATH_MNTTAB MNTTAB
70#else
71#define _PATH_MNTTAB "/etc/fstab"
72#endif
73#endif /* !_PATH_MNTTAB */
74
75#ifndef _PATH_MOUNTED
76#define _PATH_MOUNTED "/etc/mtab"
77#endif /* !_PATH_MOUNTED */
78
79#ifndef MNTTYPE_CDROM
80#define MNTTYPE_CDROM "iso9660"
81#endif
82#ifndef MNTTYPE_SUPER
83#define MNTTYPE_SUPER "supermount"
84#endif
85#endif /* USE_MNTENT */
86
87#include "SDL_cdrom.h"
88#include "../SDL_syscdrom.h"
89
90
91/* The maximum number of CD-ROM drives we'll detect */
92#define MAX_DRIVES 16
93
94/* A list of available CD-ROM drives */
95static char *SDL_cdlist[MAX_DRIVES];
96static dev_t SDL_cdmode[MAX_DRIVES];
97
98/* The system-dependent CD control functions */
99static const char *SDL_SYS_CDName(int drive);
100static int SDL_SYS_CDOpen(int drive);
101static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
102static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
103static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
104static int SDL_SYS_CDPause(SDL_CD *cdrom);
105static int SDL_SYS_CDResume(SDL_CD *cdrom);
106static int SDL_SYS_CDStop(SDL_CD *cdrom);
107static int SDL_SYS_CDEject(SDL_CD *cdrom);
108static void SDL_SYS_CDClose(SDL_CD *cdrom);
109
110/* Some ioctl() errno values which occur when the tray is empty */
111#ifndef ENOMEDIUM
112#define ENOMEDIUM ENOENT
113#endif
114#define ERRNO_TRAYEMPTY(errno) \
115 ((errno == EIO) || (errno == ENOENT) || \
116 (errno == EINVAL) || (errno == ENOMEDIUM))
117
118/* Check a drive to see if it is a CD-ROM */
119static int CheckDrive(char *drive, char *mnttype, struct stat *stbuf)
120{
121 int is_cd, cdfd;
122 struct cdrom_subchnl info;
123
124 /* If it doesn't exist, return -1 */
125 if ( stat(drive, stbuf) < 0 ) {
126 return(-1);
127 }
128
129 /* If it does exist, verify that it's an available CD-ROM */
130 is_cd = 0;
131 if ( S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode) ) {
132 cdfd = open(drive, (O_RDONLY|O_NONBLOCK), 0);
133 if ( cdfd >= 0 ) {
134 info.cdsc_format = CDROM_MSF;
135 /* Under Linux, EIO occurs when a disk is not present.
136 */
137 if ( (ioctl(cdfd, CDROMSUBCHNL, &info) == 0) ||
138 ERRNO_TRAYEMPTY(errno) ) {
139 is_cd = 1;
140 }
141 close(cdfd);
142 }
143#ifdef USE_MNTENT
144 /* Even if we can't read it, it might be mounted */
145 else if ( mnttype && (SDL_strcmp(mnttype, MNTTYPE_CDROM) == 0) ) {
146 is_cd = 1;
147 }
148#endif
149 }
150 return(is_cd);
151}
152
153/* Add a CD-ROM drive to our list of valid drives */
154static void AddDrive(char *drive, struct stat *stbuf)
155{
156 int i;
157
158 if ( SDL_numcds < MAX_DRIVES ) {
159 /* Check to make sure it's not already in our list.
160 This can happen when we see a drive via symbolic link.
161 */
162 for ( i=0; i<SDL_numcds; ++i ) {
163 if ( stbuf->st_rdev == SDL_cdmode[i] ) {
164#ifdef DEBUG_CDROM
165 fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]);
166#endif
167 return;
168 }
169 }
170
171 /* Add this drive to our list */
172 i = SDL_numcds;
173 SDL_cdlist[i] = SDL_strdup(drive);
174 if ( SDL_cdlist[i] == NULL ) {
175 SDL_OutOfMemory();
176 return;
177 }
178 SDL_cdmode[i] = stbuf->st_rdev;
179 ++SDL_numcds;
180#ifdef DEBUG_CDROM
181 fprintf(stderr, "Added CD-ROM drive: %s\n", drive);
182#endif
183 }
184}
185
186#ifdef USE_MNTENT
187static void CheckMounts(const char *mtab)
188{
189 FILE *mntfp;
190 struct mntent *mntent;
191 struct stat stbuf;
192
193 mntfp = setmntent(mtab, "r");
194 if ( mntfp != NULL ) {
195 char *tmp;
196 char *mnt_type;
197 size_t mnt_type_len;
198 char *mnt_dev;
199 size_t mnt_dev_len;
200
201 while ( (mntent=getmntent(mntfp)) != NULL ) {
202 mnt_type_len = SDL_strlen(mntent->mnt_type) + 1;
203 mnt_type = SDL_stack_alloc(char, mnt_type_len);
204 if (mnt_type == NULL)
205 continue; /* maybe you'll get lucky next time. */
206
207 mnt_dev_len = SDL_strlen(mntent->mnt_fsname) + 1;
208 mnt_dev = SDL_stack_alloc(char, mnt_dev_len);
209 if (mnt_dev == NULL) {
210 SDL_stack_free(mnt_type);
211 continue;
212 }
213
214 SDL_strlcpy(mnt_type, mntent->mnt_type, mnt_type_len);
215 SDL_strlcpy(mnt_dev, mntent->mnt_fsname, mnt_dev_len);
216
217 /* Handle "supermount" filesystem mounts */
218 if ( SDL_strcmp(mnt_type, MNTTYPE_SUPER) == 0 ) {
219 tmp = SDL_strstr(mntent->mnt_opts, "fs=");
220 if ( tmp ) {
221 SDL_stack_free(mnt_type);
222 mnt_type = SDL_strdup(tmp + SDL_strlen("fs="));
223 if ( mnt_type ) {
224 tmp = SDL_strchr(mnt_type, ',');
225 if ( tmp ) {
226 *tmp = '\0';
227 }
228 }
229 }
230 tmp = SDL_strstr(mntent->mnt_opts, "dev=");
231 if ( tmp ) {
232 SDL_stack_free(mnt_dev);
233 mnt_dev = SDL_strdup(tmp + SDL_strlen("dev="));
234 if ( mnt_dev ) {
235 tmp = SDL_strchr(mnt_dev, ',');
236 if ( tmp ) {
237 *tmp = '\0';
238 }
239 }
240 }
241 }
242 if ( SDL_strcmp(mnt_type, MNTTYPE_CDROM) == 0 ) {
243#ifdef DEBUG_CDROM
244 fprintf(stderr, "Checking mount path from %s: %s mounted on %s of %s\n",
245 mtab, mnt_dev, mntent->mnt_dir, mnt_type);
246#endif
247 if (CheckDrive(mnt_dev, mnt_type, &stbuf) > 0) {
248 AddDrive(mnt_dev, &stbuf);
249 }
250 }
251 SDL_stack_free(mnt_dev);
252 SDL_stack_free(mnt_type);
253 }
254 endmntent(mntfp);
255 }
256}
257#endif /* USE_MNTENT */
258
259int SDL_SYS_CDInit(void)
260{
261 /* checklist: /dev/cdrom, /dev/hd?, /dev/scd? /dev/sr? */
262 static char *checklist[] = {
263 "cdrom", "?a hd?", "?0 scd?", "?0 sr?", NULL
264 };
265 char *SDLcdrom;
266 int i, j, exists;
267 char drive[32];
268 struct stat stbuf;
269
270 /* Fill in our driver capabilities */
271 SDL_CDcaps.Name = SDL_SYS_CDName;
272 SDL_CDcaps.Open = SDL_SYS_CDOpen;
273 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
274 SDL_CDcaps.Status = SDL_SYS_CDStatus;
275 SDL_CDcaps.Play = SDL_SYS_CDPlay;
276 SDL_CDcaps.Pause = SDL_SYS_CDPause;
277 SDL_CDcaps.Resume = SDL_SYS_CDResume;
278 SDL_CDcaps.Stop = SDL_SYS_CDStop;
279 SDL_CDcaps.Eject = SDL_SYS_CDEject;
280 SDL_CDcaps.Close = SDL_SYS_CDClose;
281
282 /* Look in the environment for our CD-ROM drive list */
283 SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */
284 if ( SDLcdrom != NULL ) {
285 char *cdpath, *delim;
286 size_t len = SDL_strlen(SDLcdrom)+1;
287 cdpath = SDL_stack_alloc(char, len);
288 if ( cdpath != NULL ) {
289 SDL_strlcpy(cdpath, SDLcdrom, len);
290 SDLcdrom = cdpath;
291 do {
292 delim = SDL_strchr(SDLcdrom, ':');
293 if ( delim ) {
294 *delim++ = '\0';
295 }
296#ifdef DEBUG_CDROM
297 fprintf(stderr, "Checking CD-ROM drive from SDL_CDROM: %s\n", SDLcdrom);
298#endif
299 if ( CheckDrive(SDLcdrom, NULL, &stbuf) > 0 ) {
300 AddDrive(SDLcdrom, &stbuf);
301 }
302 if ( delim ) {
303 SDLcdrom = delim;
304 } else {
305 SDLcdrom = NULL;
306 }
307 } while ( SDLcdrom );
308 SDL_stack_free(cdpath);
309 }
310
311 /* If we found our drives, there's nothing left to do */
312 if ( SDL_numcds > 0 ) {
313 return(0);
314 }
315 }
316
317#ifdef USE_MNTENT
318 /* Check /dev/cdrom first :-) */
319 if (CheckDrive("/dev/cdrom", NULL, &stbuf) > 0) {
320 AddDrive("/dev/cdrom", &stbuf);
321 }
322
323 /* Now check the currently mounted CD drives */
324 CheckMounts(_PATH_MOUNTED);
325
326 /* Finally check possible mountable drives in /etc/fstab */
327 CheckMounts(_PATH_MNTTAB);
328
329 /* If we found our drives, there's nothing left to do */
330 if ( SDL_numcds > 0 ) {
331 return(0);
332 }
333#endif /* USE_MNTENT */
334
335 /* Scan the system for CD-ROM drives.
336 Not always 100% reliable, so use the USE_MNTENT code above first.
337 */
338 for ( i=0; checklist[i]; ++i ) {
339 if ( checklist[i][0] == '?' ) {
340 char *insert;
341 exists = 1;
342 for ( j=checklist[i][1]; exists; ++j ) {
343 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", &checklist[i][3]);
344 insert = SDL_strchr(drive, '?');
345 if ( insert != NULL ) {
346 *insert = j;
347 }
348#ifdef DEBUG_CDROM
349 fprintf(stderr, "Checking possible CD-ROM drive: %s\n", drive);
350#endif
351 switch (CheckDrive(drive, NULL, &stbuf)) {
352 /* Drive exists and is a CD-ROM */
353 case 1:
354 AddDrive(drive, &stbuf);
355 break;
356 /* Drive exists, but isn't a CD-ROM */
357 case 0:
358 break;
359 /* Drive doesn't exist */
360 case -1:
361 exists = 0;
362 break;
363 }
364 }
365 } else {
366 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]);
367#ifdef DEBUG_CDROM
368 fprintf(stderr, "Checking possible CD-ROM drive: %s\n", drive);
369#endif
370 if ( CheckDrive(drive, NULL, &stbuf) > 0 ) {
371 AddDrive(drive, &stbuf);
372 }
373 }
374 }
375 return(0);
376}
377
378/* General ioctl() CD-ROM command function */
379static int SDL_SYS_CDioctl(int id, int command, void *arg)
380{
381 int retval;
382
383 retval = ioctl(id, command, arg);
384 if ( retval < 0 ) {
385 SDL_SetError("ioctl() error: %s", strerror(errno));
386 }
387 return(retval);
388}
389
390static const char *SDL_SYS_CDName(int drive)
391{
392 return(SDL_cdlist[drive]);
393}
394
395static int SDL_SYS_CDOpen(int drive)
396{
397 return(open(SDL_cdlist[drive], (O_RDONLY|O_NONBLOCK), 0));
398}
399
400static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
401{
402 struct cdrom_tochdr toc;
403 int i, okay;
404 struct cdrom_tocentry entry;
405
406 okay = 0;
407 if ( SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCHDR, &toc) == 0 ) {
408 cdrom->numtracks = toc.cdth_trk1-toc.cdth_trk0+1;
409 if ( cdrom->numtracks > SDL_MAX_TRACKS ) {
410 cdrom->numtracks = SDL_MAX_TRACKS;
411 }
412 /* Read all the track TOC entries */
413 for ( i=0; i<=cdrom->numtracks; ++i ) {
414 if ( i == cdrom->numtracks ) {
415 cdrom->track[i].id = CDROM_LEADOUT;
416 } else {
417 cdrom->track[i].id = toc.cdth_trk0+i;
418 }
419 entry.cdte_track = cdrom->track[i].id;
420 entry.cdte_format = CDROM_MSF;
421 if ( SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCENTRY,
422 &entry) < 0 ) {
423 break;
424 } else {
425 if ( entry.cdte_ctrl & CDROM_DATA_TRACK ) {
426 cdrom->track[i].type = SDL_DATA_TRACK;
427 } else {
428 cdrom->track[i].type = SDL_AUDIO_TRACK;
429 }
430 cdrom->track[i].offset = MSF_TO_FRAMES(
431 entry.cdte_addr.msf.minute,
432 entry.cdte_addr.msf.second,
433 entry.cdte_addr.msf.frame);
434 cdrom->track[i].length = 0;
435 if ( i > 0 ) {
436 cdrom->track[i-1].length =
437 cdrom->track[i].offset-
438 cdrom->track[i-1].offset;
439 }
440 }
441 }
442 if ( i == (cdrom->numtracks+1) ) {
443 okay = 1;
444 }
445 }
446 return(okay ? 0 : -1);
447}
448
449/* Get CD-ROM status */
450static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
451{
452 CDstatus status;
453 struct cdrom_tochdr toc;
454 struct cdrom_subchnl info;
455
456 info.cdsc_format = CDROM_MSF;
457 if ( ioctl(cdrom->id, CDROMSUBCHNL, &info) < 0 ) {
458 if ( ERRNO_TRAYEMPTY(errno) ) {
459 status = CD_TRAYEMPTY;
460 } else {
461 status = CD_ERROR;
462 }
463 } else {
464 switch (info.cdsc_audiostatus) {
465 case CDROM_AUDIO_INVALID:
466 case CDROM_AUDIO_NO_STATUS:
467 /* Try to determine if there's a CD available */
468 if (ioctl(cdrom->id, CDROMREADTOCHDR, &toc)==0)
469 status = CD_STOPPED;
470 else
471 status = CD_TRAYEMPTY;
472 break;
473 case CDROM_AUDIO_COMPLETED:
474 status = CD_STOPPED;
475 break;
476 case CDROM_AUDIO_PLAY:
477 status = CD_PLAYING;
478 break;
479 case CDROM_AUDIO_PAUSED:
480 /* Workaround buggy CD-ROM drive */
481 if ( info.cdsc_trk == CDROM_LEADOUT ) {
482 status = CD_STOPPED;
483 } else {
484 status = CD_PAUSED;
485 }
486 break;
487 default:
488 status = CD_ERROR;
489 break;
490 }
491 }
492 if ( position ) {
493 if ( status == CD_PLAYING || (status == CD_PAUSED) ) {
494 *position = MSF_TO_FRAMES(
495 info.cdsc_absaddr.msf.minute,
496 info.cdsc_absaddr.msf.second,
497 info.cdsc_absaddr.msf.frame);
498 } else {
499 *position = 0;
500 }
501 }
502 return(status);
503}
504
505/* Start play */
506static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
507{
508 struct cdrom_msf playtime;
509
510 FRAMES_TO_MSF(start,
511 &playtime.cdmsf_min0, &playtime.cdmsf_sec0, &playtime.cdmsf_frame0);
512 FRAMES_TO_MSF(start+length,
513 &playtime.cdmsf_min1, &playtime.cdmsf_sec1, &playtime.cdmsf_frame1);
514#ifdef DEBUG_CDROM
515 fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n",
516 playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0,
517 playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1);
518#endif
519 return(SDL_SYS_CDioctl(cdrom->id, CDROMPLAYMSF, &playtime));
520}
521
522/* Pause play */
523static int SDL_SYS_CDPause(SDL_CD *cdrom)
524{
525 return(SDL_SYS_CDioctl(cdrom->id, CDROMPAUSE, 0));
526}
527
528/* Resume play */
529static int SDL_SYS_CDResume(SDL_CD *cdrom)
530{
531 return(SDL_SYS_CDioctl(cdrom->id, CDROMRESUME, 0));
532}
533
534/* Stop play */
535static int SDL_SYS_CDStop(SDL_CD *cdrom)
536{
537 return(SDL_SYS_CDioctl(cdrom->id, CDROMSTOP, 0));
538}
539
540/* Eject the CD-ROM */
541static int SDL_SYS_CDEject(SDL_CD *cdrom)
542{
543 return(SDL_SYS_CDioctl(cdrom->id, CDROMEJECT, 0));
544}
545
546/* Close the CD-ROM handle */
547static void SDL_SYS_CDClose(SDL_CD *cdrom)
548{
549 close(cdrom->id);
550}
551
552void SDL_SYS_CDQuit(void)
553{
554 int i;
555
556 if ( SDL_numcds > 0 ) {
557 for ( i=0; i<SDL_numcds; ++i ) {
558 SDL_free(SDL_cdlist[i]);
559 }
560 SDL_numcds = 0;
561 }
562}
563
564#endif /* SDL_CDROM_LINUX */
diff --git a/apps/plugins/sdl/src/cdrom/macos/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/macos/SDL_syscdrom.c
deleted file mode 100644
index 10a202544e..0000000000
--- a/apps/plugins/sdl/src/cdrom/macos/SDL_syscdrom.c
+++ /dev/null
@@ -1,525 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_MACOS
25
26/* MacOS functions for system-level CD-ROM audio control */
27
28#include <Devices.h>
29#include <Files.h>
30#include <LowMem.h> /* Use entry table macros, not functions in InterfaceLib */
31
32#include "SDL_cdrom.h"
33#include "../SDL_syscdrom.h"
34#include "SDL_syscdrom_c.h"
35
36/* Added by Matt Slot */
37#if !defined(LMGetUnitTableEntryCount)
38 #define LMGetUnitTableEntryCount() *(short *)0x01D2
39#endif
40
41/* The maximum number of CD-ROM drives we'll detect */
42#define MAX_DRIVES 26
43
44/* A list of available CD-ROM drives */
45static long SDL_cdversion = 0;
46static struct {
47 short dRefNum;
48 short driveNum;
49 long frames;
50 char name[256];
51 Boolean hasAudio;
52 } SDL_cdlist[MAX_DRIVES];
53static StringPtr gDriverName = "\p.AppleCD";
54
55/* The system-dependent CD control functions */
56static const char *SDL_SYS_CDName(int drive);
57static int SDL_SYS_CDOpen(int drive);
58static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
59static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
60static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
61static int SDL_SYS_CDPause(SDL_CD *cdrom);
62static int SDL_SYS_CDResume(SDL_CD *cdrom);
63static int SDL_SYS_CDStop(SDL_CD *cdrom);
64static int SDL_SYS_CDEject(SDL_CD *cdrom);
65static void SDL_SYS_CDClose(SDL_CD *cdrom);
66
67static short SDL_SYS_ShortToBCD(short value)
68{
69 return((value % 10) + (value / 10) * 0x10); /* Convert value to BCD */
70}
71
72static short SDL_SYS_BCDToShort(short value)
73{
74 return((value % 0x10) + (value / 0x10) * 10); /* Convert value from BCD */
75}
76
77int SDL_SYS_CDInit(void)
78{
79 SInt16 dRefNum = 0;
80 SInt16 first, last;
81
82 SDL_numcds = 0;
83
84 /* Check that the software is available */
85 if (Gestalt(kGestaltAudioCDSelector, &SDL_cdversion) ||
86 !SDL_cdversion) return(0);
87
88 /* Fill in our driver capabilities */
89 SDL_CDcaps.Name = SDL_SYS_CDName;
90 SDL_CDcaps.Open = SDL_SYS_CDOpen;
91 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
92 SDL_CDcaps.Status = SDL_SYS_CDStatus;
93 SDL_CDcaps.Play = SDL_SYS_CDPlay;
94 SDL_CDcaps.Pause = SDL_SYS_CDPause;
95 SDL_CDcaps.Resume = SDL_SYS_CDResume;
96 SDL_CDcaps.Stop = SDL_SYS_CDStop;
97 SDL_CDcaps.Eject = SDL_SYS_CDEject;
98 SDL_CDcaps.Close = SDL_SYS_CDClose;
99
100 /* Walk the list, count each AudioCD driver, and save the refnums */
101 first = -1;
102 last = 0 - LMGetUnitTableEntryCount();
103 for(dRefNum = first; dRefNum >= last; dRefNum--) {
104 Str255 driverName;
105 StringPtr namePtr;
106 DCtlHandle deviceEntry;
107
108 deviceEntry = GetDCtlEntry(dRefNum);
109 if (! deviceEntry) continue;
110
111 /* Is this an .AppleCD ? */
112 namePtr = (*deviceEntry)->dCtlFlags & (1L << dRAMBased) ?
113 ((StringPtr) ((DCtlPtr) deviceEntry)->dCtlDriver + 18) :
114 ((StringPtr) (*deviceEntry)->dCtlDriver + 18);
115 BlockMoveData(namePtr, driverName, namePtr[0]+1);
116 if (driverName[0] > gDriverName[0]) driverName[0] = gDriverName[0];
117 if (! EqualString(driverName, gDriverName, false, false)) continue;
118
119 /* Record the basic info for each drive */
120 SDL_cdlist[SDL_numcds].dRefNum = dRefNum;
121 BlockMoveData(namePtr + 1, SDL_cdlist[SDL_numcds].name, namePtr[0]);
122 SDL_cdlist[SDL_numcds].name[namePtr[0]] = 0;
123 SDL_cdlist[SDL_numcds].hasAudio = false;
124 SDL_numcds++;
125 }
126 return(0);
127}
128
129static const char *SDL_SYS_CDName(int drive)
130{
131 return(SDL_cdlist[drive].name);
132}
133
134static int get_drivenum(int drive)
135{
136 QHdr *driveQ = GetDrvQHdr();
137 DrvQEl *driveElem;
138
139 /* Update the drive number */
140 SDL_cdlist[drive].driveNum = 0;
141 if ( driveQ->qTail ) {
142 driveQ->qTail->qLink = 0;
143 }
144 for ( driveElem=(DrvQEl *)driveQ->qHead; driveElem;
145 driveElem = (DrvQEl *)driveElem->qLink ) {
146 if ( driveElem->dQRefNum == SDL_cdlist[drive].dRefNum ) {
147 SDL_cdlist[drive].driveNum = driveElem->dQDrive;
148 break;
149 }
150 }
151 return(SDL_cdlist[drive].driveNum);
152}
153
154static int SDL_SYS_CDOpen(int drive)
155{
156 return(drive);
157}
158
159static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
160{
161 CDCntrlParam cdpb;
162 CDTrackData tracks[SDL_MAX_TRACKS];
163 long i, leadout;
164
165 /* Get the number of tracks on the CD by examining the TOC */
166 SDL_memset(&cdpb, 0, sizeof(cdpb));
167 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
168 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
169 cdpb.csCode = kReadTOC;
170 cdpb.csParam.words[0] = kGetTrackRange;
171 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
172 SDL_SetError("PBControlSync() failed");
173 return(-1);
174 }
175
176 cdrom->numtracks =
177 SDL_SYS_BCDToShort(cdpb.csParam.bytes[1]) -
178 SDL_SYS_BCDToShort(cdpb.csParam.bytes[0]) + 1;
179 if ( cdrom->numtracks > SDL_MAX_TRACKS )
180 cdrom->numtracks = SDL_MAX_TRACKS;
181 cdrom->status = CD_STOPPED;
182 cdrom->cur_track = 0; /* Apparently these are set elsewhere */
183 cdrom->cur_frame = 0; /* Apparently these are set elsewhere */
184
185
186 /* Get the lead out area of the CD by examining the TOC */
187 SDL_memset(&cdpb, 0, sizeof(cdpb));
188 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
189 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
190 cdpb.csCode = kReadTOC;
191 cdpb.csParam.words[0] = kGetLeadOutArea;
192 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
193 SDL_SetError("PBControlSync() failed");
194 return(-1);
195 }
196
197 leadout = MSF_TO_FRAMES(
198 SDL_SYS_BCDToShort(cdpb.csParam.bytes[0]),
199 SDL_SYS_BCDToShort(cdpb.csParam.bytes[1]),
200 SDL_SYS_BCDToShort(cdpb.csParam.bytes[2]));
201
202 /* Get an array of track locations by examining the TOC */
203 SDL_memset(tracks, 0, sizeof(tracks));
204 SDL_memset(&cdpb, 0, sizeof(cdpb));
205 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
206 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
207 cdpb.csCode = kReadTOC;
208 cdpb.csParam.words[0] = kGetTrackEntries; /* Type of Query */
209 * ((long *) (cdpb.csParam.words+1)) = (long) tracks;
210 cdpb.csParam.words[3] = cdrom->numtracks * sizeof(tracks[0]);
211 * ((char *) (cdpb.csParam.words+4)) = 1; /* First track */
212 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
213 SDL_SetError("PBControlSync() failed");
214 return(-1);
215 }
216
217 /* Read all the track TOC entries */
218 SDL_cdlist[cdrom->id].hasAudio = false;
219 for ( i=0; i<cdrom->numtracks; ++i )
220 {
221 cdrom->track[i].id = i+1;
222 if (tracks[i].entry.control & kDataTrackMask)
223 cdrom->track[i].type = SDL_DATA_TRACK;
224 else
225 {
226 cdrom->track[i].type = SDL_AUDIO_TRACK;
227 SDL_cdlist[SDL_numcds].hasAudio = true;
228 }
229
230 cdrom->track[i].offset = MSF_TO_FRAMES(
231 SDL_SYS_BCDToShort(tracks[i].entry.min),
232 SDL_SYS_BCDToShort(tracks[i].entry.min),
233 SDL_SYS_BCDToShort(tracks[i].entry.frame));
234 cdrom->track[i].length = MSF_TO_FRAMES(
235 SDL_SYS_BCDToShort(tracks[i+1].entry.min),
236 SDL_SYS_BCDToShort(tracks[i+1].entry.min),
237 SDL_SYS_BCDToShort(tracks[i+1].entry.frame)) -
238 cdrom->track[i].offset;
239 }
240
241 /* Apparently SDL wants a fake last entry */
242 cdrom->track[i].offset = leadout;
243 cdrom->track[i].length = 0;
244
245 return(0);
246}
247
248/* Get CD-ROM status */
249static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
250{
251 CDCntrlParam cdpb;
252 CDstatus status = CD_ERROR;
253 Boolean spinning = false;
254
255 if (position) *position = 0;
256
257 /* Get the number of tracks on the CD by examining the TOC */
258 if ( ! get_drivenum(cdrom->id) ) {
259 return(CD_TRAYEMPTY);
260 }
261 SDL_memset(&cdpb, 0, sizeof(cdpb));
262 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
263 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
264 cdpb.csCode = kReadTOC;
265 cdpb.csParam.words[0] = kGetTrackRange;
266 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
267 SDL_SetError("PBControlSync() failed");
268 return(CD_ERROR);
269 }
270
271 cdrom->numtracks =
272 SDL_SYS_BCDToShort(cdpb.csParam.bytes[1]) -
273 SDL_SYS_BCDToShort(cdpb.csParam.bytes[0]) + 1;
274 if ( cdrom->numtracks > SDL_MAX_TRACKS )
275 cdrom->numtracks = SDL_MAX_TRACKS;
276 cdrom->cur_track = 0; /* Apparently these are set elsewhere */
277 cdrom->cur_frame = 0; /* Apparently these are set elsewhere */
278
279
280 if (1 || SDL_cdlist[cdrom->id].hasAudio) {
281 /* Get the current playback status */
282 SDL_memset(&cdpb, 0, sizeof(cdpb));
283 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
284 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
285 cdpb.csCode = kAudioStatus;
286 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
287 SDL_SetError("PBControlSync() failed");
288 return(-1);
289 }
290
291 switch(cdpb.csParam.cd.status) {
292 case kStatusPlaying:
293 status = CD_PLAYING;
294 spinning = true;
295 break;
296 case kStatusPaused:
297 status = CD_PAUSED;
298 spinning = true;
299 break;
300 case kStatusMuted:
301 status = CD_PLAYING; /* What should I do here? */
302 spinning = true;
303 break;
304 case kStatusDone:
305 status = CD_STOPPED;
306 spinning = true;
307 break;
308 case kStatusStopped:
309 status = CD_STOPPED;
310 spinning = false;
311 break;
312 case kStatusError:
313 default:
314 status = CD_ERROR;
315 spinning = false;
316 break;
317 }
318
319 if (spinning && position) *position = MSF_TO_FRAMES(
320 SDL_SYS_BCDToShort(cdpb.csParam.cd.minute),
321 SDL_SYS_BCDToShort(cdpb.csParam.cd.second),
322 SDL_SYS_BCDToShort(cdpb.csParam.cd.frame));
323 }
324 else
325 status = CD_ERROR; /* What should I do here? */
326
327 return(status);
328}
329
330/* Start play */
331static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
332{
333 CDCntrlParam cdpb;
334
335 /* Pause the current audio playback to avoid audible artifacts */
336 if ( SDL_SYS_CDPause(cdrom) < 0 ) {
337 return(-1);
338 }
339
340 /* Specify the AudioCD playback mode */
341 SDL_memset(&cdpb, 0, sizeof(cdpb));
342 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
343 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
344 cdpb.csCode = kSetPlayMode;
345 cdpb.csParam.bytes[0] = false; /* Repeat? */
346 cdpb.csParam.bytes[1] = kPlayModeSequential; /* Play mode */
347 /* ¥¥¥ÊTreat as soft error, NEC Drive doesnt support this call ¥¥¥ */
348 PBControlSync((ParmBlkPtr) &cdpb);
349
350#if 1
351 /* Specify the end of audio playback */
352 SDL_memset(&cdpb, 0, sizeof(cdpb));
353 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
354 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
355 cdpb.csCode = kAudioStop;
356 cdpb.csParam.words[0] = kBlockPosition; /* Position Mode */
357 *(long *) (cdpb.csParam.words + 1) = start+length-1; /* Search Address */
358 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
359 SDL_SetError("PBControlSync() failed");
360 return(-1);
361 }
362
363 /* Specify the start of audio playback, and start it */
364 SDL_memset(&cdpb, 0, sizeof(cdpb));
365 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
366 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
367 cdpb.csCode = kAudioPlay;
368 cdpb.csParam.words[0] = kBlockPosition; /* Position Mode */
369 *(long *) (cdpb.csParam.words + 1) = start+1; /* Search Address */
370 cdpb.csParam.words[3] = false; /* Stop address? */
371 cdpb.csParam.words[4] = kStereoPlayMode; /* Audio Play Mode */
372 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
373 SDL_SetError("PBControlSync() failed");
374 return(-1);
375 }
376#else
377 /* Specify the end of audio playback */
378 FRAMES_TO_MSF(start+length, &m, &s, &f);
379 SDL_memset(&cdpb, 0, sizeof(cdpb));
380 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
381 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
382 cdpb.csCode = kAudioStop;
383 cdpb.csParam.words[0] = kTrackPosition; /* Position Mode */
384 cdpb.csParam.words[1] = 0; /* Search Address (hiword)*/
385 cdpb.csParam.words[2] = /* Search Address (loword)*/
386 SDL_SYS_ShortToBCD(cdrom->numtracks);
387 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
388 SDL_SetError("PBControlSync() failed");
389 return(-1);
390 }
391
392 /* Specify the start of audio playback, and start it */
393 FRAMES_TO_MSF(start, &m, &s, &f);
394 SDL_memset(&cdpb, 0, sizeof(cdpb));
395 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
396 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
397 cdpb.csCode = kAudioPlay;
398 cdpb.csParam.words[0] = kTrackPosition; /* Position Mode */
399 cdpb.csParam.words[1] = 0; /* Search Address (hiword)*/
400 cdpb.csParam.words[2] = SDL_SYS_ShortToBCD(1); /* Search Address (loword)*/
401 cdpb.csParam.words[3] = false; /* Stop address? */
402 cdpb.csParam.words[4] = kStereoPlayMode; /* Audio Play Mode */
403 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
404 SDL_SetError("PBControlSync() failed");
405 return(-1);
406 }
407#endif
408
409 return(0);
410}
411
412/* Pause play */
413static int SDL_SYS_CDPause(SDL_CD *cdrom)
414{
415 CDCntrlParam cdpb;
416
417 SDL_memset(&cdpb, 0, sizeof(cdpb));
418 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
419 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
420 cdpb.csCode = kAudioPause;
421 cdpb.csParam.words[0] = 0; /* Pause/Continue Flag (hiword) */
422 cdpb.csParam.words[1] = 1; /* Pause/Continue Flag (loword) */
423 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
424 SDL_SetError("PBControlSync() failed");
425 return(-1);
426 }
427 return(0);
428}
429
430/* Resume play */
431static int SDL_SYS_CDResume(SDL_CD *cdrom)
432{
433 CDCntrlParam cdpb;
434
435 SDL_memset(&cdpb, 0, sizeof(cdpb));
436 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
437 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
438 cdpb.csCode = kAudioPause;
439 cdpb.csParam.words[0] = 0; /* Pause/Continue Flag (hiword) */
440 cdpb.csParam.words[1] = 0; /* Pause/Continue Flag (loword) */
441 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
442 SDL_SetError("PBControlSync() failed");
443 return(-1);
444 }
445 return(0);
446}
447
448/* Stop play */
449static int SDL_SYS_CDStop(SDL_CD *cdrom)
450{
451 CDCntrlParam cdpb;
452
453 SDL_memset(&cdpb, 0, sizeof(cdpb));
454 cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum;
455 cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
456 cdpb.csCode = kAudioStop;
457 cdpb.csParam.words[0] = 0; /* Position Mode */
458 cdpb.csParam.words[1] = 0; /* Search Address (hiword) */
459 cdpb.csParam.words[2] = 0; /* Search Address (loword) */
460 if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) {
461 SDL_SetError("PBControlSync() failed");
462 return(-1);
463 }
464 return(0);
465}
466
467/* Eject the CD-ROM */
468static int SDL_SYS_CDEject(SDL_CD *cdrom)
469{
470 Boolean disk = false;
471 QHdr *driveQ = GetDrvQHdr();
472 DrvQEl *driveElem;
473 HParamBlockRec hpb;
474 ParamBlockRec cpb;
475
476 for ( driveElem = (DrvQEl *) driveQ->qHead; driveElem; driveElem =
477 (driveElem) ? ((DrvQEl *) driveElem->qLink) :
478 ((DrvQEl *) driveQ->qHead) ) {
479 if ( driveQ->qTail ) {
480 driveQ->qTail->qLink = 0;
481 }
482 if ( driveElem->dQRefNum != SDL_cdlist[cdrom->id].dRefNum ) {
483 continue;
484 }
485
486 /* Does drive contain mounted volume? If not, skip */
487 SDL_memset(&hpb, 0, sizeof(hpb));
488 hpb.volumeParam.ioVRefNum = driveElem->dQDrive;
489 if ( PBHGetVInfoSync(&hpb) != noErr ) {
490 continue;
491 }
492 if ( (UnmountVol(0, driveElem->dQDrive) == noErr) &&
493 (Eject(0, driveElem->dQDrive) == noErr) ) {
494 driveElem = 0; /* Clear pointer to reset our loop */
495 disk = true;
496 }
497 }
498
499 /* If no disk is present, just eject the tray */
500 if (! disk) {
501 SDL_memset(&cpb, 0, sizeof(cpb));
502 cpb.cntrlParam.ioVRefNum = 0; /* No Drive */
503 cpb.cntrlParam.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum;
504 cpb.cntrlParam.csCode = kEjectTheDisc;
505 if ( PBControlSync((ParmBlkPtr)&cpb) != noErr ) {
506 SDL_SetError("PBControlSync() failed");
507 return(-1);
508 }
509 }
510 return(0);
511}
512
513/* Close the CD-ROM handle */
514static void SDL_SYS_CDClose(SDL_CD *cdrom)
515{
516 return;
517}
518
519void SDL_SYS_CDQuit(void)
520{
521 while(SDL_numcds--)
522 SDL_memset(SDL_cdlist + SDL_numcds, 0, sizeof(SDL_cdlist[0]));
523}
524
525#endif /* SDL_CDROM_MACOS */
diff --git a/apps/plugins/sdl/src/cdrom/macos/SDL_syscdrom_c.h b/apps/plugins/sdl/src/cdrom/macos/SDL_syscdrom_c.h
deleted file mode 100644
index e715a256d1..0000000000
--- a/apps/plugins/sdl/src/cdrom/macos/SDL_syscdrom_c.h
+++ /dev/null
@@ -1,140 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the MacOS specific header for the SDL CD-ROM API
25 Contributed by Matt Slot
26 */
27
28/* AppleCD Control calls */
29#define kVerifyTheDisc 5 /* Returns noErr if there is disc inserted */
30#define kEjectTheDisc 7 /* Eject disc from drive */
31#define kUserEject 80 /* Enable/disable the CD-ROM eject button */
32#define kReadTOC 100 /* Extract various TOC information from the disc */
33#define kReadQ 101 /* Extract Q subcode info for the current track */
34#define kAudioTrackSearch 103 /* Start playback from the indicated position */
35#define kAudioPlay 104 /* Start playback from the indicated position */
36#define kAudioPause 105 /* Pause/continue the playback */
37#define kAudioStop 106 /* Stop playback at the indicated position */
38#define kAudioStatus 107 /* Return audio play status */
39#define kAudioControl 109 /* Set the output volume for the audio channels */
40#define kReadAudioVolume 112 /* Get the output volume for the audio channels */
41#define kSetTrackList 122 /* Set the track program for the audio CD to play */
42#define kGetTrackList 123 /* Get the track program the audio CD is playing */
43#define kGetTrackIndex 124 /* Get the track index the audio CD is playing */
44#define kSetPlayMode 125 /* Set the audio tracks play mode */
45#define kGetPlayMode 126 /* Get the audio tracks play mode */
46
47/* AppleCD Status calls */
48#define kGetDriveType 96 /* Get the type of the physical CD-ROM drive */
49#define kWhoIsThere 97 /* Get a bitmap of SCSI IDs the driver controls */
50#define kGetBlockSize 98 /* Get current block size of the CD-ROM drive */
51
52/* AppleCD other constants */
53#define kBlockPosition 0 /* Position at the specified logical block number */
54#define kAbsMSFPosition 1 /* Position at the specified Min/Sec/Frame (in BCD) */
55#define kTrackPosition 2 /* Position at the specified track number (in BCD) */
56#define kIndexPosition 3 /* Position at the nth track in program (in BCD) */
57
58#define kMutedPlayMode 0 /* Play the audio track with no output */
59#define kStereoPlayMode 9 /* Play the audio track in normal stereo */
60
61#define kControlFieldMask 0x0D /* Bits 3,2,0 in the nibble */
62#define kDataTrackMask 0x04 /* Indicates Data Track */
63
64#define kGetTrackRange 1 /* Query TOC for track numbers */
65#define kGetLeadOutArea 2 /* Query TOC for "Lead Out" end of audio data */
66#define kGetTrackEntries 3 /* Query TOC for track starts and data types */
67
68#define kStatusPlaying 0 /* Audio Play operation in progress */
69#define kStatusPaused 1 /* CD-ROM device in Hold Track ("Pause") state */
70#define kStatusMuted 2 /* MUTING-ON operation in progress */
71#define kStatusDone 3 /* Audio Play completed */
72#define kStatusError 4 /* Error occurred during audio play operation */
73#define kStatusStopped 5 /* Audio play operation not requested */
74
75#define kPlayModeSequential 0 /* Play tracks in order */
76#define kPlayModeShuffled 1 /* Play tracks randomly */
77#define kPlayModeProgrammed 2 /* Use custom playlist */
78
79/* AppleCD Gestalt selectors */
80#define kGestaltAudioCDSelector 'aucd'
81#define kDriverVersion52 0x00000520
82#define kDriverVersion51 0x00000510
83#define kDriverVersion50 0x00000500
84
85/* Drive type constants */
86#define kDriveAppleCD_SC 1
87#define kDriveAppleCD_SCPlus_or_150 2
88#define kDriveAppleCD_300_or_300Plus 3
89
90/* Misc constants */
91#define kFirstSCSIDevice -33
92#define kLastSCSIDevice -40
93
94#if PRAGMA_STRUCT_ALIGN
95 #pragma options align=mac68k
96#endif
97
98/* AppleCD driver parameter block */
99typedef struct CDCntrlParam {
100 QElemPtr qLink;
101 short qType;
102 short ioTrap;
103 Ptr ioCmdAddr;
104 IOCompletionUPP ioCompletion;
105 OSErr ioResult;
106 StringPtr ioNamePtr;
107 short ioVRefNum;
108 short ioCRefNum;
109 short csCode;
110
111 union {
112 long longs[6];
113 short words[11];
114 unsigned char bytes[22];
115 struct {
116 unsigned char status;
117 unsigned char play;
118 unsigned char control;
119 unsigned char minute;
120 unsigned char second;
121 unsigned char frame;
122 } cd;
123 } csParam;
124
125 } CDCntrlParam, *CDCntrlParamPtr;
126
127typedef union CDTrackData {
128 long value; /* Treat as a longword value */
129 struct {
130 unsigned char reserved : 4; /* Unused by AppleCD driver */
131 unsigned char control : 4; /* Track flags (data track?) */
132 unsigned char min; /* Start of track (BCD) */
133 unsigned char sec; /* Start of track (BCD) */
134 unsigned char frame; /* Start of track (BCD) */
135 } entry; /* Broken into fields */
136 } CDTrackData, *CDTrackPtr;
137
138#if PRAGMA_STRUCT_ALIGN
139 #pragma options align=reset
140#endif
diff --git a/apps/plugins/sdl/src/cdrom/macosx/AudioFilePlayer.c b/apps/plugins/sdl/src/cdrom/macosx/AudioFilePlayer.c
deleted file mode 100644
index 97cb9b2874..0000000000
--- a/apps/plugins/sdl/src/cdrom/macosx/AudioFilePlayer.c
+++ /dev/null
@@ -1,360 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 This file based on Apple sample code. We haven't changed the file name,
23 so if you want to see the original search for it on apple.com/developer
24*/
25#include "SDL_config.h"
26#include "SDL_endian.h"
27
28/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
29 AudioFilePlayer.cpp
30*/
31#include "AudioFilePlayer.h"
32
33/*
34void ThrowResult (OSStatus result, const char* str)
35{
36 SDL_SetError ("Error: %s %d", str, result);
37 throw result;
38}
39*/
40
41#if DEBUG
42static void PrintStreamDesc (AudioStreamBasicDescription *inDesc)
43{
44 if (!inDesc) {
45 printf ("Can't print a NULL desc!\n");
46 return;
47 }
48
49 printf ("- - - - - - - - - - - - - - - - - - - -\n");
50 printf (" Sample Rate:%f\n", inDesc->mSampleRate);
51 printf (" Format ID:%s\n", (char*)&inDesc->mFormatID);
52 printf (" Format Flags:%lX\n", inDesc->mFormatFlags);
53 printf (" Bytes per Packet:%ld\n", inDesc->mBytesPerPacket);
54 printf (" Frames per Packet:%ld\n", inDesc->mFramesPerPacket);
55 printf (" Bytes per Frame:%ld\n", inDesc->mBytesPerFrame);
56 printf (" Channels per Frame:%ld\n", inDesc->mChannelsPerFrame);
57 printf (" Bits per Channel:%ld\n", inDesc->mBitsPerChannel);
58 printf ("- - - - - - - - - - - - - - - - - - - -\n");
59}
60#endif
61
62
63static int AudioFilePlayer_SetDestination (AudioFilePlayer *afp, AudioUnit *inDestUnit)
64{
65 /*if (afp->mConnected) throw static_cast<OSStatus>(-1);*/ /* can't set dest if already engaged */
66 if (afp->mConnected)
67 return 0 ;
68
69 SDL_memcpy(&afp->mPlayUnit, inDestUnit, sizeof (afp->mPlayUnit));
70
71 OSStatus result = noErr;
72
73
74 /* we can "down" cast a component instance to a component */
75 ComponentDescription desc;
76 result = GetComponentInfo ((Component)*inDestUnit, &desc, 0, 0, 0);
77 if (result) return 0; /*THROW_RESULT("GetComponentInfo")*/
78
79 /* we're going to use this to know which convert routine to call
80 a v1 audio unit will have a type of 'aunt'
81 a v2 audio unit will have one of several different types. */
82 if (desc.componentType != kAudioUnitType_Output) {
83 result = badComponentInstance;
84 /*THROW_RESULT("BAD COMPONENT")*/
85 if (result) return 0;
86 }
87
88 /* Set the input format of the audio unit. */
89 result = AudioUnitSetProperty (*inDestUnit,
90 kAudioUnitProperty_StreamFormat,
91 kAudioUnitScope_Input,
92 0,
93 &afp->mFileDescription,
94 sizeof (afp->mFileDescription));
95 /*THROW_RESULT("AudioUnitSetProperty")*/
96 if (result) return 0;
97 return 1;
98}
99
100static void AudioFilePlayer_SetNotifier(AudioFilePlayer *afp, AudioFilePlayNotifier inNotifier, void *inRefCon)
101{
102 afp->mNotifier = inNotifier;
103 afp->mRefCon = inRefCon;
104}
105
106static int AudioFilePlayer_IsConnected(AudioFilePlayer *afp)
107{
108 return afp->mConnected;
109}
110
111static AudioUnit AudioFilePlayer_GetDestUnit(AudioFilePlayer *afp)
112{
113 return afp->mPlayUnit;
114}
115
116static void AudioFilePlayer_Print(AudioFilePlayer *afp)
117{
118#if DEBUG
119 printf ("Is Connected:%s\n", (IsConnected() ? "true" : "false"));
120 printf ("- - - - - - - - - - - - - - \n");
121#endif
122}
123
124static void AudioFilePlayer_SetStartFrame (AudioFilePlayer *afp, int frame)
125{
126 SInt64 position = frame * 2352;
127
128 afp->mStartFrame = frame;
129 afp->mAudioFileManager->SetPosition (afp->mAudioFileManager, position);
130}
131
132
133static int AudioFilePlayer_GetCurrentFrame (AudioFilePlayer *afp)
134{
135 return afp->mStartFrame + (afp->mAudioFileManager->GetByteCounter(afp->mAudioFileManager) / 2352);
136}
137
138static void AudioFilePlayer_SetStopFrame (AudioFilePlayer *afp, int frame)
139{
140 SInt64 position = frame * 2352;
141
142 afp->mAudioFileManager->SetEndOfFile (afp->mAudioFileManager, position);
143}
144
145void delete_AudioFilePlayer(AudioFilePlayer *afp)
146{
147 if (afp != NULL)
148 {
149 afp->Disconnect(afp);
150
151 if (afp->mAudioFileManager) {
152 delete_AudioFileManager(afp->mAudioFileManager);
153 afp->mAudioFileManager = 0;
154 }
155
156 if (afp->mForkRefNum) {
157 FSCloseFork (afp->mForkRefNum);
158 afp->mForkRefNum = 0;
159 }
160 SDL_free(afp);
161 }
162}
163
164static int AudioFilePlayer_Connect(AudioFilePlayer *afp)
165{
166#if DEBUG
167 printf ("Connect:%x, engaged=%d\n", (int)afp->mPlayUnit, (afp->mConnected ? 1 : 0));
168#endif
169 if (!afp->mConnected)
170 {
171 if (!afp->mAudioFileManager->DoConnect(afp->mAudioFileManager))
172 return 0;
173
174 /* set the render callback for the file data to be supplied to the sound converter AU */
175 afp->mInputCallback.inputProc = afp->mAudioFileManager->FileInputProc;
176 afp->mInputCallback.inputProcRefCon = afp->mAudioFileManager;
177
178 OSStatus result = AudioUnitSetProperty (afp->mPlayUnit,
179 kAudioUnitProperty_SetRenderCallback,
180 kAudioUnitScope_Input,
181 0,
182 &afp->mInputCallback,
183 sizeof(afp->mInputCallback));
184 if (result) return 0; /*THROW_RESULT("AudioUnitSetProperty")*/
185 afp->mConnected = 1;
186 }
187
188 return 1;
189}
190
191/* warning noted, now please go away ;-) */
192/* #warning This should redirect the calling of notification code to some other thread */
193static void AudioFilePlayer_DoNotification (AudioFilePlayer *afp, OSStatus inStatus)
194{
195 if (afp->mNotifier) {
196 (*afp->mNotifier) (afp->mRefCon, inStatus);
197 } else {
198 SDL_SetError ("Notification posted with no notifier in place");
199
200 if (inStatus == kAudioFilePlay_FileIsFinished)
201 afp->Disconnect(afp);
202 else if (inStatus != kAudioFilePlayErr_FilePlayUnderrun)
203 afp->Disconnect(afp);
204 }
205}
206
207static void AudioFilePlayer_Disconnect (AudioFilePlayer *afp)
208{
209#if DEBUG
210 printf ("Disconnect:%x,%ld, engaged=%d\n", (int)afp->mPlayUnit, 0, (afp->mConnected ? 1 : 0));
211#endif
212 if (afp->mConnected)
213 {
214 afp->mConnected = 0;
215
216 afp->mInputCallback.inputProc = 0;
217 afp->mInputCallback.inputProcRefCon = 0;
218 OSStatus result = AudioUnitSetProperty (afp->mPlayUnit,
219 kAudioUnitProperty_SetRenderCallback,
220 kAudioUnitScope_Input,
221 0,
222 &afp->mInputCallback,
223 sizeof(afp->mInputCallback));
224 if (result)
225 SDL_SetError ("AudioUnitSetProperty:RemoveInputCallback:%ld", result);
226
227 afp->mAudioFileManager->Disconnect(afp->mAudioFileManager);
228 }
229}
230
231typedef struct {
232 UInt32 offset;
233 UInt32 blockSize;
234} SSNDData;
235
236static int AudioFilePlayer_OpenFile (AudioFilePlayer *afp, const FSRef *inRef, SInt64 *outFileDataSize)
237{
238 ContainerChunk chunkHeader;
239 ChunkHeader chunk;
240 SSNDData ssndData;
241
242 OSErr result;
243 HFSUniStr255 dfName;
244 ByteCount actual;
245 SInt64 offset;
246
247 /* Open the data fork of the input file */
248 result = FSGetDataForkName(&dfName);
249 if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSGetDataForkName")*/
250
251 result = FSOpenFork(inRef, dfName.length, dfName.unicode, fsRdPerm, &afp->mForkRefNum);
252 if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSOpenFork")*/
253
254 /* Read the file header, and check if it's indeed an AIFC file */
255 result = FSReadFork(afp->mForkRefNum, fsAtMark, 0, sizeof(chunkHeader), &chunkHeader, &actual);
256 if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSReadFork")*/
257
258 if (SDL_SwapBE32(chunkHeader.ckID) != 'FORM') {
259 result = -1;
260 if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): chunk id is not 'FORM'");*/
261 }
262
263 if (SDL_SwapBE32(chunkHeader.formType) != 'AIFC') {
264 result = -1;
265 if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): file format is not 'AIFC'");*/
266 }
267
268 /* Search for the SSND chunk. We ignore all compression etc. information
269 in other chunks. Of course that is kind of evil, but for now we are lazy
270 and rely on the cdfs to always give us the same fixed format.
271 TODO: Parse the COMM chunk we currently skip to fill in mFileDescription.
272 */
273 offset = 0;
274 do {
275 result = FSReadFork(afp->mForkRefNum, fsFromMark, offset, sizeof(chunk), &chunk, &actual);
276 if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSReadFork")*/
277
278 chunk.ckID = SDL_SwapBE32(chunk.ckID);
279 chunk.ckSize = SDL_SwapBE32(chunk.ckSize);
280
281 /* Skip the chunk data */
282 offset = chunk.ckSize;
283 } while (chunk.ckID != 'SSND');
284
285 /* Read the header of the SSND chunk. After this, we are positioned right
286 at the start of the audio data. */
287 result = FSReadFork(afp->mForkRefNum, fsAtMark, 0, sizeof(ssndData), &ssndData, &actual);
288 if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSReadFork")*/
289
290 ssndData.offset = SDL_SwapBE32(ssndData.offset);
291
292 result = FSSetForkPosition(afp->mForkRefNum, fsFromMark, ssndData.offset);
293 if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSSetForkPosition")*/
294
295 /* Data size */
296 *outFileDataSize = chunk.ckSize - ssndData.offset - 8;
297
298 /* File format */
299 afp->mFileDescription.mSampleRate = 44100;
300 afp->mFileDescription.mFormatID = kAudioFormatLinearPCM;
301 afp->mFileDescription.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger;
302 afp->mFileDescription.mBytesPerPacket = 4;
303 afp->mFileDescription.mFramesPerPacket = 1;
304 afp->mFileDescription.mBytesPerFrame = 4;
305 afp->mFileDescription.mChannelsPerFrame = 2;
306 afp->mFileDescription.mBitsPerChannel = 16;
307
308 return 1;
309}
310
311AudioFilePlayer *new_AudioFilePlayer (const FSRef *inFileRef)
312{
313 SInt64 fileDataSize = 0;
314
315 AudioFilePlayer *afp = (AudioFilePlayer *) SDL_malloc(sizeof (AudioFilePlayer));
316 if (afp == NULL)
317 return NULL;
318 SDL_memset(afp, '\0', sizeof (*afp));
319
320 #define SET_AUDIOFILEPLAYER_METHOD(m) afp->m = AudioFilePlayer_##m
321 SET_AUDIOFILEPLAYER_METHOD(SetDestination);
322 SET_AUDIOFILEPLAYER_METHOD(SetNotifier);
323 SET_AUDIOFILEPLAYER_METHOD(SetStartFrame);
324 SET_AUDIOFILEPLAYER_METHOD(GetCurrentFrame);
325 SET_AUDIOFILEPLAYER_METHOD(SetStopFrame);
326 SET_AUDIOFILEPLAYER_METHOD(Connect);
327 SET_AUDIOFILEPLAYER_METHOD(Disconnect);
328 SET_AUDIOFILEPLAYER_METHOD(DoNotification);
329 SET_AUDIOFILEPLAYER_METHOD(IsConnected);
330 SET_AUDIOFILEPLAYER_METHOD(GetDestUnit);
331 SET_AUDIOFILEPLAYER_METHOD(Print);
332 SET_AUDIOFILEPLAYER_METHOD(OpenFile);
333 #undef SET_AUDIOFILEPLAYER_METHOD
334
335 if (!afp->OpenFile (afp, inFileRef, &fileDataSize))
336 {
337 SDL_free(afp);
338 return NULL;
339 }
340
341 /* we want about 4 seconds worth of data for the buffer */
342 int bytesPerSecond = (UInt32) (4 * afp->mFileDescription.mSampleRate * afp->mFileDescription.mBytesPerFrame);
343
344#if DEBUG
345 printf("File format:\n");
346 PrintStreamDesc (&afp->mFileDescription);
347#endif
348
349 afp->mAudioFileManager = new_AudioFileManager(afp, afp->mForkRefNum,
350 fileDataSize,
351 bytesPerSecond);
352 if (afp->mAudioFileManager == NULL)
353 {
354 delete_AudioFilePlayer(afp);
355 return NULL;
356 }
357
358 return afp;
359}
360
diff --git a/apps/plugins/sdl/src/cdrom/macosx/AudioFilePlayer.h b/apps/plugins/sdl/src/cdrom/macosx/AudioFilePlayer.h
deleted file mode 100644
index 886d017a59..0000000000
--- a/apps/plugins/sdl/src/cdrom/macosx/AudioFilePlayer.h
+++ /dev/null
@@ -1,178 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 This file based on Apple sample code. We haven't changed the file name,
23 so if you want to see the original search for it on apple.com/developer
24*/
25#include "SDL_config.h"
26
27/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
28 AudioFilePlayer.h
29*/
30#ifndef __AudioFilePlayer_H__
31#define __AudioFilePlayer_H__
32
33#include <CoreServices/CoreServices.h>
34
35#include <AudioUnit/AudioUnit.h>
36#if MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
37#include <AudioUnit/AUNTComponent.h>
38#endif
39
40#if (MAC_OS_X_VERSION_MAX_ALLOWED < 1050)
41typedef SInt16 FSIORefNum;
42#endif
43
44#include "SDL_error.h"
45
46const char* AudioFilePlayerErrorStr (OSStatus error);
47
48/*
49void ThrowResult (OSStatus result, const char *str);
50
51#define THROW_RESULT(str) \
52 if (result) { \
53 ThrowResult (result, str); \
54 }
55*/
56
57typedef void (*AudioFilePlayNotifier)(void *inRefCon,
58 OSStatus inStatus);
59
60enum {
61 kAudioFilePlayErr_FilePlayUnderrun = -10000,
62 kAudioFilePlay_FileIsFinished = -10001,
63 kAudioFilePlay_PlayerIsUninitialized = -10002
64};
65
66
67struct S_AudioFileManager;
68
69#pragma mark __________ AudioFilePlayer
70typedef struct S_AudioFilePlayer
71{
72/*public:*/
73 int (*SetDestination)(struct S_AudioFilePlayer *afp, AudioUnit *inDestUnit);
74 void (*SetNotifier)(struct S_AudioFilePlayer *afp, AudioFilePlayNotifier inNotifier, void *inRefCon);
75 void (*SetStartFrame)(struct S_AudioFilePlayer *afp, int frame); /* seek in the file */
76 int (*GetCurrentFrame)(struct S_AudioFilePlayer *afp); /* get the current frame position */
77 void (*SetStopFrame)(struct S_AudioFilePlayer *afp, int frame); /* set limit in the file */
78 int (*Connect)(struct S_AudioFilePlayer *afp);
79 void (*Disconnect)(struct S_AudioFilePlayer *afp);
80 void (*DoNotification)(struct S_AudioFilePlayer *afp, OSStatus inError);
81 int (*IsConnected)(struct S_AudioFilePlayer *afp);
82 AudioUnit (*GetDestUnit)(struct S_AudioFilePlayer *afp);
83 void (*Print)(struct S_AudioFilePlayer *afp);
84
85/*private:*/
86 AudioUnit mPlayUnit;
87 FSIORefNum mForkRefNum;
88
89 AURenderCallbackStruct mInputCallback;
90
91 AudioStreamBasicDescription mFileDescription;
92
93 int mConnected;
94
95 struct S_AudioFileManager* mAudioFileManager;
96
97 AudioFilePlayNotifier mNotifier;
98 void* mRefCon;
99
100 int mStartFrame;
101
102#pragma mark __________ Private_Methods
103
104 int (*OpenFile)(struct S_AudioFilePlayer *afp, const FSRef *inRef, SInt64 *outFileSize);
105} AudioFilePlayer;
106
107
108AudioFilePlayer *new_AudioFilePlayer(const FSRef *inFileRef);
109void delete_AudioFilePlayer(AudioFilePlayer *afp);
110
111
112
113#pragma mark __________ AudioFileManager
114typedef struct S_AudioFileManager
115{
116/*public:*/
117 /* this method should NOT be called by an object of this class
118 as it is called by the parent's Disconnect() method */
119 void (*Disconnect)(struct S_AudioFileManager *afm);
120 int (*DoConnect)(struct S_AudioFileManager *afm);
121 OSStatus (*Read)(struct S_AudioFileManager *afm, char *buffer, ByteCount *len);
122 const char* (*GetFileBuffer)(struct S_AudioFileManager *afm);
123 const AudioFilePlayer *(*GetParent)(struct S_AudioFileManager *afm);
124 void (*SetPosition)(struct S_AudioFileManager *afm, SInt64 pos); /* seek/rewind in the file */
125 int (*GetByteCounter)(struct S_AudioFileManager *afm); /* return actual bytes streamed to audio hardware */
126 void (*SetEndOfFile)(struct S_AudioFileManager *afm, SInt64 pos); /* set the "EOF" (will behave just like it reached eof) */
127
128/*protected:*/
129 AudioFilePlayer* mParent;
130 SInt16 mForkRefNum;
131 SInt64 mAudioDataOffset;
132
133 char* mFileBuffer;
134
135 int mByteCounter;
136
137 int mReadFromFirstBuffer;
138 int mLockUnsuccessful;
139 int mIsEngaged;
140
141 int mNumTimesAskedSinceFinished;
142
143
144 void* mTmpBuffer;
145 UInt32 mBufferSize;
146 UInt32 mBufferOffset;
147/*public:*/
148 UInt32 mChunkSize;
149 SInt64 mFileLength;
150 SInt64 mReadFilePosition;
151 int mWriteToFirstBuffer;
152 int mFinishedReadingData;
153
154/*protected:*/
155 OSStatus (*Render)(struct S_AudioFileManager *afm, AudioBufferList *ioData);
156 OSStatus (*GetFileData)(struct S_AudioFileManager *afm, void** inOutData, UInt32 *inOutDataSize);
157 void (*AfterRender)(struct S_AudioFileManager *afm);
158
159/*public:*/
160 /*static*/
161 OSStatus (*FileInputProc)(void *inRefCon,
162 AudioUnitRenderActionFlags *ioActionFlags,
163 const AudioTimeStamp *inTimeStamp,
164 UInt32 inBusNumber,
165 UInt32 inNumberFrames,
166 AudioBufferList *ioData);
167} AudioFileManager;
168
169
170AudioFileManager *new_AudioFileManager (AudioFilePlayer *inParent,
171 SInt16 inForkRefNum,
172 SInt64 inFileLength,
173 UInt32 inChunkSize);
174
175void delete_AudioFileManager(AudioFileManager *afm);
176
177#endif
178
diff --git a/apps/plugins/sdl/src/cdrom/macosx/AudioFileReaderThread.c b/apps/plugins/sdl/src/cdrom/macosx/AudioFileReaderThread.c
deleted file mode 100644
index 0007c07f61..0000000000
--- a/apps/plugins/sdl/src/cdrom/macosx/AudioFileReaderThread.c
+++ /dev/null
@@ -1,610 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 This file based on Apple sample code. We haven't changed the file name,
23 so if you want to see the original search for it on apple.com/developer
24*/
25#include "SDL_config.h"
26
27/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
28 AudioFileManager.cpp
29*/
30#include "AudioFilePlayer.h"
31#include <mach/mach.h> /* used for setting policy of thread */
32#include "SDLOSXCAGuard.h"
33#include <pthread.h>
34
35/*#include <list>*/
36
37/*typedef void *FileData;*/
38typedef struct S_FileData
39{
40 AudioFileManager *obj;
41 struct S_FileData *next;
42} FileData;
43
44
45typedef struct S_FileReaderThread {
46/*public:*/
47 SDLOSXCAGuard* (*GetGuard)(struct S_FileReaderThread *frt);
48 void (*AddReader)(struct S_FileReaderThread *frt);
49 void (*RemoveReader)(struct S_FileReaderThread *frt, AudioFileManager* inItem);
50 int (*TryNextRead)(struct S_FileReaderThread *frt, AudioFileManager* inItem);
51
52 int mThreadShouldDie;
53
54/*private:*/
55 /*typedef std::list<AudioFileManager*> FileData;*/
56
57 SDLOSXCAGuard *mGuard;
58 UInt32 mThreadPriority;
59
60 int mNumReaders;
61 FileData *mFileData;
62
63
64 void (*ReadNextChunk)(struct S_FileReaderThread *frt);
65 int (*StartFixedPriorityThread)(struct S_FileReaderThread *frt);
66 /*static*/
67 UInt32 (*GetThreadBasePriority)(pthread_t inThread);
68 /*static*/
69 void* (*DiskReaderEntry)(void *inRefCon);
70} FileReaderThread;
71
72
73static SDLOSXCAGuard* FileReaderThread_GetGuard(FileReaderThread *frt)
74{
75 return frt->mGuard;
76}
77
78/* returns 1 if succeeded */
79static int FileReaderThread_TryNextRead (FileReaderThread *frt, AudioFileManager* inItem)
80{
81 int didLock = 0;
82 int succeeded = 0;
83 if (frt->mGuard->Try(frt->mGuard, &didLock))
84 {
85 /*frt->mFileData.push_back (inItem);*/
86 /* !!! FIXME: this could be faster with a "tail" member. --ryan. */
87 FileData *i = frt->mFileData;
88 FileData *prev = NULL;
89
90 FileData *newfd = (FileData *) SDL_malloc(sizeof (FileData));
91 newfd->obj = inItem;
92 newfd->next = NULL;
93
94 while (i != NULL) { prev = i; i = i->next; }
95 if (prev == NULL)
96 frt->mFileData = newfd;
97 else
98 prev->next = newfd;
99
100 frt->mGuard->Notify(frt->mGuard);
101 succeeded = 1;
102
103 if (didLock)
104 frt->mGuard->Unlock(frt->mGuard);
105 }
106
107 return succeeded;
108}
109
110static void FileReaderThread_AddReader(FileReaderThread *frt)
111{
112 if (frt->mNumReaders == 0)
113 {
114 frt->mThreadShouldDie = 0;
115 frt->StartFixedPriorityThread (frt);
116 }
117 frt->mNumReaders++;
118}
119
120static void FileReaderThread_RemoveReader (FileReaderThread *frt, AudioFileManager* inItem)
121{
122 if (frt->mNumReaders > 0)
123 {
124 int bNeedsRelease = frt->mGuard->Lock(frt->mGuard);
125
126 /*frt->mFileData.remove (inItem);*/
127 FileData *i = frt->mFileData;
128 FileData *prev = NULL;
129 while (i != NULL)
130 {
131 FileData *next = i->next;
132 if (i->obj != inItem)
133 prev = i;
134 else
135 {
136 if (prev == NULL)
137 frt->mFileData = next;
138 else
139 prev->next = next;
140 SDL_free(i);
141 }
142 i = next;
143 }
144
145 if (--frt->mNumReaders == 0) {
146 frt->mThreadShouldDie = 1;
147 frt->mGuard->Notify(frt->mGuard); /* wake up thread so it will quit */
148 frt->mGuard->Wait(frt->mGuard); /* wait for thread to die */
149 }
150
151 if (bNeedsRelease) frt->mGuard->Unlock(frt->mGuard);
152 }
153}
154
155static int FileReaderThread_StartFixedPriorityThread (FileReaderThread *frt)
156{
157 pthread_attr_t theThreadAttrs;
158 pthread_t pThread;
159
160 OSStatus result = pthread_attr_init(&theThreadAttrs);
161 if (result) return 0; /*THROW_RESULT("pthread_attr_init - Thread attributes could not be created.")*/
162
163 result = pthread_attr_setdetachstate(&theThreadAttrs, PTHREAD_CREATE_DETACHED);
164 if (result) return 0; /*THROW_RESULT("pthread_attr_setdetachstate - Thread attributes could not be detached.")*/
165
166 result = pthread_create (&pThread, &theThreadAttrs, frt->DiskReaderEntry, frt);
167 if (result) return 0; /*THROW_RESULT("pthread_create - Create and start the thread.")*/
168
169 pthread_attr_destroy(&theThreadAttrs);
170
171 /* we've now created the thread and started it
172 we'll now set the priority of the thread to the nominated priority
173 and we'll also make the thread fixed */
174 thread_extended_policy_data_t theFixedPolicy;
175 thread_precedence_policy_data_t thePrecedencePolicy;
176 SInt32 relativePriority;
177
178 /* make thread fixed */
179 theFixedPolicy.timeshare = 0; /* set to 1 for a non-fixed thread */
180 result = thread_policy_set (pthread_mach_thread_np(pThread), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT);
181 if (result) return 0; /*THROW_RESULT("thread_policy - Couldn't set thread as fixed priority.")*/
182 /* set priority */
183 /* precedency policy's "importance" value is relative to spawning thread's priority */
184 relativePriority = frt->mThreadPriority - frt->GetThreadBasePriority(pthread_self());
185
186 thePrecedencePolicy.importance = relativePriority;
187 result = thread_policy_set (pthread_mach_thread_np(pThread), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT);
188 if (result) return 0; /*THROW_RESULT("thread_policy - Couldn't set thread priority.")*/
189
190 return 1;
191}
192
193static UInt32 FileReaderThread_GetThreadBasePriority (pthread_t inThread)
194{
195 thread_basic_info_data_t threadInfo;
196 policy_info_data_t thePolicyInfo;
197 unsigned int count;
198
199 /* get basic info */
200 count = THREAD_BASIC_INFO_COUNT;
201 thread_info (pthread_mach_thread_np (inThread), THREAD_BASIC_INFO, (integer_t*)&threadInfo, &count);
202
203 switch (threadInfo.policy) {
204 case POLICY_TIMESHARE:
205 count = POLICY_TIMESHARE_INFO_COUNT;
206 thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_TIMESHARE_INFO, (integer_t*)&(thePolicyInfo.ts), &count);
207 return thePolicyInfo.ts.base_priority;
208 break;
209
210 case POLICY_FIFO:
211 count = POLICY_FIFO_INFO_COUNT;
212 thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_FIFO_INFO, (integer_t*)&(thePolicyInfo.fifo), &count);
213 if (thePolicyInfo.fifo.depressed) {
214 return thePolicyInfo.fifo.depress_priority;
215 } else {
216 return thePolicyInfo.fifo.base_priority;
217 }
218 break;
219
220 case POLICY_RR:
221 count = POLICY_RR_INFO_COUNT;
222 thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_RR_INFO, (integer_t*)&(thePolicyInfo.rr), &count);
223 if (thePolicyInfo.rr.depressed) {
224 return thePolicyInfo.rr.depress_priority;
225 } else {
226 return thePolicyInfo.rr.base_priority;
227 }
228 break;
229 }
230
231 return 0;
232}
233
234static void *FileReaderThread_DiskReaderEntry (void *inRefCon)
235{
236 FileReaderThread *frt = (FileReaderThread *)inRefCon;
237 frt->ReadNextChunk(frt);
238 #if DEBUG
239 printf ("finished with reading file\n");
240 #endif
241
242 return 0;
243}
244
245static void FileReaderThread_ReadNextChunk (FileReaderThread *frt)
246{
247 OSStatus result;
248 ByteCount dataChunkSize;
249 AudioFileManager* theItem = 0;
250
251 for (;;)
252 {
253 { /* this is a scoped based lock */
254 int bNeedsRelease = frt->mGuard->Lock(frt->mGuard);
255
256 if (frt->mThreadShouldDie) {
257 frt->mGuard->Notify(frt->mGuard);
258 if (bNeedsRelease) frt->mGuard->Unlock(frt->mGuard);
259 return;
260 }
261
262 /*if (frt->mFileData.empty())*/
263 if (frt->mFileData == NULL)
264 {
265 frt->mGuard->Wait(frt->mGuard);
266 }
267
268 /* kill thread */
269 if (frt->mThreadShouldDie) {
270
271 frt->mGuard->Notify(frt->mGuard);
272 if (bNeedsRelease) frt->mGuard->Unlock(frt->mGuard);
273 return;
274 }
275
276 /*theItem = frt->mFileData.front();*/
277 /*frt->mFileData.pop_front();*/
278 theItem = NULL;
279 if (frt->mFileData != NULL)
280 {
281 FileData *next = frt->mFileData->next;
282 theItem = frt->mFileData->obj;
283 SDL_free(frt->mFileData);
284 frt->mFileData = next;
285 }
286
287 if (bNeedsRelease) frt->mGuard->Unlock(frt->mGuard);
288 }
289
290 if ((theItem->mFileLength - theItem->mReadFilePosition) < theItem->mChunkSize)
291 dataChunkSize = theItem->mFileLength - theItem->mReadFilePosition;
292 else
293 dataChunkSize = theItem->mChunkSize;
294
295 /* this is the exit condition for the thread */
296 if (dataChunkSize <= 0) {
297 theItem->mFinishedReadingData = 1;
298 continue;
299 }
300 /* construct pointer */
301 char* writePtr = (char *) (theItem->GetFileBuffer(theItem) +
302 (theItem->mWriteToFirstBuffer ? 0 : theItem->mChunkSize));
303
304 /* read data */
305 result = theItem->Read(theItem, writePtr, &dataChunkSize);
306 if (result != noErr && result != eofErr) {
307 AudioFilePlayer *afp = (AudioFilePlayer *) theItem->GetParent(theItem);
308 afp->DoNotification(afp, result);
309 continue;
310 }
311
312 if (dataChunkSize != theItem->mChunkSize)
313 {
314 writePtr += dataChunkSize;
315
316 /* can't exit yet.. we still have to pass the partial buffer back */
317 SDL_memset(writePtr, 0, (theItem->mChunkSize - dataChunkSize));
318 }
319
320 theItem->mWriteToFirstBuffer = !theItem->mWriteToFirstBuffer; /* switch buffers */
321
322 if (result == eofErr)
323 theItem->mReadFilePosition = theItem->mFileLength;
324 else
325 theItem->mReadFilePosition += dataChunkSize; /* increment count */
326 }
327}
328
329void delete_FileReaderThread(FileReaderThread *frt)
330{
331 if (frt != NULL)
332 {
333 delete_SDLOSXCAGuard(frt->mGuard);
334 SDL_free(frt);
335 }
336}
337
338FileReaderThread *new_FileReaderThread ()
339{
340 FileReaderThread *frt = (FileReaderThread *) SDL_malloc(sizeof (FileReaderThread));
341 if (frt == NULL)
342 return NULL;
343 SDL_memset(frt, '\0', sizeof (*frt));
344
345 frt->mGuard = new_SDLOSXCAGuard();
346 if (frt->mGuard == NULL)
347 {
348 SDL_free(frt);
349 return NULL;
350 }
351
352 #define SET_FILEREADERTHREAD_METHOD(m) frt->m = FileReaderThread_##m
353 SET_FILEREADERTHREAD_METHOD(GetGuard);
354 SET_FILEREADERTHREAD_METHOD(AddReader);
355 SET_FILEREADERTHREAD_METHOD(RemoveReader);
356 SET_FILEREADERTHREAD_METHOD(TryNextRead);
357 SET_FILEREADERTHREAD_METHOD(ReadNextChunk);
358 SET_FILEREADERTHREAD_METHOD(StartFixedPriorityThread);
359 SET_FILEREADERTHREAD_METHOD(GetThreadBasePriority);
360 SET_FILEREADERTHREAD_METHOD(DiskReaderEntry);
361 #undef SET_FILEREADERTHREAD_METHOD
362
363 frt->mThreadPriority = 62;
364 return frt;
365}
366
367
368static FileReaderThread *sReaderThread;
369
370
371static int AudioFileManager_DoConnect (AudioFileManager *afm)
372{
373 if (!afm->mIsEngaged)
374 {
375 OSStatus result;
376
377 /*afm->mReadFilePosition = 0;*/
378 afm->mFinishedReadingData = 0;
379
380 afm->mNumTimesAskedSinceFinished = 0;
381 afm->mLockUnsuccessful = 0;
382
383 ByteCount dataChunkSize;
384
385 if ((afm->mFileLength - afm->mReadFilePosition) < afm->mChunkSize)
386 dataChunkSize = afm->mFileLength - afm->mReadFilePosition;
387 else
388 dataChunkSize = afm->mChunkSize;
389
390 result = afm->Read(afm, afm->mFileBuffer, &dataChunkSize);
391 if (result) return 0; /*THROW_RESULT("AudioFileManager::DoConnect(): Read")*/
392
393 afm->mReadFilePosition += dataChunkSize;
394
395 afm->mWriteToFirstBuffer = 0;
396 afm->mReadFromFirstBuffer = 1;
397
398 sReaderThread->AddReader(sReaderThread);
399
400 afm->mIsEngaged = 1;
401 }
402 /*
403 else
404 throw static_cast<OSStatus>(-1); */ /* thread has already been started */
405
406 return 1;
407}
408
409static void AudioFileManager_Disconnect (AudioFileManager *afm)
410{
411 if (afm->mIsEngaged)
412 {
413 sReaderThread->RemoveReader (sReaderThread, afm);
414 afm->mIsEngaged = 0;
415 }
416}
417
418static OSStatus AudioFileManager_Read(AudioFileManager *afm, char *buffer, ByteCount *len)
419{
420 return FSReadFork (afm->mForkRefNum,
421 fsFromStart,
422 afm->mReadFilePosition + afm->mAudioDataOffset,
423 *len,
424 buffer,
425 len);
426}
427
428static OSStatus AudioFileManager_GetFileData (AudioFileManager *afm, void** inOutData, UInt32 *inOutDataSize)
429{
430 if (afm->mFinishedReadingData)
431 {
432 ++afm->mNumTimesAskedSinceFinished;
433 *inOutDataSize = 0;
434 *inOutData = 0;
435 return noErr;
436 }
437
438 if (afm->mReadFromFirstBuffer == afm->mWriteToFirstBuffer) {
439 #if DEBUG
440 printf ("* * * * * * * Can't keep up with reading file\n");
441 #endif
442
443 afm->mParent->DoNotification (afm->mParent, kAudioFilePlayErr_FilePlayUnderrun);
444 *inOutDataSize = 0;
445 *inOutData = 0;
446 } else {
447 *inOutDataSize = afm->mChunkSize;
448 *inOutData = afm->mReadFromFirstBuffer ? afm->mFileBuffer : (afm->mFileBuffer + afm->mChunkSize);
449 }
450
451 afm->mLockUnsuccessful = !sReaderThread->TryNextRead (sReaderThread, afm);
452
453 afm->mReadFromFirstBuffer = !afm->mReadFromFirstBuffer;
454
455 return noErr;
456}
457
458static void AudioFileManager_AfterRender (AudioFileManager *afm)
459{
460 if (afm->mNumTimesAskedSinceFinished > 0)
461 {
462 int didLock = 0;
463 SDLOSXCAGuard *guard = sReaderThread->GetGuard(sReaderThread);
464 if (guard->Try(guard, &didLock)) {
465 afm->mParent->DoNotification (afm->mParent, kAudioFilePlay_FileIsFinished);
466 if (didLock)
467 guard->Unlock(guard);
468 }
469 }
470
471 if (afm->mLockUnsuccessful)
472 afm->mLockUnsuccessful = !sReaderThread->TryNextRead (sReaderThread, afm);
473}
474
475static void AudioFileManager_SetPosition (AudioFileManager *afm, SInt64 pos)
476{
477 if (pos < 0 || pos >= afm->mFileLength) {
478 SDL_SetError ("AudioFileManager::SetPosition - position invalid: %d filelen=%d\n",
479 (unsigned int)pos, (unsigned int)afm->mFileLength);
480 pos = 0;
481 }
482
483 afm->mReadFilePosition = pos;
484}
485
486static void AudioFileManager_SetEndOfFile (AudioFileManager *afm, SInt64 pos)
487{
488 if (pos <= 0 || pos > afm->mFileLength) {
489 SDL_SetError ("AudioFileManager::SetEndOfFile - position beyond actual eof\n");
490 pos = afm->mFileLength;
491 }
492
493 afm->mFileLength = pos;
494}
495
496static const char *AudioFileManager_GetFileBuffer(AudioFileManager *afm)
497{
498 return afm->mFileBuffer;
499}
500
501const AudioFilePlayer *AudioFileManager_GetParent(AudioFileManager *afm)
502{
503 return afm->mParent;
504}
505
506static int AudioFileManager_GetByteCounter(AudioFileManager *afm)
507{
508 return afm->mByteCounter;
509}
510
511static OSStatus AudioFileManager_FileInputProc (void *inRefCon,
512 AudioUnitRenderActionFlags *ioActionFlags,
513 const AudioTimeStamp *inTimeStamp,
514 UInt32 inBusNumber,
515 UInt32 inNumberFrames,
516 AudioBufferList *ioData)
517{
518 AudioFileManager* afm = (AudioFileManager*)inRefCon;
519 return afm->Render(afm, ioData);
520}
521
522static OSStatus AudioFileManager_Render (AudioFileManager *afm, AudioBufferList *ioData)
523{
524 OSStatus result = noErr;
525 AudioBuffer *abuf;
526 UInt32 i;
527
528 for (i = 0; i < ioData->mNumberBuffers; i++) {
529 abuf = &ioData->mBuffers[i];
530 if (afm->mBufferOffset >= afm->mBufferSize) {
531 result = afm->GetFileData(afm, &afm->mTmpBuffer, &afm->mBufferSize);
532 if (result) {
533 SDL_SetError ("AudioConverterFillBuffer:%ld\n", result);
534 afm->mParent->DoNotification(afm->mParent, result);
535 return result;
536 }
537
538 afm->mBufferOffset = 0;
539 }
540
541 if (abuf->mDataByteSize > afm->mBufferSize - afm->mBufferOffset)
542 abuf->mDataByteSize = afm->mBufferSize - afm->mBufferOffset;
543 abuf->mData = (char *)afm->mTmpBuffer + afm->mBufferOffset;
544 afm->mBufferOffset += abuf->mDataByteSize;
545
546 afm->mByteCounter += abuf->mDataByteSize;
547 afm->AfterRender(afm);
548 }
549 return result;
550}
551
552
553void delete_AudioFileManager (AudioFileManager *afm)
554{
555 if (afm != NULL) {
556 if (afm->mFileBuffer) {
557 free(afm->mFileBuffer);
558 }
559
560 SDL_free(afm);
561 }
562}
563
564
565AudioFileManager *new_AudioFileManager(AudioFilePlayer *inParent,
566 SInt16 inForkRefNum,
567 SInt64 inFileLength,
568 UInt32 inChunkSize)
569{
570 AudioFileManager *afm;
571
572 if (sReaderThread == NULL)
573 {
574 sReaderThread = new_FileReaderThread();
575 if (sReaderThread == NULL)
576 return NULL;
577 }
578
579 afm = (AudioFileManager *) SDL_malloc(sizeof (AudioFileManager));
580 if (afm == NULL)
581 return NULL;
582 SDL_memset(afm, '\0', sizeof (*afm));
583
584 #define SET_AUDIOFILEMANAGER_METHOD(m) afm->m = AudioFileManager_##m
585 SET_AUDIOFILEMANAGER_METHOD(Disconnect);
586 SET_AUDIOFILEMANAGER_METHOD(DoConnect);
587 SET_AUDIOFILEMANAGER_METHOD(Read);
588 SET_AUDIOFILEMANAGER_METHOD(GetFileBuffer);
589 SET_AUDIOFILEMANAGER_METHOD(GetParent);
590 SET_AUDIOFILEMANAGER_METHOD(SetPosition);
591 SET_AUDIOFILEMANAGER_METHOD(GetByteCounter);
592 SET_AUDIOFILEMANAGER_METHOD(SetEndOfFile);
593 SET_AUDIOFILEMANAGER_METHOD(Render);
594 SET_AUDIOFILEMANAGER_METHOD(GetFileData);
595 SET_AUDIOFILEMANAGER_METHOD(AfterRender);
596 SET_AUDIOFILEMANAGER_METHOD(FileInputProc);
597 #undef SET_AUDIOFILEMANAGER_METHOD
598
599 afm->mParent = inParent;
600 afm->mForkRefNum = inForkRefNum;
601 afm->mBufferSize = inChunkSize;
602 afm->mBufferOffset = inChunkSize;
603 afm->mChunkSize = inChunkSize;
604 afm->mFileLength = inFileLength;
605 afm->mFileBuffer = (char*) SDL_malloc(afm->mChunkSize * 2);
606 FSGetForkPosition(afm->mForkRefNum, &afm->mAudioDataOffset);
607 assert (afm->mFileBuffer != NULL);
608 return afm;
609}
610
diff --git a/apps/plugins/sdl/src/cdrom/macosx/CDPlayer.c b/apps/plugins/sdl/src/cdrom/macosx/CDPlayer.c
deleted file mode 100644
index beb87cd85b..0000000000
--- a/apps/plugins/sdl/src/cdrom/macosx/CDPlayer.c
+++ /dev/null
@@ -1,636 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "CDPlayer.h"
25#include "AudioFilePlayer.h"
26#include "SDLOSXCAGuard.h"
27
28/* we're exporting these functions into C land for SDL_syscdrom.c */
29/*extern "C" {*/
30
31/*///////////////////////////////////////////////////////////////////////////
32 Constants
33 //////////////////////////////////////////////////////////////////////////*/
34
35#define kAudioCDFilesystemID (UInt16)(('J' << 8) | 'H') /* 'JH'; this avoids compiler warning */
36
37/* XML PList keys */
38#define kRawTOCDataString "Format 0x02 TOC Data"
39#define kSessionsString "Sessions"
40#define kSessionTypeString "Session Type"
41#define kTrackArrayString "Track Array"
42#define kFirstTrackInSessionString "First Track"
43#define kLastTrackInSessionString "Last Track"
44#define kLeadoutBlockString "Leadout Block"
45#define kDataKeyString "Data"
46#define kPointKeyString "Point"
47#define kSessionNumberKeyString "Session Number"
48#define kStartBlockKeyString "Start Block"
49
50/*///////////////////////////////////////////////////////////////////////////
51 Globals
52 //////////////////////////////////////////////////////////////////////////*/
53
54#pragma mark -- Globals --
55
56static int playBackWasInit = 0;
57static AudioUnit theUnit;
58static AudioFilePlayer* thePlayer = NULL;
59static CDPlayerCompletionProc completionProc = NULL;
60static SDL_mutex *apiMutex = NULL;
61static SDL_sem *callbackSem;
62static SDL_CD* theCDROM;
63
64/*///////////////////////////////////////////////////////////////////////////
65 Prototypes
66 //////////////////////////////////////////////////////////////////////////*/
67
68#pragma mark -- Prototypes --
69
70static OSStatus CheckInit ();
71
72static void FilePlayNotificationHandler (void* inRefCon, OSStatus inStatus);
73
74static int RunCallBackThread (void* inRefCon);
75
76
77#pragma mark -- Public Functions --
78
79void Lock ()
80{
81 if (!apiMutex) {
82 apiMutex = SDL_CreateMutex();
83 }
84 SDL_mutexP(apiMutex);
85}
86
87void Unlock ()
88{
89 SDL_mutexV(apiMutex);
90}
91
92int DetectAudioCDVolumes(FSVolumeRefNum *volumes, int numVolumes)
93{
94 int volumeIndex;
95 int cdVolumeCount = 0;
96 OSStatus result = noErr;
97
98 for (volumeIndex = 1; result == noErr || result != nsvErr; volumeIndex++)
99 {
100 FSVolumeRefNum actualVolume;
101 FSVolumeInfo volumeInfo;
102
103 memset (&volumeInfo, 0, sizeof(volumeInfo));
104
105 result = FSGetVolumeInfo (kFSInvalidVolumeRefNum,
106 volumeIndex,
107 &actualVolume,
108 kFSVolInfoFSInfo,
109 &volumeInfo,
110 NULL,
111 NULL);
112
113 if (result == noErr)
114 {
115 if (volumeInfo.filesystemID == kAudioCDFilesystemID) /* It's an audio CD */
116 {
117 if (volumes != NULL && cdVolumeCount < numVolumes)
118 volumes[cdVolumeCount] = actualVolume;
119
120 cdVolumeCount++;
121 }
122 }
123 else
124 {
125 /* I'm commenting this out because it seems to be harmless */
126 /*SDL_SetError ("DetectAudioCDVolumes: FSGetVolumeInfo returned %d", result);*/
127 }
128 }
129
130 return cdVolumeCount;
131}
132
133int ReadTOCData (FSVolumeRefNum theVolume, SDL_CD *theCD)
134{
135 HFSUniStr255 dataForkName;
136 OSStatus theErr;
137 FSIORefNum forkRefNum;
138 SInt64 forkSize;
139 Ptr forkData = 0;
140 ByteCount actualRead;
141 CFDataRef dataRef = 0;
142 CFPropertyListRef propertyListRef = 0;
143 FSRefParam fsRefPB;
144 FSRef tocPlistFSRef;
145 FSRef rootRef;
146 const char* error = "Unspecified Error";
147 const UniChar uniName[] = { '.','T','O','C','.','p','l','i','s','t' };
148
149 theErr = FSGetVolumeInfo(theVolume, 0, 0, kFSVolInfoNone, 0, 0, &rootRef);
150 if(theErr != noErr) {
151 error = "FSGetVolumeInfo";
152 goto bail;
153 }
154
155 SDL_memset(&fsRefPB, '\0', sizeof (fsRefPB));
156
157 /* get stuff from .TOC.plist */
158 fsRefPB.ref = &rootRef;
159 fsRefPB.newRef = &tocPlistFSRef;
160 fsRefPB.nameLength = sizeof (uniName) / sizeof (uniName[0]);
161 fsRefPB.name = uniName;
162 fsRefPB.textEncodingHint = kTextEncodingUnknown;
163
164 theErr = PBMakeFSRefUnicodeSync (&fsRefPB);
165 if(theErr != noErr) {
166 error = "PBMakeFSRefUnicodeSync";
167 goto bail;
168 }
169
170 /* Load and parse the TOC XML data */
171
172 theErr = FSGetDataForkName (&dataForkName);
173 if (theErr != noErr) {
174 error = "FSGetDataForkName";
175 goto bail;
176 }
177
178 theErr = FSOpenFork (&tocPlistFSRef, dataForkName.length, dataForkName.unicode, fsRdPerm, &forkRefNum);
179 if (theErr != noErr) {
180 error = "FSOpenFork";
181 goto bail;
182 }
183
184 theErr = FSGetForkSize (forkRefNum, &forkSize);
185 if (theErr != noErr) {
186 error = "FSGetForkSize";
187 goto bail;
188 }
189
190 /* Allocate some memory for the XML data */
191 forkData = NewPtr (forkSize);
192 if(forkData == NULL) {
193 error = "NewPtr";
194 goto bail;
195 }
196
197 theErr = FSReadFork (forkRefNum, fsFromStart, 0 /* offset location */, forkSize, forkData, &actualRead);
198 if(theErr != noErr) {
199 error = "FSReadFork";
200 goto bail;
201 }
202
203 dataRef = CFDataCreate (kCFAllocatorDefault, (UInt8 *)forkData, forkSize);
204 if(dataRef == 0) {
205 error = "CFDataCreate";
206 goto bail;
207 }
208
209 propertyListRef = CFPropertyListCreateFromXMLData (kCFAllocatorDefault,
210 dataRef,
211 kCFPropertyListImmutable,
212 NULL);
213 if (propertyListRef == NULL) {
214 error = "CFPropertyListCreateFromXMLData";
215 goto bail;
216 }
217
218 /* Now we got the Property List in memory. Parse it. */
219
220 /* First, make sure the root item is a CFDictionary. If not, release and bail. */
221 if(CFGetTypeID(propertyListRef)== CFDictionaryGetTypeID())
222 {
223 CFDictionaryRef dictRef = (CFDictionaryRef)propertyListRef;
224
225 CFDataRef theRawTOCDataRef;
226 CFArrayRef theSessionArrayRef;
227 CFIndex numSessions;
228 CFIndex index;
229
230 /* This is how we get the Raw TOC Data */
231 theRawTOCDataRef = (CFDataRef)CFDictionaryGetValue (dictRef, CFSTR(kRawTOCDataString));
232
233 /* Get the session array info. */
234 theSessionArrayRef = (CFArrayRef)CFDictionaryGetValue (dictRef, CFSTR(kSessionsString));
235
236 /* Find out how many sessions there are. */
237 numSessions = CFArrayGetCount (theSessionArrayRef);
238
239 /* Initialize the total number of tracks to 0 */
240 theCD->numtracks = 0;
241
242 /* Iterate over all sessions, collecting the track data */
243 for(index = 0; index < numSessions; index++)
244 {
245 CFDictionaryRef theSessionDict;
246 CFNumberRef leadoutBlock;
247 CFArrayRef trackArray;
248 CFIndex numTracks;
249 CFIndex trackIndex;
250 UInt32 value = 0;
251
252 theSessionDict = (CFDictionaryRef) CFArrayGetValueAtIndex (theSessionArrayRef, index);
253 leadoutBlock = (CFNumberRef) CFDictionaryGetValue (theSessionDict, CFSTR(kLeadoutBlockString));
254
255 trackArray = (CFArrayRef)CFDictionaryGetValue (theSessionDict, CFSTR(kTrackArrayString));
256
257 numTracks = CFArrayGetCount (trackArray);
258
259 for(trackIndex = 0; trackIndex < numTracks; trackIndex++) {
260
261 CFDictionaryRef theTrackDict;
262 CFNumberRef trackNumber;
263 CFNumberRef sessionNumber;
264 CFNumberRef startBlock;
265 CFBooleanRef isDataTrack;
266 UInt32 value;
267
268 theTrackDict = (CFDictionaryRef) CFArrayGetValueAtIndex (trackArray, trackIndex);
269
270 trackNumber = (CFNumberRef) CFDictionaryGetValue (theTrackDict, CFSTR(kPointKeyString));
271 sessionNumber = (CFNumberRef) CFDictionaryGetValue (theTrackDict, CFSTR(kSessionNumberKeyString));
272 startBlock = (CFNumberRef) CFDictionaryGetValue (theTrackDict, CFSTR(kStartBlockKeyString));
273 isDataTrack = (CFBooleanRef) CFDictionaryGetValue (theTrackDict, CFSTR(kDataKeyString));
274
275 /* Fill in the SDL_CD struct */
276 int idx = theCD->numtracks++;
277
278 CFNumberGetValue (trackNumber, kCFNumberSInt32Type, &value);
279 theCD->track[idx].id = value;
280
281 CFNumberGetValue (startBlock, kCFNumberSInt32Type, &value);
282 theCD->track[idx].offset = value;
283
284 theCD->track[idx].type = (isDataTrack == kCFBooleanTrue) ? SDL_DATA_TRACK : SDL_AUDIO_TRACK;
285
286 /* Since the track lengths are not stored in .TOC.plist we compute them. */
287 if (trackIndex > 0) {
288 theCD->track[idx-1].length = theCD->track[idx].offset - theCD->track[idx-1].offset;
289 }
290 }
291
292 /* Compute the length of the last track */
293 CFNumberGetValue (leadoutBlock, kCFNumberSInt32Type, &value);
294
295 theCD->track[theCD->numtracks-1].length =
296 value - theCD->track[theCD->numtracks-1].offset;
297
298 /* Set offset to leadout track */
299 theCD->track[theCD->numtracks].offset = value;
300 }
301
302 }
303
304 theErr = 0;
305 goto cleanup;
306bail:
307 SDL_SetError ("ReadTOCData: %s returned %d", error, theErr);
308 theErr = -1;
309cleanup:
310
311 if (propertyListRef != NULL)
312 CFRelease(propertyListRef);
313 if (dataRef != NULL)
314 CFRelease(dataRef);
315 if (forkData != NULL)
316 DisposePtr(forkData);
317
318 FSCloseFork (forkRefNum);
319
320 return theErr;
321}
322
323int ListTrackFiles (FSVolumeRefNum theVolume, FSRef *trackFiles, int numTracks)
324{
325 OSStatus result = -1;
326 FSIterator iterator;
327 ItemCount actualObjects;
328 FSRef rootDirectory;
329 FSRef ref;
330 HFSUniStr255 nameStr;
331
332 result = FSGetVolumeInfo (theVolume,
333 0,
334 NULL,
335 kFSVolInfoFSInfo,
336 NULL,
337 NULL,
338 &rootDirectory);
339
340 if (result != noErr) {
341 SDL_SetError ("ListTrackFiles: FSGetVolumeInfo returned %d", result);
342 return result;
343 }
344
345 result = FSOpenIterator (&rootDirectory, kFSIterateFlat, &iterator);
346 if (result == noErr) {
347 do
348 {
349 result = FSGetCatalogInfoBulk (iterator, 1, &actualObjects,
350 NULL, kFSCatInfoNone, NULL, &ref, NULL, &nameStr);
351 if (result == noErr) {
352
353 CFStringRef name;
354 name = CFStringCreateWithCharacters (NULL, nameStr.unicode, nameStr.length);
355
356 /* Look for .aiff extension */
357 if (CFStringHasSuffix (name, CFSTR(".aiff")) ||
358 CFStringHasSuffix (name, CFSTR(".cdda"))) {
359
360 /* Extract the track id from the filename */
361 int trackID = 0, i = 0;
362 while (i < nameStr.length && !isdigit(nameStr.unicode[i])) {
363 ++i;
364 }
365 while (i < nameStr.length && isdigit(nameStr.unicode[i])) {
366 trackID = 10 * trackID +(nameStr.unicode[i] - '0');
367 ++i;
368 }
369
370 #if DEBUG_CDROM
371 printf("Found AIFF for track %d: '%s'\n", trackID,
372 CFStringGetCStringPtr (name, CFStringGetSystemEncoding()));
373 #endif
374
375 /* Track ID's start at 1, but we want to start at 0 */
376 trackID--;
377
378 assert(0 <= trackID && trackID <= SDL_MAX_TRACKS);
379
380 if (trackID < numTracks)
381 memcpy (&trackFiles[trackID], &ref, sizeof(FSRef));
382 }
383 CFRelease (name);
384 }
385 } while(noErr == result);
386 FSCloseIterator (iterator);
387 }
388
389 return 0;
390}
391
392int LoadFile (const FSRef *ref, int startFrame, int stopFrame)
393{
394 int error = -1;
395
396 if (CheckInit () < 0)
397 goto bail;
398
399 /* release any currently playing file */
400 if (ReleaseFile () < 0)
401 goto bail;
402
403 #if DEBUG_CDROM
404 printf ("LoadFile: %d %d\n", startFrame, stopFrame);
405 #endif
406
407 /*try {*/
408
409 /* create a new player, and attach to the audio unit */
410
411 thePlayer = new_AudioFilePlayer(ref);
412 if (thePlayer == NULL) {
413 SDL_SetError ("LoadFile: Could not create player");
414 return -3; /*throw (-3);*/
415 }
416
417 if (!thePlayer->SetDestination(thePlayer, &theUnit))
418 goto bail;
419
420 if (startFrame >= 0)
421 thePlayer->SetStartFrame (thePlayer, startFrame);
422
423 if (stopFrame >= 0 && stopFrame > startFrame)
424 thePlayer->SetStopFrame (thePlayer, stopFrame);
425
426 /* we set the notifier later */
427 /*thePlayer->SetNotifier(thePlayer, FilePlayNotificationHandler, NULL);*/
428
429 if (!thePlayer->Connect(thePlayer))
430 goto bail;
431
432 #if DEBUG_CDROM
433 thePlayer->Print(thePlayer);
434 fflush (stdout);
435 #endif
436 /*}
437 catch (...)
438 {
439 goto bail;
440 }*/
441
442 error = 0;
443
444 bail:
445 return error;
446}
447
448int ReleaseFile ()
449{
450 int error = -1;
451
452 /* (Don't see any way that the original C++ code could throw here.) --ryan. */
453 /*try {*/
454 if (thePlayer != NULL) {
455
456 thePlayer->Disconnect(thePlayer);
457
458 delete_AudioFilePlayer(thePlayer);
459
460 thePlayer = NULL;
461 }
462 /*}
463 catch (...)
464 {
465 goto bail;
466 }*/
467
468 error = 0;
469
470/* bail: */
471 return error;
472}
473
474int PlayFile ()
475{
476 OSStatus result = -1;
477
478 if (CheckInit () < 0)
479 goto bail;
480
481 /*try {*/
482
483 // start processing of the audio unit
484 result = AudioOutputUnitStart (theUnit);
485 if (result) goto bail; //THROW_RESULT("PlayFile: AudioOutputUnitStart")
486
487 /*}
488 catch (...)
489 {
490 goto bail;
491 }*/
492
493 result = 0;
494
495bail:
496 return result;
497}
498
499int PauseFile ()
500{
501 OSStatus result = -1;
502
503 if (CheckInit () < 0)
504 goto bail;
505
506 /*try {*/
507
508 /* stop processing the audio unit */
509 result = AudioOutputUnitStop (theUnit);
510 if (result) goto bail; /*THROW_RESULT("PauseFile: AudioOutputUnitStop")*/
511 /*}
512 catch (...)
513 {
514 goto bail;
515 }*/
516
517 result = 0;
518bail:
519 return result;
520}
521
522void SetCompletionProc (CDPlayerCompletionProc proc, SDL_CD *cdrom)
523{
524 assert(thePlayer != NULL);
525
526 theCDROM = cdrom;
527 completionProc = proc;
528 thePlayer->SetNotifier (thePlayer, FilePlayNotificationHandler, cdrom);
529}
530
531int GetCurrentFrame ()
532{
533 int frame;
534
535 if (thePlayer == NULL)
536 frame = 0;
537 else
538 frame = thePlayer->GetCurrentFrame (thePlayer);
539
540 return frame;
541}
542
543
544#pragma mark -- Private Functions --
545
546static OSStatus CheckInit ()
547{
548 if (playBackWasInit)
549 return 0;
550
551 OSStatus result = noErr;
552
553 /* Create the callback semaphore */
554 callbackSem = SDL_CreateSemaphore(0);
555
556 /* Start callback thread */
557 SDL_CreateThread(RunCallBackThread, NULL);
558
559 { /*try {*/
560 ComponentDescription desc;
561
562 desc.componentType = kAudioUnitType_Output;
563 desc.componentSubType = kAudioUnitSubType_DefaultOutput;
564 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
565 desc.componentFlags = 0;
566 desc.componentFlagsMask = 0;
567
568 Component comp = FindNextComponent (NULL, &desc);
569 if (comp == NULL) {
570 SDL_SetError ("CheckInit: FindNextComponent returned NULL");
571 if (result) return -1; //throw(internalComponentErr);
572 }
573
574 result = OpenAComponent (comp, &theUnit);
575 if (result) return -1; //THROW_RESULT("CheckInit: OpenAComponent")
576
577 // you need to initialize the output unit before you set it as a destination
578 result = AudioUnitInitialize (theUnit);
579 if (result) return -1; //THROW_RESULT("CheckInit: AudioUnitInitialize")
580
581
582 playBackWasInit = true;
583 }
584 /*catch (...)
585 {
586 return -1;
587 }*/
588
589 return 0;
590}
591
592static void FilePlayNotificationHandler(void * inRefCon, OSStatus inStatus)
593{
594 if (inStatus == kAudioFilePlay_FileIsFinished) {
595
596 /* notify non-CA thread to perform the callback */
597 SDL_SemPost(callbackSem);
598
599 } else if (inStatus == kAudioFilePlayErr_FilePlayUnderrun) {
600
601 SDL_SetError ("CDPlayer Notification: buffer underrun");
602 } else if (inStatus == kAudioFilePlay_PlayerIsUninitialized) {
603
604 SDL_SetError ("CDPlayer Notification: player is uninitialized");
605 } else {
606
607 SDL_SetError ("CDPlayer Notification: unknown error %ld", inStatus);
608 }
609}
610
611static int RunCallBackThread (void *param)
612{
613 for (;;) {
614
615 SDL_SemWait(callbackSem);
616
617 if (completionProc && theCDROM) {
618 #if DEBUG_CDROM
619 printf ("callback!\n");
620 #endif
621 (*completionProc)(theCDROM);
622 } else {
623 #if DEBUG_CDROM
624 printf ("callback?\n");
625 #endif
626 }
627 }
628
629 #if DEBUG_CDROM
630 printf ("thread dying now...\n");
631 #endif
632
633 return 0;
634}
635
636/*}; // extern "C" */
diff --git a/apps/plugins/sdl/src/cdrom/macosx/CDPlayer.h b/apps/plugins/sdl/src/cdrom/macosx/CDPlayer.h
deleted file mode 100644
index be1ac1826a..0000000000
--- a/apps/plugins/sdl/src/cdrom/macosx/CDPlayer.h
+++ /dev/null
@@ -1,69 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __CDPlayer__H__
25#define __CDPlayer__H__ 1
26
27#include <string.h>
28
29#include <Carbon/Carbon.h>
30#include <CoreFoundation/CoreFoundation.h>
31#include <AudioUnit/AudioUnit.h>
32
33#include "SDL.h"
34#include "SDL_thread.h"
35#include "SDL_mutex.h"
36
37#ifdef __cplusplus
38extern "C" {
39#endif
40
41typedef void (*CDPlayerCompletionProc)(SDL_CD *cdrom) ;
42
43void Lock ();
44
45void Unlock();
46
47int LoadFile (const FSRef *ref, int startFrame, int endFrame); /* pass -1 to do nothing */
48
49int ReleaseFile ();
50
51int PlayFile ();
52
53int PauseFile ();
54
55void SetCompletionProc (CDPlayerCompletionProc proc, SDL_CD *cdrom);
56
57int ReadTOCData (FSVolumeRefNum theVolume, SDL_CD *theCD);
58
59int ListTrackFiles (FSVolumeRefNum theVolume, FSRef *trackFiles, int numTracks);
60
61int DetectAudioCDVolumes (FSVolumeRefNum *volumes, int numVolumes);
62
63int GetCurrentFrame ();
64
65#ifdef __cplusplus
66};
67#endif
68
69#endif /* __CD_Player__H__ */
diff --git a/apps/plugins/sdl/src/cdrom/macosx/SDLOSXCAGuard.c b/apps/plugins/sdl/src/cdrom/macosx/SDLOSXCAGuard.c
deleted file mode 100644
index e8caf1bf10..0000000000
--- a/apps/plugins/sdl/src/cdrom/macosx/SDLOSXCAGuard.c
+++ /dev/null
@@ -1,199 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Note: This file hasn't been modified so technically we have to keep the disclaimer :-(
26
27 Copyright: © Copyright 2002 Apple Computer, Inc. All rights reserved.
28
29 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
30 ("Apple") in consideration of your agreement to the following terms, and your
31 use, installation, modification or redistribution of this Apple software
32 constitutes acceptance of these terms. If you do not agree with these terms,
33 please do not use, install, modify or redistribute this Apple software.
34
35 In consideration of your agreement to abide by the following terms, and subject
36 to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs
37 copyrights in this original Apple software (the "Apple Software"), to use,
38 reproduce, modify and redistribute the Apple Software, with or without
39 modifications, in source and/or binary forms; provided that if you redistribute
40 the Apple Software in its entirety and without modifications, you must retain
41 this notice and the following text and disclaimers in all such redistributions of
42 the Apple Software. Neither the name, trademarks, service marks or logos of
43 Apple Computer, Inc. may be used to endorse or promote products derived from the
44 Apple Software without specific prior written permission from Apple. Except as
45 expressly stated in this notice, no other rights or licenses, express or implied,
46 are granted by Apple herein, including but not limited to any patent rights that
47 may be infringed by your derivative works or by other works in which the Apple
48 Software may be incorporated.
49
50 The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
51 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
52 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
53 PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
54 COMBINATION WITH YOUR PRODUCTS.
55
56 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
57 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
58 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
60 OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
61 (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
62 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
63*/
64/*=============================================================================
65 CAGuard.cp
66
67=============================================================================*/
68
69/*=============================================================================
70 Includes
71 =============================================================================*/
72
73/*
74#include <stdio.h>
75#include <stdlib.h>
76#include <string.h>
77*/
78#include "SDL_stdinc.h"
79
80/*#define NDEBUG 1*/
81/*
82#include <assert.h>
83*/
84#define assert(X)
85
86
87#include "SDLOSXCAGuard.h"
88
89/*#warning Need a try-based Locker too*/
90/*=============================================================================
91 SDLOSXCAGuard
92 =============================================================================*/
93
94static int SDLOSXCAGuard_Lock(SDLOSXCAGuard *cag)
95{
96 int theAnswer = 0;
97
98 if(pthread_self() != cag->mOwner)
99 {
100 OSStatus theError = pthread_mutex_lock(&cag->mMutex);
101 (void)theError;
102 assert(theError == 0);
103 cag->mOwner = pthread_self();
104 theAnswer = 1;
105 }
106
107 return theAnswer;
108}
109
110static void SDLOSXCAGuard_Unlock(SDLOSXCAGuard *cag)
111{
112 OSStatus theError;
113 assert(pthread_self() == cag->mOwner);
114
115 cag->mOwner = 0;
116 theError = pthread_mutex_unlock(&cag->mMutex);
117 (void)theError;
118 assert(theError == 0);
119}
120
121static int SDLOSXCAGuard_Try (SDLOSXCAGuard *cag, int *outWasLocked)
122{
123 int theAnswer = 0;
124 *outWasLocked = 0;
125
126 if (pthread_self() == cag->mOwner) {
127 theAnswer = 1;
128 *outWasLocked = 0;
129 } else {
130 OSStatus theError = pthread_mutex_trylock(&cag->mMutex);
131 if (theError == 0) {
132 cag->mOwner = pthread_self();
133 theAnswer = 1;
134 *outWasLocked = 1;
135 }
136 }
137
138 return theAnswer;
139}
140
141static void SDLOSXCAGuard_Wait(SDLOSXCAGuard *cag)
142{
143 OSStatus theError;
144 assert(pthread_self() == cag->mOwner);
145
146 cag->mOwner = 0;
147
148 theError = pthread_cond_wait(&cag->mCondVar, &cag->mMutex);
149 (void)theError;
150 assert(theError == 0);
151 cag->mOwner = pthread_self();
152}
153
154static void SDLOSXCAGuard_Notify(SDLOSXCAGuard *cag)
155{
156 OSStatus theError = pthread_cond_signal(&cag->mCondVar);
157 (void)theError;
158 assert(theError == 0);
159}
160
161
162SDLOSXCAGuard *new_SDLOSXCAGuard(void)
163{
164 OSStatus theError;
165 SDLOSXCAGuard *cag = (SDLOSXCAGuard *) SDL_malloc(sizeof (SDLOSXCAGuard));
166 if (cag == NULL)
167 return NULL;
168 SDL_memset(cag, '\0', sizeof (*cag));
169
170 #define SET_SDLOSXCAGUARD_METHOD(m) cag->m = SDLOSXCAGuard_##m
171 SET_SDLOSXCAGUARD_METHOD(Lock);
172 SET_SDLOSXCAGUARD_METHOD(Unlock);
173 SET_SDLOSXCAGUARD_METHOD(Try);
174 SET_SDLOSXCAGUARD_METHOD(Wait);
175 SET_SDLOSXCAGUARD_METHOD(Notify);
176 #undef SET_SDLOSXCAGUARD_METHOD
177
178 theError = pthread_mutex_init(&cag->mMutex, NULL);
179 (void)theError;
180 assert(theError == 0);
181
182 theError = pthread_cond_init(&cag->mCondVar, NULL);
183 (void)theError;
184 assert(theError == 0);
185
186 cag->mOwner = 0;
187 return cag;
188}
189
190void delete_SDLOSXCAGuard(SDLOSXCAGuard *cag)
191{
192 if (cag != NULL)
193 {
194 pthread_mutex_destroy(&cag->mMutex);
195 pthread_cond_destroy(&cag->mCondVar);
196 SDL_free(cag);
197 }
198}
199
diff --git a/apps/plugins/sdl/src/cdrom/macosx/SDLOSXCAGuard.h b/apps/plugins/sdl/src/cdrom/macosx/SDLOSXCAGuard.h
deleted file mode 100644
index f22c6956fe..0000000000
--- a/apps/plugins/sdl/src/cdrom/macosx/SDLOSXCAGuard.h
+++ /dev/null
@@ -1,116 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Note: This file hasn't been modified so technically we have to keep the disclaimer :-(
26
27
28 Copyright: © Copyright 2002 Apple Computer, Inc. All rights reserved.
29
30 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
31 ("Apple") in consideration of your agreement to the following terms, and your
32 use, installation, modification or redistribution of this Apple software
33 constitutes acceptance of these terms. If you do not agree with these terms,
34 please do not use, install, modify or redistribute this Apple software.
35
36 In consideration of your agreement to abide by the following terms, and subject
37 to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs
38 copyrights in this original Apple software (the "Apple Software"), to use,
39 reproduce, modify and redistribute the Apple Software, with or without
40 modifications, in source and/or binary forms; provided that if you redistribute
41 the Apple Software in its entirety and without modifications, you must retain
42 this notice and the following text and disclaimers in all such redistributions of
43 the Apple Software. Neither the name, trademarks, service marks or logos of
44 Apple Computer, Inc. may be used to endorse or promote products derived from the
45 Apple Software without specific prior written permission from Apple. Except as
46 expressly stated in this notice, no other rights or licenses, express or implied,
47 are granted by Apple herein, including but not limited to any patent rights that
48 may be infringed by your derivative works or by other works in which the Apple
49 Software may be incorporated.
50
51 The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
52 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
53 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
54 PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
55 COMBINATION WITH YOUR PRODUCTS.
56
57 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
58 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
59 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
61 OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
62 (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
63 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64*/
65/*=============================================================================
66 CAGuard.h
67
68=============================================================================*/
69#if !defined(__CAGuard_h__)
70#define __CAGuard_h__
71
72/*=============================================================================
73 Includes
74 =============================================================================*/
75
76#include <CoreAudio/CoreAudioTypes.h>
77#include <pthread.h>
78
79
80/*=============================================================================
81 CAGuard
82
83 This is your typical mutex with signalling implemented via pthreads.
84 Lock() will return true if and only if the guard is locked on that call.
85 A thread that already has the guard will receive 'false' if it locks it
86 again. Use of the stack-based CAGuard::Locker class is highly recommended
87 to properly manage the recursive nesting. The Wait calls with timeouts
88 will return true if and only if the timeout period expired. They will
89 return false if they receive notification any other way.
90 =============================================================================*/
91
92typedef struct S_SDLOSXCAGuard
93{
94
95/* Construction/Destruction */
96/*public:*/
97/* Actions */
98/*public:*/
99 int (*Lock)(struct S_SDLOSXCAGuard *cag);
100 void (*Unlock)(struct S_SDLOSXCAGuard *cag);
101 int (*Try)(struct S_SDLOSXCAGuard *cag, int *outWasLocked); /* returns true if lock is free, false if not */
102 void (*Wait)(struct S_SDLOSXCAGuard *cag);
103 void (*Notify)(struct S_SDLOSXCAGuard *cag);
104
105/* Implementation */
106/*protected:*/
107 pthread_mutex_t mMutex;
108 pthread_cond_t mCondVar;
109 pthread_t mOwner;
110} SDLOSXCAGuard;
111
112SDLOSXCAGuard *new_SDLOSXCAGuard(void);
113void delete_SDLOSXCAGuard(SDLOSXCAGuard *cag);
114
115#endif
116
diff --git a/apps/plugins/sdl/src/cdrom/macosx/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/macosx/SDL_syscdrom.c
deleted file mode 100644
index 5018750222..0000000000
--- a/apps/plugins/sdl/src/cdrom/macosx/SDL_syscdrom.c
+++ /dev/null
@@ -1,514 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_MACOSX
25
26#include "SDL_syscdrom_c.h"
27
28#pragma mark -- Globals --
29
30static FSRef** tracks;
31static FSVolumeRefNum* volumes;
32static CDstatus status;
33static int nextTrackFrame;
34static int nextTrackFramesRemaining;
35static int fakeCD;
36static int currentTrack;
37static int didReadTOC;
38static int cacheTOCNumTracks;
39static int currentDrive; /* Only allow 1 drive in use at a time */
40
41#pragma mark -- Prototypes --
42
43static const char *SDL_SYS_CDName (int drive);
44static int SDL_SYS_CDOpen (int drive);
45static int SDL_SYS_CDGetTOC (SDL_CD *cdrom);
46static CDstatus SDL_SYS_CDStatus (SDL_CD *cdrom, int *position);
47static int SDL_SYS_CDPlay (SDL_CD *cdrom, int start, int length);
48static int SDL_SYS_CDPause (SDL_CD *cdrom);
49static int SDL_SYS_CDResume (SDL_CD *cdrom);
50static int SDL_SYS_CDStop (SDL_CD *cdrom);
51static int SDL_SYS_CDEject (SDL_CD *cdrom);
52static void SDL_SYS_CDClose (SDL_CD *cdrom);
53
54#pragma mark -- Helper Functions --
55
56/* Read a list of tracks from the volume */
57static int LoadTracks (SDL_CD *cdrom)
58{
59 /* Check if tracks are already loaded */
60 if ( tracks[cdrom->id] != NULL )
61 return 0;
62
63 /* Allocate memory for tracks */
64 tracks[cdrom->id] = (FSRef*) SDL_calloc (1, sizeof(**tracks) * cdrom->numtracks);
65 if (tracks[cdrom->id] == NULL) {
66 SDL_OutOfMemory ();
67 return -1;
68 }
69
70 /* Load tracks */
71 if (ListTrackFiles (volumes[cdrom->id], tracks[cdrom->id], cdrom->numtracks) < 0)
72 return -1;
73
74 return 0;
75}
76
77/* Find a file for a given start frame and length */
78static FSRef* GetFileForOffset (SDL_CD *cdrom, int start, int length, int *outStartFrame, int *outStopFrame)
79{
80 int i;
81
82 for (i = 0; i < cdrom->numtracks; i++) {
83
84 if (cdrom->track[i].offset <= start &&
85 start < (cdrom->track[i].offset + cdrom->track[i].length))
86 break;
87 }
88
89 if (i == cdrom->numtracks)
90 return NULL;
91
92 currentTrack = i;
93
94 *outStartFrame = start - cdrom->track[i].offset;
95
96 if ((*outStartFrame + length) < cdrom->track[i].length) {
97 *outStopFrame = *outStartFrame + length;
98 length = 0;
99 nextTrackFrame = -1;
100 nextTrackFramesRemaining = -1;
101 }
102 else {
103 *outStopFrame = -1;
104 length -= cdrom->track[i].length - *outStartFrame;
105 nextTrackFrame = cdrom->track[i+1].offset;
106 nextTrackFramesRemaining = length;
107 }
108
109 return &tracks[cdrom->id][i];
110}
111
112/* Setup another file for playback, or stop playback (called from another thread) */
113static void CompletionProc (SDL_CD *cdrom)
114{
115
116 Lock ();
117
118 if (nextTrackFrame > 0 && nextTrackFramesRemaining > 0) {
119
120 /* Load the next file to play */
121 int startFrame, stopFrame;
122 FSRef *file;
123
124 PauseFile ();
125 ReleaseFile ();
126
127 file = GetFileForOffset (cdrom, nextTrackFrame,
128 nextTrackFramesRemaining, &startFrame, &stopFrame);
129
130 if (file == NULL) {
131 status = CD_STOPPED;
132 Unlock ();
133 return;
134 }
135
136 LoadFile (file, startFrame, stopFrame);
137
138 SetCompletionProc (CompletionProc, cdrom);
139
140 PlayFile ();
141 }
142 else {
143
144 /* Release the current file */
145 PauseFile ();
146 ReleaseFile ();
147 status = CD_STOPPED;
148 }
149
150 Unlock ();
151}
152
153
154#pragma mark -- Driver Functions --
155
156/* Initialize */
157int SDL_SYS_CDInit (void)
158{
159 /* Initialize globals */
160 volumes = NULL;
161 tracks = NULL;
162 status = CD_STOPPED;
163 nextTrackFrame = -1;
164 nextTrackFramesRemaining = -1;
165 fakeCD = SDL_FALSE;
166 currentTrack = -1;
167 didReadTOC = SDL_FALSE;
168 cacheTOCNumTracks = -1;
169 currentDrive = -1;
170
171 /* Fill in function pointers */
172 SDL_CDcaps.Name = SDL_SYS_CDName;
173 SDL_CDcaps.Open = SDL_SYS_CDOpen;
174 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
175 SDL_CDcaps.Status = SDL_SYS_CDStatus;
176 SDL_CDcaps.Play = SDL_SYS_CDPlay;
177 SDL_CDcaps.Pause = SDL_SYS_CDPause;
178 SDL_CDcaps.Resume = SDL_SYS_CDResume;
179 SDL_CDcaps.Stop = SDL_SYS_CDStop;
180 SDL_CDcaps.Eject = SDL_SYS_CDEject;
181 SDL_CDcaps.Close = SDL_SYS_CDClose;
182
183 /*
184 Read the list of "drives"
185
186 This is currently a hack that infers drives from
187 mounted audio CD volumes, rather than
188 actual CD-ROM devices - which means it may not
189 act as expected sometimes.
190 */
191
192 /* Find out how many cd volumes are mounted */
193 SDL_numcds = DetectAudioCDVolumes (NULL, 0);
194
195 /*
196 If there are no volumes, fake a cd device
197 so tray empty can be reported.
198 */
199 if (SDL_numcds == 0) {
200
201 fakeCD = SDL_TRUE;
202 SDL_numcds = 1;
203 status = CD_TRAYEMPTY;
204
205 return 0;
206 }
207
208 /* Allocate space for volumes */
209 volumes = (FSVolumeRefNum*) SDL_calloc (1, sizeof(*volumes) * SDL_numcds);
210 if (volumes == NULL) {
211 SDL_OutOfMemory ();
212 return -1;
213 }
214
215 /* Allocate space for tracks */
216 tracks = (FSRef**) SDL_calloc (1, sizeof(*tracks) * (SDL_numcds + 1));
217 if (tracks == NULL) {
218 SDL_OutOfMemory ();
219 return -1;
220 }
221
222 /* Mark the end of the tracks array */
223 tracks[ SDL_numcds ] = (FSRef*)-1;
224
225 /*
226 Redetect, now save all volumes for later
227 Update SDL_numcds just in case it changed
228 */
229 {
230 int numVolumes = SDL_numcds;
231
232 SDL_numcds = DetectAudioCDVolumes (volumes, numVolumes);
233
234 /* If more cds suddenly show up, ignore them */
235 if (SDL_numcds > numVolumes) {
236 SDL_SetError ("Some CD's were added but they will be ignored");
237 SDL_numcds = numVolumes;
238 }
239 }
240
241 return 0;
242}
243
244/* Shutdown and cleanup */
245void SDL_SYS_CDQuit(void)
246{
247 ReleaseFile();
248
249 if (volumes != NULL)
250 free (volumes);
251
252 if (tracks != NULL) {
253
254 FSRef **ptr;
255 for (ptr = tracks; *ptr != (FSRef*)-1; ptr++)
256 if (*ptr != NULL)
257 free (*ptr);
258
259 free (tracks);
260 }
261}
262
263/* Get the Unix disk name of the volume */
264static const char *SDL_SYS_CDName (int drive)
265{
266 /*
267 * !!! FIXME: PBHGetVolParmsSync() is gone in 10.6,
268 * !!! FIXME: replaced with FSGetVolumeParms(), which
269 * !!! FIXME: isn't available before 10.5. :/
270 */
271 return "Mac OS X CD-ROM Device";
272
273#if 0
274 OSStatus err = noErr;
275 HParamBlockRec pb;
276 GetVolParmsInfoBuffer volParmsInfo;
277
278 if (fakeCD)
279 return "Fake CD-ROM Device";
280
281 pb.ioParam.ioNamePtr = NULL;
282 pb.ioParam.ioVRefNum = volumes[drive];
283 pb.ioParam.ioBuffer = (Ptr)&volParmsInfo;
284 pb.ioParam.ioReqCount = (SInt32)sizeof(volParmsInfo);
285 err = PBHGetVolParmsSync(&pb);
286
287 if (err != noErr) {
288 SDL_SetError ("PBHGetVolParmsSync returned %d", err);
289 return NULL;
290 }
291
292 return volParmsInfo.vMDeviceID;
293#endif
294}
295
296/* Open the "device" */
297static int SDL_SYS_CDOpen (int drive)
298{
299 /* Only allow 1 device to be open */
300 if (currentDrive >= 0) {
301 SDL_SetError ("Only one cdrom is supported");
302 return -1;
303 }
304 else
305 currentDrive = drive;
306
307 return drive;
308}
309
310/* Get the table of contents */
311static int SDL_SYS_CDGetTOC (SDL_CD *cdrom)
312{
313 if (fakeCD) {
314 SDL_SetError (kErrorFakeDevice);
315 return -1;
316 }
317
318 if (didReadTOC) {
319 cdrom->numtracks = cacheTOCNumTracks;
320 return 0;
321 }
322
323
324 ReadTOCData (volumes[cdrom->id], cdrom);
325 didReadTOC = SDL_TRUE;
326 cacheTOCNumTracks = cdrom->numtracks;
327
328 return 0;
329}
330
331/* Get CD-ROM status */
332static CDstatus SDL_SYS_CDStatus (SDL_CD *cdrom, int *position)
333{
334 if (position) {
335 int trackFrame;
336
337 Lock ();
338 trackFrame = GetCurrentFrame ();
339 Unlock ();
340
341 *position = cdrom->track[currentTrack].offset + trackFrame;
342 }
343
344 return status;
345}
346
347/* Start playback */
348static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
349{
350 int startFrame, stopFrame;
351 FSRef *ref;
352
353 if (fakeCD) {
354 SDL_SetError (kErrorFakeDevice);
355 return -1;
356 }
357
358 Lock();
359
360 if (LoadTracks (cdrom) < 0)
361 return -2;
362
363 if (PauseFile () < 0)
364 return -3;
365
366 if (ReleaseFile () < 0)
367 return -4;
368
369 ref = GetFileForOffset (cdrom, start, length, &startFrame, &stopFrame);
370 if (ref == NULL) {
371 SDL_SetError ("SDL_SYS_CDPlay: No file for start=%d, length=%d", start, length);
372 return -5;
373 }
374
375 if (LoadFile (ref, startFrame, stopFrame) < 0)
376 return -6;
377
378 SetCompletionProc (CompletionProc, cdrom);
379
380 if (PlayFile () < 0)
381 return -7;
382
383 status = CD_PLAYING;
384
385 Unlock();
386
387 return 0;
388}
389
390/* Pause playback */
391static int SDL_SYS_CDPause(SDL_CD *cdrom)
392{
393 if (fakeCD) {
394 SDL_SetError (kErrorFakeDevice);
395 return -1;
396 }
397
398 Lock ();
399
400 if (PauseFile () < 0) {
401 Unlock ();
402 return -2;
403 }
404
405 status = CD_PAUSED;
406
407 Unlock ();
408
409 return 0;
410}
411
412/* Resume playback */
413static int SDL_SYS_CDResume(SDL_CD *cdrom)
414{
415 if (fakeCD) {
416 SDL_SetError (kErrorFakeDevice);
417 return -1;
418 }
419
420 Lock ();
421
422 if (PlayFile () < 0) {
423 Unlock ();
424 return -2;
425 }
426
427 status = CD_PLAYING;
428
429 Unlock ();
430
431 return 0;
432}
433
434/* Stop playback */
435static int SDL_SYS_CDStop(SDL_CD *cdrom)
436{
437 if (fakeCD) {
438 SDL_SetError (kErrorFakeDevice);
439 return -1;
440 }
441
442 Lock ();
443
444 if (PauseFile () < 0) {
445 Unlock ();
446 return -2;
447 }
448
449 if (ReleaseFile () < 0) {
450 Unlock ();
451 return -3;
452 }
453
454 status = CD_STOPPED;
455
456 Unlock ();
457
458 return 0;
459}
460
461/* Eject the CD-ROM (Unmount the volume) */
462static int SDL_SYS_CDEject(SDL_CD *cdrom)
463{
464 OSStatus err;
465 pid_t dissenter;
466
467 if (fakeCD) {
468 SDL_SetError (kErrorFakeDevice);
469 return -1;
470 }
471
472 Lock ();
473
474 if (PauseFile () < 0) {
475 Unlock ();
476 return -2;
477 }
478
479 if (ReleaseFile () < 0) {
480 Unlock ();
481 return -3;
482 }
483
484 status = CD_STOPPED;
485
486 /* Eject the volume */
487 err = FSEjectVolumeSync(volumes[cdrom->id], kNilOptions, &dissenter);
488
489 if (err != noErr) {
490 Unlock ();
491 SDL_SetError ("PBUnmountVol returned %d", err);
492 return -4;
493 }
494
495 status = CD_TRAYEMPTY;
496
497 /* Invalidate volume and track info */
498 volumes[cdrom->id] = 0;
499 free (tracks[cdrom->id]);
500 tracks[cdrom->id] = NULL;
501
502 Unlock ();
503
504 return 0;
505}
506
507/* Close the CD-ROM */
508static void SDL_SYS_CDClose(SDL_CD *cdrom)
509{
510 currentDrive = -1;
511 return;
512}
513
514#endif /* SDL_CDROM_MACOSX */
diff --git a/apps/plugins/sdl/src/cdrom/macosx/SDL_syscdrom_c.h b/apps/plugins/sdl/src/cdrom/macosx/SDL_syscdrom_c.h
deleted file mode 100644
index 589c5897e6..0000000000
--- a/apps/plugins/sdl/src/cdrom/macosx/SDL_syscdrom_c.h
+++ /dev/null
@@ -1,136 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the Mac OS X / CoreAudio specific header for the SDL CD-ROM API
25 Contributed by Darrell Walisser and Max Horn
26 */
27
28/***********************************************************************************
29 Implementation Notes
30 *********************
31
32 This code has several limitations currently (all of which are proabaly fixable):
33
34 1. A CD-ROM device is inferred from a mounted cdfs volume, so device 0 is
35 not necessarily the first CD-ROM device on the system. (Somewhat easy to fix
36 by useing the device name from the volume id's to reorder the volumes)
37
38 2. You can only open and control 1 CD-ROM device at a time. (Challenging to fix,
39 due to extensive code restructuring)
40
41 3. The status reported by SDL_CDStatus only changes to from CD_PLAYING to CD_STOPPED in
42 1-second intervals (because the audio is buffered in 1-second chunks) If
43 the audio data is less than 1 second, the remainder is filled with silence.
44
45 If you need to play sequences back-to-back that are less that 1 second long,
46 use the frame position to determine when to play the next sequence, instead
47 of SDL_CDStatus.
48
49 This may be possible to fix with a clever usage of the AudioUnit API.
50
51 4. When new volumes are inserted, our volume information is not updated. The only way
52 to refresh this information is to reinit the CD-ROM subsystem of SDL. To fix this,
53 one would probably have to fix point 1 above first, then figure out how to register
54 for a notification when new media is mounted in order to perform an automatic
55 rescan for cdfs volumes.
56
57
58
59 So, here comes a description of how this all works.
60
61 < Initializing >
62
63 To get things rolling, we have to locate mounted volumes that contain
64 audio (since nearly all Macs don't have analog audio-in on the sound card).
65 That's easy, since these volumes have a flag that indicates this special
66 filesystem. See DetectAudioCDVolumes() in CDPlayer.cpp for this code.
67
68 Next, we parse the invisible .TOC.plist in the root of the volume, which gets us
69 the track information (number, offset, length, leadout, etc). See ReadTOCData() in
70 CDPlayer.cpp for the skinny on this.
71
72
73 < The Playback Loop >
74
75 Now come the tricky parts. Let's start with basic audio playback. When a frame
76 range to play is requested, we must first find the .aiff files on the volume,
77 hopefully in the right order. Since these files all begin with a number "1 Audio Track",
78 etc, this is used to determine the correct track order.
79
80 Once all files are determined, we have to find what file corresponds to the start
81 and length parameter to SDL_SYS_CDPlay(). Again, this is quite simple by walking the
82 cdrom's track list. At this point, we also save the offset to the next track and frames
83 remaining, if we're going to have to play another file after the first one. See
84 GetFileForOffset() for this code.
85
86 At this point we have all info needed to start playback, so we hand off to the LoadFile()
87 function, which proceeds to do its magic and plays back the file.
88
89 When the file is finished playing, CompletionProc() is invoked, at which time we can
90 play the next file if the previously saved next track and frames remaining
91 indicates that we should.
92
93
94 < Magic >
95
96 OK, so it's not really magic, but since I don't fully understand all the hidden details it
97 seems like it to me ;-) The API's involved are the AudioUnit and AudioFile API's. These
98 appear to be an extension of CoreAudio for creating modular playback and f/x entities.
99 The important thing is that CPU usage is very low and reliability is very high. You'd
100 be hard-pressed to find a way to stutter the playback with other CPU-intensive tasks.
101
102 One part of this magic is that it uses multiple threads, which carries the usual potential
103 for disaster if not handled carefully. Playback currently requires 4 additional threads:
104 1. The coreaudio runloop thread
105 2. The coreaudio device i/o thread
106 3. The file streaming thread
107 4. The notification/callback thread
108
109 The first 2 threads are necessary evil - CoreAudio creates this no matter what the situation
110 is (even the SDL sound implementation creates theses suckers). The last two are are created
111 by us.
112
113 The file is streamed from disk using a threaded double-buffer approach.
114 This way, the high latency operation of reading from disk can be performed without interrupting
115 the real-time device thread (which amounts to avoiding dropouts). The device thread grabs the
116 buffer that isn't being read and sends it to the CoreAudio mixer where it eventually gets
117 to the sound card.
118
119 The device thread posts a notification when the file streaming thread is out of data. This
120 notification must be handled in a separate thread to avoid potential deadlock in the
121 device thread. That's where the notification thread comes in. This thread is signaled
122 whenever a notification needs to be processed, so another file can be played back if need be.
123
124 The API in CDPlayer.cpp contains synchronization because otherwise both the notification thread
125 and main thread (or another other thread using the SDL CD api) can potentially call it at the same time.
126
127************************************************************************************/
128
129
130#include "SDL_cdrom.h"
131#include "../SDL_syscdrom.h"
132
133#include "CDPlayer.h"
134
135#define kErrorFakeDevice "Error: Cannot proceed since we're faking a CD-ROM device. Reinit the CD-ROM subsystem to scan for new volumes."
136
diff --git a/apps/plugins/sdl/src/cdrom/mint/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/mint/SDL_syscdrom.c
deleted file mode 100644
index 0bc10edb72..0000000000
--- a/apps/plugins/sdl/src/cdrom/mint/SDL_syscdrom.c
+++ /dev/null
@@ -1,317 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_MINT
25
26/*
27 Atari MetaDOS CD-ROM functions
28
29 Patrice Mandin
30*/
31
32#include <errno.h>
33
34#include <mint/cdromio.h>
35#include <mint/metados.h>
36
37#include "SDL_cdrom.h"
38#include "../SDL_syscdrom.h"
39
40/* Some ioctl() errno values which occur when the tray is empty */
41#ifndef ENOMEDIUM
42#define ENOMEDIUM ENOENT
43#endif
44#define ERRNO_TRAYEMPTY(errno) \
45 ((errno == EIO) || (errno == ENOENT) || \
46 (errno == EINVAL) || (errno == ENOMEDIUM))
47
48/* The maximum number of CD-ROM drives we'll detect */
49#define MAX_DRIVES 32
50
51typedef struct {
52 char device[3]; /* Physical device letter + ':' + '\0' */
53 metaopen_t metaopen; /* Infos on opened drive */
54} metados_drive_t;
55
56static metados_drive_t metados_drives[MAX_DRIVES];
57
58/* The system-dependent CD control functions */
59static const char *SDL_SYS_CDName(int drive);
60static int SDL_SYS_CDOpen(int drive);
61static void SDL_SYS_CDClose(SDL_CD *cdrom);
62static int SDL_SYS_CDioctl(int id, int command, void *arg);
63static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
64static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
65static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
66static int SDL_SYS_CDPause(SDL_CD *cdrom);
67static int SDL_SYS_CDResume(SDL_CD *cdrom);
68static int SDL_SYS_CDStop(SDL_CD *cdrom);
69static int SDL_SYS_CDEject(SDL_CD *cdrom);
70
71int SDL_SYS_CDInit(void)
72{
73 metainit_t metainit={0,0,0,0};
74 metaopen_t metaopen;
75 int i, handle;
76 struct cdrom_subchnl info;
77
78 Metainit(&metainit);
79 if (metainit.version == NULL) {
80#ifdef DEBUG_CDROM
81 fprintf(stderr, "MetaDOS not installed\n");
82#endif
83 return -1;
84 }
85
86 if (metainit.drives_map == 0) {
87#ifdef DEBUG_CDROM
88 fprintf(stderr, "No MetaDOS devices present\n");
89#endif
90 return -1;
91 }
92
93 SDL_numcds = 0;
94
95 for (i='A'; i<='Z'; i++) {
96 metados_drives[SDL_numcds].device[0] = 0;
97 metados_drives[SDL_numcds].device[1] = ':';
98 metados_drives[SDL_numcds].device[2] = 0;
99
100 if (metainit.drives_map & (1<<(i-'A'))) {
101 handle = Metaopen(i, &metaopen);
102 if (handle == 0) {
103
104 info.cdsc_format = CDROM_MSF;
105 if ( (Metaioctl(i, METADOS_IOCTL_MAGIC, CDROMSUBCHNL, &info) == 0) || ERRNO_TRAYEMPTY(errno) ) {
106 metados_drives[SDL_numcds].device[0] = i;
107 ++SDL_numcds;
108 }
109
110 Metaclose(i);
111 }
112 }
113 }
114
115 /* Fill in our driver capabilities */
116 SDL_CDcaps.Name = SDL_SYS_CDName;
117 SDL_CDcaps.Open = SDL_SYS_CDOpen;
118 SDL_CDcaps.Close = SDL_SYS_CDClose;
119
120 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
121 SDL_CDcaps.Status = SDL_SYS_CDStatus;
122 SDL_CDcaps.Play = SDL_SYS_CDPlay;
123 SDL_CDcaps.Pause = SDL_SYS_CDPause;
124 SDL_CDcaps.Resume = SDL_SYS_CDResume;
125 SDL_CDcaps.Stop = SDL_SYS_CDStop;
126 SDL_CDcaps.Eject = SDL_SYS_CDEject;
127
128 return 0;
129}
130
131void SDL_SYS_CDQuit(void)
132{
133 SDL_numcds = 0;
134}
135
136static const char *SDL_SYS_CDName(int drive)
137{
138 return(metados_drives[drive].device);
139}
140
141static int SDL_SYS_CDOpen(int drive)
142{
143 int handle;
144
145 handle = Metaopen(metados_drives[drive].device[0], &(metados_drives[drive].metaopen));
146 if (handle == 0) {
147 return drive;
148 }
149
150 return -1;
151}
152
153static void SDL_SYS_CDClose(SDL_CD *cdrom)
154{
155 Metaclose(metados_drives[cdrom->id].device[0]);
156}
157
158static int SDL_SYS_CDioctl(int id, int command, void *arg)
159{
160 int retval;
161
162 retval = Metaioctl(metados_drives[id].device[0], METADOS_IOCTL_MAGIC, command, arg);
163 if ( retval < 0 ) {
164 SDL_SetError("ioctl() error: %s", strerror(errno));
165 }
166 return(retval);
167}
168
169static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
170{
171 int i,okay;
172 struct cdrom_tochdr toc;
173 struct cdrom_tocentry entry;
174
175 /* Use standard ioctl() */
176 if (SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCHDR, &toc)<0) {
177 return -1;
178 }
179
180 cdrom->numtracks = toc.cdth_trk1-toc.cdth_trk0+1;
181 if ( cdrom->numtracks > SDL_MAX_TRACKS ) {
182 cdrom->numtracks = SDL_MAX_TRACKS;
183 }
184
185 /* Read all the track TOC entries */
186 okay=1;
187 for ( i=0; i<=cdrom->numtracks; ++i ) {
188 if ( i == cdrom->numtracks ) {
189 cdrom->track[i].id = CDROM_LEADOUT;
190 } else {
191 cdrom->track[i].id = toc.cdth_trk0+i;
192 }
193 entry.cdte_track = cdrom->track[i].id;
194 entry.cdte_format = CDROM_MSF;
195 if ( SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCENTRY, &entry) < 0 ) {
196 okay=0;
197 break;
198 } else {
199 if ( entry.cdte_ctrl & CDROM_DATA_TRACK ) {
200 cdrom->track[i].type = SDL_DATA_TRACK;
201 } else {
202 cdrom->track[i].type = SDL_AUDIO_TRACK;
203 }
204 cdrom->track[i].offset = MSF_TO_FRAMES(
205 entry.cdte_addr.msf.minute,
206 entry.cdte_addr.msf.second,
207 entry.cdte_addr.msf.frame);
208 cdrom->track[i].length = 0;
209 if ( i > 0 ) {
210 cdrom->track[i-1].length = cdrom->track[i].offset-cdrom->track[i-1].offset;
211 }
212 }
213 }
214
215 return(okay ? 0 : -1);
216}
217
218/* Get CD-ROM status */
219static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
220{
221 CDstatus status;
222 struct cdrom_tochdr toc;
223 struct cdrom_subchnl info;
224
225 info.cdsc_format = CDROM_MSF;
226 if ( SDL_SYS_CDioctl(cdrom->id, CDROMSUBCHNL, &info) < 0 ) {
227 if ( ERRNO_TRAYEMPTY(errno) ) {
228 status = CD_TRAYEMPTY;
229 } else {
230 status = CD_ERROR;
231 }
232 } else {
233 switch (info.cdsc_audiostatus) {
234 case CDROM_AUDIO_INVALID:
235 case CDROM_AUDIO_NO_STATUS:
236 /* Try to determine if there's a CD available */
237 if (SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCHDR, &toc)==0) {
238 status = CD_STOPPED;
239 } else {
240 status = CD_TRAYEMPTY;
241 }
242 break;
243 case CDROM_AUDIO_COMPLETED:
244 status = CD_STOPPED;
245 break;
246 case CDROM_AUDIO_PLAY:
247 status = CD_PLAYING;
248 break;
249 case CDROM_AUDIO_PAUSED:
250 /* Workaround buggy CD-ROM drive */
251 if ( info.cdsc_trk == CDROM_LEADOUT ) {
252 status = CD_STOPPED;
253 } else {
254 status = CD_PAUSED;
255 }
256 break;
257 default:
258 status = CD_ERROR;
259 break;
260 }
261 }
262 if ( position ) {
263 if ( status == CD_PLAYING || (status == CD_PAUSED) ) {
264 *position = MSF_TO_FRAMES(
265 info.cdsc_absaddr.msf.minute,
266 info.cdsc_absaddr.msf.second,
267 info.cdsc_absaddr.msf.frame);
268 } else {
269 *position = 0;
270 }
271 }
272 return(status);
273}
274
275/* Start play */
276static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
277{
278 struct cdrom_msf playtime;
279
280 FRAMES_TO_MSF(start,
281 &playtime.cdmsf_min0, &playtime.cdmsf_sec0, &playtime.cdmsf_frame0);
282 FRAMES_TO_MSF(start+length,
283 &playtime.cdmsf_min1, &playtime.cdmsf_sec1, &playtime.cdmsf_frame1);
284#ifdef DEBUG_CDROM
285 fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n",
286 playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0,
287 playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1);
288#endif
289
290 return SDL_SYS_CDioctl(cdrom->id, CDROMPLAYMSF, &playtime);
291}
292
293/* Pause play */
294static int SDL_SYS_CDPause(SDL_CD *cdrom)
295{
296 return SDL_SYS_CDioctl(cdrom->id, CDROMPAUSE, 0);
297}
298
299/* Resume play */
300static int SDL_SYS_CDResume(SDL_CD *cdrom)
301{
302 return SDL_SYS_CDioctl(cdrom->id, CDROMRESUME, 0);
303}
304
305/* Stop play */
306static int SDL_SYS_CDStop(SDL_CD *cdrom)
307{
308 return SDL_SYS_CDioctl(cdrom->id, CDROMSTOP, 0);
309}
310
311/* Eject the CD-ROM */
312static int SDL_SYS_CDEject(SDL_CD *cdrom)
313{
314 return SDL_SYS_CDioctl(cdrom->id, CDROMEJECT, 0);
315}
316
317#endif /* SDL_CDROM_MINT */
diff --git a/apps/plugins/sdl/src/cdrom/openbsd/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/openbsd/SDL_syscdrom.c
deleted file mode 100644
index e4d03a6a37..0000000000
--- a/apps/plugins/sdl/src/cdrom/openbsd/SDL_syscdrom.c
+++ /dev/null
@@ -1,416 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_OPENBSD
25
26/* Functions for system-level CD-ROM audio control */
27
28#include <sys/types.h>
29#include <sys/ioctl.h>
30#include <sys/stat.h>
31#include <fcntl.h>
32#include <errno.h>
33#include <unistd.h>
34#include <sys/ioctl.h>
35#include <sys/cdio.h>
36
37#include "SDL_cdrom.h"
38#include "../SDL_syscdrom.h"
39
40
41/* The maximum number of CD-ROM drives we'll detect */
42#define MAX_DRIVES 16
43
44/* A list of available CD-ROM drives */
45static char *SDL_cdlist[MAX_DRIVES];
46static dev_t SDL_cdmode[MAX_DRIVES];
47
48/* The system-dependent CD control functions */
49static const char *SDL_SYS_CDName(int drive);
50static int SDL_SYS_CDOpen(int drive);
51static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
52static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
53static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
54static int SDL_SYS_CDPause(SDL_CD *cdrom);
55static int SDL_SYS_CDResume(SDL_CD *cdrom);
56static int SDL_SYS_CDStop(SDL_CD *cdrom);
57static int SDL_SYS_CDEject(SDL_CD *cdrom);
58static void SDL_SYS_CDClose(SDL_CD *cdrom);
59
60/* Some ioctl() errno values which occur when the tray is empty */
61#define ERRNO_TRAYEMPTY(errno) \
62 ((errno == EIO) || (errno == ENOENT) || (errno == EINVAL) || \
63 (errno == ENODEV))
64
65/* Check a drive to see if it is a CD-ROM */
66static int CheckDrive(char *drive, struct stat *stbuf)
67{
68 int is_cd, cdfd;
69 struct ioc_read_subchannel info;
70
71 /* If it doesn't exist, return -1 */
72 if ( stat(drive, stbuf) < 0 ) {
73 return(-1);
74 }
75
76 /* If it does exist, verify that it's an available CD-ROM */
77 is_cd = 0;
78 if ( S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode) ) {
79 cdfd = open(drive, (O_RDONLY|O_EXCL|O_NONBLOCK), 0);
80 if ( cdfd >= 0 ) {
81 info.address_format = CD_MSF_FORMAT;
82 info.data_format = CD_CURRENT_POSITION;
83 info.data_len = 0;
84 info.data = NULL;
85 /* Under Linux, EIO occurs when a disk is not present.
86 This isn't 100% reliable, so we use the USE_MNTENT
87 code above instead.
88 */
89 if ( (ioctl(cdfd, CDIOCREADSUBCHANNEL, &info) == 0) ||
90 ERRNO_TRAYEMPTY(errno) ) {
91 is_cd = 1;
92 }
93 close(cdfd);
94 }
95 else if (ERRNO_TRAYEMPTY(errno))
96 is_cd = 1;
97 }
98 return(is_cd);
99}
100
101/* Add a CD-ROM drive to our list of valid drives */
102static void AddDrive(char *drive, struct stat *stbuf)
103{
104 int i;
105
106 if ( SDL_numcds < MAX_DRIVES ) {
107 /* Check to make sure it's not already in our list.
108 This can happen when we see a drive via symbolic link.
109 */
110 for ( i=0; i<SDL_numcds; ++i ) {
111 if ( stbuf->st_rdev == SDL_cdmode[i] ) {
112#ifdef DEBUG_CDROM
113 fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]);
114#endif
115 return;
116 }
117 }
118
119 /* Add this drive to our list */
120 i = SDL_numcds;
121 SDL_cdlist[i] = SDL_strdup(drive);
122 if ( SDL_cdlist[i] == NULL ) {
123 SDL_OutOfMemory();
124 return;
125 }
126 SDL_cdmode[i] = stbuf->st_rdev;
127 ++SDL_numcds;
128#ifdef DEBUG_CDROM
129 fprintf(stderr, "Added CD-ROM drive: %s\n", drive);
130#endif
131 }
132}
133
134int SDL_SYS_CDInit(void)
135{
136 static char *checklist[] = {
137#if defined(__OPENBSD__)
138 "?0 cd?c", "cdrom", NULL
139#elif defined(__NETBSD__)
140 "?0 cd?d", "?0 cd?c", "cdrom", NULL
141#else
142 "?0 cd?c", "?0 acd?c", "cdrom", NULL
143#endif
144 };
145 char *SDLcdrom;
146 int i, j, exists;
147 char drive[32];
148 struct stat stbuf;
149
150 /* Fill in our driver capabilities */
151 SDL_CDcaps.Name = SDL_SYS_CDName;
152 SDL_CDcaps.Open = SDL_SYS_CDOpen;
153 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
154 SDL_CDcaps.Status = SDL_SYS_CDStatus;
155 SDL_CDcaps.Play = SDL_SYS_CDPlay;
156 SDL_CDcaps.Pause = SDL_SYS_CDPause;
157 SDL_CDcaps.Resume = SDL_SYS_CDResume;
158 SDL_CDcaps.Stop = SDL_SYS_CDStop;
159 SDL_CDcaps.Eject = SDL_SYS_CDEject;
160 SDL_CDcaps.Close = SDL_SYS_CDClose;
161
162 /* Look in the environment for our CD-ROM drive list */
163 SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */
164 if ( SDLcdrom != NULL ) {
165 char *cdpath, *delim;
166 size_t len = SDL_strlen(SDLcdrom)+1;
167 cdpath = SDL_stack_alloc(char, len);
168 if ( cdpath != NULL ) {
169 SDL_strlcpy(cdpath, SDLcdrom, len);
170 SDLcdrom = cdpath;
171 do {
172 delim = SDL_strchr(SDLcdrom, ':');
173 if ( delim ) {
174 *delim++ = '\0';
175 }
176 if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) {
177 AddDrive(SDLcdrom, &stbuf);
178 }
179 if ( delim ) {
180 SDLcdrom = delim;
181 } else {
182 SDLcdrom = NULL;
183 }
184 } while ( SDLcdrom );
185 SDL_stack_free(cdpath);
186 }
187
188 /* If we found our drives, there's nothing left to do */
189 if ( SDL_numcds > 0 ) {
190 return(0);
191 }
192 }
193
194 /* Scan the system for CD-ROM drives */
195 for ( i=0; checklist[i]; ++i ) {
196 if ( checklist[i][0] == '?' ) {
197 char *insert;
198 exists = 1;
199 for ( j=checklist[i][1]; exists; ++j ) {
200 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", &checklist[i][3]);
201 insert = SDL_strchr(drive, '?');
202 if ( insert != NULL ) {
203 *insert = j;
204 }
205 switch (CheckDrive(drive, &stbuf)) {
206 /* Drive exists and is a CD-ROM */
207 case 1:
208 AddDrive(drive, &stbuf);
209 break;
210 /* Drive exists, but isn't a CD-ROM */
211 case 0:
212 break;
213 /* Drive doesn't exist */
214 case -1:
215 exists = 0;
216 break;
217 }
218 }
219 } else {
220 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]);
221 if ( CheckDrive(drive, &stbuf) > 0 ) {
222 AddDrive(drive, &stbuf);
223 }
224 }
225 }
226 return(0);
227}
228
229/* General ioctl() CD-ROM command function */
230static int SDL_SYS_CDioctl(int id, int command, void *arg)
231{
232 int retval;
233
234 retval = ioctl(id, command, arg);
235 if ( retval < 0 ) {
236 SDL_SetError("ioctl() error: %s", strerror(errno));
237 }
238 return(retval);
239}
240
241static const char *SDL_SYS_CDName(int drive)
242{
243 return(SDL_cdlist[drive]);
244}
245
246static int SDL_SYS_CDOpen(int drive)
247{
248 return(open(SDL_cdlist[drive], (O_RDONLY|O_EXCL|O_NONBLOCK), 0));
249}
250
251static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
252{
253 struct ioc_toc_header toc;
254 int i, okay;
255 struct ioc_read_toc_entry entry;
256 struct cd_toc_entry data;
257
258 okay = 0;
259 if ( SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCHEADER, &toc) == 0 ) {
260 cdrom->numtracks = toc.ending_track-toc.starting_track+1;
261 if ( cdrom->numtracks > SDL_MAX_TRACKS ) {
262 cdrom->numtracks = SDL_MAX_TRACKS;
263 }
264 /* Read all the track TOC entries */
265 for ( i=0; i<=cdrom->numtracks; ++i ) {
266 if ( i == cdrom->numtracks ) {
267 cdrom->track[i].id = 0xAA; /* CDROM_LEADOUT */
268 } else {
269 cdrom->track[i].id = toc.starting_track+i;
270 }
271 entry.starting_track = cdrom->track[i].id;
272 entry.address_format = CD_MSF_FORMAT;
273 entry.data_len = sizeof(data);
274 entry.data = &data;
275 if ( SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCENTRYS,
276 &entry) < 0 ) {
277 break;
278 } else {
279 cdrom->track[i].type = data.control;
280 cdrom->track[i].offset = MSF_TO_FRAMES(
281 data.addr.msf.minute,
282 data.addr.msf.second,
283 data.addr.msf.frame);
284 cdrom->track[i].length = 0;
285 if ( i > 0 ) {
286 cdrom->track[i-1].length =
287 cdrom->track[i].offset-
288 cdrom->track[i-1].offset;
289 }
290 }
291 }
292 if ( i == (cdrom->numtracks+1) ) {
293 okay = 1;
294 }
295 }
296 return(okay ? 0 : -1);
297}
298
299/* Get CD-ROM status */
300static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
301{
302 CDstatus status;
303 struct ioc_toc_header toc;
304 struct ioc_read_subchannel info;
305 struct cd_sub_channel_info data;
306
307 info.address_format = CD_MSF_FORMAT;
308 info.data_format = CD_CURRENT_POSITION;
309 info.track = 0;
310 info.data_len = sizeof(data);
311 info.data = &data;
312 if ( ioctl(cdrom->id, CDIOCREADSUBCHANNEL, &info) < 0 ) {
313 if ( ERRNO_TRAYEMPTY(errno) ) {
314 status = CD_TRAYEMPTY;
315 } else {
316 status = CD_ERROR;
317 }
318 } else {
319 switch (data.header.audio_status) {
320 case CD_AS_AUDIO_INVALID:
321 case CD_AS_NO_STATUS:
322 /* Try to determine if there's a CD available */
323 if (ioctl(cdrom->id,CDIOREADTOCHEADER,&toc)==0)
324 status = CD_STOPPED;
325 else
326 status = CD_TRAYEMPTY;
327 break;
328 case CD_AS_PLAY_COMPLETED:
329 status = CD_STOPPED;
330 break;
331 case CD_AS_PLAY_IN_PROGRESS:
332 status = CD_PLAYING;
333 break;
334 case CD_AS_PLAY_PAUSED:
335 status = CD_PAUSED;
336 break;
337 default:
338 status = CD_ERROR;
339 break;
340 }
341 }
342 if ( position ) {
343 if ( status == CD_PLAYING || (status == CD_PAUSED) ) {
344 *position = MSF_TO_FRAMES(
345 data.what.position.absaddr.msf.minute,
346 data.what.position.absaddr.msf.second,
347 data.what.position.absaddr.msf.frame);
348 } else {
349 *position = 0;
350 }
351 }
352 return(status);
353}
354
355/* Start play */
356static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
357{
358 struct ioc_play_msf playtime;
359
360 FRAMES_TO_MSF(start,
361 &playtime.start_m, &playtime.start_s, &playtime.start_f);
362 FRAMES_TO_MSF(start+length,
363 &playtime.end_m, &playtime.end_s, &playtime.end_f);
364#ifdef DEBUG_CDROM
365 fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n",
366 playtime.start_m, playtime.start_s, playtime.start_f,
367 playtime.end_m, playtime.end_s, playtime.end_f);
368#endif
369 ioctl(cdrom->id, CDIOCSTART, 0);
370 return(SDL_SYS_CDioctl(cdrom->id, CDIOCPLAYMSF, &playtime));
371}
372
373/* Pause play */
374static int SDL_SYS_CDPause(SDL_CD *cdrom)
375{
376 return(SDL_SYS_CDioctl(cdrom->id, CDIOCPAUSE, 0));
377}
378
379/* Resume play */
380static int SDL_SYS_CDResume(SDL_CD *cdrom)
381{
382 return(SDL_SYS_CDioctl(cdrom->id, CDIOCRESUME, 0));
383}
384
385/* Stop play */
386static int SDL_SYS_CDStop(SDL_CD *cdrom)
387{
388 return(SDL_SYS_CDioctl(cdrom->id, CDIOCSTOP, 0));
389}
390
391/* Eject the CD-ROM */
392static int SDL_SYS_CDEject(SDL_CD *cdrom)
393{
394 SDL_SYS_CDioctl(cdrom->id, CDIOCALLOW, 0);
395 return(SDL_SYS_CDioctl(cdrom->id, CDIOCEJECT, 0));
396}
397
398/* Close the CD-ROM handle */
399static void SDL_SYS_CDClose(SDL_CD *cdrom)
400{
401 close(cdrom->id);
402}
403
404void SDL_SYS_CDQuit(void)
405{
406 int i;
407
408 if ( SDL_numcds > 0 ) {
409 for ( i=0; i<SDL_numcds; ++i ) {
410 SDL_free(SDL_cdlist[i]);
411 }
412 SDL_numcds = 0;
413 }
414}
415
416#endif /* SDL_CDROM_OPENBSD */
diff --git a/apps/plugins/sdl/src/cdrom/os2/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/os2/SDL_syscdrom.c
deleted file mode 100644
index 6ed9c658fb..0000000000
--- a/apps/plugins/sdl/src/cdrom/os2/SDL_syscdrom.c
+++ /dev/null
@@ -1,393 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_OS2
25
26/* Functions for system-level CD-ROM audio control */
27
28#define INCL_MCIOS2
29#include <os2.h>
30#include <os2me.h>
31
32#include "SDL_cdrom.h"
33#include "../SDL_syscdrom.h"
34
35/* Size of MCI result buffer (in bytes) */
36#define MCI_CMDRETBUFSIZE 128
37
38/* The maximum number of CD-ROM drives we'll detect */
39#define MAX_DRIVES 16
40
41/* A list of available CD-ROM drives */
42static char *SDL_cdlist[MAX_DRIVES];
43//static dev_t SDL_cdmode[MAX_DRIVES];
44
45/* The system-dependent CD control functions */
46static const char *SDL_SYS_CDName(int drive);
47static int SDL_SYS_CDOpen(int drive);
48static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
49static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
50static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
51static int SDL_SYS_CDPause(SDL_CD *cdrom);
52static int SDL_SYS_CDResume(SDL_CD *cdrom);
53static int SDL_SYS_CDStop(SDL_CD *cdrom);
54static int SDL_SYS_CDEject(SDL_CD *cdrom);
55static void SDL_SYS_CDClose(SDL_CD *cdrom);
56
57/* MCI Timing Functions */
58#define MCI_MMTIMEPERSECOND 3000
59#define FRAMESFROMMM(mmtime) (((mmtime)*CD_FPS)/MCI_MMTIMEPERSECOND)
60
61
62/* Ready for MCI CDAudio Devices */
63int SDL_SYS_CDInit(void)
64{
65int i; /* generig counter */
66MCI_SYSINFO_PARMS msp; /* Structure to MCI SysInfo parameters */
67CHAR SysInfoRet[MCI_CMDRETBUFSIZE]; /* Buffer for MCI Command result */
68
69/* Fill in our driver capabilities */
70SDL_CDcaps.Name = SDL_SYS_CDName;
71SDL_CDcaps.Open = SDL_SYS_CDOpen;
72SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
73SDL_CDcaps.Status = SDL_SYS_CDStatus;
74SDL_CDcaps.Play = SDL_SYS_CDPlay;
75SDL_CDcaps.Pause = SDL_SYS_CDPause;
76SDL_CDcaps.Resume = SDL_SYS_CDResume;
77SDL_CDcaps.Stop = SDL_SYS_CDStop;
78SDL_CDcaps.Eject = SDL_SYS_CDEject;
79SDL_CDcaps.Close = SDL_SYS_CDClose;
80
81/* Get the number of CD ROMs in the System */
82/* Clean SysInfo structure */
83SDL_memset(&msp, 0x00, sizeof(MCI_SYSINFO_PARMS));
84/* Prepare structure to Ask Numer of Audio CDs */
85msp.usDeviceType = MCI_DEVTYPE_CD_AUDIO; /* CD Audio Type */
86msp.pszReturn = (PSZ)&SysInfoRet; /* Return Structure */
87msp.ulRetSize = MCI_CMDRETBUFSIZE; /* Size of ret struct */
88if (LOUSHORT(mciSendCommand(0,MCI_SYSINFO, MCI_SYSINFO_QUANTITY | MCI_WAIT, (PVOID)&msp, 0)) != MCIERR_SUCCESS) return(CD_ERROR);
89SDL_numcds = atoi(SysInfoRet);
90if (SDL_numcds > MAX_DRIVES) SDL_numcds = MAX_DRIVES; /* Limit maximum CD number */
91
92/* Get and Add their system name to the SDL_cdlist */
93msp.pszReturn = (PSZ)&SysInfoRet; /* Return Structure */
94msp.ulRetSize = MCI_CMDRETBUFSIZE; /* Size of ret struct */
95msp.usDeviceType = MCI_DEVTYPE_CD_AUDIO; /* CD Audio Type */
96for (i=0; i<SDL_numcds; i++)
97 {
98 msp.ulNumber = i+1;
99 mciSendCommand(0,MCI_SYSINFO, MCI_SYSINFO_NAME | MCI_WAIT,&msp, 0);
100 SDL_cdlist[i] = SDL_strdup(SysInfoRet);
101 if ( SDL_cdlist[i] == NULL )
102 {
103 SDL_OutOfMemory();
104 return(-1);
105 }
106 }
107return(0);
108}
109
110/* Return CDAudio System Dependent Device Name - Ready for MCI*/
111static const char *SDL_SYS_CDName(int drive)
112{
113return(SDL_cdlist[drive]);
114}
115
116/* Open CDAudio Device - Ready for MCI */
117static int SDL_SYS_CDOpen(int drive)
118{
119MCI_OPEN_PARMS mop;
120MCI_SET_PARMS msp;
121MCI_GENERIC_PARMS mgp;
122
123/* Open the device */
124mop.hwndCallback = (HWND)NULL; // None
125mop.usDeviceID = (USHORT)NULL; // Will be returned.
126mop.pszDeviceType = (PSZ)SDL_cdlist[drive]; // CDAudio Device
127if (LOUSHORT(mciSendCommand(0,MCI_OPEN,MCI_WAIT,&mop, 0)) != MCIERR_SUCCESS) return(CD_ERROR);
128/* Set time format */
129msp.hwndCallback = (HWND)NULL; // None
130msp.ulTimeFormat = MCI_FORMAT_MSF; // Minute : Second : Frame structure
131msp.ulSpeedFormat = (ULONG)NULL; // No change
132msp.ulAudio = (ULONG)NULL; // No Channel
133msp.ulLevel = (ULONG)NULL; // No Volume
134msp.ulOver = (ULONG)NULL; // No Delay
135msp.ulItem = (ULONG)NULL; // No item
136msp.ulValue = (ULONG)NULL; // No value for item flag
137if (LOUSHORT(mciSendCommand(mop.usDeviceID,MCI_SET,MCI_WAIT | MCI_SET_TIME_FORMAT,&msp, 0)) == MCIERR_SUCCESS) return (mop.usDeviceID);
138/* Error setting time format? - Close opened device */
139mgp.hwndCallback = (HWND)NULL; // None
140mciSendCommand(mop.usDeviceID,MCI_CLOSE,MCI_WAIT,&mgp, 0);
141return(CD_ERROR);
142}
143
144/* Get CD Table Of Contents - Ready for MCI */
145static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
146{
147MCI_TOC_PARMS mtp;
148MCI_STATUS_PARMS msp;
149MCI_TOC_REC * mtr;
150INT i;
151
152/* Correction because MCI cannot read TOC while CD is playing (it'll stop!) */
153if (cdrom->status == CD_PLAYING || cdrom->status == CD_PAUSED) return 0;
154
155/* Get Number of Tracks */
156msp.hwndCallback = (HWND)NULL; /* None */
157msp.ulReturn = (ULONG)NULL; /* We want this information */
158msp.ulItem = MCI_STATUS_NUMBER_OF_TRACKS;
159msp.ulValue = (ULONG)NULL; /* No additional information */
160if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) != MCIERR_SUCCESS) return(CD_ERROR);
161cdrom->numtracks = msp.ulReturn;
162if ( cdrom->numtracks > SDL_MAX_TRACKS )
163 {
164 cdrom->numtracks = SDL_MAX_TRACKS;
165 }
166/* Alocate space for TOC data */
167mtr = (MCI_TOC_REC *)SDL_malloc(cdrom->numtracks*sizeof(MCI_TOC_REC));
168if ( mtr == NULL )
169 {
170 SDL_OutOfMemory();
171 return(-1);
172 }
173/* Get TOC from CD */
174mtp.pBuf = mtr;
175mtp.ulBufSize = cdrom->numtracks*sizeof(MCI_TOC_REC);
176if (LOUSHORT(mciSendCommand(cdrom->id,MCI_GETTOC,MCI_WAIT,&mtp, 0)) != MCIERR_SUCCESS)
177 {
178 SDL_OutOfMemory();
179 SDL_free(mtr);
180 return(CD_ERROR);
181 }
182/* Fill SDL Tracks Structure */
183for (i=0; i<cdrom->numtracks; i++)
184 {
185 /* Set Track ID */
186 cdrom->track[i].id = (mtr+i)->TrackNum;
187 /* Set Track Type */
188 msp.hwndCallback = (HWND)NULL; /* None */
189 msp.ulReturn = (ULONG)NULL; /* We want this information */
190 msp.ulItem = MCI_CD_STATUS_TRACK_TYPE;
191 msp.ulValue = (ULONG)((mtr+i)->TrackNum); /* Track Number? */
192 if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_TRACK | MCI_STATUS_ITEM,&msp, 0)) != MCIERR_SUCCESS)
193 {
194 SDL_free(mtr);
195 return (CD_ERROR);
196 }
197 if (msp.ulReturn==MCI_CD_TRACK_AUDIO) cdrom->track[i].type = SDL_AUDIO_TRACK;
198 else cdrom->track[i].type = SDL_DATA_TRACK;
199 /* Set Track Length - values from MCI are in MMTIMEs - 3000 MMTIME = 1 second */
200 cdrom->track[i].length = FRAMESFROMMM((mtr+i)->ulEndAddr - (mtr+i)->ulStartAddr);
201 /* Set Track Offset */
202 cdrom->track[i].offset = FRAMESFROMMM((mtr+i)->ulStartAddr);
203 }
204SDL_free(mtr);
205return(0);
206}
207
208
209/* Get CD-ROM status - Ready for MCI */
210static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
211{
212CDstatus status;
213MCI_STATUS_PARMS msp;
214
215/* Get Status from MCI */
216msp.hwndCallback = (HWND)NULL; /* None */
217msp.ulReturn = (ULONG)NULL; /* We want this information */
218msp.ulItem = MCI_STATUS_MODE;
219msp.ulValue = (ULONG)NULL; /* No additional information */
220if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) != MCIERR_SUCCESS) status = CD_ERROR;
221else
222 {
223 switch(msp.ulReturn)
224 {
225 case MCI_MODE_NOT_READY:
226 status = CD_TRAYEMPTY;
227 break;
228 case MCI_MODE_PAUSE:
229 status = CD_PAUSED;
230 break;
231 case MCI_MODE_PLAY:
232 status = CD_PLAYING;
233 break;
234 case MCI_MODE_STOP:
235 status = CD_STOPPED;
236 break;
237 /* These cases should not occour */
238 case MCI_MODE_RECORD:
239 case MCI_MODE_SEEK:
240 default:
241 status = CD_ERROR;
242 break;
243 }
244 }
245
246/* Determine position */
247if (position != NULL) /* The SDL $&$&%# CDROM call sends NULL pointer here! */
248 {
249 if ((status == CD_PLAYING) || (status == CD_PAUSED))
250 {
251 /* Get Position */
252 msp.hwndCallback = (HWND)NULL; /* None */
253 msp.ulReturn = (ULONG)NULL; /* We want this information */
254 msp.ulItem = MCI_STATUS_POSITION;
255 msp.ulValue = (ULONG)NULL; /* No additiona info */
256 if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) != MCIERR_SUCCESS) return (CD_ERROR);
257 /* Convert from MSF (format selected in the Open process) to Frames (format that will be returned) */
258 *position = MSF_TO_FRAMES(MSF_MINUTE(msp.ulReturn),MSF_SECOND(msp.ulReturn),MSF_FRAME(msp.ulReturn));
259 }
260 else *position = 0;
261 }
262return(status);
263}
264
265/* Start play - Ready for MCI */
266static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
267{
268MCI_GENERIC_PARMS mgp;
269MCI_STATUS_PARMS msp;
270MCI_PLAY_PARMS mpp;
271ULONG min,sec,frm;
272
273/* Start MSF */
274FRAMES_TO_MSF(start, &min, &sec, &frm);
275MSF_MINUTE(mpp.ulFrom) = min;
276MSF_SECOND(mpp.ulFrom) = sec;
277MSF_FRAME(mpp.ulFrom) = frm;
278/* End MSF */
279FRAMES_TO_MSF(start+length, &min, &sec, &frm);
280MSF_MINUTE(mpp.ulTo) = min;
281MSF_SECOND(mpp.ulTo) = sec;
282MSF_FRAME(mpp.ulTo) = frm;
283#ifdef DEBUG_CDROM
284 fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n",
285 playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0,
286 playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1);
287#endif
288/* Verifies if it is paused first... and if it is, unpause before stopping it. */
289msp.hwndCallback = (HWND)NULL; /* None */
290msp.ulReturn = (ULONG)NULL; /* We want this information */
291msp.ulItem = MCI_STATUS_MODE;
292msp.ulValue = (ULONG)NULL; /* No additional information */
293if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) == MCIERR_SUCCESS)
294 {
295 if (msp.ulReturn == MCI_MODE_PAUSE)
296 {
297 mgp.hwndCallback = (HWND)NULL; // None
298 mciSendCommand(cdrom->id,MCI_RESUME,0,&mgp, 0);
299 }
300 }
301/* Now play it. */
302mpp.hwndCallback = (HWND)NULL; // We do not want the info. temp
303if (LOUSHORT(mciSendCommand(cdrom->id,MCI_PLAY,MCI_FROM | MCI_TO,&mpp, 0)) == MCIERR_SUCCESS) return 0;
304return (CD_ERROR);
305}
306
307/* Pause play - Ready for MCI */
308static int SDL_SYS_CDPause(SDL_CD *cdrom)
309{
310MCI_GENERIC_PARMS mgp;
311
312mgp.hwndCallback = (HWND)NULL; // None
313if (LOUSHORT(mciSendCommand(cdrom->id,MCI_PAUSE,MCI_WAIT,&mgp, 0)) == MCIERR_SUCCESS) return 0;
314return(CD_ERROR);
315}
316
317/* Resume play - Ready for MCI */
318static int SDL_SYS_CDResume(SDL_CD *cdrom)
319{
320MCI_GENERIC_PARMS mgp;
321
322mgp.hwndCallback = (HWND)NULL; // None
323if (LOUSHORT(mciSendCommand(cdrom->id,MCI_RESUME,MCI_WAIT,&mgp, 0)) == MCIERR_SUCCESS) return 0;
324return(CD_ERROR);
325}
326
327/* Stop play - Ready for MCI */
328static int SDL_SYS_CDStop(SDL_CD *cdrom)
329{
330MCI_GENERIC_PARMS mgp;
331MCI_STATUS_PARMS msp;
332
333/* Verifies if it is paused first... and if it is, unpause before stopping it. */
334msp.hwndCallback = (HWND)NULL; /* None */
335msp.ulReturn = (ULONG)NULL; /* We want this information */
336msp.ulItem = MCI_STATUS_MODE;
337msp.ulValue = (ULONG)NULL; /* No additional information */
338if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) == MCIERR_SUCCESS)
339 {
340 if (msp.ulReturn == MCI_MODE_PAUSE)
341 {
342 mgp.hwndCallback = (HWND)NULL; // None
343 mciSendCommand(cdrom->id,MCI_RESUME,0,&mgp, 0);
344 }
345 }
346/* Now stops the media */
347mgp.hwndCallback = (HWND)NULL; // None
348if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STOP,MCI_WAIT,&mgp, 0)) == MCIERR_SUCCESS) return 0;
349return(CD_ERROR);
350}
351
352/* Eject the CD-ROM - Ready for MCI */
353static int SDL_SYS_CDEject(SDL_CD *cdrom)
354{
355MCI_SET_PARMS msp;
356
357msp.hwndCallback = (HWND)NULL; // None
358msp.ulTimeFormat = (ULONG)NULL; // No change
359msp.ulSpeedFormat = (ULONG)NULL; // No change
360msp.ulAudio = (ULONG)NULL; // No Channel
361msp.ulLevel = (ULONG)NULL; // No Volume
362msp.ulOver = (ULONG)NULL; // No Delay
363msp.ulItem = (ULONG)NULL; // No item
364msp.ulValue = (ULONG)NULL; // No value for item flag
365if (LOUSHORT(mciSendCommand(cdrom->id,MCI_SET,MCI_WAIT | MCI_SET_DOOR_OPEN,&msp, 0)) == MCIERR_SUCCESS) return 0;
366return(CD_ERROR);
367}
368
369/* Close the CD-ROM handle - Ready for MCI */
370static void SDL_SYS_CDClose(SDL_CD *cdrom)
371{
372MCI_GENERIC_PARMS mgp;
373
374mgp.hwndCallback = (HWND)NULL; // None
375mciSendCommand(cdrom->id,MCI_CLOSE,MCI_WAIT,&mgp, 0);
376}
377
378/* Finalize CDROM Subsystem - Ready for MCI */
379void SDL_SYS_CDQuit(void)
380{
381int i;
382
383if ( SDL_numcds > 0 )
384 {
385 for ( i=0; i<SDL_numcds; ++i )
386 {
387 SDL_free(SDL_cdlist[i]);
388 }
389 SDL_numcds = 0;
390 }
391}
392
393#endif /* SDL_CDROM_OS2 */
diff --git a/apps/plugins/sdl/src/cdrom/osf/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/osf/SDL_syscdrom.c
deleted file mode 100644
index 8478a7b4cf..0000000000
--- a/apps/plugins/sdl/src/cdrom/osf/SDL_syscdrom.c
+++ /dev/null
@@ -1,444 +0,0 @@
1/*
2 Tru64 audio module for SDL (Simple DirectMedia Layer)
3 Copyright (C) 2003
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19
20*/
21#include "SDL_config.h"
22
23#ifdef SDL_CDROM_OSF
24
25/* Functions for system-level CD-ROM audio control */
26
27/* #define DEBUG_CDROM 1 */
28
29#include <sys/types.h>
30#include <dirent.h>
31#include <sys/stat.h>
32#include <fcntl.h>
33#include <io/cam/cdrom.h>
34#include <io/cam/rzdisk.h>
35#include <io/common/devgetinfo.h>
36
37#include "SDL_cdrom.h"
38#include "../SDL_syscdrom.h"
39
40/* The maximum number of CD-ROM drives we'll detect */
41#define MAX_DRIVES 16
42
43/* A list of available CD-ROM drives */
44static char *SDL_cdlist[MAX_DRIVES];
45static dev_t SDL_cdmode[MAX_DRIVES];
46
47/* The system-dependent CD control functions */
48static const char *SDL_SYS_CDName(int drive);
49static int SDL_SYS_CDOpen(int drive);
50static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
51static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
52static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
53static int SDL_SYS_CDPause(SDL_CD *cdrom);
54static int SDL_SYS_CDResume(SDL_CD *cdrom);
55static int SDL_SYS_CDStop(SDL_CD *cdrom);
56static int SDL_SYS_CDEject(SDL_CD *cdrom);
57static void SDL_SYS_CDClose(SDL_CD *cdrom);
58
59/* Check a drive to see if it is a CD-ROM */
60/* Caution!! Not tested. */
61static int CheckDrive(char *drive, struct stat *stbuf)
62{
63 int cdfd, is_cd = 0;
64 struct mode_sel_sns_params msp;
65 struct inquiry_info inq;
66
67#ifdef DEBUG_CDROM
68 char *devtype[] = {"Disk", "Tape", "Printer", "Processor", "WORM",
69 "CD-ROM", "Scanner", "Optical", "Changer", "Comm", "Unknown"};
70#endif
71
72 bzero(&msp, sizeof(msp));
73 bzero(&inq, sizeof(inq));
74
75 /* If it doesn't exist, return -1 */
76 if ( stat(drive, stbuf) < 0 ) {
77 return(-1);
78 }
79
80 if ( (cdfd = open(drive, (O_RDWR|O_NDELAY), 0)) >= 0 ) {
81 msp.msp_addr = (caddr_t) &inq;
82 msp.msp_pgcode = 0;
83 msp.msp_pgctrl = 0;
84 msp.msp_length = sizeof(inq);
85 msp.msp_setps = 0;
86
87 if ( ioctl(cdfd, SCSI_GET_INQUIRY_DATA, &msp) )
88 return (0);
89
90#ifdef DEBUG_CDROM
91 fprintf(stderr, "Device Type: %s\n", devtype[inq.perfdt]);
92 fprintf(stderr, "Vendor: %.8s\n", inq.vndrid);
93 fprintf(stderr, "Product: %.8s\n", inq.prodid);
94 fprintf(stderr, "Revision: %.8s\n", inq.revlvl);
95#endif
96 if ( inq.perfdt == DTYPE_RODIRECT )
97 is_cd = 1;
98 }
99
100 return(is_cd);
101}
102
103/* Add a CD-ROM drive to our list of valid drives */
104static void AddDrive(char *drive, struct stat *stbuf)
105{
106 int i;
107
108 if ( SDL_numcds < MAX_DRIVES ) {
109 /* Check to make sure it's not already in our list.
110 * This can happen when we see a drive via symbolic link.
111 *
112 */
113 for ( i=0; i<SDL_numcds; ++i ) {
114 if ( stbuf->st_rdev == SDL_cdmode[i] ) {
115#ifdef DEBUG_CDROM
116 fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]);
117#endif
118 return;
119 }
120 }
121
122 /* Add this drive to our list */
123 i = SDL_numcds;
124 SDL_cdlist[i] = SDL_strdup(drive);
125 if ( SDL_cdlist[i] == NULL ) {
126 SDL_OutOfMemory();
127 return;
128 }
129 SDL_cdmode[i] = stbuf->st_rdev;
130 ++SDL_numcds;
131#ifdef DEBUG_CDROM
132 fprintf(stderr, "Added CD-ROM drive: %s\n", drive);
133#endif
134 }
135}
136
137int SDL_SYS_CDInit(void)
138{
139 /* checklist:
140 *
141 * Tru64 5.X (/dev/rdisk/cdrom?c)
142 * dir: /dev/rdisk, name: cdrom
143 *
144 * Digital UNIX 4.0X (/dev/rrz?c)
145 * dir: /dev, name: rrz
146 *
147 */
148 struct {
149 char *dir;
150 char *name;
151 } checklist[] = {
152 {"/dev/rdisk", "cdrom"},
153 {"/dev", "rrz"},
154 {NULL, NULL}};
155 char drive[32];
156 char *SDLcdrom;
157 int i, j, exists;
158 struct stat stbuf;
159
160 /* Fill in our driver capabilities */
161 SDL_CDcaps.Name = SDL_SYS_CDName;
162 SDL_CDcaps.Open = SDL_SYS_CDOpen;
163 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
164 SDL_CDcaps.Status = SDL_SYS_CDStatus;
165 SDL_CDcaps.Play = SDL_SYS_CDPlay;
166 SDL_CDcaps.Pause = SDL_SYS_CDPause;
167 SDL_CDcaps.Resume = SDL_SYS_CDResume;
168 SDL_CDcaps.Stop = SDL_SYS_CDStop;
169 SDL_CDcaps.Eject = SDL_SYS_CDEject;
170 SDL_CDcaps.Close = SDL_SYS_CDClose;
171
172
173 /* Look in the environment for our CD-ROM drive list */
174 SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */
175 if ( SDLcdrom != NULL ) {
176 char *cdpath, *delim;
177 size_t len = SDL_strlen(SDLcdrom)+1;
178 cdpath = SDL_stack_alloc(char, len);
179 if ( cdpath != NULL ) {
180 SDL_strlcpy(cdpath, SDLcdrom, len);
181 SDLcdrom = cdpath;
182 do {
183 delim = SDL_strchr(SDLcdrom, ':');
184 if ( delim ) {
185 *delim++ = '\0';
186 }
187 if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) {
188 AddDrive(SDLcdrom, &stbuf);
189 }
190 if ( delim ) {
191 SDLcdrom = delim;
192 } else {
193 SDLcdrom = NULL;
194 }
195 } while ( SDLcdrom );
196 SDL_stack_free(cdpath);
197 }
198
199 /* If we found our drives, there's nothing left to do */
200 if ( SDL_numcds > 0 ) {
201 return(0);
202 }
203 }
204 /* Scan the system for CD-ROM drives */
205 for ( i = 0; checklist[i].dir; ++i) {
206 DIR *devdir;
207 struct dirent *devent;
208 int name_len;
209
210 devdir = opendir(checklist[i].dir);
211 if (devdir) {
212 name_len = SDL_strlen(checklist[i].name);
213 while (devent = readdir(devdir))
214 if (SDL_memcmp(checklist[i].name, devent->d_name, name_len) == 0)
215 if (devent->d_name[devent->d_namlen-1] == 'c') {
216 SDL_snprintf(drive, SDL_arraysize(drive), "%s/%s", checklist[i].dir, devent->d_name);
217#ifdef DEBUG_CDROM
218 fprintf(stderr, "Try to add drive: %s\n", drive);
219#endif
220 if ( CheckDrive(drive, &stbuf) > 0 )
221 AddDrive(drive, &stbuf);
222 }
223 closedir(devdir);
224 } else {
225#ifdef DEBUG_CDROM
226 fprintf(stderr, "cannot open dir: %s\n", checklist[i].dir);
227#endif
228 }
229 }
230 return (0);
231}
232
233static const char *SDL_SYS_CDName(int drive)
234{
235 return(SDL_cdlist[drive]);
236}
237
238static int SDL_SYS_CDOpen(int drive)
239{
240 /* O_RDWR: To use ioctl(fd, SCSI_STOP_UNIT) */
241 return(open(SDL_cdlist[drive], (O_RDWR|O_NDELAY), 0));
242}
243
244static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
245{
246 struct cd_toc toc;
247 struct cd_toc_header hdr;
248 struct cd_toc_entry *cdte;
249 int i;
250 int okay = 0;
251 if ( ioctl(cdrom->id, CDROM_TOC_HEADER, &hdr) ) {
252 fprintf(stderr,"ioctl error CDROM_TOC_HEADER\n");
253 return -1;
254 }
255 cdrom->numtracks = hdr.th_ending_track - hdr.th_starting_track + 1;
256 if ( cdrom->numtracks > SDL_MAX_TRACKS ) {
257 cdrom->numtracks = SDL_MAX_TRACKS;
258 }
259#ifdef DEBUG_CDROM
260 fprintf(stderr,"hdr.th_data_len1 = %d\n", hdr.th_data_len1);
261 fprintf(stderr,"hdr.th_data_len0 = %d\n", hdr.th_data_len0);
262 fprintf(stderr,"hdr.th_starting_track = %d\n", hdr.th_starting_track);
263 fprintf(stderr,"hdr.th_ending_track = %d\n", hdr.th_ending_track);
264 fprintf(stderr,"cdrom->numtracks = %d\n", cdrom->numtracks);
265#endif
266 toc.toc_address_format = CDROM_LBA_FORMAT;
267 toc.toc_starting_track = 0;
268 toc.toc_alloc_length = (hdr.th_data_len1 << 8) +
269 hdr.th_data_len0 + sizeof(hdr);
270 if ( (toc.toc_buffer = alloca(toc.toc_alloc_length)) == NULL) {
271 fprintf(stderr,"cannot allocate toc.toc_buffer\n");
272 return -1;
273 }
274
275 bzero (toc.toc_buffer, toc.toc_alloc_length);
276 if (ioctl(cdrom->id, CDROM_TOC_ENTRYS, &toc)) {
277 fprintf(stderr,"ioctl error CDROM_TOC_ENTRYS\n");
278 return -1;
279 }
280
281 cdte =(struct cd_toc_entry *) ((char *) toc.toc_buffer + sizeof(hdr));
282 for (i=0; i <= cdrom->numtracks; ++i) {
283 if (i == cdrom->numtracks ) {
284 cdrom->track[i].id = 0xAA;;
285 } else {
286 cdrom->track[i].id = hdr.th_starting_track + i;
287 }
288
289 cdrom->track[i].type =
290 cdte[i].te_control & CDROM_DATA_TRACK;
291 cdrom->track[i].offset =
292 cdte[i].te_absaddr.lba.addr3 << 24 |
293 cdte[i].te_absaddr.lba.addr2 << 16 |
294 cdte[i].te_absaddr.lba.addr1 << 8 |
295 cdte[i].te_absaddr.lba.addr0;
296 cdrom->track[i].length = 0;
297 if ( i > 0 ) {
298 cdrom->track[i - 1].length =
299 cdrom->track[i].offset -
300 cdrom->track[i - 1].offset;
301 }
302 }
303#ifdef DEBUG_CDROM
304 for (i = 0; i <= cdrom->numtracks; i++) {
305 fprintf(stderr,"toc_entry[%d].te_track_number = %d\n",
306 i,cdte[i].te_track_number);
307 fprintf(stderr,"cdrom->track[%d].id = %d\n", i,cdrom->track[i].id);
308 fprintf(stderr,"cdrom->track[%d].type = %x\n", i,cdrom->track[i].type);
309 fprintf(stderr,"cdrom->track[%d].offset = %d\n", i,cdrom->track[i].offset);
310 fprintf(stderr,"cdrom->track[%d].length = %d\n", i,cdrom->track[i].length);
311 }
312#endif
313 if ( i == (cdrom->numtracks+1) ) {
314 okay = 1;
315 }
316
317 return(okay ? 0 : -1);
318}
319
320/* Get CD-ROM status */
321static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
322{
323 CDstatus status;
324 struct cd_sub_channel sc;
325 struct cd_subc_channel_data scd;
326
327 sc.sch_address_format = CDROM_LBA_FORMAT;
328 sc.sch_data_format = CDROM_CURRENT_POSITION;
329 sc.sch_track_number = 0;
330 sc.sch_alloc_length = sizeof(scd);
331 sc.sch_buffer = (caddr_t)&scd;
332 if ( ioctl(cdrom->id, CDROM_READ_SUBCHANNEL, &sc) ) {
333 status = CD_ERROR;
334 fprintf(stderr,"ioctl error CDROM_READ_SUBCHANNEL \n");
335 } else {
336 switch (scd.scd_header.sh_audio_status) {
337 case AS_AUDIO_INVALID:
338 status = CD_STOPPED;
339 break;
340 case AS_PLAY_IN_PROGRESS:
341 status = CD_PLAYING;
342 break;
343 case AS_PLAY_PAUSED:
344 status = CD_PAUSED;
345 break;
346 case AS_PLAY_COMPLETED:
347 status = CD_STOPPED;
348 break;
349 case AS_PLAY_ERROR:
350 status = CD_ERROR;
351 break;
352 case AS_NO_STATUS:
353 status = CD_STOPPED;
354 break;
355 default:
356 status = CD_ERROR;
357 break;
358 }
359#ifdef DEBUG_CDROM
360 fprintf(stderr,"scd.scd_header.sh_audio_status = %x\n",
361 scd.scd_header.sh_audio_status);
362#endif
363 }
364 if (position) {
365 if (status == CD_PLAYING || (status == CD_PAUSED) ) {
366 *position =
367 scd.scd_position_data.scp_absaddr.lba.addr3 << 24 |
368 scd.scd_position_data.scp_absaddr.lba.addr2 << 16 |
369 scd.scd_position_data.scp_absaddr.lba.addr1 << 8 |
370 scd.scd_position_data.scp_absaddr.lba.addr0;
371 } else {
372 *position = 0;
373 }
374 }
375
376 return status;
377}
378
379/* Start play */
380static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
381{
382/*
383 * Play MSF
384 */
385 struct cd_play_audio_msf msf;
386 int end;
387
388 bzero(&msf, sizeof(msf));
389 end = start +length;
390 FRAMES_TO_MSF(start + 150, /* LBA = 4500*M + 75*S + F - 150 */
391 &msf.msf_starting_M_unit,
392 &msf.msf_starting_S_unit,
393 &msf.msf_starting_F_unit);
394 FRAMES_TO_MSF(end + 150, /* LBA = 4500*M + 75*S + F - 150 */
395 &msf.msf_ending_M_unit,
396 &msf.msf_ending_S_unit,
397 &msf.msf_ending_F_unit);
398
399 return(ioctl(cdrom->id, CDROM_PLAY_AUDIO_MSF, &msf));
400}
401
402/* Pause play */
403static int SDL_SYS_CDPause(SDL_CD *cdrom)
404{
405 return(ioctl(cdrom->id, CDROM_PAUSE_PLAY));
406}
407
408/* Resume play */
409static int SDL_SYS_CDResume(SDL_CD *cdrom)
410{
411 return(ioctl(cdrom->id, CDROM_RESUME_PLAY));
412}
413
414/* Stop play */
415static int SDL_SYS_CDStop(SDL_CD *cdrom)
416{
417 return(ioctl(cdrom->id, SCSI_STOP_UNIT));
418}
419
420/* Eject the CD-ROM */
421static int SDL_SYS_CDEject(SDL_CD *cdrom)
422{
423 return(ioctl(cdrom->id, CDROM_EJECT_CADDY));
424}
425
426/* Close the CD-ROM handle */
427static void SDL_SYS_CDClose(SDL_CD *cdrom)
428{
429 close(cdrom->id);
430}
431
432void SDL_SYS_CDQuit(void)
433{
434 int i;
435
436 if ( SDL_numcds > 0 ) {
437 for ( i=0; i<SDL_numcds; ++i ) {
438 SDL_free(SDL_cdlist[i]);
439 }
440 SDL_numcds = 0;
441 }
442}
443
444#endif /* SDL_CDROM_OSF */
diff --git a/apps/plugins/sdl/src/cdrom/qnx/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/qnx/SDL_syscdrom.c
deleted file mode 100644
index 0e38b7905e..0000000000
--- a/apps/plugins/sdl/src/cdrom/qnx/SDL_syscdrom.c
+++ /dev/null
@@ -1,551 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_QNX
25
26/* Functions for system-level CD-ROM audio control */
27
28#include <sys/types.h>
29#include <sys/stat.h>
30#include <sys/ioctl.h>
31#include <fcntl.h>
32#include <errno.h>
33#include <unistd.h>
34#include <sys/cdrom.h>
35#include <sys/dcmd_cam.h>
36
37#include "SDL_timer.h"
38#include "SDL_cdrom.h"
39#include "../SDL_syscdrom.h"
40
41/* The maximum number of CD-ROM drives we'll detect */
42#define MAX_DRIVES 16
43
44#define QNX_CD_OPENMODE O_RDONLY | O_EXCL
45
46/* A list of available CD-ROM drives */
47static char *SDL_cdlist[MAX_DRIVES];
48static dev_t SDL_cdmode[MAX_DRIVES];
49static int SDL_cdopen[MAX_DRIVES];
50
51/* The system-dependent CD control functions */
52static const char *SDL_SYS_CDName(int drive);
53static int SDL_SYS_CDOpen(int drive);
54static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
55static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
56static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
57static int SDL_SYS_CDPause(SDL_CD *cdrom);
58static int SDL_SYS_CDResume(SDL_CD *cdrom);
59static int SDL_SYS_CDStop(SDL_CD *cdrom);
60static int SDL_SYS_CDEject(SDL_CD *cdrom);
61static void SDL_SYS_CDClose(SDL_CD *cdrom);
62
63/* Check a drive to see if it is a CD-ROM */
64static int CheckDrive(char *drive, struct stat *stbuf)
65{
66 int is_cd, cdfd;
67 cam_devinfo_t dinfo;
68 int devctlret=0;
69
70 int atapi;
71 int removable;
72 int cdb10;
73
74 /* If it doesn't exist, return -1 */
75 if (stat(drive, stbuf) < 0)
76 {
77 return(-1);
78 }
79
80 /* If it does exist, verify that it's an available CD-ROM */
81 is_cd = 0;
82
83 if (S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode))
84 {
85 cdfd = open(drive, QNX_CD_OPENMODE);
86 if ( cdfd >= 0 )
87 {
88 devctlret=devctl(cdfd, DCMD_CAM_DEVINFO, &dinfo, sizeof(cam_devinfo_t), NULL);
89
90 if (devctlret==EOK)
91 {
92 atapi=dinfo.flags & DEV_ATAPI;
93 removable=dinfo.flags & DEV_REMOVABLE;
94 cdb10=dinfo.flags & DEV_CDB_10; /* I'm not sure about that flag */
95
96 /* in the near future need to add more checks for splitting cdroms from other devices */
97 if ((atapi)&&(removable))
98 {
99 is_cd = 1;
100 }
101 }
102
103 close(cdfd);
104 }
105 }
106 return(is_cd);
107}
108
109/* Add a CD-ROM drive to our list of valid drives */
110static void AddDrive(char *drive, struct stat *stbuf)
111{
112 int i;
113
114 if (SDL_numcds < MAX_DRIVES)
115 {
116 /* Check to make sure it's not already in our list.
117 This can happen when we see a drive via symbolic link. */
118
119 for (i=0; i<SDL_numcds; ++i)
120 {
121 if (stbuf->st_rdev == SDL_cdmode[i])
122 {
123 return;
124 }
125 }
126
127 /* Add this drive to our list */
128
129 i = SDL_numcds;
130 SDL_cdlist[i] = SDL_strdup(drive);
131 if (SDL_cdlist[i] == NULL)
132 {
133 SDL_OutOfMemory();
134 return;
135 }
136 SDL_cdmode[i] = stbuf->st_rdev;
137 ++SDL_numcds;
138 }
139}
140
141int SDL_SYS_CDInit(void)
142{
143 /* checklist: /dev/cdrom, /dev/cd?, /dev/scd? */
144 static char *checklist[]={"cdrom", "?0 cd?", "?1 cd?", "?0 scd?", NULL};
145
146 char *SDLcdrom;
147 int i, j, exists;
148 char drive[32];
149 struct stat stbuf;
150
151 /* Fill in our driver capabilities */
152 SDL_CDcaps.Name = SDL_SYS_CDName;
153 SDL_CDcaps.Open = SDL_SYS_CDOpen;
154 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
155 SDL_CDcaps.Status = SDL_SYS_CDStatus;
156 SDL_CDcaps.Play = SDL_SYS_CDPlay;
157 SDL_CDcaps.Pause = SDL_SYS_CDPause;
158 SDL_CDcaps.Resume = SDL_SYS_CDResume;
159 SDL_CDcaps.Stop = SDL_SYS_CDStop;
160 SDL_CDcaps.Eject = SDL_SYS_CDEject;
161 SDL_CDcaps.Close = SDL_SYS_CDClose;
162
163 /* clearing device open status */
164 for (i=0; i<MAX_DRIVES; i++)
165 {
166 SDL_cdopen[i]=0;
167 }
168
169 /* Look in the environment for our CD-ROM drive list */
170 SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */
171 if ( SDLcdrom != NULL )
172 {
173 char *cdpath, *delim;
174 size_t len = SDL_strlen(SDLcdrom)+1;
175 cdpath = SDL_stack_alloc(char, len);
176 if (cdpath != NULL)
177 {
178 SDL_strlcpy(cdpath, SDLcdrom, len);
179 SDLcdrom = cdpath;
180 do {
181 delim = SDL_strchr(SDLcdrom, ':');
182 if (delim)
183 {
184 *delim++ = '\0';
185 }
186 if (CheckDrive(SDLcdrom, &stbuf) > 0)
187 {
188 AddDrive(SDLcdrom, &stbuf);
189 }
190 if (delim)
191 {
192 SDLcdrom = delim;
193 }
194 else
195 {
196 SDLcdrom = NULL;
197 }
198 } while (SDLcdrom);
199 SDL_stack_free(cdpath);
200 }
201
202 /* If we found our drives, there's nothing left to do */
203 if (SDL_numcds > 0)
204 {
205 return(0);
206 }
207 }
208
209 /* Scan the system for CD-ROM drives */
210 for ( i=0; checklist[i]; ++i )
211 {
212 if (checklist[i][0] == '?')
213 {
214 char* insert;
215 exists = 1;
216
217 for ( j=checklist[i][1]; exists; ++j )
218 {
219 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", &checklist[i][3]);
220 insert = SDL_strchr(drive, '?');
221 if (insert != NULL)
222 {
223 *insert = j;
224 }
225 switch (CheckDrive(drive, &stbuf))
226 {
227 /* Drive exists and is a CD-ROM */
228 case 1:
229 AddDrive(drive, &stbuf);
230 break;
231 /* Drive exists, but isn't a CD-ROM */
232 case 0:
233 break;
234 /* Drive doesn't exist */
235 case -1:
236 exists = 0;
237 break;
238 }
239 }
240 }
241 else
242 {
243 SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]);
244 if (CheckDrive(drive, &stbuf) > 0)
245 {
246 AddDrive(drive, &stbuf);
247 }
248 }
249 }
250 return(0);
251}
252
253static const char *SDL_SYS_CDName(int drive)
254{
255 return(SDL_cdlist[drive]);
256}
257
258static int SDL_SYS_CDOpen(int drive)
259{
260 int handle;
261
262 handle=open(SDL_cdlist[drive], QNX_CD_OPENMODE);
263
264 if (handle>0)
265 {
266 SDL_cdopen[drive]=handle;
267 }
268
269 return (handle);
270}
271
272static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
273{
274 cdrom_read_toc_t toc;
275 int i, okay;
276
277 okay = 0;
278 if (devctl(cdrom->id, DCMD_CAM_CDROMREADTOC, &toc, sizeof(toc), NULL) == 0)
279 {
280 cdrom->numtracks = toc.last_track - toc.first_track + 1;
281 if (cdrom->numtracks > SDL_MAX_TRACKS)
282 {
283 cdrom->numtracks = SDL_MAX_TRACKS;
284 }
285 /* Read all the track TOC entries */
286 for (i=0; i<=cdrom->numtracks; ++i)
287 {
288 if (i == cdrom->numtracks)
289 {
290 cdrom->track[i].id = CDROM_LEADOUT;
291 }
292 else
293 {
294 cdrom->track[i].id = toc.first_track+i;
295 }
296
297 cdrom->track[i].type = toc.toc_entry[i].control_adr & 0x0F;
298 cdrom->track[i].offset = toc.toc_entry[i].addr.lba;
299 cdrom->track[i].length = 0;
300
301 if (i > 0)
302 {
303 cdrom->track[i-1].length = cdrom->track[i].offset-cdrom->track[i-1].offset;
304 }
305 }
306 if (i == (cdrom->numtracks+1))
307 {
308 okay = 1;
309 }
310 }
311 return (okay ? 0 : -1);
312}
313
314/* Get CD-ROM status */
315static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
316{
317 CDstatus status;
318
319 cdrom_read_toc_t toc;
320 cdrom_subch_data_t info;
321 cam_devinfo_t dinfo;
322
323 int devctlret=0;
324 int drive=-1;
325 int i;
326 int eagaincnt=0;
327
328 /* check media presence before read subchannel call, some cdroms can lockups */
329 /* if no media, while calling read subchannel functions. */
330 devctlret=devctl(cdrom->id, DCMD_CAM_DEVINFO, &dinfo, sizeof(cam_devinfo_t), NULL);
331
332 if (devctlret==EOK)
333 {
334 if ((dinfo.flags & DEV_NO_MEDIA)!=0)
335 {
336 status = CD_TRAYEMPTY;
337 if (position)
338 {
339 *position = 0;
340 }
341 return (status);
342 }
343 }
344
345 /* if media exists, then do other stuff */
346
347 SDL_memset(&info, 0x00, sizeof(info));
348 info.subch_command.data_format = CDROM_SUBCH_CURRENT_POSITION;
349
350 do {
351 devctlret=devctl(cdrom->id, DCMD_CAM_CDROMSUBCHNL, &info, sizeof(info), NULL);
352 if (devctlret==EIO)
353 {
354 /* big workaround for media change, handle is unusable after that,
355 that bug was found in QNX 6.2, 6.2.1 is not released yet. */
356
357 for (i=0; i<MAX_DRIVES; i++)
358 {
359 if (SDL_cdopen[i]==cdrom->id)
360 {
361 drive=i;
362 break;
363 }
364 }
365 if (drive==-1)
366 {
367 /* that cannot happen, but ... */
368 break;
369 }
370 close(cdrom->id);
371 cdrom->id=open(SDL_cdlist[drive], QNX_CD_OPENMODE);
372 devctlret=EAGAIN;
373 }
374 if (devctlret==EAGAIN)
375 {
376 eagaincnt++;
377 }
378 if (eagaincnt==2)
379 {
380 /* workaround for broken cdroms, which can return always EAGAIN when its not ready, */
381 /* that mean errornous media or just no media avail */
382 devctlret=ENXIO;
383 break;
384 }
385 } while ((devctlret==EAGAIN)||(devctlret==ESTALE));
386
387 if (devctlret != 0)
388 {
389 if (devctlret==ENXIO)
390 {
391 status = CD_TRAYEMPTY;
392 }
393 else
394 {
395 status = CD_ERROR;
396 }
397 }
398 else
399 {
400 switch (info.current_position.header.audio_status)
401 {
402 case CDROM_AUDIO_INVALID:
403 case CDROM_AUDIO_NO_STATUS:
404 /* Try to determine if there's a CD available */
405 if (devctl(cdrom->id, DCMD_CAM_CDROMREADTOC, &toc, sizeof(toc), NULL)==0)
406 status = CD_STOPPED;
407 else
408 status = CD_TRAYEMPTY;
409 break;
410 case CDROM_AUDIO_COMPLETED:
411 status = CD_STOPPED;
412 break;
413 case CDROM_AUDIO_PLAY:
414 status = CD_PLAYING;
415 break;
416 case CDROM_AUDIO_PAUSED:
417 /* Workaround buggy CD-ROM drive */
418 if (info.current_position.data_format == CDROM_LEADOUT)
419 {
420 status = CD_STOPPED;
421 }
422 else
423 {
424 status = CD_PAUSED;
425 }
426 break;
427 default:
428 status = CD_ERROR;
429 break;
430 }
431 }
432
433 if (position)
434 {
435 if (status==CD_PLAYING || (status==CD_PAUSED))
436 {
437 *position = MSF_TO_FRAMES(info.current_position.addr.msf.minute,
438 info.current_position.addr.msf.second,
439 info.current_position.addr.msf.frame);
440 }
441 else
442 {
443 *position = 0;
444 }
445 }
446
447 return (status);
448}
449
450/* Start play */
451static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
452{
453 cdrom_playmsf_t playtime;
454
455 FRAMES_TO_MSF(start, &playtime.start_minute, &playtime.start_second, &playtime.start_frame);
456 FRAMES_TO_MSF(start+length, &playtime.end_minute, &playtime.end_second, &playtime.end_frame);
457
458 if (devctl(cdrom->id, DCMD_CAM_CDROMPLAYMSF, &playtime, sizeof(playtime), NULL) != 0)
459 {
460 return -1;
461 }
462 else
463 {
464 return 0;
465 }
466}
467
468/* Pause play */
469static int SDL_SYS_CDPause(SDL_CD *cdrom)
470{
471 if (devctl(cdrom->id, DCMD_CAM_CDROMPAUSE, NULL, 0, NULL)!=0)
472 {
473 return -1;
474 }
475 else
476 {
477 return 0;
478 }
479}
480
481/* Resume play */
482static int SDL_SYS_CDResume(SDL_CD *cdrom)
483{
484 if (devctl(cdrom->id, DCMD_CAM_CDROMRESUME, NULL, 0, NULL)!=0)
485 {
486 return -1;
487 }
488 else
489 {
490 return 0;
491 }
492}
493
494/* Stop play */
495static int SDL_SYS_CDStop(SDL_CD *cdrom)
496{
497 if (devctl(cdrom->id, DCMD_CAM_CDROMSTOP, NULL, 0, NULL)!=0)
498 {
499 return -1;
500 }
501 else
502 {
503 return 0;
504 }
505}
506
507/* Eject the CD-ROM */
508static int SDL_SYS_CDEject(SDL_CD *cdrom)
509{
510 if (devctl(cdrom->id, DCMD_CAM_EJECT_MEDIA, NULL, 0, NULL)!=0)
511 {
512 return -1;
513 }
514 else
515 {
516 return 0;
517 }
518}
519
520/* Close the CD-ROM handle */
521static void SDL_SYS_CDClose(SDL_CD *cdrom)
522{
523 int i;
524
525 for (i=0; i<MAX_DRIVES; i++)
526 {
527 if (SDL_cdopen[i]==cdrom->id)
528 {
529 SDL_cdopen[i]=0;
530 break;
531 }
532 }
533
534 close(cdrom->id);
535}
536
537void SDL_SYS_CDQuit(void)
538{
539 int i;
540
541 if (SDL_numcds > 0)
542 {
543 for (i=0; i<SDL_numcds; ++i)
544 {
545 SDL_free(SDL_cdlist[i]);
546 }
547 SDL_numcds = 0;
548 }
549}
550
551#endif /* SDL_CDROM_QNX */
diff --git a/apps/plugins/sdl/src/cdrom/win32/SDL_syscdrom.c b/apps/plugins/sdl/src/cdrom/win32/SDL_syscdrom.c
deleted file mode 100644
index cac9fd3b61..0000000000
--- a/apps/plugins/sdl/src/cdrom/win32/SDL_syscdrom.c
+++ /dev/null
@@ -1,386 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_CDROM_WIN32
25
26/* Functions for system-level CD-ROM audio control */
27
28#define WIN32_LEAN_AND_MEAN
29#include <windows.h>
30#include <mmsystem.h>
31
32#include "SDL_cdrom.h"
33#include "../SDL_syscdrom.h"
34
35/* This really broken?? */
36#define BROKEN_MCI_PAUSE /* Pausing actually stops play -- Doh! */
37
38/* The maximum number of CD-ROM drives we'll detect (Don't change!) */
39#define MAX_DRIVES 26
40
41/* A list of available CD-ROM drives */
42static char *SDL_cdlist[MAX_DRIVES];
43static MCIDEVICEID SDL_mciID[MAX_DRIVES];
44#ifdef BROKEN_MCI_PAUSE
45static int SDL_paused[MAX_DRIVES];
46#endif
47static int SDL_CD_end_position;
48
49/* The system-dependent CD control functions */
50static const char *SDL_SYS_CDName(int drive);
51static int SDL_SYS_CDOpen(int drive);
52static int SDL_SYS_CDGetTOC(SDL_CD *cdrom);
53static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position);
54static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length);
55static int SDL_SYS_CDPause(SDL_CD *cdrom);
56static int SDL_SYS_CDResume(SDL_CD *cdrom);
57static int SDL_SYS_CDStop(SDL_CD *cdrom);
58static int SDL_SYS_CDEject(SDL_CD *cdrom);
59static void SDL_SYS_CDClose(SDL_CD *cdrom);
60
61
62/* Add a CD-ROM drive to our list of valid drives */
63static void AddDrive(char *drive)
64{
65 int i;
66
67 if ( SDL_numcds < MAX_DRIVES ) {
68 /* Add this drive to our list */
69 i = SDL_numcds;
70 SDL_cdlist[i] = SDL_strdup(drive);
71 if ( SDL_cdlist[i] == NULL ) {
72 SDL_OutOfMemory();
73 return;
74 }
75 ++SDL_numcds;
76#ifdef CDROM_DEBUG
77 fprintf(stderr, "Added CD-ROM drive: %s\n", drive);
78#endif
79 }
80}
81
82int SDL_SYS_CDInit(void)
83{
84 /* checklist: Drive 'A' - 'Z' */
85 int i;
86 char drive[4];
87
88 /* Fill in our driver capabilities */
89 SDL_CDcaps.Name = SDL_SYS_CDName;
90 SDL_CDcaps.Open = SDL_SYS_CDOpen;
91 SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC;
92 SDL_CDcaps.Status = SDL_SYS_CDStatus;
93 SDL_CDcaps.Play = SDL_SYS_CDPlay;
94 SDL_CDcaps.Pause = SDL_SYS_CDPause;
95 SDL_CDcaps.Resume = SDL_SYS_CDResume;
96 SDL_CDcaps.Stop = SDL_SYS_CDStop;
97 SDL_CDcaps.Eject = SDL_SYS_CDEject;
98 SDL_CDcaps.Close = SDL_SYS_CDClose;
99
100 /* Scan the system for CD-ROM drives */
101 for ( i='A'; i<='Z'; ++i ) {
102 SDL_snprintf(drive, SDL_arraysize(drive), "%c:\\", i);
103 if ( GetDriveType(drive) == DRIVE_CDROM ) {
104 AddDrive(drive);
105 }
106 }
107 SDL_memset(SDL_mciID, 0, sizeof(SDL_mciID));
108 return(0);
109}
110
111/* General ioctl() CD-ROM command function */
112static int SDL_SYS_CDioctl(int id, UINT msg, DWORD flags, void *arg)
113{
114 MCIERROR mci_error;
115
116 mci_error = mciSendCommand(SDL_mciID[id], msg, flags, (DWORD_PTR)arg);
117 if ( mci_error ) {
118 char error[256];
119
120 mciGetErrorString(mci_error, error, 256);
121 SDL_SetError("mciSendCommand() error: %s", error);
122 }
123 return(!mci_error ? 0 : -1);
124}
125
126static const char *SDL_SYS_CDName(int drive)
127{
128 return(SDL_cdlist[drive]);
129}
130
131static int SDL_SYS_CDOpen(int drive)
132{
133 MCI_OPEN_PARMS mci_open;
134 MCI_SET_PARMS mci_set;
135 char device[3];
136 DWORD flags;
137
138 /* Open the requested device */
139 mci_open.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO;
140 device[0] = *SDL_cdlist[drive];
141 device[1] = ':';
142 device[2] = '\0';
143 mci_open.lpstrElementName = device;
144 flags =
145 (MCI_OPEN_TYPE|MCI_OPEN_SHAREABLE|MCI_OPEN_TYPE_ID|MCI_OPEN_ELEMENT);
146 if ( SDL_SYS_CDioctl(0, MCI_OPEN, flags, &mci_open) < 0 ) {
147 flags &= ~MCI_OPEN_SHAREABLE;
148 if ( SDL_SYS_CDioctl(0, MCI_OPEN, flags, &mci_open) < 0 ) {
149 return(-1);
150 }
151 }
152 SDL_mciID[drive] = mci_open.wDeviceID;
153
154 /* Set the minute-second-frame time format */
155 mci_set.dwTimeFormat = MCI_FORMAT_MSF;
156 SDL_SYS_CDioctl(drive, MCI_SET, MCI_SET_TIME_FORMAT, &mci_set);
157
158#ifdef BROKEN_MCI_PAUSE
159 SDL_paused[drive] = 0;
160#endif
161 return(drive);
162}
163
164static int SDL_SYS_CDGetTOC(SDL_CD *cdrom)
165{
166 MCI_STATUS_PARMS mci_status;
167 int i, okay;
168 DWORD flags;
169
170 okay = 0;
171 mci_status.dwItem = MCI_STATUS_NUMBER_OF_TRACKS;
172 flags = MCI_STATUS_ITEM | MCI_WAIT;
173 if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, &mci_status) == 0 ) {
174 cdrom->numtracks = mci_status.dwReturn;
175 if ( cdrom->numtracks > SDL_MAX_TRACKS ) {
176 cdrom->numtracks = SDL_MAX_TRACKS;
177 }
178 /* Read all the track TOC entries */
179 flags = MCI_STATUS_ITEM | MCI_TRACK | MCI_WAIT;
180 for ( i=0; i<cdrom->numtracks; ++i ) {
181 cdrom->track[i].id = i+1;
182 mci_status.dwTrack = cdrom->track[i].id;
183#ifdef MCI_CDA_STATUS_TYPE_TRACK
184 mci_status.dwItem = MCI_CDA_STATUS_TYPE_TRACK;
185 if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags,
186 &mci_status) < 0 ) {
187 break;
188 }
189 if ( mci_status.dwReturn == MCI_CDA_TRACK_AUDIO ) {
190 cdrom->track[i].type = SDL_AUDIO_TRACK;
191 } else {
192 cdrom->track[i].type = SDL_DATA_TRACK;
193 }
194#else
195 cdrom->track[i].type = SDL_AUDIO_TRACK;
196#endif
197 mci_status.dwItem = MCI_STATUS_POSITION;
198 if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags,
199 &mci_status) < 0 ) {
200 break;
201 }
202 cdrom->track[i].offset = MSF_TO_FRAMES(
203 MCI_MSF_MINUTE(mci_status.dwReturn),
204 MCI_MSF_SECOND(mci_status.dwReturn),
205 MCI_MSF_FRAME(mci_status.dwReturn));
206 cdrom->track[i].length = 0;
207 if ( i > 0 ) {
208 cdrom->track[i-1].length =
209 cdrom->track[i].offset-
210 cdrom->track[i-1].offset;
211 }
212 }
213 if ( i == cdrom->numtracks ) {
214 mci_status.dwTrack = cdrom->track[i - 1].id;
215 mci_status.dwItem = MCI_STATUS_LENGTH;
216 if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags,
217 &mci_status) == 0 ) {
218 cdrom->track[i - 1].length = MSF_TO_FRAMES(
219 MCI_MSF_MINUTE(mci_status.dwReturn),
220 MCI_MSF_SECOND(mci_status.dwReturn),
221 MCI_MSF_FRAME(mci_status.dwReturn));
222 /* compute lead-out offset */
223 cdrom->track[i].offset = cdrom->track[i - 1].offset +
224 cdrom->track[i - 1].length;
225 cdrom->track[i].length = 0;
226 okay = 1;
227 }
228 }
229 }
230 return(okay ? 0 : -1);
231}
232
233/* Get CD-ROM status */
234static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position)
235{
236 CDstatus status;
237 MCI_STATUS_PARMS mci_status;
238 DWORD flags;
239
240 flags = MCI_STATUS_ITEM | MCI_WAIT;
241 mci_status.dwItem = MCI_STATUS_MODE;
242 if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, &mci_status) < 0 ) {
243 status = CD_ERROR;
244 } else {
245 switch (mci_status.dwReturn) {
246 case MCI_MODE_NOT_READY:
247 case MCI_MODE_OPEN:
248 status = CD_TRAYEMPTY;
249 break;
250 case MCI_MODE_STOP:
251#ifdef BROKEN_MCI_PAUSE
252 if ( SDL_paused[cdrom->id] ) {
253 status = CD_PAUSED;
254 } else {
255 status = CD_STOPPED;
256 }
257#else
258 status = CD_STOPPED;
259#endif /* BROKEN_MCI_PAUSE */
260 break;
261 case MCI_MODE_PLAY:
262#ifdef BROKEN_MCI_PAUSE
263 if ( SDL_paused[cdrom->id] ) {
264 status = CD_PAUSED;
265 } else {
266 status = CD_PLAYING;
267 }
268#else
269 status = CD_PLAYING;
270#endif /* BROKEN_MCI_PAUSE */
271 break;
272 case MCI_MODE_PAUSE:
273 status = CD_PAUSED;
274 break;
275 default:
276 status = CD_ERROR;
277 break;
278 }
279 }
280 if ( position ) {
281 if ( status == CD_PLAYING || (status == CD_PAUSED) ) {
282 mci_status.dwItem = MCI_STATUS_POSITION;
283 if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags,
284 &mci_status) == 0 ) {
285 *position = MSF_TO_FRAMES(
286 MCI_MSF_MINUTE(mci_status.dwReturn),
287 MCI_MSF_SECOND(mci_status.dwReturn),
288 MCI_MSF_FRAME(mci_status.dwReturn));
289 } else {
290 *position = 0;
291 }
292 } else {
293 *position = 0;
294 }
295 }
296 return(status);
297}
298
299/* Start play */
300static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length)
301{
302 MCI_PLAY_PARMS mci_play;
303 int m, s, f;
304 DWORD flags;
305
306 flags = MCI_FROM | MCI_TO | MCI_NOTIFY;
307 mci_play.dwCallback = 0;
308 FRAMES_TO_MSF(start, &m, &s, &f);
309 mci_play.dwFrom = MCI_MAKE_MSF(m, s, f);
310 FRAMES_TO_MSF(start+length, &m, &s, &f);
311 mci_play.dwTo = MCI_MAKE_MSF(m, s, f);
312 SDL_CD_end_position = mci_play.dwTo;
313 return(SDL_SYS_CDioctl(cdrom->id, MCI_PLAY, flags, &mci_play));
314}
315
316/* Pause play */
317static int SDL_SYS_CDPause(SDL_CD *cdrom)
318{
319#ifdef BROKEN_MCI_PAUSE
320 SDL_paused[cdrom->id] = 1;
321#endif
322 return(SDL_SYS_CDioctl(cdrom->id, MCI_PAUSE, MCI_WAIT, NULL));
323}
324
325/* Resume play */
326static int SDL_SYS_CDResume(SDL_CD *cdrom)
327{
328#ifdef BROKEN_MCI_PAUSE
329 MCI_STATUS_PARMS mci_status;
330 int okay;
331 int flags;
332
333 okay = 0;
334 /* Play from the current play position to the end position set earlier */
335 flags = MCI_STATUS_ITEM | MCI_WAIT;
336 mci_status.dwItem = MCI_STATUS_POSITION;
337 if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, &mci_status) == 0 ) {
338 MCI_PLAY_PARMS mci_play;
339
340 flags = MCI_FROM | MCI_TO | MCI_NOTIFY;
341 mci_play.dwCallback = 0;
342 mci_play.dwFrom = mci_status.dwReturn;
343 mci_play.dwTo = SDL_CD_end_position;
344 if (SDL_SYS_CDioctl(cdrom->id,MCI_PLAY,flags,&mci_play) == 0) {
345 okay = 1;
346 SDL_paused[cdrom->id] = 0;
347 }
348 }
349 return(okay ? 0 : -1);
350#else
351 return(SDL_SYS_CDioctl(cdrom->id, MCI_RESUME, MCI_WAIT, NULL));
352#endif /* BROKEN_MCI_PAUSE */
353}
354
355/* Stop play */
356static int SDL_SYS_CDStop(SDL_CD *cdrom)
357{
358 return(SDL_SYS_CDioctl(cdrom->id, MCI_STOP, MCI_WAIT, NULL));
359}
360
361/* Eject the CD-ROM */
362static int SDL_SYS_CDEject(SDL_CD *cdrom)
363{
364 return(SDL_SYS_CDioctl(cdrom->id, MCI_SET, MCI_SET_DOOR_OPEN, NULL));
365}
366
367/* Close the CD-ROM handle */
368static void SDL_SYS_CDClose(SDL_CD *cdrom)
369{
370 SDL_SYS_CDioctl(cdrom->id, MCI_CLOSE, MCI_WAIT, NULL);
371}
372
373void SDL_SYS_CDQuit(void)
374{
375 int i;
376
377 if ( SDL_numcds > 0 ) {
378 for ( i=0; i<SDL_numcds; ++i ) {
379 SDL_free(SDL_cdlist[i]);
380 SDL_cdlist[i] = NULL;
381 }
382 SDL_numcds = 0;
383 }
384}
385
386#endif /* SDL_CDROM_WIN32 */
diff --git a/apps/plugins/sdl/src/hermes/COPYING.LIB b/apps/plugins/sdl/src/hermes/COPYING.LIB
deleted file mode 100644
index 69679a5636..0000000000
--- a/apps/plugins/sdl/src/hermes/COPYING.LIB
+++ /dev/null
@@ -1,438 +0,0 @@
1 GNU LIBRARY GENERAL PUBLIC LICENSE
2 Version 2, June 1991
3
4 Copyright (C) 1991 Free Software Foundation, Inc.
5 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9[This is the first released version of the library GPL. It is
10 numbered 2 because it goes with version 2 of the ordinary GPL.]
11
12 Preamble
13
14 The licenses for most software are designed to take away your
15freedom to share and change it. By contrast, the GNU General Public
16Licenses are intended to guarantee your freedom to share and change
17free software--to make sure the software is free for all its users.
18
19 This license, the Library General Public License, applies to some
20specially designated Free Software Foundation software, and to any
21other libraries whose authors decide to use it. You can use it for
22your libraries, too.
23
24 When we speak of free software, we are referring to freedom, not
25price. Our General Public Licenses are designed to make sure that you
26have the freedom to distribute copies of free software (and charge for
27this service if you wish), that you receive source code or can get it
28if you want it, that you can change the software or use pieces of it
29in new free programs; and that you know you can do these things.
30
31 To protect your rights, we need to make restrictions that forbid
32anyone to deny you these rights or to ask you to surrender the rights.
33These restrictions translate to certain responsibilities for you if
34you distribute copies of the library, or if you modify it.
35
36 For example, if you distribute copies of the library, whether gratis
37or for a fee, you must give the recipients all the rights that we gave
38you. You must make sure that they, too, receive or can get the source
39code. If you link a program with the library, you must provide
40complete object files to the recipients so that they can relink them
41with the library, after making changes to the library and recompiling
42it. And you must show them these terms so they know their rights.
43
44 Our method of protecting your rights has two steps: (1) copyright
45the library, and (2) offer you this license which gives you legal
46permission to copy, distribute and/or modify the library.
47
48 Also, for each distributor's protection, we want to make certain
49that everyone understands that there is no warranty for this free
50library. If the library is modified by someone else and passed on, we
51want its recipients to know that what they have is not the original
52version, so that any problems introduced by others will not reflect on
53the original authors' reputations.
54
55 Finally, any free program is threatened constantly by software
56patents. We wish to avoid the danger that companies distributing free
57software will individually obtain patent licenses, thus in effect
58transforming the program into proprietary software. To prevent this,
59we have made it clear that any patent must be licensed for everyone's
60free use or not licensed at all.
61
62 Most GNU software, including some libraries, is covered by the ordinary
63GNU General Public License, which was designed for utility programs. This
64license, the GNU Library General Public License, applies to certain
65designated libraries. This license is quite different from the ordinary
66one; be sure to read it in full, and don't assume that anything in it is
67the same as in the ordinary license.
68
69 The reason we have a separate public license for some libraries is that
70they blur the distinction we usually make between modifying or adding to a
71program and simply using it. Linking a program with a library, without
72changing the library, is in some sense simply using the library, and is
73analogous to running a utility program or application program. However, in
74a textual and legal sense, the linked executable is a combined work, a
75derivative of the original library, and the ordinary General Public License
76treats it as such.
77
78 Because of this blurred distinction, using the ordinary General
79Public License for libraries did not effectively promote software
80sharing, because most developers did not use the libraries. We
81concluded that weaker conditions might promote sharing better.
82
83 However, unrestricted linking of non-free programs would deprive the
84users of those programs of all benefit from the free status of the
85libraries themselves. This Library General Public License is intended to
86permit developers of non-free programs to use free libraries, while
87preserving your freedom as a user of such programs to change the free
88libraries that are incorporated in them. (We have not seen how to achieve
89this as regards changes in header files, but we have achieved it as regards
90changes in the actual functions of the Library.) The hope is that this
91will lead to faster development of free libraries.
92
93 The precise terms and conditions for copying, distribution and
94modification follow. Pay close attention to the difference between a
95"work based on the library" and a "work that uses the library". The
96former contains code derived from the library, while the latter only
97works together with the library.
98
99 Note that it is possible for a library to be covered by the ordinary
100General Public License rather than by this special one.
101
102 GNU LIBRARY GENERAL PUBLIC LICENSE
103 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
104
105 0. This License Agreement applies to any software library which
106contains a notice placed by the copyright holder or other authorized
107party saying it may be distributed under the terms of this Library
108General Public License (also called "this License"). Each licensee is
109addressed as "you".
110
111 A "library" means a collection of software functions and/or data
112prepared so as to be conveniently linked with application programs
113(which use some of those functions and data) to form executables.
114
115 The "Library", below, refers to any such software library or work
116which has been distributed under these terms. A "work based on the
117Library" means either the Library or any derivative work under
118copyright law: that is to say, a work containing the Library or a
119portion of it, either verbatim or with modifications and/or translated
120straightforwardly into another language. (Hereinafter, translation is
121included without limitation in the term "modification".)
122
123 "Source code" for a work means the preferred form of the work for
124making modifications to it. For a library, complete source code means
125all the source code for all modules it contains, plus any associated
126interface definition files, plus the scripts used to control compilation
127and installation of the library.
128
129 Activities other than copying, distribution and modification are not
130covered by this License; they are outside its scope. The act of
131running a program using the Library is not restricted, and output from
132such a program is covered only if its contents constitute a work based
133on the Library (independent of the use of the Library in a tool for
134writing it). Whether that is true depends on what the Library does
135and what the program that uses the Library does.
136
137 1. You may copy and distribute verbatim copies of the Library's
138complete source code as you receive it, in any medium, provided that
139you conspicuously and appropriately publish on each copy an
140appropriate copyright notice and disclaimer of warranty; keep intact
141all the notices that refer to this License and to the absence of any
142warranty; and distribute a copy of this License along with the
143Library.
144
145 You may charge a fee for the physical act of transferring a copy,
146and you may at your option offer warranty protection in exchange for a
147fee.
148
149 2. You may modify your copy or copies of the Library or any portion
150of it, thus forming a work based on the Library, and copy and
151distribute such modifications or work under the terms of Section 1
152above, provided that you also meet all of these conditions:
153
154 a) The modified work must itself be a software library.
155
156 b) You must cause the files modified to carry prominent notices
157 stating that you changed the files and the date of any change.
158
159 c) You must cause the whole of the work to be licensed at no
160 charge to all third parties under the terms of this License.
161
162 d) If a facility in the modified Library refers to a function or a
163 table of data to be supplied by an application program that uses
164 the facility, other than as an argument passed when the facility
165 is invoked, then you must make a good faith effort to ensure that,
166 in the event an application does not supply such function or
167 table, the facility still operates, and performs whatever part of
168 its purpose remains meaningful.
169
170 (For example, a function in a library to compute square roots has
171 a purpose that is entirely well-defined independent of the
172 application. Therefore, Subsection 2d requires that any
173 application-supplied function or table used by this function must
174 be optional: if the application does not supply it, the square
175 root function must still compute square roots.)
176
177These requirements apply to the modified work as a whole. If
178identifiable sections of that work are not derived from the Library,
179and can be reasonably considered independent and separate works in
180themselves, then this License, and its terms, do not apply to those
181sections when you distribute them as separate works. But when you
182distribute the same sections as part of a whole which is a work based
183on the Library, the distribution of the whole must be on the terms of
184this License, whose permissions for other licensees extend to the
185entire whole, and thus to each and every part regardless of who wrote
186it.
187
188Thus, it is not the intent of this section to claim rights or contest
189your rights to work written entirely by you; rather, the intent is to
190exercise the right to control the distribution of derivative or
191collective works based on the Library.
192
193In addition, mere aggregation of another work not based on the Library
194with the Library (or with a work based on the Library) on a volume of
195a storage or distribution medium does not bring the other work under
196the scope of this License.
197
198 3. You may opt to apply the terms of the ordinary GNU General Public
199License instead of this License to a given copy of the Library. To do
200this, you must alter all the notices that refer to this License, so
201that they refer to the ordinary GNU General Public License, version 2,
202instead of to this License. (If a newer version than version 2 of the
203ordinary GNU General Public License has appeared, then you can specify
204that version instead if you wish.) Do not make any other change in
205these notices.
206
207 Once this change is made in a given copy, it is irreversible for
208that copy, so the ordinary GNU General Public License applies to all
209subsequent copies and derivative works made from that copy.
210
211 This option is useful when you wish to copy part of the code of
212the Library into a program that is not a library.
213
214 4. You may copy and distribute the Library (or a portion or
215derivative of it, under Section 2) in object code or executable form
216under the terms of Sections 1 and 2 above provided that you accompany
217it with the complete corresponding machine-readable source code, which
218must be distributed under the terms of Sections 1 and 2 above on a
219medium customarily used for software interchange.
220
221 If distribution of object code is made by offering access to copy
222from a designated place, then offering equivalent access to copy the
223source code from the same place satisfies the requirement to
224distribute the source code, even though third parties are not
225compelled to copy the source along with the object code.
226
227 5. A program that contains no derivative of any portion of the
228Library, but is designed to work with the Library by being compiled or
229linked with it, is called a "work that uses the Library". Such a
230work, in isolation, is not a derivative work of the Library, and
231therefore falls outside the scope of this License.
232
233 However, linking a "work that uses the Library" with the Library
234creates an executable that is a derivative of the Library (because it
235contains portions of the Library), rather than a "work that uses the
236library". The executable is therefore covered by this License.
237Section 6 states terms for distribution of such executables.
238
239 When a "work that uses the Library" uses material from a header file
240that is part of the Library, the object code for the work may be a
241derivative work of the Library even though the source code is not.
242Whether this is true is especially significant if the work can be
243linked without the Library, or if the work is itself a library. The
244threshold for this to be true is not precisely defined by law.
245
246 If such an object file uses only numerical parameters, data
247structure layouts and accessors, and small macros and small inline
248functions (ten lines or less in length), then the use of the object
249file is unrestricted, regardless of whether it is legally a derivative
250work. (Executables containing this object code plus portions of the
251Library will still fall under Section 6.)
252
253 Otherwise, if the work is a derivative of the Library, you may
254distribute the object code for the work under the terms of Section 6.
255Any executables containing that work also fall under Section 6,
256whether or not they are linked directly with the Library itself.
257
258 6. As an exception to the Sections above, you may also compile or
259link a "work that uses the Library" with the Library to produce a
260work containing portions of the Library, and distribute that work
261under terms of your choice, provided that the terms permit
262modification of the work for the customer's own use and reverse
263engineering for debugging such modifications.
264
265 You must give prominent notice with each copy of the work that the
266Library is used in it and that the Library and its use are covered by
267this License. You must supply a copy of this License. If the work
268during execution displays copyright notices, you must include the
269copyright notice for the Library among them, as well as a reference
270directing the user to the copy of this License. Also, you must do one
271of these things:
272
273 a) Accompany the work with the complete corresponding
274 machine-readable source code for the Library including whatever
275 changes were used in the work (which must be distributed under
276 Sections 1 and 2 above); and, if the work is an executable linked
277 with the Library, with the complete machine-readable "work that
278 uses the Library", as object code and/or source code, so that the
279 user can modify the Library and then relink to produce a modified
280 executable containing the modified Library. (It is understood
281 that the user who changes the contents of definitions files in the
282 Library will not necessarily be able to recompile the application
283 to use the modified definitions.)
284
285 b) Accompany the work with a written offer, valid for at
286 least three years, to give the same user the materials
287 specified in Subsection 6a, above, for a charge no more
288 than the cost of performing this distribution.
289
290 c) If distribution of the work is made by offering access to copy
291 from a designated place, offer equivalent access to copy the above
292 specified materials from the same place.
293
294 d) Verify that the user has already received a copy of these
295 materials or that you have already sent this user a copy.
296
297 For an executable, the required form of the "work that uses the
298Library" must include any data and utility programs needed for
299reproducing the executable from it. However, as a special exception,
300the source code distributed need not include anything that is normally
301distributed (in either source or binary form) with the major
302components (compiler, kernel, and so on) of the operating system on
303which the executable runs, unless that component itself accompanies
304the executable.
305
306 It may happen that this requirement contradicts the license
307restrictions of other proprietary libraries that do not normally
308accompany the operating system. Such a contradiction means you cannot
309use both them and the Library together in an executable that you
310distribute.
311
312 7. You may place library facilities that are a work based on the
313Library side-by-side in a single library together with other library
314facilities not covered by this License, and distribute such a combined
315library, provided that the separate distribution of the work based on
316the Library and of the other library facilities is otherwise
317permitted, and provided that you do these two things:
318
319 a) Accompany the combined library with a copy of the same work
320 based on the Library, uncombined with any other library
321 facilities. This must be distributed under the terms of the
322 Sections above.
323
324 b) Give prominent notice with the combined library of the fact
325 that part of it is a work based on the Library, and explaining
326 where to find the accompanying uncombined form of the same work.
327
328 8. You may not copy, modify, sublicense, link with, or distribute
329the Library except as expressly provided under this License. Any
330attempt otherwise to copy, modify, sublicense, link with, or
331distribute the Library is void, and will automatically terminate your
332rights under this License. However, parties who have received copies,
333or rights, from you under this License will not have their licenses
334terminated so long as such parties remain in full compliance.
335
336 9. You are not required to accept this License, since you have not
337signed it. However, nothing else grants you permission to modify or
338distribute the Library or its derivative works. These actions are
339prohibited by law if you do not accept this License. Therefore, by
340modifying or distributing the Library (or any work based on the
341Library), you indicate your acceptance of this License to do so, and
342all its terms and conditions for copying, distributing or modifying
343the Library or works based on it.
344
345 10. Each time you redistribute the Library (or any work based on the
346Library), the recipient automatically receives a license from the
347original licensor to copy, distribute, link with or modify the Library
348subject to these terms and conditions. You may not impose any further
349restrictions on the recipients' exercise of the rights granted herein.
350You are not responsible for enforcing compliance by third parties to
351this License.
352
353 11. If, as a consequence of a court judgment or allegation of patent
354infringement or for any other reason (not limited to patent issues),
355conditions are imposed on you (whether by court order, agreement or
356otherwise) that contradict the conditions of this License, they do not
357excuse you from the conditions of this License. If you cannot
358distribute so as to satisfy simultaneously your obligations under this
359License and any other pertinent obligations, then as a consequence you
360may not distribute the Library at all. For example, if a patent
361license would not permit royalty-free redistribution of the Library by
362all those who receive copies directly or indirectly through you, then
363the only way you could satisfy both it and this License would be to
364refrain entirely from distribution of the Library.
365
366If any portion of this section is held invalid or unenforceable under any
367particular circumstance, the balance of the section is intended to apply,
368and the section as a whole is intended to apply in other circumstances.
369
370It is not the purpose of this section to induce you to infringe any
371patents or other property right claims or to contest validity of any
372such claims; this section has the sole purpose of protecting the
373integrity of the free software distribution system which is
374implemented by public license practices. Many people have made
375generous contributions to the wide range of software distributed
376through that system in reliance on consistent application of that
377system; it is up to the author/donor to decide if he or she is willing
378to distribute software through any other system and a licensee cannot
379impose that choice.
380
381This section is intended to make thoroughly clear what is believed to
382be a consequence of the rest of this License.
383
384 12. If the distribution and/or use of the Library is restricted in
385certain countries either by patents or by copyrighted interfaces, the
386original copyright holder who places the Library under this License may add
387an explicit geographical distribution limitation excluding those countries,
388so that distribution is permitted only in or among countries not thus
389excluded. In such case, this License incorporates the limitation as if
390written in the body of this License.
391
392 13. The Free Software Foundation may publish revised and/or new
393versions of the Library General Public License from time to time.
394Such new versions will be similar in spirit to the present version,
395but may differ in detail to address new problems or concerns.
396
397Each version is given a distinguishing version number. If the Library
398specifies a version number of this License which applies to it and
399"any later version", you have the option of following the terms and
400conditions either of that version or of any later version published by
401the Free Software Foundation. If the Library does not specify a
402license version number, you may choose any version ever published by
403the Free Software Foundation.
404
405 14. If you wish to incorporate parts of the Library into other free
406programs whose distribution conditions are incompatible with these,
407write to the author to ask for permission. For software which is
408copyrighted by the Free Software Foundation, write to the Free
409Software Foundation; we sometimes make exceptions for this. Our
410decision will be guided by the two goals of preserving the free status
411of all derivatives of our free software and of promoting the sharing
412and reuse of software generally.
413
414 NO WARRANTY
415
416 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
417WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
418EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
419OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
420KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
421IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
422PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
423LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
424THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
425
426 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
427WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
428AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
429FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
430CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
431LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
432RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
433FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
434SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
435DAMAGES.
436
437 END OF TERMS AND CONDITIONS
438
diff --git a/apps/plugins/sdl/src/hermes/HeadMMX.h b/apps/plugins/sdl/src/hermes/HeadMMX.h
deleted file mode 100644
index 5d9850cca9..0000000000
--- a/apps/plugins/sdl/src/hermes/HeadMMX.h
+++ /dev/null
@@ -1,100 +0,0 @@
1/*
2 Header definitions for the MMX routines for the HERMES library
3 Copyright (c) 1998 Christian Nentwich (c.nentwich@cs.ucl.ac.uk)
4 This source code is licensed under the GNU LGPL
5
6 Please refer to the file COPYING.LIB contained in the distribution for
7 licensing conditions
8*/
9#include "SDL_config.h"
10
11#ifndef __HERMES_HEAD_MMX__
12#define __HERMES_HEAD_MMX__
13
14
15/* If you cannot stand ifdefs, then please do not look into this file, it's
16 going to end your life :) */
17
18#ifdef X86_ASSEMBLER
19
20
21#ifdef __cplusplus
22extern "C" {
23#endif
24
25void STACKCALL ConvertMMX(HermesConverterInterface *);
26
27void STACKCALL ClearMMX_32(HermesClearInterface *);
28void STACKCALL ClearMMX_24(HermesClearInterface *);
29void STACKCALL ClearMMX_16(HermesClearInterface *);
30void STACKCALL ClearMMX_8(HermesClearInterface *);
31
32void ConvertMMXpII32_24RGB888();
33void ConvertMMXpII32_16RGB565();
34void ConvertMMXpII32_16BGR565();
35void ConvertMMXpII32_16RGB555();
36void ConvertMMXpII32_16BGR565();
37void ConvertMMXpII32_16BGR555();
38
39void ConvertMMXp32_16RGB555();
40
41#ifdef __cplusplus
42}
43#endif
44
45
46
47/* Fix the underscore business with ELF compilers */
48
49#if (defined(__ELF__) && defined(__GNUC__)) || defined(__SUNPRO_C)
50 #ifdef __cplusplus
51 extern "C" {
52 #endif
53
54 extern void _ConvertMMX(HermesConverterInterface *);
55 extern void _ConvertMMXpII32_24RGB888();
56 extern void _ConvertMMXpII32_16RGB565();
57 extern void _ConvertMMXpII32_16BGR565();
58 extern void _ConvertMMXpII32_16RGB555();
59 extern void _ConvertMMXpII32_16BGR555();
60
61 #define ConvertMMX _ConvertMMX
62 #define ConvertMMXpII32_24RGB888 _ConvertMMXpII32_24RGB888
63 #define ConvertMMXpII32_16RGB565 _ConvertMMXpII32_16RGB565
64 #define ConvertMMXpII32_16BGR565 _ConvertMMXpII32_16BGR565
65 #define ConvertMMXpII32_16RGB555 _ConvertMMXpII32_16RGB555
66 #define ConvertMMXpII32_16BGR555 _ConvertMMXpII32_16BGR555
67
68 #ifdef __cplusplus
69 }
70 #endif
71
72#endif /* ELF and GNUC */
73
74
75
76
77/* Make it work with Watcom */
78#ifdef __WATCOMC__
79#pragma warning 601 9
80
81#pragma aux ConvertMMX "_*" modify [EAX EBX ECX EDX ESI EDI]
82
83#pragma aux ClearMMX_32 "_*" modify [EAX EBX ECX EDX ESI EDI]
84#pragma aux ClearMMX_24 "_*" modify [EAX EBX ECX EDX ESI EDI]
85#pragma aux ClearMMX_16 "_*" modify [EAX EBX ECX EDX ESI EDI]
86#pragma aux ClearMMX_8 "_*" modify [EAX EBX ECX EDX ESI EDI]
87
88#pragma aux ConvertMMXpII32_24RGB888 "_*"
89#pragma aux ConvertMMXpII32_16RGB565 "_*"
90#pragma aux ConvertMMXpII32_16BGR565 "_*"
91#pragma aux ConvertMMXpII32_16RGB555 "_*"
92#pragma aux ConvertMMXpII32_16BGR555 "_*"
93#pragma aux ConvertMMXp32_16RGB555 "_*"
94
95#endif /* WATCOM */
96
97#endif /* X86_ASSEMBLER */
98
99
100#endif
diff --git a/apps/plugins/sdl/src/hermes/HeadX86.h b/apps/plugins/sdl/src/hermes/HeadX86.h
deleted file mode 100644
index fc6b6ddddf..0000000000
--- a/apps/plugins/sdl/src/hermes/HeadX86.h
+++ /dev/null
@@ -1,186 +0,0 @@
1/*
2 Header definitions for the x86 routines for the HERMES library
3 Copyright (c) 1998 Christian Nentwich (brn@eleet.mcb.at)
4 This source code is licensed under the GNU LGPL
5
6 Please refer to the file COPYING.LIB contained in the distribution for
7 licensing conditions
8*/
9
10#ifndef __HERMES_HEAD_X86__
11#define __HERMES_HEAD_X86__
12
13
14#ifdef X86_ASSEMBLER
15
16/* If you can't stand IFDEFS, then close your eyes now, please :) */
17
18/* Ok, we start with normal function definitions */
19#ifdef __cplusplus
20extern "C" {
21#endif
22
23
24void STACKCALL ConvertX86(HermesConverterInterface *);
25void STACKCALL ClearX86_32(HermesClearInterface *);
26void STACKCALL ClearX86_24(HermesClearInterface *);
27void STACKCALL ClearX86_16(HermesClearInterface *);
28void STACKCALL ClearX86_8(HermesClearInterface *);
29
30int STACKCALL Hermes_X86_CPU();
31
32void ConvertX86p32_32BGR888();
33void ConvertX86p32_32RGBA888();
34void ConvertX86p32_32BGRA888();
35void ConvertX86p32_24RGB888();
36void ConvertX86p32_24BGR888();
37void ConvertX86p32_16RGB565();
38void ConvertX86p32_16BGR565();
39void ConvertX86p32_16RGB555();
40void ConvertX86p32_16BGR555();
41void ConvertX86p32_8RGB332();
42
43void ConvertX86p16_32RGB888();
44void ConvertX86p16_32BGR888();
45void ConvertX86p16_32RGBA888();
46void ConvertX86p16_32BGRA888();
47void ConvertX86p16_24RGB888();
48void ConvertX86p16_24BGR888();
49void ConvertX86p16_16BGR565();
50void ConvertX86p16_16RGB555();
51void ConvertX86p16_16BGR555();
52void ConvertX86p16_8RGB332();
53
54void CopyX86p_4byte();
55void CopyX86p_3byte();
56void CopyX86p_2byte();
57void CopyX86p_1byte();
58
59void ConvertX86pI8_32();
60void ConvertX86pI8_24();
61void ConvertX86pI8_16();
62
63extern int ConvertX86p16_32RGB888_LUT_X86[512];
64extern int ConvertX86p16_32BGR888_LUT_X86[512];
65extern int ConvertX86p16_32RGBA888_LUT_X86[512];
66extern int ConvertX86p16_32BGRA888_LUT_X86[512];
67
68#ifdef __cplusplus
69}
70#endif
71
72
73
74
75/* Now fix up the ELF underscore problem */
76
77#if (defined(__ELF__) && defined(__GNUC__)) || defined(__SUNPRO_C)
78 #ifdef __cplusplus
79 extern "C" {
80 #endif
81
82 extern int _Hermes_X86_CPU();
83
84 extern void _ConvertX86(HermesConverterInterface *);
85
86 extern void _ConvertX86p32_32BGR888();
87 extern void _ConvertX86p32_32RGBA888();
88 extern void _ConvertX86p32_32BGRA888();
89 extern void _ConvertX86p32_24RGB888();
90 extern void _ConvertX86p32_24BGR888();
91 extern void _ConvertX86p32_16RGB565();
92 extern void _ConvertX86p32_16BGR565();
93 extern void _ConvertX86p32_16RGB555();
94 extern void _ConvertX86p32_16BGR555();
95 extern void _ConvertX86p32_8RGB332();
96
97 extern void _ConvertX86p16_16BGR565();
98 extern void _ConvertX86p16_16RGB555();
99 extern void _ConvertX86p16_16BGR555();
100 extern void _ConvertX86p16_8RGB332();
101
102
103 #define Hermes_X86_CPU _Hermes_X86_CPU
104
105 #define ConvertX86 _ConvertX86
106
107 #define ConvertX86p32_32BGR888 _ConvertX86p32_32BGR888
108 #define ConvertX86p32_32RGBA888 _ConvertX86p32_32RGBA888
109 #define ConvertX86p32_32BGRA888 _ConvertX86p32_32BGRA888
110 #define ConvertX86p32_24RGB888 _ConvertX86p32_24RGB888
111 #define ConvertX86p32_24BGR888 _ConvertX86p32_24BGR888
112 #define ConvertX86p32_16RGB565 _ConvertX86p32_16RGB565
113 #define ConvertX86p32_16BGR565 _ConvertX86p32_16BGR565
114 #define ConvertX86p32_16RGB555 _ConvertX86p32_16RGB555
115 #define ConvertX86p32_16BGR555 _ConvertX86p32_16BGR555
116 #define ConvertX86p32_8RGB332 _ConvertX86p32_8RGB332
117
118 #define ConvertX86p16_16BGR565 _ConvertX86p16_16BGR565
119 #define ConvertX86p16_16RGB555 _ConvertX86p16_16RGB555
120 #define ConvertX86p16_16BGR555 _ConvertX86p16_16BGR555
121 #define ConvertX86p16_8RGB332 _ConvertX86p16_8RGB332
122
123
124 #ifdef __cplusplus
125 }
126 #endif
127
128#endif /* ELF & GNU */
129
130
131
132/* Make it run with WATCOM C */
133#ifdef __WATCOMC__
134#pragma warning 601 9
135
136#pragma aux Hermes_X86_CPU "_*"
137
138#pragma aux ConvertX86 "_*" modify [EAX EBX ECX EDX ESI EDI]
139#pragma aux ClearX86_32 "_*" modify [EAX EBX ECX EDX ESI EDI]
140#pragma aux ClearX86_24 "_*" modify [EAX EBX ECX EDX ESI EDI]
141#pragma aux ClearX86_16 "_*" modify [EAX EBX ECX EDX ESI EDI]
142#pragma aux ClearX86_8 "_*" modify [EAX EBX ECX EDX ESI EDI]
143
144#pragma aux ConvertX86p32_32BGR888 "_*"
145#pragma aux ConvertX86p32_32RGBA888 "_*"
146#pragma aux ConvertX86p32_32BGRA888 "_*"
147#pragma aux ConvertX86p32_24RGB888 "_*"
148#pragma aux ConvertX86p32_24BGR888 "_*"
149#pragma aux ConvertX86p32_16RGB565 "_*"
150#pragma aux ConvertX86p32_16BGR565 "_*"
151#pragma aux ConvertX86p32_16RGB555 "_*"
152#pragma aux ConvertX86p32_16BGR555 "_*"
153#pragma aux ConvertX86p32_8RGB332 "_*"
154
155#pragma aux ConvertX86p16_32RGB888 "_*"
156#pragma aux ConvertX86p16_32BGR888 "_*"
157#pragma aux ConvertX86p16_32RGBA888 "_*"
158#pragma aux ConvertX86p16_32BGRA888 "_*"
159#pragma aux ConvertX86p16_24RGB888 "_*"
160#pragma aux ConvertX86p16_24BGR888 "_*"
161#pragma aux ConvertX86p16_16BGR565 "_*"
162#pragma aux ConvertX86p16_16RGB555 "_*"
163#pragma aux ConvertX86p16_16BGR555 "_*"
164#pragma aux ConvertX86p16_8RGB332 "_*"
165
166#pragma aux CopyX86p_4byte "_*"
167#pragma aux CopyX86p_3byte "_*"
168#pragma aux CopyX86p_2byte "_*"
169#pragma aux CopyX86p_1byte "_*"
170
171#pragma aux ConvertX86pI8_32 "_*"
172#pragma aux ConvertX86pI8_24 "_*"
173#pragma aux ConvertX86pI8_16 "_*"
174
175#pragma aux ConvertX86p16_32RGB888_LUT_X86 "_*"
176#pragma aux ConvertX86p16_32BGR888_LUT_X86 "_*"
177#pragma aux ConvertX86p16_32RGBA888_LUT_X86 "_*"
178#pragma aux ConvertX86p16_32BGRA888_LUT_X86 "_*"
179
180#endif /* __WATCOMC__ */
181
182
183#endif /* X86_ASSEMBLER */
184
185
186#endif
diff --git a/apps/plugins/sdl/src/hermes/README b/apps/plugins/sdl/src/hermes/README
deleted file mode 100644
index a03b6cfda4..0000000000
--- a/apps/plugins/sdl/src/hermes/README
+++ /dev/null
@@ -1,13 +0,0 @@
1HERMES 1.2.4 (c)1998 Christian Nentwich (brn) (c.nentwich@cs.ucl.ac.uk)
2and quite a few assembler routines (c) Glenn Fielder (gaffer@gaffer.org)
3
4This library and all the files enclosed in this package are free software
5under the terms of the GNU Library General Public License (LGPL). Please
6refer to the included file COPYING.LIB for the exact terms.
7----------------------------------------------------------------------------
8
9This is a stripped down version of HERMES, including only the x86 assembler
10converters, for use with Simple DirectMedia Layer.
11
12The full HERMES library is available at: http://hermes.terminal.at/
13
diff --git a/apps/plugins/sdl/src/hermes/common.inc b/apps/plugins/sdl/src/hermes/common.inc
deleted file mode 100644
index 9587e6ffbd..0000000000
--- a/apps/plugins/sdl/src/hermes/common.inc
+++ /dev/null
@@ -1,9 +0,0 @@
1; Some common macros for hermes nasm code
2
3%macro SDL_FUNC 1
4%ifdef HIDDEN_VISIBILITY
5GLOBAL %1:function hidden
6%else
7GLOBAL %1
8%endif
9%endmacro
diff --git a/apps/plugins/sdl/src/hermes/mmx_main.asm b/apps/plugins/sdl/src/hermes/mmx_main.asm
deleted file mode 100644
index 00032b95c6..0000000000
--- a/apps/plugins/sdl/src/hermes/mmx_main.asm
+++ /dev/null
@@ -1,74 +0,0 @@
1;
2; mmx format converter main loops for HERMES
3; Some routines Copyright (c) 1998 Christian Nentwich (c.nentwich@cs.ucl.ac.uk)
4; This source code is licensed under the GNU LGPL
5;
6; Please refer to the file COPYING.LIB contained in the distribution for
7; licensing conditions
8;
9
10BITS 32
11
12%include "common.inc"
13
14SDL_FUNC _ConvertMMX
15
16SECTION .text
17
18;; _ConvertMMX:
19;; [ESP+8] ConverterInfo*
20;; --------------------------------------------------------------------------
21;; ConverterInfo (ebp+..)
22;; 0: void *s_pixels
23;; 4: int s_width
24;; 8: int s_height
25;; 12: int s_add
26;; 16: void *d_pixels
27;; 20: int d_width
28;; 24: int d_height
29;; 28: int d_add
30;; 32: void (*converter_function)()
31;; 36: int32 *lookup
32
33_ConvertMMX:
34 push ebp
35 mov ebp,esp
36
37; Save the registers used by the blitters, necessary for optimized code
38 pusha
39
40 mov eax,[ebp+8]
41
42 cmp dword [eax+4],BYTE 0
43 je endconvert
44
45 mov ebp,eax
46
47 mov esi,[ebp+0]
48 mov edi,[ebp+16]
49
50y_loop:
51 mov ecx,[ebp+4]
52
53 call [ebp+32]
54
55 add esi,[ebp+12]
56 add edi,[ebp+28]
57
58 dec dword [ebp+8]
59 jnz y_loop
60
61
62; Restore the registers used by the blitters, necessary for optimized code
63 popa
64
65 pop ebp
66
67endconvert:
68 emms
69
70 ret
71
72%ifidn __OUTPUT_FORMAT__,elf32
73section .note.GNU-stack noalloc noexec nowrite progbits
74%endif
diff --git a/apps/plugins/sdl/src/hermes/mmxp2_32.asm b/apps/plugins/sdl/src/hermes/mmxp2_32.asm
deleted file mode 100644
index 20c3277a26..0000000000
--- a/apps/plugins/sdl/src/hermes/mmxp2_32.asm
+++ /dev/null
@@ -1,405 +0,0 @@
1;
2; pII-optimised MMX format converters for HERMES
3; Copyright (c) 1998 Christian Nentwich (c.nentwich@cs.ucl.ac.uk)
4; and (c) 1999 Jonathan Matthew (jmatthew@uq.net.au)
5; This source code is licensed under the GNU LGPL
6;
7; Please refer to the file COPYING.LIB contained in the distribution for
8; licensing conditions
9;
10; COPYRIGHT NOTICE
11;
12; This file partly contains code that is (c) Intel Corporation, specifically
13; the mode detection routine, and the converter to 15 bit (8 pixel
14; conversion routine from the mmx programming tutorial pages).
15;
16;
17; These routines aren't exactly pII optimised - it's just that as they
18; are, they're terrible on p5 MMXs, but less so on pIIs. Someone needs to
19; optimise them for p5 MMXs..
20
21BITS 32
22
23%include "common.inc"
24
25SDL_FUNC _ConvertMMXpII32_24RGB888
26SDL_FUNC _ConvertMMXpII32_16RGB565
27SDL_FUNC _ConvertMMXpII32_16BGR565
28SDL_FUNC _ConvertMMXpII32_16RGB555
29SDL_FUNC _ConvertMMXpII32_16BGR555
30
31;; Macros for conversion routines
32
33%macro _push_immq_mask 1
34 push dword %1
35 push dword %1
36%endmacro
37
38%macro load_immq 2
39 _push_immq_mask %2
40 movq %1, [esp]
41%endmacro
42
43%macro pand_immq 2
44 _push_immq_mask %2
45 pand %1, [esp]
46%endmacro
47
48%define CLEANUP_IMMQ_LOADS(num) \
49 add esp, byte 8 * num
50
51%define mmx32_rgb888_mask 00ffffffh
52%define mmx32_rgb565_b 000000f8h
53%define mmx32_rgb565_g 0000fc00h
54%define mmx32_rgb565_r 00f80000h
55
56%define mmx32_rgb555_rb 00f800f8h
57%define mmx32_rgb555_g 0000f800h
58%define mmx32_rgb555_mul 20000008h
59%define mmx32_bgr555_mul 00082000h
60
61SECTION .text
62
63_ConvertMMXpII32_24RGB888:
64
65 ; set up mm6 as the mask, mm7 as zero
66 load_immq mm6, mmx32_rgb888_mask
67 CLEANUP_IMMQ_LOADS(1)
68 pxor mm7, mm7
69
70 mov edx, ecx ; save ecx
71 and ecx, 0fffffffch ; clear lower two bits
72 jnz .L1
73 jmp .L2
74
75.L1:
76
77 movq mm0, [esi] ; A R G B a r g b
78 pand mm0, mm6 ; 0 R G B 0 r g b
79 movq mm1, [esi+8] ; A R G B a r g b
80 pand mm1, mm6 ; 0 R G B 0 r g b
81
82 movq mm2, mm0 ; 0 R G B 0 r g b
83 punpckhdq mm2, mm7 ; 0 0 0 0 0 R G B
84 punpckldq mm0, mm7 ; 0 0 0 0 0 r g b
85 psllq mm2, 24 ; 0 0 R G B 0 0 0
86 por mm0, mm2 ; 0 0 R G B r g b
87
88 movq mm3, mm1 ; 0 R G B 0 r g b
89 psllq mm3, 48 ; g b 0 0 0 0 0 0
90 por mm0, mm3 ; g b R G B r g b
91
92 movq mm4, mm1 ; 0 R G B 0 r g b
93 punpckhdq mm4, mm7 ; 0 0 0 0 0 R G B
94 punpckldq mm1, mm7 ; 0 0 0 0 0 r g b
95 psrlq mm1, 16 ; 0 0 0 R G B 0 r
96 psllq mm4, 8 ; 0 0 0 0 R G B 0
97 por mm1, mm4 ; 0 0 0 0 R G B r
98
99 movq [edi], mm0
100 add esi, BYTE 16
101 movd [edi+8], mm1
102 add edi, BYTE 12
103 sub ecx, BYTE 4
104 jnz .L1
105
106.L2:
107 mov ecx, edx
108 and ecx, BYTE 3
109 jz .L4
110.L3:
111 mov al, [esi]
112 mov bl, [esi+1]
113 mov dl, [esi+2]
114 mov [edi], al
115 mov [edi+1], bl
116 mov [edi+2], dl
117 add esi, BYTE 4
118 add edi, BYTE 3
119 dec ecx
120 jnz .L3
121.L4:
122 retn
123
124
125
126_ConvertMMXpII32_16RGB565:
127
128 ; set up masks
129 load_immq mm5, mmx32_rgb565_b
130 load_immq mm6, mmx32_rgb565_g
131 load_immq mm7, mmx32_rgb565_r
132 CLEANUP_IMMQ_LOADS(3)
133
134 mov edx, ecx
135 shr ecx, 2
136 jnz .L1
137 jmp .L2 ; not necessary at the moment, but doesn't hurt (much)
138
139.L1:
140 movq mm0, [esi] ; argb
141 movq mm1, mm0 ; argb
142 pand mm0, mm6 ; 00g0
143 movq mm3, mm1 ; argb
144 pand mm1, mm5 ; 000b
145 pand mm3, mm7 ; 0r00
146 pslld mm1, 2 ; 0 0 000000bb bbb00000
147 por mm0, mm1 ; 0 0 ggggggbb bbb00000
148 psrld mm0, 5 ; 0 0 00000ggg gggbbbbb
149
150 movq mm4, [esi+8] ; argb
151 movq mm2, mm4 ; argb
152 pand mm4, mm6 ; 00g0
153 movq mm1, mm2 ; argb
154 pand mm2, mm5 ; 000b
155 pand mm1, mm7 ; 0r00
156 pslld mm2, 2 ; 0 0 000000bb bbb00000
157 por mm4, mm2 ; 0 0 ggggggbb bbb00000
158 psrld mm4, 5 ; 0 0 00000ggg gggbbbbb
159
160 packuswb mm3, mm1 ; R 0 r 0
161 packssdw mm0, mm4 ; as above.. ish
162 por mm0, mm3 ; done.
163 movq [edi], mm0
164
165 add esi, 16
166 add edi, 8
167 dec ecx
168 jnz .L1
169
170.L2:
171 mov ecx, edx
172 and ecx, BYTE 3
173 jz .L4
174.L3:
175 mov al, [esi]
176 mov bh, [esi+1]
177 mov ah, [esi+2]
178 shr al, 3
179 and eax, 0F81Fh ; BYTE?
180 shr ebx, 5
181 and ebx, 07E0h ; BYTE?
182 add eax, ebx
183 mov [edi], al
184 mov [edi+1], ah
185 add esi, BYTE 4
186 add edi, BYTE 2
187 dec ecx
188 jnz .L3
189
190.L4:
191 retn
192
193
194_ConvertMMXpII32_16BGR565:
195
196 load_immq mm5, mmx32_rgb565_r
197 load_immq mm6, mmx32_rgb565_g
198 load_immq mm7, mmx32_rgb565_b
199 CLEANUP_IMMQ_LOADS(3)
200
201 mov edx, ecx
202 shr ecx, 2
203 jnz .L1
204 jmp .L2
205
206.L1:
207 movq mm0, [esi] ; a r g b
208 movq mm1, mm0 ; a r g b
209 pand mm0, mm6 ; 0 0 g 0
210 movq mm3, mm1 ; a r g b
211 pand mm1, mm5 ; 0 r 0 0
212 pand mm3, mm7 ; 0 0 0 b
213
214 psllq mm3, 16 ; 0 b 0 0
215 psrld mm1, 14 ; 0 0 000000rr rrr00000
216 por mm0, mm1 ; 0 0 ggggggrr rrr00000
217 psrld mm0, 5 ; 0 0 00000ggg gggrrrrr
218
219 movq mm4, [esi+8] ; a r g b
220 movq mm2, mm4 ; a r g b
221 pand mm4, mm6 ; 0 0 g 0
222 movq mm1, mm2 ; a r g b
223 pand mm2, mm5 ; 0 r 0 0
224 pand mm1, mm7 ; 0 0 0 b
225
226 psllq mm1, 16 ; 0 b 0 0
227 psrld mm2, 14 ; 0 0 000000rr rrr00000
228 por mm4, mm2 ; 0 0 ggggggrr rrr00000
229 psrld mm4, 5 ; 0 0 00000ggg gggrrrrr
230
231 packuswb mm3, mm1 ; BBBBB000 00000000 bbbbb000 00000000
232 packssdw mm0, mm4 ; 00000GGG GGGRRRRR 00000GGG GGGRRRRR
233 por mm0, mm3 ; BBBBBGGG GGGRRRRR bbbbbggg gggrrrrr
234 movq [edi], mm0
235
236 add esi, BYTE 16
237 add edi, BYTE 8
238 dec ecx
239 jnz .L1
240
241.L2:
242 and edx, BYTE 3
243 jz .L4
244.L3:
245 mov al, [esi+2]
246 mov bh, [esi+1]
247 mov ah, [esi]
248 shr al, 3
249 and eax, 0F81Fh ; BYTE ?
250 shr ebx, 5
251 and ebx, 07E0h ; BYTE ?
252 add eax, ebx
253 mov [edi], al
254 mov [edi+1], ah
255 add esi, BYTE 4
256 add edi, BYTE 2
257 dec edx
258 jnz .L3
259
260.L4:
261 retn
262
263_ConvertMMXpII32_16BGR555:
264
265 ; the 16BGR555 converter is identical to the RGB555 one,
266 ; except it uses a different multiplier for the pmaddwd
267 ; instruction. cool huh.
268
269 load_immq mm7, mmx32_bgr555_mul
270 jmp _convert_bgr555_cheat
271
272; This is the same as the Intel version.. they obviously went to
273; much more trouble to expand/coil the loop than I did, so theirs
274; would almost certainly be faster, even if only a little.
275; I did rename 'mmx32_rgb555_add' to 'mmx32_rgb555_mul', which is
276; (I think) a more accurate name..
277_ConvertMMXpII32_16RGB555:
278
279 load_immq mm7, mmx32_rgb555_mul
280_convert_bgr555_cheat:
281 load_immq mm6, mmx32_rgb555_g
282 CLEANUP_IMMQ_LOADS(2)
283
284 mov edx,ecx ; Save ecx
285
286 and ecx,DWORD 0fffffff8h ; clear lower three bits
287 jnz .L_OK
288 jmp near .L2
289
290.L_OK:
291
292 movq mm2,[esi+8]
293
294 movq mm0,[esi]
295 movq mm3,mm2
296
297 pand_immq mm3, mmx32_rgb555_rb
298 movq mm1,mm0
299
300 pand_immq mm1, mmx32_rgb555_rb
301 pmaddwd mm3,mm7
302
303 CLEANUP_IMMQ_LOADS(2)
304
305 pmaddwd mm1,mm7
306 pand mm2,mm6
307
308.L1:
309 movq mm4,[esi+24]
310 pand mm0,mm6
311
312 movq mm5,[esi+16]
313 por mm3,mm2
314
315 psrld mm3,6
316 por mm1,mm0
317
318 movq mm0,mm4
319 psrld mm1,6
320
321 pand_immq mm0, mmx32_rgb555_rb
322 packssdw mm1,mm3
323
324 movq mm3,mm5
325 pmaddwd mm0,mm7
326
327 pand_immq mm3, mmx32_rgb555_rb
328 pand mm4,mm6
329
330 movq [edi],mm1
331 pmaddwd mm3,mm7
332
333 add esi,BYTE 32
334 por mm4,mm0
335
336 pand mm5,mm6
337 psrld mm4,6
338
339 movq mm2,[esi+8]
340 por mm5,mm3
341
342 movq mm0,[esi]
343 psrld mm5,6
344
345 movq mm3,mm2
346 movq mm1,mm0
347
348 pand_immq mm3, mmx32_rgb555_rb
349 packssdw mm5,mm4
350
351 pand_immq mm1, mmx32_rgb555_rb
352 pand mm2,mm6
353
354 CLEANUP_IMMQ_LOADS(4)
355
356 movq [edi+8],mm5
357 pmaddwd mm3,mm7
358
359 pmaddwd mm1,mm7
360 add edi,BYTE 16
361
362 sub ecx,BYTE 8
363 jz .L2
364 jmp .L1
365
366
367.L2:
368 mov ecx,edx
369
370 and ecx,BYTE 7
371 jz .L4
372
373.L3:
374 mov ebx,[esi]
375 add esi,BYTE 4
376
377 mov eax,ebx
378 mov edx,ebx
379
380 shr eax,3
381 shr edx,6
382
383 and eax,BYTE 0000000000011111b
384 and edx, 0000001111100000b
385
386 shr ebx,9
387
388 or eax,edx
389
390 and ebx, 0111110000000000b
391
392 or eax,ebx
393
394 mov [edi],ax
395 add edi,BYTE 2
396
397 dec ecx
398 jnz .L3
399
400.L4:
401 retn
402
403%ifidn __OUTPUT_FORMAT__,elf32
404section .note.GNU-stack noalloc noexec nowrite progbits
405%endif
diff --git a/apps/plugins/sdl/src/hermes/x86_main.asm b/apps/plugins/sdl/src/hermes/x86_main.asm
deleted file mode 100644
index f7dd3db70c..0000000000
--- a/apps/plugins/sdl/src/hermes/x86_main.asm
+++ /dev/null
@@ -1,75 +0,0 @@
1;
2; x86 format converters for HERMES
3; Some routines Copyright (c) 1998 Christian Nentwich (brn@eleet.mcb.at)
4; This source code is licensed under the GNU LGPL
5;
6; Please refer to the file COPYING.LIB contained in the distribution for
7; licensing conditions
8;
9; Most routines are (c) Glenn Fiedler (ptc@gaffer.org), used with permission
10;
11
12BITS 32
13
14%include "common.inc"
15
16SDL_FUNC _ConvertX86
17
18SECTION .text
19
20;; _ConvertX86:
21;; [ESP+8] ConverterInfo*
22;; --------------------------------------------------------------------------
23;; ConverterInfo (ebp+..)
24;; 0: void *s_pixels
25;; 4: int s_width
26;; 8: int s_height
27;; 12: int s_add
28;; 16: void *d_pixels
29;; 20: int d_width
30;; 24: int d_height
31;; 28: int d_add
32;; 32: void (*converter_function)()
33;; 36: int32 *lookup
34
35_ConvertX86:
36 push ebp
37 mov ebp,esp
38
39; Save the registers used by the blitters, necessary for optimized code
40 pusha
41
42 mov eax,[ebp+8]
43
44 cmp dword [eax+4],BYTE 0
45 je endconvert
46
47 mov ebp,eax
48
49 mov esi,[ebp+0]
50 mov edi,[ebp+16]
51
52y_loop:
53 mov ecx,[ebp+4]
54
55 call [ebp+32]
56
57 add esi,[ebp+12]
58 add edi,[ebp+28]
59
60 dec dword [ebp+8]
61 jnz y_loop
62
63; Restore the registers used by the blitters, necessary for optimized code
64 popa
65
66 pop ebp
67
68endconvert:
69 ret
70
71
72
73%ifidn __OUTPUT_FORMAT__,elf32
74section .note.GNU-stack noalloc noexec nowrite progbits
75%endif
diff --git a/apps/plugins/sdl/src/hermes/x86p_16.asm b/apps/plugins/sdl/src/hermes/x86p_16.asm
deleted file mode 100644
index 1801bcd153..0000000000
--- a/apps/plugins/sdl/src/hermes/x86p_16.asm
+++ /dev/null
@@ -1,490 +0,0 @@
1;
2; x86 format converters for HERMES
3; Copyright (c) 1998 Glenn Fielder (gaffer@gaffer.org)
4; This source code is licensed under the GNU LGPL
5;
6; Please refer to the file COPYING.LIB contained in the distribution for
7; licensing conditions
8;
9; Routines adjusted for Hermes by Christian Nentwich (brn@eleet.mcb.at)
10; Used with permission.
11;
12
13BITS 32
14
15%include "common.inc"
16
17SDL_FUNC _ConvertX86p16_16BGR565
18SDL_FUNC _ConvertX86p16_16RGB555
19SDL_FUNC _ConvertX86p16_16BGR555
20SDL_FUNC _ConvertX86p16_8RGB332
21
22EXTERN _ConvertX86
23
24SECTION .text
25
26_ConvertX86p16_16BGR565:
27
28 ; check short
29 cmp ecx,BYTE 16
30 ja .L3
31
32
33.L1: ; short loop
34 mov al,[esi]
35 mov ah,[esi+1]
36 mov ebx,eax
37 mov edx,eax
38 shr eax,11
39 and eax,BYTE 11111b
40 and ebx,11111100000b
41 shl edx,11
42 add eax,ebx
43 add eax,edx
44 mov [edi],al
45 mov [edi+1],ah
46 add esi,BYTE 2
47 add edi,BYTE 2
48 dec ecx
49 jnz .L1
50.L2:
51 retn
52
53.L3: ; head
54 mov eax,edi
55 and eax,BYTE 11b
56 jz .L4
57 mov al,[esi]
58 mov ah,[esi+1]
59 mov ebx,eax
60 mov edx,eax
61 shr eax,11
62 and eax,BYTE 11111b
63 and ebx,11111100000b
64 shl edx,11
65 add eax,ebx
66 add eax,edx
67 mov [edi],al
68 mov [edi+1],ah
69 add esi,BYTE 2
70 add edi,BYTE 2
71 dec ecx
72
73.L4: ; save count
74 push ecx
75
76 ; unroll twice
77 shr ecx,1
78
79 ; point arrays to end
80 lea esi,[esi+ecx*4]
81 lea edi,[edi+ecx*4]
82
83 ; negative counter
84 neg ecx
85 jmp SHORT .L6
86
87.L5: mov [edi+ecx*4-4],eax
88.L6: mov eax,[esi+ecx*4]
89
90 mov ebx,[esi+ecx*4]
91 and eax,07E007E0h
92
93 mov edx,[esi+ecx*4]
94 and ebx,0F800F800h
95
96 shr ebx,11
97 and edx,001F001Fh
98
99 shl edx,11
100 add eax,ebx
101
102 add eax,edx
103 inc ecx
104
105 jnz .L5
106
107 mov [edi+ecx*4-4],eax
108
109 ; tail
110 pop ecx
111 and ecx,BYTE 1
112 jz .L7
113 mov al,[esi]
114 mov ah,[esi+1]
115 mov ebx,eax
116 mov edx,eax
117 shr eax,11
118 and eax,BYTE 11111b
119 and ebx,11111100000b
120 shl edx,11
121 add eax,ebx
122 add eax,edx
123 mov [edi],al
124 mov [edi+1],ah
125 add esi,BYTE 2
126 add edi,BYTE 2
127
128.L7:
129 retn
130
131
132
133
134
135
136_ConvertX86p16_16RGB555:
137
138 ; check short
139 cmp ecx,BYTE 32
140 ja .L3
141
142
143.L1: ; short loop
144 mov al,[esi]
145 mov ah,[esi+1]
146 mov ebx,eax
147 shr ebx,1
148 and ebx, 0111111111100000b
149 and eax,BYTE 0000000000011111b
150 add eax,ebx
151 mov [edi],al
152 mov [edi+1],ah
153 add esi,BYTE 2
154 add edi,BYTE 2
155 dec ecx
156 jnz .L1
157.L2:
158 retn
159
160.L3: ; head
161 mov eax,edi
162 and eax,BYTE 11b
163 jz .L4
164 mov al,[esi]
165 mov ah,[esi+1]
166 mov ebx,eax
167 shr ebx,1
168 and ebx, 0111111111100000b
169 and eax,BYTE 0000000000011111b
170 add eax,ebx
171 mov [edi],al
172 mov [edi+1],ah
173 add esi,BYTE 2
174 add edi,BYTE 2
175 dec ecx
176
177.L4: ; save ebp
178 push ebp
179
180 ; save count
181 push ecx
182
183 ; unroll four times
184 shr ecx,2
185
186 ; point arrays to end
187 lea esi,[esi+ecx*8]
188 lea edi,[edi+ecx*8]
189
190 ; negative counter
191 xor ebp,ebp
192 sub ebp,ecx
193
194.L5: mov eax,[esi+ebp*8] ; agi?
195 mov ecx,[esi+ebp*8+4]
196
197 mov ebx,eax
198 mov edx,ecx
199
200 and eax,0FFC0FFC0h
201 and ecx,0FFC0FFC0h
202
203 shr eax,1
204 and ebx,001F001Fh
205
206 shr ecx,1
207 and edx,001F001Fh
208
209 add eax,ebx
210 add ecx,edx
211
212 mov [edi+ebp*8],eax
213 mov [edi+ebp*8+4],ecx
214
215 inc ebp
216 jnz .L5
217
218 ; tail
219 pop ecx
220.L6: and ecx,BYTE 11b
221 jz .L7
222 mov al,[esi]
223 mov ah,[esi+1]
224 mov ebx,eax
225 shr ebx,1
226 and ebx, 0111111111100000b
227 and eax,BYTE 0000000000011111b
228 add eax,ebx
229 mov [edi],al
230 mov [edi+1],ah
231 add esi,BYTE 2
232 add edi,BYTE 2
233 dec ecx
234 jmp SHORT .L6
235
236.L7: pop ebp
237 retn
238
239
240
241
242
243
244_ConvertX86p16_16BGR555:
245
246 ; check short
247 cmp ecx,BYTE 16
248 ja .L3
249
250
251.L1: ; short loop
252 mov al,[esi]
253 mov ah,[esi+1]
254 mov ebx,eax
255 mov edx,eax
256 shr eax,11
257 and eax,BYTE 11111b
258 shr ebx,1
259 and ebx,1111100000b
260 shl edx,10
261 and edx,0111110000000000b
262 add eax,ebx
263 add eax,edx
264 mov [edi],al
265 mov [edi+1],ah
266 add esi,BYTE 2
267 add edi,BYTE 2
268 dec ecx
269 jnz .L1
270.L2:
271 retn
272
273.L3: ; head
274 mov eax,edi
275 and eax,BYTE 11b
276 jz .L4
277 mov al,[esi]
278 mov ah,[esi+1]
279 mov ebx,eax
280 mov edx,eax
281 shr eax,11
282 and eax,BYTE 11111b
283 shr ebx,1
284 and ebx,1111100000b
285 shl edx,10
286 and edx,0111110000000000b
287 add eax,ebx
288 add eax,edx
289 mov [edi],al
290 mov [edi+1],ah
291 add esi,BYTE 2
292 add edi,BYTE 2
293 dec ecx
294
295.L4: ; save count
296 push ecx
297
298 ; unroll twice
299 shr ecx,1
300
301 ; point arrays to end
302 lea esi,[esi+ecx*4]
303 lea edi,[edi+ecx*4]
304
305 ; negative counter
306 neg ecx
307 jmp SHORT .L6
308
309.L5: mov [edi+ecx*4-4],eax
310.L6: mov eax,[esi+ecx*4]
311
312 shr eax,1
313 mov ebx,[esi+ecx*4]
314
315 and eax,03E003E0h
316 mov edx,[esi+ecx*4]
317
318 and ebx,0F800F800h
319
320 shr ebx,11
321 and edx,001F001Fh
322
323 shl edx,10
324 add eax,ebx
325
326 add eax,edx
327 inc ecx
328
329 jnz .L5
330
331 mov [edi+ecx*4-4],eax
332
333 ; tail
334 pop ecx
335 and ecx,BYTE 1
336 jz .L7
337 mov al,[esi]
338 mov ah,[esi+1]
339 mov ebx,eax
340 mov edx,eax
341 shr eax,11
342 and eax,BYTE 11111b
343 shr ebx,1
344 and ebx,1111100000b
345 shl edx,10
346 and edx,0111110000000000b
347 add eax,ebx
348 add eax,edx
349 mov [edi],al
350 mov [edi+1],ah
351 add esi,BYTE 2
352 add edi,BYTE 2
353
354.L7:
355 retn
356
357
358
359
360
361
362_ConvertX86p16_8RGB332:
363
364 ; check short
365 cmp ecx,BYTE 16
366 ja .L3
367
368
369.L1: ; short loop
370 mov al,[esi+0]
371 mov ah,[esi+1]
372 mov ebx,eax
373 mov edx,eax
374 and eax,BYTE 11000b ; blue
375 shr eax,3
376 and ebx,11100000000b ; green
377 shr ebx,6
378 and edx,1110000000000000b ; red
379 shr edx,8
380 add eax,ebx
381 add eax,edx
382 mov [edi],al
383 add esi,BYTE 2
384 inc edi
385 dec ecx
386 jnz .L1
387.L2:
388 retn
389
390.L3: mov eax,edi
391 and eax,BYTE 11b
392 jz .L4
393 mov al,[esi+0]
394 mov ah,[esi+1]
395 mov ebx,eax
396 mov edx,eax
397 and eax,BYTE 11000b ; blue
398 shr eax,3
399 and ebx,11100000000b ; green
400 shr ebx,6
401 and edx,1110000000000000b ; red
402 shr edx,8
403 add eax,ebx
404 add eax,edx
405 mov [edi],al
406 add esi,BYTE 2
407 inc edi
408 dec ecx
409 jmp SHORT .L3
410
411.L4: ; save ebp
412 push ebp
413
414 ; save count
415 push ecx
416
417 ; unroll 4 times
418 shr ecx,2
419
420 ; prestep
421 mov dl,[esi+0]
422 mov bl,[esi+1]
423 mov dh,[esi+2]
424
425.L5: shl edx,16
426 mov bh,[esi+3]
427
428 shl ebx,16
429 mov dl,[esi+4]
430
431 mov dh,[esi+6]
432 mov bl,[esi+5]
433
434 and edx,00011000000110000001100000011000b
435 mov bh,[esi+7]
436
437 ror edx,16+3
438 mov eax,ebx ; setup eax for reds
439
440 and ebx,00000111000001110000011100000111b
441 and eax,11100000111000001110000011100000b ; reds
442
443 ror ebx,16-2
444 add esi,BYTE 8
445
446 ror eax,16
447 add edi,BYTE 4
448
449 add eax,ebx
450 mov bl,[esi+1] ; greens
451
452 add eax,edx
453 mov dl,[esi+0] ; blues
454
455 mov [edi-4],eax
456 mov dh,[esi+2]
457
458 dec ecx
459 jnz .L5
460
461 ; check tail
462 pop ecx
463 and ecx,BYTE 11b
464 jz .L7
465
466.L6: ; tail
467 mov al,[esi+0]
468 mov ah,[esi+1]
469 mov ebx,eax
470 mov edx,eax
471 and eax,BYTE 11000b ; blue
472 shr eax,3
473 and ebx,11100000000b ; green
474 shr ebx,6
475 and edx,1110000000000000b ; red
476 shr edx,8
477 add eax,ebx
478 add eax,edx
479 mov [edi],al
480 add esi,BYTE 2
481 inc edi
482 dec ecx
483 jnz .L6
484
485.L7: pop ebp
486 retn
487
488%ifidn __OUTPUT_FORMAT__,elf32
489section .note.GNU-stack noalloc noexec nowrite progbits
490%endif
diff --git a/apps/plugins/sdl/src/hermes/x86p_32.asm b/apps/plugins/sdl/src/hermes/x86p_32.asm
deleted file mode 100644
index 2b478802d1..0000000000
--- a/apps/plugins/sdl/src/hermes/x86p_32.asm
+++ /dev/null
@@ -1,1044 +0,0 @@
1;
2; x86 format converters for HERMES
3; Some routines Copyright (c) 1998 Christian Nentwich (brn@eleet.mcb.at)
4; This source code is licensed under the GNU LGPL
5;
6; Please refer to the file COPYING.LIB contained in the distribution for
7; licensing conditions
8;
9; Most routines are (c) Glenn Fiedler (ptc@gaffer.org), used with permission
10;
11
12BITS 32
13
14%include "common.inc"
15
16SDL_FUNC _ConvertX86p32_32BGR888
17SDL_FUNC _ConvertX86p32_32RGBA888
18SDL_FUNC _ConvertX86p32_32BGRA888
19SDL_FUNC _ConvertX86p32_24RGB888
20SDL_FUNC _ConvertX86p32_24BGR888
21SDL_FUNC _ConvertX86p32_16RGB565
22SDL_FUNC _ConvertX86p32_16BGR565
23SDL_FUNC _ConvertX86p32_16RGB555
24SDL_FUNC _ConvertX86p32_16BGR555
25SDL_FUNC _ConvertX86p32_8RGB332
26
27SECTION .text
28
29;; _Convert_*
30;; Paramters:
31;; ESI = source
32;; EDI = dest
33;; ECX = amount (NOT 0!!! (the _ConvertX86 routine checks for that though))
34;; Destroys:
35;; EAX, EBX, EDX
36
37
38_ConvertX86p32_32BGR888:
39
40 ; check short
41 cmp ecx,BYTE 32
42 ja .L3
43
44.L1: ; short loop
45 mov edx,[esi]
46 bswap edx
47 ror edx,8
48 mov [edi],edx
49 add esi,BYTE 4
50 add edi,BYTE 4
51 dec ecx
52 jnz .L1
53.L2:
54 retn
55
56.L3: ; save ebp
57 push ebp
58
59 ; unroll four times
60 mov ebp,ecx
61 shr ebp,2
62
63 ; save count
64 push ecx
65
66.L4: mov eax,[esi]
67 mov ebx,[esi+4]
68
69 bswap eax
70
71 bswap ebx
72
73 ror eax,8
74 mov ecx,[esi+8]
75
76 ror ebx,8
77 mov edx,[esi+12]
78
79 bswap ecx
80
81 bswap edx
82
83 ror ecx,8
84 mov [edi+0],eax
85
86 ror edx,8
87 mov [edi+4],ebx
88
89 mov [edi+8],ecx
90 mov [edi+12],edx
91
92 add esi,BYTE 16
93 add edi,BYTE 16
94
95 dec ebp
96 jnz .L4
97
98 ; check tail
99 pop ecx
100 and ecx,BYTE 11b
101 jz .L6
102
103.L5: ; tail loop
104 mov edx,[esi]
105 bswap edx
106 ror edx,8
107 mov [edi],edx
108 add esi,BYTE 4
109 add edi,BYTE 4
110 dec ecx
111 jnz .L5
112
113.L6: pop ebp
114 retn
115
116
117
118
119_ConvertX86p32_32RGBA888:
120
121 ; check short
122 cmp ecx,BYTE 32
123 ja .L3
124
125.L1: ; short loop
126 mov edx,[esi]
127 rol edx,8
128 mov [edi],edx
129 add esi,BYTE 4
130 add edi,BYTE 4
131 dec ecx
132 jnz .L1
133.L2:
134 retn
135
136.L3: ; save ebp
137 push ebp
138
139 ; unroll four times
140 mov ebp,ecx
141 shr ebp,2
142
143 ; save count
144 push ecx
145
146.L4: mov eax,[esi]
147 mov ebx,[esi+4]
148
149 rol eax,8
150 mov ecx,[esi+8]
151
152 rol ebx,8
153 mov edx,[esi+12]
154
155 rol ecx,8
156 mov [edi+0],eax
157
158 rol edx,8
159 mov [edi+4],ebx
160
161 mov [edi+8],ecx
162 mov [edi+12],edx
163
164 add esi,BYTE 16
165 add edi,BYTE 16
166
167 dec ebp
168 jnz .L4
169
170 ; check tail
171 pop ecx
172 and ecx,BYTE 11b
173 jz .L6
174
175.L5: ; tail loop
176 mov edx,[esi]
177 rol edx,8
178 mov [edi],edx
179 add esi,BYTE 4
180 add edi,BYTE 4
181 dec ecx
182 jnz .L5
183
184.L6: pop ebp
185 retn
186
187
188
189
190_ConvertX86p32_32BGRA888:
191
192 ; check short
193 cmp ecx,BYTE 32
194 ja .L3
195
196.L1: ; short loop
197 mov edx,[esi]
198 bswap edx
199 mov [edi],edx
200 add esi,BYTE 4
201 add edi,BYTE 4
202 dec ecx
203 jnz .L1
204.L2:
205 retn
206
207.L3: ; save ebp
208 push ebp
209
210 ; unroll four times
211 mov ebp,ecx
212 shr ebp,2
213
214 ; save count
215 push ecx
216
217.L4: mov eax,[esi]
218 mov ebx,[esi+4]
219
220 mov ecx,[esi+8]
221 mov edx,[esi+12]
222
223 bswap eax
224
225 bswap ebx
226
227 bswap ecx
228
229 bswap edx
230
231 mov [edi+0],eax
232 mov [edi+4],ebx
233
234 mov [edi+8],ecx
235 mov [edi+12],edx
236
237 add esi,BYTE 16
238 add edi,BYTE 16
239
240 dec ebp
241 jnz .L4
242
243 ; check tail
244 pop ecx
245 and ecx,BYTE 11b
246 jz .L6
247
248.L5: ; tail loop
249 mov edx,[esi]
250 bswap edx
251 mov [edi],edx
252 add esi,BYTE 4
253 add edi,BYTE 4
254 dec ecx
255 jnz .L5
256
257.L6: pop ebp
258 retn
259
260
261
262
263;; 32 bit RGB 888 to 24 BIT RGB 888
264
265_ConvertX86p32_24RGB888:
266
267 ; check short
268 cmp ecx,BYTE 32
269 ja .L3
270
271.L1: ; short loop
272 mov al,[esi]
273 mov bl,[esi+1]
274 mov dl,[esi+2]
275 mov [edi],al
276 mov [edi+1],bl
277 mov [edi+2],dl
278 add esi,BYTE 4
279 add edi,BYTE 3
280 dec ecx
281 jnz .L1
282.L2:
283 retn
284
285.L3: ; head
286 mov edx,edi
287 and edx,BYTE 11b
288 jz .L4
289 mov al,[esi]
290 mov bl,[esi+1]
291 mov dl,[esi+2]
292 mov [edi],al
293 mov [edi+1],bl
294 mov [edi+2],dl
295 add esi,BYTE 4
296 add edi,BYTE 3
297 dec ecx
298 jmp SHORT .L3
299
300.L4: ; unroll 4 times
301 push ebp
302 mov ebp,ecx
303 shr ebp,2
304
305 ; save count
306 push ecx
307
308.L5: mov eax,[esi] ; first dword eax = [A][R][G][B]
309 mov ebx,[esi+4] ; second dword ebx = [a][r][g][b]
310
311 shl eax,8 ; eax = [R][G][B][.]
312 mov ecx,[esi+12] ; third dword ecx = [a][r][g][b]
313
314 shl ebx,8 ; ebx = [r][g][b][.]
315 mov al,[esi+4] ; eax = [R][G][B][b]
316
317 ror eax,8 ; eax = [b][R][G][B] (done)
318 mov bh,[esi+8+1] ; ebx = [r][g][G][.]
319
320 mov [edi],eax
321 add edi,BYTE 3*4
322
323 shl ecx,8 ; ecx = [r][g][b][.]
324 mov bl,[esi+8+0] ; ebx = [r][g][G][B]
325
326 rol ebx,16 ; ebx = [G][B][r][g] (done)
327 mov cl,[esi+8+2] ; ecx = [r][g][b][R] (done)
328
329 mov [edi+4-3*4],ebx
330 add esi,BYTE 4*4
331
332 mov [edi+8-3*4],ecx
333 dec ebp
334
335 jnz .L5
336
337 ; check tail
338 pop ecx
339 and ecx,BYTE 11b
340 jz .L7
341
342.L6: ; tail loop
343 mov al,[esi]
344 mov bl,[esi+1]
345 mov dl,[esi+2]
346 mov [edi],al
347 mov [edi+1],bl
348 mov [edi+2],dl
349 add esi,BYTE 4
350 add edi,BYTE 3
351 dec ecx
352 jnz .L6
353
354.L7: pop ebp
355 retn
356
357
358
359
360;; 32 bit RGB 888 to 24 bit BGR 888
361
362_ConvertX86p32_24BGR888:
363
364 ; check short
365 cmp ecx,BYTE 32
366 ja .L3
367
368.L1: ; short loop
369 mov dl,[esi]
370 mov bl,[esi+1]
371 mov al,[esi+2]
372 mov [edi],al
373 mov [edi+1],bl
374 mov [edi+2],dl
375 add esi,BYTE 4
376 add edi,BYTE 3
377 dec ecx
378 jnz .L1
379.L2:
380 retn
381
382.L3: ; head
383 mov edx,edi
384 and edx,BYTE 11b
385 jz .L4
386 mov dl,[esi]
387 mov bl,[esi+1]
388 mov al,[esi+2]
389 mov [edi],al
390 mov [edi+1],bl
391 mov [edi+2],dl
392 add esi,BYTE 4
393 add edi,BYTE 3
394 dec ecx
395 jmp SHORT .L3
396
397.L4: ; unroll 4 times
398 push ebp
399 mov ebp,ecx
400 shr ebp,2
401
402 ; save count
403 push ecx
404
405.L5:
406 mov eax,[esi] ; first dword eax = [A][R][G][B]
407 mov ebx,[esi+4] ; second dword ebx = [a][r][g][b]
408
409 bswap eax ; eax = [B][G][R][A]
410
411 bswap ebx ; ebx = [b][g][r][a]
412
413 mov al,[esi+4+2] ; eax = [B][G][R][r]
414 mov bh,[esi+4+4+1] ; ebx = [b][g][G][a]
415
416 ror eax,8 ; eax = [r][B][G][R] (done)
417 mov bl,[esi+4+4+2] ; ebx = [b][g][G][R]
418
419 ror ebx,16 ; ebx = [G][R][b][g] (done)
420 mov [edi],eax
421
422 mov [edi+4],ebx
423 mov ecx,[esi+12] ; third dword ecx = [a][r][g][b]
424
425 bswap ecx ; ecx = [b][g][r][a]
426
427 mov cl,[esi+8] ; ecx = [b][g][r][B] (done)
428 add esi,BYTE 4*4
429
430 mov [edi+8],ecx
431 add edi,BYTE 3*4
432
433 dec ebp
434 jnz .L5
435
436 ; check tail
437 pop ecx
438 and ecx,BYTE 11b
439 jz .L7
440
441.L6: ; tail loop
442 mov dl,[esi]
443 mov bl,[esi+1]
444 mov al,[esi+2]
445 mov [edi],al
446 mov [edi+1],bl
447 mov [edi+2],dl
448 add esi,BYTE 4
449 add edi,BYTE 3
450 dec ecx
451 jnz .L6
452
453.L7:
454 pop ebp
455 retn
456
457
458
459
460;; 32 bit RGB 888 to 16 BIT RGB 565
461
462_ConvertX86p32_16RGB565:
463 ; check short
464 cmp ecx,BYTE 16
465 ja .L3
466
467.L1: ; short loop
468 mov bl,[esi+0] ; blue
469 mov al,[esi+1] ; green
470 mov ah,[esi+2] ; red
471 shr ah,3
472 and al,11111100b
473 shl eax,3
474 shr bl,3
475 add al,bl
476 mov [edi+0],al
477 mov [edi+1],ah
478 add esi,BYTE 4
479 add edi,BYTE 2
480 dec ecx
481 jnz .L1
482
483.L2: ; End of short loop
484 retn
485
486
487.L3: ; head
488 mov ebx,edi
489 and ebx,BYTE 11b
490 jz .L4
491
492 mov bl,[esi+0] ; blue
493 mov al,[esi+1] ; green
494 mov ah,[esi+2] ; red
495 shr ah,3
496 and al,11111100b
497 shl eax,3
498 shr bl,3
499 add al,bl
500 mov [edi+0],al
501 mov [edi+1],ah
502 add esi,BYTE 4
503 add edi,BYTE 2
504 dec ecx
505
506.L4:
507 ; save count
508 push ecx
509
510 ; unroll twice
511 shr ecx,1
512
513 ; point arrays to end
514 lea esi,[esi+ecx*8]
515 lea edi,[edi+ecx*4]
516
517 ; negative counter
518 neg ecx
519 jmp SHORT .L6
520
521.L5:
522 mov [edi+ecx*4-4],eax
523.L6:
524 mov eax,[esi+ecx*8]
525
526 shr ah,2
527 mov ebx,[esi+ecx*8+4]
528
529 shr eax,3
530 mov edx,[esi+ecx*8+4]
531
532 shr bh,2
533 mov dl,[esi+ecx*8+2]
534
535 shl ebx,13
536 and eax,000007FFh
537
538 shl edx,8
539 and ebx,07FF0000h
540
541 and edx,0F800F800h
542 add eax,ebx
543
544 add eax,edx
545 inc ecx
546
547 jnz .L5
548
549 mov [edi+ecx*4-4],eax
550
551 ; tail
552 pop ecx
553 test cl,1
554 jz .L7
555
556 mov bl,[esi+0] ; blue
557 mov al,[esi+1] ; green
558 mov ah,[esi+2] ; red
559 shr ah,3
560 and al,11111100b
561 shl eax,3
562 shr bl,3
563 add al,bl
564 mov [edi+0],al
565 mov [edi+1],ah
566 add esi,BYTE 4
567 add edi,BYTE 2
568
569.L7:
570 retn
571
572
573
574
575;; 32 bit RGB 888 to 16 BIT BGR 565
576
577_ConvertX86p32_16BGR565:
578
579 ; check short
580 cmp ecx,BYTE 16
581 ja .L3
582
583.L1: ; short loop
584 mov ah,[esi+0] ; blue
585 mov al,[esi+1] ; green
586 mov bl,[esi+2] ; red
587 shr ah,3
588 and al,11111100b
589 shl eax,3
590 shr bl,3
591 add al,bl
592 mov [edi+0],al
593 mov [edi+1],ah
594 add esi,BYTE 4
595 add edi,BYTE 2
596 dec ecx
597 jnz .L1
598.L2:
599 retn
600
601.L3: ; head
602 mov ebx,edi
603 and ebx,BYTE 11b
604 jz .L4
605 mov ah,[esi+0] ; blue
606 mov al,[esi+1] ; green
607 mov bl,[esi+2] ; red
608 shr ah,3
609 and al,11111100b
610 shl eax,3
611 shr bl,3
612 add al,bl
613 mov [edi+0],al
614 mov [edi+1],ah
615 add esi,BYTE 4
616 add edi,BYTE 2
617 dec ecx
618
619.L4: ; save count
620 push ecx
621
622 ; unroll twice
623 shr ecx,1
624
625 ; point arrays to end
626 lea esi,[esi+ecx*8]
627 lea edi,[edi+ecx*4]
628
629 ; negative count
630 neg ecx
631 jmp SHORT .L6
632
633.L5:
634 mov [edi+ecx*4-4],eax
635.L6:
636 mov edx,[esi+ecx*8+4]
637
638 mov bh,[esi+ecx*8+4]
639 mov ah,[esi+ecx*8]
640
641 shr bh,3
642 mov al,[esi+ecx*8+1]
643
644 shr ah,3
645 mov bl,[esi+ecx*8+5]
646
647 shl eax,3
648 mov dl,[esi+ecx*8+2]
649
650 shl ebx,19
651 and eax,0000FFE0h
652
653 shr edx,3
654 and ebx,0FFE00000h
655
656 and edx,001F001Fh
657 add eax,ebx
658
659 add eax,edx
660 inc ecx
661
662 jnz .L5
663
664 mov [edi+ecx*4-4],eax
665
666 ; tail
667 pop ecx
668 and ecx,BYTE 1
669 jz .L7
670 mov ah,[esi+0] ; blue
671 mov al,[esi+1] ; green
672 mov bl,[esi+2] ; red
673 shr ah,3
674 and al,11111100b
675 shl eax,3
676 shr bl,3
677 add al,bl
678 mov [edi+0],al
679 mov [edi+1],ah
680 add esi,BYTE 4
681 add edi,BYTE 2
682
683.L7:
684 retn
685
686
687
688
689;; 32 BIT RGB TO 16 BIT RGB 555
690
691_ConvertX86p32_16RGB555:
692
693 ; check short
694 cmp ecx,BYTE 16
695 ja .L3
696
697.L1: ; short loop
698 mov bl,[esi+0] ; blue
699 mov al,[esi+1] ; green
700 mov ah,[esi+2] ; red
701 shr ah,3
702 and al,11111000b
703 shl eax,2
704 shr bl,3
705 add al,bl
706 mov [edi+0],al
707 mov [edi+1],ah
708 add esi,BYTE 4
709 add edi,BYTE 2
710 dec ecx
711 jnz .L1
712.L2:
713 retn
714
715.L3: ; head
716 mov ebx,edi
717 and ebx,BYTE 11b
718 jz .L4
719 mov bl,[esi+0] ; blue
720 mov al,[esi+1] ; green
721 mov ah,[esi+2] ; red
722 shr ah,3
723 and al,11111000b
724 shl eax,2
725 shr bl,3
726 add al,bl
727 mov [edi+0],al
728 mov [edi+1],ah
729 add esi,BYTE 4
730 add edi,BYTE 2
731 dec ecx
732
733.L4: ; save count
734 push ecx
735
736 ; unroll twice
737 shr ecx,1
738
739 ; point arrays to end
740 lea esi,[esi+ecx*8]
741 lea edi,[edi+ecx*4]
742
743 ; negative counter
744 neg ecx
745 jmp SHORT .L6
746
747.L5:
748 mov [edi+ecx*4-4],eax
749.L6:
750 mov eax,[esi+ecx*8]
751
752 shr ah,3
753 mov ebx,[esi+ecx*8+4]
754
755 shr eax,3
756 mov edx,[esi+ecx*8+4]
757
758 shr bh,3
759 mov dl,[esi+ecx*8+2]
760
761 shl ebx,13
762 and eax,000007FFh
763
764 shl edx,7
765 and ebx,07FF0000h
766
767 and edx,07C007C00h
768 add eax,ebx
769
770 add eax,edx
771 inc ecx
772
773 jnz .L5
774
775 mov [edi+ecx*4-4],eax
776
777 ; tail
778 pop ecx
779 and ecx,BYTE 1
780 jz .L7
781 mov bl,[esi+0] ; blue
782 mov al,[esi+1] ; green
783 mov ah,[esi+2] ; red
784 shr ah,3
785 and al,11111000b
786 shl eax,2
787 shr bl,3
788 add al,bl
789 mov [edi+0],al
790 mov [edi+1],ah
791 add esi,BYTE 4
792 add edi,BYTE 2
793
794.L7:
795 retn
796
797
798
799
800;; 32 BIT RGB TO 16 BIT BGR 555
801
802_ConvertX86p32_16BGR555:
803
804 ; check short
805 cmp ecx,BYTE 16
806 ja .L3
807
808
809.L1: ; short loop
810 mov ah,[esi+0] ; blue
811 mov al,[esi+1] ; green
812 mov bl,[esi+2] ; red
813 shr ah,3
814 and al,11111000b
815 shl eax,2
816 shr bl,3
817 add al,bl
818 mov [edi+0],al
819 mov [edi+1],ah
820 add esi,BYTE 4
821 add edi,BYTE 2
822 dec ecx
823 jnz .L1
824.L2:
825 retn
826
827.L3: ; head
828 mov ebx,edi
829 and ebx,BYTE 11b
830 jz .L4
831 mov ah,[esi+0] ; blue
832 mov al,[esi+1] ; green
833 mov bl,[esi+2] ; red
834 shr ah,3
835 and al,11111000b
836 shl eax,2
837 shr bl,3
838 add al,bl
839 mov [edi+0],al
840 mov [edi+1],ah
841 add esi,BYTE 4
842 add edi,BYTE 2
843 dec ecx
844
845.L4: ; save count
846 push ecx
847
848 ; unroll twice
849 shr ecx,1
850
851 ; point arrays to end
852 lea esi,[esi+ecx*8]
853 lea edi,[edi+ecx*4]
854
855 ; negative counter
856 neg ecx
857 jmp SHORT .L6
858
859.L5:
860 mov [edi+ecx*4-4],eax
861.L6:
862 mov edx,[esi+ecx*8+4]
863
864 mov bh,[esi+ecx*8+4]
865 mov ah,[esi+ecx*8]
866
867 shr bh,3
868 mov al,[esi+ecx*8+1]
869
870 shr ah,3
871 mov bl,[esi+ecx*8+5]
872
873 shl eax,2
874 mov dl,[esi+ecx*8+2]
875
876 shl ebx,18
877 and eax,00007FE0h
878
879 shr edx,3
880 and ebx,07FE00000h
881
882 and edx,001F001Fh
883 add eax,ebx
884
885 add eax,edx
886 inc ecx
887
888 jnz .L5
889
890 mov [edi+ecx*4-4],eax
891
892 ; tail
893 pop ecx
894 and ecx,BYTE 1
895 jz .L7
896 mov ah,[esi+0] ; blue
897 mov al,[esi+1] ; green
898 mov bl,[esi+2] ; red
899 shr ah,3
900 and al,11111000b
901 shl eax,2
902 shr bl,3
903 add al,bl
904 mov [edi+0],al
905 mov [edi+1],ah
906 add esi,BYTE 4
907 add edi,BYTE 2
908
909.L7:
910 retn
911
912
913
914
915
916;; FROM 32 BIT RGB to 8 BIT RGB (rrrgggbbb)
917;; This routine writes FOUR pixels at once (dword) and then, if they exist
918;; the trailing three pixels
919_ConvertX86p32_8RGB332:
920
921
922.L_ALIGNED:
923 push ecx
924
925 shr ecx,2 ; We will draw 4 pixels at once
926 jnz .L1
927
928 jmp .L2 ; short jump out of range :(
929
930.L1:
931 mov eax,[esi] ; first pair of pixels
932 mov edx,[esi+4]
933
934 shr dl,6
935 mov ebx,eax
936
937 shr al,6
938 and ah,0e0h
939
940 shr ebx,16
941 and dh,0e0h
942
943 shr ah,3
944 and bl,0e0h
945
946 shr dh,3
947
948 or al,bl
949
950 mov ebx,edx
951 or al,ah
952
953 shr ebx,16
954 or dl,dh
955
956 and bl,0e0h
957
958 or dl,bl
959
960 mov ah,dl
961
962
963
964 mov ebx,[esi+8] ; second pair of pixels
965
966 mov edx,ebx
967 and bh,0e0h
968
969 shr bl,6
970 and edx,0e00000h
971
972 shr edx,16
973
974 shr bh,3
975
976 ror eax,16
977 or bl,dl
978
979 mov edx,[esi+12]
980 or bl,bh
981
982 mov al,bl
983
984 mov ebx,edx
985 and dh,0e0h
986
987 shr dl,6
988 and ebx,0e00000h
989
990 shr dh,3
991 mov ah,dl
992
993 shr ebx,16
994 or ah,dh
995
996 or ah,bl
997
998 rol eax,16
999 add esi,BYTE 16
1000
1001 mov [edi],eax
1002 add edi,BYTE 4
1003
1004 dec ecx
1005 jz .L2 ; L1 out of range for short jump :(
1006
1007 jmp .L1
1008.L2:
1009
1010 pop ecx
1011 and ecx,BYTE 3 ; mask out number of pixels to draw
1012
1013 jz .L4 ; Nothing to do anymore
1014
1015.L3:
1016 mov eax,[esi] ; single pixel conversion for trailing pixels
1017
1018 mov ebx,eax
1019
1020 shr al,6
1021 and ah,0e0h
1022
1023 shr ebx,16
1024
1025 shr ah,3
1026 and bl,0e0h
1027
1028 or al,ah
1029 or al,bl
1030
1031 mov [edi],al
1032
1033 inc edi
1034 add esi,BYTE 4
1035
1036 dec ecx
1037 jnz .L3
1038
1039.L4:
1040 retn
1041
1042%ifidn __OUTPUT_FORMAT__,elf32
1043section .note.GNU-stack noalloc noexec nowrite progbits
1044%endif
diff --git a/apps/plugins/sdl/src/joystick/beos/SDL_bejoystick.cc b/apps/plugins/sdl/src/joystick/beos/SDL_bejoystick.cc
deleted file mode 100644
index af8a34164b..0000000000
--- a/apps/plugins/sdl/src/joystick/beos/SDL_bejoystick.cc
+++ /dev/null
@@ -1,237 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_JOYSTICK_BEOS
25
26/* This is the system specific header for the SDL joystick API */
27
28#include <be/support/String.h>
29#include <be/device/Joystick.h>
30
31extern "C" {
32
33#include "SDL_joystick.h"
34#include "../SDL_sysjoystick.h"
35#include "../SDL_joystick_c.h"
36
37
38/* The maximum number of joysticks we'll detect */
39#define MAX_JOYSTICKS 16
40
41/* A list of available joysticks */
42static char *SDL_joyport[MAX_JOYSTICKS];
43static char *SDL_joyname[MAX_JOYSTICKS];
44
45/* The private structure used to keep track of a joystick */
46struct joystick_hwdata {
47 BJoystick *stick;
48 uint8 *new_hats;
49 int16 *new_axes;
50};
51
52/* Function to scan the system for joysticks.
53 * This function should set SDL_numjoysticks to the number of available
54 * joysticks. Joystick 0 should be the system default joystick.
55 * It should return 0, or -1 on an unrecoverable fatal error.
56 */
57int SDL_SYS_JoystickInit(void)
58{
59 BJoystick joystick;
60 int numjoysticks;
61 int i;
62 int32 nports;
63 char name[B_OS_NAME_LENGTH];
64
65 /* Search for attached joysticks */
66 nports = joystick.CountDevices();
67 numjoysticks = 0;
68 SDL_memset(SDL_joyport, 0, (sizeof SDL_joyport));
69 SDL_memset(SDL_joyname, 0, (sizeof SDL_joyname));
70 for ( i=0; (SDL_numjoysticks < MAX_JOYSTICKS) && (i < nports); ++i ) {
71 if ( joystick.GetDeviceName(i, name) == B_OK ) {
72 if ( joystick.Open(name) != B_ERROR ) {
73 BString stick_name;
74 joystick.GetControllerName(&stick_name);
75 SDL_joyport[numjoysticks] = strdup(name);
76 SDL_joyname[numjoysticks] =
77 strdup(stick_name.String());
78 numjoysticks++;
79 joystick.Close();
80 }
81 }
82 }
83 return(numjoysticks);
84}
85
86/* Function to get the device-dependent name of a joystick */
87const char *SDL_SYS_JoystickName(int index)
88{
89 return SDL_joyname[index];
90}
91
92/* Function to open a joystick for use.
93 The joystick to open is specified by the index field of the joystick.
94 This should fill the nbuttons and naxes fields of the joystick structure.
95 It returns 0, or -1 if there is an error.
96 */
97int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
98{
99 BJoystick *stick;
100
101 /* Create the joystick data structure */
102 joystick->hwdata = (struct joystick_hwdata *)
103 SDL_malloc(sizeof(*joystick->hwdata));
104 if ( joystick->hwdata == NULL ) {
105 SDL_OutOfMemory();
106 return(-1);
107 }
108 SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata));
109 stick = new BJoystick;
110 joystick->hwdata->stick = stick;
111
112 /* Open the requested joystick for use */
113 if ( stick->Open(SDL_joyport[joystick->index]) == B_ERROR ) {
114 SDL_SetError("Unable to open joystick");
115 SDL_SYS_JoystickClose(joystick);
116 return(-1);
117 }
118
119 /* Set the joystick to calibrated mode */
120 stick->EnableCalibration();
121
122 /* Get the number of buttons, hats, and axes on the joystick */
123 joystick->nbuttons = stick->CountButtons();
124 joystick->naxes = stick->CountAxes();
125 joystick->nhats = stick->CountHats();
126
127 joystick->hwdata->new_axes = (int16 *)
128 SDL_malloc(joystick->naxes*sizeof(int16));
129 joystick->hwdata->new_hats = (uint8 *)
130 SDL_malloc(joystick->nhats*sizeof(uint8));
131 if ( ! joystick->hwdata->new_hats || ! joystick->hwdata->new_axes ) {
132 SDL_OutOfMemory();
133 SDL_SYS_JoystickClose(joystick);
134 return(-1);
135 }
136
137 /* We're done! */
138 return(0);
139}
140
141/* Function to update the state of a joystick - called as a device poll.
142 * This function shouldn't update the joystick structure directly,
143 * but instead should call SDL_PrivateJoystick*() to deliver events
144 * and update joystick device state.
145 */
146void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
147{
148 static const Uint8 hat_map[9] = {
149 SDL_HAT_CENTERED,
150 SDL_HAT_UP,
151 SDL_HAT_RIGHTUP,
152 SDL_HAT_RIGHT,
153 SDL_HAT_RIGHTDOWN,
154 SDL_HAT_DOWN,
155 SDL_HAT_LEFTDOWN,
156 SDL_HAT_LEFT,
157 SDL_HAT_LEFTUP
158 };
159 const int JITTER = (32768/10); /* 10% jitter threshold (ok?) */
160
161 BJoystick *stick;
162 int i, change;
163 int16 *axes;
164 uint8 *hats;
165 uint32 buttons;
166
167 /* Set up data pointers */
168 stick = joystick->hwdata->stick;
169 axes = joystick->hwdata->new_axes;
170 hats = joystick->hwdata->new_hats;
171
172 /* Get the new joystick state */
173 stick->Update();
174 stick->GetAxisValues(axes);
175 stick->GetHatValues(hats);
176 buttons = stick->ButtonValues();
177
178 /* Generate axis motion events */
179 for ( i=0; i<joystick->naxes; ++i ) {
180 change = ((int32)axes[i] - joystick->axes[i]);
181 if ( (change > JITTER) || (change < -JITTER) ) {
182 SDL_PrivateJoystickAxis(joystick, i, axes[i]);
183 }
184 }
185
186 /* Generate hat change events */
187 for ( i=0; i<joystick->nhats; ++i ) {
188 if ( hats[i] != joystick->hats[i] ) {
189 SDL_PrivateJoystickHat(joystick, i, hat_map[hats[i]]);
190 }
191 }
192
193 /* Generate button events */
194 for ( i=0; i<joystick->nbuttons; ++i ) {
195 if ( (buttons&0x01) != joystick->buttons[i] ) {
196 SDL_PrivateJoystickButton(joystick, i, (buttons&0x01));
197 }
198 buttons >>= 1;
199 }
200}
201
202/* Function to close a joystick after use */
203void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
204{
205 if ( joystick->hwdata ) {
206 joystick->hwdata->stick->Close();
207 delete joystick->hwdata->stick;
208 if ( joystick->hwdata->new_hats ) {
209 SDL_free(joystick->hwdata->new_hats);
210 }
211 if ( joystick->hwdata->new_axes ) {
212 SDL_free(joystick->hwdata->new_axes);
213 }
214 SDL_free(joystick->hwdata);
215 joystick->hwdata = NULL;
216 }
217}
218
219/* Function to perform any system-specific joystick related cleanup */
220void SDL_SYS_JoystickQuit(void)
221{
222 int i;
223
224 for ( i=0; SDL_joyport[i]; ++i ) {
225 SDL_free(SDL_joyport[i]);
226 }
227 SDL_joyport[0] = NULL;
228
229 for ( i=0; SDL_joyname[i]; ++i ) {
230 SDL_free(SDL_joyname[i]);
231 }
232 SDL_joyname[0] = NULL;
233}
234
235}; // extern "C"
236
237#endif /* SDL_JOYSTICK_BEOS */
diff --git a/apps/plugins/sdl/src/joystick/bsd/SDL_sysjoystick.c b/apps/plugins/sdl/src/joystick/bsd/SDL_sysjoystick.c
deleted file mode 100644
index 500fc62951..0000000000
--- a/apps/plugins/sdl/src/joystick/bsd/SDL_sysjoystick.c
+++ /dev/null
@@ -1,608 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_JOYSTICK_USBHID
25
26/*
27 * Joystick driver for the uhid(4) interface found in OpenBSD,
28 * NetBSD and FreeBSD.
29 *
30 * Maintainer: <vedge at csoft.org>
31 */
32
33#include <sys/param.h>
34
35#include <unistd.h>
36#include <fcntl.h>
37#include <errno.h>
38
39#ifndef __FreeBSD_kernel_version
40#define __FreeBSD_kernel_version __FreeBSD_version
41#endif
42
43#if defined(HAVE_USB_H)
44#include <usb.h>
45#endif
46#ifdef __DragonFly__
47#include <bus/usb/usb.h>
48#include <bus/usb/usbhid.h>
49#else
50#include <dev/usb/usb.h>
51#include <dev/usb/usbhid.h>
52#endif
53
54#if defined(HAVE_USBHID_H)
55#include <usbhid.h>
56#elif defined(HAVE_LIBUSB_H)
57#include <libusb.h>
58#elif defined(HAVE_LIBUSBHID_H)
59#include <libusbhid.h>
60#endif
61
62#if defined(__FREEBSD__) || defined(__FreeBSD_kernel__)
63#ifndef __DragonFly__
64#include <osreldate.h>
65#endif
66#if __FreeBSD_kernel_version > 800063
67#include <dev/usb/usb_ioctl.h>
68#endif
69#include <sys/joystick.h>
70#endif
71
72#if SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H
73#include <machine/joystick.h>
74#endif
75
76#include "SDL_joystick.h"
77#include "../SDL_sysjoystick.h"
78#include "../SDL_joystick_c.h"
79
80#define MAX_UHID_JOYS 4
81#define MAX_JOY_JOYS 2
82#define MAX_JOYS (MAX_UHID_JOYS + MAX_JOY_JOYS)
83
84struct report {
85#if defined(__FREEBSD__) && (__FreeBSD_kernel_version > 800063)
86 struct usb_gen_descriptor *buf; /* Buffer */
87#else
88 struct usb_ctl_report *buf; /* Buffer */
89#endif
90 size_t size; /* Buffer size */
91 int rid; /* Report ID */
92 enum {
93 SREPORT_UNINIT,
94 SREPORT_CLEAN,
95 SREPORT_DIRTY
96 } status;
97};
98
99static struct {
100 int uhid_report;
101 hid_kind_t kind;
102 const char *name;
103} const repinfo[] = {
104 { UHID_INPUT_REPORT, hid_input, "input" },
105 { UHID_OUTPUT_REPORT, hid_output, "output" },
106 { UHID_FEATURE_REPORT, hid_feature, "feature" }
107};
108
109enum {
110 REPORT_INPUT = 0,
111 REPORT_OUTPUT = 1,
112 REPORT_FEATURE = 2
113};
114
115enum {
116 JOYAXE_X,
117 JOYAXE_Y,
118 JOYAXE_Z,
119 JOYAXE_SLIDER,
120 JOYAXE_WHEEL,
121 JOYAXE_RX,
122 JOYAXE_RY,
123 JOYAXE_RZ,
124 JOYAXE_count
125};
126
127struct joystick_hwdata {
128 int fd;
129 char *path;
130 enum {
131 BSDJOY_UHID, /* uhid(4) */
132 BSDJOY_JOY /* joy(4) */
133 } type;
134 struct report_desc *repdesc;
135 struct report inreport;
136 int axis_map[JOYAXE_count]; /* map present JOYAXE_* to 0,1,..*/
137 int x;
138 int y;
139 int xmin;
140 int ymin;
141 int xmax;
142 int ymax;
143};
144
145static char *joynames[MAX_JOYS];
146static char *joydevnames[MAX_JOYS];
147
148static int report_alloc(struct report *, struct report_desc *, int);
149static void report_free(struct report *);
150
151#if defined(USBHID_UCR_DATA) || defined(__FreeBSD_kernel__)
152#define REP_BUF_DATA(rep) ((rep)->buf->ucr_data)
153#elif (defined(__FREEBSD__) && (__FreeBSD_kernel_version > 800063))
154#define REP_BUF_DATA(rep) ((rep)->buf->ugd_data)
155#else
156#define REP_BUF_DATA(rep) ((rep)->buf->data)
157#endif
158
159int
160SDL_SYS_JoystickInit(void)
161{
162 char s[16];
163 int i, fd;
164
165 SDL_numjoysticks = 0;
166
167 SDL_memset(joynames, 0, sizeof(joynames));
168 SDL_memset(joydevnames, 0, sizeof(joydevnames));
169
170 for (i = 0; i < MAX_UHID_JOYS; i++) {
171 SDL_Joystick nj;
172
173 SDL_snprintf(s, SDL_arraysize(s), "/dev/uhid%d", i);
174
175 nj.index = SDL_numjoysticks;
176 joynames[nj.index] = strdup(s);
177
178 if (SDL_SYS_JoystickOpen(&nj) == 0) {
179 SDL_SYS_JoystickClose(&nj);
180 SDL_numjoysticks++;
181 } else {
182 SDL_free(joynames[nj.index]);
183 joynames[nj.index] = NULL;
184 }
185 }
186 for (i = 0; i < MAX_JOY_JOYS; i++) {
187 SDL_snprintf(s, SDL_arraysize(s), "/dev/joy%d", i);
188 fd = open(s, O_RDONLY);
189 if (fd != -1) {
190 joynames[SDL_numjoysticks++] = strdup(s);
191 close(fd);
192 }
193 }
194
195 /* Read the default USB HID usage table. */
196 hid_init(NULL);
197
198 return (SDL_numjoysticks);
199}
200
201const char *
202SDL_SYS_JoystickName(int index)
203{
204 if (joydevnames[index] != NULL) {
205 return (joydevnames[index]);
206 }
207 return (joynames[index]);
208}
209
210static int
211usage_to_joyaxe(unsigned usage)
212{
213 int joyaxe;
214 switch (usage) {
215 case HUG_X:
216 joyaxe = JOYAXE_X; break;
217 case HUG_Y:
218 joyaxe = JOYAXE_Y; break;
219 case HUG_Z:
220 joyaxe = JOYAXE_Z; break;
221 case HUG_SLIDER:
222 joyaxe = JOYAXE_SLIDER; break;
223 case HUG_WHEEL:
224 joyaxe = JOYAXE_WHEEL; break;
225 case HUG_RX:
226 joyaxe = JOYAXE_RX; break;
227 case HUG_RY:
228 joyaxe = JOYAXE_RY; break;
229 case HUG_RZ:
230 joyaxe = JOYAXE_RZ; break;
231 default:
232 joyaxe = -1;
233 }
234 return joyaxe;
235}
236
237static unsigned
238hatval_to_sdl(Sint32 hatval)
239{
240 static const unsigned hat_dir_map[8] = {
241 SDL_HAT_UP, SDL_HAT_RIGHTUP, SDL_HAT_RIGHT, SDL_HAT_RIGHTDOWN,
242 SDL_HAT_DOWN, SDL_HAT_LEFTDOWN, SDL_HAT_LEFT, SDL_HAT_LEFTUP
243 };
244 unsigned result;
245 if ((hatval & 7) == hatval)
246 result = hat_dir_map[hatval];
247 else
248 result = SDL_HAT_CENTERED;
249 return result;
250}
251
252
253int
254SDL_SYS_JoystickOpen(SDL_Joystick *joy)
255{
256 char *path = joynames[joy->index];
257 struct joystick_hwdata *hw;
258 struct hid_item hitem;
259 struct hid_data *hdata;
260 struct report *rep;
261 int fd;
262 int i;
263
264 fd = open(path, O_RDONLY);
265 if (fd == -1) {
266 SDL_SetError("%s: %s", path, strerror(errno));
267 return (-1);
268 }
269
270 hw = (struct joystick_hwdata *)SDL_malloc(sizeof(struct joystick_hwdata));
271 if (hw == NULL) {
272 SDL_OutOfMemory();
273 close(fd);
274 return (-1);
275 }
276 joy->hwdata = hw;
277 hw->fd = fd;
278 hw->path = strdup(path);
279 hw->x = 0;
280 hw->y = 0;
281 hw->xmin = 0xffff;
282 hw->ymin = 0xffff;
283 hw->xmax = 0;
284 hw->ymax = 0;
285 if (! SDL_strncmp(path, "/dev/joy", 8)) {
286 hw->type = BSDJOY_JOY;
287 joy->naxes = 2;
288 joy->nbuttons = 2;
289 joy->nhats = 0;
290 joy->nballs = 0;
291 joydevnames[joy->index] = strdup("Gameport joystick");
292 goto usbend;
293 } else {
294 hw->type = BSDJOY_UHID;
295 }
296
297 {
298 int ax;
299 for (ax = 0; ax < JOYAXE_count; ax++)
300 hw->axis_map[ax] = -1;
301 }
302 hw->repdesc = hid_get_report_desc(fd);
303 if (hw->repdesc == NULL) {
304 SDL_SetError("%s: USB_GET_REPORT_DESC: %s", hw->path,
305 strerror(errno));
306 goto usberr;
307 }
308 rep = &hw->inreport;
309#if defined(__FREEBSD__) && (__FreeBSD_kernel_version > 800063) || defined(__FreeBSD_kernel__)
310 rep->rid = hid_get_report_id(fd);
311 if (rep->rid < 0) {
312#else
313 if (ioctl(fd, USB_GET_REPORT_ID, &rep->rid) < 0) {
314#endif
315 rep->rid = -1; /* XXX */
316 }
317 if (report_alloc(rep, hw->repdesc, REPORT_INPUT) < 0) {
318 goto usberr;
319 }
320 if (rep->size <= 0) {
321 SDL_SetError("%s: Input report descriptor has invalid length",
322 hw->path);
323 goto usberr;
324 }
325
326#if defined(USBHID_NEW) || (defined(__FREEBSD__) && __FreeBSD_kernel_version >= 500111) || defined(__FreeBSD_kernel__)
327 hdata = hid_start_parse(hw->repdesc, 1 << hid_input, rep->rid);
328#else
329 hdata = hid_start_parse(hw->repdesc, 1 << hid_input);
330#endif
331 if (hdata == NULL) {
332 SDL_SetError("%s: Cannot start HID parser", hw->path);
333 goto usberr;
334 }
335 joy->naxes = 0;
336 joy->nbuttons = 0;
337 joy->nhats = 0;
338 joy->nballs = 0;
339 for (i=0; i<JOYAXE_count; i++)
340 hw->axis_map[i] = -1;
341
342 while (hid_get_item(hdata, &hitem) > 0) {
343 char *sp;
344 const char *s;
345
346 switch (hitem.kind) {
347 case hid_collection:
348 switch (HID_PAGE(hitem.usage)) {
349 case HUP_GENERIC_DESKTOP:
350 switch (HID_USAGE(hitem.usage)) {
351 case HUG_JOYSTICK:
352 case HUG_GAME_PAD:
353 s = hid_usage_in_page(hitem.usage);
354 sp = SDL_malloc(SDL_strlen(s) + 5);
355 SDL_snprintf(sp, SDL_strlen(s) + 5, "%s (%d)", s,
356 joy->index);
357 joydevnames[joy->index] = sp;
358 }
359 }
360 break;
361 case hid_input:
362 switch (HID_PAGE(hitem.usage)) {
363 case HUP_GENERIC_DESKTOP: {
364 unsigned usage = HID_USAGE(hitem.usage);
365 int joyaxe = usage_to_joyaxe(usage);
366 if (joyaxe >= 0) {
367 hw->axis_map[joyaxe] = 1;
368 } else if (usage == HUG_HAT_SWITCH) {
369 joy->nhats++;
370 }
371 break;
372 }
373 case HUP_BUTTON:
374 joy->nbuttons++;
375 break;
376 default:
377 break;
378 }
379 break;
380 default:
381 break;
382 }
383 }
384 hid_end_parse(hdata);
385 for (i=0; i<JOYAXE_count; i++)
386 if (hw->axis_map[i] > 0)
387 hw->axis_map[i] = joy->naxes++;
388
389usbend:
390 /* The poll blocks the event thread. */
391 fcntl(fd, F_SETFL, O_NONBLOCK);
392
393 return (0);
394usberr:
395 close(hw->fd);
396 SDL_free(hw->path);
397 SDL_free(hw);
398 return (-1);
399}
400
401void
402SDL_SYS_JoystickUpdate(SDL_Joystick *joy)
403{
404 struct hid_item hitem;
405 struct hid_data *hdata;
406 struct report *rep;
407 int nbutton, naxe = -1;
408 Sint32 v;
409
410#if defined(__FREEBSD__) || SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H || defined(__FreeBSD_kernel__)
411 struct joystick gameport;
412
413 if (joy->hwdata->type == BSDJOY_JOY) {
414 if (read(joy->hwdata->fd, &gameport, sizeof gameport) != sizeof gameport)
415 return;
416 if (abs(joy->hwdata->x - gameport.x) > 8) {
417 joy->hwdata->x = gameport.x;
418 if (joy->hwdata->x < joy->hwdata->xmin) {
419 joy->hwdata->xmin = joy->hwdata->x;
420 }
421 if (joy->hwdata->x > joy->hwdata->xmax) {
422 joy->hwdata->xmax = joy->hwdata->x;
423 }
424 if (joy->hwdata->xmin == joy->hwdata->xmax) {
425 joy->hwdata->xmin--;
426 joy->hwdata->xmax++;
427 }
428 v = (Sint32)joy->hwdata->x;
429 v -= (joy->hwdata->xmax + joy->hwdata->xmin + 1)/2;
430 v *= 32768/((joy->hwdata->xmax - joy->hwdata->xmin + 1)/2);
431 SDL_PrivateJoystickAxis(joy, 0, v);
432 }
433 if (abs(joy->hwdata->y - gameport.y) > 8) {
434 joy->hwdata->y = gameport.y;
435 if (joy->hwdata->y < joy->hwdata->ymin) {
436 joy->hwdata->ymin = joy->hwdata->y;
437 }
438 if (joy->hwdata->y > joy->hwdata->ymax) {
439 joy->hwdata->ymax = joy->hwdata->y;
440 }
441 if (joy->hwdata->ymin == joy->hwdata->ymax) {
442 joy->hwdata->ymin--;
443 joy->hwdata->ymax++;
444 }
445 v = (Sint32)joy->hwdata->y;
446 v -= (joy->hwdata->ymax + joy->hwdata->ymin + 1)/2;
447 v *= 32768/((joy->hwdata->ymax - joy->hwdata->ymin + 1)/2);
448 SDL_PrivateJoystickAxis(joy, 1, v);
449 }
450 if (gameport.b1 != joy->buttons[0]) {
451 SDL_PrivateJoystickButton(joy, 0, gameport.b1);
452 }
453 if (gameport.b2 != joy->buttons[1]) {
454 SDL_PrivateJoystickButton(joy, 1, gameport.b2);
455 }
456 return;
457 }
458#endif /* defined(__FREEBSD__) || SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H */
459
460 rep = &joy->hwdata->inreport;
461
462 if (read(joy->hwdata->fd, REP_BUF_DATA(rep), rep->size) != rep->size) {
463 return;
464 }
465#if defined(USBHID_NEW) || (defined(__FREEBSD__) && __FreeBSD_kernel_version >= 500111) || defined(__FreeBSD_kernel__)
466 hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input, rep->rid);
467#else
468 hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input);
469#endif
470 if (hdata == NULL) {
471 fprintf(stderr, "%s: Cannot start HID parser\n",
472 joy->hwdata->path);
473 return;
474 }
475
476 for (nbutton = 0; hid_get_item(hdata, &hitem) > 0;) {
477 switch (hitem.kind) {
478 case hid_input:
479 switch (HID_PAGE(hitem.usage)) {
480 case HUP_GENERIC_DESKTOP: {
481 unsigned usage = HID_USAGE(hitem.usage);
482 int joyaxe = usage_to_joyaxe(usage);
483 if (joyaxe >= 0) {
484 naxe = joy->hwdata->axis_map[joyaxe];
485 /* scaleaxe */
486 v = (Sint32)hid_get_data(REP_BUF_DATA(rep),
487 &hitem);
488 v -= (hitem.logical_maximum + hitem.logical_minimum + 1)/2;
489 v *= 32768/((hitem.logical_maximum - hitem.logical_minimum + 1)/2);
490 if (v != joy->axes[naxe]) {
491 SDL_PrivateJoystickAxis(joy, naxe, v);
492 }
493 } else if (usage == HUG_HAT_SWITCH) {
494 v = (Sint32)hid_get_data(REP_BUF_DATA(rep),
495 &hitem);
496 SDL_PrivateJoystickHat(joy, 0,
497 hatval_to_sdl(v)-hitem.logical_minimum);
498 }
499 break;
500 }
501 case HUP_BUTTON:
502 v = (Sint32)hid_get_data(REP_BUF_DATA(rep),
503 &hitem);
504 if (joy->buttons[nbutton] != v) {
505 SDL_PrivateJoystickButton(joy,
506 nbutton, v);
507 }
508 nbutton++;
509 break;
510 default:
511 continue;
512 }
513 break;
514 default:
515 break;
516 }
517 }
518 hid_end_parse(hdata);
519
520 return;
521}
522
523/* Function to close a joystick after use */
524void
525SDL_SYS_JoystickClose(SDL_Joystick *joy)
526{
527 if (SDL_strncmp(joy->hwdata->path, "/dev/joy", 8)) {
528 report_free(&joy->hwdata->inreport);
529 hid_dispose_report_desc(joy->hwdata->repdesc);
530 }
531 close(joy->hwdata->fd);
532 SDL_free(joy->hwdata->path);
533 SDL_free(joy->hwdata);
534
535 return;
536}
537
538void
539SDL_SYS_JoystickQuit(void)
540{
541 int i;
542
543 for (i = 0; i < MAX_JOYS; i++) {
544 if (joynames[i] != NULL)
545 SDL_free(joynames[i]);
546 if (joydevnames[i] != NULL)
547 SDL_free(joydevnames[i]);
548 }
549
550 return;
551}
552
553static int
554report_alloc(struct report *r, struct report_desc *rd, int repind)
555{
556 int len;
557
558#ifdef __DragonFly__
559 len = hid_report_size(rd, r->rid, repinfo[repind].kind);
560#elif __FREEBSD__
561# if (__FreeBSD_kernel_version >= 460000) || defined(__FreeBSD_kernel__)
562# if (__FreeBSD_kernel_version <= 500111)
563 len = hid_report_size(rd, r->rid, repinfo[repind].kind);
564# else
565 len = hid_report_size(rd, repinfo[repind].kind, r->rid);
566# endif
567# else
568 len = hid_report_size(rd, repinfo[repind].kind, &r->rid);
569# endif
570#else
571# ifdef USBHID_NEW
572 len = hid_report_size(rd, repinfo[repind].kind, r->rid);
573# else
574 len = hid_report_size(rd, repinfo[repind].kind, &r->rid);
575# endif
576#endif
577
578 if (len < 0) {
579 SDL_SetError("Negative HID report size");
580 return (-1);
581 }
582 r->size = len;
583
584 if (r->size > 0) {
585 r->buf = SDL_malloc(sizeof(*r->buf) - sizeof(REP_BUF_DATA(r)) +
586 r->size);
587 if (r->buf == NULL) {
588 SDL_OutOfMemory();
589 return (-1);
590 }
591 } else {
592 r->buf = NULL;
593 }
594
595 r->status = SREPORT_CLEAN;
596 return (0);
597}
598
599static void
600report_free(struct report *r)
601{
602 if (r->buf != NULL) {
603 SDL_free(r->buf);
604 }
605 r->status = SREPORT_UNINIT;
606}
607
608#endif /* SDL_JOYSTICK_USBHID */
diff --git a/apps/plugins/sdl/src/joystick/darwin/SDL_sysjoystick.c b/apps/plugins/sdl/src/joystick/darwin/SDL_sysjoystick.c
deleted file mode 100644
index a9ccb35fad..0000000000
--- a/apps/plugins/sdl/src/joystick/darwin/SDL_sysjoystick.c
+++ /dev/null
@@ -1,842 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_JOYSTICK_IOKIT
25
26/* SDL joystick driver for Darwin / Mac OS X, based on the IOKit HID API */
27/* Written 2001 by Max Horn */
28
29#include <unistd.h>
30#include <ctype.h>
31#include <sysexits.h>
32#include <mach/mach.h>
33#include <mach/mach_error.h>
34#include <IOKit/IOKitLib.h>
35#include <IOKit/IOCFPlugIn.h>
36#ifdef MACOS_10_0_4
37#include <IOKit/hidsystem/IOHIDUsageTables.h>
38#else
39/* The header was moved here in Mac OS X 10.1 */
40#include <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
41#endif
42#include <IOKit/hid/IOHIDLib.h>
43#include <IOKit/hid/IOHIDKeys.h>
44#include <CoreFoundation/CoreFoundation.h>
45#include <Carbon/Carbon.h> /* for NewPtrClear, DisposePtr */
46
47#include "SDL_joystick.h"
48#include "../SDL_sysjoystick.h"
49#include "../SDL_joystick_c.h"
50
51struct recElement
52{
53 IOHIDElementCookie cookie; /* unique value which identifies element, will NOT change */
54 long min; /* reported min value possible */
55 long max; /* reported max value possible */
56#if 0
57 /* TODO: maybe should handle the following stuff somehow? */
58
59 long scaledMin; /* reported scaled min value possible */
60 long scaledMax; /* reported scaled max value possible */
61 long size; /* size in bits of data return from element */
62 Boolean relative; /* are reports relative to last report (deltas) */
63 Boolean wrapping; /* does element wrap around (one value higher than max is min) */
64 Boolean nonLinear; /* are the values reported non-linear relative to element movement */
65 Boolean preferredState; /* does element have a preferred state (such as a button) */
66 Boolean nullState; /* does element have null state */
67#endif /* 0 */
68
69 /* runtime variables used for auto-calibration */
70 long minReport; /* min returned value */
71 long maxReport; /* max returned value */
72
73 struct recElement * pNext; /* next element in list */
74};
75typedef struct recElement recElement;
76
77struct joystick_hwdata
78{
79 IOHIDDeviceInterface ** interface; /* interface to device, NULL = no interface */
80
81 char product[256]; /* name of product */
82 long usage; /* usage page from IOUSBHID Parser.h which defines general usage */
83 long usagePage; /* usage within above page from IOUSBHID Parser.h which defines specific usage */
84
85 long axes; /* number of axis (calculated, not reported by device) */
86 long buttons; /* number of buttons (calculated, not reported by device) */
87 long hats; /* number of hat switches (calculated, not reported by device) */
88 long elements; /* number of total elements (shouldbe total of above) (calculated, not reported by device) */
89
90 recElement* firstAxis;
91 recElement* firstButton;
92 recElement* firstHat;
93
94 int removed;
95 int uncentered;
96
97 struct joystick_hwdata* pNext; /* next device */
98};
99typedef struct joystick_hwdata recDevice;
100
101
102/* Linked list of all available devices */
103static recDevice *gpDeviceList = NULL;
104
105
106static void HIDReportErrorNum (char * strError, long numError)
107{
108 SDL_SetError(strError);
109}
110
111static void HIDGetCollectionElements (CFMutableDictionaryRef deviceProperties, recDevice *pDevice);
112
113/* returns current value for element, polling element
114 * will return 0 on error conditions which should be accounted for by application
115 */
116
117static SInt32 HIDGetElementValue (recDevice *pDevice, recElement *pElement)
118{
119 IOReturn result = kIOReturnSuccess;
120 IOHIDEventStruct hidEvent;
121 hidEvent.value = 0;
122
123 if (NULL != pDevice && NULL != pElement && NULL != pDevice->interface)
124 {
125 result = (*(pDevice->interface))->getElementValue(pDevice->interface, pElement->cookie, &hidEvent);
126 if (kIOReturnSuccess == result)
127 {
128 /* record min and max for auto calibration */
129 if (hidEvent.value < pElement->minReport)
130 pElement->minReport = hidEvent.value;
131 if (hidEvent.value > pElement->maxReport)
132 pElement->maxReport = hidEvent.value;
133 }
134 }
135
136 /* auto user scale */
137 return hidEvent.value;
138}
139
140static SInt32 HIDScaledCalibratedValue (recDevice *pDevice, recElement *pElement, long min, long max)
141{
142 float deviceScale = max - min;
143 float readScale = pElement->maxReport - pElement->minReport;
144 SInt32 value = HIDGetElementValue(pDevice, pElement);
145 if (readScale == 0)
146 return value; /* no scaling at all */
147 else
148 return ((value - pElement->minReport) * deviceScale / readScale) + min;
149}
150
151
152static void HIDRemovalCallback(void * target,
153 IOReturn result,
154 void * refcon,
155 void * sender)
156{
157 recDevice *device = (recDevice *) refcon;
158 device->removed = 1;
159 device->uncentered = 1;
160}
161
162
163
164/* Create and open an interface to device, required prior to extracting values or building queues.
165 * Note: appliction now owns the device and must close and release it prior to exiting
166 */
167
168static IOReturn HIDCreateOpenDeviceInterface (io_object_t hidDevice, recDevice *pDevice)
169{
170 IOReturn result = kIOReturnSuccess;
171 HRESULT plugInResult = S_OK;
172 SInt32 score = 0;
173 IOCFPlugInInterface ** ppPlugInInterface = NULL;
174
175 if (NULL == pDevice->interface)
176 {
177 result = IOCreatePlugInInterfaceForService (hidDevice, kIOHIDDeviceUserClientTypeID,
178 kIOCFPlugInInterfaceID, &ppPlugInInterface, &score);
179 if (kIOReturnSuccess == result)
180 {
181 /* Call a method of the intermediate plug-in to create the device interface */
182 plugInResult = (*ppPlugInInterface)->QueryInterface (ppPlugInInterface,
183 CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID), (void *) &(pDevice->interface));
184 if (S_OK != plugInResult)
185 HIDReportErrorNum ("CouldnÕt query HID class device interface from plugInInterface", plugInResult);
186 (*ppPlugInInterface)->Release (ppPlugInInterface);
187 }
188 else
189 HIDReportErrorNum ("Failed to create **plugInInterface via IOCreatePlugInInterfaceForService.", result);
190 }
191 if (NULL != pDevice->interface)
192 {
193 result = (*(pDevice->interface))->open (pDevice->interface, 0);
194 if (kIOReturnSuccess != result)
195 HIDReportErrorNum ("Failed to open pDevice->interface via open.", result);
196 else
197 (*(pDevice->interface))->setRemovalCallback (pDevice->interface, HIDRemovalCallback, pDevice, pDevice);
198
199 }
200 return result;
201}
202
203/* Closes and releases interface to device, should be done prior to exting application
204 * Note: will have no affect if device or interface do not exist
205 * application will "own" the device if interface is not closed
206 * (device may have to be plug and re-plugged in different location to get it working again without a restart)
207 */
208
209static IOReturn HIDCloseReleaseInterface (recDevice *pDevice)
210{
211 IOReturn result = kIOReturnSuccess;
212
213 if ((NULL != pDevice) && (NULL != pDevice->interface))
214 {
215 /* close the interface */
216 result = (*(pDevice->interface))->close (pDevice->interface);
217 if (kIOReturnNotOpen == result)
218 {
219 /* do nothing as device was not opened, thus can't be closed */
220 }
221 else if (kIOReturnSuccess != result)
222 HIDReportErrorNum ("Failed to close IOHIDDeviceInterface.", result);
223 /* release the interface */
224 result = (*(pDevice->interface))->Release (pDevice->interface);
225 if (kIOReturnSuccess != result)
226 HIDReportErrorNum ("Failed to release IOHIDDeviceInterface.", result);
227 pDevice->interface = NULL;
228 }
229 return result;
230}
231
232/* extracts actual specific element information from each element CF dictionary entry */
233
234static void HIDGetElementInfo (CFTypeRef refElement, recElement *pElement)
235{
236 long number;
237 CFTypeRef refType;
238
239 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementCookieKey));
240 if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
241 pElement->cookie = (IOHIDElementCookie) number;
242 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMinKey));
243 if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
244 pElement->minReport = pElement->min = number;
245 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMaxKey));
246 if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
247 pElement->maxReport = pElement->max = number;
248/*
249 TODO: maybe should handle the following stuff somehow?
250
251 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMinKey));
252 if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
253 pElement->scaledMin = number;
254 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMaxKey));
255 if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
256 pElement->scaledMax = number;
257 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementSizeKey));
258 if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
259 pElement->size = number;
260 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsRelativeKey));
261 if (refType)
262 pElement->relative = CFBooleanGetValue (refType);
263 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsWrappingKey));
264 if (refType)
265 pElement->wrapping = CFBooleanGetValue (refType);
266 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsNonLinearKey));
267 if (refType)
268 pElement->nonLinear = CFBooleanGetValue (refType);
269 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasPreferedStateKey));
270 if (refType)
271 pElement->preferredState = CFBooleanGetValue (refType);
272 refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasNullStateKey));
273 if (refType)
274 pElement->nullState = CFBooleanGetValue (refType);
275*/
276}
277
278/* examines CF dictionary vlaue in device element hierarchy to determine if it is element of interest or a collection of more elements
279 * if element of interest allocate storage, add to list and retrieve element specific info
280 * if collection then pass on to deconstruction collection into additional individual elements
281 */
282
283static void HIDAddElement (CFTypeRef refElement, recDevice* pDevice)
284{
285 recElement* element = NULL;
286 recElement** headElement = NULL;
287 long elementType, usagePage, usage;
288 CFTypeRef refElementType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementTypeKey));
289 CFTypeRef refUsagePage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsagePageKey));
290 CFTypeRef refUsage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsageKey));
291
292
293 if ((refElementType) && (CFNumberGetValue (refElementType, kCFNumberLongType, &elementType)))
294 {
295 /* look at types of interest */
296 if ((elementType == kIOHIDElementTypeInput_Misc) || (elementType == kIOHIDElementTypeInput_Button) ||
297 (elementType == kIOHIDElementTypeInput_Axis))
298 {
299 if (refUsagePage && CFNumberGetValue (refUsagePage, kCFNumberLongType, &usagePage) &&
300 refUsage && CFNumberGetValue (refUsage, kCFNumberLongType, &usage))
301 {
302 switch (usagePage) /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */
303 {
304 case kHIDPage_GenericDesktop:
305 {
306 switch (usage) /* look at usage to determine function */
307 {
308 case kHIDUsage_GD_X:
309 case kHIDUsage_GD_Y:
310 case kHIDUsage_GD_Z:
311 case kHIDUsage_GD_Rx:
312 case kHIDUsage_GD_Ry:
313 case kHIDUsage_GD_Rz:
314 case kHIDUsage_GD_Slider:
315 case kHIDUsage_GD_Dial:
316 case kHIDUsage_GD_Wheel:
317 element = (recElement *) NewPtrClear (sizeof (recElement));
318 if (element)
319 {
320 pDevice->axes++;
321 headElement = &(pDevice->firstAxis);
322 }
323 break;
324 case kHIDUsage_GD_Hatswitch:
325 element = (recElement *) NewPtrClear (sizeof (recElement));
326 if (element)
327 {
328 pDevice->hats++;
329 headElement = &(pDevice->firstHat);
330 }
331 break;
332 }
333 }
334 break;
335 case kHIDPage_Button:
336 element = (recElement *) NewPtrClear (sizeof (recElement));
337 if (element)
338 {
339 pDevice->buttons++;
340 headElement = &(pDevice->firstButton);
341 }
342 break;
343 default:
344 break;
345 }
346 }
347 }
348 else if (kIOHIDElementTypeCollection == elementType)
349 HIDGetCollectionElements ((CFMutableDictionaryRef) refElement, pDevice);
350 }
351
352 if (element && headElement) /* add to list */
353 {
354 pDevice->elements++;
355 if (NULL == *headElement)
356 *headElement = element;
357 else
358 {
359 recElement *elementPrevious, *elementCurrent;
360 elementCurrent = *headElement;
361 while (elementCurrent)
362 {
363 elementPrevious = elementCurrent;
364 elementCurrent = elementPrevious->pNext;
365 }
366 elementPrevious->pNext = element;
367 }
368 element->pNext = NULL;
369 HIDGetElementInfo (refElement, element);
370 }
371}
372
373/* collects information from each array member in device element list (each array memeber = element) */
374
375static void HIDGetElementsCFArrayHandler (const void * value, void * parameter)
376{
377 if (CFGetTypeID (value) == CFDictionaryGetTypeID ())
378 HIDAddElement ((CFTypeRef) value, (recDevice *) parameter);
379}
380
381/* handles retrieval of element information from arrays of elements in device IO registry information */
382
383static void HIDGetElements (CFTypeRef refElementCurrent, recDevice *pDevice)
384{
385 CFTypeID type = CFGetTypeID (refElementCurrent);
386 if (type == CFArrayGetTypeID()) /* if element is an array */
387 {
388 CFRange range = {0, CFArrayGetCount (refElementCurrent)};
389 /* CountElementsCFArrayHandler called for each array member */
390 CFArrayApplyFunction (refElementCurrent, range, HIDGetElementsCFArrayHandler, pDevice);
391 }
392}
393
394/* handles extracting element information from element collection CF types
395 * used from top level element decoding and hierarchy deconstruction to flatten device element list
396 */
397
398static void HIDGetCollectionElements (CFMutableDictionaryRef deviceProperties, recDevice *pDevice)
399{
400 CFTypeRef refElementTop = CFDictionaryGetValue (deviceProperties, CFSTR(kIOHIDElementKey));
401 if (refElementTop)
402 HIDGetElements (refElementTop, pDevice);
403}
404
405/* use top level element usage page and usage to discern device usage page and usage setting appropriate vlaues in device record */
406
407static void HIDTopLevelElementHandler (const void * value, void * parameter)
408{
409 CFTypeRef refCF = 0;
410 if (CFGetTypeID (value) != CFDictionaryGetTypeID ())
411 return;
412 refCF = CFDictionaryGetValue (value, CFSTR(kIOHIDElementUsagePageKey));
413 if (!CFNumberGetValue (refCF, kCFNumberLongType, &((recDevice *) parameter)->usagePage))
414 SDL_SetError ("CFNumberGetValue error retrieving pDevice->usagePage.");
415 refCF = CFDictionaryGetValue (value, CFSTR(kIOHIDElementUsageKey));
416 if (!CFNumberGetValue (refCF, kCFNumberLongType, &((recDevice *) parameter)->usage))
417 SDL_SetError ("CFNumberGetValue error retrieving pDevice->usage.");
418}
419
420/* extracts device info from CF dictionary records in IO registry */
421
422static void HIDGetDeviceInfo (io_object_t hidDevice, CFMutableDictionaryRef hidProperties, recDevice *pDevice)
423{
424 CFMutableDictionaryRef usbProperties = 0;
425 io_registry_entry_t parent1, parent2;
426
427 /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
428 * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
429 */
430 if ((KERN_SUCCESS == IORegistryEntryGetParentEntry (hidDevice, kIOServicePlane, &parent1)) &&
431 (KERN_SUCCESS == IORegistryEntryGetParentEntry (parent1, kIOServicePlane, &parent2)) &&
432 (KERN_SUCCESS == IORegistryEntryCreateCFProperties (parent2, &usbProperties, kCFAllocatorDefault, kNilOptions)))
433 {
434 if (usbProperties)
435 {
436 CFTypeRef refCF = 0;
437 /* get device info
438 * try hid dictionary first, if fail then go to usb dictionary
439 */
440
441
442 /* get product name */
443 refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDProductKey));
444 if (!refCF)
445 refCF = CFDictionaryGetValue (usbProperties, CFSTR("USB Product Name"));
446 if (refCF)
447 {
448 if (!CFStringGetCString (refCF, pDevice->product, 256, CFStringGetSystemEncoding ()))
449 SDL_SetError ("CFStringGetCString error retrieving pDevice->product.");
450 }
451
452 /* get usage page and usage */
453 refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey));
454 if (refCF)
455 {
456 if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usagePage))
457 SDL_SetError ("CFNumberGetValue error retrieving pDevice->usagePage.");
458 refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsageKey));
459 if (refCF)
460 if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usage))
461 SDL_SetError ("CFNumberGetValue error retrieving pDevice->usage.");
462 }
463
464 if (NULL == refCF) /* get top level element HID usage page or usage */
465 {
466 /* use top level element instead */
467 CFTypeRef refCFTopElement = 0;
468 refCFTopElement = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDElementKey));
469 {
470 /* refCFTopElement points to an array of element dictionaries */
471 CFRange range = {0, CFArrayGetCount (refCFTopElement)};
472 CFArrayApplyFunction (refCFTopElement, range, HIDTopLevelElementHandler, pDevice);
473 }
474 }
475
476 CFRelease (usbProperties);
477 }
478 else
479 SDL_SetError ("IORegistryEntryCreateCFProperties failed to create usbProperties.");
480
481 if (kIOReturnSuccess != IOObjectRelease (parent2))
482 SDL_SetError ("IOObjectRelease error with parent2.");
483 if (kIOReturnSuccess != IOObjectRelease (parent1))
484 SDL_SetError ("IOObjectRelease error with parent1.");
485 }
486}
487
488
489static recDevice *HIDBuildDevice (io_object_t hidDevice)
490{
491 recDevice *pDevice = (recDevice *) NewPtrClear (sizeof (recDevice));
492 if (pDevice)
493 {
494 /* get dictionary for HID properties */
495 CFMutableDictionaryRef hidProperties = 0;
496 kern_return_t result = IORegistryEntryCreateCFProperties (hidDevice, &hidProperties, kCFAllocatorDefault, kNilOptions);
497 if ((result == KERN_SUCCESS) && hidProperties)
498 {
499 /* create device interface */
500 result = HIDCreateOpenDeviceInterface (hidDevice, pDevice);
501 if (kIOReturnSuccess == result)
502 {
503 HIDGetDeviceInfo (hidDevice, hidProperties, pDevice); /* hidDevice used to find parents in registry tree */
504 HIDGetCollectionElements (hidProperties, pDevice);
505 }
506 else
507 {
508 DisposePtr((Ptr)pDevice);
509 pDevice = NULL;
510 }
511 CFRelease (hidProperties);
512 }
513 else
514 {
515 DisposePtr((Ptr)pDevice);
516 pDevice = NULL;
517 }
518 }
519 return pDevice;
520}
521
522/* disposes of the element list associated with a device and the memory associated with the list
523 */
524
525static void HIDDisposeElementList (recElement **elementList)
526{
527 recElement *pElement = *elementList;
528 while (pElement)
529 {
530 recElement *pElementNext = pElement->pNext;
531 DisposePtr ((Ptr) pElement);
532 pElement = pElementNext;
533 }
534 *elementList = NULL;
535}
536
537/* disposes of a single device, closing and releaseing interface, freeing memory fro device and elements, setting device pointer to NULL
538 * all your device no longer belong to us... (i.e., you do not 'own' the device anymore)
539 */
540
541static recDevice *HIDDisposeDevice (recDevice **ppDevice)
542{
543 kern_return_t result = KERN_SUCCESS;
544 recDevice *pDeviceNext = NULL;
545 if (*ppDevice)
546 {
547 /* save next device prior to disposing of this device */
548 pDeviceNext = (*ppDevice)->pNext;
549
550 /* free element lists */
551 HIDDisposeElementList (&(*ppDevice)->firstAxis);
552 HIDDisposeElementList (&(*ppDevice)->firstButton);
553 HIDDisposeElementList (&(*ppDevice)->firstHat);
554
555 result = HIDCloseReleaseInterface (*ppDevice); /* function sanity checks interface value (now application does not own device) */
556 if (kIOReturnSuccess != result)
557 HIDReportErrorNum ("HIDCloseReleaseInterface failed when trying to dipose device.", result);
558 DisposePtr ((Ptr)*ppDevice);
559 *ppDevice = NULL;
560 }
561 return pDeviceNext;
562}
563
564
565/* Function to scan the system for joysticks.
566 * Joystick 0 should be the system default joystick.
567 * This function should return the number of available joysticks, or -1
568 * on an unrecoverable fatal error.
569 */
570int SDL_SYS_JoystickInit(void)
571{
572 IOReturn result = kIOReturnSuccess;
573 mach_port_t masterPort = 0;
574 io_iterator_t hidObjectIterator = 0;
575 CFMutableDictionaryRef hidMatchDictionary = NULL;
576 recDevice *device, *lastDevice;
577 io_object_t ioHIDDeviceObject = 0;
578
579 SDL_numjoysticks = 0;
580
581 if (gpDeviceList)
582 {
583 SDL_SetError("Joystick: Device list already inited.");
584 return -1;
585 }
586
587 result = IOMasterPort (bootstrap_port, &masterPort);
588 if (kIOReturnSuccess != result)
589 {
590 SDL_SetError("Joystick: IOMasterPort error with bootstrap_port.");
591 return -1;
592 }
593
594 /* Set up a matching dictionary to search I/O Registry by class name for all HID class devices. */
595 hidMatchDictionary = IOServiceMatching (kIOHIDDeviceKey);
596 if (hidMatchDictionary)
597 {
598 /* Add key for device type (joystick, in this case) to refine the matching dictionary. */
599
600 /* NOTE: we now perform this filtering later
601 UInt32 usagePage = kHIDPage_GenericDesktop;
602 UInt32 usage = kHIDUsage_GD_Joystick;
603 CFNumberRef refUsage = NULL, refUsagePage = NULL;
604
605 refUsage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usage);
606 CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsageKey), refUsage);
607 refUsagePage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usagePage);
608 CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsagePageKey), refUsagePage);
609 */
610 }
611 else
612 {
613 SDL_SetError("Joystick: Failed to get HID CFMutableDictionaryRef via IOServiceMatching.");
614 return -1;
615 }
616
617 /*/ Now search I/O Registry for matching devices. */
618 result = IOServiceGetMatchingServices (masterPort, hidMatchDictionary, &hidObjectIterator);
619 /* Check for errors */
620 if (kIOReturnSuccess != result)
621 {
622 SDL_SetError("Joystick: Couldn't create a HID object iterator.");
623 return -1;
624 }
625 if (!hidObjectIterator) /* there are no joysticks */
626 {
627 gpDeviceList = NULL;
628 SDL_numjoysticks = 0;
629 return 0;
630 }
631 /* IOServiceGetMatchingServices consumes a reference to the dictionary, so we don't need to release the dictionary ref. */
632
633 /* build flat linked list of devices from device iterator */
634
635 gpDeviceList = lastDevice = NULL;
636
637 while ((ioHIDDeviceObject = IOIteratorNext (hidObjectIterator)))
638 {
639 /* build a device record */
640 device = HIDBuildDevice (ioHIDDeviceObject);
641 if (!device)
642 continue;
643
644 /* dump device object, it is no longer needed */
645 result = IOObjectRelease (ioHIDDeviceObject);
646/* if (KERN_SUCCESS != result)
647 HIDReportErrorNum ("IOObjectRelease error with ioHIDDeviceObject.", result);
648*/
649
650 /* Filter device list to non-keyboard/mouse stuff */
651 if ( (device->usagePage != kHIDPage_GenericDesktop) ||
652 ((device->usage != kHIDUsage_GD_Joystick &&
653 device->usage != kHIDUsage_GD_GamePad &&
654 device->usage != kHIDUsage_GD_MultiAxisController)) ) {
655
656 /* release memory for the device */
657 HIDDisposeDevice (&device);
658 DisposePtr((Ptr)device);
659 continue;
660 }
661
662 /* Add device to the end of the list */
663 if (lastDevice)
664 lastDevice->pNext = device;
665 else
666 gpDeviceList = device;
667 lastDevice = device;
668 }
669 result = IOObjectRelease (hidObjectIterator); /* release the iterator */
670
671 /* Count the total number of devices we found */
672 device = gpDeviceList;
673 while (device)
674 {
675 SDL_numjoysticks++;
676 device = device->pNext;
677 }
678
679 return SDL_numjoysticks;
680}
681
682/* Function to get the device-dependent name of a joystick */
683const char *SDL_SYS_JoystickName(int index)
684{
685 recDevice *device = gpDeviceList;
686
687 for (; index > 0; index--)
688 device = device->pNext;
689
690 return device->product;
691}
692
693/* Function to open a joystick for use.
694 * The joystick to open is specified by the index field of the joystick.
695 * This should fill the nbuttons and naxes fields of the joystick structure.
696 * It returns 0, or -1 if there is an error.
697 */
698int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
699{
700 recDevice *device = gpDeviceList;
701 int index;
702
703 for (index = joystick->index; index > 0; index--)
704 device = device->pNext;
705
706 joystick->hwdata = device;
707 joystick->name = device->product;
708
709 joystick->naxes = device->axes;
710 joystick->nhats = device->hats;
711 joystick->nballs = 0;
712 joystick->nbuttons = device->buttons;
713
714 return 0;
715}
716
717/* Function to update the state of a joystick - called as a device poll.
718 * This function shouldn't update the joystick structure directly,
719 * but instead should call SDL_PrivateJoystick*() to deliver events
720 * and update joystick device state.
721 */
722void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
723{
724 recDevice *device = joystick->hwdata;
725 recElement *element;
726 SInt32 value, range;
727 int i;
728
729 if (device->removed) /* device was unplugged; ignore it. */
730 {
731 if (device->uncentered)
732 {
733 device->uncentered = 0;
734
735 /* Tell the app that everything is centered/unpressed... */
736 for (i = 0; i < device->axes; i++)
737 SDL_PrivateJoystickAxis(joystick, i, 0);
738
739 for (i = 0; i < device->buttons; i++)
740 SDL_PrivateJoystickButton(joystick, i, 0);
741
742 for (i = 0; i < device->hats; i++)
743 SDL_PrivateJoystickHat(joystick, i, SDL_HAT_CENTERED);
744 }
745
746 return;
747 }
748
749 element = device->firstAxis;
750 i = 0;
751 while (element)
752 {
753 value = HIDScaledCalibratedValue(device, element, -32768, 32767);
754 if ( value != joystick->axes[i] )
755 SDL_PrivateJoystickAxis(joystick, i, value);
756 element = element->pNext;
757 ++i;
758 }
759
760 element = device->firstButton;
761 i = 0;
762 while (element)
763 {
764 value = HIDGetElementValue(device, element);
765 if (value > 1) /* handle pressure-sensitive buttons */
766 value = 1;
767 if ( value != joystick->buttons[i] )
768 SDL_PrivateJoystickButton(joystick, i, value);
769 element = element->pNext;
770 ++i;
771 }
772
773 element = device->firstHat;
774 i = 0;
775 while (element)
776 {
777 Uint8 pos = 0;
778
779 range = (element->max - element->min + 1);
780 value = HIDGetElementValue(device, element) - element->min;
781 if (range == 4) /* 4 position hatswitch - scale up value */
782 value *= 2;
783 else if (range != 8) /* Neither a 4 nor 8 positions - fall back to default position (centered) */
784 value = -1;
785 switch(value)
786 {
787 case 0:
788 pos = SDL_HAT_UP;
789 break;
790 case 1:
791 pos = SDL_HAT_RIGHTUP;
792 break;
793 case 2:
794 pos = SDL_HAT_RIGHT;
795 break;
796 case 3:
797 pos = SDL_HAT_RIGHTDOWN;
798 break;
799 case 4:
800 pos = SDL_HAT_DOWN;
801 break;
802 case 5:
803 pos = SDL_HAT_LEFTDOWN;
804 break;
805 case 6:
806 pos = SDL_HAT_LEFT;
807 break;
808 case 7:
809 pos = SDL_HAT_LEFTUP;
810 break;
811 default:
812 /* Every other value is mapped to center. We do that because some
813 * joysticks use 8 and some 15 for this value, and apparently
814 * there are even more variants out there - so we try to be generous.
815 */
816 pos = SDL_HAT_CENTERED;
817 break;
818 }
819 if ( pos != joystick->hats[i] )
820 SDL_PrivateJoystickHat(joystick, i, pos);
821 element = element->pNext;
822 ++i;
823 }
824
825 return;
826}
827
828/* Function to close a joystick after use */
829void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
830{
831 /* Should we do anything here? */
832 return;
833}
834
835/* Function to perform any system-specific joystick related cleanup */
836void SDL_SYS_JoystickQuit(void)
837{
838 while (NULL != gpDeviceList)
839 gpDeviceList = HIDDisposeDevice (&gpDeviceList);
840}
841
842#endif /* SDL_JOYSTICK_IOKIT */
diff --git a/apps/plugins/sdl/src/joystick/dc/SDL_sysjoystick.c b/apps/plugins/sdl/src/joystick/dc/SDL_sysjoystick.c
deleted file mode 100644
index dc089e7bf0..0000000000
--- a/apps/plugins/sdl/src/joystick/dc/SDL_sysjoystick.c
+++ /dev/null
@@ -1,193 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_JOYSTICK_DC
25
26#include "SDL_events.h"
27#include "SDL_joystick.h"
28#include "../SDL_sysjoystick.h"
29#include "../SDL_joystick_c.h"
30
31#include <dc/maple.h>
32#include <dc/maple/controller.h>
33
34#define MAX_JOYSTICKS 8 /* only 2 are supported in the multimedia API */
35#define MAX_AXES 6 /* each joystick can have up to 6 axes */
36#define MAX_BUTTONS 8 /* and 8 buttons */
37#define MAX_HATS 2
38
39#define JOYNAMELEN 8
40
41/* array to hold joystick ID values */
42static uint8 SYS_Joystick_addr[MAX_JOYSTICKS];
43
44/* The private structure used to keep track of a joystick */
45struct joystick_hwdata
46{
47 cont_cond_t prev_cond;
48 int prev_buttons;
49};
50
51/* Function to scan the system for joysticks.
52 * This function should set SDL_numjoysticks to the number of available
53 * joysticks. Joystick 0 should be the system default joystick.
54 * It should return 0, or -1 on an unrecoverable fatal error.
55 */
56int SDL_SYS_JoystickInit(void)
57{
58 int numdevs;
59
60 int p,u;
61
62 numdevs = 0;
63 for(p=0;p<MAPLE_PORT_COUNT;p++) {
64 for(u=0;u<MAPLE_UNIT_COUNT;u++) {
65 if (maple_device_func(p,u)&MAPLE_FUNC_CONTROLLER) {
66 SYS_Joystick_addr[numdevs] = maple_addr(p,u);
67 numdevs++;
68 }
69 }
70 }
71
72 return(numdevs);
73}
74
75/* Function to get the device-dependent name of a joystick */
76const char *SDL_SYS_JoystickName(int index)
77{
78 maple_device_t *dev;
79 if (maple_compat_resolve(SYS_Joystick_addr[index],&dev,MAPLE_FUNC_CONTROLLER)!=0) return NULL;
80 return dev->info.product_name;
81}
82
83/* Function to open a joystick for use.
84 The joystick to open is specified by the index field of the joystick.
85 This should fill the nbuttons and naxes fields of the joystick structure.
86 It returns 0, or -1 if there is an error.
87 */
88int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
89{
90 /* allocate memory for system specific hardware data */
91 joystick->hwdata = (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata));
92 if (joystick->hwdata == NULL)
93 {
94 SDL_OutOfMemory();
95 return(-1);
96 }
97 SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata));
98
99 /* fill nbuttons, naxes, and nhats fields */
100 joystick->nbuttons = MAX_BUTTONS;
101 joystick->naxes = MAX_AXES;
102 joystick->nhats = MAX_HATS;
103 return(0);
104}
105
106
107/* Function to update the state of a joystick - called as a device poll.
108 * This function shouldn't update the joystick structure directly,
109 * but instead should call SDL_PrivateJoystick*() to deliver events
110 * and update joystick device state.
111 */
112
113void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
114{
115const int sdl_buttons[] = {
116 CONT_C,
117 CONT_B,
118 CONT_A,
119 CONT_START,
120 CONT_Z,
121 CONT_Y,
122 CONT_X,
123 CONT_D
124};
125
126 uint8 addr;
127 cont_cond_t cond,*prev_cond;
128 int buttons,prev_buttons,i,changed;
129
130 addr = SYS_Joystick_addr[joystick->index];
131 if (cont_get_cond(addr,&cond)<0) return;
132
133 buttons = cond.buttons;
134 prev_buttons = joystick->hwdata->prev_buttons;
135 changed = buttons^prev_buttons;
136
137 if ((changed)&(CONT_DPAD_UP|CONT_DPAD_DOWN|CONT_DPAD_LEFT|CONT_DPAD_RIGHT)) {
138 int hat = SDL_HAT_CENTERED;
139 if (buttons&CONT_DPAD_UP) hat|=SDL_HAT_UP;
140 if (buttons&CONT_DPAD_DOWN) hat|=SDL_HAT_DOWN;
141 if (buttons&CONT_DPAD_LEFT) hat|=SDL_HAT_LEFT;
142 if (buttons&CONT_DPAD_RIGHT) hat|=SDL_HAT_RIGHT;
143 SDL_PrivateJoystickHat(joystick, 0, hat);
144 }
145 if ((changed)&(CONT_DPAD2_UP|CONT_DPAD2_DOWN|CONT_DPAD2_LEFT|CONT_DPAD2_RIGHT)) {
146 int hat = SDL_HAT_CENTERED;
147 if (buttons&CONT_DPAD2_UP) hat|=SDL_HAT_UP;
148 if (buttons&CONT_DPAD2_DOWN) hat|=SDL_HAT_DOWN;
149 if (buttons&CONT_DPAD2_LEFT) hat|=SDL_HAT_LEFT;
150 if (buttons&CONT_DPAD2_RIGHT) hat|=SDL_HAT_RIGHT;
151 SDL_PrivateJoystickHat(joystick, 1, hat);
152 }
153
154 for(i=0;i<sizeof(sdl_buttons)/sizeof(sdl_buttons[0]);i++) {
155 if (changed & sdl_buttons[i]) {
156 SDL_PrivateJoystickButton(joystick, i, (buttons & sdl_buttons[i])?SDL_PRESSED:SDL_RELEASED);
157 }
158 }
159
160 prev_cond = &joystick->hwdata->prev_cond;
161 if (cond.joyx!=prev_cond->joyx)
162 SDL_PrivateJoystickAxis(joystick, 0, cond.joyx-128);
163 if (cond.joyy!=prev_cond->joyy)
164 SDL_PrivateJoystickAxis(joystick, 1, cond.joyy-128);
165 if (cond.rtrig!=prev_cond->rtrig)
166 SDL_PrivateJoystickAxis(joystick, 2, cond.rtrig);
167 if (cond.ltrig!=prev_cond->ltrig)
168 SDL_PrivateJoystickAxis(joystick, 3, cond.ltrig);
169 if (cond.joy2x!=prev_cond->joy2x)
170 SDL_PrivateJoystickAxis(joystick, 4, cond.joy2x-128);
171 if (cond.joy2y!=prev_cond->joy2y)
172 SDL_PrivateJoystickAxis(joystick, 5, cond.joy2y-128);
173
174 joystick->hwdata->prev_buttons = buttons;
175 joystick->hwdata->prev_cond = cond;
176}
177
178/* Function to close a joystick after use */
179void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
180{
181 if (joystick->hwdata != NULL) {
182 /* free system specific hardware data */
183 SDL_free(joystick->hwdata);
184 }
185}
186
187/* Function to perform any system-specific joystick related cleanup */
188void SDL_SYS_JoystickQuit(void)
189{
190 return;
191}
192
193#endif /* SDL_JOYSTICK_DC */
diff --git a/apps/plugins/sdl/src/joystick/linux/SDL_sysjoystick.c b/apps/plugins/sdl/src/joystick/linux/SDL_sysjoystick.c
deleted file mode 100644
index ee43974789..0000000000
--- a/apps/plugins/sdl/src/joystick/linux/SDL_sysjoystick.c
+++ /dev/null
@@ -1,1218 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_JOYSTICK_LINUX
25
26/* This is the system specific header for the SDL joystick API */
27
28#include <sys/stat.h>
29#include <unistd.h>
30#include <fcntl.h>
31#include <sys/ioctl.h>
32#include <limits.h> /* For the definition of PATH_MAX */
33#include <linux/joystick.h>
34#if SDL_INPUT_LINUXEV
35#include <linux/input.h>
36#endif
37
38#include "SDL_joystick.h"
39#include "../SDL_sysjoystick.h"
40#include "../SDL_joystick_c.h"
41
42/* Special joystick configurations */
43static struct {
44 const char *name;
45 int naxes;
46 int nhats;
47 int nballs;
48} special_joysticks[] = {
49 { "MadCatz Panther XL", 3, 2, 1 }, /* We don't handle rudder (axis 8) */
50 { "SideWinder Precision Pro", 4, 1, 0 },
51 { "SideWinder 3D Pro", 4, 1, 0 },
52 { "Microsoft SideWinder 3D Pro", 4, 1, 0 },
53 { "Microsoft SideWinder Precision Pro", 4, 1, 0 },
54 { "Microsoft SideWinder Dual Strike USB version 1.0", 2, 1, 0 },
55 { "WingMan Interceptor", 3, 3, 0 },
56 { "WingMan Extreme Digital 3D", 4, 1, 0 },
57 { "Microsoft SideWinder Precision 2 Joystick", 4, 1, 0 },
58 { "Logitech Inc. WingMan Extreme Digital 3D", 4, 1, 0 },
59 { "Saitek Saitek X45", 6, 1, 0 }
60};
61
62/* It looks like newer kernels have the logical mapping at the driver level */
63#define NO_LOGICAL_JOYSTICKS
64
65#ifndef NO_LOGICAL_JOYSTICKS
66
67/*
68 Some USB HIDs show up as a single joystick even though they actually
69 control 2 or more joysticks.
70*/
71/*
72 This code handles the MP-8800 (Quad) and MP-8866 (Dual), which can
73 be identified by their transparent blue design. It's quite trivial
74 to add other joysticks with similar quirky behavior.
75 -id
76*/
77
78struct joystick_logical_mapping {
79 int njoy;
80 int nthing;
81};
82
83/*
84 {logical joy, logical axis},
85 {logical joy, logical hat},
86 {logical joy, logical ball},
87 {logical joy, logical button}
88*/
89
90static struct joystick_logical_mapping mp88xx_1_logical_axismap[] = {
91 {0,0},{0,1},{0,2},{0,3},{0,4},{0,5}
92};
93static struct joystick_logical_mapping mp88xx_1_logical_buttonmap[] = {
94 {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11}
95};
96
97static struct joystick_logical_mapping mp88xx_2_logical_axismap[] = {
98 {0,0},{0,1},{0,2},{1,0},{1,1},{0,3},
99 {1,2},{1,3},{0,4},{0,5},{1,4},{1,5}
100};
101static struct joystick_logical_mapping mp88xx_2_logical_buttonmap[] = {
102 {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11},
103 {1,0},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},{1,9},{1,10},{1,11}
104};
105
106static struct joystick_logical_mapping mp88xx_3_logical_axismap[] = {
107 {0,0},{0,1},{0,2},{1,0},{1,1},{0,3},
108 {1,2},{1,3},{2,0},{2,1},{2,2},{2,3},
109 {0,4},{0,5},{1,4},{1,5},{2,4},{2,5}
110};
111static struct joystick_logical_mapping mp88xx_3_logical_buttonmap[] = {
112 {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11},
113 {1,0},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},{1,9},{1,10},{1,11},
114 {2,0},{2,1},{2,2},{2,3},{2,4},{2,5},{2,6},{2,7},{2,8},{2,9},{2,10},{2,11}
115};
116
117static struct joystick_logical_mapping mp88xx_4_logical_axismap[] = {
118 {0,0},{0,1},{0,2},{1,0},{1,1},{0,3},
119 {1,2},{1,3},{2,0},{2,1},{2,2},{2,3},
120 {3,0},{3,1},{3,2},{3,3},{0,4},{0,5},
121 {1,4},{1,5},{2,4},{2,5},{3,4},{3,5}
122};
123static struct joystick_logical_mapping mp88xx_4_logical_buttonmap[] = {
124 {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11},
125 {1,0},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},{1,9},{1,10},{1,11},
126 {2,0},{2,1},{2,2},{2,3},{2,4},{2,5},{2,6},{2,7},{2,8},{2,9},{2,10},{2,11},
127 {3,0},{3,1},{3,2},{3,3},{3,4},{3,5},{3,6},{3,7},{3,8},{3,9},{3,10},{3,11}
128};
129
130struct joystick_logical_layout {
131 int naxes;
132 int nhats;
133 int nballs;
134 int nbuttons;
135};
136
137static struct joystick_logical_layout mp88xx_1_logical_layout[] = {
138 {6, 0, 0, 12}
139};
140static struct joystick_logical_layout mp88xx_2_logical_layout[] = {
141 {6, 0, 0, 12},
142 {6, 0, 0, 12}
143};
144static struct joystick_logical_layout mp88xx_3_logical_layout[] = {
145 {6, 0, 0, 12},
146 {6, 0, 0, 12},
147 {6, 0, 0, 12}
148};
149static struct joystick_logical_layout mp88xx_4_logical_layout[] = {
150 {6, 0, 0, 12},
151 {6, 0, 0, 12},
152 {6, 0, 0, 12},
153 {6, 0, 0, 12}
154};
155
156/*
157 This array sets up a means of mapping a single physical joystick to
158 multiple logical joysticks. (djm)
159
160 njoys
161 the number of logical joysticks
162
163 layouts
164 an array of layout structures, one to describe each logical joystick
165
166 axes, hats, balls, buttons
167 arrays that map a physical thingy to a logical thingy
168 */
169struct joystick_logicalmap {
170 const char *name;
171 int nbuttons;
172 int njoys;
173 struct joystick_logical_layout *layout;
174 struct joystick_logical_mapping *axismap;
175 struct joystick_logical_mapping *hatmap;
176 struct joystick_logical_mapping *ballmap;
177 struct joystick_logical_mapping *buttonmap;
178};
179
180static struct joystick_logicalmap joystick_logicalmap[] = {
181 {
182 "WiseGroup.,Ltd MP-8866 Dual USB Joypad",
183 12,
184 1,
185 mp88xx_1_logical_layout,
186 mp88xx_1_logical_axismap,
187 NULL,
188 NULL,
189 mp88xx_1_logical_buttonmap
190 },
191 {
192 "WiseGroup.,Ltd MP-8866 Dual USB Joypad",
193 24,
194 2,
195 mp88xx_2_logical_layout,
196 mp88xx_2_logical_axismap,
197 NULL,
198 NULL,
199 mp88xx_2_logical_buttonmap
200 },
201 {
202 "WiseGroup.,Ltd MP-8800 Quad USB Joypad",
203 12,
204 1,
205 mp88xx_1_logical_layout,
206 mp88xx_1_logical_axismap,
207 NULL,
208 NULL,
209 mp88xx_1_logical_buttonmap
210 },
211 {
212 "WiseGroup.,Ltd MP-8800 Quad USB Joypad",
213 24,
214 2,
215 mp88xx_2_logical_layout,
216 mp88xx_2_logical_axismap,
217 NULL,
218 NULL,
219 mp88xx_2_logical_buttonmap
220 },
221 {
222 "WiseGroup.,Ltd MP-8800 Quad USB Joypad",
223 36,
224 3,
225 mp88xx_3_logical_layout,
226 mp88xx_3_logical_axismap,
227 NULL,
228 NULL,
229 mp88xx_3_logical_buttonmap
230 },
231 {
232 "WiseGroup.,Ltd MP-8800 Quad USB Joypad",
233 48,
234 4,
235 mp88xx_4_logical_layout,
236 mp88xx_4_logical_axismap,
237 NULL,
238 NULL,
239 mp88xx_4_logical_buttonmap
240 }
241};
242
243/* find the head of a linked list, given a point in it
244 */
245#define SDL_joylist_head(i, start)\
246 for(i = start; SDL_joylist[i].fname == NULL;) i = SDL_joylist[i].prev;
247
248#define SDL_logical_joydecl(d) d
249
250
251#else
252
253#define SDL_logical_joydecl(d)
254
255#endif /* USE_LOGICAL_JOYSTICKS */
256
257/* The maximum number of joysticks we'll detect */
258#define MAX_JOYSTICKS 32
259
260/* A list of available joysticks */
261static struct
262{
263 char* fname;
264#ifndef NO_LOGICAL_JOYSTICKS
265 SDL_Joystick* joy;
266 struct joystick_logicalmap* map;
267 int prev;
268 int next;
269 int logicalno;
270#endif /* USE_LOGICAL_JOYSTICKS */
271} SDL_joylist[MAX_JOYSTICKS];
272
273
274/* The private structure used to keep track of a joystick */
275struct joystick_hwdata {
276 int fd;
277 /* The current linux joystick driver maps hats to two axes */
278 struct hwdata_hat {
279 int axis[2];
280 } *hats;
281 /* The current linux joystick driver maps balls to two axes */
282 struct hwdata_ball {
283 int axis[2];
284 } *balls;
285
286 /* Support for the Linux 2.4 unified input interface */
287#if SDL_INPUT_LINUXEV
288 SDL_bool is_hid;
289 Uint8 key_map[KEY_MAX-BTN_MISC];
290 Uint8 abs_map[ABS_MAX];
291 struct axis_correct {
292 int used;
293 int coef[3];
294 } abs_correct[ABS_MAX];
295#endif
296};
297
298
299#ifndef NO_LOGICAL_JOYSTICKS
300
301static int CountLogicalJoysticks(int max)
302{
303 register int i, j, k, ret, prev;
304 const char* name;
305 int nbuttons, fd;
306 unsigned char n;
307
308 ret = 0;
309
310 for(i = 0; i < max; i++) {
311 name = SDL_SYS_JoystickName(i);
312
313 fd = open(SDL_joylist[i].fname, O_RDONLY, 0);
314 if ( fd >= 0 ) {
315 if ( ioctl(fd, JSIOCGBUTTONS, &n) < 0 ) {
316 nbuttons = -1;
317 } else {
318 nbuttons = n;
319 }
320 close(fd);
321 }
322 else {
323 nbuttons=-1;
324 }
325
326 if (name) {
327 for(j = 0; j < SDL_arraysize(joystick_logicalmap); j++) {
328 if (!SDL_strcmp(name, joystick_logicalmap[j].name) && (nbuttons==-1 || nbuttons==joystick_logicalmap[j].nbuttons)) {
329 prev = i;
330 SDL_joylist[prev].map = &(joystick_logicalmap[j]);
331
332 for(k = 1; k < joystick_logicalmap[j].njoys; k++) {
333 SDL_joylist[prev].next = max + ret;
334 SDL_joylist[max+ret].prev = prev;
335
336 prev = max + ret;
337 SDL_joylist[prev].logicalno = k;
338 SDL_joylist[prev].map = &(joystick_logicalmap[j]);
339 ret++;
340 }
341
342 break;
343 }
344 }
345 }
346 }
347
348 return ret;
349}
350
351static void LogicalSuffix(int logicalno, char* namebuf, int len)
352{
353 register int slen;
354 const static char suffixs[] =
355 "01020304050607080910111213141516171819"
356 "20212223242526272829303132";
357 const char* suffix;
358 slen = SDL_strlen(namebuf);
359 suffix = NULL;
360
361 if (logicalno*2<sizeof(suffixs))
362 suffix = suffixs + (logicalno*2);
363
364 if (slen + 4 < len && suffix) {
365 namebuf[slen++] = ' ';
366 namebuf[slen++] = '#';
367 namebuf[slen++] = suffix[0];
368 namebuf[slen++] = suffix[1];
369 namebuf[slen++] = 0;
370 }
371}
372
373#endif /* USE_LOGICAL_JOYSTICKS */
374
375#if SDL_INPUT_LINUXEV
376#define test_bit(nr, addr) \
377 (((1UL << ((nr) % (sizeof(long) * 8))) & ((addr)[(nr) / (sizeof(long) * 8)])) != 0)
378#define NBITS(x) ((((x)-1)/(sizeof(long) * 8))+1)
379
380static int EV_IsJoystick(int fd)
381{
382 unsigned long evbit[NBITS(EV_MAX)] = { 0 };
383 unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
384 unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
385
386 if ( (ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
387 (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
388 (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0) ) {
389 return(0);
390 }
391 if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) &&
392 test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit) &&
393 (test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_A, keybit) || test_bit(BTN_1, keybit)))) return 0;
394 return(1);
395}
396
397#endif /* SDL_INPUT_LINUXEV */
398
399/* Function to scan the system for joysticks */
400int SDL_SYS_JoystickInit(void)
401{
402 /* The base path of the joystick devices */
403 const char *joydev_pattern[] = {
404#if SDL_INPUT_LINUXEV
405 "/dev/input/event%d",
406#endif
407 "/dev/input/js%d",
408 "/dev/js%d"
409 };
410 int numjoysticks;
411 int i, j;
412 int fd;
413 char path[PATH_MAX];
414 dev_t dev_nums[MAX_JOYSTICKS]; /* major/minor device numbers */
415 struct stat sb;
416 int n, duplicate;
417
418 numjoysticks = 0;
419
420 /* First see if the user specified one or more joysticks to use */
421 if ( SDL_getenv("SDL_JOYSTICK_DEVICE") != NULL ) {
422 char *envcopy, *envpath, *delim;
423 envcopy = SDL_strdup(SDL_getenv("SDL_JOYSTICK_DEVICE"));
424 envpath = envcopy;
425 while ( envpath != NULL ) {
426 delim = SDL_strchr(envpath, ':');
427 if ( delim != NULL ) {
428 *delim++ = '\0';
429 }
430 if ( stat(envpath, &sb) == 0 ) {
431 fd = open(envpath, O_RDONLY, 0);
432 if ( fd >= 0 ) {
433 /* Assume the user knows what they're doing. */
434 SDL_joylist[numjoysticks].fname = SDL_strdup(envpath);
435 if ( SDL_joylist[numjoysticks].fname ) {
436 dev_nums[numjoysticks] = sb.st_rdev;
437 ++numjoysticks;
438 }
439 close(fd);
440 }
441 }
442 envpath = delim;
443 }
444 SDL_free(envcopy);
445 }
446
447 for ( i=0; i<SDL_arraysize(joydev_pattern); ++i ) {
448 for ( j=0; j < MAX_JOYSTICKS; ++j ) {
449 SDL_snprintf(path, SDL_arraysize(path), joydev_pattern[i], j);
450
451 /* rcg06302000 replaced access(F_OK) call with stat().
452 * stat() will fail if the file doesn't exist, so it's
453 * equivalent behaviour.
454 */
455 if ( stat(path, &sb) == 0 ) {
456 /* Check to make sure it's not already in list.
457 * This happens when we see a stick via symlink.
458 */
459 duplicate = 0;
460 for (n=0; (n<numjoysticks) && !duplicate; ++n) {
461 if ( sb.st_rdev == dev_nums[n] ) {
462 duplicate = 1;
463 }
464 }
465 if (duplicate) {
466 continue;
467 }
468
469 fd = open(path, O_RDONLY, 0);
470 if ( fd < 0 ) {
471 continue;
472 }
473#if SDL_INPUT_LINUXEV
474#ifdef DEBUG_INPUT_EVENTS
475 printf("Checking %s\n", path);
476#endif
477 if ( (i == 0) && ! EV_IsJoystick(fd) ) {
478 close(fd);
479 continue;
480 }
481#endif
482 close(fd);
483
484 /* We're fine, add this joystick */
485 SDL_joylist[numjoysticks].fname = SDL_strdup(path);
486 if ( SDL_joylist[numjoysticks].fname ) {
487 dev_nums[numjoysticks] = sb.st_rdev;
488 ++numjoysticks;
489 }
490 }
491 }
492
493#if SDL_INPUT_LINUXEV
494 /* This is a special case...
495 If the event devices are valid then the joystick devices
496 will be duplicates but without extra information about their
497 hats or balls. Unfortunately, the event devices can't
498 currently be calibrated, so it's a win-lose situation.
499 So : /dev/input/eventX = /dev/input/jsY = /dev/jsY
500 */
501 if ( (i == 0) && (numjoysticks > 0) )
502 break;
503#endif
504 }
505#ifndef NO_LOGICAL_JOYSTICKS
506 numjoysticks += CountLogicalJoysticks(numjoysticks);
507#endif
508
509 return(numjoysticks);
510}
511
512/* Function to get the device-dependent name of a joystick */
513const char *SDL_SYS_JoystickName(int index)
514{
515 int fd;
516 static char namebuf[128];
517 char *name;
518 SDL_logical_joydecl(int oindex = index);
519
520#ifndef NO_LOGICAL_JOYSTICKS
521 SDL_joylist_head(index, index);
522#endif
523 name = NULL;
524 fd = open(SDL_joylist[index].fname, O_RDONLY, 0);
525 if ( fd >= 0 ) {
526 if (
527#if SDL_INPUT_LINUXEV
528 (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) <= 0) &&
529#endif
530 (ioctl(fd, JSIOCGNAME(sizeof(namebuf)), namebuf) <= 0) ) {
531 name = SDL_joylist[index].fname;
532 } else {
533 name = namebuf;
534 }
535 close(fd);
536
537
538#ifndef NO_LOGICAL_JOYSTICKS
539 if (SDL_joylist[oindex].prev || SDL_joylist[oindex].next || index!=oindex)
540 {
541 LogicalSuffix(SDL_joylist[oindex].logicalno, namebuf, 128);
542 }
543#endif
544 }
545 return name;
546}
547
548static int allocate_hatdata(SDL_Joystick *joystick)
549{
550 int i;
551
552 joystick->hwdata->hats = (struct hwdata_hat *)SDL_malloc(
553 joystick->nhats * sizeof(struct hwdata_hat));
554 if ( joystick->hwdata->hats == NULL ) {
555 return(-1);
556 }
557 for ( i=0; i<joystick->nhats; ++i ) {
558 joystick->hwdata->hats[i].axis[0] = 1;
559 joystick->hwdata->hats[i].axis[1] = 1;
560 }
561 return(0);
562}
563
564static int allocate_balldata(SDL_Joystick *joystick)
565{
566 int i;
567
568 joystick->hwdata->balls = (struct hwdata_ball *)SDL_malloc(
569 joystick->nballs * sizeof(struct hwdata_ball));
570 if ( joystick->hwdata->balls == NULL ) {
571 return(-1);
572 }
573 for ( i=0; i<joystick->nballs; ++i ) {
574 joystick->hwdata->balls[i].axis[0] = 0;
575 joystick->hwdata->balls[i].axis[1] = 0;
576 }
577 return(0);
578}
579
580static SDL_bool JS_ConfigJoystick(SDL_Joystick *joystick, int fd)
581{
582 SDL_bool handled;
583 unsigned char n;
584 int tmp_naxes, tmp_nhats, tmp_nballs;
585 const char *name;
586 char *env, env_name[128];
587 int i;
588
589 handled = SDL_FALSE;
590
591 /* Default joystick device settings */
592 if ( ioctl(fd, JSIOCGAXES, &n) < 0 ) {
593 joystick->naxes = 2;
594 } else {
595 joystick->naxes = n;
596 }
597 if ( ioctl(fd, JSIOCGBUTTONS, &n) < 0 ) {
598 joystick->nbuttons = 2;
599 } else {
600 joystick->nbuttons = n;
601 }
602
603 name = SDL_SYS_JoystickName(joystick->index);
604
605 /* Generic analog joystick support */
606 if ( SDL_strstr(name, "Analog") == name && SDL_strstr(name, "-hat") ) {
607 if ( SDL_sscanf(name,"Analog %d-axis %*d-button %d-hat",
608 &tmp_naxes, &tmp_nhats) == 2 ) {
609
610 joystick->naxes = tmp_naxes;
611 joystick->nhats = tmp_nhats;
612
613 handled = SDL_TRUE;
614 }
615 }
616
617 /* Special joystick support */
618 for ( i=0; i < SDL_arraysize(special_joysticks); ++i ) {
619 if ( SDL_strcmp(name, special_joysticks[i].name) == 0 ) {
620
621 joystick->naxes = special_joysticks[i].naxes;
622 joystick->nhats = special_joysticks[i].nhats;
623 joystick->nballs = special_joysticks[i].nballs;
624
625 handled = SDL_TRUE;
626 break;
627 }
628 }
629
630 /* User environment joystick support */
631 if ( (env = SDL_getenv("SDL_LINUX_JOYSTICK")) ) {
632 *env_name = '\0';
633 if ( *env == '\'' && SDL_sscanf(env, "'%[^']s'", env_name) == 1 )
634 env += SDL_strlen(env_name)+2;
635 else if ( SDL_sscanf(env, "%s", env_name) == 1 )
636 env += SDL_strlen(env_name);
637
638 if ( SDL_strcmp(name, env_name) == 0 ) {
639
640 if ( SDL_sscanf(env, "%d %d %d", &tmp_naxes, &tmp_nhats,
641 &tmp_nballs) == 3 ) {
642
643 joystick->naxes = tmp_naxes;
644 joystick->nhats = tmp_nhats;
645 joystick->nballs = tmp_nballs;
646
647 handled = SDL_TRUE;
648 }
649 }
650 }
651
652 /* Remap hats and balls */
653 if (handled) {
654 if ( joystick->nhats > 0 ) {
655 if ( allocate_hatdata(joystick) < 0 ) {
656 joystick->nhats = 0;
657 }
658 }
659 if ( joystick->nballs > 0 ) {
660 if ( allocate_balldata(joystick) < 0 ) {
661 joystick->nballs = 0;
662 }
663 }
664 }
665
666 return(handled);
667}
668
669#if SDL_INPUT_LINUXEV
670
671static SDL_bool EV_ConfigJoystick(SDL_Joystick *joystick, int fd)
672{
673 int i, t;
674 unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
675 unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
676 unsigned long relbit[NBITS(REL_MAX)] = { 0 };
677
678 /* See if this device uses the new unified event API */
679 if ( (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) &&
680 (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) >= 0) &&
681 (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) >= 0) ) {
682 joystick->hwdata->is_hid = SDL_TRUE;
683
684 /* Get the number of buttons, axes, and other thingamajigs */
685 for ( i=BTN_JOYSTICK; i < KEY_MAX; ++i ) {
686 if ( test_bit(i, keybit) ) {
687#ifdef DEBUG_INPUT_EVENTS
688 printf("Joystick has button: 0x%x\n", i);
689#endif
690 joystick->hwdata->key_map[i-BTN_MISC] =
691 joystick->nbuttons;
692 ++joystick->nbuttons;
693 }
694 }
695 for ( i=BTN_MISC; i < BTN_JOYSTICK; ++i ) {
696 if ( test_bit(i, keybit) ) {
697#ifdef DEBUG_INPUT_EVENTS
698 printf("Joystick has button: 0x%x\n", i);
699#endif
700 joystick->hwdata->key_map[i-BTN_MISC] =
701 joystick->nbuttons;
702 ++joystick->nbuttons;
703 }
704 }
705 for ( i=0; i<ABS_MISC; ++i ) {
706 /* Skip hats */
707 if ( i == ABS_HAT0X ) {
708 i = ABS_HAT3Y;
709 continue;
710 }
711 if ( test_bit(i, absbit) ) {
712 struct input_absinfo absinfo;
713
714 if ( ioctl(fd, EVIOCGABS(i), &absinfo) < 0 )
715 continue;
716#ifdef DEBUG_INPUT_EVENTS
717 printf("Joystick has absolute axis: %x\n", i);
718 printf("Values = { %d, %d, %d, %d, %d }\n",
719 absinfo.value, absinfo.minimum,
720 absinfo.maximum, absinfo.fuzz, absinfo.flat);
721#endif /* DEBUG_INPUT_EVENTS */
722 joystick->hwdata->abs_map[i] = joystick->naxes;
723 if ( absinfo.minimum == absinfo.maximum ) {
724 joystick->hwdata->abs_correct[i].used = 0;
725 } else {
726 joystick->hwdata->abs_correct[i].used = 1;
727 joystick->hwdata->abs_correct[i].coef[0] =
728 (absinfo.maximum + absinfo.minimum) / 2 - absinfo.flat;
729 joystick->hwdata->abs_correct[i].coef[1] =
730 (absinfo.maximum + absinfo.minimum) / 2 + absinfo.flat;
731 t = ((absinfo.maximum - absinfo.minimum) / 2 - 2 * absinfo.flat);
732 if ( t != 0 ) {
733 joystick->hwdata->abs_correct[i].coef[2] = (1 << 29) / t;
734 } else {
735 joystick->hwdata->abs_correct[i].coef[2] = 0;
736 }
737 }
738 ++joystick->naxes;
739 }
740 }
741 for ( i=ABS_HAT0X; i <= ABS_HAT3Y; i += 2 ) {
742 if ( test_bit(i, absbit) || test_bit(i+1, absbit) ) {
743#ifdef DEBUG_INPUT_EVENTS
744 printf("Joystick has hat %d\n",(i-ABS_HAT0X)/2);
745#endif
746 ++joystick->nhats;
747 }
748 }
749 if ( test_bit(REL_X, relbit) || test_bit(REL_Y, relbit) ) {
750 ++joystick->nballs;
751 }
752
753 /* Allocate data to keep track of these thingamajigs */
754 if ( joystick->nhats > 0 ) {
755 if ( allocate_hatdata(joystick) < 0 ) {
756 joystick->nhats = 0;
757 }
758 }
759 if ( joystick->nballs > 0 ) {
760 if ( allocate_balldata(joystick) < 0 ) {
761 joystick->nballs = 0;
762 }
763 }
764 }
765 return(joystick->hwdata->is_hid);
766}
767
768#endif /* SDL_INPUT_LINUXEV */
769
770#ifndef NO_LOGICAL_JOYSTICKS
771static void ConfigLogicalJoystick(SDL_Joystick *joystick)
772{
773 struct joystick_logical_layout* layout;
774
775 layout = SDL_joylist[joystick->index].map->layout +
776 SDL_joylist[joystick->index].logicalno;
777
778 joystick->nbuttons = layout->nbuttons;
779 joystick->nhats = layout->nhats;
780 joystick->naxes = layout->naxes;
781 joystick->nballs = layout->nballs;
782}
783#endif
784
785
786/* Function to open a joystick for use.
787 The joystick to open is specified by the index field of the joystick.
788 This should fill the nbuttons and naxes fields of the joystick structure.
789 It returns 0, or -1 if there is an error.
790 */
791int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
792{
793 int fd;
794 SDL_logical_joydecl(int realindex);
795 SDL_logical_joydecl(SDL_Joystick *realjoy = NULL);
796
797 /* Open the joystick and set the joystick file descriptor */
798#ifndef NO_LOGICAL_JOYSTICKS
799 if (SDL_joylist[joystick->index].fname == NULL) {
800 SDL_joylist_head(realindex, joystick->index);
801 realjoy = SDL_JoystickOpen(realindex);
802
803 if (realjoy == NULL)
804 return(-1);
805
806 fd = realjoy->hwdata->fd;
807
808 } else {
809 fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0);
810 }
811 SDL_joylist[joystick->index].joy = joystick;
812#else
813 fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0);
814#endif
815
816 if ( fd < 0 ) {
817 SDL_SetError("Unable to open %s\n",
818 SDL_joylist[joystick->index]);
819 return(-1);
820 }
821 joystick->hwdata = (struct joystick_hwdata *)
822 SDL_malloc(sizeof(*joystick->hwdata));
823 if ( joystick->hwdata == NULL ) {
824 SDL_OutOfMemory();
825 close(fd);
826 return(-1);
827 }
828 SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata));
829 joystick->hwdata->fd = fd;
830
831 /* Set the joystick to non-blocking read mode */
832 fcntl(fd, F_SETFL, O_NONBLOCK);
833
834 /* Get the number of buttons and axes on the joystick */
835#ifndef NO_LOGICAL_JOYSTICKS
836 if (realjoy)
837 ConfigLogicalJoystick(joystick);
838 else
839#endif
840#if SDL_INPUT_LINUXEV
841 if ( ! EV_ConfigJoystick(joystick, fd) )
842#endif
843 JS_ConfigJoystick(joystick, fd);
844
845 return(0);
846}
847
848#ifndef NO_LOGICAL_JOYSTICKS
849
850static SDL_Joystick* FindLogicalJoystick(
851 SDL_Joystick *joystick, struct joystick_logical_mapping* v)
852{
853 SDL_Joystick *logicaljoy;
854 register int i;
855
856 i = joystick->index;
857 logicaljoy = NULL;
858
859 /* get the fake joystick that will receive the event
860 */
861 for(;;) {
862
863 if (SDL_joylist[i].logicalno == v->njoy) {
864 logicaljoy = SDL_joylist[i].joy;
865 break;
866 }
867
868 if (SDL_joylist[i].next == 0)
869 break;
870
871 i = SDL_joylist[i].next;
872
873 }
874
875 return logicaljoy;
876}
877
878static int LogicalJoystickButton(
879 SDL_Joystick *joystick, Uint8 button, Uint8 state){
880 struct joystick_logical_mapping* buttons;
881 SDL_Joystick *logicaljoy = NULL;
882
883 /* if there's no map then this is just a regular joystick
884 */
885 if (SDL_joylist[joystick->index].map == NULL)
886 return 0;
887
888 /* get the logical joystick that will receive the event
889 */
890 buttons = SDL_joylist[joystick->index].map->buttonmap+button;
891 logicaljoy = FindLogicalJoystick(joystick, buttons);
892
893 if (logicaljoy == NULL)
894 return 1;
895
896 SDL_PrivateJoystickButton(logicaljoy, buttons->nthing, state);
897
898 return 1;
899}
900
901static int LogicalJoystickAxis(
902 SDL_Joystick *joystick, Uint8 axis, Sint16 value)
903{
904 struct joystick_logical_mapping* axes;
905 SDL_Joystick *logicaljoy = NULL;
906
907 /* if there's no map then this is just a regular joystick
908 */
909 if (SDL_joylist[joystick->index].map == NULL)
910 return 0;
911
912 /* get the logical joystick that will receive the event
913 */
914 axes = SDL_joylist[joystick->index].map->axismap+axis;
915 logicaljoy = FindLogicalJoystick(joystick, axes);
916
917 if (logicaljoy == NULL)
918 return 1;
919
920 SDL_PrivateJoystickAxis(logicaljoy, axes->nthing, value);
921
922 return 1;
923}
924#endif /* USE_LOGICAL_JOYSTICKS */
925
926static __inline__
927void HandleHat(SDL_Joystick *stick, Uint8 hat, int axis, int value)
928{
929 struct hwdata_hat *the_hat;
930 const Uint8 position_map[3][3] = {
931 { SDL_HAT_LEFTUP, SDL_HAT_UP, SDL_HAT_RIGHTUP },
932 { SDL_HAT_LEFT, SDL_HAT_CENTERED, SDL_HAT_RIGHT },
933 { SDL_HAT_LEFTDOWN, SDL_HAT_DOWN, SDL_HAT_RIGHTDOWN }
934 };
935 SDL_logical_joydecl(SDL_Joystick *logicaljoy = NULL);
936 SDL_logical_joydecl(struct joystick_logical_mapping* hats = NULL);
937
938 if (stick->nhats <= hat) {
939 return; /* whoops, that shouldn't happen! */
940 }
941
942 the_hat = &stick->hwdata->hats[hat];
943 if ( value < 0 ) {
944 value = 0;
945 } else
946 if ( value == 0 ) {
947 value = 1;
948 } else
949 if ( value > 0 ) {
950 value = 2;
951 }
952 if ( value != the_hat->axis[axis] ) {
953 the_hat->axis[axis] = value;
954
955#ifndef NO_LOGICAL_JOYSTICKS
956 /* if there's no map then this is just a regular joystick
957 */
958 if (SDL_joylist[stick->index].map != NULL) {
959
960 /* get the fake joystick that will receive the event
961 */
962 hats = SDL_joylist[stick->index].map->hatmap+hat;
963 logicaljoy = FindLogicalJoystick(stick, hats);
964 }
965
966 if (logicaljoy) {
967 stick = logicaljoy;
968 hat = hats->nthing;
969 }
970#endif /* USE_LOGICAL_JOYSTICKS */
971
972 SDL_PrivateJoystickHat(stick, hat,
973 position_map[the_hat->axis[1]][the_hat->axis[0]]);
974 }
975}
976
977static __inline__
978void HandleBall(SDL_Joystick *stick, Uint8 ball, int axis, int value)
979{
980 if ((stick->nballs <= ball) || (axis >= 2)) {
981 return; /* whoops, that shouldn't happen! */
982 }
983 stick->hwdata->balls[ball].axis[axis] += value;
984}
985
986/* Function to update the state of a joystick - called as a device poll.
987 * This function shouldn't update the joystick structure directly,
988 * but instead should call SDL_PrivateJoystick*() to deliver events
989 * and update joystick device state.
990 */
991static __inline__ void JS_HandleEvents(SDL_Joystick *joystick)
992{
993 struct js_event events[32];
994 int i, len;
995 Uint8 other_axis;
996
997#ifndef NO_LOGICAL_JOYSTICKS
998 if (SDL_joylist[joystick->index].fname == NULL) {
999 SDL_joylist_head(i, joystick->index);
1000 JS_HandleEvents(SDL_joylist[i].joy);
1001 return;
1002 }
1003#endif
1004
1005 while ((len=read(joystick->hwdata->fd, events, (sizeof events))) > 0) {
1006 len /= sizeof(events[0]);
1007 for ( i=0; i<len; ++i ) {
1008 switch (events[i].type & ~JS_EVENT_INIT) {
1009 case JS_EVENT_AXIS:
1010 if ( events[i].number < joystick->naxes ) {
1011#ifndef NO_LOGICAL_JOYSTICKS
1012 if (!LogicalJoystickAxis(joystick,
1013 events[i].number, events[i].value))
1014#endif
1015 SDL_PrivateJoystickAxis(joystick,
1016 events[i].number, events[i].value);
1017 break;
1018 }
1019 events[i].number -= joystick->naxes;
1020 other_axis = (events[i].number / 2);
1021 if ( other_axis < joystick->nhats ) {
1022 HandleHat(joystick, other_axis,
1023 events[i].number%2,
1024 events[i].value);
1025 break;
1026 }
1027 events[i].number -= joystick->nhats*2;
1028 other_axis = (events[i].number / 2);
1029 if ( other_axis < joystick->nballs ) {
1030 HandleBall(joystick, other_axis,
1031 events[i].number%2,
1032 events[i].value);
1033 break;
1034 }
1035 break;
1036 case JS_EVENT_BUTTON:
1037#ifndef NO_LOGICAL_JOYSTICKS
1038 if (!LogicalJoystickButton(joystick,
1039 events[i].number, events[i].value))
1040#endif
1041 SDL_PrivateJoystickButton(joystick,
1042 events[i].number, events[i].value);
1043 break;
1044 default:
1045 /* ?? */
1046 break;
1047 }
1048 }
1049 }
1050}
1051#if SDL_INPUT_LINUXEV
1052static __inline__ int EV_AxisCorrect(SDL_Joystick *joystick, int which, int value)
1053{
1054 struct axis_correct *correct;
1055
1056 correct = &joystick->hwdata->abs_correct[which];
1057 if ( correct->used ) {
1058 if ( value > correct->coef[0] ) {
1059 if ( value < correct->coef[1] ) {
1060 return 0;
1061 }
1062 value -= correct->coef[1];
1063 } else {
1064 value -= correct->coef[0];
1065 }
1066 value *= correct->coef[2];
1067 value >>= 14;
1068 }
1069
1070 /* Clamp and return */
1071 if ( value < -32768 ) return -32768;
1072 if ( value > 32767 ) return 32767;
1073
1074 return value;
1075}
1076
1077static __inline__ void EV_HandleEvents(SDL_Joystick *joystick)
1078{
1079 struct input_event events[32];
1080 int i, len;
1081 int code;
1082
1083#ifndef NO_LOGICAL_JOYSTICKS
1084 if (SDL_joylist[joystick->index].fname == NULL) {
1085 SDL_joylist_head(i, joystick->index);
1086 return EV_HandleEvents(SDL_joylist[i].joy);
1087 }
1088#endif
1089
1090 while ((len=read(joystick->hwdata->fd, events, (sizeof events))) > 0) {
1091 len /= sizeof(events[0]);
1092 for ( i=0; i<len; ++i ) {
1093 code = events[i].code;
1094 switch (events[i].type) {
1095 case EV_KEY:
1096 if ( code >= BTN_MISC ) {
1097 code -= BTN_MISC;
1098#ifndef NO_LOGICAL_JOYSTICKS
1099 if (!LogicalJoystickButton(joystick,
1100 joystick->hwdata->key_map[code],
1101 events[i].value))
1102#endif
1103 SDL_PrivateJoystickButton(joystick,
1104 joystick->hwdata->key_map[code],
1105 events[i].value);
1106 }
1107 break;
1108 case EV_ABS:
1109 switch (code) {
1110 case ABS_HAT0X:
1111 case ABS_HAT0Y:
1112 case ABS_HAT1X:
1113 case ABS_HAT1Y:
1114 case ABS_HAT2X:
1115 case ABS_HAT2Y:
1116 case ABS_HAT3X:
1117 case ABS_HAT3Y:
1118 code -= ABS_HAT0X;
1119 HandleHat(joystick, code/2, code%2,
1120 events[i].value);
1121 break;
1122 default:
1123 events[i].value = EV_AxisCorrect(joystick, code, events[i].value);
1124#ifndef NO_LOGICAL_JOYSTICKS
1125 if (!LogicalJoystickAxis(joystick,
1126 joystick->hwdata->abs_map[code],
1127 events[i].value))
1128#endif
1129 SDL_PrivateJoystickAxis(joystick,
1130 joystick->hwdata->abs_map[code],
1131 events[i].value);
1132 break;
1133 }
1134 break;
1135 case EV_REL:
1136 switch (code) {
1137 case REL_X:
1138 case REL_Y:
1139 code -= REL_X;
1140 HandleBall(joystick, code/2, code%2,
1141 events[i].value);
1142 break;
1143 default:
1144 break;
1145 }
1146 break;
1147 default:
1148 break;
1149 }
1150 }
1151 }
1152}
1153#endif /* SDL_INPUT_LINUXEV */
1154
1155void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
1156{
1157 int i;
1158
1159#if SDL_INPUT_LINUXEV
1160 if ( joystick->hwdata->is_hid )
1161 EV_HandleEvents(joystick);
1162 else
1163#endif
1164 JS_HandleEvents(joystick);
1165
1166 /* Deliver ball motion updates */
1167 for ( i=0; i<joystick->nballs; ++i ) {
1168 int xrel, yrel;
1169
1170 xrel = joystick->hwdata->balls[i].axis[0];
1171 yrel = joystick->hwdata->balls[i].axis[1];
1172 if ( xrel || yrel ) {
1173 joystick->hwdata->balls[i].axis[0] = 0;
1174 joystick->hwdata->balls[i].axis[1] = 0;
1175 SDL_PrivateJoystickBall(joystick, (Uint8)i, xrel, yrel);
1176 }
1177 }
1178}
1179
1180/* Function to close a joystick after use */
1181void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
1182{
1183#ifndef NO_LOGICAL_JOYSTICKS
1184 register int i;
1185 if (SDL_joylist[joystick->index].fname == NULL) {
1186 SDL_joylist_head(i, joystick->index);
1187 SDL_JoystickClose(SDL_joylist[i].joy);
1188 }
1189#endif
1190
1191 if ( joystick->hwdata ) {
1192#ifndef NO_LOGICAL_JOYSTICKS
1193 if (SDL_joylist[joystick->index].fname != NULL)
1194#endif
1195 close(joystick->hwdata->fd);
1196 if ( joystick->hwdata->hats ) {
1197 SDL_free(joystick->hwdata->hats);
1198 }
1199 if ( joystick->hwdata->balls ) {
1200 SDL_free(joystick->hwdata->balls);
1201 }
1202 SDL_free(joystick->hwdata);
1203 joystick->hwdata = NULL;
1204 }
1205}
1206
1207/* Function to perform any system-specific joystick related cleanup */
1208void SDL_SYS_JoystickQuit(void)
1209{
1210 int i;
1211
1212 for ( i=0; SDL_joylist[i].fname; ++i ) {
1213 SDL_free(SDL_joylist[i].fname);
1214 SDL_joylist[i].fname = NULL;
1215 }
1216}
1217
1218#endif /* SDL_JOYSTICK_LINUX */
diff --git a/apps/plugins/sdl/src/joystick/macos/SDL_sysjoystick.c b/apps/plugins/sdl/src/joystick/macos/SDL_sysjoystick.c
deleted file mode 100644
index 3645dbd014..0000000000
--- a/apps/plugins/sdl/src/joystick/macos/SDL_sysjoystick.c
+++ /dev/null
@@ -1,320 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_JOYSTICK_MACOS
25
26/* SDL stuff -- "SDL_sysjoystick.c"
27 MacOS joystick functions by Frederick Reitberger
28
29 The code that follows is meant for SDL. Use at your own risk.
30*/
31
32#include <InputSprocket.h>
33
34#include "SDL_joystick.h"
35#include "../SDL_sysjoystick.h"
36#include "../SDL_joystick_c.h"
37
38
39/* The max number of joysticks we will detect */
40#define MAX_JOYSTICKS 16
41/* Limit ourselves to 32 elements per device */
42#define kMaxReferences 32
43
44#define ISpSymmetricAxisToFloat(axis) ((((float) axis) - kISpAxisMiddle) / (kISpAxisMaximum-kISpAxisMiddle))
45#define ISpAsymmetricAxisToFloat(axis) (((float) axis) / (kISpAxisMaximum))
46
47
48static ISpDeviceReference SYS_Joysticks[MAX_JOYSTICKS];
49static ISpElementListReference SYS_Elements[MAX_JOYSTICKS];
50static ISpDeviceDefinition SYS_DevDef[MAX_JOYSTICKS];
51
52struct joystick_hwdata
53{
54 char name[64];
55/* Uint8 id;*/
56 ISpElementReference refs[kMaxReferences];
57 /* gonna need some sort of mapping info */
58};
59
60
61/* Function to scan the system for joysticks.
62 * Joystick 0 should be the system default joystick.
63 * This function should return the number of available joysticks, or -1
64 * on an unrecoverable fatal error.
65 */
66int SDL_SYS_JoystickInit(void)
67{
68 static ISpDeviceClass classes[4] = {
69 kISpDeviceClass_Joystick,
70 #if kISpDeviceClass_Gamepad
71 kISpDeviceClass_Gamepad,
72 #endif
73 kISpDeviceClass_Wheel,
74 0
75 };
76 OSErr err;
77 int i;
78 UInt32 count, numJoysticks;
79
80 if ( (Ptr)0 == (Ptr)ISpStartup ) {
81 SDL_SetError("InputSprocket not installed");
82 return -1; // InputSprocket not installed
83 }
84
85 if( (Ptr)0 == (Ptr)ISpGetVersion ) {
86 SDL_SetError("InputSprocket not version 1.1 or newer");
87 return -1; // old version of ISp (not at least 1.1)
88 }
89
90 ISpStartup();
91
92 /* Get all the joysticks */
93 numJoysticks = 0;
94 for ( i=0; classes[i]; ++i ) {
95 count = 0;
96 err = ISpDevices_ExtractByClass(
97 classes[i],
98 MAX_JOYSTICKS-numJoysticks,
99 &count,
100 &SYS_Joysticks[numJoysticks]);
101 numJoysticks += count;
102 }
103
104 for(i = 0; i < numJoysticks; i++)
105 {
106 ISpDevice_GetDefinition(
107 SYS_Joysticks[i], sizeof(ISpDeviceDefinition),
108 &SYS_DevDef[i]);
109
110 err = ISpElementList_New(
111 0, NULL,
112 &SYS_Elements[i], 0);
113
114 if (err) {
115 SDL_OutOfMemory();
116 return -1;
117 }
118
119 ISpDevice_GetElementList(
120 SYS_Joysticks[i],
121 &SYS_Elements[i]);
122 }
123
124 ISpDevices_Deactivate(numJoysticks, SYS_Joysticks);
125
126 return numJoysticks;
127}
128
129/* Function to get the device-dependent name of a joystick */
130const char *SDL_SYS_JoystickName(int index)
131{
132 static char name[64];
133 int len;
134
135 /* convert pascal string to c-string */
136 len = SYS_DevDef[index].deviceName[0];
137 if ( len >= sizeof(name) ) {
138 len = (sizeof(name) - 1);
139 }
140 SDL_memcpy(name, &SYS_DevDef[index].deviceName[1], len);
141 name[len] = '\0';
142
143 return name;
144}
145
146/* Function to open a joystick for use.
147 The joystick to open is specified by the index field of the joystick.
148 This should fill the nbuttons and naxes fields of the joystick structure.
149 It returns 0, or -1 if there is an error.
150 */
151int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
152{
153 int index;
154 UInt32 count, gotCount, count2;
155 long numAxis, numButtons, numHats, numBalls;
156
157 count = kMaxReferences;
158 count2 = 0;
159 numAxis = numButtons = numHats = numBalls = 0;
160
161 index = joystick->index;
162
163 /* allocate memory for system specific hardware data */
164 joystick->hwdata = (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata));
165 if (joystick->hwdata == NULL)
166 {
167 SDL_OutOfMemory();
168 return(-1);
169 }
170 SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata));
171 SDL_strlcpy(joystick->hwdata->name, SDL_SYS_JoystickName(index), SDL_arraysize(joystick->hwdata->name));
172 joystick->name = joystick->hwdata->name;
173
174 ISpElementList_ExtractByKind(
175 SYS_Elements[index],
176 kISpElementKind_Axis,
177 count,
178 &gotCount,
179 joystick->hwdata->refs);
180
181 numAxis = gotCount;
182 count -= gotCount;
183 count2 += gotCount;
184
185 ISpElementList_ExtractByKind(
186 SYS_Elements[index],
187 kISpElementKind_DPad,
188 count,
189 &gotCount,
190 &(joystick->hwdata->refs[count2]));
191
192 numHats = gotCount;
193 count -= gotCount;
194 count2 += gotCount;
195
196 ISpElementList_ExtractByKind(
197 SYS_Elements[index],
198 kISpElementKind_Button,
199 count,
200 &gotCount,
201 &(joystick->hwdata->refs[count2]));
202
203 numButtons = gotCount;
204 count -= gotCount;
205 count2 += gotCount;
206
207 joystick->naxes = numAxis;
208 joystick->nhats = numHats;
209 joystick->nballs = numBalls;
210 joystick->nbuttons = numButtons;
211
212 ISpDevices_Activate(
213 1,
214 &SYS_Joysticks[index]);
215
216 return 0;
217}
218
219/* Function to update the state of a joystick - called as a device poll.
220 * This function shouldn't update the joystick structure directly,
221 * but instead should call SDL_PrivateJoystick*() to deliver events
222 * and update joystick device state.
223 */
224void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
225{
226 int i, j;
227 ISpAxisData a;
228 ISpDPadData b;
229 //ISpDeltaData c;
230 ISpButtonData d;
231
232 for(i = 0, j = 0; i < joystick->naxes; i++, j++)
233 {
234 Sint16 value;
235
236 ISpElement_GetSimpleState(
237 joystick->hwdata->refs[j],
238 &a);
239 value = (ISpSymmetricAxisToFloat(a)* 32767.0);
240 if ( value != joystick->axes[i] ) {
241 SDL_PrivateJoystickAxis(joystick, i, value);
242 }
243 }
244
245 for(i = 0; i < joystick->nhats; i++, j++)
246 {
247 Uint8 pos;
248
249 ISpElement_GetSimpleState(
250 joystick->hwdata->refs[j],
251 &b);
252 switch(b) {
253 case kISpPadIdle:
254 pos = SDL_HAT_CENTERED;
255 break;
256 case kISpPadLeft:
257 pos = SDL_HAT_LEFT;
258 break;
259 case kISpPadUpLeft:
260 pos = SDL_HAT_LEFTUP;
261 break;
262 case kISpPadUp:
263 pos = SDL_HAT_UP;
264 break;
265 case kISpPadUpRight:
266 pos = SDL_HAT_RIGHTUP;
267 break;
268 case kISpPadRight:
269 pos = SDL_HAT_RIGHT;
270 break;
271 case kISpPadDownRight:
272 pos = SDL_HAT_RIGHTDOWN;
273 break;
274 case kISpPadDown:
275 pos = SDL_HAT_DOWN;
276 break;
277 case kISpPadDownLeft:
278 pos = SDL_HAT_LEFTDOWN;
279 break;
280 }
281 if ( pos != joystick->hats[i] ) {
282 SDL_PrivateJoystickHat(joystick, i, pos);
283 }
284 }
285
286 for(i = 0; i < joystick->nballs; i++, j++)
287 {
288 /* ignore balls right now */
289 }
290
291 for(i = 0; i < joystick->nbuttons; i++, j++)
292 {
293 ISpElement_GetSimpleState(
294 joystick->hwdata->refs[j],
295 &d);
296 if ( d != joystick->buttons[i] ) {
297 SDL_PrivateJoystickButton(joystick, i, d);
298 }
299 }
300}
301
302/* Function to close a joystick after use */
303void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
304{
305 int index;
306
307 index = joystick->index;
308
309 ISpDevices_Deactivate(
310 1,
311 &SYS_Joysticks[index]);
312}
313
314/* Function to perform any system-specific joystick related cleanup */
315void SDL_SYS_JoystickQuit(void)
316{
317 ISpShutdown();
318}
319
320#endif /* SDL_JOYSTICK_MACOS */
diff --git a/apps/plugins/sdl/src/joystick/mint/SDL_sysjoystick.c b/apps/plugins/sdl/src/joystick/mint/SDL_sysjoystick.c
deleted file mode 100644
index 9a36152927..0000000000
--- a/apps/plugins/sdl/src/joystick/mint/SDL_sysjoystick.c
+++ /dev/null
@@ -1,826 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_JOYSTICK_MINT
25
26/*
27 * Atari Joystick/Joypad drivers
28 *
29 * Patrice Mandin
30 */
31
32#include <mint/cookie.h>
33#include <mint/osbind.h>
34
35#include "SDL_events.h"
36#include "../SDL_sysjoystick.h"
37#include "../SDL_joystick_c.h"
38
39#include "../../video/ataricommon/SDL_ikbdinterrupt_s.h"
40#include "../../video/ataricommon/SDL_xbiosevents_c.h"
41#include "../../video/ataricommon/SDL_xbiosinterrupt_s.h"
42
43/*--- Const ---*/
44
45/* We can have:
46 1 joystick on IKBD port 1, read via hardware I/O
47 or same joystick on IKBD port 1, read via xbios
48 1 joypad on port A (up to 4 with teamtap)
49 or 2 joysticks on joypad port A
50 or 1 analog paddle on joypad port A
51 or 1 lightpen on joypad port A
52 1 joypad on port B (up to 4 with teamtap)
53 or 2 joysticks on joypad port B
54 or 1 analog paddle on joypad port B
55 2 joysticks on parallel port
56*/
57
58enum {
59 IKBD_JOY1=0,
60 XBIOS_JOY1,
61 PORTA_PAD0,
62 PORTA_PAD1,
63 PORTA_PAD2,
64 PORTA_PAD3,
65 PORTB_PAD0,
66 PORTB_PAD1,
67 PORTB_PAD2,
68 PORTB_PAD3,
69 PORTA_JOY0,
70 PORTA_JOY1,
71 PORTB_JOY0,
72 PORTB_JOY1,
73 PORTA_LP,
74 PORTA_ANPAD,
75 PORTB_ANPAD,
76#if 0
77 PARA_JOY0,
78 PARA_JOY1,
79#endif
80 MAX_JOYSTICKS
81};
82
83enum {
84 MCH_ST=0,
85 MCH_STE,
86 MCH_TT,
87 MCH_F30,
88 MCH_CLONE,
89 MCH_ARANYM
90};
91
92/* Joypad buttons
93 * Procontroller note:
94 * L,R are connected to 4,6
95 * X,Y,Z are connected to 7,8,9
96 */
97
98enum {
99 JP_UP=0, JP_DOWN, JP_LEFT, JP_RIGHT,
100 JP_KPMULT, JP_KP7, JP_KP4, JP_KP1,
101 JP_KP0, JP_KP8, JP_KP5, JP_KP2,
102 JP_KPNUM, JP_KP9, JP_KP6, JP_KP3,
103 JP_PAUSE, JP_FIRE0, JP_UNDEF0, JP_FIRE1,
104 JP_UNDEF1, JP_FIRE2, JP_UNDEF2, JP_OPTION
105};
106
107#define JP_NUM_BUTTONS 17
108
109#define PORT_JS_RIGHT (1<<0)
110#define PORT_JS_LEFT (1<<1)
111#define PORT_JS_DOWN (1<<2)
112#define PORT_JS_UP (1<<3)
113#define PORT_JS_FIRE (1<<4)
114
115enum {
116 TEAMTAP_MAYBE=0,
117 TEAMTAP_YES,
118 TEAMTAP_NO
119};
120
121/* Teamtap detection values */
122static const Uint32 teamtap_ghosts[20][4]={
123 {1<<JP_UP, /* for this event on joypad 0, port X */
124 (1<<JP_UP)|(1<<JP_KP0), /* we get this on joypad 1 */
125 (1<<JP_UP)|(1<<JP_KPNUM)|(1<<JP_KP0), /* this on joypad 2 */
126 (1<<JP_KPMULT)|(1<<JP_KP0)}, /* this on joypad 3 */
127 {1<<JP_DOWN,
128 (1<<JP_DOWN)|(1<<JP_KP8),
129 (1<<JP_DOWN)|(1<<JP_KP9)|(1<<JP_KP8),
130 (1<<JP_KP7)|(1<<JP_KP8)},
131 {1<<JP_LEFT,
132 (1<<JP_LEFT)|(1<<JP_KP5),
133 (1<<JP_LEFT)|(1<<JP_KP6)|(1<<JP_KP5),
134 (1<<JP_KP4)|(1<<JP_KP5)},
135 {1<<JP_RIGHT,
136 (1<<JP_RIGHT)|(1<<JP_KP2),
137 (1<<JP_RIGHT)|(1<<JP_KP3)|(1<<JP_KP2),
138 (1<<JP_KP1)|(1<<JP_KP2)},
139 {1<<JP_OPTION,
140 (1<<JP_OPTION)|(1<<JP_FIRE1)|(1<<JP_FIRE2),
141 (1<<JP_FIRE0)|(1<<JP_FIRE1)|(1<<JP_FIRE2),
142 0},
143 {1<<JP_FIRE0,
144 (1<<JP_FIRE2)|(1<<JP_FIRE0),
145 (1<<JP_FIRE0)|(1<<JP_OPTION)|(1<<JP_FIRE2),
146 (1<<JP_FIRE1)|(1<<JP_FIRE2)},
147 {1<<JP_FIRE1,
148 (1<<JP_FIRE0),
149 (1<<JP_OPTION)|(1<<JP_FIRE0)|(1<<JP_FIRE1),
150 (1<<JP_FIRE0)|(1<<JP_FIRE2)},
151 {1<<JP_FIRE2,
152 (1<<JP_OPTION)|(1<<JP_FIRE0)|(1<<JP_FIRE1)|(1<<JP_FIRE2),
153 (1<<JP_OPTION),
154 (1<<JP_FIRE0)|(1<<JP_FIRE1)},
155 {1<<JP_KP1,
156 (1<<JP_RIGHT)|(1<<JP_KP1),
157 (1<<JP_RIGHT)|(1<<JP_KP1)|(1<<JP_KP3),
158 (1<<JP_RIGHT)|(1<<JP_KP2)},
159 {1<<JP_KP2,
160 (1<<JP_RIGHT)|(1<<JP_KP1)|(1<<JP_KP2)|(1<<JP_KP3),
161 (1<<JP_KP3),
162 (1<<JP_RIGHT)|(1<<JP_KP1)},
163 {1<<JP_KP3,
164 (1<<JP_RIGHT)|(1<<JP_KP1)|(1<<JP_KP2)|(1<<JP_KP3),
165 (1<<JP_RIGHT)|(1<<JP_KP1)|(1<<JP_KP2),
166 0},
167 {1<<JP_KP4,
168 (1<<JP_LEFT)|(1<<JP_KP4),
169 (1<<JP_LEFT)|(1<<JP_KP4)|(1<<JP_KP6),
170 (1<<JP_LEFT)|(1<<JP_KP5)},
171 {1<<JP_KP5,
172 (1<<JP_LEFT)|(1<<JP_KP4)|(1<<JP_KP5)|(1<<JP_KP6),
173 (1<<JP_KP6),
174 (1<<JP_LEFT)|(1<<JP_KP4)},
175 {1<<JP_KP6,
176 (1<<JP_LEFT)|(1<<JP_KP4)|(1<<JP_KP5)|(1<<JP_KP6),
177 (1<<JP_LEFT)|(1<<JP_KP4)|(1<<JP_KP5),
178 0},
179 {1<<JP_KP7,
180 (1<<JP_DOWN)|(1<<JP_KP7),
181 (1<<JP_DOWN)|(1<<JP_KP7)|(1<<JP_KP9),
182 (1<<JP_DOWN)|(1<<JP_KP8)},
183 {1<<JP_KP8,
184 (1<<JP_DOWN)|(1<<JP_KP7)|(1<<JP_KP8)|(1<<JP_KP9),
185 (1<<JP_KP9),
186 (1<<JP_DOWN)|(1<<JP_KP7)},
187 {1<<JP_KP9,
188 (1<<JP_DOWN)|(1<<JP_KP7)|(1<<JP_KP8)|(1<<JP_KP9),
189 (1<<JP_DOWN)|(1<<JP_KP7)|(1<<JP_KP8),
190 0},
191 {1<<JP_KPMULT,
192 (1<<JP_UP)|(1<<JP_KPMULT),
193 (1<<JP_UP)|(1<<JP_KPNUM),
194 (1<<JP_UP)|(1<<JP_KP0)},
195 {1<<JP_KP0,
196 (1<<JP_UP)|(1<<JP_KPNUM)|(1<<JP_KPMULT)|(1<<JP_KP0),
197 1<<JP_KPNUM,
198 (1<<JP_UP)|(1<<JP_KPMULT)},
199 {1<<JP_KPNUM,
200 (1<<JP_UP)|(1<<JP_KPNUM)|(1<<JP_KPMULT)|(1<<JP_KP0),
201 (1<<JP_UP)|(1<<JP_KPMULT)|(1<<JP_KP0),
202 0},
203};
204
205/*--- Types ---*/
206
207typedef struct {
208 SDL_bool enabled;
209 char *name;
210 Uint32 prevstate;
211} atarijoy_t;
212
213/*--- Variables ---*/
214
215static atarijoy_t atarijoysticks[MAX_JOYSTICKS]={
216 {SDL_FALSE,"IKBD joystick port 1",0},
217 {SDL_FALSE,"Xbios joystick port 1",0},
218 {SDL_FALSE,"Joypad 0 port A",0},
219 {SDL_FALSE,"Joypad 1 port A",0},
220 {SDL_FALSE,"Joypad 2 port A",0},
221 {SDL_FALSE,"Joypad 3 port A",0},
222 {SDL_FALSE,"Joypad 0 port B",0},
223 {SDL_FALSE,"Joypad 1 port B",0},
224 {SDL_FALSE,"Joypad 2 port B",0},
225 {SDL_FALSE,"Joypad 3 port B",0},
226 {SDL_FALSE,"Joystick 0 port A",0},
227 {SDL_FALSE,"Joystick 1 port A",0},
228 {SDL_FALSE,"Joystick 0 port B",0},
229 {SDL_FALSE,"Joystick 1 port B",0},
230 {SDL_FALSE,"Lightpen port A",0},
231 {SDL_FALSE,"Analog paddle port A",0},
232 {SDL_FALSE,"Analog paddle port B",0}
233#if 0
234 ,{SDL_FALSE,"Joystick 0 parallel port",0},
235 {SDL_FALSE,"Joystick 1 parallel port",0}
236#endif
237};
238
239static const int jp_buttons[JP_NUM_BUTTONS]={
240 JP_FIRE0, JP_FIRE1, JP_FIRE2, JP_PAUSE,
241 JP_OPTION, JP_KPMULT, JP_KPNUM, JP_KP0,
242 JP_KP1, JP_KP2, JP_KP3, JP_KP4,
243 JP_KP5, JP_KP6, JP_KP7, JP_KP8,
244 JP_KP9
245};
246
247static SDL_bool joypad_ports_enabled=SDL_FALSE;
248static int has_teamtap[2]={TEAMTAP_MAYBE,TEAMTAP_MAYBE};
249
250/* Updated joypad ports */
251static Uint16 jp_paddles[4];
252static Uint16 jp_lightpens[2];
253static Uint16 jp_directions;
254static Uint16 jp_fires;
255static Uint32 jp_joypads[8];
256
257/*--- Functions prototypes ---*/
258
259static int GetEnabledAtariJoystick(int index);
260static void UpdateJoypads(void);
261
262/*--- Functions ---*/
263
264int SDL_SYS_JoystickInit(void)
265{
266 int i;
267 long cookie_mch;
268 const char *envr=SDL_getenv("SDL_JOYSTICK_ATARI");
269
270#define TEST_JOY_ENABLED(env,idstring,num) \
271 if (SDL_strstr(env,idstring"-off")) { \
272 atarijoysticks[num].enabled=SDL_FALSE; \
273 } \
274 if (SDL_strstr(env,idstring"-on")) { \
275 atarijoysticks[num].enabled=SDL_TRUE; \
276 }
277
278 /* Cookie _MCH present ? if not, assume ST machine */
279 if (Getcookie(C__MCH, &cookie_mch) != C_FOUND) {
280 cookie_mch = MCH_ST << 16;
281 }
282
283 /* Enable some default joysticks */
284 if ((cookie_mch == MCH_ST<<16) || ((cookie_mch>>16) == MCH_STE) ||
285 (cookie_mch == MCH_TT<<16) || (cookie_mch == MCH_F30<<16) ||
286 (cookie_mch == MCH_ARANYM<<16))
287 {
288 atarijoysticks[IKBD_JOY1].enabled=(SDL_AtariIkbd_enabled!=0);
289 }
290 if ((cookie_mch == MCH_STE<<16) || (cookie_mch == MCH_F30<<16) ||
291 (cookie_mch == MCH_ARANYM<<16))
292 {
293 atarijoysticks[PORTA_PAD0].enabled =
294 atarijoysticks[PORTA_PAD1].enabled =
295 atarijoysticks[PORTA_PAD2].enabled =
296 atarijoysticks[PORTA_PAD3].enabled =
297 atarijoysticks[PORTB_PAD0].enabled =
298 atarijoysticks[PORTB_PAD1].enabled =
299 atarijoysticks[PORTB_PAD2].enabled =
300 atarijoysticks[PORTB_PAD3].enabled = SDL_TRUE;
301 }
302 if (!atarijoysticks[IKBD_JOY1].enabled) {
303 atarijoysticks[XBIOS_JOY1].enabled=(SDL_AtariXbios_enabled!=0);
304 }
305
306 /* Read environment for joysticks to enable */
307 if (envr) {
308 /* IKBD on any Atari, maybe clones */
309 if ((cookie_mch == MCH_ST<<16) || ((cookie_mch>>16) == MCH_STE) ||
310 (cookie_mch == MCH_TT<<16) || (cookie_mch == MCH_F30<<16) ||
311 (cookie_mch == MCH_ARANYM<<16)) {
312 if (SDL_AtariIkbd_enabled!=0) {
313 TEST_JOY_ENABLED(envr, "ikbd-joy1", IKBD_JOY1);
314 }
315 }
316 /* Joypads ports on STE, Falcon and maybe others */
317 if ((cookie_mch == MCH_STE<<16) || (cookie_mch == MCH_F30<<16) ||
318 (cookie_mch == MCH_ARANYM<<16)) {
319 TEST_JOY_ENABLED(envr, "porta-pad", PORTA_PAD0);
320 if (!atarijoysticks[PORTA_PAD0].enabled) {
321 TEST_JOY_ENABLED(envr, "porta-joy0", PORTA_JOY0);
322 TEST_JOY_ENABLED(envr, "porta-joy1", PORTA_JOY1);
323 if (!(atarijoysticks[PORTA_JOY0].enabled) && !(atarijoysticks[PORTA_JOY1].enabled)) {
324 TEST_JOY_ENABLED(envr, "porta-lp", PORTA_LP);
325 if (!atarijoysticks[PORTA_LP].enabled) {
326 TEST_JOY_ENABLED(envr, "porta-anpad", PORTA_ANPAD);
327 }
328 }
329 }
330
331 TEST_JOY_ENABLED(envr, "portb-pad", PORTB_PAD0);
332 if (!atarijoysticks[PORTB_PAD0].enabled) {
333 TEST_JOY_ENABLED(envr, "portb-joy0", PORTB_JOY0);
334 TEST_JOY_ENABLED(envr, "portb-joy1", PORTB_JOY1);
335 if (!(atarijoysticks[PORTB_JOY0].enabled) && !(atarijoysticks[PORTB_JOY1].enabled)) {
336 TEST_JOY_ENABLED(envr, "portb-anpad", PORTB_ANPAD);
337 }
338 }
339 }
340
341 if (!atarijoysticks[IKBD_JOY1].enabled) {
342 if (SDL_AtariXbios_enabled!=0) {
343 TEST_JOY_ENABLED(envr, "xbios-joy1", XBIOS_JOY1);
344 }
345 }
346#if 0
347 /* Parallel port on any Atari, maybe clones */
348 if ((cookie_mch == MCH_ST<<16) || ((cookie_mch>>16) == MCH_STE) ||
349 (cookie_mch == MCH_TT<<16) || (cookie_mch == MCH_F30<<16)) {
350 TEST_JOY_ENABLED(envr, "para-joy0", PARA_JOY0);
351 TEST_JOY_ENABLED(envr, "para-joy1", PARA_JOY1);
352 }
353#endif
354 }
355
356 /* Need to update joypad ports ? */
357 joypad_ports_enabled=SDL_FALSE;
358 for (i=PORTA_PAD0;i<=PORTB_ANPAD;i++) {
359 if (atarijoysticks[i].enabled) {
360 joypad_ports_enabled=SDL_TRUE;
361 break;
362 }
363 }
364
365 SDL_numjoysticks = 0;
366 for (i=0;i<MAX_JOYSTICKS;i++) {
367 if (atarijoysticks[i].enabled) {
368 ++SDL_numjoysticks;
369 }
370 }
371
372 return(SDL_numjoysticks);
373}
374
375static int GetEnabledAtariJoystick(int index)
376{
377 int i,j;
378
379 /* Return the nth'index' enabled atari joystick */
380 j=0;
381 for (i=0;i<MAX_JOYSTICKS;i++) {
382 if (!atarijoysticks[i].enabled) {
383 continue;
384 }
385
386 if (j==index) {
387 break;
388 }
389
390 ++j;
391 }
392 if (i==MAX_JOYSTICKS)
393 return -1;
394
395 return i;
396}
397
398const char *SDL_SYS_JoystickName(int index)
399{
400 int numjoystick;
401
402 numjoystick=GetEnabledAtariJoystick(index);
403 if (numjoystick==-1)
404 return NULL;
405
406 return(atarijoysticks[numjoystick].name);
407}
408
409int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
410{
411 int numjoystick;
412
413 numjoystick=GetEnabledAtariJoystick(joystick->index);
414 if (numjoystick==-1)
415 return -1;
416
417 joystick->naxes=0;
418 joystick->nhats=0;
419 joystick->nballs=0;
420
421 switch(numjoystick) {
422 case PORTA_PAD0:
423 case PORTA_PAD1:
424 case PORTA_PAD2:
425 case PORTA_PAD3:
426 case PORTB_PAD0:
427 case PORTB_PAD1:
428 case PORTB_PAD2:
429 case PORTB_PAD3:
430 joystick->nhats=1;
431 joystick->nbuttons=JP_NUM_BUTTONS;
432 break;
433 case PORTA_LP:
434 case PORTA_ANPAD:
435 case PORTB_ANPAD:
436 joystick->naxes=2;
437 joystick->nbuttons=2;
438 break;
439 default:
440 joystick->nhats=1;
441 joystick->nbuttons=1;
442 break;
443 }
444
445 return(0);
446}
447
448/* Detect Teamtap using ghost events */
449static void detect_teamtap(int num_port)
450{
451 int i,j;
452
453 /* Check if joypad 1,2,3 triggered but not 0 */
454 for (i=1; i<4; i++) {
455 if (jp_joypads[num_port*4+i] && (jp_joypads[num_port*4]==0)) {
456 has_teamtap[num_port] = TEAMTAP_YES;
457 return;
458 }
459 }
460
461 /* Check if joypad 0 on a given port triggered ghost events for
462 * other joypads
463 */
464 for (i=0; i<20; i++) {
465 int with_teamtap=1;
466
467 if (jp_joypads[num_port*4]!=teamtap_ghosts[i][0])
468 continue;
469
470 /* If any button on first joypad pressed, check other pads */
471 for (j=1; j<4; j++) {
472 if ((jp_joypads[num_port*4+j] & teamtap_ghosts[i][j])
473 ==teamtap_ghosts[i][j])
474 {
475 with_teamtap = 0;
476 }
477 }
478
479 has_teamtap[num_port] = (with_teamtap ? TEAMTAP_YES : TEAMTAP_NO);
480 break;
481 }
482}
483
484void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
485{
486 int numjoystick;
487 Uint8 hatstate;
488 Uint32 curstate,prevstate;
489
490 numjoystick=GetEnabledAtariJoystick(joystick->index);
491 if (numjoystick==-1)
492 return;
493
494 prevstate = atarijoysticks[numjoystick].prevstate;
495
496 if (joypad_ports_enabled) {
497 Supexec(UpdateJoypads);
498 }
499
500 switch (numjoystick) {
501 case IKBD_JOY1:
502 case XBIOS_JOY1:
503 {
504 curstate = 0;
505
506 if (numjoystick==IKBD_JOY1) {
507 curstate = SDL_AtariIkbd_joystick & 0xff;
508 }
509 if (numjoystick==XBIOS_JOY1) {
510 curstate = SDL_AtariXbios_joystick & 0xff;
511 }
512
513 if (curstate != prevstate) {
514 hatstate = SDL_HAT_CENTERED;
515 if (curstate & IKBD_JOY_LEFT) {
516 hatstate |= SDL_HAT_LEFT;
517 }
518 if (curstate & IKBD_JOY_RIGHT) {
519 hatstate |= SDL_HAT_RIGHT;
520 }
521 if (curstate & IKBD_JOY_UP) {
522 hatstate |= SDL_HAT_UP;
523 }
524 if (curstate & IKBD_JOY_DOWN) {
525 hatstate |= SDL_HAT_DOWN;
526 }
527 SDL_PrivateJoystickHat(joystick, 0, hatstate);
528
529 /* Button */
530 if ((curstate & IKBD_JOY_FIRE) && !(prevstate & IKBD_JOY_FIRE)) {
531 SDL_PrivateJoystickButton(joystick,0,SDL_PRESSED);
532 }
533 if (!(curstate & IKBD_JOY_FIRE) && (prevstate & IKBD_JOY_FIRE)) {
534 SDL_PrivateJoystickButton(joystick,0,SDL_RELEASED);
535 }
536 }
537 atarijoysticks[numjoystick].prevstate = curstate;
538 }
539 break;
540 case PORTA_PAD0:
541 case PORTA_PAD1:
542 case PORTA_PAD2:
543 case PORTA_PAD3:
544 case PORTB_PAD0:
545 case PORTB_PAD1:
546 case PORTB_PAD2:
547 case PORTB_PAD3:
548 {
549 int numjoypad,i,numport;
550
551 numjoypad = numport = 0;
552 switch(numjoystick) {
553 case PORTA_PAD0:
554 numjoypad = 0; break;
555 case PORTA_PAD1:
556 numjoypad = 1; break;
557 case PORTA_PAD2:
558 numjoypad = 2; break;
559 case PORTA_PAD3:
560 numjoypad = 3; break;
561 case PORTB_PAD0:
562 numjoypad = 4; numport = 1; break;
563 case PORTB_PAD1:
564 numjoypad = 5; numport = 1; break;
565 case PORTB_PAD2:
566 numjoypad = 6; numport = 1; break;
567 case PORTB_PAD3:
568 numjoypad = 7; numport = 1; break;
569 }
570
571 jp_joypads[numjoypad] &= 0xabffff;
572
573 if (has_teamtap[numport]==TEAMTAP_MAYBE) {
574 detect_teamtap(numport);
575 }
576 /* No events for PORTX_PAD[1,2,3] if no teamtap detected */
577 if (has_teamtap[numport] == TEAMTAP_NO) {
578 if ((numjoypad & 3)!=0) {
579 return;
580 }
581 }
582
583 curstate=jp_joypads[numjoypad];
584 if (curstate!=prevstate) {
585 hatstate = SDL_HAT_CENTERED;
586 if (curstate & (1<<JP_LEFT)) {
587 hatstate |= SDL_HAT_LEFT;
588 }
589 if (curstate & (1<<JP_RIGHT)) {
590 hatstate |= SDL_HAT_RIGHT;
591 }
592 if (curstate & (1<<JP_UP)) {
593 hatstate |= SDL_HAT_UP;
594 }
595 if (curstate & (1<<JP_DOWN)) {
596 hatstate |= SDL_HAT_DOWN;
597 }
598 SDL_PrivateJoystickHat(joystick, 0, hatstate);
599
600 /* Buttons */
601 for (i=0;i<JP_NUM_BUTTONS;i++) {
602 int button;
603
604 button=1<<jp_buttons[i];
605
606 if ((curstate & button) && !(prevstate & button)) {
607 SDL_PrivateJoystickButton(joystick,i,SDL_PRESSED);
608 }
609 if (!(curstate & button) && (prevstate & button)) {
610 SDL_PrivateJoystickButton(joystick,i,SDL_RELEASED);
611 }
612 }
613 }
614 atarijoysticks[numjoystick].prevstate = curstate;
615 }
616 break;
617 case PORTA_JOY0:
618 case PORTA_JOY1:
619 case PORTB_JOY0:
620 case PORTB_JOY1:
621 {
622 int fire_shift=0,dir_shift=0;
623
624 if (numjoystick==PORTA_JOY0) { fire_shift=0; dir_shift=0; }
625 if (numjoystick==PORTA_JOY1) { fire_shift=1; dir_shift=4; }
626 if (numjoystick==PORTB_JOY0) { fire_shift=2; dir_shift=8; }
627 if (numjoystick==PORTB_JOY1) { fire_shift=3; dir_shift=12; }
628
629 curstate = (jp_directions>>dir_shift) & 15;
630 curstate |= ((jp_fires>>fire_shift) & 1)<<4;
631
632 if (curstate != prevstate) {
633 hatstate = SDL_HAT_CENTERED;
634 if (curstate & PORT_JS_LEFT) {
635 hatstate |= SDL_HAT_LEFT;
636 }
637 if (curstate & PORT_JS_RIGHT) {
638 hatstate |= SDL_HAT_RIGHT;
639 }
640 if (curstate & PORT_JS_UP) {
641 hatstate |= SDL_HAT_UP;
642 }
643 if (curstate & PORT_JS_DOWN) {
644 hatstate |= SDL_HAT_DOWN;
645 }
646 SDL_PrivateJoystickHat(joystick, 0, hatstate);
647
648 /* Button */
649 if ((curstate & PORT_JS_FIRE) && !(prevstate & PORT_JS_FIRE)) {
650 SDL_PrivateJoystickButton(joystick,0,SDL_PRESSED);
651 }
652 if (!(curstate & PORT_JS_FIRE) && (prevstate & PORT_JS_FIRE)) {
653 SDL_PrivateJoystickButton(joystick,0,SDL_RELEASED);
654 }
655 }
656 atarijoysticks[numjoystick].prevstate = curstate;
657 }
658 break;
659 case PORTA_LP:
660 {
661 int i;
662
663 curstate = jp_lightpens[0]>>1;
664 curstate |= (jp_lightpens[1]>>1)<<15;
665 curstate |= (jp_fires & 3)<<30;
666
667 if (curstate != prevstate) {
668 /* X axis */
669 SDL_PrivateJoystickAxis(joystick,0,jp_lightpens[0] ^ 0x8000);
670 /* Y axis */
671 SDL_PrivateJoystickAxis(joystick,1,jp_lightpens[1] ^ 0x8000);
672 /* Buttons */
673 for (i=0;i<2;i++) {
674 int button;
675
676 button=1<<(30+i);
677
678 if ((curstate & button) && !(prevstate & button)) {
679 SDL_PrivateJoystickButton(joystick,i,SDL_PRESSED);
680 }
681 if (!(curstate & button) && (prevstate & button)) {
682 SDL_PrivateJoystickButton(joystick,i,SDL_RELEASED);
683 }
684 }
685 }
686 atarijoysticks[numjoystick].prevstate = curstate;
687 }
688 break;
689 case PORTA_ANPAD:
690 case PORTB_ANPAD:
691 {
692 int numpaddle, i;
693
694 numpaddle=0<<1;
695 if (numjoystick==PORTB_ANPAD) numpaddle=1<<1;
696
697 curstate = jp_paddles[numpaddle]>>1;
698 curstate |= (jp_paddles[numpaddle+1]>>1)<<15;
699 curstate |= ((jp_fires>>numpaddle) & 3)<<30;
700
701 if (curstate != prevstate) {
702 /* X axis */
703 SDL_PrivateJoystickAxis(joystick,0,jp_paddles[numpaddle] ^ 0x8000);
704 /* Y axis */
705 SDL_PrivateJoystickAxis(joystick,1,jp_paddles[numpaddle+1] ^ 0x8000);
706 /* Buttons */
707 for (i=0;i<2;i++) {
708 int button;
709
710 button=1<<(30+i);
711
712 if ((curstate & button) && !(prevstate & button)) {
713 SDL_PrivateJoystickButton(joystick,i,SDL_PRESSED);
714 }
715 if (!(curstate & button) && (prevstate & button)) {
716 SDL_PrivateJoystickButton(joystick,i,SDL_RELEASED);
717 }
718 }
719 }
720 atarijoysticks[numjoystick].prevstate = curstate;
721 }
722 break;
723#if 0
724 case PARA_JOY0:
725 case PARA_JOY1:
726 break;
727#endif
728 };
729
730 return;
731}
732
733void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
734{
735 return;
736}
737
738void SDL_SYS_JoystickQuit(void)
739{
740 SDL_numjoysticks=0;
741 return;
742}
743
744/*--- Joypad I/O read/write interface ---*/
745
746#define JOYPAD_IO_BASE (0xffff9200)
747struct JOYPAD_IO_S {
748 Uint16 fires;
749 Uint16 directions;
750 Uint16 dummy1[6];
751 Uint16 paddles[4];
752 Uint16 dummy2[4];
753 Uint16 lightpens[2];
754};
755#define JOYPAD_IO ((*(volatile struct JOYPAD_IO_S *)JOYPAD_IO_BASE))
756
757static const Uint16 joypad_masks[8*4]={
758 0xfffe, 0xfffd, 0xfffb, 0xfff7,
759 0xfff0, 0xfff1, 0xfff2, 0xfff3,
760 0xfff4, 0xfff5, 0xfff6, 0xfff8,
761 0xfff9, 0xfffa, 0xfffc, 0xffff,
762 0xffef, 0xffdf, 0xffbf, 0xff7f,
763 0xff0f, 0xff1f, 0xff2f, 0xff3f,
764 0xff4f, 0xff5f, 0xff6f, 0xff8f,
765 0xff9f, 0xffaf, 0xffcf, 0xffff
766};
767
768static void UpdateJoypads(void)
769{
770 Uint16 tmp, i, j;
771 Uint32 cur_fire, cur_dir;
772
773 /*--- This function is called in supervisor mode ---*/
774
775 /* Update joysticks */
776 jp_fires = (~(JOYPAD_IO.fires)) & 15;
777 jp_directions = (~(JOYPAD_IO.directions));
778
779 /* Update lightpen */
780 tmp = JOYPAD_IO.lightpens[0] & 1023;
781 jp_lightpens[0] = (tmp<<6) | (tmp>>4);
782 tmp = JOYPAD_IO.lightpens[1] & 1023;
783 jp_lightpens[1] = (tmp<<6) | (tmp>>4);
784
785 /* Update paddles */
786 tmp = (JOYPAD_IO.paddles[0] & 255);
787 jp_paddles[0] = (tmp<<8) | tmp;
788 tmp = (JOYPAD_IO.paddles[1] & 255);
789 jp_paddles[1] = (tmp<<8) | tmp;
790 tmp = (JOYPAD_IO.paddles[2] & 255);
791 jp_paddles[2] = (tmp<<8) | tmp;
792 tmp = (JOYPAD_IO.paddles[3] & 255);
793 jp_paddles[3] = (tmp<<8) | tmp;
794
795 /* Update joypads on teamtap port A */
796 for (i=0; i<4; i++) {
797 jp_joypads[i] = 0;
798 for (j=0; j<4; j++) {
799 JOYPAD_IO.directions = joypad_masks[(i*4)+j];
800
801 cur_fire = (~(JOYPAD_IO.fires) & 3)<<16;
802 cur_dir = (~(JOYPAD_IO.directions)>>8) & 15;
803
804 jp_joypads[i] |= cur_fire<<(j*2);
805 jp_joypads[i] |= cur_dir<<(j*4);
806 }
807 }
808
809 /* Update joypads on teamtap port B */
810 for (i=4; i<8; i++) {
811 jp_joypads[i] = 0;
812 for (j=0; j<4; j++) {
813 JOYPAD_IO.directions = joypad_masks[(i*4)+j];
814
815 cur_fire = (~(JOYPAD_IO.fires) & 0xc)<<14;
816 cur_dir = (~(JOYPAD_IO.directions)>>12) & 15;
817
818 jp_joypads[i] |= cur_fire<<(j*2);
819 jp_joypads[i] |= cur_dir<<(j*4);
820 }
821 }
822
823 JOYPAD_IO.directions=0xffff;
824}
825
826#endif /* SDL_JOYSTICK_MINT */
diff --git a/apps/plugins/sdl/src/joystick/nds/SDL_sysjoystick.c b/apps/plugins/sdl/src/joystick/nds/SDL_sysjoystick.c
deleted file mode 100644
index 122f48d863..0000000000
--- a/apps/plugins/sdl/src/joystick/nds/SDL_sysjoystick.c
+++ /dev/null
@@ -1,150 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the system specific header for the SDL joystick API */
25#include <nds.h>
26//#include <nds/registers_alt.h>
27
28#include "SDL_error.h"
29#include "SDL_events.h"
30#include "SDL_joystick.h"
31#include "../SDL_sysjoystick.h"
32#include "../SDL_joystick_c.h"
33
34#include "../../video/nds/SDL_ndsevents_c.h"
35
36/* Function to scan the system for joysticks.
37 * This function should set SDL_numjoysticks to the number of available
38 * joysticks. Joystick 0 should be the system default joystick.
39 * It should return 0, or -1 on an unrecoverable fatal error.
40 */
41int SDL_SYS_JoystickInit(void)
42{
43 SDL_numjoysticks = 1;
44 //keysInit();
45
46 return(1);
47}
48
49/* Function to get the device-dependent name of a joystick */
50const char *SDL_SYS_JoystickName(int index)
51{
52 if(!index)
53 return "NDS builtin joypad";
54 SDL_SetError("No joystick available with that index");
55 return (NULL);
56}
57
58/* Function to open a joystick for use.
59 The joystick to open is specified by the index field of the joystick.
60 This should fill the nbuttons and naxes fields of the joystick structure.
61 It returns 0, or -1 if there is an error.
62 */
63int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
64{
65 joystick->nbuttons=8;
66 joystick->nhats=0;
67 joystick->nballs=0;
68 joystick->naxes=2;
69 return 0;
70}
71
72
73/* Function to update the state of a joystick - called as a device poll.
74 * This function shouldn't update the joystick structure directly,
75 * but instead should call SDL_PrivateJoystick*() to deliver events
76 * and update joystick device state.
77 */
78
79int prevbutton=0;
80int prevkey=0;
81
82int dc=0;int ldc=0;
83u32 keysd,keysu=0;
84void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
85{
86 //dc=keysd;
87 //if (dc)
88 //{
89 //fprintf(stderr,"heartbeat= %d\n",REG_VCOUNT);
90 //swiWaitForVBlank();
91 //scanKeys();
92 //keysd = keysDown();
93 //keysu = keysUp();
94 //ldc=keysd;
95
96 //}
97 /*if (prevkey && prevbutton)
98 {
99 scanKeys();
100 }
101 */
102
103 //scanKeys();
104 keysd = keysDown();
105 keysu = keysUp();
106
107
108 short ax=0,v=0,h=0;
109 if((keysd&KEY_UP)) {ax=1;v=-10;SDL_PrivateJoystickAxis(joystick,ax,v);prevkey=KEY_UP;}//fprintf(stderr,"KEY_UP\n");}
110 if((keysd&KEY_DOWN)) {ax=1;v=10;SDL_PrivateJoystickAxis(joystick,ax,v);prevkey=KEY_DOWN;}//fprintf(stderr,"KEY_DOWN\n");}
111 if((keysd&KEY_LEFT)) {ax=0;h=-10;SDL_PrivateJoystickAxis(joystick,ax,h);prevkey=KEY_LEFT;}//fprintf(stderr,"KEY_LEFT\n");}
112 if((keysd&KEY_RIGHT)) {ax=0;h=10;SDL_PrivateJoystickAxis(joystick,ax,h);prevkey=KEY_RIGHT;}//fprintf(stderr,"KEY_RIGHT\n");}
113
114 if((keysu&KEY_UP)) {ax=1;v=0;SDL_PrivateJoystickAxis(joystick,ax,v);prevkey=0;}//fprintf(stderr,"KEY_UP\n");}
115 if((keysu&KEY_DOWN)) {ax=1;v=0;SDL_PrivateJoystickAxis(joystick,ax,v);prevkey=0;}//fprintf(stderr,"KEY_DOWN\n");}
116 if((keysu&KEY_LEFT)) {ax=0;h=0;SDL_PrivateJoystickAxis(joystick,ax,h);prevkey=0;}//fprintf(stderr,"KEY_LEFT\n");}
117 if((keysu&KEY_RIGHT)) {ax=0;h=0;SDL_PrivateJoystickAxis(joystick,ax,h);prevkey=0;}//fprintf(stderr,"KEY_RIGHT\n");}
118
119 if((keysd&KEY_A)) {SDL_PrivateJoystickButton(joystick,0,SDL_PRESSED);prevbutton=KEY_A;}
120 if((keysd&KEY_B)) {SDL_PrivateJoystickButton(joystick,1,SDL_PRESSED);prevbutton=KEY_B;}
121 if((keysd&KEY_X)) {SDL_PrivateJoystickButton(joystick,2,SDL_PRESSED);prevbutton=KEY_X;}
122 if((keysd&KEY_Y)) {SDL_PrivateJoystickButton(joystick,3,SDL_PRESSED);prevbutton=KEY_Y;}
123 if((keysd&KEY_SELECT)) {SDL_PrivateJoystickButton(joystick,6,SDL_PRESSED);prevbutton=KEY_SELECT;}
124 if((keysd&KEY_START)) {SDL_PrivateJoystickButton(joystick,7,SDL_PRESSED);prevbutton=KEY_START;}
125 if((keysd&KEY_L)) {SDL_PrivateJoystickButton(joystick,4,SDL_PRESSED);prevbutton=KEY_L;}
126 if((keysd&KEY_R)) {SDL_PrivateJoystickButton(joystick,5,SDL_PRESSED);prevbutton=KEY_R;}
127
128 if((keysu&KEY_A)) {SDL_PrivateJoystickButton(joystick,0,SDL_RELEASED);prevbutton=0;}
129 if((keysu&KEY_B)) {SDL_PrivateJoystickButton(joystick,1,SDL_RELEASED);prevbutton=0;}
130 if((keysu&KEY_X)) {SDL_PrivateJoystickButton(joystick,2,SDL_RELEASED);prevbutton=0;}
131 if((keysu&KEY_Y)) {SDL_PrivateJoystickButton(joystick,3,SDL_RELEASED);prevbutton=0;}
132 if((keysu&KEY_SELECT)) {SDL_PrivateJoystickButton(joystick,6,SDL_RELEASED);prevbutton=0;}
133 if((keysu&KEY_START)) {SDL_PrivateJoystickButton(joystick,7,SDL_RELEASED);prevbutton=0;}
134 if((keysu&KEY_L)) {SDL_PrivateJoystickButton(joystick,4,SDL_RELEASED);prevbutton=0;}
135 if((keysu&KEY_R)) {SDL_PrivateJoystickButton(joystick,5,SDL_RELEASED);prevbutton=0;}
136
137
138
139}
140
141/* Function to close a joystick after use */
142void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
143{
144}
145
146/* Function to perform any system-specific joystick related cleanup */
147void SDL_SYS_JoystickQuit(void)
148{
149}
150
diff --git a/apps/plugins/sdl/src/joystick/riscos/SDL_sysjoystick.c b/apps/plugins/sdl/src/joystick/riscos/SDL_sysjoystick.c
deleted file mode 100644
index 214d4c7474..0000000000
--- a/apps/plugins/sdl/src/joystick/riscos/SDL_sysjoystick.c
+++ /dev/null
@@ -1,176 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_JOYSTICK_RISCOS
25
26/*
27 RISC OS - Joystick support by Alan Buckley (alan_baa@hotmail.com) - 10 April 2003
28
29 Note: Currently assumes joystick is present if joystick module is loaded
30 and that there is one joystick with four buttons.
31*/
32
33/* This is the system specific header for the SDL joystick API */
34
35#include "SDL_events.h"
36#include "SDL_joystick.h"
37#include "../SDL_sysjoystick.h"
38#include "../SDL_joystick_c.h"
39
40#include "kernel.h"
41
42#define JOYSTICK_READ 0x43F40
43
44struct joystick_hwdata
45{
46 int joystate;
47};
48
49
50/* Function to scan the system for joysticks.
51 * This function should set SDL_numjoysticks to the number of available
52 * joysticks. Joystick 0 should be the system default joystick.
53 * It should return number of joysticks, or -1 on an unrecoverable fatal error.
54 */
55int SDL_SYS_JoystickInit(void)
56{
57 _kernel_swi_regs regs;
58
59 /* Try to read joystick 0 */
60 regs.r[0] = 0;
61 if (_kernel_swi(JOYSTICK_READ, &regs, &regs) == NULL)
62 {
63 /* Switch works so assume we've got a joystick */
64 return 1;
65 }
66 /* Switch fails so it looks like there's no joystick here */
67
68 return(0);
69}
70
71/* Function to get the device-dependent name of a joystick */
72const char *SDL_SYS_JoystickName(int index)
73{
74 if (index == 0)
75 {
76 return "RISC OS Joystick 0";
77 }
78
79 SDL_SetError("No joystick available with that index");
80 return(NULL);
81}
82
83/* Function to open a joystick for use.
84 The joystick to open is specified by the index field of the joystick.
85 This should fill the nbuttons and naxes fields of the joystick structure.
86 It returns 0, or -1 if there is an error.
87 */
88int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
89{
90 _kernel_swi_regs regs;
91
92 if(!(joystick->hwdata=SDL_malloc(sizeof(struct joystick_hwdata))))
93 return -1;
94
95 regs.r[0] = joystick->index;
96
97 /* Don't know how to get exact count of buttons so assume max of 4 for now */
98 joystick->nbuttons=4;
99
100 joystick->nhats=0;
101 joystick->nballs=0;
102 joystick->naxes=2;
103 joystick->hwdata->joystate=0;
104
105 return 0;
106
107}
108
109/* Function to update the state of a joystick - called as a device poll.
110 * This function shouldn't update the joystick structure directly,
111 * but instead should call SDL_PrivateJoystick*() to deliver events
112 * and update joystick device state.
113 */
114void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
115{
116 _kernel_swi_regs regs;
117 regs.r[0] = joystick->index;
118
119 if (_kernel_swi(JOYSTICK_READ, &regs, &regs) == NULL)
120 {
121 int newstate = regs.r[0];
122 int oldstate = joystick->hwdata->joystate;
123 if (newstate != oldstate)
124 {
125 if ((newstate & 0xFF) != (oldstate & 0xFF))
126 {
127 int y = regs.r[0] & 0xFF;
128 /* Convert to signed values */
129 if (y >= 128) y -= 256;
130 SDL_PrivateJoystickAxis(joystick,1,-y * 256); /* Up and down opposite to result in SDL */
131 }
132 if ((newstate & 0xFF00) != (oldstate & 0xFF00))
133 {
134 int x = (regs.r[0] & 0xFF00) >> 8;
135 if (x >= 128) x -= 256;
136 SDL_PrivateJoystickAxis(joystick,0,x * 256);
137 }
138
139 if ((newstate & 0xFF0000) != (oldstate & 0xFF0000))
140 {
141 int buttons = (regs.r[0] & 0xFF0000) >> 16;
142 int oldbuttons = (oldstate & 0xFF0000) >> 16;
143 int i;
144 for (i = 0; i < joystick->nbuttons; i++)
145 {
146 if ((buttons & (1<<i)) != (oldbuttons & (1<<i)))
147 {
148 if (buttons & (1<<i)) SDL_PrivateJoystickButton(joystick,i,SDL_PRESSED);
149 else SDL_PrivateJoystickButton(joystick,i,SDL_RELEASED);
150 }
151 }
152 }
153 joystick->hwdata->joystate = newstate;
154 }
155 }
156
157 return;
158}
159
160/* Function to close a joystick after use */
161void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
162{
163 if(joystick->hwdata)
164 SDL_free(joystick->hwdata);
165 return;
166}
167
168/* Function to perform any system-specific joystick related cleanup */
169void SDL_SYS_JoystickQuit(void)
170{
171 SDL_numjoysticks=0;
172
173 return;
174}
175
176#endif /* SDL_JOYSTICK_RISCOS */
diff --git a/apps/plugins/sdl/src/joystick/win32/SDL_mmjoystick.c b/apps/plugins/sdl/src/joystick/win32/SDL_mmjoystick.c
deleted file mode 100644
index 8c53f9e3dd..0000000000
--- a/apps/plugins/sdl/src/joystick/win32/SDL_mmjoystick.c
+++ /dev/null
@@ -1,407 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_JOYSTICK_WINMM
25
26/* Win32 MultiMedia Joystick driver, contributed by Andrei de A. Formiga */
27
28#define WIN32_LEAN_AND_MEAN
29#include <windows.h>
30#include <mmsystem.h>
31#include <regstr.h>
32
33#include "SDL_events.h"
34#include "SDL_joystick.h"
35#include "../SDL_sysjoystick.h"
36#include "../SDL_joystick_c.h"
37
38#define MAX_JOYSTICKS 16
39#define MAX_AXES 6 /* each joystick can have up to 6 axes */
40#define MAX_BUTTONS 32 /* and 32 buttons */
41#define AXIS_MIN -32768 /* minimum value for axis coordinate */
42#define AXIS_MAX 32767 /* maximum value for axis coordinate */
43/* limit axis to 256 possible positions to filter out noise */
44#define JOY_AXIS_THRESHOLD (((AXIS_MAX)-(AXIS_MIN))/256)
45#define JOY_BUTTON_FLAG(n) (1<<n)
46
47
48/* array to hold joystick ID values */
49static UINT SYS_JoystickID[MAX_JOYSTICKS];
50static JOYCAPS SYS_Joystick[MAX_JOYSTICKS];
51static char *SYS_JoystickName[MAX_JOYSTICKS];
52
53/* The private structure used to keep track of a joystick */
54struct joystick_hwdata
55{
56 /* joystick ID */
57 UINT id;
58
59 /* values used to translate device-specific coordinates into
60 SDL-standard ranges */
61 struct _transaxis {
62 int offset;
63 float scale;
64 } transaxis[6];
65};
66
67/* Convert a win32 Multimedia API return code to a text message */
68static void SetMMerror(char *function, int code);
69
70
71static char *GetJoystickName(int index, const char *szRegKey)
72{
73 /* added 7/24/2004 by Eckhard Stolberg */
74 /*
75 see if there is a joystick for the current
76 index (1-16) listed in the registry
77 */
78 char *name = NULL;
79 HKEY hTopKey;
80 HKEY hKey;
81 DWORD regsize;
82 LONG regresult;
83 char regkey[256];
84 char regvalue[256];
85 char regname[256];
86
87 SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s\\%s",
88 REGSTR_PATH_JOYCONFIG, szRegKey, REGSTR_KEY_JOYCURR);
89 hTopKey = HKEY_LOCAL_MACHINE;
90 regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
91 if (regresult != ERROR_SUCCESS) {
92 hTopKey = HKEY_CURRENT_USER;
93 regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
94 }
95 if (regresult != ERROR_SUCCESS) {
96 return NULL;
97 }
98
99 /* find the registry key name for the joystick's properties */
100 regsize = sizeof(regname);
101 SDL_snprintf(regvalue, SDL_arraysize(regvalue), "Joystick%d%s", index+1, REGSTR_VAL_JOYOEMNAME);
102 regresult = RegQueryValueExA(hKey, regvalue, 0, 0, (LPBYTE)regname, &regsize);
103 RegCloseKey(hKey);
104
105 if (regresult != ERROR_SUCCESS) {
106 return NULL;
107 }
108
109 /* open that registry key */
110 SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s", REGSTR_PATH_JOYOEM, regname);
111 regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
112 if (regresult != ERROR_SUCCESS) {
113 return NULL;
114 }
115
116 /* find the size for the OEM name text */
117 regsize = sizeof(regvalue);
118 regresult = RegQueryValueExA(hKey, REGSTR_VAL_JOYOEMNAME, 0, 0, NULL, &regsize);
119 if (regresult == ERROR_SUCCESS) {
120 /* allocate enough memory for the OEM name text ... */
121 name = (char *) SDL_malloc(regsize);
122 if ( name ) {
123 /* ... and read it from the registry */
124 regresult = RegQueryValueExA(hKey,
125 REGSTR_VAL_JOYOEMNAME, 0, 0,
126 (LPBYTE) name, &regsize);
127 }
128 }
129 RegCloseKey(hKey);
130
131 return(name);
132}
133
134/* Function to scan the system for joysticks.
135 * This function should set SDL_numjoysticks to the number of available
136 * joysticks. Joystick 0 should be the system default joystick.
137 * It should return 0, or -1 on an unrecoverable fatal error.
138 */
139int SDL_SYS_JoystickInit(void)
140{
141 int i;
142 int maxdevs;
143 int numdevs;
144 JOYINFOEX joyinfo;
145 JOYCAPS joycaps;
146 MMRESULT result;
147
148 /* Reset the joystick ID & name mapping tables */
149 for ( i = 0; i < MAX_JOYSTICKS; ++i ) {
150 SYS_JoystickID[i] = 0;
151 SYS_JoystickName[i] = NULL;
152 }
153
154 /* Loop over all potential joystick devices */
155 numdevs = 0;
156 maxdevs = joyGetNumDevs();
157 for ( i = JOYSTICKID1; i < maxdevs && numdevs < MAX_JOYSTICKS; ++i ) {
158
159 joyinfo.dwSize = sizeof(joyinfo);
160 joyinfo.dwFlags = JOY_RETURNALL;
161 result = joyGetPosEx(i, &joyinfo);
162 if ( result == JOYERR_NOERROR ) {
163 result = joyGetDevCaps(i, &joycaps, sizeof(joycaps));
164 if ( result == JOYERR_NOERROR ) {
165 SYS_JoystickID[numdevs] = i;
166 SYS_Joystick[numdevs] = joycaps;
167 SYS_JoystickName[numdevs] = GetJoystickName(i, joycaps.szRegKey);
168 numdevs++;
169 }
170 }
171 }
172 return(numdevs);
173}
174
175/* Function to get the device-dependent name of a joystick */
176const char *SDL_SYS_JoystickName(int index)
177{
178 if ( SYS_JoystickName[index] != NULL ) {
179 return(SYS_JoystickName[index]);
180 } else {
181 return(SYS_Joystick[index].szPname);
182 }
183}
184
185/* Function to open a joystick for use.
186 The joystick to open is specified by the index field of the joystick.
187 This should fill the nbuttons and naxes fields of the joystick structure.
188 It returns 0, or -1 if there is an error.
189 */
190int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
191{
192 int index, i;
193 int caps_flags[MAX_AXES-2] =
194 { JOYCAPS_HASZ, JOYCAPS_HASR, JOYCAPS_HASU, JOYCAPS_HASV };
195 int axis_min[MAX_AXES], axis_max[MAX_AXES];
196
197
198 /* shortcut */
199 index = joystick->index;
200 axis_min[0] = SYS_Joystick[index].wXmin;
201 axis_max[0] = SYS_Joystick[index].wXmax;
202 axis_min[1] = SYS_Joystick[index].wYmin;
203 axis_max[1] = SYS_Joystick[index].wYmax;
204 axis_min[2] = SYS_Joystick[index].wZmin;
205 axis_max[2] = SYS_Joystick[index].wZmax;
206 axis_min[3] = SYS_Joystick[index].wRmin;
207 axis_max[3] = SYS_Joystick[index].wRmax;
208 axis_min[4] = SYS_Joystick[index].wUmin;
209 axis_max[4] = SYS_Joystick[index].wUmax;
210 axis_min[5] = SYS_Joystick[index].wVmin;
211 axis_max[5] = SYS_Joystick[index].wVmax;
212
213 /* allocate memory for system specific hardware data */
214 joystick->hwdata = (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata));
215 if (joystick->hwdata == NULL)
216 {
217 SDL_OutOfMemory();
218 return(-1);
219 }
220 SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata));
221
222 /* set hardware data */
223 joystick->hwdata->id = SYS_JoystickID[index];
224 for ( i = 0; i < MAX_AXES; ++i ) {
225 if ( (i<2) || (SYS_Joystick[index].wCaps & caps_flags[i-2]) ) {
226 joystick->hwdata->transaxis[i].offset =
227 AXIS_MIN - axis_min[i];
228 joystick->hwdata->transaxis[i].scale =
229 (float)(AXIS_MAX - AXIS_MIN) / (axis_max[i] - axis_min[i]);
230 } else {
231 joystick->hwdata->transaxis[i].offset = 0;
232 joystick->hwdata->transaxis[i].scale = 1.0; /* Just in case */
233 }
234 }
235
236 /* fill nbuttons, naxes, and nhats fields */
237 joystick->nbuttons = SYS_Joystick[index].wNumButtons;
238 joystick->naxes = SYS_Joystick[index].wNumAxes;
239 if ( SYS_Joystick[index].wCaps & JOYCAPS_HASPOV ) {
240 joystick->nhats = 1;
241 } else {
242 joystick->nhats = 0;
243 }
244 return(0);
245}
246
247static Uint8 TranslatePOV(DWORD value)
248{
249 Uint8 pos;
250
251 pos = SDL_HAT_CENTERED;
252 if ( value != JOY_POVCENTERED ) {
253 if ( (value > JOY_POVLEFT) || (value < JOY_POVRIGHT) ) {
254 pos |= SDL_HAT_UP;
255 }
256 if ( (value > JOY_POVFORWARD) && (value < JOY_POVBACKWARD) ) {
257 pos |= SDL_HAT_RIGHT;
258 }
259 if ( (value > JOY_POVRIGHT) && (value < JOY_POVLEFT) ) {
260 pos |= SDL_HAT_DOWN;
261 }
262 if ( value > JOY_POVBACKWARD ) {
263 pos |= SDL_HAT_LEFT;
264 }
265 }
266 return(pos);
267}
268
269/* Function to update the state of a joystick - called as a device poll.
270 * This function shouldn't update the joystick structure directly,
271 * but instead should call SDL_PrivateJoystick*() to deliver events
272 * and update joystick device state.
273 */
274void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
275{
276 MMRESULT result;
277 int i;
278 DWORD flags[MAX_AXES] = { JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ,
279 JOY_RETURNR, JOY_RETURNU, JOY_RETURNV };
280 DWORD pos[MAX_AXES];
281 struct _transaxis *transaxis;
282 int value, change;
283 JOYINFOEX joyinfo;
284
285 joyinfo.dwSize = sizeof(joyinfo);
286 joyinfo.dwFlags = JOY_RETURNALL|JOY_RETURNPOVCTS;
287 if ( ! joystick->hats ) {
288 joyinfo.dwFlags &= ~(JOY_RETURNPOV|JOY_RETURNPOVCTS);
289 }
290 result = joyGetPosEx(joystick->hwdata->id, &joyinfo);
291 if ( result != JOYERR_NOERROR ) {
292 SetMMerror("joyGetPosEx", result);
293 return;
294 }
295
296 /* joystick motion events */
297 pos[0] = joyinfo.dwXpos;
298 pos[1] = joyinfo.dwYpos;
299 pos[2] = joyinfo.dwZpos;
300 pos[3] = joyinfo.dwRpos;
301 pos[4] = joyinfo.dwUpos;
302 pos[5] = joyinfo.dwVpos;
303
304 transaxis = joystick->hwdata->transaxis;
305 for (i = 0; i < joystick->naxes; i++) {
306 if (joyinfo.dwFlags & flags[i]) {
307 value = (int)(((float)pos[i] + transaxis[i].offset) * transaxis[i].scale);
308 change = (value - joystick->axes[i]);
309 if ( (change < -JOY_AXIS_THRESHOLD) || (change > JOY_AXIS_THRESHOLD) ) {
310 SDL_PrivateJoystickAxis(joystick, (Uint8)i, (Sint16)value);
311 }
312 }
313 }
314
315 /* joystick button events */
316 if ( joyinfo.dwFlags & JOY_RETURNBUTTONS ) {
317 for ( i = 0; i < joystick->nbuttons; ++i ) {
318 if ( joyinfo.dwButtons & JOY_BUTTON_FLAG(i) ) {
319 if ( ! joystick->buttons[i] ) {
320 SDL_PrivateJoystickButton(joystick, (Uint8)i, SDL_PRESSED);
321 }
322 } else {
323 if ( joystick->buttons[i] ) {
324 SDL_PrivateJoystickButton(joystick, (Uint8)i, SDL_RELEASED);
325 }
326 }
327 }
328 }
329
330 /* joystick hat events */
331 if ( joyinfo.dwFlags & JOY_RETURNPOV ) {
332 Uint8 pos;
333
334 pos = TranslatePOV(joyinfo.dwPOV);
335 if ( pos != joystick->hats[0] ) {
336 SDL_PrivateJoystickHat(joystick, 0, pos);
337 }
338 }
339}
340
341/* Function to close a joystick after use */
342void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
343{
344 if (joystick->hwdata != NULL) {
345 /* free system specific hardware data */
346 SDL_free(joystick->hwdata);
347 joystick->hwdata = NULL;
348 }
349}
350
351/* Function to perform any system-specific joystick related cleanup */
352void SDL_SYS_JoystickQuit(void)
353{
354 int i;
355 for (i = 0; i < MAX_JOYSTICKS; i++) {
356 if ( SYS_JoystickName[i] != NULL ) {
357 SDL_free(SYS_JoystickName[i]);
358 SYS_JoystickName[i] = NULL;
359 }
360 }
361}
362
363
364/* implementation functions */
365void SetMMerror(char *function, int code)
366{
367 static char *error;
368 static char errbuf[1024];
369
370 errbuf[0] = 0;
371 switch (code)
372 {
373 case MMSYSERR_NODRIVER:
374 error = "Joystick driver not present";
375 break;
376
377 case MMSYSERR_INVALPARAM:
378 case JOYERR_PARMS:
379 error = "Invalid parameter(s)";
380 break;
381
382 case MMSYSERR_BADDEVICEID:
383 error = "Bad device ID";
384 break;
385
386 case JOYERR_UNPLUGGED:
387 error = "Joystick not attached";
388 break;
389
390 case JOYERR_NOCANDO:
391 error = "Can't capture joystick input";
392 break;
393
394 default:
395 SDL_snprintf(errbuf, SDL_arraysize(errbuf),
396 "%s: Unknown Multimedia system error: 0x%x",
397 function, code);
398 break;
399 }
400
401 if ( ! errbuf[0] ) {
402 SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error);
403 }
404 SDL_SetError("%s", errbuf);
405}
406
407#endif /* SDL_JOYSTICK_WINMM */
diff --git a/apps/plugins/sdl/src/loadso/beos/SDL_sysloadso.c b/apps/plugins/sdl/src/loadso/beos/SDL_sysloadso.c
deleted file mode 100644
index 28267b72b3..0000000000
--- a/apps/plugins/sdl/src/loadso/beos/SDL_sysloadso.c
+++ /dev/null
@@ -1,72 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_LOADSO_BEOS
25
26/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
27/* System dependent library loading routines */
28
29#include <stdio.h>
30#include <be/kernel/image.h>
31
32#include "SDL_loadso.h"
33
34void *
35SDL_LoadObject(const char *sofile)
36{
37 void *handle = NULL;
38 image_id library_id = load_add_on(sofile);
39 if (library_id < 0) {
40 SDL_SetError(strerror((int) library_id));
41 } else {
42 handle = (void *) (library_id);
43 }
44 return (handle);
45}
46
47void *
48SDL_LoadFunction(void *handle, const char *name)
49{
50 void *sym = NULL;
51 image_id library_id = (image_id) handle;
52 status_t rc = get_image_symbol(library_id, name, B_SYMBOL_TYPE_TEXT, &sym);
53 if (rc != B_NO_ERROR) {
54 SDL_SetError(strerror(rc));
55 }
56 return (sym);
57}
58
59void
60SDL_UnloadObject(void *handle)
61{
62 image_id library_id;
63 if (handle != NULL) {
64 library_id = (image_id) handle;
65 unload_add_on(library_id);
66 }
67}
68
69#endif /* SDL_LOADSO_BEOS */
70
71/* vi: set ts=4 sw=4 expandtab: */
72
diff --git a/apps/plugins/sdl/src/loadso/dlopen/SDL_sysloadso.c b/apps/plugins/sdl/src/loadso/dlopen/SDL_sysloadso.c
deleted file mode 100644
index 7985ee7f9d..0000000000
--- a/apps/plugins/sdl/src/loadso/dlopen/SDL_sysloadso.c
+++ /dev/null
@@ -1,69 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_LOADSO_DLOPEN
25
26/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
27/* System dependent library loading routines */
28
29#include <stdio.h>
30#include <dlfcn.h>
31
32#include "SDL_loadso.h"
33
34void *SDL_LoadObject(const char *sofile)
35{
36 void *handle = dlopen(sofile, RTLD_NOW);
37 const char *loaderror = (char *)dlerror();
38 if ( handle == NULL ) {
39 SDL_SetError("Failed loading %s: %s", sofile, loaderror);
40 }
41 return(handle);
42}
43
44void *SDL_LoadFunction(void *handle, const char *name)
45{
46 void *symbol = dlsym(handle, name);
47 if ( symbol == NULL ) {
48 /* append an underscore for platforms that need that. */
49 size_t len = 1+SDL_strlen(name)+1;
50 char *_name = SDL_stack_alloc(char, len);
51 _name[0] = '_';
52 SDL_strlcpy(&_name[1], name, len);
53 symbol = dlsym(handle, _name);
54 SDL_stack_free(_name);
55 if ( symbol == NULL ) {
56 SDL_SetError("Failed loading %s: %s", name, (const char *)dlerror());
57 }
58 }
59 return(symbol);
60}
61
62void SDL_UnloadObject(void *handle)
63{
64 if ( handle != NULL ) {
65 dlclose(handle);
66 }
67}
68
69#endif /* SDL_LOADSO_DLOPEN */
diff --git a/apps/plugins/sdl/src/loadso/macos/SDL_sysloadso.c b/apps/plugins/sdl/src/loadso/macos/SDL_sysloadso.c
deleted file mode 100644
index c035b1786c..0000000000
--- a/apps/plugins/sdl/src/loadso/macos/SDL_sysloadso.c
+++ /dev/null
@@ -1,106 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_LOADSO_MACOS
25
26/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
27/* System dependent library loading routines */
28
29#include <stdio.h>
30#include <string.h>
31#define OLDP2C 1
32#include <Strings.h>
33#include <CodeFragments.h>
34#include <Errors.h>
35
36#include "SDL_loadso.h"
37
38void *SDL_LoadObject(const char *sofile)
39{
40 void *handle = NULL;
41 const char *loaderror = NULL;
42 CFragConnectionID library_id;
43 Ptr mainAddr;
44 Str255 errName;
45 OSErr error;
46 char psofile[512];
47
48 SDL_strlcpy(psofile, sofile, SDL_arraysize(psofile));
49 error = GetSharedLibrary(C2PStr(psofile), kCompiledCFragArch,
50 kLoadCFrag, &library_id, &mainAddr, errName);
51 switch (error) {
52 case noErr:
53 loaderror = NULL;
54 break;
55 case cfragNoLibraryErr:
56 loaderror = "Library not found";
57 break;
58 case cfragUnresolvedErr:
59 loaderror = "Unabled to resolve symbols";
60 break;
61 case cfragNoPrivateMemErr:
62 case cfragNoClientMemErr:
63 loaderror = "Out of memory";
64 break;
65 default:
66 loaderror = "Unknown Code Fragment Manager error";
67 break;
68 }
69 if ( loaderror == NULL ) {
70 handle = (void *)(library_id);
71 } else {
72 SDL_SetError("Failed loading %s: %s", sofile, loaderror);
73 }
74 return(handle);
75}
76
77void *SDL_LoadFunction(void *handle, const char *name)
78{
79 void *symbol = NULL;
80 const char *loaderror = NULL;
81 CFragSymbolClass class;
82 CFragConnectionID library_id = (CFragConnectionID)handle;
83 char pname[512];
84
85 SDL_strlcpy(pname, name, SDL_arraysize(pname));
86 if ( FindSymbol(library_id, C2PStr(pname),
87 (char **)&symbol, &class) != noErr ) {
88 loaderror = "Symbol not found";
89 }
90
91 if ( symbol == NULL ) {
92 SDL_SetError("Failed loading %s: %s", name, loaderror);
93 }
94 return(symbol);
95}
96
97void SDL_UnloadObject(void *handle)
98{
99 CFragConnectionID library_id;
100 if ( handle != NULL ) {
101 library_id = (CFragConnectionID)handle;
102 CloseConnection(&library_id);
103 }
104}
105
106#endif /* SDL_LOADSO_MACOS */
diff --git a/apps/plugins/sdl/src/loadso/macosx/SDL_dlcompat.c b/apps/plugins/sdl/src/loadso/macosx/SDL_dlcompat.c
deleted file mode 100644
index 091947f2dc..0000000000
--- a/apps/plugins/sdl/src/loadso/macosx/SDL_dlcompat.c
+++ /dev/null
@@ -1,1407 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_LOADSO_DLCOMPAT
25
26/* Please note that dlcompat apparently ships in current Mac OS X versions
27 * as a system library that provides compatibility with the Unix "dlopen"
28 * interface. In order to allow SDL to work on older OS X releases and also
29 * not conflict with the system lib on newer versions, we include dlcompat
30 * in SDL and change the symbols to prevent symbol clash with any existing
31 * system libraries. --ryan.
32 */
33
34/* here is the dlcompat license: */
35
36/*
37Copyright (c) 2002 Jorge Acereda <jacereda@users.sourceforge.net> &
38 Peter O'Gorman <ogorman@users.sourceforge.net>
39
40Portions may be copyright others, see the AUTHORS file included with this
41distribution.
42
43Maintained by Peter O'Gorman <ogorman@users.sourceforge.net>
44
45Bug Reports and other queries should go to <ogorman@users.sourceforge.net>
46
47Permission is hereby granted, free of charge, to any person obtaining
48a copy of this software and associated documentation files (the
49"Software"), to deal in the Software without restriction, including
50without limitation the rights to use, copy, modify, merge, publish,
51distribute, sublicense, and/or sell copies of the Software, and to
52permit persons to whom the Software is furnished to do so, subject to
53the following conditions:
54
55The above copyright notice and this permission notice shall be
56included in all copies or substantial portions of the Software.
57
58THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
59EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
60MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
61NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
62LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
63OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
64WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
65*/
66
67#include <pthread.h>
68#include <sys/types.h>
69#include <sys/stat.h>
70#include <stdarg.h>
71#include <limits.h>
72#include <mach-o/dyld.h>
73#include <mach-o/nlist.h>
74#include <mach-o/getsect.h>
75
76#include "SDL_stdinc.h"
77
78/* Just playing to see if it would compile with the freebsd headers, it does,
79 * but because of the different values for RTLD_LOCAL etc, it would break binary
80 * compat... oh well
81 */
82#ifndef __BSD_VISIBLE
83#define __BSD_VISIBLE 1
84#endif
85
86/*include "dlfcn.h"*/
87#ifdef __cplusplus
88extern "C" {
89#endif
90
91#if defined (__GNUC__) && __GNUC__ > 3
92#define dl_restrict __restrict
93#else
94#define dl_restrict
95#endif
96
97#if 0
98#ifndef _POSIX_SOURCE
99/*
100 * Structure filled in by dladdr().
101 */
102typedef struct SDL_OSX_dl_info {
103 const char *dli_fname; /* Pathname of shared object */
104 void *dli_fbase; /* Base address of shared object */
105 const char *dli_sname; /* Name of nearest symbol */
106 void *dli_saddr; /* Address of nearest symbol */
107} SDL_OSX_Dl_info;
108
109static int SDL_OSX_dladdr(const void * dl_restrict, SDL_OSX_Dl_info * dl_restrict);
110#endif /* ! _POSIX_SOURCE */
111#endif /* 0 */
112
113static int SDL_OSX_dlclose(void * handle);
114static const char * SDL_OSX_dlerror(void);
115static void * SDL_OSX_dlopen(const char *path, int mode);
116static void * SDL_OSX_dlsym(void * dl_restrict handle, const char * dl_restrict symbol);
117
118#define RTLD_LAZY 0x1
119#define RTLD_NOW 0x2
120#define RTLD_LOCAL 0x4
121#define RTLD_GLOBAL 0x8
122
123#ifndef _POSIX_SOURCE
124#define RTLD_NOLOAD 0x10
125#define RTLD_NODELETE 0x80
126
127/*
128 * Special handle arguments for SDL_OSX_dlsym().
129 */
130#define RTLD_NEXT ((void *) -1) /* Search subsequent objects. */
131#define RTLD_DEFAULT ((void *) -2) /* Use default search algorithm. */
132#endif /* ! _POSIX_SOURCE */
133
134#ifdef __cplusplus
135}
136#endif
137
138#ifndef dl_restrict
139#define dl_restrict __restrict
140#endif
141/* This is not available on 10.1 */
142#ifndef LC_LOAD_WEAK_DYLIB
143#define LC_LOAD_WEAK_DYLIB (0x18 | LC_REQ_DYLD)
144#endif
145
146/* With this stuff here, this thing may actually compile/run on 10.0 systems
147 * Not that I have a 10.0 system to test it on anylonger
148 */
149#ifndef LC_REQ_DYLD
150#define LC_REQ_DYLD 0x80000000
151#endif
152#ifndef NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
153#define NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED 0x4
154#endif
155#ifndef NSADDIMAGE_OPTION_RETURN_ON_ERROR
156#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
157#endif
158#ifndef NSLOOKUPSYMBOLINIMAGE_OPTION_BIND
159#define NSLOOKUPSYMBOLINIMAGE_OPTION_BIND 0x0
160#endif
161#ifndef NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
162#define NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR 0x4
163#endif
164/* These symbols will be looked for in dyld */
165static const struct mach_header *(*dyld_NSAddImage) (const char *, unsigned long) = 0;
166static int (*dyld_NSIsSymbolNameDefinedInImage) (const struct mach_header *, const char *) = 0;
167static NSSymbol(*dyld_NSLookupSymbolInImage)
168 (const struct mach_header *, const char *, unsigned long) = 0;
169
170/* Define this to make dlcompat reuse data block. This way in theory we save
171 * a little bit of overhead. However we then couldn't correctly catch excess
172 * calls to SDL_OSX_dlclose(). Hence we don't use this feature
173 */
174#undef REUSE_STATUS
175
176/* Size of the internal error message buffer (used by dlerror()) */
177#define ERR_STR_LEN 251
178
179/* Maximum number of search paths supported by getSearchPath */
180#define MAX_SEARCH_PATHS 32
181
182
183#define MAGIC_DYLIB_OFI ((NSObjectFileImage) 'DYOF')
184#define MAGIC_DYLIB_MOD ((NSModule) 'DYMO')
185
186/* internal flags */
187#define DL_IN_LIST 0x01
188
189/* our mutex */
190static pthread_mutex_t dlcompat_mutex;
191/* Our thread specific storage
192 */
193static pthread_key_t dlerror_key;
194
195struct dlthread
196{
197 int lockcnt;
198 unsigned char errset;
199 char errstr[ERR_STR_LEN];
200};
201
202/* This is our central data structure. Whenever a module is loaded via
203 * SDL_OSX_dlopen(), we create such a struct.
204 */
205struct dlstatus
206{
207 struct dlstatus *next; /* pointer to next element in the linked list */
208 NSModule module;
209 const struct mach_header *lib;
210 int refs; /* reference count */
211 int mode; /* mode in which this module was loaded */
212 dev_t device;
213 ino_t inode;
214 int flags; /* Any internal flags we may need */
215};
216
217/* Head node of the dlstatus list */
218static struct dlstatus mainStatus = { 0, MAGIC_DYLIB_MOD, NULL, -1, RTLD_GLOBAL, 0, 0, 0 };
219static struct dlstatus *stqueue = &mainStatus;
220
221
222/* Storage for the last error message (used by dlerror()) */
223/* static char err_str[ERR_STR_LEN]; */
224/* static int err_filled = 0; */
225
226/* Prototypes to internal functions */
227static void debug(const char *fmt, ...);
228static void error(const char *str, ...);
229static const char *safegetenv(const char *s);
230static const char *searchList(void);
231static const char *getSearchPath(int i);
232static const char *getFullPath(int i, const char *file);
233static const struct stat *findFile(const char *file, const char **fullPath);
234static int isValidStatus(struct dlstatus *status);
235static inline int isFlagSet(int mode, int flag);
236static struct dlstatus *lookupStatus(const struct stat *sbuf);
237static void insertStatus(struct dlstatus *dls, const struct stat *sbuf);
238static int promoteLocalToGlobal(struct dlstatus *dls);
239static void *reference(struct dlstatus *dls, int mode);
240static void *dlsymIntern(struct dlstatus *dls, const char *symbol, int canSetError);
241static struct dlstatus *allocStatus(void);
242static struct dlstatus *loadModule(const char *path, const struct stat *sbuf, int mode);
243static NSSymbol search_linked_libs(const struct mach_header *mh, const char *symbol);
244static const char *get_lib_name(const struct mach_header *mh);
245static const struct mach_header *get_mach_header_from_NSModule(NSModule mod);
246static void dlcompat_init_func(void);
247static inline void dlcompat_init_check(void);
248static inline void dolock(void);
249static inline void dounlock(void);
250static void dlerrorfree(void *data);
251static void resetdlerror(void);
252static const struct mach_header *my_find_image(const char *name);
253static const struct mach_header *image_for_address(const void *address);
254static inline char *dyld_error_str(void);
255
256#if FINK_BUILD
257/* Two Global Functions */
258static void *dlsym_prepend_underscore(void *handle, const char *symbol);
259static void *dlsym_auto_underscore(void *handle, const char *symbol);
260
261/* And their _intern counterparts */
262static void *dlsym_prepend_underscore_intern(void *handle, const char *symbol);
263static void *dlsym_auto_underscore_intern(void *handle, const char *symbol);
264#endif
265
266/* Functions */
267
268static void debug(const char *fmt, ...)
269{
270#if DEBUG > 1
271 va_list arg;
272 va_start(arg, fmt);
273 fprintf(stderr, "DLDEBUG: ");
274 vfprintf(stderr, fmt, arg);
275 fprintf(stderr, "\n");
276 fflush(stderr);
277 va_end(arg);
278#endif
279}
280
281static void error(const char *str, ...)
282{
283 va_list arg;
284 struct dlthread *tss;
285 char * err_str;
286 va_start(arg, str);
287 tss = pthread_getspecific(dlerror_key);
288 err_str = tss->errstr;
289 SDL_strlcpy(err_str, "dlcompat: ", ERR_STR_LEN);
290 vsnprintf(err_str + 10, ERR_STR_LEN - 10, str, arg);
291 va_end(arg);
292 debug("ERROR: %s\n", err_str);
293 tss->errset = 1;
294}
295
296static void warning(const char *str)
297{
298#if DEBUG > 0
299 fprintf(stderr, "WARNING: dlcompat: %s\n", str);
300#endif
301}
302
303static const char *safegetenv(const char *s)
304{
305 const char *ss = SDL_getenv(s);
306 return ss ? ss : "";
307}
308
309/* because this is only used for debugging and error reporting functions, we
310 * don't really care about how elegant it is... it could use the load
311 * commands to find the install name of the library, but...
312 */
313static const char *get_lib_name(const struct mach_header *mh)
314{
315 unsigned long count = _dyld_image_count();
316 unsigned long i;
317 const char *val = NULL;
318 if (mh)
319 {
320 for (i = 0; i < count; i++)
321 {
322 if (mh == _dyld_get_image_header(i))
323 {
324 val = _dyld_get_image_name(i);
325 break;
326 }
327 }
328 }
329 return val;
330}
331
332/* Returns the mach_header for the module bu going through all the loaded images
333 * and finding the one with the same name as the module. There really ought to be
334 * an api for doing this, would be faster, but there isn't one right now
335 */
336static const struct mach_header *get_mach_header_from_NSModule(NSModule mod)
337{
338 const char *mod_name = NSNameOfModule(mod);
339 const struct mach_header *mh = NULL;
340 unsigned long count = _dyld_image_count();
341 unsigned long i;
342 debug("Module name: %s", mod_name);
343 for (i = 0; i < count; i++)
344 {
345 if (!SDL_strcmp(mod_name, _dyld_get_image_name(i)))
346 {
347 mh = _dyld_get_image_header(i);
348 break;
349 }
350 }
351 return mh;
352}
353
354
355/* Compute and return a list of all directories that we should search when
356 * trying to locate a module. We first look at the values of LD_LIBRARY_PATH
357 * and DYLD_LIBRARY_PATH, and then finally fall back to looking into
358 * /usr/lib and /lib. Since both of the environments variables can contain a
359 * list of colon seperated paths, we simply concat them and the two other paths
360 * into one big string, which we then can easily parse.
361 * Splitting this string into the actual path list is done by getSearchPath()
362 */
363static const char *searchList()
364{
365 size_t buf_size;
366 static char *buf=NULL;
367 const char *ldlp = safegetenv("LD_LIBRARY_PATH");
368 const char *dyldlp = safegetenv("DYLD_LIBRARY_PATH");
369 const char *stdpath = SDL_getenv("DYLD_FALLBACK_LIBRARY_PATH");
370 if (!stdpath)
371 stdpath = "/usr/local/lib:/lib:/usr/lib";
372 if (!buf)
373 {
374 buf_size = SDL_strlen(ldlp) + SDL_strlen(dyldlp) + SDL_strlen(stdpath) + 4;
375 buf = SDL_malloc(buf_size);
376 SDL_snprintf(buf, buf_size, "%s%s%s%s%s%c", dyldlp, (dyldlp[0] ? ":" : ""), ldlp, (ldlp[0] ? ":" : ""),
377 stdpath, '\0');
378 }
379 return buf;
380}
381
382/* Returns the ith search path from the list as computed by searchList() */
383static const char *getSearchPath(int i)
384{
385 static const char *list = 0;
386 static char **path = (char **)0;
387 static int end = 0;
388 static int numsize = MAX_SEARCH_PATHS;
389 static char **tmp;
390 /* So we can call SDL_free() in the "destructor" we use i=-1 to return the alloc'd array */
391 if (i == -1)
392 {
393 return (const char*)path;
394 }
395 if (!path)
396 {
397 path = (char **)SDL_calloc(MAX_SEARCH_PATHS, sizeof(char **));
398 }
399 if (!list && !end)
400 list = searchList();
401 if (i >= (numsize))
402 {
403 debug("Increasing size for long PATH");
404 tmp = (char **)SDL_calloc((MAX_SEARCH_PATHS + numsize), sizeof(char **));
405 if (tmp)
406 {
407 SDL_memcpy(tmp, path, sizeof(char **) * numsize);
408 SDL_free(path);
409 path = tmp;
410 numsize += MAX_SEARCH_PATHS;
411 }
412 else
413 {
414 return 0;
415 }
416 }
417
418 while (!path[i] && !end)
419 {
420 path[i] = strsep((char **)&list, ":");
421
422 if (path[i][0] == 0)
423 path[i] = 0;
424 end = (list == 0);
425 }
426 return path[i];
427}
428
429static const char *getFullPath(int i, const char *file)
430{
431 static char buf[PATH_MAX];
432 const char *path = getSearchPath(i);
433 if (path)
434 {
435 SDL_snprintf(buf, PATH_MAX, "%s/%s", path, file);
436 }
437 return path ? buf : 0;
438}
439
440/* Given a file name, try to determine the full path for that file. Starts
441 * its search in the current directory, and then tries all paths in the
442 * search list in the order they are specified there.
443 */
444static const struct stat *findFile(const char *file, const char **fullPath)
445{
446 int i = 0;
447 static struct stat sbuf;
448 char *fileName;
449 debug("finding file %s", file);
450 *fullPath = file;
451 if (0 == stat(file, &sbuf))
452 return &sbuf;
453 if (SDL_strchr(file, '/'))
454 return 0; /* If the path had a / we don't look in env var places */
455 fileName = NULL;
456 if (!fileName)
457 fileName = (char *)file;
458 while ((*fullPath = getFullPath(i++, fileName)))
459 {
460 if (0 == stat(*fullPath, &sbuf))
461 return &sbuf;
462 }
463 ;
464 return 0;
465}
466
467/* Determine whether a given dlstatus is valid or not */
468static int isValidStatus(struct dlstatus *status)
469{
470 /* Walk the list to verify status is contained in it */
471 struct dlstatus *dls = stqueue;
472 while (dls && status != dls)
473 dls = dls->next;
474 if (dls == 0)
475 error("invalid handle");
476 else if ((dls->module == 0) || (dls->refs == 0))
477 error("handle to closed library");
478 else
479 return TRUE;
480 return FALSE;
481}
482
483static inline int isFlagSet(int mode, int flag)
484{
485 return (mode & flag) == flag;
486}
487
488static struct dlstatus *lookupStatus(const struct stat *sbuf)
489{
490 struct dlstatus *dls = stqueue;
491 debug("looking for status");
492 while (dls && ( /* isFlagSet(dls->mode, RTLD_UNSHARED) */ 0
493 || sbuf->st_dev != dls->device || sbuf->st_ino != dls->inode))
494 dls = dls->next;
495 return dls;
496}
497
498static void insertStatus(struct dlstatus *dls, const struct stat *sbuf)
499{
500 debug("inserting status");
501 dls->inode = sbuf->st_ino;
502 dls->device = sbuf->st_dev;
503 dls->refs = 0;
504 dls->mode = 0;
505 if ((dls->flags & DL_IN_LIST) == 0)
506 {
507 dls->next = stqueue;
508 stqueue = dls;
509 dls->flags |= DL_IN_LIST;
510 }
511}
512
513static struct dlstatus *allocStatus()
514{
515 struct dlstatus *dls;
516#ifdef REUSE_STATUS
517 dls = stqueue;
518 while (dls && dls->module)
519 dls = dls->next;
520 if (!dls)
521#endif
522 dls = SDL_calloc(sizeof(*dls),1);
523 return dls;
524}
525
526static int promoteLocalToGlobal(struct dlstatus *dls)
527{
528 static int (*p) (NSModule module) = 0;
529 debug("promoting");
530 if (!p)
531 _dyld_func_lookup("__dyld_NSMakePrivateModulePublic", (void **)&p);
532 return (dls->module == MAGIC_DYLIB_MOD) || (p && p(dls->module));
533}
534
535static void *reference(struct dlstatus *dls, int mode)
536{
537 if (dls)
538 {
539 if (dls->module == MAGIC_DYLIB_MOD && isFlagSet(mode, RTLD_LOCAL))
540 {
541 warning("trying to open a .dylib with RTLD_LOCAL");
542 error("unable to open a .dylib with RTLD_LOCAL");
543 return NULL;
544 }
545 if (isFlagSet(mode, RTLD_GLOBAL) &&
546 !isFlagSet(dls->mode, RTLD_GLOBAL) && !promoteLocalToGlobal(dls))
547 {
548 error("unable to promote local module to global");
549 return NULL;
550 }
551 dls->mode |= mode;
552 dls->refs++;
553 }
554 else
555 debug("reference called with NULL argument");
556
557 return dls;
558}
559
560static const struct mach_header *my_find_image(const char *name)
561{
562 const struct mach_header *mh = 0;
563 const char *id = NULL;
564 int i = _dyld_image_count();
565 int j;
566 mh = (struct mach_header *)
567 dyld_NSAddImage(name, NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED |
568 NSADDIMAGE_OPTION_RETURN_ON_ERROR);
569 if (!mh)
570 {
571 for (j = 0; j < i; j++)
572 {
573 id = _dyld_get_image_name(j);
574 if (!SDL_strcmp(id, name))
575 {
576 mh = _dyld_get_image_header(j);
577 break;
578 }
579 }
580 }
581 return mh;
582}
583
584/*
585 * dyld adds libraries by first adding the directly dependant libraries in link order, and
586 * then adding the dependencies for those libraries, so we should do the same... but we don't
587 * bother adding the extra dependencies, if the symbols are neither in the loaded image nor
588 * any of it's direct dependencies, then it probably isn't there.
589 */
590static NSSymbol search_linked_libs(const struct mach_header * mh, const char *symbol)
591{
592 unsigned int n;
593 struct load_command *lc = 0;
594 struct mach_header *wh;
595 NSSymbol nssym = 0;
596 if (dyld_NSAddImage && dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage)
597 {
598 lc = (struct load_command *)((char *)mh + sizeof(struct mach_header));
599 for (n = 0; n < mh->ncmds; n++, lc = (struct load_command *)((char *)lc + lc->cmdsize))
600 {
601 if ((LC_LOAD_DYLIB == lc->cmd) || (LC_LOAD_WEAK_DYLIB == lc->cmd))
602 {
603 if ((wh = (struct mach_header *)
604 my_find_image((char *)(((struct dylib_command *)lc)->dylib.name.offset +
605 (char *)lc))))
606 {
607 if (dyld_NSIsSymbolNameDefinedInImage(wh, symbol))
608 {
609 nssym = dyld_NSLookupSymbolInImage(wh,
610 symbol,
611 NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
612 NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
613 break;
614 }
615 }
616 }
617 }
618 if ((!nssym) && NSIsSymbolNameDefined(symbol))
619 {
620 /* I've never seen this debug message...*/
621 debug("Symbol \"%s\" is defined but was not found", symbol);
622 }
623 }
624 return nssym;
625}
626
627/* Up to the caller to SDL_free() returned string */
628static inline char *dyld_error_str()
629{
630 NSLinkEditErrors dylder;
631 int dylderno;
632 const char *dylderrstr;
633 const char *dyldfile;
634 char* retStr = NULL;
635 NSLinkEditError(&dylder, &dylderno, &dyldfile, &dylderrstr);
636 if (dylderrstr && *dylderrstr)
637 {
638 retStr = SDL_strdup(dylderrstr);
639 }
640 return retStr;
641}
642
643static void *dlsymIntern(struct dlstatus *dls, const char *symbol, int canSetError)
644{
645 NSSymbol nssym = 0;
646#ifdef __GCC__
647 void *caller = __builtin_return_address(1); /* Be *very* careful about inlining */
648#else
649 void *caller = NULL;
650#endif
651 const struct mach_header *caller_mh = 0;
652 char *savedErrorStr = NULL;
653 resetdlerror();
654#ifndef RTLD_SELF
655#define RTLD_SELF ((void *) -3)
656#endif
657 if (NULL == dls)
658 dls = RTLD_SELF;
659 if ((RTLD_NEXT == dls) || (RTLD_SELF == dls))
660 {
661 if (dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage && caller)
662 {
663 caller_mh = image_for_address(caller);
664 if (RTLD_SELF == dls)
665 {
666 /* FIXME: We should be using the NSModule api, if SELF is an MH_BUNDLE
667 * But it appears to work anyway, and looking at the code in dyld_libfuncs.c
668 * this is acceptable.
669 */
670 if (dyld_NSIsSymbolNameDefinedInImage(caller_mh, symbol))
671 {
672 nssym = dyld_NSLookupSymbolInImage(caller_mh,
673 symbol,
674 NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
675 NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
676 }
677 }
678 if (!nssym)
679 {
680 if (RTLD_SELF == dls)
681 savedErrorStr = dyld_error_str();
682 nssym = search_linked_libs(caller_mh, symbol);
683 }
684 }
685 else
686 {
687 if (canSetError)
688 error("RTLD_SELF and RTLD_NEXT are not supported");
689 return NULL;
690 }
691 }
692 if (!nssym)
693 {
694
695 if (RTLD_DEFAULT == dls)
696 {
697 dls = &mainStatus;
698 }
699 if (!isValidStatus(dls))
700 return NULL;
701
702 if (dls->module != MAGIC_DYLIB_MOD)
703 {
704 nssym = NSLookupSymbolInModule(dls->module, symbol);
705 if (!nssym && NSIsSymbolNameDefined(symbol))
706 {
707 debug("Searching dependencies");
708 savedErrorStr = dyld_error_str();
709 nssym = search_linked_libs(get_mach_header_from_NSModule(dls->module), symbol);
710 }
711 }
712 else if (dls->lib && dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage)
713 {
714 if (dyld_NSIsSymbolNameDefinedInImage(dls->lib, symbol))
715 {
716 nssym = dyld_NSLookupSymbolInImage(dls->lib,
717 symbol,
718 NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
719 NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
720 }
721 else if (NSIsSymbolNameDefined(symbol))
722 {
723 debug("Searching dependencies");
724 savedErrorStr = dyld_error_str();
725 nssym = search_linked_libs(dls->lib, symbol);
726 }
727 }
728 else if (dls->module == MAGIC_DYLIB_MOD)
729 {
730 /* Global context, use NSLookupAndBindSymbol */
731 if (NSIsSymbolNameDefined(symbol))
732 {
733 /* There doesn't seem to be a return on error option for this call???
734 this is potentially broken, if binding fails, it will improperly
735 exit the application. */
736 nssym = NSLookupAndBindSymbol(symbol);
737 }
738 else
739 {
740 if (savedErrorStr)
741 SDL_free(savedErrorStr);
742 savedErrorStr = SDL_malloc(256);
743 SDL_snprintf(savedErrorStr, 256, "Symbol \"%s\" not in global context",symbol);
744 }
745 }
746 }
747 /* Error reporting */
748 if (!nssym)
749 {
750 if (!savedErrorStr || !SDL_strlen(savedErrorStr))
751 {
752 if (savedErrorStr)
753 SDL_free(savedErrorStr);
754 savedErrorStr = SDL_malloc(256);
755 SDL_snprintf(savedErrorStr, 256,"Symbol \"%s\" not found",symbol);
756 }
757 if (canSetError)
758 {
759 error(savedErrorStr);
760 }
761 else
762 {
763 debug(savedErrorStr);
764 }
765 if (savedErrorStr)
766 SDL_free(savedErrorStr);
767 return NULL;
768 }
769 return NSAddressOfSymbol(nssym);
770}
771
772static struct dlstatus *loadModule(const char *path, const struct stat *sbuf, int mode)
773{
774 NSObjectFileImage ofi = 0;
775 NSObjectFileImageReturnCode ofirc;
776 struct dlstatus *dls;
777 NSLinkEditErrors ler;
778 int lerno;
779 const char *errstr;
780 const char *file;
781 void (*init) (void);
782
783 ofirc = NSCreateObjectFileImageFromFile(path, &ofi);
784 switch (ofirc)
785 {
786 case NSObjectFileImageSuccess:
787 break;
788 case NSObjectFileImageInappropriateFile:
789 if (dyld_NSAddImage && dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage)
790 {
791 if (isFlagSet(mode, RTLD_LOCAL))
792 {
793 warning("trying to open a .dylib with RTLD_LOCAL");
794 error("unable to open this file with RTLD_LOCAL");
795 return NULL;
796 }
797 }
798 else
799 {
800 error("opening this file is unsupported on this system");
801 return NULL;
802 }
803 break;
804 case NSObjectFileImageFailure:
805 error("object file setup failure");
806 return NULL;
807 case NSObjectFileImageArch:
808 error("no object for this architecture");
809 return NULL;
810 case NSObjectFileImageFormat:
811 error("bad object file format");
812 return NULL;
813 case NSObjectFileImageAccess:
814 error("can't read object file");
815 return NULL;
816 default:
817 error("unknown error from NSCreateObjectFileImageFromFile()");
818 return NULL;
819 }
820 dls = lookupStatus(sbuf);
821 if (!dls)
822 {
823 dls = allocStatus();
824 }
825 if (!dls)
826 {
827 error("unable to allocate memory");
828 return NULL;
829 }
830 // dls->lib = 0;
831 if (ofirc == NSObjectFileImageInappropriateFile)
832 {
833 if ((dls->lib = dyld_NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR)))
834 {
835 debug("Dynamic lib loaded at %ld", dls->lib);
836 ofi = MAGIC_DYLIB_OFI;
837 dls->module = MAGIC_DYLIB_MOD;
838 ofirc = NSObjectFileImageSuccess;
839 /* Although it is possible with a bit of work to modify this so it works and
840 functions with RTLD_NOW, I don't deem it necessary at the moment */
841 }
842 if (!(dls->module))
843 {
844 NSLinkEditError(&ler, &lerno, &file, &errstr);
845 if (!errstr || (!SDL_strlen(errstr)))
846 error("Can't open this file type");
847 else
848 error(errstr);
849 if ((dls->flags & DL_IN_LIST) == 0)
850 {
851 SDL_free(dls);
852 }
853 return NULL;
854 }
855 }
856 else
857 {
858 dls->module = NSLinkModule(ofi, path,
859 NSLINKMODULE_OPTION_RETURN_ON_ERROR |
860 NSLINKMODULE_OPTION_PRIVATE |
861 (isFlagSet(mode, RTLD_NOW) ? NSLINKMODULE_OPTION_BINDNOW : 0));
862 NSDestroyObjectFileImage(ofi);
863 if (dls->module)
864 {
865 dls->lib = get_mach_header_from_NSModule(dls->module);
866 }
867 }
868 if (!dls->module)
869 {
870 NSLinkEditError(&ler, &lerno, &file, &errstr);
871 if ((dls->flags & DL_IN_LIST) == 0)
872 {
873 SDL_free(dls);
874 }
875 error(errstr);
876 return NULL;
877 }
878
879 insertStatus(dls, sbuf);
880 dls = reference(dls, mode);
881 if ((init = dlsymIntern(dls, "__init", 0)))
882 {
883 debug("calling _init()");
884 init();
885 }
886 return dls;
887}
888
889inline static void dlcompat_init_check(void)
890{
891 static pthread_mutex_t l = PTHREAD_MUTEX_INITIALIZER;
892 static int init_done = 0;
893
894 pthread_mutex_lock(&l);
895 if (!init_done) {
896 dlcompat_init_func();
897 init_done = 1;
898 }
899 pthread_mutex_unlock(&l);
900}
901
902static void dlcompat_init_func(void)
903{
904 _dyld_func_lookup("__dyld_NSAddImage", (void **)&dyld_NSAddImage);
905 _dyld_func_lookup("__dyld_NSIsSymbolNameDefinedInImage",
906 (void **)&dyld_NSIsSymbolNameDefinedInImage);
907 _dyld_func_lookup("__dyld_NSLookupSymbolInImage", (void **)&dyld_NSLookupSymbolInImage);
908 if (pthread_mutex_init(&dlcompat_mutex, NULL))
909 exit(1);
910 if (pthread_key_create(&dlerror_key, &dlerrorfree))
911 exit(1);
912}
913
914static void resetdlerror()
915{
916 struct dlthread *tss;
917 tss = pthread_getspecific(dlerror_key);
918 tss->errset = 0;
919}
920
921static void dlerrorfree(void *data)
922{
923 SDL_free(data);
924}
925
926/* We kind of want a recursive lock here, but meet a little trouble
927 * because they are not available pre OS X 10.2, so we fake it
928 * using thread specific storage to keep a lock count
929 */
930static inline void dolock(void)
931{
932 int err = 0;
933 struct dlthread *tss;
934 dlcompat_init_check();
935 tss = pthread_getspecific(dlerror_key);
936 if (!tss)
937 {
938 tss = SDL_malloc(sizeof(struct dlthread));
939 tss->lockcnt = 0;
940 tss->errset = 0;
941 if (pthread_setspecific(dlerror_key, tss))
942 {
943 fprintf(stderr,"dlcompat: pthread_setspecific failed\n");
944 exit(1);
945 }
946 }
947 if (!tss->lockcnt)
948 err = pthread_mutex_lock(&dlcompat_mutex);
949 tss->lockcnt = tss->lockcnt +1;
950 if (err)
951 exit(err);
952}
953
954static inline void dounlock(void)
955{
956 int err = 0;
957 struct dlthread *tss;
958 tss = pthread_getspecific(dlerror_key);
959 tss->lockcnt = tss->lockcnt -1;
960 if (!tss->lockcnt)
961 err = pthread_mutex_unlock(&dlcompat_mutex);
962 if (err)
963 exit(err);
964}
965
966static void *SDL_OSX_dlopen(const char *path, int mode)
967{
968 const struct stat *sbuf;
969 struct dlstatus *dls;
970 const char *fullPath;
971
972 dolock();
973 resetdlerror();
974 if (!path)
975 {
976 dls = &mainStatus;
977 goto dlopenok;
978 }
979 if (!(sbuf = findFile(path, &fullPath)))
980 {
981 error("file \"%s\" not found", path);
982 goto dlopenerror;
983 }
984 /* Now checks that it hasn't been closed already */
985 if ((dls = lookupStatus(sbuf)) && (dls->refs > 0))
986 {
987 /* debug("status found"); */
988 dls = reference(dls, mode);
989 goto dlopenok;
990 }
991#ifdef RTLD_NOLOAD
992 if (isFlagSet(mode, RTLD_NOLOAD))
993 {
994 error("no existing handle and RTLD_NOLOAD specified");
995 goto dlopenerror;
996 }
997#endif
998 if (isFlagSet(mode, RTLD_LAZY) && isFlagSet(mode, RTLD_NOW))
999 {
1000 error("how can I load something both RTLD_LAZY and RTLD_NOW?");
1001 goto dlopenerror;
1002 }
1003 dls = loadModule(fullPath, sbuf, mode);
1004
1005 dlopenok:
1006 dounlock();
1007 return (void *)dls;
1008 dlopenerror:
1009 dounlock();
1010 return NULL;
1011}
1012
1013#if !FINK_BUILD
1014static void *SDL_OSX_dlsym(void * dl_restrict handle, const char * dl_restrict symbol)
1015{
1016 int sym_len = SDL_strlen(symbol);
1017 void *value = NULL;
1018 char *malloc_sym = NULL;
1019 dolock();
1020 malloc_sym = SDL_malloc(sym_len + 2);
1021 if (malloc_sym)
1022 {
1023 SDL_snprintf(malloc_sym, sym_len+2, "_%s", symbol);
1024 value = dlsymIntern(handle, malloc_sym, 1);
1025 SDL_free(malloc_sym);
1026 }
1027 else
1028 {
1029 error("Unable to allocate memory");
1030 goto dlsymerror;
1031 }
1032 dounlock();
1033 return value;
1034 dlsymerror:
1035 dounlock();
1036 return NULL;
1037}
1038#endif
1039
1040#if FINK_BUILD
1041
1042static void *dlsym_prepend_underscore(void *handle, const char *symbol)
1043{
1044 void *answer;
1045 dolock();
1046 answer = dlsym_prepend_underscore_intern(handle, symbol);
1047 dounlock();
1048 return answer;
1049}
1050
1051static void *dlsym_prepend_underscore_intern(void *handle, const char *symbol)
1052{
1053/*
1054 * A quick and easy way for porting packages which call dlsym(handle,"sym")
1055 * If the porter adds -Ddlsym=dlsym_prepend_underscore to the CFLAGS then
1056 * this function will be called, and will add the required underscore.
1057 *
1058 * Note that I haven't figured out yet which should be "standard", prepend
1059 * the underscore always, or not at all. These global functions need to go away
1060 * for opendarwin.
1061 */
1062 int sym_len = SDL_strlen(symbol);
1063 void *value = NULL;
1064 char *malloc_sym = NULL;
1065 malloc_sym = SDL_malloc(sym_len + 2);
1066 if (malloc_sym)
1067 {
1068 SDL_snprintf(malloc_sym, sym_len+2, "_%s", symbol);
1069 value = dlsymIntern(handle, malloc_sym, 1);
1070 SDL_free(malloc_sym);
1071 }
1072 else
1073 {
1074 error("Unable to allocate memory");
1075 }
1076 return value;
1077}
1078
1079static void *dlsym_auto_underscore(void *handle, const char *symbol)
1080{
1081 void *answer;
1082 dolock();
1083 answer = dlsym_auto_underscore_intern(handle, symbol);
1084 dounlock();
1085 return answer;
1086
1087}
1088static void *dlsym_auto_underscore_intern(void *handle, const char *symbol)
1089{
1090 struct dlstatus *dls = handle;
1091 void *addr = 0;
1092 addr = dlsymIntern(dls, symbol, 0);
1093 if (!addr)
1094 addr = dlsym_prepend_underscore_intern(handle, symbol);
1095 return addr;
1096}
1097
1098
1099static void *SDL_OSX_dlsym(void * dl_restrict handle, const char * dl_restrict symbol)
1100{
1101 struct dlstatus *dls = handle;
1102 void *addr = 0;
1103 dolock();
1104 addr = dlsymIntern(dls, symbol, 1);
1105 dounlock();
1106 return addr;
1107}
1108#endif
1109
1110static int SDL_OSX_dlclose(void *handle)
1111{
1112 struct dlstatus *dls = handle;
1113 dolock();
1114 resetdlerror();
1115 if (!isValidStatus(dls))
1116 {
1117 goto dlcloseerror;
1118 }
1119 if (dls->module == MAGIC_DYLIB_MOD)
1120 {
1121 const char *name;
1122 if (!dls->lib)
1123 {
1124 name = "global context";
1125 }
1126 else
1127 {
1128 name = get_lib_name(dls->lib);
1129 }
1130 warning("trying to close a .dylib!");
1131 error("Not closing \"%s\" - dynamic libraries cannot be closed", name);
1132 goto dlcloseerror;
1133 }
1134 if (!dls->module)
1135 {
1136 error("module already closed");
1137 goto dlcloseerror;
1138 }
1139
1140 if (dls->refs == 1)
1141 {
1142 unsigned long options = 0;
1143 void (*fini) (void);
1144 if ((fini = dlsymIntern(dls, "__fini", 0)))
1145 {
1146 debug("calling _fini()");
1147 fini();
1148 }
1149 options |= NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES;
1150#ifdef RTLD_NODELETE
1151 if (isFlagSet(dls->mode, RTLD_NODELETE))
1152 options |= NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED;
1153#endif
1154 if (!NSUnLinkModule(dls->module, options))
1155 {
1156 error("unable to unlink module");
1157 goto dlcloseerror;
1158 }
1159 dls->refs--;
1160 dls->module = 0;
1161 /* Note: the dlstatus struct dls is neither removed from the list
1162 * nor is the memory it occupies freed. This shouldn't pose a
1163 * problem in mostly all cases, though.
1164 */
1165 }
1166 dounlock();
1167 return 0;
1168 dlcloseerror:
1169 dounlock();
1170 return 1;
1171}
1172
1173static const char *SDL_OSX_dlerror(void)
1174{
1175 struct dlthread *tss;
1176 const char * err_str = NULL;
1177 dlcompat_init_check();
1178 tss = pthread_getspecific(dlerror_key);
1179 if (tss != NULL && tss->errset != 0) {
1180 tss->errset = 0;
1181 err_str = tss->errstr;
1182 }
1183 return (err_str);
1184}
1185
1186/* Given an address, return the mach_header for the image containing it
1187 * or zero if the given address is not contained in any loaded images.
1188 */
1189static const struct mach_header *image_for_address(const void *address)
1190{
1191 unsigned long i;
1192 unsigned long j;
1193 unsigned long count = _dyld_image_count();
1194 const struct mach_header *mh = 0;
1195 struct load_command *lc = 0;
1196 unsigned long addr = 0;
1197 for (i = 0; i < count; i++)
1198 {
1199 addr = (unsigned long)address - _dyld_get_image_vmaddr_slide(i);
1200 mh = _dyld_get_image_header(i);
1201 if (mh)
1202 {
1203 lc = (struct load_command *)((char *)mh + sizeof(struct mach_header));
1204 for (j = 0; j < mh->ncmds; j++, lc = (struct load_command *)((char *)lc + lc->cmdsize))
1205 {
1206 if (LC_SEGMENT == lc->cmd &&
1207 addr >= ((struct segment_command *)lc)->vmaddr &&
1208 addr <
1209 ((struct segment_command *)lc)->vmaddr + ((struct segment_command *)lc)->vmsize)
1210 {
1211 goto image_found;
1212 }
1213 }
1214 }
1215 mh = 0;
1216 }
1217 image_found:
1218 return mh;
1219}
1220
1221#if 0 /* unused */
1222static int SDL_OSX_dladdr(const void * dl_restrict p, SDL_OSX_Dl_info * dl_restrict info)
1223{
1224/*
1225 FIXME: USe the routine image_for_address.
1226*/
1227 unsigned long i;
1228 unsigned long j;
1229 unsigned long count = _dyld_image_count();
1230 struct mach_header *mh = 0;
1231 struct load_command *lc = 0;
1232 unsigned long addr = NULL;
1233 unsigned long table_off = (unsigned long)0;
1234 int found = 0;
1235 if (!info)
1236 return 0;
1237 dolock();
1238 resetdlerror();
1239 info->dli_fname = 0;
1240 info->dli_fbase = 0;
1241 info->dli_sname = 0;
1242 info->dli_saddr = 0;
1243/* Some of this was swiped from code posted by Douglas Davidson <ddavidso AT apple DOT com>
1244 * to darwin-development AT lists DOT apple DOT com and slightly modified
1245 */
1246 for (i = 0; i < count; i++)
1247 {
1248 addr = (unsigned long)p - _dyld_get_image_vmaddr_slide(i);
1249 mh = _dyld_get_image_header(i);
1250 if (mh)
1251 {
1252 lc = (struct load_command *)((char *)mh + sizeof(struct mach_header));
1253 for (j = 0; j < mh->ncmds; j++, lc = (struct load_command *)((char *)lc + lc->cmdsize))
1254 {
1255 if (LC_SEGMENT == lc->cmd &&
1256 addr >= ((struct segment_command *)lc)->vmaddr &&
1257 addr <
1258 ((struct segment_command *)lc)->vmaddr + ((struct segment_command *)lc)->vmsize)
1259 {
1260 info->dli_fname = _dyld_get_image_name(i);
1261 info->dli_fbase = (void *)mh;
1262 found = 1;
1263 break;
1264 }
1265 }
1266 if (found)
1267 break;
1268 }
1269 }
1270 if (!found)
1271 {
1272 dounlock();
1273 return 0;
1274 }
1275 lc = (struct load_command *)((char *)mh + sizeof(struct mach_header));
1276 for (j = 0; j < mh->ncmds; j++, lc = (struct load_command *)((char *)lc + lc->cmdsize))
1277 {
1278 if (LC_SEGMENT == lc->cmd)
1279 {
1280 if (!SDL_strcmp(((struct segment_command *)lc)->segname, "__LINKEDIT"))
1281 break;
1282 }
1283 }
1284 table_off =
1285 ((unsigned long)((struct segment_command *)lc)->vmaddr) -
1286 ((unsigned long)((struct segment_command *)lc)->fileoff) + _dyld_get_image_vmaddr_slide(i);
1287 debug("table off %x", table_off);
1288
1289 lc = (struct load_command *)((char *)mh + sizeof(struct mach_header));
1290 for (j = 0; j < mh->ncmds; j++, lc = (struct load_command *)((char *)lc + lc->cmdsize))
1291 {
1292 if (LC_SYMTAB == lc->cmd)
1293 {
1294
1295 struct nlist *symtable = (struct nlist *)(((struct symtab_command *)lc)->symoff + table_off);
1296 unsigned long numsyms = ((struct symtab_command *)lc)->nsyms;
1297 struct nlist *nearest = NULL;
1298 unsigned long diff = 0xffffffff;
1299 unsigned long strtable = (unsigned long)(((struct symtab_command *)lc)->stroff + table_off);
1300 debug("symtable %x", symtable);
1301 for (i = 0; i < numsyms; i++)
1302 {
1303 /* Ignore the following kinds of Symbols */
1304 if ((!symtable->n_value) /* Undefined */
1305 || (symtable->n_type >= N_PEXT) /* Debug symbol */
1306 || (!(symtable->n_type & N_EXT)) /* Local Symbol */
1307 )
1308 {
1309 symtable++;
1310 continue;
1311 }
1312 if ((addr >= symtable->n_value) && (diff >= (symtable->n_value - addr)))
1313 {
1314 diff = (unsigned long)symtable->n_value - addr;
1315 nearest = symtable;
1316 }
1317 symtable++;
1318 }
1319 if (nearest)
1320 {
1321 info->dli_saddr = nearest->n_value + ((void *)p - addr);
1322 info->dli_sname = (char *)(strtable + nearest->n_un.n_strx);
1323 }
1324 }
1325 }
1326 dounlock();
1327 return 1;
1328}
1329#endif
1330
1331/*
1332 * Implement the dlfunc() interface, which behaves exactly the same as
1333 * dlsym() except that it returns a function pointer instead of a data
1334 * pointer. This can be used by applications to avoid compiler warnings
1335 * about undefined behavior, and is intended as prior art for future
1336 * POSIX standardization. This function requires that all pointer types
1337 * have the same representation, which is true on all platforms FreeBSD
1338 * runs on, but is not guaranteed by the C standard.
1339 */
1340#if 0
1341static dlfunc_t SDL_OSX_dlfunc(void * dl_restrict handle, const char * dl_restrict symbol)
1342{
1343 union
1344 {
1345 void *d;
1346 dlfunc_t f;
1347 } rv;
1348 int sym_len = SDL_strlen(symbol);
1349 char *malloc_sym = NULL;
1350 dolock();
1351 malloc_sym = SDL_malloc(sym_len + 2);
1352 if (malloc_sym)
1353 {
1354 SDL_snprintf(malloc_sym, sym_len+2, "_%s", symbol);
1355 rv.d = dlsymIntern(handle, malloc_sym, 1);
1356 SDL_free(malloc_sym);
1357 }
1358 else
1359 {
1360 error("Unable to allocate memory");
1361 goto dlfuncerror;
1362 }
1363 dounlock();
1364 return rv.f;
1365 dlfuncerror:
1366 dounlock();
1367 return NULL;
1368}
1369#endif
1370
1371
1372
1373/* dlcompat ends, here's the SDL interface... --ryan. */
1374
1375
1376/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1377/* System dependent library loading routines */
1378
1379#include "SDL_loadso.h"
1380
1381void *SDL_LoadObject(const char *sofile)
1382{
1383 void *handle = SDL_OSX_dlopen(sofile, RTLD_NOW);
1384 const char *loaderror = SDL_OSX_dlerror();
1385 if ( handle == NULL ) {
1386 SDL_SetError("Failed loading %s: %s", sofile, loaderror);
1387 }
1388 return(handle);
1389}
1390
1391void *SDL_LoadFunction(void *handle, const char *name)
1392{
1393 void *symbol = SDL_OSX_dlsym(handle, name);
1394 if ( symbol == NULL ) {
1395 SDL_SetError("Failed loading %s: %s", name, SDL_OSX_dlerror());
1396 }
1397 return(symbol);
1398}
1399
1400void SDL_UnloadObject(void *handle)
1401{
1402 if ( handle != NULL ) {
1403 SDL_OSX_dlclose(handle);
1404 }
1405}
1406
1407#endif /* SDL_LOADSO_DLCOMPAT */
diff --git a/apps/plugins/sdl/src/loadso/mint/SDL_sysloadso.c b/apps/plugins/sdl/src/loadso/mint/SDL_sysloadso.c
deleted file mode 100644
index d6dd732ca8..0000000000
--- a/apps/plugins/sdl/src/loadso/mint/SDL_sysloadso.c
+++ /dev/null
@@ -1,62 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_LOADSO_LDG
25
26/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
27/* System dependent library loading routines */
28
29#include <stdio.h>
30#include <gem.h>
31#include <ldg.h>
32
33#include "SDL_loadso.h"
34
35void *SDL_LoadObject(const char *sofile)
36{
37 const char *loaderror = "Unknown error";
38 void *handle = (void *)ldg_open((char *)sofile, ldg_global);
39 if ( handle == NULL ) {
40 SDL_SetError("Failed loading %s: %s", sofile, loaderror);
41 }
42 return(handle);
43}
44
45void *SDL_LoadFunction(void *handle, const char *name)
46{
47 const char *loaderror = "Unknown error";
48 void *symbol = (void *)ldg_find((char *)name, (LDG *)handle);
49 if ( symbol == NULL ) {
50 SDL_SetError("Failed loading %s: %s", name, loaderror);
51 }
52 return(symbol);
53}
54
55void SDL_UnloadObject(void *handle)
56{
57 if ( handle != NULL ) {
58 ldg_close((LDG *)handle, ldg_global);
59 }
60}
61
62#endif /* SDL_LOADSO_LDG */
diff --git a/apps/plugins/sdl/src/loadso/os2/SDL_sysloadso.c b/apps/plugins/sdl/src/loadso/os2/SDL_sysloadso.c
deleted file mode 100644
index 62ea536dd0..0000000000
--- a/apps/plugins/sdl/src/loadso/os2/SDL_sysloadso.c
+++ /dev/null
@@ -1,71 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_LOADSO_OS2
25
26/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
27/* System dependent library loading routines */
28
29#include <stdio.h>
30#define INCL_DOSERRORS
31#define INCL_DOSMODULEMGR
32#include <os2.h>
33
34#include "SDL_loadso.h"
35
36void *SDL_LoadObject(const char *sofile)
37{
38 HMODULE handle = NULL;
39 char buf[512];
40 APIRET ulrc = DosLoadModule(buf, sizeof (buf), (char *) sofile, &handle);
41
42 /* Generate an error message if all loads failed */
43 if ((ulrc != NO_ERROR) || (handle == NULL))
44 SDL_SetError("Failed loading %s: %s", sofile, buf);
45
46 return((void *) handle);
47}
48
49void *SDL_LoadFunction(void *handle, const char *name)
50{
51 const char *loaderror = "Unknown error";
52 void *symbol = NULL;
53 APIRET ulrc = DosQueryProcAddr((HMODULE)handle, 0, (char *)name, &symbol);
54 if (ulrc == ERROR_INVALID_HANDLE)
55 loaderror = "Invalid module handle";
56 else if (ulrc == ERROR_INVALID_NAME)
57 loaderror = "Symbol not found";
58
59 if (symbol == NULL)
60 SDL_SetError("Failed loading %s: %s", name, loaderror);
61
62 return(symbol);
63}
64
65void SDL_UnloadObject(void *handle)
66{
67 if ( handle != NULL )
68 DosFreeModule((HMODULE) handle);
69}
70
71#endif /* SDL_LOADSO_OS2 */
diff --git a/apps/plugins/sdl/src/loadso/win32/SDL_sysloadso.c b/apps/plugins/sdl/src/loadso/win32/SDL_sysloadso.c
deleted file mode 100644
index 784c7e7786..0000000000
--- a/apps/plugins/sdl/src/loadso/win32/SDL_sysloadso.c
+++ /dev/null
@@ -1,139 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_LOADSO_WIN32
25
26/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
27/* System dependent library loading routines */
28
29#define WIN32_LEAN_AND_MEAN
30#include <windows.h>
31
32#include "SDL_loadso.h"
33
34void *SDL_LoadObject(const char *sofile)
35{
36 void *handle = NULL;
37 const char *loaderror = "Unknown error";
38
39#if defined(_WIN32_WCE)
40 char errbuf[512];
41
42 wchar_t *errbuf_t = SDL_malloc(512 * sizeof(wchar_t));
43 wchar_t *sofile_t = SDL_malloc((MAX_PATH+1) * sizeof(wchar_t));
44
45 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, sofile, -1, sofile_t, MAX_PATH);
46 handle = (void *)LoadLibrary(sofile_t);
47
48 /* Generate an error message if all loads failed */
49 if ( handle == NULL ) {
50 FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS |
51 FORMAT_MESSAGE_FROM_SYSTEM),
52 NULL, GetLastError(),
53 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
54 errbuf_t, SDL_arraysize(errbuf), NULL);
55 WideCharToMultiByte(CP_ACP, 0, errbuf_t, -1, errbuf, 511, NULL, NULL);
56 loaderror = errbuf;
57 }
58
59 SDL_free(sofile_t);
60 SDL_free(errbuf_t);
61
62#else /*if defined(__WIN32__)*/
63 char errbuf[512];
64
65 handle = (void *)LoadLibrary(sofile);
66
67 /* Generate an error message if all loads failed */
68 if ( handle == NULL ) {
69 FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS |
70 FORMAT_MESSAGE_FROM_SYSTEM),
71 NULL, GetLastError(),
72 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
73 errbuf, SDL_arraysize(errbuf), NULL);
74 loaderror = errbuf;
75 }
76#endif
77
78 if ( handle == NULL ) {
79 SDL_SetError("Failed loading %s: %s", sofile, loaderror);
80 }
81 return(handle);
82}
83
84void *SDL_LoadFunction(void *handle, const char *name)
85{
86 void *symbol = NULL;
87 const char *loaderror = "Unknown error";
88
89#if defined(_WIN32_WCE)
90 char errbuf[512];
91 int length = SDL_strlen(name);
92
93 wchar_t *name_t = SDL_malloc((length + 1) * sizeof(wchar_t));
94 wchar_t *errbuf_t = SDL_malloc(512 * sizeof(wchar_t));
95
96 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, name, -1, name_t, length+1);
97
98 symbol = (void *)GetProcAddress((HMODULE)handle, name_t);
99 if ( symbol == NULL ) {
100 FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS |
101 FORMAT_MESSAGE_FROM_SYSTEM),
102 NULL, GetLastError(),
103 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
104 errbuf_t, SDL_arraysize(errbuf), NULL);
105 WideCharToMultiByte(CP_ACP, 0, errbuf_t, -1, errbuf, 511, NULL, NULL);
106 loaderror = errbuf;
107 }
108
109 SDL_free(name_t);
110 SDL_free(errbuf_t);
111
112#else /*if defined(WIN32)*/
113 char errbuf[512];
114
115 symbol = (void *)GetProcAddress((HMODULE)handle, name);
116 if ( symbol == NULL ) {
117 FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS |
118 FORMAT_MESSAGE_FROM_SYSTEM),
119 NULL, GetLastError(),
120 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
121 errbuf, SDL_arraysize(errbuf), NULL);
122 loaderror = errbuf;
123 }
124#endif
125
126 if ( symbol == NULL ) {
127 SDL_SetError("Failed loading %s: %s", name, loaderror);
128 }
129 return(symbol);
130}
131
132void SDL_UnloadObject(void *handle)
133{
134 if ( handle != NULL ) {
135 FreeLibrary((HMODULE)handle);
136 }
137}
138
139#endif /* SDL_LOADSO_WIN32 */
diff --git a/apps/plugins/sdl/src/main/beos/SDL_BeApp.cc b/apps/plugins/sdl/src/main/beos/SDL_BeApp.cc
deleted file mode 100644
index 8b793779ac..0000000000
--- a/apps/plugins/sdl/src/main/beos/SDL_BeApp.cc
+++ /dev/null
@@ -1,111 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the BeApp specific portions of the application */
25
26#include <AppKit.h>
27#include <storage/Path.h>
28#include <storage/Entry.h>
29#include <unistd.h>
30
31#include "SDL_BeApp.h"
32#include "SDL_thread.h"
33#include "SDL_timer.h"
34#include "SDL_error.h"
35
36/* Flag to tell whether or not the Be application is active or not */
37int SDL_BeAppActive = 0;
38static SDL_Thread *SDL_AppThread = NULL;
39
40static int StartBeApp(void *unused)
41{
42 if(!be_app) {
43 BApplication *App;
44
45 App = new BApplication("application/x-SDL-executable");
46
47 App->Run();
48 delete App;
49 }
50 return(0);
51}
52
53/* Initialize the Be Application, if it's not already started */
54int SDL_InitBeApp(void)
55{
56 /* Create the BApplication that handles appserver interaction */
57 if ( SDL_BeAppActive <= 0 ) {
58 SDL_AppThread = SDL_CreateThread(StartBeApp, NULL);
59 if ( SDL_AppThread == NULL ) {
60 SDL_SetError("Couldn't create BApplication thread");
61 return(-1);
62 }
63
64 /* Change working to directory to that of executable */
65 app_info info;
66 if (B_OK == be_app->GetAppInfo(&info)) {
67 entry_ref ref = info.ref;
68 BEntry entry;
69 if (B_OK == entry.SetTo(&ref)) {
70 BPath path;
71 if (B_OK == path.SetTo(&entry)) {
72 if (B_OK == path.GetParent(&path)) {
73 chdir(path.Path());
74 }
75 }
76 }
77 }
78
79 do {
80 SDL_Delay(10);
81 } while ( (be_app == NULL) || be_app->IsLaunching() );
82
83 /* Mark the application active */
84 SDL_BeAppActive = 0;
85 }
86
87 /* Increment the application reference count */
88 ++SDL_BeAppActive;
89
90 /* The app is running, and we're ready to go */
91 return(0);
92}
93
94/* Quit the Be Application, if there's nothing left to do */
95void SDL_QuitBeApp(void)
96{
97 /* Decrement the application reference count */
98 --SDL_BeAppActive;
99
100 /* If the reference count reached zero, clean up the app */
101 if ( SDL_BeAppActive == 0 ) {
102 if ( SDL_AppThread != NULL ) {
103 if ( be_app != NULL ) { /* Not tested */
104 be_app->PostMessage(B_QUIT_REQUESTED);
105 }
106 SDL_WaitThread(SDL_AppThread, NULL);
107 SDL_AppThread = NULL;
108 }
109 /* be_app should now be NULL since be_app has quit */
110 }
111}
diff --git a/apps/plugins/sdl/src/main/beos/SDL_BeApp.h b/apps/plugins/sdl/src/main/beos/SDL_BeApp.h
deleted file mode 100644
index 9f88212438..0000000000
--- a/apps/plugins/sdl/src/main/beos/SDL_BeApp.h
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the BeApp specific portions of the application */
25
26/* Initialize the Be Application, if it's not already started */
27extern int SDL_InitBeApp(void);
28
29/* Quit the Be Application, if there's nothing left to do */
30extern void SDL_QuitBeApp(void);
31
32/* Flag to tell whether the app is active or not */
33extern int SDL_BeAppActive;
diff --git a/apps/plugins/sdl/src/main/macos/SDL.r b/apps/plugins/sdl/src/main/macos/SDL.r
deleted file mode 100644
index 438f6872ef..0000000000
--- a/apps/plugins/sdl/src/main/macos/SDL.r
+++ /dev/null
@@ -1 +0,0 @@
1data 'DLOG' (1000) { $"0072 0040 00EA 01B3 0001 0100 0000 0000 0000 03E8 0C43 6F6D 6D61 6E64 204C 696E" /* .r.@.ê.³...........è.Command Lin */ $"6500 280A" /* e.( */ }; data 'DLOG' (1001) { $"0072 0040 00DB 01AC 0001 0100 0000 0000 0000 03E9 0C45 7272 6F72 2057 696E 646F" /* .r.@.Û.¬...........é.Error Windo */ $"7700 280A" /* w.( */ }; data 'DLOG' (1002) { $"00B8 00BE 0147 01D8 0005 0100 0000 0000 0000 03EA 1643 6F6E 6669 726D 2044 6973" /* .¸.¾.G.Ø...........ê.Confirm Dis */ $"706C 6179 2043 6861 6E67 6510 280A" /* play Change.( */ }; data 'DITL' (1000) { $"0005 0000 0000 0052 0113 0066 0158 0402 4F4B 0000 0000 0052 00C2 0066 0107 0406" /* .......R...f.X..OK.....R.Â.f.... */ $"4361 6E63 656C 0000 0000 000F 0084 001F 0155 1000 0000 0000 0054 0019 0066 007D" /* Cancel.......„...U.......T...f.} */ $"050E 4F75 7470 7574 2074 6F20 6669 6C65 0000 0000 000F 0018 001F 007F 080D 436F" /* ..Output to file..............Co */ $"6D6D 616E 6420 4C69 6E65 3A00 0000 0000 0030 0018 0040 0158 0702 0080" /* mmand Line:......0...@.X...€ */ }; data 'DITL' (1001) { $"0001 0000 0000 0046 0120 005A 015A 0402 4F4B 0000 0000 0010 000A 0038 0160 0800" /* .......F. .Z.Z..OK.......Â.8.`.. */ }; data 'DITL' (1002) { $"0002 0000 0000 006F 001E 0083 0058 0406 4361 6E63 656C 0000 0000 006E 00C0 0082" /* .......o...ƒ.X..Cancel.....n.À.‚ */ $"00FA 0402 4F4B 0000 0000 000E 000F 005F 010C 88B3 5468 6520 7365 7474 696E 6720" /* .ú..OK........._..ˆ³The setting */ $"666F 7220 796F 7572 206D 6F6E 6974 6F72 2068 6173 2062 6565 6E20 6368 616E 6765" /* for your monitor has been change */ $"642C 2061 6E64 2069 7420 6D61 7920 6E6F 7420 6265 2064 6973 706C 6179 6564 2063" /* d, and it may not be displayed c */ $"6F72 7265 6374 6C79 2E20 546F 2063 6F6E 6669 726D 2074 6865 2064 6973 706C 6179" /* orrectly. To confirm the display */ $"2069 7320 636F 7272 6563 742C 2063 6C69 636B 204F 4B2E 2054 6F20 7265 7475 726E" /* is correct, click OK. To return */ $"2074 6F20 7468 6520 6F72 6967 696E 616C 2073 6574 7469 6E67 2C20 636C 6963 6B20" /* to the original setting, click */ $"4361 6E63 656C 2E00" /* Cancel.. */ }; data 'MENU' (128, preload) { $"0080 0000 0000 0000 0000 FFFF FFFB 0114 0C41 626F 7574 2053 444C 2E2E 2E00 0000" /* .€........ÿÿÿû...About SDL...... */ $"0001 2D00 0000 0000" /* ..-..... */ }; data 'MENU' (129) { $"0081 0000 0000 0000 0000 FFFF FFFF 0C56 6964 656F 2044 7269 7665 7219 4472 6177" /* .........ÿÿÿÿ.Video Driver.Draw */ $"5370 726F 636B 6574 2028 4675 6C6C 7363 7265 656E 2900 0000 001E 546F 6F6C 426F" /* Sprocket (Fullscreen).....ToolBo */ $"7820 2028 4675 6C6C 7363 7265 656E 2F57 696E 646F 7765 6429 0000 0000 00" /* x (Fullscreen/Windowed)..... */ }; data 'CNTL' (128) { $"0000 0000 0010 0140 0000 0100 0064 0081 03F0 0000 0000 0D56 6964 656F 2044 7269" /* .......@.....d..ð.....Video Dri */ $"7665 723A" /* ver: */ }; data 'TMPL' (128, "CLne") { $"0C43 6F6D 6D61 6E64 204C 696E 6550 5354 520C 5669 6465 6F20 4472 6976 6572 5053" /* .Command LinePSTR.Video DriverPS */ $"5452 0C53 6176 6520 546F 2046 696C 6542 4F4F 4C" /* TR.Save To FileBOOL */ }; \ No newline at end of file
diff --git a/apps/plugins/sdl/src/main/macos/SDL.shlib.r b/apps/plugins/sdl/src/main/macos/SDL.shlib.r
deleted file mode 100644
index 313c79485a..0000000000
--- a/apps/plugins/sdl/src/main/macos/SDL.shlib.r
+++ /dev/null
@@ -1 +0,0 @@
1 #ifndef __TYPES_R__ #include "Types.r" #endif #ifndef __BALLOONS_R__ #include "Balloons.r" #endif #define VERSION_MAJOR 1 #define VERSION_MINOR 2 #define REVISION 13 #define STATE release /* development | alpha | beta | release */ #define RELEASE_NO 0 /* number after letter, or zero for release */ #define COUNTRY verUS #define VERSION_STRING "1.2.13" #define NAME "SDL" #define SHORT_DESCRIPTION "Simple DirectMedia Layer by Sam Lantinga" #define LONG_DESCRIPTION "A cross-platform multimedia library.\n\nhttp://www.libsdl.org" resource 'vers' (1) { VERSION_MAJOR, (VERSION_MINOR << 4) | REVISION, STATE, RELEASE_NO, COUNTRY, VERSION_STRING, VERSION_STRING }; resource 'vers' (2) { VERSION_MAJOR, (VERSION_MINOR << 4) | REVISION, STATE, RELEASE_NO, COUNTRY, VERSION_STRING, SHORT_DESCRIPTION }; /* Extension Manager info */ data 'CCI' (128) { NAME "\n\n" LONG_DESCRIPTION }; /* Finder help balloon */ resource 'hfdr' (kHMHelpID) { HelpMgrVersion, hmDefaultOptions, 0, 0, { HMStringItem { NAME "\n\n" LONG_DESCRIPTION } } }; \ No newline at end of file
diff --git a/apps/plugins/sdl/src/main/macos/SDL_main.c b/apps/plugins/sdl/src/main/macos/SDL_main.c
deleted file mode 100644
index ff1ffdca0d..0000000000
--- a/apps/plugins/sdl/src/main/macos/SDL_main.c
+++ /dev/null
@@ -1,610 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/* This file takes care of command line argument parsing, and stdio redirection
24 in the MacOS environment. (stdio/stderr is *not* directed for Mach-O builds)
25 */
26
27#if defined(__APPLE__) && defined(__MACH__)
28#include <Carbon/Carbon.h>
29#elif TARGET_API_MAC_CARBON && (UNIVERSAL_INTERFACES_VERSION > 0x0335)
30#include <Carbon.h>
31#else
32#include <Dialogs.h>
33#include <Fonts.h>
34#include <Events.h>
35#include <Resources.h>
36#include <Folders.h>
37#endif
38
39/* Include the SDL main definition header */
40#include "SDL.h"
41#include "SDL_main.h"
42#ifdef main
43#undef main
44#endif
45
46#if !(defined(__APPLE__) && defined(__MACH__))
47/* The standard output files */
48#define STDOUT_FILE "stdout.txt"
49#define STDERR_FILE "stderr.txt"
50#endif
51
52#if !defined(__MWERKS__) && !TARGET_API_MAC_CARBON
53 /* In MPW, the qd global has been removed from the libraries */
54 QDGlobals qd;
55#endif
56
57/* Structure for keeping prefs in 1 variable */
58typedef struct {
59 Str255 command_line;
60 Str255 video_driver_name;
61 Boolean output_to_file;
62} PrefsRecord;
63
64/* See if the command key is held down at startup */
65static Boolean CommandKeyIsDown(void)
66{
67 KeyMap theKeyMap;
68
69 GetKeys(theKeyMap);
70
71 if (((unsigned char *) theKeyMap)[6] & 0x80) {
72 return(true);
73 }
74 return(false);
75}
76
77#if !(defined(__APPLE__) && defined(__MACH__))
78
79/* Parse a command line buffer into arguments */
80static int ParseCommandLine(char *cmdline, char **argv)
81{
82 char *bufp;
83 int argc;
84
85 argc = 0;
86 for ( bufp = cmdline; *bufp; ) {
87 /* Skip leading whitespace */
88 while ( SDL_isspace(*bufp) ) {
89 ++bufp;
90 }
91 /* Skip over argument */
92 if ( *bufp == '"' ) {
93 ++bufp;
94 if ( *bufp ) {
95 if ( argv ) {
96 argv[argc] = bufp;
97 }
98 ++argc;
99 }
100 /* Skip over word */
101 while ( *bufp && (*bufp != '"') ) {
102 ++bufp;
103 }
104 } else {
105 if ( *bufp ) {
106 if ( argv ) {
107 argv[argc] = bufp;
108 }
109 ++argc;
110 }
111 /* Skip over word */
112 while ( *bufp && ! SDL_isspace(*bufp) ) {
113 ++bufp;
114 }
115 }
116 if ( *bufp ) {
117 if ( argv ) {
118 *bufp = '\0';
119 }
120 ++bufp;
121 }
122 }
123 if ( argv ) {
124 argv[argc] = NULL;
125 }
126 return(argc);
127}
128
129/* Remove the output files if there was no output written */
130static void cleanup_output(void)
131{
132 FILE *file;
133 int empty;
134
135 /* Flush the output in case anything is queued */
136 fclose(stdout);
137 fclose(stderr);
138
139 /* See if the files have any output in them */
140 file = fopen(STDOUT_FILE, "rb");
141 if ( file ) {
142 empty = (fgetc(file) == EOF) ? 1 : 0;
143 fclose(file);
144 if ( empty ) {
145 remove(STDOUT_FILE);
146 }
147 }
148 file = fopen(STDERR_FILE, "rb");
149 if ( file ) {
150 empty = (fgetc(file) == EOF) ? 1 : 0;
151 fclose(file);
152 if ( empty ) {
153 remove(STDERR_FILE);
154 }
155 }
156}
157
158#endif //!(defined(__APPLE__) && defined(__MACH__))
159
160static int getCurrentAppName (StrFileName name) {
161
162 ProcessSerialNumber process;
163 ProcessInfoRec process_info;
164 FSSpec process_fsp;
165
166 process.highLongOfPSN = 0;
167 process.lowLongOfPSN = kCurrentProcess;
168 process_info.processInfoLength = sizeof (process_info);
169 process_info.processName = NULL;
170 process_info.processAppSpec = &process_fsp;
171
172 if ( noErr != GetProcessInformation (&process, &process_info) )
173 return 0;
174
175 SDL_memcpy(name, process_fsp.name, process_fsp.name[0] + 1);
176 return 1;
177}
178
179static int getPrefsFile (FSSpec *prefs_fsp, int create) {
180
181 /* The prefs file name is the application name, possibly truncated, */
182 /* plus " Preferences */
183
184 #define SUFFIX " Preferences"
185 #define MAX_NAME 19 /* 31 - strlen (SUFFIX) */
186
187 short volume_ref_number;
188 long directory_id;
189 StrFileName prefs_name;
190 StrFileName app_name;
191
192 /* Get Preferences folder - works with Multiple Users */
193 if ( noErr != FindFolder ( kOnSystemDisk, kPreferencesFolderType, kDontCreateFolder,
194 &volume_ref_number, &directory_id) )
195 exit (-1);
196
197 if ( ! getCurrentAppName (app_name) )
198 exit (-1);
199
200 /* Truncate if name is too long */
201 if (app_name[0] > MAX_NAME )
202 app_name[0] = MAX_NAME;
203
204 SDL_memcpy(prefs_name + 1, app_name + 1, app_name[0]);
205 SDL_memcpy(prefs_name + app_name[0] + 1, SUFFIX, strlen (SUFFIX));
206 prefs_name[0] = app_name[0] + strlen (SUFFIX);
207
208 /* Make the file spec for prefs file */
209 if ( noErr != FSMakeFSSpec (volume_ref_number, directory_id, prefs_name, prefs_fsp) ) {
210 if ( !create )
211 return 0;
212 else {
213 /* Create the prefs file */
214 SDL_memcpy(prefs_fsp->name, prefs_name, prefs_name[0] + 1);
215 prefs_fsp->parID = directory_id;
216 prefs_fsp->vRefNum = volume_ref_number;
217
218 FSpCreateResFile (prefs_fsp, 0x3f3f3f3f, 'pref', 0); // '????' parsed as trigraph
219
220 if ( noErr != ResError () )
221 return 0;
222 }
223 }
224 return 1;
225}
226
227static int readPrefsResource (PrefsRecord *prefs) {
228
229 Handle prefs_handle;
230
231 prefs_handle = Get1Resource( 'CLne', 128 );
232
233 if (prefs_handle != NULL) {
234 int offset = 0;
235// int j = 0;
236
237 HLock(prefs_handle);
238
239 /* Get command line string */
240 SDL_memcpy(prefs->command_line, *prefs_handle, (*prefs_handle)[0]+1);
241
242 /* Get video driver name */
243 offset += (*prefs_handle)[0] + 1;
244 SDL_memcpy(prefs->video_driver_name, *prefs_handle + offset, (*prefs_handle)[offset] + 1);
245
246 /* Get save-to-file option (1 or 0) */
247 offset += (*prefs_handle)[offset] + 1;
248 prefs->output_to_file = (*prefs_handle)[offset];
249
250 ReleaseResource( prefs_handle );
251
252 return ResError() == noErr;
253 }
254
255 return 0;
256}
257
258static int writePrefsResource (PrefsRecord *prefs, short resource_file) {
259
260 Handle prefs_handle;
261
262 UseResFile (resource_file);
263
264 prefs_handle = Get1Resource ( 'CLne', 128 );
265 if (prefs_handle != NULL)
266 RemoveResource (prefs_handle);
267
268 prefs_handle = NewHandle ( prefs->command_line[0] + prefs->video_driver_name[0] + 4 );
269 if (prefs_handle != NULL) {
270
271 int offset;
272
273 HLock (prefs_handle);
274
275 /* Command line text */
276 offset = 0;
277 SDL_memcpy(*prefs_handle, prefs->command_line, prefs->command_line[0] + 1);
278
279 /* Video driver name */
280 offset += prefs->command_line[0] + 1;
281 SDL_memcpy(*prefs_handle + offset, prefs->video_driver_name, prefs->video_driver_name[0] + 1);
282
283 /* Output-to-file option */
284 offset += prefs->video_driver_name[0] + 1;
285 *( *((char**)prefs_handle) + offset) = (char)prefs->output_to_file;
286 *( *((char**)prefs_handle) + offset + 1) = 0;
287
288 AddResource (prefs_handle, 'CLne', 128, "\pCommand Line");
289 WriteResource (prefs_handle);
290 UpdateResFile (resource_file);
291 DisposeHandle (prefs_handle);
292
293 return ResError() == noErr;
294 }
295
296 return 0;
297}
298
299static int readPreferences (PrefsRecord *prefs) {
300
301 int no_error = 1;
302 FSSpec prefs_fsp;
303
304 /* Check for prefs file first */
305 if ( getPrefsFile (&prefs_fsp, 0) ) {
306
307 short prefs_resource;
308
309 prefs_resource = FSpOpenResFile (&prefs_fsp, fsRdPerm);
310 if ( prefs_resource == -1 ) /* this shouldn't happen, but... */
311 return 0;
312
313 UseResFile (prefs_resource);
314 no_error = readPrefsResource (prefs);
315 CloseResFile (prefs_resource);
316 }
317
318 /* Fall back to application's resource fork (reading only, so this is safe) */
319 else {
320
321 no_error = readPrefsResource (prefs);
322 }
323
324 return no_error;
325}
326
327static int writePreferences (PrefsRecord *prefs) {
328
329 int no_error = 1;
330 FSSpec prefs_fsp;
331
332 /* Get prefs file, create if it doesn't exist */
333 if ( getPrefsFile (&prefs_fsp, 1) ) {
334
335 short prefs_resource;
336
337 prefs_resource = FSpOpenResFile (&prefs_fsp, fsRdWrPerm);
338 if (prefs_resource == -1)
339 return 0;
340 no_error = writePrefsResource (prefs, prefs_resource);
341 CloseResFile (prefs_resource);
342 }
343
344 return no_error;
345}
346
347/* This is where execution begins */
348int main(int argc, char *argv[])
349{
350
351#if !(defined(__APPLE__) && defined(__MACH__))
352#pragma unused(argc, argv)
353#endif
354
355#define DEFAULT_ARGS "\p" /* pascal string for default args */
356#define DEFAULT_VIDEO_DRIVER "\ptoolbox" /* pascal string for default video driver name */
357#define DEFAULT_OUTPUT_TO_FILE 1 /* 1 == output to file, 0 == no output */
358
359#define VIDEO_ID_DRAWSPROCKET 1 /* these correspond to popup menu choices */
360#define VIDEO_ID_TOOLBOX 2
361
362 PrefsRecord prefs = { DEFAULT_ARGS, DEFAULT_VIDEO_DRIVER, DEFAULT_OUTPUT_TO_FILE };
363
364#if !(defined(__APPLE__) && defined(__MACH__))
365 int nargs;
366 char **args;
367 char *commandLine;
368
369 StrFileName appNameText;
370#endif
371 int videodriver = VIDEO_ID_TOOLBOX;
372 int settingsChanged = 0;
373
374 long i;
375
376 /* Kyle's SDL command-line dialog code ... */
377#if !TARGET_API_MAC_CARBON
378 InitGraf (&qd.thePort);
379 InitFonts ();
380 InitWindows ();
381 InitMenus ();
382 InitDialogs (nil);
383#endif
384 InitCursor ();
385 FlushEvents(everyEvent,0);
386#if !TARGET_API_MAC_CARBON
387 MaxApplZone ();
388#endif
389 MoreMasters ();
390 MoreMasters ();
391#if 0
392 /* Intialize SDL, and put up a dialog if we fail */
393 if ( SDL_Init (0) < 0 ) {
394
395#define kErr_OK 1
396#define kErr_Text 2
397
398 DialogPtr errorDialog;
399 short dummyType;
400 Rect dummyRect;
401 Handle dummyHandle;
402 short itemHit;
403
404 errorDialog = GetNewDialog (1001, nil, (WindowPtr)-1);
405 if (errorDialog == NULL)
406 return -1;
407 DrawDialog (errorDialog);
408
409 GetDialogItem (errorDialog, kErr_Text, &dummyType, &dummyHandle, &dummyRect);
410 SetDialogItemText (dummyHandle, "\pError Initializing SDL");
411
412#if TARGET_API_MAC_CARBON
413 SetPort (GetDialogPort(errorDialog));
414#else
415 SetPort (errorDialog);
416#endif
417 do {
418 ModalDialog (nil, &itemHit);
419 } while (itemHit != kErr_OK);
420
421 DisposeDialog (errorDialog);
422 exit (-1);
423 }
424 atexit(cleanup_output);
425 atexit(SDL_Quit);
426#endif
427
428/* Set up SDL's QuickDraw environment */
429#if !TARGET_API_MAC_CARBON
430 SDL_InitQuickDraw(&qd);
431#endif
432
433 if ( readPreferences (&prefs) ) {
434
435 if (SDL_memcmp(prefs.video_driver_name+1, "DSp", 3) == 0)
436 videodriver = 1;
437 else if (SDL_memcmp(prefs.video_driver_name+1, "toolbox", 7) == 0)
438 videodriver = 2;
439 }
440
441 if ( CommandKeyIsDown() ) {
442
443#define kCL_OK 1
444#define kCL_Cancel 2
445#define kCL_Text 3
446#define kCL_File 4
447#define kCL_Video 6
448
449 DialogPtr commandDialog;
450 short dummyType;
451 Rect dummyRect;
452 Handle dummyHandle;
453 short itemHit;
454 #if TARGET_API_MAC_CARBON
455 ControlRef control;
456 #endif
457
458 /* Assume that they will change settings, rather than do exhaustive check */
459 settingsChanged = 1;
460
461 /* Create dialog and display it */
462 commandDialog = GetNewDialog (1000, nil, (WindowPtr)-1);
463 #if TARGET_API_MAC_CARBON
464 SetPort ( GetDialogPort(commandDialog) );
465 #else
466 SetPort (commandDialog);
467 #endif
468
469 /* Setup controls */
470 #if TARGET_API_MAC_CARBON
471 GetDialogItemAsControl(commandDialog, kCL_File, &control);
472 SetControlValue (control, prefs.output_to_file);
473 #else
474 GetDialogItem (commandDialog, kCL_File, &dummyType, &dummyHandle, &dummyRect); /* MJS */
475 SetControlValue ((ControlHandle)dummyHandle, prefs.output_to_file );
476 #endif
477
478 GetDialogItem (commandDialog, kCL_Text, &dummyType, &dummyHandle, &dummyRect);
479 SetDialogItemText (dummyHandle, prefs.command_line);
480
481 #if TARGET_API_MAC_CARBON
482 GetDialogItemAsControl(commandDialog, kCL_Video, &control);
483 SetControlValue (control, videodriver);
484 #else
485 GetDialogItem (commandDialog, kCL_Video, &dummyType, &dummyHandle, &dummyRect);
486 SetControlValue ((ControlRef)dummyHandle, videodriver);
487 #endif
488
489 SetDialogDefaultItem (commandDialog, kCL_OK);
490 SetDialogCancelItem (commandDialog, kCL_Cancel);
491
492 do {
493
494 ModalDialog(nil, &itemHit); /* wait for user response */
495
496 /* Toggle command-line output checkbox */
497 if ( itemHit == kCL_File ) {
498 #if TARGET_API_MAC_CARBON
499 GetDialogItemAsControl(commandDialog, kCL_File, &control);
500 SetControlValue (control, !GetControlValue(control));
501 #else
502 GetDialogItem(commandDialog, kCL_File, &dummyType, &dummyHandle, &dummyRect); /* MJS */
503 SetControlValue((ControlHandle)dummyHandle, !GetControlValue((ControlHandle)dummyHandle) );
504 #endif
505 }
506
507 } while (itemHit != kCL_OK && itemHit != kCL_Cancel);
508
509 /* Get control values, even if they did not change */
510 GetDialogItem (commandDialog, kCL_Text, &dummyType, &dummyHandle, &dummyRect); /* MJS */
511 GetDialogItemText (dummyHandle, prefs.command_line);
512
513 #if TARGET_API_MAC_CARBON
514 GetDialogItemAsControl(commandDialog, kCL_File, &control);
515 prefs.output_to_file = GetControlValue(control);
516 #else
517 GetDialogItem (commandDialog, kCL_File, &dummyType, &dummyHandle, &dummyRect); /* MJS */
518 prefs.output_to_file = GetControlValue ((ControlHandle)dummyHandle);
519 #endif
520
521 #if TARGET_API_MAC_CARBON
522 GetDialogItemAsControl(commandDialog, kCL_Video, &control);
523 videodriver = GetControlValue(control);
524 #else
525 GetDialogItem (commandDialog, kCL_Video, &dummyType, &dummyHandle, &dummyRect);
526 videodriver = GetControlValue ((ControlRef)dummyHandle);
527 #endif
528
529 DisposeDialog (commandDialog);
530
531 if (itemHit == kCL_Cancel ) {
532 exit (0);
533 }
534 }
535
536 /* Set pseudo-environment variables for video driver, update prefs */
537 switch ( videodriver ) {
538 case VIDEO_ID_DRAWSPROCKET:
539 SDL_putenv("SDL_VIDEODRIVER=DSp");
540 SDL_memcpy(prefs.video_driver_name, "\pDSp", 4);
541 break;
542 case VIDEO_ID_TOOLBOX:
543 SDL_putenv("SDL_VIDEODRIVER=toolbox");
544 SDL_memcpy(prefs.video_driver_name, "\ptoolbox", 8);
545 break;
546 }
547
548#if !(defined(__APPLE__) && defined(__MACH__))
549 /* Redirect standard I/O to files */
550 if ( prefs.output_to_file ) {
551 freopen (STDOUT_FILE, "w", stdout);
552 freopen (STDERR_FILE, "w", stderr);
553 } else {
554 fclose (stdout);
555 fclose (stderr);
556 }
557#endif
558
559 if (settingsChanged) {
560 /* Save the prefs, even if they might not have changed (but probably did) */
561 if ( ! writePreferences (&prefs) )
562 fprintf (stderr, "WARNING: Could not save preferences!\n");
563 }
564
565#if !(defined(__APPLE__) && defined(__MACH__))
566 appNameText[0] = 0;
567 getCurrentAppName (appNameText); /* check for error here ? */
568
569 commandLine = (char*) malloc (appNameText[0] + prefs.command_line[0] + 2);
570 if ( commandLine == NULL ) {
571 exit(-1);
572 }
573
574 /* Rather than rewrite ParseCommandLine method, let's replace */
575 /* any spaces in application name with underscores, */
576 /* so that the app name is only 1 argument */
577 for (i = 1; i < 1+appNameText[0]; i++)
578 if ( appNameText[i] == ' ' ) appNameText[i] = '_';
579
580 /* Copy app name & full command text to command-line C-string */
581 SDL_memcpy(commandLine, appNameText + 1, appNameText[0]);
582 commandLine[appNameText[0]] = ' ';
583 SDL_memcpy(commandLine + appNameText[0] + 1, prefs.command_line + 1, prefs.command_line[0]);
584 commandLine[ appNameText[0] + 1 + prefs.command_line[0] ] = '\0';
585
586 /* Parse C-string into argv and argc */
587 nargs = ParseCommandLine (commandLine, NULL);
588 args = (char **)malloc((nargs+1)*(sizeof *args));
589 if ( args == NULL ) {
590 exit(-1);
591 }
592 ParseCommandLine (commandLine, args);
593
594 /* Run the main application code */
595 SDL_main(nargs, args);
596 free (args);
597 free (commandLine);
598
599 /* Remove useless stdout.txt and stderr.txt */
600 cleanup_output ();
601#else // defined(__APPLE__) && defined(__MACH__)
602 SDL_main(argc, argv);
603#endif
604
605 /* Exit cleanly, calling atexit() functions */
606 exit (0);
607
608 /* Never reached, but keeps the compiler quiet */
609 return (0);
610}
diff --git a/apps/plugins/sdl/src/main/macos/SIZE.r b/apps/plugins/sdl/src/main/macos/SIZE.r
deleted file mode 100644
index 940f37fc7f..0000000000
--- a/apps/plugins/sdl/src/main/macos/SIZE.r
+++ /dev/null
@@ -1 +0,0 @@
1 #include "Processes.r" resource 'SIZE' (-1) { reserved, acceptSuspendResumeEvents, reserved, canBackground, doesActivateOnFGSwitch, backgroundAndForeground, getFrontClicks, ignoreAppDiedEvents, is32BitCompatible, isHighLevelEventAware, onlyLocalHLEvents, notStationeryAware, useTextEditServices, reserved, reserved, reserved, 5242880, // 5 megs minimum 5242880 // 5 megs maximum }; \ No newline at end of file
diff --git a/apps/plugins/sdl/src/main/macos/exports/Makefile b/apps/plugins/sdl/src/main/macos/exports/Makefile
deleted file mode 100644
index 5f37ae0760..0000000000
--- a/apps/plugins/sdl/src/main/macos/exports/Makefile
+++ /dev/null
@@ -1,39 +0,0 @@
1
2EXPORTS = SDL.x
3HEADERS = \
4 ../../../../include/SDL.h \
5 ../../../../include/SDL_active.h \
6 ../../../../include/SDL_audio.h \
7 ../../../../include/SDL_byteorder.h \
8 ../../../../include/SDL_cdrom.h \
9 ../../../../include/SDL_copying.h \
10 ../../../../include/SDL_cpuinfo.h \
11 ../../../../include/SDL_endian.h \
12 ../../../../include/SDL_error.h \
13 ../../../../include/SDL_events.h \
14 ../../../../include/SDL_getenv.h \
15 ../../../../include/SDL_joystick.h \
16 ../../../../include/SDL_keyboard.h \
17 ../../../../include/SDL_keysym.h \
18 ../../../../include/SDL_loadso.h \
19 ../../../../include/SDL_mouse.h \
20 ../../../../include/SDL_mutex.h \
21 ../../../../include/SDL_name.h \
22 ../../../../include/SDL_platform.h \
23 ../../../../include/SDL_quit.h \
24 ../../../../include/SDL_rwops.h \
25 ../../../../include/SDL_syswm.h \
26 ../../../../include/SDL_thread.h \
27 ../../../../include/SDL_timer.h \
28 ../../../../include/SDL_types.h \
29 ../../../../include/SDL_version.h \
30 ../../../../include/SDL_video.h
31
32
33all: $(EXPORTS)
34
35$(EXPORTS): Makefile gendef.pl $(HEADERS)
36 perl gendef.pl $(HEADERS) >$@ || rm $@
37
38clean:
39 rm -f $(EXPORTS)
diff --git a/apps/plugins/sdl/src/main/macos/exports/SDL.x b/apps/plugins/sdl/src/main/macos/exports/SDL.x
deleted file mode 100644
index 4830c43e93..0000000000
--- a/apps/plugins/sdl/src/main/macos/exports/SDL.x
+++ /dev/null
@@ -1 +0,0 @@
1 SDL_Init SDL_InitSubSystem SDL_QuitSubSystem SDL_WasInit SDL_Quit SDL_GetAppState SDL_AudioInit SDL_AudioQuit SDL_AudioDriverName SDL_OpenAudio SDL_GetAudioStatus SDL_PauseAudio SDL_LoadWAV_RW SDL_FreeWAV SDL_BuildAudioCVT SDL_ConvertAudio SDL_MixAudio SDL_LockAudio SDL_UnlockAudio SDL_CloseAudio SDL_CDNumDrives SDL_CDName SDL_CDOpen SDL_CDStatus SDL_CDPlayTracks SDL_CDPlay SDL_CDPause SDL_CDResume SDL_CDStop SDL_CDEject SDL_CDClose SDL_HasRDTSC SDL_HasMMX SDL_HasMMXExt SDL_Has3DNow SDL_Has3DNowExt SDL_HasSSE SDL_HasSSE2 SDL_HasAltiVec SDL_SetError SDL_GetError SDL_ClearError SDL_Error SDL_PumpEvents SDL_PeepEvents SDL_PollEvent SDL_WaitEvent SDL_PushEvent SDL_SetEventFilter SDL_GetEventFilter SDL_EventState SDL_NumJoysticks SDL_JoystickName SDL_JoystickOpen SDL_JoystickOpened SDL_JoystickIndex SDL_JoystickNumAxes SDL_JoystickNumBalls SDL_JoystickNumHats SDL_JoystickNumButtons SDL_JoystickUpdate SDL_JoystickEventState SDL_JoystickGetAxis SDL_JoystickGetHat SDL_JoystickGetBall SDL_JoystickGetButton SDL_JoystickClose SDL_EnableUNICODE SDL_EnableKeyRepeat SDL_GetKeyRepeat SDL_GetKeyState SDL_GetModState SDL_SetModState SDL_GetKeyName SDL_LoadObject SDL_LoadFunction SDL_UnloadObject SDL_GetMouseState SDL_GetRelativeMouseState SDL_WarpMouse SDL_CreateCursor SDL_SetCursor SDL_GetCursor SDL_FreeCursor SDL_ShowCursor SDL_CreateMutex SDL_mutexP SDL_mutexV SDL_DestroyMutex SDL_CreateSemaphore SDL_DestroySemaphore SDL_SemWait SDL_SemTryWait SDL_SemWaitTimeout SDL_SemPost SDL_SemValue SDL_CreateCond SDL_DestroyCond SDL_CondSignal SDL_CondBroadcast SDL_CondWait SDL_CondWaitTimeout SDL_RWFromFile SDL_RWFromFP SDL_RWFromMem SDL_RWFromConstMem SDL_AllocRW SDL_FreeRW SDL_ReadLE16 SDL_ReadBE16 SDL_ReadLE32 SDL_ReadBE32 SDL_ReadLE64 SDL_ReadBE64 SDL_WriteLE16 SDL_WriteBE16 SDL_WriteLE32 SDL_WriteBE32 SDL_WriteLE64 SDL_WriteBE64 SDL_GetWMInfo SDL_CreateThread SDL_CreateThread SDL_ThreadID SDL_GetThreadID SDL_WaitThread SDL_KillThread SDL_GetTicks SDL_Delay SDL_SetTimer SDL_AddTimer SDL_RemoveTimer SDL_Linked_Version SDL_VideoInit SDL_VideoQuit SDL_VideoDriverName SDL_GetVideoSurface SDL_GetVideoInfo SDL_VideoModeOK SDL_ListModes SDL_SetVideoMode SDL_UpdateRects SDL_UpdateRect SDL_Flip SDL_SetGamma SDL_SetGammaRamp SDL_GetGammaRamp SDL_SetColors SDL_SetPalette SDL_MapRGB SDL_MapRGBA SDL_GetRGB SDL_GetRGBA SDL_CreateRGBSurface SDL_CreateRGBSurfaceFrom SDL_FreeSurface SDL_LockSurface SDL_UnlockSurface SDL_LoadBMP_RW SDL_SaveBMP_RW SDL_SetColorKey SDL_SetAlpha SDL_SetClipRect SDL_GetClipRect SDL_ConvertSurface SDL_UpperBlit SDL_LowerBlit SDL_FillRect SDL_DisplayFormat SDL_DisplayFormatAlpha SDL_CreateYUVOverlay SDL_LockYUVOverlay SDL_UnlockYUVOverlay SDL_DisplayYUVOverlay SDL_FreeYUVOverlay SDL_GL_LoadLibrary SDL_GL_GetProcAddress SDL_GL_SetAttribute SDL_GL_GetAttribute SDL_GL_SwapBuffers SDL_GL_UpdateRects SDL_GL_Lock SDL_GL_Unlock SDL_WM_SetCaption SDL_WM_GetCaption SDL_WM_SetIcon SDL_WM_IconifyWindow SDL_WM_ToggleFullScreen SDL_WM_GrabInput SDL_SoftStretch SDL_putenv SDL_getenv SDL_qsort SDL_revcpy SDL_strlcpy SDL_strlcat SDL_strdup SDL_strrev SDL_strupr SDL_strlwr SDL_ltoa SDL_ultoa SDL_strcasecmp SDL_strncasecmp SDL_snprintf SDL_vsnprintf SDL_iconv SDL_iconv_string SDL_InitQuickDraw \ No newline at end of file
diff --git a/apps/plugins/sdl/src/main/macos/exports/gendef.pl b/apps/plugins/sdl/src/main/macos/exports/gendef.pl
deleted file mode 100644
index 9cffca92aa..0000000000
--- a/apps/plugins/sdl/src/main/macos/exports/gendef.pl
+++ /dev/null
@@ -1,43 +0,0 @@
1#!/usr/bin/perl
2#
3# Program to take a set of header files and generate DLL export definitions
4
5# Special exports to ignore for this platform
6
7while ( ($file = shift(@ARGV)) ) {
8 if ( ! defined(open(FILE, $file)) ) {
9 warn "Couldn't open $file: $!\n";
10 next;
11 }
12 $printed_header = 0;
13 $file =~ s,.*/,,;
14 while (<FILE>) {
15 if ( / DECLSPEC.* SDLCALL ([^\s\(]+)/ ) {
16 if ( not $exclude{$1} ) {
17 print "\t$1\r";
18 }
19 }
20 }
21 close(FILE);
22}
23
24# Special exports to include for this platform
25print "\tSDL_putenv\r";
26print "\tSDL_getenv\r";
27print "\tSDL_qsort\r";
28print "\tSDL_revcpy\r";
29print "\tSDL_strlcpy\r";
30print "\tSDL_strlcat\r";
31print "\tSDL_strdup\r";
32print "\tSDL_strrev\r";
33print "\tSDL_strupr\r";
34print "\tSDL_strlwr\r";
35print "\tSDL_ltoa\r";
36print "\tSDL_ultoa\r";
37print "\tSDL_strcasecmp\r";
38print "\tSDL_strncasecmp\r";
39print "\tSDL_snprintf\r";
40print "\tSDL_vsnprintf\r";
41print "\tSDL_iconv\r";
42print "\tSDL_iconv_string\r";
43print "\tSDL_InitQuickDraw\r";
diff --git a/apps/plugins/sdl/src/main/macosx/Info.plist.in b/apps/plugins/sdl/src/main/macosx/Info.plist.in
deleted file mode 100644
index b3d69abac9..0000000000
--- a/apps/plugins/sdl/src/main/macosx/Info.plist.in
+++ /dev/null
@@ -1,24 +0,0 @@
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
3<plist version="0.9">
4<dict>
5 <key>CFBundleDevelopmentRegion</key>
6 <string>English</string>
7 <key>CFBundleExecutable</key>
8 <string>@EXECUTABLE_NAME@</string>
9 <key>CFBundleInfoDictionaryVersion</key>
10 <string>6.0</string>
11 <key>CFBundleName</key>
12 <string>@PACKAGE@</string>
13 <key>CFBundlePackageType</key>
14 <string>APPL</string>
15 <key>CFBundleShortVersionString</key>
16 <string>@VERSION@</string>
17 <key>CFBundleSignature</key>
18 <string>????</string>
19 <key>NSMainNibFile</key>
20 <string>SDLMain.nib</string>
21 <key>NSPrincipalClass</key>
22 <string>NSApplication</string>
23</dict>
24</plist>
diff --git a/apps/plugins/sdl/src/main/macosx/SDLMain.h b/apps/plugins/sdl/src/main/macosx/SDLMain.h
deleted file mode 100644
index c56d90cbe8..0000000000
--- a/apps/plugins/sdl/src/main/macosx/SDLMain.h
+++ /dev/null
@@ -1,16 +0,0 @@
1/* SDLMain.m - main entry point for our Cocoa-ized SDL app
2 Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
3 Non-NIB-Code & other changes: Max Horn <max@quendi.de>
4
5 Feel free to customize this file to suit your needs
6*/
7
8#ifndef _SDLMain_h_
9#define _SDLMain_h_
10
11#import <Cocoa/Cocoa.h>
12
13@interface SDLMain : NSObject
14@end
15
16#endif /* _SDLMain_h_ */
diff --git a/apps/plugins/sdl/src/main/macosx/SDLMain.m b/apps/plugins/sdl/src/main/macosx/SDLMain.m
deleted file mode 100644
index 2434f81aa9..0000000000
--- a/apps/plugins/sdl/src/main/macosx/SDLMain.m
+++ /dev/null
@@ -1,381 +0,0 @@
1/* SDLMain.m - main entry point for our Cocoa-ized SDL app
2 Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
3 Non-NIB-Code & other changes: Max Horn <max@quendi.de>
4
5 Feel free to customize this file to suit your needs
6*/
7
8#include "SDL.h"
9#include "SDLMain.h"
10#include <sys/param.h> /* for MAXPATHLEN */
11#include <unistd.h>
12
13/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
14 but the method still is there and works. To avoid warnings, we declare
15 it ourselves here. */
16@interface NSApplication(SDL_Missing_Methods)
17- (void)setAppleMenu:(NSMenu *)menu;
18@end
19
20/* Use this flag to determine whether we use SDLMain.nib or not */
21#define SDL_USE_NIB_FILE 0
22
23/* Use this flag to determine whether we use CPS (docking) or not */
24#define SDL_USE_CPS 1
25#ifdef SDL_USE_CPS
26/* Portions of CPS.h */
27typedef struct CPSProcessSerNum
28{
29 UInt32 lo;
30 UInt32 hi;
31} CPSProcessSerNum;
32
33extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn);
34extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
35extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn);
36
37#endif /* SDL_USE_CPS */
38
39static int gArgc;
40static char **gArgv;
41static BOOL gFinderLaunch;
42static BOOL gCalledAppMainline = FALSE;
43
44static NSString *getApplicationName(void)
45{
46 const NSDictionary *dict;
47 NSString *appName = 0;
48
49 /* Determine the application name */
50 dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
51 if (dict)
52 appName = [dict objectForKey: @"CFBundleName"];
53
54 if (![appName length])
55 appName = [[NSProcessInfo processInfo] processName];
56
57 return appName;
58}
59
60#if SDL_USE_NIB_FILE
61/* A helper category for NSString */
62@interface NSString (ReplaceSubString)
63- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
64@end
65#endif
66
67@interface NSApplication (SDLApplication)
68@end
69
70@implementation NSApplication (SDLApplication)
71/* Invoked from the Quit menu item */
72- (void)terminate:(id)sender
73{
74 /* Post a SDL_QUIT event */
75 SDL_Event event;
76 event.type = SDL_QUIT;
77 SDL_PushEvent(&event);
78}
79@end
80
81/* The main class of the application, the application's delegate */
82@implementation SDLMain
83
84/* Set the working directory to the .app's parent directory */
85- (void) setupWorkingDirectory:(BOOL)shouldChdir
86{
87 if (shouldChdir)
88 {
89 char parentdir[MAXPATHLEN];
90 CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
91 CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
92 if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) {
93 chdir(parentdir); /* chdir to the binary app's parent */
94 }
95 CFRelease(url);
96 CFRelease(url2);
97 }
98}
99
100#if SDL_USE_NIB_FILE
101
102/* Fix menu to contain the real app name instead of "SDL App" */
103- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
104{
105 NSRange aRange;
106 NSEnumerator *enumerator;
107 NSMenuItem *menuItem;
108
109 aRange = [[aMenu title] rangeOfString:@"SDL App"];
110 if (aRange.length != 0)
111 [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
112
113 enumerator = [[aMenu itemArray] objectEnumerator];
114 while ((menuItem = [enumerator nextObject]))
115 {
116 aRange = [[menuItem title] rangeOfString:@"SDL App"];
117 if (aRange.length != 0)
118 [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
119 if ([menuItem hasSubmenu])
120 [self fixMenu:[menuItem submenu] withAppName:appName];
121 }
122}
123
124#else
125
126static void setApplicationMenu(void)
127{
128 /* warning: this code is very odd */
129 NSMenu *appleMenu;
130 NSMenuItem *menuItem;
131 NSString *title;
132 NSString *appName;
133
134 appName = getApplicationName();
135 appleMenu = [[NSMenu alloc] initWithTitle:@""];
136
137 /* Add menu items */
138 title = [@"About " stringByAppendingString:appName];
139 [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
140
141 [appleMenu addItem:[NSMenuItem separatorItem]];
142
143 title = [@"Hide " stringByAppendingString:appName];
144 [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
145
146 menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
147 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
148
149 [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
150
151 [appleMenu addItem:[NSMenuItem separatorItem]];
152
153 title = [@"Quit " stringByAppendingString:appName];
154 [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
155
156
157 /* Put menu into the menubar */
158 menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
159 [menuItem setSubmenu:appleMenu];
160 [[NSApp mainMenu] addItem:menuItem];
161
162 /* Tell the application object that this is now the application menu */
163 [NSApp setAppleMenu:appleMenu];
164
165 /* Finally give up our references to the objects */
166 [appleMenu release];
167 [menuItem release];
168}
169
170/* Create a window menu */
171static void setupWindowMenu(void)
172{
173 NSMenu *windowMenu;
174 NSMenuItem *windowMenuItem;
175 NSMenuItem *menuItem;
176
177 windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
178
179 /* "Minimize" item */
180 menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
181 [windowMenu addItem:menuItem];
182 [menuItem release];
183
184 /* Put menu into the menubar */
185 windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
186 [windowMenuItem setSubmenu:windowMenu];
187 [[NSApp mainMenu] addItem:windowMenuItem];
188
189 /* Tell the application object that this is now the window menu */
190 [NSApp setWindowsMenu:windowMenu];
191
192 /* Finally give up our references to the objects */
193 [windowMenu release];
194 [windowMenuItem release];
195}
196
197/* Replacement for NSApplicationMain */
198static void CustomApplicationMain (int argc, char **argv)
199{
200 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
201 SDLMain *sdlMain;
202
203 /* Ensure the application object is initialised */
204 [NSApplication sharedApplication];
205
206#ifdef SDL_USE_CPS
207 {
208 CPSProcessSerNum PSN;
209 /* Tell the dock about us */
210 if (!CPSGetCurrentProcess(&PSN))
211 if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
212 if (!CPSSetFrontProcess(&PSN))
213 [NSApplication sharedApplication];
214 }
215#endif /* SDL_USE_CPS */
216
217 /* Set up the menubar */
218 [NSApp setMainMenu:[[NSMenu alloc] init]];
219 setApplicationMenu();
220 setupWindowMenu();
221
222 /* Create SDLMain and make it the app delegate */
223 sdlMain = [[SDLMain alloc] init];
224 [NSApp setDelegate:sdlMain];
225
226 /* Start the main event loop */
227 [NSApp run];
228
229 [sdlMain release];
230 [pool release];
231}
232
233#endif
234
235
236/*
237 * Catch document open requests...this lets us notice files when the app
238 * was launched by double-clicking a document, or when a document was
239 * dragged/dropped on the app's icon. You need to have a
240 * CFBundleDocumentsType section in your Info.plist to get this message,
241 * apparently.
242 *
243 * Files are added to gArgv, so to the app, they'll look like command line
244 * arguments. Previously, apps launched from the finder had nothing but
245 * an argv[0].
246 *
247 * This message may be received multiple times to open several docs on launch.
248 *
249 * This message is ignored once the app's mainline has been called.
250 */
251- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
252{
253 const char *temparg;
254 size_t arglen;
255 char *arg;
256 char **newargv;
257
258 if (!gFinderLaunch) /* MacOS is passing command line args. */
259 return FALSE;
260
261 if (gCalledAppMainline) /* app has started, ignore this document. */
262 return FALSE;
263
264 temparg = [filename UTF8String];
265 arglen = SDL_strlen(temparg) + 1;
266 arg = (char *) SDL_malloc(arglen);
267 if (arg == NULL)
268 return FALSE;
269
270 newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));
271 if (newargv == NULL)
272 {
273 SDL_free(arg);
274 return FALSE;
275 }
276 gArgv = newargv;
277
278 SDL_strlcpy(arg, temparg, arglen);
279 gArgv[gArgc++] = arg;
280 gArgv[gArgc] = NULL;
281 return TRUE;
282}
283
284
285/* Called when the internal event loop has just started running */
286- (void) applicationDidFinishLaunching: (NSNotification *) note
287{
288 int status;
289
290 /* Set the working directory to the .app's parent directory */
291 [self setupWorkingDirectory:gFinderLaunch];
292
293#if SDL_USE_NIB_FILE
294 /* Set the main menu to contain the real app name instead of "SDL App" */
295 [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
296#endif
297
298 /* Hand off to main application code */
299 gCalledAppMainline = TRUE;
300 status = SDL_main (gArgc, gArgv);
301
302 /* We're done, thank you for playing */
303 exit(status);
304}
305@end
306
307
308@implementation NSString (ReplaceSubString)
309
310- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
311{
312 unsigned int bufferSize;
313 unsigned int selfLen = [self length];
314 unsigned int aStringLen = [aString length];
315 unichar *buffer;
316 NSRange localRange;
317 NSString *result;
318
319 bufferSize = selfLen + aStringLen - aRange.length;
320 buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar));
321
322 /* Get first part into buffer */
323 localRange.location = 0;
324 localRange.length = aRange.location;
325 [self getCharacters:buffer range:localRange];
326
327 /* Get middle part into buffer */
328 localRange.location = 0;
329 localRange.length = aStringLen;
330 [aString getCharacters:(buffer+aRange.location) range:localRange];
331
332 /* Get last part into buffer */
333 localRange.location = aRange.location + aRange.length;
334 localRange.length = selfLen - localRange.location;
335 [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
336
337 /* Build output string */
338 result = [NSString stringWithCharacters:buffer length:bufferSize];
339
340 NSDeallocateMemoryPages(buffer, bufferSize);
341
342 return result;
343}
344
345@end
346
347
348
349#ifdef main
350# undef main
351#endif
352
353
354/* Main entry point to executable - should *not* be SDL_main! */
355int main (int argc, char **argv)
356{
357 /* Copy the arguments into a global variable */
358 /* This is passed if we are launched by double-clicking */
359 if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
360 gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
361 gArgv[0] = argv[0];
362 gArgv[1] = NULL;
363 gArgc = 1;
364 gFinderLaunch = YES;
365 } else {
366 int i;
367 gArgc = argc;
368 gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
369 for (i = 0; i <= argc; i++)
370 gArgv[i] = argv[i];
371 gFinderLaunch = NO;
372 }
373
374#if SDL_USE_NIB_FILE
375 NSApplicationMain (argc, argv);
376#else
377 CustomApplicationMain (argc, argv);
378#endif
379 return 0;
380}
381
diff --git a/apps/plugins/sdl/src/main/macosx/SDLMain.nib/classes.nib b/apps/plugins/sdl/src/main/macosx/SDLMain.nib/classes.nib
deleted file mode 100644
index f8f4e9a4b9..0000000000
--- a/apps/plugins/sdl/src/main/macosx/SDLMain.nib/classes.nib
+++ /dev/null
@@ -1,12 +0,0 @@
1{
2 IBClasses = (
3 {CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
4 {
5 ACTIONS = {makeFullscreen = id; quit = id; };
6 CLASS = SDLMain;
7 LANGUAGE = ObjC;
8 SUPERCLASS = NSObject;
9 }
10 );
11 IBVersion = 1;
12}
diff --git a/apps/plugins/sdl/src/main/macosx/SDLMain.nib/info.nib b/apps/plugins/sdl/src/main/macosx/SDLMain.nib/info.nib
deleted file mode 100644
index 2211cf9d75..0000000000
--- a/apps/plugins/sdl/src/main/macosx/SDLMain.nib/info.nib
+++ /dev/null
@@ -1,12 +0,0 @@
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
3<plist version="0.9">
4<dict>
5 <key>IBDocumentLocation</key>
6 <string>49 97 356 240 0 0 987 746 </string>
7 <key>IBMainMenuLocation</key>
8 <string>20 515 195 44 0 46 800 532 </string>
9 <key>IBUserGuides</key>
10 <dict/>
11</dict>
12</plist>
diff --git a/apps/plugins/sdl/src/main/macosx/SDLMain.nib/objects.nib b/apps/plugins/sdl/src/main/macosx/SDLMain.nib/objects.nib
deleted file mode 100644
index 9f697b0ee7..0000000000
--- a/apps/plugins/sdl/src/main/macosx/SDLMain.nib/objects.nib
+++ /dev/null
Binary files differ
diff --git a/apps/plugins/sdl/src/main/macosx/info.nib b/apps/plugins/sdl/src/main/macosx/info.nib
deleted file mode 100644
index d13726f807..0000000000
--- a/apps/plugins/sdl/src/main/macosx/info.nib
+++ /dev/null
@@ -1 +0,0 @@
1// This is just a stub file to force automake to create the install directory
diff --git a/apps/plugins/sdl/src/main/qtopia/SDL_qtopia_main.cc b/apps/plugins/sdl/src/main/qtopia/SDL_qtopia_main.cc
deleted file mode 100644
index 46fd518ff0..0000000000
--- a/apps/plugins/sdl/src/main/qtopia/SDL_qtopia_main.cc
+++ /dev/null
@@ -1,47 +0,0 @@
1
2/* Include the SDL main definition header */
3#include "SDL_main.h"
4#include <stdlib.h>
5#include <unistd.h>
6#ifdef main
7#undef main
8#endif
9#ifdef QWS
10#include <qpe/qpeapplication.h>
11#include <qapplication.h>
12#include <qpe/qpeapplication.h>
13#include <stdlib.h>
14
15// Workaround for OPIE to remove taskbar icon. Also fixes
16// some issues in Qtopia where there are left-over qcop files in /tmp/.
17// I'm guessing this will also clean up the taskbar in the Sharp version
18// of Qtopia.
19static inline void cleanupQCop() {
20 QString appname(qApp->argv()[0]);
21 int slash = appname.findRev("/");
22 if(slash != -1) { appname = appname.mid(slash+1); }
23 QString cmd = QPEApplication::qpeDir() + "bin/qcop QPE/System 'closing(QString)' '"+appname+"'";
24 system(cmd.latin1());
25 cmd = "/tmp/qcop-msg-"+appname;
26 unlink(cmd.latin1());
27}
28
29static QPEApplication *app;
30#endif
31
32extern int SDL_main(int argc, char *argv[]);
33
34int main(int argc, char *argv[])
35{
36#ifdef QWS
37 // This initializes the Qtopia application. It needs to be done here
38 // because it parses command line options.
39 app = new QPEApplication(argc, argv);
40 QWidget dummy;
41 app->showMainWidget(&dummy);
42 atexit(cleanupQCop);
43#endif
44 // Exit here because if return is used, the application
45 // doesn't seem to quit correctly.
46 exit(SDL_main(argc, argv));
47}
diff --git a/apps/plugins/sdl/src/main/symbian/EKA1/SDL_main.cpp b/apps/plugins/sdl/src/main/symbian/EKA1/SDL_main.cpp
deleted file mode 100644
index 683db874ff..0000000000
--- a/apps/plugins/sdl/src/main/symbian/EKA1/SDL_main.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_main.cpp
25 The Epoc executable startup functions
26
27 Epoc version by Hannu Viitala (hannu.j.viitala@mbnet.fi)
28*/
29
30#include <e32std.h>
31#include <e32def.h>
32#include <e32svr.h>
33#include <e32base.h>
34#include <estlib.h>
35#include <stdlib.h>
36#include <stdio.h>
37#include <w32std.h>
38#include <apgtask.h>
39
40#include "SDL_error.h"
41
42#if defined(__WINS__)
43#include <estw32.h>
44IMPORT_C void RegisterWsExe(const TDesC &aName);
45#endif
46
47/* The prototype for the application's main() function */
48#define main SDL_main
49extern "C" int main (int argc, char *argv[], char *envp[]);
50extern "C" void exit (int ret);
51
52
53/* Epoc main function */
54
55#ifdef __WINS__
56
57
58void GetCmdLine(int& aArgc, char**& aArgv)
59 {
60 RChunk chunk;
61
62 if(chunk.OpenGlobal(RThread().Name(), ETrue) != KErrNone)
63 return;
64
65 TUint* ptr = (TUint*) chunk.Base();
66 if(ptr != NULL)
67 {
68 aArgc = (int) *(ptr); // count
69 aArgv = (char**) *(ptr + 1);
70 }
71 chunk.Close();
72 }
73
74#endif
75
76
77TInt E32Main()
78 {
79 /* Get the clean-up stack */
80 CTrapCleanup* cleanup = CTrapCleanup::New();
81
82 /* Arrange for multi-threaded operation */
83 SpawnPosixServerThread();
84
85 /* Get args and environment */
86 int argc=0;
87 char** argv=0;
88 char** envp=0;
89
90#ifndef __WINS__
91 __crt0(argc,argv,envp);
92#else
93 GetCmdLine(argc, argv);
94#endif
95 /* Start the application! */
96
97 /* Create stdlib */
98 _REENT;
99
100 /* Set process and thread priority and name */
101
102 RThread currentThread;
103 RProcess thisProcess;
104 TParse exeName;
105 exeName.Set(thisProcess.FileName(), NULL, NULL);
106 currentThread.Rename(exeName.Name());
107 currentThread.SetProcessPriority(EPriorityLow);
108 currentThread.SetPriority(EPriorityMuchLess);
109
110 /* Call stdlib main */
111 int ret = main(argc, argv, envp); /* !! process exits here if there is "exit()" in main! */
112
113 /* Call exit */
114 //exit(ret); /* !! process exits here! */
115 //Markus: I do not understand above
116 //I commented it at let this function
117 //to return ret value - was it purpose
118 //that cleanup below is not called at all - why?
119
120 /* Free resources and return */
121
122 _cleanup(); //this is normally called at exit, I call it here, Markus
123
124 CloseSTDLIB();
125 delete cleanup;
126#ifdef __WINS__
127// User::Panic(_L("exit"), ret);
128 // RThread().Kill(ret); //Markus get rid of this thread
129 // RThread().RaiseException(EExcKill);
130#endif
131 return ret;//Markus, or exit(ret); ??
132 //return(KErrNone);
133 }
134
135
136#ifdef __WINS__
137EXPORT_C TInt WinsMain()
138 {
139 return E32Main();
140 // return WinsMain(0, 0, 0);
141 }
142#endif
143
144/* Epoc dll entry point */
145#if defined(__WINS__)
146GLDEF_C TInt E32Dll(TDllReason)
147 {
148 return(KErrNone);
149 }
150#endif
151
152
diff --git a/apps/plugins/sdl/src/main/symbian/EKA2/SDL_main.cpp b/apps/plugins/sdl/src/main/symbian/EKA2/SDL_main.cpp
deleted file mode 100644
index 3dc69d4aad..0000000000
--- a/apps/plugins/sdl/src/main/symbian/EKA2/SDL_main.cpp
+++ /dev/null
@@ -1,1035 +0,0 @@
1/*
2 SDL_Main.cpp
3 Symbian OS services for SDL
4
5 Markus Mertama
6*/
7
8
9#include "epoc_sdl.h"
10
11#include"sdlepocapi.h"
12#include <e32base.h>
13#include <estlib.h>
14#include <stdio.h>
15#include <badesca.h>
16
17#include "vectorbuffer.h"
18#include <w32std.h>
19#include <aknappui.h>
20#include <aknapp.h>
21#include "SDL_epocevents_c.h"
22#include "SDL_keysym.h"
23#include "dsa.h"
24
25
26#ifdef SYMBIANC
27#include <reent.h>
28#endif
29
30//Markus Mertama
31
32
33extern SDLKey* KeyMap();
34extern void ResetKeyMap();
35
36class CCurrentAppUi;
37
38//const TUid KSDLUid = { 0xF01F3D69 };
39
40NONSHARABLE_CLASS(EnvUtils)
41 {
42 public:
43 static void DisableKeyBlocking();
44 static TBool Rendezvous(RThread& aThread, TRequestStatus& aStatus);
45 };
46
47TInt Panic(TInt aErr, TInt aLine)
48 {
49 TBuf<64> b;
50 b.Format(_L("Main at %d"), aLine);
51 User::Panic(b, aErr);
52 return 0;
53 }
54
55
56NONSHARABLE_CLASS(CCurrentAppUi) : public CAknAppUi
57 {
58 public:
59 static CCurrentAppUi* Cast(CEikAppUi* aUi);
60 void DisableKeyBlocking();
61 };
62
63
64CCurrentAppUi* CCurrentAppUi::Cast(CEikAppUi* aUi)
65 {
66 return static_cast<CCurrentAppUi*>(aUi);
67 }
68
69void CCurrentAppUi::DisableKeyBlocking()
70 {
71 SetKeyBlockMode(ENoKeyBlock);
72 }
73
74
75class CEventQueue : public CBase, public MEventQueue
76 {
77 public:
78 static CEventQueue* NewL();
79 ~CEventQueue();
80 public:
81 TInt Append(const TWsEvent& aEvent);
82 const TWsEvent& Shift();
83 void Lock();
84 void Unlock();
85 TBool HasData();
86 private:
87 TVector<TWsEvent, 64> iVector;
88 RCriticalSection iCS;
89 };
90
91 CEventQueue* CEventQueue::NewL()
92 {
93 CEventQueue* q = new (ELeave) CEventQueue();
94 CleanupStack::PushL(q);
95 User::LeaveIfError(q->iCS.CreateLocal());
96 CleanupStack::Pop();
97 return q;
98 }
99
100CEventQueue::~CEventQueue()
101 {
102 iCS.Close();
103 }
104
105TInt CEventQueue::Append(const TWsEvent& aEvent)
106 {
107 iCS.Wait();
108 const TInt err = iVector.Append(aEvent);
109 iCS.Signal();
110 return err;
111 }
112
113
114TBool CEventQueue::HasData()
115 {
116 return iVector.Size() > 0;
117 }
118
119
120void CEventQueue::Lock()
121 {
122 iCS.Wait();
123 }
124
125void CEventQueue::Unlock()
126 {
127 iCS.Signal();
128 }
129
130const TWsEvent& CEventQueue::Shift()
131 {
132 const TWsEvent& event = iVector.Shift();
133 return event;
134 }
135
136
137TSdlCleanupItem::TSdlCleanupItem(TSdlCleanupOperation aOperation, TAny* aItem) :
138iOperation(aOperation), iItem(aItem), iThread(RThread().Id())
139 {
140 }
141
142class CEikonEnv;
143class CSdlAppServ;
144
145
146NONSHARABLE_CLASS(EpocSdlEnvData)
147 {
148 public:
149 void Free();
150 CEventQueue* iEventQueue;
151 TMainFunc iMain;
152 TInt iEpocEnvFlags;
153 int iArgc;
154 char** iArgv;
155 CDsa* iDsa;
156 CSdlAppServ* iAppSrv;
157 TThreadId iId;
158 CArrayFix<TSdlCleanupItem>* iCleanupItems;
159 CEikAppUi* iAppUi;
160 CSDL* iSdl;
161 };
162
163
164EpocSdlEnvData* gEpocEnv;
165
166#define MAINFUNC(x) EXPORT_C TMainFunc::TMainFunc(mainfunc##x aFunc){Mem::FillZ(iMainFunc, sizeof(iMainFunc)); iMainFunc[x - 1] = (void*) aFunc;}
167
168MAINFUNC(1)
169MAINFUNC(2)
170MAINFUNC(3)
171MAINFUNC(4)
172MAINFUNC(5)
173MAINFUNC(6)
174
175EXPORT_C TMainFunc::TMainFunc()
176 {
177 Mem::FillZ(iMainFunc, sizeof(iMainFunc));
178 }
179
180
181const void* TMainFunc::operator[](TInt aIndex) const
182 {
183 return iMainFunc[aIndex];
184 }
185
186
187NONSHARABLE_CLASS(CSdlAppServ) : public CActive
188 {
189 public:
190 enum
191 {
192 EAppSrvNoop = CDsa::ELastDsaRequest,
193 EAppSrvWindowWidth,
194 EAppSrvWindowHeight,
195 EAppSrvWindowDisplayMode,
196 EAppSrvWindowPointerCursorMode,
197 EAppSrvDsaStatus,
198 EAppSrvStopThread,
199 EAppSrvWaitDsa
200 };
201 CSdlAppServ();
202 void ConstructL();
203 ~CSdlAppServ();
204 TInt Request(TInt aService);
205 TInt RequestValue(TInt aService);
206 void Init();
207 void PanicMain(TInt aReason);
208 void PanicMain(const TDesC& aInfo, TInt aReason);
209 void SetObserver(MSDLObserver* aObserver);
210 TInt ObserverEvent(TInt aEvent, TInt aParam);
211 void SetParam(TInt aParam);
212 void HandleObserverValue(TInt aService, TInt aReturnValue, TBool aMainThread);
213 MSDLObserver* Observer();
214 private:
215 void RunL();
216 void DoCancel();
217 private:
218 const TThreadId iMainId;
219 RThread iAppThread;
220 TInt iService;
221 TInt iReturnValue;
222 RSemaphore iSema;
223 MSDLObserver* iObserver;
224 TRequestStatus* iStatusPtr;
225 };
226
227CSdlAppServ::CSdlAppServ() : CActive(CActive::EPriorityHigh), iMainId(RThread().Id())
228 {
229 }
230
231
232
233MSDLObserver* CSdlAppServ::Observer()
234 {
235 return iObserver;
236 }
237
238
239void CSdlAppServ::SetObserver(MSDLObserver* aObserver)
240 {
241 iObserver = aObserver;
242 }
243
244TInt CSdlAppServ::ObserverEvent(TInt aEvent, TInt aParam)
245 {
246 if(iObserver != NULL)
247 {
248 if(RThread().Id() == gEpocEnv->iId)
249 {
250 return iObserver->SdlThreadEvent(aEvent, aParam);
251 }
252 else if(RThread().Id() == iMainId)
253 {
254 return iObserver->SdlEvent(aEvent, aParam);
255 }
256 PANIC(KErrNotSupported);
257 }
258 return 0;
259 }
260
261void CSdlAppServ::PanicMain(TInt aReason)
262 {
263 iAppThread.Panic(RThread().Name(), aReason);
264 }
265
266void CSdlAppServ::PanicMain(const TDesC& aInfo, TInt aReason)
267 {
268 iAppThread.Panic(aInfo, aReason);
269 }
270
271void CSdlAppServ::ConstructL()
272 {
273 CActiveScheduler::Add(this);
274 User::LeaveIfError(iSema.CreateLocal(1));
275 iStatus = KRequestPending;
276 iStatusPtr = &iStatus;
277 SetActive();
278 }
279
280 CSdlAppServ::~CSdlAppServ()
281 {
282 Cancel();
283 if(iSema.Handle() != NULL)
284 iSema.Signal();
285 iSema.Close();
286 iAppThread.Close();
287 }
288
289TInt CSdlAppServ::Request(TInt aService)
290 {
291 if(RThread().Id() != iAppThread.Id())
292 {
293 iSema.Wait();
294 iService = aService;
295 iAppThread.RequestComplete(iStatusPtr, KErrNone);
296 return KErrNone;
297 }
298 return KErrBadHandle;
299 }
300
301TInt CSdlAppServ::RequestValue(TInt aService)
302 {
303 Request(aService);
304 Request(EAppSrvNoop);
305 return iReturnValue;
306 }
307
308void CSdlAppServ::Init()
309 {
310 PANIC_IF_ERROR(iAppThread.Open(iMainId));
311 }
312
313void CSdlAppServ::SetParam(TInt aParam)
314 {
315 iReturnValue = aParam;
316 }
317
318void CSdlAppServ::HandleObserverValue(TInt aService, TInt aReturnValue, TBool aMainThread)
319 {
320 if(iObserver != NULL && aMainThread)
321 {
322 switch(aService)
323 {
324 case MSDLObserver::EEventScreenSizeChanged:
325 if(aReturnValue == MSDLObserver::EScreenSizeChangedDefaultPalette)
326 EpocSdlEnv::LockPalette(EFalse);
327 break;
328 }
329 }
330 if(!aMainThread && aService == MSDLObserver::EEventSuspend)
331 {
332 if(iObserver == NULL ||
333 (gEpocEnv->iDsa->Stopped() && aReturnValue != MSDLObserver::ESuspendNoSuspend))
334 {
335 EpocSdlEnv::Suspend();
336 }
337 }
338 }
339
340void CSdlAppServ::RunL()
341 {
342 if(iStatus == KErrNone)
343 {
344 switch(iService)
345 {
346 case CSdlAppServ::EAppSrvWaitDsa:
347 EpocSdlEnv::SetWaitDsa();
348 iReturnValue = EpocSdlEnv::IsDsaAvailable();
349 // }
350 // gEpocEnv->iDsa->Stop();
351 // gEpocEnv->iDsa->RestartL();
352 break;
353 case CSdlAppServ::EAppSrvStopThread:
354 gEpocEnv->iDsa->SetSuspend();
355 break;
356 case EpocSdlEnv::EDisableKeyBlocking:
357 EnvUtils::DisableKeyBlocking();
358 break;
359
360 case EAppSrvWindowPointerCursorMode:
361 iReturnValue = gEpocEnv->iDsa != NULL ?
362 gEpocEnv->iDsa->Session().PointerCursorMode() : KErrNotReady;
363 break;
364 case EAppSrvDsaStatus:
365 gEpocEnv->iDsa->Stop();
366 iReturnValue = KErrNone;
367 break;
368 case CDsa::ERequestUpdate:
369 gEpocEnv->iDsa->UnlockHWSurfaceRequestComplete();
370 break;
371 case EAppSrvNoop:
372 break;
373 case MSDLObserver::EEventResume:
374 case MSDLObserver::EEventSuspend:
375 case MSDLObserver::EEventScreenSizeChanged:
376 case MSDLObserver::EEventWindowReserved:
377 case MSDLObserver::EEventKeyMapInit:
378 case MSDLObserver::EEventWindowNotAvailable:
379 case MSDLObserver::EEventMainExit:
380 iReturnValue = ObserverEvent(iService, iReturnValue);
381 HandleObserverValue(iService, iReturnValue, ETrue);
382 break;
383 default:
384 PANIC(KErrNotSupported);
385 }
386 iStatus = KRequestPending;
387 iStatusPtr = &iStatus;
388 SetActive();
389 }
390 iSema.Signal();
391 }
392
393void CSdlAppServ::DoCancel()
394 {
395 iSema.Wait();
396 TRequestStatus* s = &iStatus;
397 iAppThread.RequestComplete(s, KErrCancel);
398 }
399
400
401
402MEventQueue& EpocSdlEnv::EventQueue()
403 {
404 __ASSERT_DEBUG(gEpocEnv != NULL, PANIC(KErrNotReady));
405 return *gEpocEnv->iEventQueue;
406 }
407
408
409TBool EpocSdlEnv::Flags(TInt aFlag)
410 {
411 const TInt flag = gEpocEnv->iEpocEnvFlags & aFlag;
412 return flag == aFlag;
413 }
414
415TInt EpocSdlEnv::Argc()
416 {
417 __ASSERT_DEBUG(gEpocEnv != NULL, PANIC(KErrNotReady));
418 return gEpocEnv->iArgc;
419 }
420
421
422char** EpocSdlEnv::Argv()
423 {
424 __ASSERT_DEBUG(gEpocEnv != NULL, PANIC(KErrNotReady));
425 return gEpocEnv->iArgv;
426 }
427
428
429TBool EpocSdlEnv::IsDsaAvailable()
430 {
431 __ASSERT_DEBUG(gEpocEnv != NULL, PANIC(KErrNotReady));
432 return gEpocEnv->iDsa != NULL && gEpocEnv->iDsa->IsDsaAvailable();
433 }
434
435
436void EpocSdlEnv::WaitDsaAvailable()
437 {
438 EpocSdlEnv::ObserverEvent(MSDLObserver::EEventWindowNotAvailable, 0);
439 gEpocEnv->iAppSrv->Request(CSdlAppServ::EAppSrvStopThread);
440 if(EpocSdlEnv::Flags(CSDL::EEnableFocusStop))
441 {
442 EpocSdlEnv::ObserverEvent(MSDLObserver::EEventSuspend, 0);
443 }
444 }
445
446void EpocSdlEnv::Suspend()
447 {
448 if(gEpocEnv->iDsa->Stopped() || EpocSdlEnv::Flags(CSDL::EEnableFocusStop))
449 {
450 // gEpocEnv->iDsa->ReleaseStop();
451 gEpocEnv->iDsa->SetSuspend();
452 RThread().Suspend();
453 EpocSdlEnv::ObserverEvent(MSDLObserver::EEventResume, 0);
454 }
455 }
456
457void EpocSdlEnv::SetWaitDsa()
458 {
459 if(!IsDsaAvailable())
460 {
461 RThread th;
462 th.Open(gEpocEnv->iId);
463 th.Suspend();
464 th.Close();
465 gEpocEnv->iDsa->SetSuspend();
466 }
467 }
468
469void EpocSdlEnv::Resume()
470 {
471 gEpocEnv->iDsa->Resume();
472 RThread th;
473 th.Open(gEpocEnv->iId);
474 th.Resume();
475 th.Close();
476
477 const TInt value = gEpocEnv->iAppSrv->ObserverEvent(MSDLObserver::EEventResume, 0);
478 gEpocEnv->iAppSrv->HandleObserverValue(MSDLObserver::EEventResume, value, ETrue);
479 }
480
481
482TInt EpocSdlEnv::AllocSwSurface(const TSize& aSize, TDisplayMode aMode)
483 {
484 return gEpocEnv->iDsa->AllocSurface(EFalse, aSize, aMode);
485 }
486
487TInt EpocSdlEnv::AllocHwSurface(const TSize& aSize, TDisplayMode aMode)
488 {
489 return gEpocEnv->iDsa->AllocSurface(ETrue, aSize, aMode);
490 }
491
492
493void EpocSdlEnv::UnlockHwSurface()
494 {
495 gEpocEnv->iDsa->UnlockHwSurface();
496 }
497
498TUint8* EpocSdlEnv::LockHwSurface()
499 {
500 return gEpocEnv->iDsa->LockHwSurface();
501 }
502
503
504void EpocSdlEnv::UpdateSwSurface()
505 {
506 gEpocEnv->iDsa->UpdateSwSurface();
507 }
508
509TBool EpocSdlEnv::AddUpdateRect(TUint8* aAddress, const TRect& aUpdateRect, const TRect& aRect)
510 {
511 return gEpocEnv->iDsa->AddUpdateRect(aAddress, aUpdateRect, aRect);
512 }
513
514void EpocSdlEnv::Request(TInt aService)
515 {
516 __ASSERT_DEBUG(gEpocEnv != NULL, PANIC(KErrNotReady));
517 gEpocEnv->iAppSrv->Request(aService);
518 }
519
520
521TSize EpocSdlEnv::WindowSize(const TSize& aRequestedSize)
522 {
523 __ASSERT_DEBUG(gEpocEnv != NULL, PANIC(KErrNotReady));
524 if(EpocSdlEnv::Flags(CSDL::EAllowImageResize) && gEpocEnv->iDsa->WindowSize() != aRequestedSize)
525 {
526 TRAP_IGNORE(gEpocEnv->iDsa->CreateZoomerL(aRequestedSize));
527 }
528 return gEpocEnv->iDsa->WindowSize();
529 }
530
531 TSize EpocSdlEnv::WindowSize()
532 {
533 __ASSERT_DEBUG(gEpocEnv != NULL, PANIC(KErrNotReady));
534 return gEpocEnv->iDsa->WindowSize();
535 }
536
537TDisplayMode EpocSdlEnv::DisplayMode()
538 {
539 return gEpocEnv->iDsa->DisplayMode();
540 }
541
542TPointerCursorMode EpocSdlEnv::PointerMode()
543 {
544 return static_cast<TPointerCursorMode>
545 (gEpocEnv->iAppSrv->RequestValue(CSdlAppServ::EAppSrvWindowPointerCursorMode));
546 }
547
548TInt EpocSdlEnv::SetPalette(TInt aFirstcolor, TInt aColorCount, TUint32* aPalette)
549 {
550 return gEpocEnv->iDsa->SetPalette(aFirstcolor, aColorCount, aPalette);
551 }
552
553void EpocSdlEnv::PanicMain(TInt aErr)
554 {
555 gEpocEnv->iAppSrv->PanicMain(aErr);
556 }
557
558
559TInt EpocSdlEnv::AppendCleanupItem(const TSdlCleanupItem& aItem)
560 {
561 TRAPD(err, gEpocEnv->iCleanupItems->AppendL(aItem));
562 return err;
563 }
564
565void EpocSdlEnv::RemoveCleanupItem(TAny* aItem)
566 {
567 for(TInt i = 0; i < gEpocEnv->iCleanupItems->Count(); i++)
568 {
569 if(gEpocEnv->iCleanupItems->At(i).iItem == aItem)
570 gEpocEnv->iCleanupItems->Delete(i);
571 }
572 }
573
574void EpocSdlEnv::CleanupItems()
575 {
576 const TThreadId id = RThread().Id();
577 TInt last = gEpocEnv->iCleanupItems->Count() - 1;
578 TInt i;
579 for(i = last; i >= 0 ; i--)
580 {
581 TSdlCleanupItem& item = gEpocEnv->iCleanupItems->At(i);
582 if(item.iThread == id)
583 {
584 item.iThread = TThreadId(0);
585 item.iOperation(item.iItem);
586 }
587 }
588 last = gEpocEnv->iCleanupItems->Count() - 1;
589 for(i = last; i >= 0 ; i--)
590 {
591 TSdlCleanupItem& item = gEpocEnv->iCleanupItems->At(i);
592 if(item.iThread == TThreadId(0))
593 {
594 gEpocEnv->iCleanupItems->Delete(i);
595 }
596 }
597 }
598
599void EpocSdlEnv::FreeSurface()
600 {
601 Request(CSdlAppServ::EAppSrvDsaStatus);
602 gEpocEnv->iDsa->Free();
603 }
604
605void EpocSdlEnv::LockPalette(TBool aLock)
606 {
607 gEpocEnv->iDsa->LockPalette(aLock);
608 }
609
610void EpocSdlEnv::ObserverEvent(TInt aService, TInt aParam)
611 {
612 const TBool sdlThread = RThread().Id() == gEpocEnv->iId;
613 const TInt valuea = gEpocEnv->iAppSrv->ObserverEvent(aService, aParam);
614 gEpocEnv->iAppSrv->HandleObserverValue(aService, valuea, !sdlThread);
615 if(sdlThread)
616 {
617 gEpocEnv->iAppSrv->SetParam(aParam);
618 const TInt valuet = gEpocEnv->iAppSrv->RequestValue(aService);
619 gEpocEnv->iAppSrv->HandleObserverValue(aService, valuet, EFalse);
620 }
621 }
622
623
624TPoint EpocSdlEnv::WindowCoordinates(const TPoint& aPoint)
625 {
626 return gEpocEnv->iDsa->WindowCoordinates(aPoint);
627 }
628
629void EpocSdlEnv::PanicMain(const TDesC& aInfo, TInt aErr)
630 {
631 gEpocEnv->iAppSrv->PanicMain(aInfo, aErr);
632 }
633//Dsa is a low priority ao, it has to wait if its pending event, but ws
634//event has been prioritized before it
635//this is not called from app thread!
636void EpocSdlEnv::WaitDeviceChange()
637 {
638 LockPalette(ETrue);
639 gEpocEnv->iAppSrv->RequestValue(CSdlAppServ::EAppSrvWaitDsa);
640 const TSize sz = WindowSize();
641 const TInt param = reinterpret_cast<TInt>(&sz);
642 ObserverEvent(MSDLObserver::EEventScreenSizeChanged, param);
643
644 // RThread().Suspend();
645 }
646
647LOCAL_C TBool CheckSdl()
648 {
649 TInt isExit = ETrue;
650 RThread sdl;
651 if(sdl.Open(gEpocEnv->iId) == KErrNone)
652 {
653 if(sdl.ExitType() == EExitPending)
654 {
655 isExit = EFalse;
656 }
657 sdl.Close();
658 }
659 return isExit;
660 }
661
662void EpocSdlEnvData::Free()
663 {
664 if(RThread().Id() == gEpocEnv->iId)
665 {
666 iDsa->Free();
667 return;
668 }
669
670 __ASSERT_ALWAYS(iArgv == NULL || CheckSdl(), PANIC(KErrNotReady));
671
672 for(TInt i = 0; i < iArgc; i++)
673 User::Free( iArgv[i] );
674
675 User::Free(iArgv);
676
677
678 delete iEventQueue;
679
680 if(iDsa != NULL)
681 iDsa->Free();
682
683 delete iDsa;
684 delete iAppSrv;
685 }
686
687_LIT(KSDLMain, "SDLMain");
688
689LOCAL_C int MainL()
690 {
691 gEpocEnv->iCleanupItems = new (ELeave) CArrayFixFlat<TSdlCleanupItem>(8);
692
693 char** envp=0;
694 /* !! process exits here if there is "exit()" in main! */
695 int ret = 0;
696 for(TInt i = 0; i < 6; i++)
697 {
698 void* f = (void*) gEpocEnv->iMain[i];
699 if(f != NULL)
700 {
701 switch(i)
702 {
703 case 0:
704 ret = ((mainfunc1)f)();
705 return ret;
706 case 3:
707 ((mainfunc1)f)();
708 return ret;
709 case 1:
710 ret = ((mainfunc2)f)(EpocSdlEnv::Argc(), EpocSdlEnv::Argv());
711 return ret;
712 case 4:
713 ((mainfunc2)f)(EpocSdlEnv::Argc(), EpocSdlEnv::Argv());
714 return ret;
715 case 2:
716 ret = ((mainfunc3)f)(EpocSdlEnv::Argc(), EpocSdlEnv::Argv(), envp);
717 return ret;
718 case 5:
719 ((mainfunc3)f)(EpocSdlEnv::Argc(), EpocSdlEnv::Argv(), envp);
720 return ret;
721 }
722 }
723 }
724 PANIC(KErrNotFound);
725 return 0;
726 }
727
728LOCAL_C TInt DoMain(TAny* /*aParam*/)
729 {
730
731
732 CTrapCleanup* cleanup = CTrapCleanup::New();
733
734 TBool fbsconnected = EFalse;
735 if(RFbsSession::GetSession() == NULL)
736 {
737 PANIC_IF_ERROR(RFbsSession::Connect());
738 fbsconnected = ETrue;
739 }
740
741 gEpocEnv->iAppSrv->Init();
742
743#ifdef SYMBIANC
744 // Create stdlib
745 _REENT;
746#endif
747
748 // Call stdlib main
749 int ret = 0;
750
751 //completes waiting rendesvous
752 RThread::Rendezvous(KErrNone);
753
754 TRAPD(err, err = MainL());
755
756 EpocSdlEnv::ObserverEvent(MSDLObserver::EEventMainExit, err);
757
758 // Free resources and return
759
760 EpocSdlEnv::CleanupItems();
761
762 gEpocEnv->iCleanupItems->Reset();
763 delete gEpocEnv->iCleanupItems;
764 gEpocEnv->iCleanupItems = NULL;
765
766 gEpocEnv->Free(); //free up in thread resources
767
768#ifdef SYMBIANC
769 _cleanup(); //this is normally called at exit, I call it here
770#endif
771
772 if(fbsconnected)
773 RFbsSession::Disconnect();
774
775#ifdef SYMBIANC
776 CloseSTDLIB();
777#endif
778
779 // delete as;
780 delete cleanup;
781
782 return err == KErrNone ? ret : err;;
783 }
784
785
786
787EXPORT_C CSDL::~CSDL()
788 {
789 gEpocEnv->Free();
790 User::Free(gEpocEnv);
791 gEpocEnv->iSdl = NULL;
792 }
793
794EXPORT_C CSDL* CSDL::NewL(TInt aFlags)
795 {
796 __ASSERT_ALWAYS(gEpocEnv == NULL, PANIC(KErrAlreadyExists));
797 gEpocEnv = (EpocSdlEnvData*) User::AllocL(sizeof(EpocSdlEnvData));
798 Mem::FillZ(gEpocEnv, sizeof(EpocSdlEnvData));
799
800 gEpocEnv->iEpocEnvFlags = aFlags;
801 gEpocEnv->iEventQueue = CEventQueue::NewL();
802
803 gEpocEnv->iAppSrv = new (ELeave) CSdlAppServ();
804 gEpocEnv->iAppSrv->ConstructL();
805
806 CSDL* sdl = new (ELeave) CSDL();
807
808 gEpocEnv->iSdl = sdl;
809
810 return sdl;
811 }
812
813 /*
814EXPORT_C void CSDL::ReInitL(TFlags aFlags)
815 {
816 const TFlags prevFlags = gEpocEnv->iEpocEnvFlags;
817 gEpocEnv->iEpocEnvFlags = aFlags;
818 TInt err = KErrNone;
819 if(((prevFlags & EDrawModeDSB) != (aFlags & EDrawModeDSB)) && gEpocEnv->iDsa)
820 {
821 delete gEpocEnv->iDsa;
822 gEpocEnv->iDsa = NULL;
823 gEpocEnv->iDsa = CDsa::RecreateL(EpocSdlEnv::Flags(CSDL::EDrawModeDSB));
824 }
825 }
826 */
827
828
829EXPORT_C void CSDL::SetContainerWindowL(RWindow& aWindow, RWsSession& aSession, CWsScreenDevice& aDevice)
830 {
831 if(gEpocEnv->iDsa == NULL)
832 gEpocEnv->iDsa = CDsa::CreateL(aSession);
833 gEpocEnv->iDsa->ConstructL(aWindow, aDevice);
834 }
835
836
837EXPORT_C TThreadId CSDL::CallMainL(const TMainFunc& aFunc, TRequestStatus* const aStatus, const CDesC8Array* const aArg, TInt aFlags, TInt aStackSize)
838 {
839 ASSERT(gEpocEnv != NULL);
840 gEpocEnv->iMain = aFunc;
841 const TBool args = aArg != NULL;
842
843 gEpocEnv->iArgc = aArg->Count() + 1;
844 gEpocEnv->iArgv = (char**) User::AllocL(sizeof(char*) * (gEpocEnv->iArgc + 1));
845
846 TInt k = 0;
847 const TFileName processName = RProcess().FileName();
848 const TInt len = processName.Length();
849 gEpocEnv->iArgv[k] = (char*) User::AllocL(len + 1);
850 Mem::Copy(gEpocEnv->iArgv[k], processName.Ptr(), len);
851 gEpocEnv->iArgv[k][len] = 0;
852
853 for(TInt i = 0; args && (i < aArg->Count()); i++)
854 {
855 k++;
856 const TInt len = aArg->MdcaPoint(i).Length();
857 gEpocEnv->iArgv[k] = (char*) User::AllocL(len + 1);
858 Mem::Copy(gEpocEnv->iArgv[k], aArg->MdcaPoint(i).Ptr(), len);
859 gEpocEnv->iArgv[k][len] = 0;
860 }
861
862 gEpocEnv->iArgv[gEpocEnv->iArgc] = NULL;
863
864 RThread thread;
865 User::LeaveIfError(thread.Create(KSDLMain, DoMain, aStackSize, NULL, NULL));
866
867 if(aStatus != NULL)
868 {
869 thread.Logon(*aStatus);
870 }
871
872 gEpocEnv->iId = thread.Id();
873 thread.SetPriority(EPriorityLess);
874 if((aFlags & CSDL::ERequestResume) == 0)
875 {
876 thread.Resume();
877 }
878 thread.Close();
879 return gEpocEnv->iId;
880 }
881
882EXPORT_C TInt CSDL::AppendWsEvent(const TWsEvent& aEvent)
883 {
884 return EpocSdlEnv::EventQueue().Append(aEvent);
885 }
886
887EXPORT_C void CSDL::SDLPanic(const TDesC& aInfo, TInt aErr)
888 {
889 EpocSdlEnv::PanicMain(aInfo, aErr);
890 }
891
892EXPORT_C TInt CSDL::GetSDLCode(TInt aScanCode)
893 {
894 if(aScanCode < 0)
895 return MAX_SCANCODE;
896 if(aScanCode >= MAX_SCANCODE)
897 return -1;
898 return KeyMap()[aScanCode];
899 }
900
901EXPORT_C TInt CSDL::SDLCodesCount() const
902 {
903 return MAX_SCANCODE;
904 }
905
906EXPORT_C void CSDL::ResetSDLCodes()
907 {
908 ResetKeyMap();
909 }
910
911EXPORT_C void CSDL::SetOrientation(TOrientationMode aMode)
912 {
913 gEpocEnv->iDsa->SetOrientation(aMode);
914 }
915
916EXPORT_C TInt CSDL::SetSDLCode(TInt aScanCode, TInt aSDLCode)
917 {
918 const TInt current = GetSDLCode(aScanCode);
919 if(aScanCode >= 0 && aScanCode < MAX_SCANCODE)
920 KeyMap()[aScanCode] = static_cast<SDLKey>(aSDLCode);
921 return current;
922 }
923
924
925EXPORT_C MSDLObserver* CSDL::Observer()
926 {
927 return gEpocEnv->iAppSrv->Observer();
928 }
929
930EXPORT_C void CSDL::SetObserver(MSDLObserver* aObserver)
931 {
932 gEpocEnv->iAppSrv->SetObserver(aObserver);
933 }
934
935EXPORT_C void CSDL::Resume()
936 {
937 EpocSdlEnv::Resume();
938 }
939
940EXPORT_C void CSDL::Suspend()
941 {
942 gEpocEnv->iDsa->DoStop();
943 }
944
945EXPORT_C CSDL::CSDL()
946 {
947 }
948
949EXPORT_C void CSDL::DisableKeyBlocking(CAknAppUi& aAppUi) const
950 {
951 gEpocEnv->iAppUi = &aAppUi;
952 EnvUtils::DisableKeyBlocking();
953 }
954
955EXPORT_C TInt CSDL::SetBlitter(MBlitter* aBlitter)
956 {
957 if(gEpocEnv && gEpocEnv->iDsa)
958 {
959 gEpocEnv->iDsa->SetBlitter(aBlitter);
960 return KErrNone;
961 }
962 return KErrNotReady;
963 }
964
965
966EXPORT_C TInt CSDL::AppendOverlay(MOverlay& aOverlay, TInt aPriority)
967 {
968 if(gEpocEnv && gEpocEnv->iDsa)
969 {
970 return gEpocEnv->iDsa->AppendOverlay(aOverlay, aPriority);
971 }
972 return KErrNotReady;
973 }
974
975EXPORT_C TInt CSDL::RemoveOverlay(MOverlay& aOverlay)
976 {
977 if(gEpocEnv && gEpocEnv->iDsa)
978 {
979 return gEpocEnv->iDsa->RemoveOverlay(aOverlay);
980 }
981 return KErrNotReady;
982 }
983
984EXPORT_C TInt CSDL::RedrawRequest()
985 {
986 if(gEpocEnv && gEpocEnv->iDsa)
987 {
988 return gEpocEnv->iDsa->RedrawRequest();
989 }
990 return KErrNotReady;
991 }
992
993/*
994EXPORT_C CSDL* CSDL::Current()
995 {
996 return gEpocEnv != NULL ? gEpocEnv->iSdl : NULL;
997 }
998
999
1000EXPORT_C TInt CSDL::SetVolume(TInt aVolume)
1001 {
1002 return EpocSdlEnv::SetVolume(aVolume);
1003 }
1004
1005EXPORT_C TInt CSDL::Volume() const
1006 {
1007 return EpocSdlEnv::Volume();
1008 }
1009
1010EXPORT_C TInt CSDL::MaxVolume() const
1011 {
1012 return EpocSdlEnv::MaxVolume();
1013 }
1014*/
1015
1016void EnvUtils::DisableKeyBlocking()
1017 {
1018 if(gEpocEnv->iAppUi != NULL)
1019 return CCurrentAppUi::Cast(gEpocEnv->iAppUi)->DisableKeyBlocking();
1020 }
1021
1022TBool EnvUtils::Rendezvous(RThread& aThread, TRequestStatus& aStatus)
1023 {
1024 if(gEpocEnv->iId != TThreadId(0) &&
1025 aThread.Open(gEpocEnv->iId) &&
1026 aThread.ExitType() == EExitPending)
1027 {
1028 aThread.Rendezvous(aStatus);
1029 return ETrue;
1030 }
1031 return EFalse;
1032 }
1033
1034
1035
diff --git a/apps/plugins/sdl/src/main/symbian/EKA2/sdlexe.cpp b/apps/plugins/sdl/src/main/symbian/EKA2/sdlexe.cpp
deleted file mode 100644
index bb160c4090..0000000000
--- a/apps/plugins/sdl/src/main/symbian/EKA2/sdlexe.cpp
+++ /dev/null
@@ -1,809 +0,0 @@
1// INCLUDES
2#include <aknapp.h>
3#include <aknappui.h>
4#include <eikdoc.h>
5#include <sdlepocapi.h>
6#include <bautils.h>
7#include <eikstart.h>
8#include <badesca.h>
9#include <bautils.h>
10#include <apgcli.h>
11#include <sdlmain.h>
12#include <eikedwin.h>
13#include <eiklabel.h>
14#include <sdlexe.rsg>
15#include <aknglobalmsgquery.h>
16#include <apgwgnam.h>
17
18
19
20// FORWARD DECLARATIONS
21class CApaDocument;
22
23
24//const TUid KSDLUID = { 0xF01F605E };
25
26LOCAL_C void MakeCCmdLineL(const TDesC8& aParam, CDesC8Array& aArray)
27 {
28
29 const TChar dq('\"');
30
31 TLex8 lex(aParam);
32 TBool in = EFalse;
33
34 lex.SkipSpaceAndMark();
35
36 while(!lex.Eos())
37 {
38 TPtrC8 ptr;
39 if(in)
40 {
41 const TPtrC8 rem = lex.RemainderFromMark();
42 const TInt pos = rem.Locate(dq);
43 if(pos > 0)
44 {
45 lex.Inc(pos);
46 ptr.Set(lex.MarkedToken());
47 lex.SkipAndMark(1);
48 }
49 else
50 {
51 ptr.Set(rem);
52 }
53 in = EFalse;
54 }
55 else
56 {
57 ptr.Set(lex.NextToken());
58 const TInt pos = ptr.Locate(dq);
59 if(pos == 0)
60 {
61 lex.UnGetToMark();
62 lex.SkipAndMark(1);
63 in = ETrue;
64 continue; // back to in brace
65 }
66 else
67 lex.SkipSpaceAndMark();
68 }
69
70 aArray.AppendL(ptr);
71
72 }
73 }
74
75NONSHARABLE_CLASS(TVirtualCursor) : public MOverlay
76 {
77 public:
78 TVirtualCursor();
79 void Set(const TRect& aRect, CFbsBitmap* aBmp, CFbsBitmap* aAlpha);
80 void Move(TInt aX, TInt aY);
81 void MakeEvent(TWsEvent& aEvent, const TPoint& aBasePos) const;
82 void Toggle();
83 TBool IsOn() const;
84 private:
85 void Draw(CBitmapContext& aGc, const TRect& aTargetRect, const TSize& aSize);
86 private:
87 TRect iRect;
88 TPoint iInc;
89 TPoint iPos;
90 TBool iIsOn;
91 CFbsBitmap* iCBmp;
92 CFbsBitmap* iAlpha;
93 };
94
95
96TVirtualCursor::TVirtualCursor() : iInc(0, 0), iIsOn(EFalse), iCBmp(NULL)
97 {
98 }
99
100const TInt KMaxMove = 10;
101
102void TVirtualCursor::Move(TInt aX, TInt aY)
103 {
104 if(aX > 0 && iInc.iX > 0)
105 ++iInc.iX;
106 else if(aX < 0 && iInc.iX < 0)
107 --iInc.iX;
108 else
109 iInc.iX = aX;
110
111 if(aY > 0 && iInc.iY > 0)
112 ++iInc.iY;
113 else if(aY < 0 && iInc.iY < 0)
114 --iInc.iY;
115 else
116 iInc.iY = aY;
117
118 iInc.iX = Min(KMaxMove, iInc.iX);
119
120 iInc.iX = Max(-KMaxMove, iInc.iX);
121
122 iInc.iY = Min(KMaxMove, iInc.iY);
123
124 iInc.iY =Max(-KMaxMove, iInc.iY);
125
126 const TPoint pos = iPos + iInc;
127 if(iRect.Contains(pos))
128 {
129 iPos = pos;
130 }
131 else
132 {
133 iInc = TPoint(0, 0);
134 }
135 }
136
137
138void TVirtualCursor::Toggle()
139 {
140 iIsOn = !iIsOn;
141 }
142
143
144TBool TVirtualCursor::IsOn() const
145 {
146 return iIsOn;
147 }
148
149void TVirtualCursor::Set(const TRect& aRect, CFbsBitmap* aBmp, CFbsBitmap* aAlpha)
150 {
151 iRect = aRect;
152 iCBmp = aBmp;
153 iAlpha = aAlpha;
154 }
155
156
157void TVirtualCursor::MakeEvent(TWsEvent& aEvent, const TPoint& aBasePos) const
158 {
159 aEvent.SetType(EEventPointer),
160 aEvent.SetTimeNow();
161 TPointerEvent& pointer = *aEvent.Pointer();
162 pointer.iType = TPointerEvent::EButton1Down;
163 pointer.iPosition = iPos;
164 pointer.iParentPosition = aBasePos;
165 }
166
167
168void TVirtualCursor::Draw(CBitmapContext& aGc, const TRect& /*aTargetRect*/, const TSize& /*aSize*/)
169 {
170 if(iIsOn && iCBmp != NULL)
171 {
172 const TRect rect(TPoint(0, 0), iCBmp->SizeInPixels());
173 aGc.AlphaBlendBitmaps(iPos, iCBmp, rect, iAlpha, TPoint(0, 0));
174 }
175
176 }
177
178NONSHARABLE_CLASS(TSdlClass)
179 {
180 public:
181 TSdlClass();
182 void SetMain(const TMainFunc& aFunc, TInt aFlags, MSDLMainObs* aObs, TInt aExeFlags);
183 TInt SdlFlags() const;
184 const TMainFunc& Main() const;
185 void SendEvent(TInt aEvent, TInt aParam, CSDL* aSDL);
186 TInt AppFlags() const;
187 void AppFlags(TInt aFlags);
188 private:
189 TMainFunc iFunc;
190 TInt iSdlFlags;
191 TInt iExeFlags;
192 MSDLMainObs* iObs;
193 };
194
195
196void TSdlClass::AppFlags(TInt aFlags)
197 {
198 iExeFlags |= aFlags;
199 }
200
201void TSdlClass::SendEvent(TInt aEvent, TInt aParam, CSDL* aSDL)
202 {
203 if(iObs != NULL)
204 iObs->SDLMainEvent(aEvent, aParam, aSDL);
205 }
206
207TInt TSdlClass::AppFlags() const
208 {
209 return iExeFlags;
210 }
211
212void TSdlClass::SetMain(const TMainFunc& aFunc, TInt aFlags, MSDLMainObs* aObs, TInt aExeFlags)
213 {
214 iFunc = aFunc;
215 iSdlFlags = aFlags;
216 iExeFlags = aExeFlags;
217 iObs = aObs;
218 }
219
220const TMainFunc& TSdlClass::Main() const
221 {
222 return iFunc;
223 }
224
225
226 TInt TSdlClass::SdlFlags() const
227 {
228 return iSdlFlags;
229 }
230
231
232
233TSdlClass::TSdlClass()
234 {
235 Mem::FillZ(this, sizeof(this));
236 }
237
238TSdlClass gSDLClass;
239
240
241////////////////////////////////////////////////////////////////
242
243NONSHARABLE_CLASS(CSDLApplication) : public CAknApplication
244 {
245 public:
246 CSDLApplication();
247 private:
248 CApaDocument* CreateDocumentL();
249 TFileName ResourceFileName() const;
250 TUid AppDllUid() const;
251 void FindMeL();
252 TUid iUid;
253 };
254
255NONSHARABLE_CLASS(CSDLDocument) : public CEikDocument
256 {
257 public:
258 CSDLDocument(CEikApplication& aApp);
259 private:
260 CEikAppUi* CreateAppUiL();
261
262 };
263
264 ////////////////////////////////////////////////////////////////////
265
266
267NONSHARABLE_CLASS(MExitWait)
268 {
269 public:
270 virtual void DoExit(TInt aErr) = 0;
271 };
272
273/////////////////////////////////////////////////////////////////////////
274
275NONSHARABLE_CLASS(CExitWait) : public CActive
276 {
277 public:
278 CExitWait(MExitWait& aWait);
279 ~CExitWait();
280 private:
281 void RunL();
282 void DoCancel();
283 private:
284 MExitWait& iWait;
285 TRequestStatus* iStatusPtr;
286 };
287
288////////////////////////////////////////////////////////////////////////
289
290
291NONSHARABLE_CLASS(CSDLWin) : public CCoeControl
292 {
293 public:
294 void ConstructL(const TRect& aRect);
295 RWindow& GetWindow() const;
296 void SetNoDraw();
297 private:
298 void Draw(const TRect& aRect) const;
299 private:
300 TBool iNoDraw;
301 };
302
303
304////////////////////////////////////////////////////////////////////////////
305
306NONSHARABLE_CLASS(CSDLAppUi) : public CAknAppUi, public MExitWait, MSDLObserver
307 {
308 public:
309 ~CSDLAppUi();
310 private: // New functions
311 void ConstructL();
312 void HandleCommandL(TInt aCommand);
313 void HandleWsEventL(const TWsEvent& aEvent, CCoeControl* aDestination);
314 void HandleResourceChangeL(TInt aType);
315
316 void DoExit(TInt aErr);
317
318 TInt SdlEvent(TInt aEvent, TInt aParam);
319 TInt SdlThreadEvent(TInt aEvent, TInt aParam);
320
321 void StartL();
322 static TBool StartL(TAny* aThis);
323
324 TBool ParamEditorL(TDes& aCheat);
325
326 TBool ProcessCommandParametersL(CApaCommandLine &aCommandLine);
327
328 void PrepareToExit();
329 void HandleConsoleWindowL();
330 void HandleConsoleWindow();
331 void HandleForegroundEventL(TBool aForeground);
332
333 static TBool IdleRequestL(TAny* aThis);
334
335 TBool HandleKeyL(const TWsEvent& aEvent);
336
337
338 private:
339 CExitWait* iWait;
340 CSDLWin* iSDLWin;
341 CSDL* iSdl;
342 CIdle* iStarter;
343 TBool iExitRequest;
344 CDesC8Array* iParams;
345 TInt iResOffset;
346 CIdle* iIdle;
347 TInt iStdOut;
348 TVirtualCursor iCursor;
349 CFbsBitmap* iCBmp;
350 CFbsBitmap* iAlpha;
351 // TTime iLastPress;
352 // CSDL::TOrientationMode iOrientation;
353 };
354
355////////////////////////////////////////////////////////////////////////////////////////7
356
357CApaDocument* CSDLApplication::CreateDocumentL()
358 {
359 return new (ELeave) CSDLDocument(*this);
360 }
361
362TUid CSDLApplication::AppDllUid() const
363 {
364 return iUid;
365 }
366
367
368CSDLApplication::CSDLApplication()
369 {
370 TRAPD(err, FindMeL());
371 ASSERT(err == KErrNone);
372 }
373
374void CSDLApplication::FindMeL()
375 {
376 RApaLsSession apa;
377 User::LeaveIfError(apa.Connect());
378 CleanupClosePushL(apa);
379 User::LeaveIfError(apa.GetAllApps());
380 TFileName name = RProcess().FileName();
381 TApaAppInfo info;
382 while(apa.GetNextApp(info) == KErrNone)
383 {
384 if(info.iFullName.CompareF(name) == 0)
385 {
386 iUid = info.iUid;
387 break;
388 }
389 }
390 CleanupStack::PopAndDestroy();
391 }
392
393TFileName CSDLApplication::ResourceFileName() const
394 {
395 return KNullDesC();
396 }
397
398///////////////////////////////////////////////////////////////////////////////////////////
399
400CExitWait::CExitWait(MExitWait& aWait) : CActive(CActive::EPriorityStandard), iWait(aWait)
401 {
402 CActiveScheduler::Add(this);
403 SetActive();
404 iStatusPtr = &iStatus;
405 }
406
407CExitWait::~CExitWait()
408 {
409 Cancel();
410 }
411
412void CExitWait::RunL()
413 {
414 if(iStatusPtr != NULL )
415 iWait.DoExit(iStatus.Int());
416 }
417
418void CExitWait::DoCancel()
419 {
420 if(iStatusPtr != NULL )
421 User::RequestComplete(iStatusPtr , KErrCancel);
422 }
423
424
425//////////////////////////////////////////////////////////////////////////////////////////////
426
427CSDLDocument::CSDLDocument(CEikApplication& aApp) : CEikDocument(aApp)
428 {}
429
430CEikAppUi* CSDLDocument::CreateAppUiL()
431 {
432 return new (ELeave) CSDLAppUi;
433 }
434
435///////////////////////////////////////////////////////////////////////////
436
437void CSDLWin:: ConstructL(const TRect& aRect)
438 {
439 CreateWindowL();
440 SetRect(aRect);
441 ActivateL();
442 }
443
444
445RWindow& CSDLWin::GetWindow() const
446 {
447 return Window();
448 }
449
450
451void CSDLWin::Draw(const TRect& /*aRect*/) const
452 {
453 if(!iNoDraw)
454 {
455 CWindowGc& gc = SystemGc();
456 gc.SetPenStyle(CGraphicsContext::ESolidPen);
457 gc.SetPenColor(KRgbGray);
458 gc.SetBrushStyle(CGraphicsContext::ESolidBrush);
459 gc.SetBrushColor(0xaaaaaa);
460 gc.DrawRect(Rect());
461 }
462 }
463
464void CSDLWin::SetNoDraw()
465 {
466 iNoDraw = ETrue;
467 }
468
469/////////////////////////////////////////////////////////////////////////
470
471CSDLAppUi::~CSDLAppUi()
472 {
473 if(iIdle)
474 iIdle->Cancel();
475 delete iIdle;
476 if(iStarter != NULL)
477 iStarter->Cancel();
478 delete iStarter;
479 delete iWait;
480 delete iSdl;
481 delete iSDLWin;
482 delete iParams;
483 delete iCBmp;
484 delete iAlpha;
485 }
486
487
488void CSDLAppUi::ConstructL()
489 {
490 BaseConstructL(ENoAppResourceFile | ENoScreenFurniture);
491
492
493 RLibrary lib;
494 User::LeaveIfError(lib.Load(_L("sdlexe.dll")));
495 TFileName name = lib.FileName();
496 lib.Close();
497 name.Replace(3, name.Length() - 3, _L("resource\\apps\\sdlexe.rsc"));
498 BaflUtils::NearestLanguageFile(iEikonEnv->FsSession(), name);
499 iResOffset = iCoeEnv->AddResourceFileL(name);
500
501 name.Replace(name.Length() - 3, 3, _L("mbm"));
502
503 TEntry e;
504 const TInt err = iEikonEnv->FsSession().Entry(name, e);
505
506 iCBmp = iEikonEnv->CreateBitmapL(name, 0);
507 iAlpha = iEikonEnv->CreateBitmapL(name, 1);
508
509 iIdle = CIdle::NewL(CActive::EPriorityIdle);
510
511 iSDLWin = new (ELeave) CSDLWin;
512 iSDLWin->ConstructL(ApplicationRect());
513
514 iSdl = CSDL::NewL(gSDLClass.SdlFlags());
515
516 gSDLClass.SendEvent(MSDLMainObs::ESDLCreated, 0, iSdl);
517
518 iSdl->SetObserver(this);
519 iSdl->DisableKeyBlocking(*this);
520 iSdl->SetContainerWindowL(
521 iSDLWin->GetWindow(),
522 iEikonEnv->WsSession(),
523 *iEikonEnv->ScreenDevice());
524 iSdl->AppendOverlay(iCursor, 0);
525
526 iCursor.Set(TRect(TPoint(0, 0), iSDLWin->Size()), iCBmp, iAlpha);
527
528 iStarter = CIdle::NewL(CActive::EPriorityLow);
529 iStarter->Start(TCallBack(StartL, this));
530
531
532 }
533
534
535
536TBool CSDLAppUi::StartL(TAny* aThis)
537 {
538 static_cast<CSDLAppUi*>(aThis)->StartL();
539 return EFalse;
540 }
541
542
543void CSDLAppUi::PrepareToExit()
544 {
545 CAknAppUiBase::PrepareToExit(); //aknappu::PrepareToExit crashes
546 iCoeEnv->DeleteResourceFile(iResOffset);
547 }
548
549TBool CSDLAppUi::ProcessCommandParametersL(CApaCommandLine &aCommandLine)
550 {
551 const TPtrC8 cmdLine = aCommandLine.TailEnd();
552 iParams = new (ELeave) CDesC8ArrayFlat(8);
553 MakeCCmdLineL(cmdLine, *iParams);
554 return EFalse;
555 }
556
557
558 TBool CSDLAppUi::ParamEditorL(TDes& aCheat)
559 {
560 CAknTextQueryDialog* query = CAknTextQueryDialog::NewL(aCheat);
561 CleanupStack::PushL(query);
562 query->SetPromptL(_L("Enter parameters"));
563 CleanupStack::Pop();
564 return query->ExecuteLD(R_PARAMEDITOR);
565 }
566
567 void CSDLAppUi::StartL()
568 {
569 if(gSDLClass.AppFlags() & SDLEnv::EParamQuery)
570 {
571 TBuf8<256> cmd;
572 RFile file;
573 TInt err = file.Open(iEikonEnv->FsSession(), _L("sdl_param.txt"),EFileRead);
574 if(err == KErrNone)
575 {
576 file.Read(cmd);
577 file.Close();
578 MakeCCmdLineL(cmd, *iParams);
579 }
580 if(err != KErrNone || gSDLClass.AppFlags() & (SDLEnv::EParamQueryDialog ^ SDLEnv::EParamQuery))
581 {
582 TBuf<256> buffer;
583 if(ParamEditorL(buffer))
584 {
585 cmd.Copy(buffer);
586 MakeCCmdLineL(cmd, *iParams);
587 }
588 }
589 }
590 iWait = new (ELeave) CExitWait(*this);
591 iSdl->CallMainL(gSDLClass.Main(), &iWait->iStatus, iParams, CSDL::ENoParamFlags, 0xA000);
592 }
593
594void CSDLAppUi::HandleCommandL(TInt aCommand)
595 {
596 switch(aCommand)
597 {
598 case EAknSoftkeyBack:
599 case EAknSoftkeyExit:
600 case EAknCmdExit:
601 case EEikCmdExit:
602 gSDLClass.AppFlags(SDLEnv::EAllowConsoleView);
603 if(iWait == NULL || !iWait->IsActive() || iSdl == NULL)
604 {
605 Exit();
606 }
607 else if(!iExitRequest)
608 {
609 iExitRequest = ETrue; //trick how SDL can be closed!
610 iSdl->Suspend();
611 }
612 break;
613 }
614 }
615
616
617
618TBool CSDLAppUi::HandleKeyL(const TWsEvent& aEvent)
619 {
620 const TInt type = aEvent.Type();
621 if(!(type == EEventKey || type == EEventKeyUp || type == EEventKeyDown))
622 {
623 return ETrue;
624 }
625 const TKeyEvent& key = *aEvent.Key();
626 if((key.iScanCode == EStdKeyYes) && (gSDLClass.AppFlags() & SDLEnv::EVirtualMouse))
627 {
628 if(type == EEventKeyUp)
629 {
630 iCursor.Toggle();
631 iSdl->RedrawRequest();
632 }
633 return EFalse;
634 }
635 if(iCursor.IsOn())
636 {
637 switch(key.iScanCode)
638 {
639 case EStdKeyUpArrow:
640 iCursor.Move(0, -1);
641 break;
642 case EStdKeyDownArrow:
643 iCursor.Move(0, 1);
644 break;
645 case EStdKeyLeftArrow:
646 iCursor.Move(-1, 0);
647 break;
648 case EStdKeyRightArrow:
649 iCursor.Move(1, 0);
650 break;
651 case EStdKeyDevice3:
652 if(type == EEventKeyUp)
653 {
654 TWsEvent event;
655 iCursor.MakeEvent(event, iSDLWin->Position());
656 iSdl->AppendWsEvent(event);
657 }
658 return EFalse;
659 default:
660 return ETrue;
661 }
662 iSdl->RedrawRequest();
663 return EFalse;
664 }
665 return ETrue;
666 }
667
668 void CSDLAppUi::HandleWsEventL(const TWsEvent& aEvent, CCoeControl* aDestination)
669 {
670 if(iSdl && iWait && HandleKeyL(aEvent))
671 iSdl->AppendWsEvent(aEvent);
672 CAknAppUi::HandleWsEventL(aEvent, aDestination);
673 }
674
675 void CSDLAppUi::HandleResourceChangeL(TInt aType)
676 {
677 CAknAppUi::HandleResourceChangeL(aType);
678 if(aType == KEikDynamicLayoutVariantSwitch)
679 {
680 iSDLWin->SetRect(ApplicationRect());
681 iSdl->SetContainerWindowL(
682 iSDLWin->GetWindow(),
683 iEikonEnv->WsSession(),
684 *iEikonEnv->ScreenDevice());
685 }
686 }
687
688
689void CSDLAppUi::DoExit(TInt/*Err*/)
690 {
691 iExitRequest = ETrue;
692 Exit();
693 }
694
695
696 TInt CSDLAppUi::SdlThreadEvent(TInt aEvent, TInt /*aParam*/)
697 {
698 switch(aEvent)
699 {
700 case MSDLObserver::EEventResume:
701 break;
702 case MSDLObserver::EEventSuspend:
703 if(iExitRequest)
704 return MSDLObserver::ESuspendNoSuspend;
705 break;
706 case MSDLObserver::EEventWindowReserved:
707 break;
708 case MSDLObserver::EEventWindowNotAvailable:
709 break;
710 case MSDLObserver::EEventScreenSizeChanged:
711 break;
712 }
713 return MSDLObserver::EParameterNone;
714 }
715
716TInt CSDLAppUi::SdlEvent(TInt aEvent, TInt /*aParam*/)
717 {
718 switch(aEvent)
719 {
720 case MSDLObserver::EEventResume:
721 break;
722 case MSDLObserver::EEventSuspend:
723 if(iExitRequest)
724 return MSDLObserver::ESuspendNoSuspend;
725 break;
726 case MSDLObserver::EEventWindowReserved:
727 break;
728 case MSDLObserver::EEventWindowNotAvailable:
729 {
730 TRAP_IGNORE(HandleConsoleWindowL());
731 }
732 break;
733 case MSDLObserver::EEventScreenSizeChanged:
734 break;
735 case MSDLObserver::EEventKeyMapInit:
736 break;
737 case MSDLObserver::EEventMainExit:
738 if(iStdOut != 0)
739 {
740 gSDLClass.AppFlags(SDLEnv::EAllowConsoleView);
741 iEikonEnv->WsSession().SetWindowGroupOrdinalPosition(iStdOut, 0);
742 }
743 break;
744 }
745 return MSDLObserver::EParameterNone;
746 }
747
748void CSDLAppUi::HandleForegroundEventL(TBool aForeground)
749 {
750 CAknAppUi::HandleForegroundEventL(aForeground);
751 if(!aForeground)
752 HandleConsoleWindow();
753 }
754
755void CSDLAppUi::HandleConsoleWindow()
756 {
757 if(!iIdle->IsActive())
758 iIdle->Start(TCallBack(IdleRequestL, this));
759 }
760
761TBool CSDLAppUi::IdleRequestL(TAny* aThis)
762 {
763 static_cast<CSDLAppUi*>(aThis)->HandleConsoleWindowL();
764 return EFalse;
765 }
766
767void CSDLAppUi::HandleConsoleWindowL()
768 {
769 if(gSDLClass.AppFlags() & SDLEnv::EAllowConsoleView)
770 {
771 return;
772 }
773 RWsSession& ses = iEikonEnv->WsSession();
774 const TInt focus = ses.GetFocusWindowGroup();
775 CApaWindowGroupName* name = CApaWindowGroupName::NewLC(ses, focus);
776 const TPtrC caption = name->Caption();
777 if(0 == caption.CompareF(_L("STDOUT")))
778 {
779 iStdOut = focus;
780 ses.SetWindowGroupOrdinalPosition(iEikonEnv->RootWin().Identifier(), 0);
781 }
782 CleanupStack::PopAndDestroy(); //name
783 }
784
785
786////////////////////////////////////////////////////////////////////////
787
788
789CApaApplication* NewApplication()
790 {
791 return new CSDLApplication();
792 }
793
794
795EXPORT_C TInt SDLEnv::SetMain(const TMainFunc& aFunc, TInt aSdlFlags, MSDLMainObs* aObs, TInt aSdlExeFlags)
796 {
797 gSDLClass.SetMain(aFunc, aSdlFlags, aObs, aSdlExeFlags);
798 return EikStart::RunApplication(NewApplication);
799 }
800
801//////////////////////////////////////////////////////////////////////
802
803TInt SDLUiPrint(const TDesC8& /*aInfo*/)
804 {
805 return KErrNotFound;
806 }
807
808
809
diff --git a/apps/plugins/sdl/src/main/symbian/EKA2/sdllib.cpp b/apps/plugins/sdl/src/main/symbian/EKA2/sdllib.cpp
deleted file mode 100644
index 7c09996ec7..0000000000
--- a/apps/plugins/sdl/src/main/symbian/EKA2/sdllib.cpp
+++ /dev/null
@@ -1,12 +0,0 @@
1#include<eikstart.h>
2#include<sdlmain.h>
3#include<sdlepocapi.h>
4
5
6GLREF_C TInt E32Main()
7 {
8 return SDLEnv::SetMain(SDL_main, CSDL::EEnableFocusStop | CSDL::EAllowImageResize,
9 NULL, SDLEnv::EParamQuery | SDLEnv::EVirtualMouse);
10 }
11
12 \ No newline at end of file
diff --git a/apps/plugins/sdl/src/main/symbian/EKA2/vectorbuffer.cpp b/apps/plugins/sdl/src/main/symbian/EKA2/vectorbuffer.cpp
deleted file mode 100644
index 72c3b3e5c0..0000000000
--- a/apps/plugins/sdl/src/main/symbian/EKA2/vectorbuffer.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
1/*
2 vectorbuffer.cpp
3 yet another circle buffer
4
5 Markus Mertama
6*/
7
8#include"vectorbuffer.h"
9
10
11
12void VectorPanic(TInt aErr, TInt aLine)
13 {
14 TBuf<64> b;
15 b.Format(_L("vector buffer at % d "), aLine);
16 User::Panic(b, aErr);
17 }
18
19void TNodeBuffer::TNode::Terminator(TNodeBuffer::TNode* aNode)
20 {
21 Mem::Copy(iSucc, &aNode, sizeof(TNode*));
22 }
23
24TInt TNodeBuffer::TNode::Size() const
25 {
26 return reinterpret_cast<const TUint8*>(iSucc) - Ptr();
27 }
28
29const TUint8* TNodeBuffer::TNode::Ptr() const
30 {
31 return reinterpret_cast<const TUint8*>(this) + sizeof(TNode);
32 }
33
34TNodeBuffer::TNode* TNodeBuffer::TNode::Empty(TUint8* aBuffer)
35 {
36 TNode* node = reinterpret_cast<TNode*>(aBuffer);
37 node->iSucc = node + 1;
38 return node;
39 }
40
41 TNodeBuffer::TNode* TNodeBuffer::TNode::New(TNode* aPred, const TDesC8& aData)
42 {
43 TNode* node = aPred->Size() == 0 ? aPred : aPred->iSucc;
44
45
46 TUint8* start = reinterpret_cast<TUint8*>(node) + sizeof(TNode);
47 node->iSucc = reinterpret_cast<TNode*>(start + aData.Size());
48 node->iSucc->iSucc = NULL; //terminator
49
50 __ASSERT_DEBUG(node->Size() == aData.Size(), VECPANIC(KErrCorrupt));
51
52 Mem::Copy(start, aData.Ptr(), aData.Size());
53 return node;
54 }
55
56
57
58
59
60
61
62 \ No newline at end of file
diff --git a/apps/plugins/sdl/src/main/symbian/EKA2/vectorbuffer.h b/apps/plugins/sdl/src/main/symbian/EKA2/vectorbuffer.h
deleted file mode 100644
index 3d8be58d6a..0000000000
--- a/apps/plugins/sdl/src/main/symbian/EKA2/vectorbuffer.h
+++ /dev/null
@@ -1,240 +0,0 @@
1/*
2 vectorbuffer.cpp
3 yet another circle buffer
4
5 Markus Mertama
6*/
7
8#ifndef __VECTORBUFFER_H__
9#define __VECTORBUFFER_H__
10
11#include<e32std.h>
12#define VLOG(x)
13#define VECPANIC(x) VectorPanic(x, __LINE__)
14void VectorPanic(TInt, TInt);
15
16
17//int DEBUG_INT;
18
19NONSHARABLE_CLASS(TNodeBuffer)
20 {
21 public:
22 protected:
23 NONSHARABLE_CLASS(TNode)
24 {
25 public:
26 static TNode* Empty(TUint8* iBuffer);
27 static TNode* New(TNode* aPrev, const TDesC8& aData);
28 const TUint8* Ptr() const;
29 TInt Size() const;
30 inline TNode* Succ();
31 static void SetSucc(TNode*& aNode);
32 void Terminator(TNode* aNode);
33 private:
34 TNode* iSucc;
35 };
36 };
37
38inline TNodeBuffer::TNode* TNodeBuffer::TNode::Succ()
39 {
40 return iSucc;
41 }
42
43template <TInt C>
44NONSHARABLE_CLASS(TVectorBuffer) : public TNodeBuffer
45 {
46 public:
47 TVectorBuffer();
48 TInt Append(const TDesC8& aData);
49 // TInt AppendOverwrite(const TDesC8& aData);
50 TPtrC8 Shift();
51 TPtrC8 operator[](TInt aIndex) const;
52 TInt Size() const;
53 private:
54 TInt GetRoom(TInt aSize) const;
55 TInt Unreserved() const;
56 private:
57 TNode* iTop;
58 TNode* iBottom;
59 TInt iSize;
60 TUint8 iBuffer[C];
61 };
62
63template <TInt C>
64TVectorBuffer<C>::TVectorBuffer() : iSize(0)
65 {
66 Mem::FillZ(iBuffer, C);
67 iTop = TNode::Empty(iBuffer); //these points to buffer
68 iBottom = TNode::Empty(iBuffer);
69 }
70
71template<TInt C >
72TInt TVectorBuffer<C>::Unreserved() const
73 {
74 __ASSERT_DEBUG(iBottom < iBottom->Succ(), VECPANIC(KErrCorrupt));
75 const TInt bytesbetween =
76 reinterpret_cast<const TUint8*>(iBottom->Succ()) -
77 reinterpret_cast<const TUint8*>(iTop);
78 const TInt topsize = sizeof(TNode);
79 if(bytesbetween > 0) //bytesbetween is room between bottom and top
80 { //therefore free room is subracted from free space
81
82 const TInt room = C - bytesbetween - topsize;
83 return room;
84 }
85 if(bytesbetween == 0)
86 {
87
88 if(Size() > 0)
89 return 0;
90 else
91 return C - topsize;
92 }
93 const TInt room = -bytesbetween - topsize; //free is space between pointers
94 return room;
95 }
96
97template <TInt C>
98TInt TVectorBuffer<C>::GetRoom(TInt aSize) const
99 {
100 const TInt bytesnew = sizeof(TNode) + aSize;
101 const TInt room = Unreserved() - bytesnew;
102 return room;
103 }
104
105template <TInt C>
106TInt TVectorBuffer<C>::Append(const TDesC8& aData) //ei ole ok!
107 {
108 const TInt len = aData.Length();
109 if(GetRoom(len) < 0)
110 {
111 return KErrOverflow;
112 }
113 if(iBottom->Succ()->Ptr() - iBuffer > (C - (len + TInt(sizeof(TNode)))))
114 {
115 VLOG("rc");
116 // RDebug::Print(_L("vector: append"));
117 TNode* p = TNode::Empty(iBuffer);
118 iBottom->Terminator(p);
119 iBottom = p;
120 return Append(aData);
121 // Append();
122 // iBottom = TNode::New(p, aData); //just append something into end
123 }
124
125 //DEBUG_INT++;
126
127 iBottom = TNode::New(iBottom, aData);
128
129 iSize += len;
130 return KErrNone;
131 }
132
133/*
134template <TInt C>
135TInt TVectorBuffer<C>::AppendOverwrite(const TDesC8& aData) //ei ole ok!
136 {
137 while(Append(aData) == KErrOverflow)
138 {
139 if(iTop->Succ() == NULL)
140 {
141 return KErrUnderflow;
142 }
143 //Shift(); //data is lost
144 }
145 return KErrNone;
146 }
147*/
148template <TInt C>
149TPtrC8 TVectorBuffer<C>::Shift()
150 {
151 __ASSERT_ALWAYS(iTop->Succ() != NULL, VECPANIC(KErrUnderflow)); //can never pass-by bottom
152 TNode* node = iTop;
153 iTop = iTop->Succ();
154 if(iTop > node)
155 {
156 // DEBUG_INT--;
157 iSize -= node->Size();
158 return TPtrC8(node->Ptr(), node->Size());
159 }
160 else
161 {
162 // RDebug::Print(_L("vector: shift"));
163 return Shift(); //this happens when buffer is terminated, and data lies in next
164 }
165 }
166
167template <TInt C>
168TInt TVectorBuffer<C>::Size() const
169 {
170 return iSize;
171 }
172
173template <TInt C>
174TPtrC8 TVectorBuffer<C>::operator[](TInt aIndex) const
175 {
176 TInt index = 0;
177 TNode* t = iTop->Size() > 0 ? iTop : iTop->Succ(); //eliminate terminator
178 while(index < aIndex)
179 {
180 TNode* nt = t->Succ();
181 if(nt < t)
182 {
183 nt = nt->Succ();
184 }
185 t = nt;
186 if(t->Size() > 0)
187 index++;
188 __ASSERT_ALWAYS(t->Succ() != NULL, VECPANIC(KErrUnderflow)); //can never pass-by bottom
189 }
190 return t->Ptr();
191 }
192
193
194template <class T, TInt C>
195NONSHARABLE_CLASS(TVector) : public TVectorBuffer<C * sizeof(T)>
196 {
197 public:
198 TVector();
199 TInt Append(const T& aData);
200 const T& Shift();
201 TInt Size() const;
202 const T& operator[](TInt aIndex) const;
203 };
204
205template <class T, TInt C>
206TVector<T, C>::TVector() : TVectorBuffer<C * sizeof(T)>()
207 {
208 }
209
210template <class T, TInt C>
211TInt TVector<T, C>::Append(const T& aData)
212 {
213 const TPckgC<T> data(aData);
214 return TVectorBuffer<C * sizeof(T)>::Append(data);
215 }
216
217template <class T, TInt C>
218const T& TVector<T, C>::Shift()
219 {
220 const TPtrC8 ptr = TVectorBuffer<C * sizeof(T)>::Shift();
221 return *(reinterpret_cast<const T*>(ptr.Ptr()));
222 }
223
224
225template <class T, TInt C>
226TInt TVector<T, C>::Size() const
227 {
228 return TVectorBuffer<C * sizeof(T)>::Size() / sizeof(T);
229 }
230
231template <class T, TInt C>
232const T& TVector<T, C>::operator[](TInt aIndex) const
233 {
234 const TPtrC8 ptr = TVectorBuffer<C * sizeof(T)>::operator[](aIndex);
235 return *(reinterpret_cast<const T*>(ptr.Ptr()));
236 }
237
238#endif
239
240
diff --git a/apps/plugins/sdl/src/main/win32/SDL_win32_main.c b/apps/plugins/sdl/src/main/win32/SDL_win32_main.c
deleted file mode 100644
index 672b48c12e..0000000000
--- a/apps/plugins/sdl/src/main/win32/SDL_win32_main.c
+++ /dev/null
@@ -1,402 +0,0 @@
1/*
2 SDL_main.c, placed in the public domain by Sam Lantinga 4/13/98
3
4 The WinMain function -- calls your program's main() function
5*/
6
7#include <stdio.h>
8#include <stdlib.h>
9
10#define WIN32_LEAN_AND_MEAN
11#include <windows.h>
12
13#ifdef _WIN32_WCE
14# define DIR_SEPERATOR TEXT("\\")
15# undef _getcwd
16# define _getcwd(str,len) wcscpy(str,TEXT(""))
17# define setbuf(f,b)
18# define setvbuf(w,x,y,z)
19# define fopen _wfopen
20# define freopen _wfreopen
21# define remove(x) DeleteFile(x)
22#else
23# define DIR_SEPERATOR TEXT("/")
24# include <direct.h>
25#endif
26
27/* Include the SDL main definition header */
28#include "SDL.h"
29#include "SDL_main.h"
30
31#ifdef main
32# ifndef _WIN32_WCE_EMULATION
33# undef main
34# endif /* _WIN32_WCE_EMULATION */
35#endif /* main */
36
37/* The standard output files */
38#define STDOUT_FILE TEXT("stdout.txt")
39#define STDERR_FILE TEXT("stderr.txt")
40
41/* Set a variable to tell if the stdio redirect has been enabled. */
42static int stdioRedirectEnabled = 0;
43
44#ifdef _WIN32_WCE
45 static wchar_t stdoutPath[MAX_PATH];
46 static wchar_t stderrPath[MAX_PATH];
47#else
48 static char stdoutPath[MAX_PATH];
49 static char stderrPath[MAX_PATH];
50#endif
51
52#if defined(_WIN32_WCE) && _WIN32_WCE < 300
53/* seems to be undefined in Win CE although in online help */
54#define isspace(a) (((CHAR)a == ' ') || ((CHAR)a == '\t'))
55#endif /* _WIN32_WCE < 300 */
56
57static void UnEscapeQuotes( char *arg )
58{
59 char *last = NULL;
60
61 while( *arg ) {
62 if( *arg == '"' && *last == '\\' ) {
63 char *c_curr = arg;
64 char *c_last = last;
65
66 while( *c_curr ) {
67 *c_last = *c_curr;
68 c_last = c_curr;
69 c_curr++;
70 }
71 *c_last = '\0';
72 }
73 last = arg;
74 arg++;
75 }
76}
77
78/* Parse a command line buffer into arguments */
79static int ParseCommandLine(char *cmdline, char **argv)
80{
81 char *bufp;
82 char *lastp = NULL;
83 int argc, last_argc;
84
85 argc = last_argc = 0;
86 for ( bufp = cmdline; *bufp; ) {
87 /* Skip leading whitespace */
88 while ( isspace(*bufp) ) {
89 ++bufp;
90 }
91 /* Skip over argument */
92 if ( *bufp == '"' ) {
93 ++bufp;
94 if ( *bufp ) {
95 if ( argv ) {
96 argv[argc] = bufp;
97 }
98 ++argc;
99 }
100 /* Skip over word */
101 while ( *bufp && ( *bufp != '"' || (lastp && *lastp == '\\') ) ) {
102 lastp = bufp;
103 ++bufp;
104 }
105 } else {
106 if ( *bufp ) {
107 if ( argv ) {
108 argv[argc] = bufp;
109 }
110 ++argc;
111 }
112 /* Skip over word */
113 while ( *bufp && ! isspace(*bufp) ) {
114 ++bufp;
115 }
116 }
117 if ( *bufp ) {
118 if ( argv ) {
119 *bufp = '\0';
120 }
121 ++bufp;
122 }
123
124 /* Strip out \ from \" sequences */
125 if( argv && last_argc != argc ) {
126 UnEscapeQuotes( argv[last_argc] );
127 }
128 last_argc = argc;
129 }
130 if ( argv ) {
131 argv[argc] = NULL;
132 }
133 return(argc);
134}
135
136/* Show an error message */
137static void ShowError(const char *title, const char *message)
138{
139/* If USE_MESSAGEBOX is defined, you need to link with user32.lib */
140#ifdef USE_MESSAGEBOX
141 MessageBox(NULL, message, title, MB_ICONEXCLAMATION|MB_OK);
142#else
143 fprintf(stderr, "%s: %s\n", title, message);
144#endif
145}
146
147/* Pop up an out of memory message, returns to Windows */
148static BOOL OutOfMemory(void)
149{
150 ShowError("Fatal Error", "Out of memory - aborting");
151 return FALSE;
152}
153
154/* SDL_Quit() shouldn't be used with atexit() directly because
155 calling conventions may differ... */
156static void cleanup(void)
157{
158 SDL_Quit();
159}
160
161/* Remove the output files if there was no output written */
162static void cleanup_output(void) {
163 FILE *file;
164 int empty;
165
166 /* Flush the output in case anything is queued */
167 fclose(stdout);
168 fclose(stderr);
169
170 /* Without redirection we're done */
171 if (!stdioRedirectEnabled) {
172 return;
173 }
174
175 /* See if the files have any output in them */
176 if ( stdoutPath[0] ) {
177 file = fopen(stdoutPath, TEXT("rb"));
178 if ( file ) {
179 empty = (fgetc(file) == EOF) ? 1 : 0;
180 fclose(file);
181 if ( empty ) {
182 remove(stdoutPath);
183 }
184 }
185 }
186 if ( stderrPath[0] ) {
187 file = fopen(stderrPath, TEXT("rb"));
188 if ( file ) {
189 empty = (fgetc(file) == EOF) ? 1 : 0;
190 fclose(file);
191 if ( empty ) {
192 remove(stderrPath);
193 }
194 }
195 }
196}
197
198/* Redirect the output (stdout and stderr) to a file */
199static void redirect_output(void)
200{
201 DWORD pathlen;
202#ifdef _WIN32_WCE
203 wchar_t path[MAX_PATH];
204#else
205 char path[MAX_PATH];
206#endif
207 FILE *newfp;
208
209 pathlen = GetModuleFileName(NULL, path, SDL_arraysize(path));
210 while ( pathlen > 0 && path[pathlen] != '\\' ) {
211 --pathlen;
212 }
213 path[pathlen] = '\0';
214
215#ifdef _WIN32_WCE
216 wcsncpy( stdoutPath, path, SDL_arraysize(stdoutPath) );
217 wcsncat( stdoutPath, DIR_SEPERATOR STDOUT_FILE, SDL_arraysize(stdoutPath) );
218#else
219 SDL_strlcpy( stdoutPath, path, SDL_arraysize(stdoutPath) );
220 SDL_strlcat( stdoutPath, DIR_SEPERATOR STDOUT_FILE, SDL_arraysize(stdoutPath) );
221#endif
222
223 /* Redirect standard input and standard output */
224 newfp = freopen(stdoutPath, TEXT("w"), stdout);
225
226#ifndef _WIN32_WCE
227 if ( newfp == NULL ) { /* This happens on NT */
228#if !defined(stdout)
229 stdout = fopen(stdoutPath, TEXT("w"));
230#else
231 newfp = fopen(stdoutPath, TEXT("w"));
232 if ( newfp ) {
233 *stdout = *newfp;
234 }
235#endif
236 }
237#endif /* _WIN32_WCE */
238
239#ifdef _WIN32_WCE
240 wcsncpy( stderrPath, path, SDL_arraysize(stdoutPath) );
241 wcsncat( stderrPath, DIR_SEPERATOR STDOUT_FILE, SDL_arraysize(stdoutPath) );
242#else
243 SDL_strlcpy( stderrPath, path, SDL_arraysize(stderrPath) );
244 SDL_strlcat( stderrPath, DIR_SEPERATOR STDERR_FILE, SDL_arraysize(stderrPath) );
245#endif
246
247 newfp = freopen(stderrPath, TEXT("w"), stderr);
248#ifndef _WIN32_WCE
249 if ( newfp == NULL ) { /* This happens on NT */
250#if !defined(stderr)
251 stderr = fopen(stderrPath, TEXT("w"));
252#else
253 newfp = fopen(stderrPath, TEXT("w"));
254 if ( newfp ) {
255 *stderr = *newfp;
256 }
257#endif
258 }
259#endif /* _WIN32_WCE */
260
261 setvbuf(stdout, NULL, _IOLBF, BUFSIZ); /* Line buffered */
262 setbuf(stderr, NULL); /* No buffering */
263 stdioRedirectEnabled = 1;
264}
265
266#if defined(_MSC_VER) && !defined(_WIN32_WCE)
267/* The VC++ compiler needs main defined */
268#define console_main main
269#endif
270
271/* This is where execution begins [console apps] */
272int console_main(int argc, char *argv[])
273{
274 size_t n;
275 char *bufp, *appname;
276 int status;
277
278 /* Get the class name from argv[0] */
279 appname = argv[0];
280 if ( (bufp=SDL_strrchr(argv[0], '\\')) != NULL ) {
281 appname = bufp+1;
282 } else
283 if ( (bufp=SDL_strrchr(argv[0], '/')) != NULL ) {
284 appname = bufp+1;
285 }
286
287 if ( (bufp=SDL_strrchr(appname, '.')) == NULL )
288 n = SDL_strlen(appname);
289 else
290 n = (bufp-appname);
291
292 bufp = SDL_stack_alloc(char, n+1);
293 if ( bufp == NULL ) {
294 return OutOfMemory();
295 }
296 SDL_strlcpy(bufp, appname, n+1);
297 appname = bufp;
298
299 /* Load SDL dynamic link library */
300 if ( SDL_Init(SDL_INIT_NOPARACHUTE) < 0 ) {
301 ShowError("WinMain() error", SDL_GetError());
302 return(FALSE);
303 }
304 atexit(cleanup_output);
305 atexit(cleanup);
306
307 /* Sam:
308 We still need to pass in the application handle so that
309 DirectInput will initialize properly when SDL_RegisterApp()
310 is called later in the video initialization.
311 */
312 SDL_SetModuleHandle(GetModuleHandle(NULL));
313
314 /* Run the application main() code */
315 status = SDL_main(argc, argv);
316
317 /* Exit cleanly, calling atexit() functions */
318 exit(status);
319
320 /* Hush little compiler, don't you cry... */
321 return 0;
322}
323
324/* This is where execution begins [windowed apps] */
325#ifdef _WIN32_WCE
326int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPWSTR szCmdLine, int sw)
327#else
328int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw)
329#endif
330{
331 HMODULE handle;
332 char **argv;
333 int argc;
334 char *cmdline;
335 char *env_str;
336#ifdef _WIN32_WCE
337 wchar_t *bufp;
338 int nLen;
339#else
340 char *bufp;
341 size_t nLen;
342#endif
343
344 /* Start up DDHELP.EXE before opening any files, so DDHELP doesn't
345 keep them open. This is a hack.. hopefully it will be fixed
346 someday. DDHELP.EXE starts up the first time DDRAW.DLL is loaded.
347 */
348 handle = LoadLibrary(TEXT("DDRAW.DLL"));
349 if ( handle != NULL ) {
350 FreeLibrary(handle);
351 }
352
353 /* Check for stdio redirect settings and do the redirection */
354 if ((env_str = SDL_getenv("SDL_STDIO_REDIRECT"))) {
355 if (SDL_atoi(env_str)) {
356 redirect_output();
357 }
358 }
359#ifndef NO_STDIO_REDIRECT
360 else {
361 redirect_output();
362 }
363#endif
364
365#ifdef _WIN32_WCE
366 nLen = wcslen(szCmdLine)+128+1;
367 bufp = SDL_stack_alloc(wchar_t, nLen*2);
368 wcscpy (bufp, TEXT("\""));
369 GetModuleFileName(NULL, bufp+1, 128-3);
370 wcscpy (bufp+wcslen(bufp), TEXT("\" "));
371 wcsncpy(bufp+wcslen(bufp), szCmdLine,nLen-wcslen(bufp));
372 nLen = wcslen(bufp)+1;
373 cmdline = SDL_stack_alloc(char, nLen);
374 if ( cmdline == NULL ) {
375 return OutOfMemory();
376 }
377 WideCharToMultiByte(CP_ACP, 0, bufp, -1, cmdline, nLen, NULL, NULL);
378#else
379 /* Grab the command line */
380 bufp = GetCommandLine();
381 nLen = SDL_strlen(bufp)+1;
382 cmdline = SDL_stack_alloc(char, nLen);
383 if ( cmdline == NULL ) {
384 return OutOfMemory();
385 }
386 SDL_strlcpy(cmdline, bufp, nLen);
387#endif
388
389 /* Parse it into argv and argc */
390 argc = ParseCommandLine(cmdline, NULL);
391 argv = SDL_stack_alloc(char*, argc+1);
392 if ( argv == NULL ) {
393 return OutOfMemory();
394 }
395 ParseCommandLine(cmdline, argv);
396
397 /* Run the main program (after a little SDL initialization) */
398 console_main(argc, argv);
399
400 /* Hush little compiler, don't you cry... */
401 return 0;
402}
diff --git a/apps/plugins/sdl/src/main/win32/version.rc b/apps/plugins/sdl/src/main/win32/version.rc
deleted file mode 100644
index 38fb6423e8..0000000000
--- a/apps/plugins/sdl/src/main/win32/version.rc
+++ /dev/null
@@ -1,38 +0,0 @@
1
2#include "winresrc.h"
3
4LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
5
6/////////////////////////////////////////////////////////////////////////////
7//
8// Version
9//
10
11VS_VERSION_INFO VERSIONINFO
12 FILEVERSION 1,2,14,0
13 PRODUCTVERSION 1,2,14,0
14 FILEFLAGSMASK 0x3fL
15 FILEFLAGS 0x0L
16 FILEOS 0x40004L
17 FILETYPE 0x2L
18 FILESUBTYPE 0x0L
19BEGIN
20 BLOCK "StringFileInfo"
21 BEGIN
22 BLOCK "040904b0"
23 BEGIN
24 VALUE "CompanyName", "\0"
25 VALUE "FileDescription", "SDL\0"
26 VALUE "FileVersion", "1, 2, 14, 0\0"
27 VALUE "InternalName", "SDL\0"
28 VALUE "LegalCopyright", "Copyright © 2009 Sam Lantinga\0"
29 VALUE "OriginalFilename", "SDL.dll\0"
30 VALUE "ProductName", "Simple DirectMedia Layer\0"
31 VALUE "ProductVersion", "1, 2, 14, 0\0"
32 END
33 END
34 BLOCK "VarFileInfo"
35 BEGIN
36 VALUE "Translation", 0x409, 1200
37 END
38END
diff --git a/apps/plugins/sdl/src/thread/beos/SDL_syssem.c b/apps/plugins/sdl/src/thread/beos/SDL_syssem.c
deleted file mode 100644
index eba1944bc8..0000000000
--- a/apps/plugins/sdl/src/thread/beos/SDL_syssem.c
+++ /dev/null
@@ -1,142 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Semaphores in the BeOS environment */
25
26#include <be/kernel/OS.h>
27
28#include "SDL_thread.h"
29
30
31struct SDL_semaphore {
32 sem_id id;
33};
34
35/* Create a counting semaphore */
36SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
37{
38 SDL_sem *sem;
39
40 sem = (SDL_sem *)SDL_malloc(sizeof(*sem));
41 if ( sem ) {
42 sem->id = create_sem(initial_value, "SDL semaphore");
43 if ( sem->id < B_NO_ERROR ) {
44 SDL_SetError("create_sem() failed");
45 SDL_free(sem);
46 sem = NULL;
47 }
48 } else {
49 SDL_OutOfMemory();
50 }
51 return(sem);
52}
53
54/* Free the semaphore */
55void SDL_DestroySemaphore(SDL_sem *sem)
56{
57 if ( sem ) {
58 if ( sem->id >= B_NO_ERROR ) {
59 delete_sem(sem->id);
60 }
61 SDL_free(sem);
62 }
63}
64
65int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
66{
67 int32 val;
68 int retval;
69
70 if ( ! sem ) {
71 SDL_SetError("Passed a NULL semaphore");
72 return -1;
73 }
74
75 tryagain:
76 if ( timeout == SDL_MUTEX_MAXWAIT ) {
77 val = acquire_sem(sem->id);
78 } else {
79 timeout *= 1000; /* BeOS uses a timeout in microseconds */
80 val = acquire_sem_etc(sem->id, 1, B_RELATIVE_TIMEOUT, timeout);
81 }
82 switch (val) {
83 case B_INTERRUPTED:
84 goto tryagain;
85 case B_NO_ERROR:
86 retval = 0;
87 break;
88 case B_TIMED_OUT:
89 retval = SDL_MUTEX_TIMEDOUT;
90 break;
91 case B_WOULD_BLOCK:
92 retval = SDL_MUTEX_TIMEDOUT;
93 break;
94 default:
95 SDL_SetError("acquire_sem() failed");
96 retval = -1;
97 break;
98 }
99
100 return retval;
101}
102
103int SDL_SemTryWait(SDL_sem *sem)
104{
105 return SDL_SemWaitTimeout(sem, 0);
106}
107
108int SDL_SemWait(SDL_sem *sem)
109{
110 return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT);
111}
112
113/* Returns the current count of the semaphore */
114Uint32 SDL_SemValue(SDL_sem *sem)
115{
116 int32 count;
117 Uint32 value;
118
119 value = 0;
120 if ( sem ) {
121 get_sem_count(sem->id, &count);
122 if ( count > 0 ) {
123 value = (Uint32)count;
124 }
125 }
126 return value;
127}
128
129/* Atomically increases the semaphore's count (not blocking) */
130int SDL_SemPost(SDL_sem *sem)
131{
132 if ( ! sem ) {
133 SDL_SetError("Passed a NULL semaphore");
134 return -1;
135 }
136
137 if ( release_sem(sem->id) != B_NO_ERROR ) {
138 SDL_SetError("release_sem() failed");
139 return -1;
140 }
141 return 0;
142}
diff --git a/apps/plugins/sdl/src/thread/beos/SDL_systhread.c b/apps/plugins/sdl/src/thread/beos/SDL_systhread.c
deleted file mode 100644
index 63b52075f0..0000000000
--- a/apps/plugins/sdl/src/thread/beos/SDL_systhread.c
+++ /dev/null
@@ -1,96 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* BeOS thread management routines for SDL */
25
26#include <stdio.h>
27#include <signal.h>
28#include <be/kernel/OS.h>
29
30#include "SDL_mutex.h"
31#include "SDL_thread.h"
32#include "../SDL_thread_c.h"
33#include "../SDL_systhread.h"
34
35
36static int sig_list[] = {
37 SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGWINCH, 0
38};
39
40void SDL_MaskSignals(sigset_t *omask)
41{
42 sigset_t mask;
43 int i;
44
45 sigemptyset(&mask);
46 for ( i=0; sig_list[i]; ++i ) {
47 sigaddset(&mask, sig_list[i]);
48 }
49 sigprocmask(SIG_BLOCK, &mask, omask);
50}
51void SDL_UnmaskSignals(sigset_t *omask)
52{
53 sigprocmask(SIG_SETMASK, omask, NULL);
54}
55
56static int32 RunThread(void *data)
57{
58 SDL_RunThread(data);
59 return(0);
60}
61
62int SDL_SYS_CreateThread(SDL_Thread *thread, void *args)
63{
64 /* Create the thread and go! */
65 thread->handle=spawn_thread(RunThread, "SDL", B_NORMAL_PRIORITY, args);
66 if ( (thread->handle == B_NO_MORE_THREADS) ||
67 (thread->handle == B_NO_MEMORY) ) {
68 SDL_SetError("Not enough resources to create thread");
69 return(-1);
70 }
71 resume_thread(thread->handle);
72 return(0);
73}
74
75void SDL_SYS_SetupThread(void)
76{
77 /* Mask asynchronous signals for this thread */
78 SDL_MaskSignals(NULL);
79}
80
81Uint32 SDL_ThreadID(void)
82{
83 return((Uint32)find_thread(NULL));
84}
85
86void SDL_SYS_WaitThread(SDL_Thread *thread)
87{
88 status_t the_status;
89
90 wait_for_thread(thread->handle, &the_status);
91}
92
93void SDL_SYS_KillThread(SDL_Thread *thread)
94{
95 kill_thread(thread->handle);
96}
diff --git a/apps/plugins/sdl/src/thread/beos/SDL_systhread_c.h b/apps/plugins/sdl/src/thread/beos/SDL_systhread_c.h
deleted file mode 100644
index f82548e463..0000000000
--- a/apps/plugins/sdl/src/thread/beos/SDL_systhread_c.h
+++ /dev/null
@@ -1,31 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <signal.h>
25#include <be/kernel/OS.h>
26
27typedef thread_id SYS_ThreadHandle;
28
29/* Functions needed to work with system threads in other portions of SDL */
30extern void SDL_MaskSignals(sigset_t *omask);
31extern void SDL_UnmaskSignals(sigset_t *omask);
diff --git a/apps/plugins/sdl/src/thread/dc/SDL_syscond.c b/apps/plugins/sdl/src/thread/dc/SDL_syscond.c
deleted file mode 100644
index f6e7223e3d..0000000000
--- a/apps/plugins/sdl/src/thread/dc/SDL_syscond.c
+++ /dev/null
@@ -1,215 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* An implementation of condition variables using semaphores and mutexes */
25/*
26 This implementation borrows heavily from the BeOS condition variable
27 implementation, written by Christopher Tate and Owen Smith. Thanks!
28 */
29
30#include "SDL_thread.h"
31
32struct SDL_cond
33{
34 SDL_mutex *lock;
35 int waiting;
36 int signals;
37 SDL_sem *wait_sem;
38 SDL_sem *wait_done;
39};
40
41/* Create a condition variable */
42SDL_cond * SDL_CreateCond(void)
43{
44 SDL_cond *cond;
45
46 cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond));
47 if ( cond ) {
48 cond->lock = SDL_CreateMutex();
49 cond->wait_sem = SDL_CreateSemaphore(0);
50 cond->wait_done = SDL_CreateSemaphore(0);
51 cond->waiting = cond->signals = 0;
52 if ( ! cond->lock || ! cond->wait_sem || ! cond->wait_done ) {
53 SDL_DestroyCond(cond);
54 cond = NULL;
55 }
56 } else {
57 SDL_OutOfMemory();
58 }
59 return(cond);
60}
61
62/* Destroy a condition variable */
63void SDL_DestroyCond(SDL_cond *cond)
64{
65 if ( cond ) {
66 if ( cond->wait_sem ) {
67 SDL_DestroySemaphore(cond->wait_sem);
68 }
69 if ( cond->wait_done ) {
70 SDL_DestroySemaphore(cond->wait_done);
71 }
72 if ( cond->lock ) {
73 SDL_DestroyMutex(cond->lock);
74 }
75 SDL_free(cond);
76 }
77}
78
79/* Restart one of the threads that are waiting on the condition variable */
80int SDL_CondSignal(SDL_cond *cond)
81{
82 if ( ! cond ) {
83 SDL_SetError("Passed a NULL condition variable");
84 return -1;
85 }
86
87 /* If there are waiting threads not already signalled, then
88 signal the condition and wait for the thread to respond.
89 */
90 SDL_LockMutex(cond->lock);
91 if ( cond->waiting > cond->signals ) {
92 ++cond->signals;
93 SDL_SemPost(cond->wait_sem);
94 SDL_UnlockMutex(cond->lock);
95 SDL_SemWait(cond->wait_done);
96 } else {
97 SDL_UnlockMutex(cond->lock);
98 }
99
100 return 0;
101}
102
103/* Restart all threads that are waiting on the condition variable */
104int SDL_CondBroadcast(SDL_cond *cond)
105{
106 if ( ! cond ) {
107 SDL_SetError("Passed a NULL condition variable");
108 return -1;
109 }
110
111 /* If there are waiting threads not already signalled, then
112 signal the condition and wait for the thread to respond.
113 */
114 SDL_LockMutex(cond->lock);
115 if ( cond->waiting > cond->signals ) {
116 int i, num_waiting;
117
118 num_waiting = (cond->waiting - cond->signals);
119 cond->signals = cond->waiting;
120 for ( i=0; i<num_waiting; ++i ) {
121 SDL_SemPost(cond->wait_sem);
122 }
123 /* Now all released threads are blocked here, waiting for us.
124 Collect them all (and win fabulous prizes!) :-)
125 */
126 SDL_UnlockMutex(cond->lock);
127 for ( i=0; i<num_waiting; ++i ) {
128 SDL_SemWait(cond->wait_done);
129 }
130 } else {
131 SDL_UnlockMutex(cond->lock);
132 }
133
134 return 0;
135}
136
137/* Wait on the condition variable for at most 'ms' milliseconds.
138 The mutex must be locked before entering this function!
139 The mutex is unlocked during the wait, and locked again after the wait.
140
141Typical use:
142
143Thread A:
144 SDL_LockMutex(lock);
145 while ( ! condition ) {
146 SDL_CondWait(cond);
147 }
148 SDL_UnlockMutex(lock);
149
150Thread B:
151 SDL_LockMutex(lock);
152 ...
153 condition = true;
154 ...
155 SDL_UnlockMutex(lock);
156 */
157int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms)
158{
159 int retval;
160
161 if ( ! cond ) {
162 SDL_SetError("Passed a NULL condition variable");
163 return -1;
164 }
165
166 /* Obtain the protection mutex, and increment the number of waiters.
167 This allows the signal mechanism to only perform a signal if there
168 are waiting threads.
169 */
170 SDL_LockMutex(cond->lock);
171 ++cond->waiting;
172 SDL_UnlockMutex(cond->lock);
173
174 /* Unlock the mutex, as is required by condition variable semantics */
175 SDL_UnlockMutex(mutex);
176
177 /* Wait for a signal */
178 if ( ms == SDL_MUTEX_MAXWAIT ) {
179 retval = SDL_SemWait(cond->wait_sem);
180 } else {
181 retval = SDL_SemWaitTimeout(cond->wait_sem, ms);
182 }
183
184 /* Let the signaler know we have completed the wait, otherwise
185 the signaler can race ahead and get the condition semaphore
186 if we are stopped between the mutex unlock and semaphore wait,
187 giving a deadlock. See the following URL for details:
188 http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html
189 */
190 SDL_LockMutex(cond->lock);
191 if ( cond->signals > 0 ) {
192 /* If we timed out, we need to eat a condition signal */
193 if ( retval > 0 ) {
194 SDL_SemWait(cond->wait_sem);
195 }
196 /* We always notify the signal thread that we are done */
197 SDL_SemPost(cond->wait_done);
198
199 /* Signal handshake complete */
200 --cond->signals;
201 }
202 --cond->waiting;
203 SDL_UnlockMutex(cond->lock);
204
205 /* Lock the mutex, as is required by condition variable semantics */
206 SDL_LockMutex(mutex);
207
208 return retval;
209}
210
211/* Wait on the condition variable forever */
212int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex)
213{
214 return SDL_CondWaitTimeout(cond, mutex, SDL_MUTEX_MAXWAIT);
215}
diff --git a/apps/plugins/sdl/src/thread/dc/SDL_syscond_c.h b/apps/plugins/sdl/src/thread/dc/SDL_syscond_c.h
deleted file mode 100644
index 1120b2d80d..0000000000
--- a/apps/plugins/sdl/src/thread/dc/SDL_syscond_c.h
+++ /dev/null
@@ -1,23 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
diff --git a/apps/plugins/sdl/src/thread/dc/SDL_sysmutex.c b/apps/plugins/sdl/src/thread/dc/SDL_sysmutex.c
deleted file mode 100644
index c6c465131b..0000000000
--- a/apps/plugins/sdl/src/thread/dc/SDL_sysmutex.c
+++ /dev/null
@@ -1,122 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* An implementation of mutexes using semaphores */
25
26#include "SDL_thread.h"
27#include "SDL_systhread_c.h"
28
29#include <arch/spinlock.h>
30
31struct SDL_mutex {
32 int recursive;
33 Uint32 owner;
34 spinlock_t mutex;
35};
36
37/* Create a mutex */
38SDL_mutex *SDL_CreateMutex(void)
39{
40 SDL_mutex *mutex;
41
42 /* Allocate mutex memory */
43 mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex));
44 if ( mutex ) {
45 spinlock_init(&mutex->mutex);
46 mutex->recursive = 0;
47 mutex->owner = 0;
48 } else {
49 SDL_OutOfMemory();
50 }
51 return mutex;
52}
53
54/* Free the mutex */
55void SDL_DestroyMutex(SDL_mutex *mutex)
56{
57 if ( mutex ) {
58 SDL_free(mutex);
59 }
60}
61
62/* Lock the semaphore */
63int SDL_mutexP(SDL_mutex *mutex)
64{
65#if SDL_THREADS_DISABLED
66 return SDL_arraysize(return ),0;
67#else
68 Uint32 this_thread;
69
70 if ( mutex == NULL ) {
71 SDL_SetError("Passed a NULL mutex");
72 return -1;
73 }
74
75 this_thread = SDL_ThreadID();
76 if ( mutex->owner == this_thread ) {
77 ++mutex->recursive;
78 } else {
79 /* The order of operations is important.
80 We set the locking thread id after we obtain the lock
81 so unlocks from other threads will fail.
82 */
83 spinlock_lock(&mutex->mutex);
84 mutex->owner = this_thread;
85 mutex->recursive = 0;
86 }
87
88 return 0;
89#endif /* SDL_THREADS_DISABLED */
90}
91
92/* Unlock the mutex */
93int SDL_mutexV(SDL_mutex *mutex)
94{
95#if SDL_THREADS_DISABLED
96 return 0;
97#else
98 if ( mutex == NULL ) {
99 SDL_SetError("Passed a NULL mutex");
100 return -1;
101 }
102
103 /* If we don't own the mutex, we can't unlock it */
104 if ( SDL_ThreadID() != mutex->owner ) {
105 SDL_SetError("mutex not owned by this thread");
106 return -1;
107 }
108
109 if ( mutex->recursive ) {
110 --mutex->recursive;
111 } else {
112 /* The order of operations is important.
113 First reset the owner so another thread doesn't lock
114 the mutex and set the ownership before we reset it,
115 then release the lock semaphore.
116 */
117 mutex->owner = 0;
118 spinlock_unlock(&mutex->mutex);
119 }
120 return 0;
121#endif /* SDL_THREADS_DISABLED */
122}
diff --git a/apps/plugins/sdl/src/thread/dc/SDL_sysmutex_c.h b/apps/plugins/sdl/src/thread/dc/SDL_sysmutex_c.h
deleted file mode 100644
index 1120b2d80d..0000000000
--- a/apps/plugins/sdl/src/thread/dc/SDL_sysmutex_c.h
+++ /dev/null
@@ -1,23 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
diff --git a/apps/plugins/sdl/src/thread/dc/SDL_syssem.c b/apps/plugins/sdl/src/thread/dc/SDL_syssem.c
deleted file mode 100644
index 9831ccdbd7..0000000000
--- a/apps/plugins/sdl/src/thread/dc/SDL_syssem.c
+++ /dev/null
@@ -1,173 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23#include <errno.h>
24
25#include "SDL_config.h"
26
27/* An implementation of semaphores using mutexes and condition variables */
28
29#include "SDL_timer.h"
30#include "SDL_thread.h"
31#include "SDL_systhread_c.h"
32
33
34#if SDL_THREADS_DISABLED
35
36SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
37{
38 SDL_SetError("SDL not configured with thread support");
39 return (SDL_sem *)0;
40}
41
42void SDL_DestroySemaphore(SDL_sem *sem)
43{
44 return;
45}
46
47int SDL_SemTryWait(SDL_sem *sem)
48{
49 SDL_SetError("SDL not configured with thread support");
50 return -1;
51}
52
53int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
54{
55 SDL_SetError("SDL not configured with thread support");
56 return -1;
57}
58
59int SDL_SemWait(SDL_sem *sem)
60{
61 SDL_SetError("SDL not configured with thread support");
62 return -1;
63}
64
65Uint32 SDL_SemValue(SDL_sem *sem)
66{
67 return 0;
68}
69
70int SDL_SemPost(SDL_sem *sem)
71{
72 SDL_SetError("SDL not configured with thread support");
73 return -1;
74}
75
76#else
77
78#include <kos/sem.h>
79
80struct SDL_semaphore
81{
82 semaphore_t sem;
83};
84
85SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
86{
87 return (SDL_sem *)sem_create(initial_value);
88}
89
90/* WARNING:
91 You cannot call this function when another thread is using the semaphore.
92*/
93void SDL_DestroySemaphore(SDL_sem *sem)
94{
95 if ( ! sem ) {
96 SDL_SetError("Passed a NULL semaphore");
97 return;
98 }
99
100 sem_destroy(&sem->sem);
101}
102
103int SDL_SemTryWait(SDL_sem *sem)
104{
105 int retval;
106
107 if ( ! sem ) {
108 SDL_SetError("Passed a NULL semaphore");
109 return -1;
110 }
111
112 retval = sem_trywait(&sem->sem);
113 if (retval==0) return 0;
114 else return SDL_MUTEX_TIMEDOUT;
115
116 return retval;
117}
118
119int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
120{
121 int retval;
122
123 if ( ! sem ) {
124 SDL_SetError("Passed a NULL semaphore");
125 return -1;
126 }
127
128 /* A timeout of 0 is an easy case */
129 if ( timeout == 0 ) {
130 return SDL_SemTryWait(sem);
131 }
132
133 retval = sem_wait_timed(&sem->sem,timeout);
134 if (retval==-1) retval= SDL_MUTEX_TIMEDOUT;
135
136 return retval;
137}
138
139int SDL_SemWait(SDL_sem *sem)
140{
141 int retval;
142
143 if ( ! sem ) {
144 SDL_SetError("Passed a NULL semaphore");
145 return -1;
146 }
147
148 while ( ((retval = sem_wait(&sem->sem)) == -1) && (errno == EINTR) ) {}
149 return retval;
150}
151
152Uint32 SDL_SemValue(SDL_sem *sem)
153{
154 if ( ! sem ) {
155 SDL_SetError("Passed a NULL semaphore");
156 return -1;
157 }
158
159 return sem_count(&sem->sem);
160}
161
162int SDL_SemPost(SDL_sem *sem)
163{
164 if ( ! sem ) {
165 SDL_SetError("Passed a NULL semaphore");
166 return -1;
167 }
168
169 sem_signal(&sem->sem);
170 return 0;
171}
172
173#endif /* SDL_THREADS_DISABLED */
diff --git a/apps/plugins/sdl/src/thread/dc/SDL_syssem_c.h b/apps/plugins/sdl/src/thread/dc/SDL_syssem_c.h
deleted file mode 100644
index 1120b2d80d..0000000000
--- a/apps/plugins/sdl/src/thread/dc/SDL_syssem_c.h
+++ /dev/null
@@ -1,23 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
diff --git a/apps/plugins/sdl/src/thread/dc/SDL_systhread.c b/apps/plugins/sdl/src/thread/dc/SDL_systhread.c
deleted file mode 100644
index dd26675491..0000000000
--- a/apps/plugins/sdl/src/thread/dc/SDL_systhread.c
+++ /dev/null
@@ -1,60 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Thread management routines for SDL */
25
26#include "SDL_thread.h"
27#include "../SDL_thread_c.h"
28#include "../SDL_systhread.h"
29
30#include <kos/thread.h>
31
32int SDL_SYS_CreateThread(SDL_Thread *thread, void *args)
33{
34 thread->handle = thd_create(SDL_RunThread,args);
35 if (thread->handle == NULL) {
36 SDL_SetError("Not enough resources to create thread");
37 return(-1);
38 }
39 return(0);
40}
41
42void SDL_SYS_SetupThread(void)
43{
44 return;
45}
46
47Uint32 SDL_ThreadID(void)
48{
49 return (Uint32)thd_get_current();
50}
51
52void SDL_SYS_WaitThread(SDL_Thread *thread)
53{
54 thd_wait(thread->handle);
55}
56
57void SDL_SYS_KillThread(SDL_Thread *thread)
58{
59 thd_destroy(thread->handle);
60}
diff --git a/apps/plugins/sdl/src/thread/dc/SDL_systhread_c.h b/apps/plugins/sdl/src/thread/dc/SDL_systhread_c.h
deleted file mode 100644
index 3cda1a4a51..0000000000
--- a/apps/plugins/sdl/src/thread/dc/SDL_systhread_c.h
+++ /dev/null
@@ -1,24 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24typedef struct kthread* SYS_ThreadHandle;
diff --git a/apps/plugins/sdl/src/thread/irix/SDL_syssem.c b/apps/plugins/sdl/src/thread/irix/SDL_syssem.c
deleted file mode 100644
index 208c379cdd..0000000000
--- a/apps/plugins/sdl/src/thread/irix/SDL_syssem.c
+++ /dev/null
@@ -1,219 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_thread.h"
25#include "SDL_timer.h"
26
27
28#include <stdio.h>
29#include <stdlib.h>
30#include <sys/types.h>
31#include <sys/ipc.h>
32#include <sys/sem.h>
33#include <errno.h>
34
35#include "SDL_error.h"
36#include "SDL_thread.h"
37
38
39struct SDL_semaphore {
40 int id;
41};
42
43/* Not defined by many operating systems, use configure to detect */
44/*
45#if !defined(HAVE_SEMUN)
46union semun {
47 int val;
48 struct semid_ds *buf;
49 ushort *array;
50};
51#endif
52*/
53
54static struct sembuf op_trywait[2] = {
55 { 0, -1, (IPC_NOWAIT|SEM_UNDO) } /* Decrement semaphore, no block */
56};
57static struct sembuf op_wait[2] = {
58 { 0, -1, SEM_UNDO } /* Decrement semaphore */
59};
60static struct sembuf op_post[1] = {
61 { 0, 1, (IPC_NOWAIT|SEM_UNDO) } /* Increment semaphore */
62};
63
64/* Create a blockable semaphore */
65SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
66{
67 extern int _creating_thread_lock; /* SDL_threads.c */
68 SDL_sem *sem;
69 union semun init;
70
71 sem = (SDL_sem *)SDL_malloc(sizeof(*sem));
72 if ( sem == NULL ) {
73 SDL_OutOfMemory();
74 return(NULL);
75 }
76 sem->id = semget(IPC_PRIVATE, 1, (0600|IPC_CREAT));
77 if ( sem->id < 0 ) {
78 SDL_SetError("Couldn't create semaphore");
79 SDL_free(sem);
80 return(NULL);
81 }
82 init.val = initial_value; /* Initialize semaphore */
83 semctl(sem->id, 0, SETVAL, init);
84 return(sem);
85}
86
87void SDL_DestroySemaphore(SDL_sem *sem)
88{
89 if ( sem ) {
90#ifdef __IRIX__
91 semctl(sem->id, 0, IPC_RMID);
92#else
93 union semun dummy;
94 dummy.val = 0;
95 semctl(sem->id, 0, IPC_RMID, dummy);
96#endif
97 SDL_free(sem);
98 }
99}
100
101int SDL_SemTryWait(SDL_sem *sem)
102{
103 int retval;
104
105 if ( ! sem ) {
106 SDL_SetError("Passed a NULL semaphore");
107 return -1;
108 }
109
110 retval = 0;
111 tryagain:
112 if ( semop(sem->id, op_trywait, 1) < 0 ) {
113 if ( errno == EINTR ) {
114 goto tryagain;
115 }
116 retval = SDL_MUTEX_TIMEDOUT;
117 }
118 return retval;
119}
120
121int SDL_SemWait(SDL_sem *sem)
122{
123 int retval;
124
125 if ( ! sem ) {
126 SDL_SetError("Passed a NULL semaphore");
127 return -1;
128 }
129
130 retval = 0;
131 tryagain:
132 if ( semop(sem->id, op_wait, 1) < 0 ) {
133 if ( errno == EINTR ) {
134 goto tryagain;
135 }
136 SDL_SetError("Semaphore operation error");
137 retval = -1;
138 }
139 return retval;
140}
141
142int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
143{
144 int retval;
145
146 if ( ! sem ) {
147 SDL_SetError("Passed a NULL semaphore");
148 return -1;
149 }
150
151 /* Try the easy cases first */
152 if ( timeout == 0 ) {
153 return SDL_SemTryWait(sem);
154 }
155 if ( timeout == SDL_MUTEX_MAXWAIT ) {
156 return SDL_SemWait(sem);
157 }
158
159 /* Ack! We have to busy wait... */
160 timeout += SDL_GetTicks();
161 do {
162 retval = SDL_SemTryWait(sem);
163 if ( retval == 0 ) {
164 break;
165 }
166 SDL_Delay(1);
167 } while ( SDL_GetTicks() < timeout );
168
169 return retval;
170}
171
172Uint32 SDL_SemValue(SDL_sem *sem)
173{
174 int semval;
175 Uint32 value;
176
177 value = 0;
178 if ( sem ) {
179 tryagain:
180#ifdef __IRIX__
181 semval = semctl(sem->id, 0, GETVAL);
182#else
183 {
184 union semun arg;
185 arg.val = 0;
186 semval = semctl(sem->id, 0, GETVAL, arg);
187 }
188#endif
189 if ( semval < 0 ) {
190 if ( errno == EINTR ) {
191 goto tryagain;
192 }
193 } else {
194 value = (Uint32)semval;
195 }
196 }
197 return value;
198}
199
200int SDL_SemPost(SDL_sem *sem)
201{
202 int retval;
203
204 if ( ! sem ) {
205 SDL_SetError("Passed a NULL semaphore");
206 return -1;
207 }
208
209 retval = 0;
210 tryagain:
211 if ( semop(sem->id, op_post, 1) < 0 ) {
212 if ( errno == EINTR ) {
213 goto tryagain;
214 }
215 SDL_SetError("Semaphore operation error");
216 retval = -1;
217 }
218 return retval;
219}
diff --git a/apps/plugins/sdl/src/thread/irix/SDL_systhread.c b/apps/plugins/sdl/src/thread/irix/SDL_systhread.c
deleted file mode 100644
index 7ae7fc6771..0000000000
--- a/apps/plugins/sdl/src/thread/irix/SDL_systhread.c
+++ /dev/null
@@ -1,85 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* IRIX thread management routines for SDL */
25
26#include <errno.h>
27#include <signal.h>
28#include <sys/types.h>
29#include <sys/wait.h>
30#include <sys/prctl.h>
31
32#include "SDL_thread.h"
33#include "../SDL_systhread.h"
34
35
36static int sig_list[] = {
37 SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCLD, SIGWINCH,
38 SIGVTALRM, SIGPROF, 0
39};
40
41
42int SDL_SYS_CreateThread(SDL_Thread *thread, void *args)
43{
44 /* Create the thread and go! */
45 if ( sproc(SDL_RunThread, PR_SALL, args) < 0 ) {
46 SDL_SetError("Not enough resources to create thread");
47 return(-1);
48 }
49 return(0);
50}
51
52void SDL_SYS_SetupThread(void)
53{
54 int i;
55 sigset_t mask;
56
57 /* Mask asynchronous signals for this thread */
58 sigemptyset(&mask);
59 for ( i=0; sig_list[i]; ++i ) {
60 sigaddset(&mask, sig_list[i]);
61 }
62 sigprocmask(SIG_BLOCK, &mask, NULL);
63}
64
65/* WARNING: This may not work for systems with 64-bit pid_t */
66Uint32 SDL_ThreadID(void)
67{
68 return((Uint32)getpid());
69}
70
71/* WARNING: This may not work for systems with 64-bit pid_t */
72void SDL_WaitThread(SDL_Thread *thread, int *status)
73{
74 errno = 0;
75 while ( errno != ECHILD ) {
76 waitpid(thread->handle, NULL, 0);
77 }
78}
79
80/* WARNING: This may not work for systems with 64-bit pid_t */
81void SDL_KillThread(SDL_Thread *thread)
82{
83 kill(thread->handle, SIGKILL);
84}
85
diff --git a/apps/plugins/sdl/src/thread/irix/SDL_systhread_c.h b/apps/plugins/sdl/src/thread/irix/SDL_systhread_c.h
deleted file mode 100644
index ee28634fb1..0000000000
--- a/apps/plugins/sdl/src/thread/irix/SDL_systhread_c.h
+++ /dev/null
@@ -1,27 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <sys/types.h>
25
26typedef pid_t SYS_ThreadHandle;
27
diff --git a/apps/plugins/sdl/src/thread/os2/SDL_syscond.c b/apps/plugins/sdl/src/thread/os2/SDL_syscond.c
deleted file mode 100644
index 3e80594c2a..0000000000
--- a/apps/plugins/sdl/src/thread/os2/SDL_syscond.c
+++ /dev/null
@@ -1,215 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* An implementation of condition variables using semaphores and mutexes */
25/*
26 This implementation borrows heavily from the BeOS condition variable
27 implementation, written by Christopher Tate and Owen Smith. Thanks!
28 */
29
30#include "SDL_thread.h"
31
32struct SDL_cond
33{
34 SDL_mutex *lock;
35 int waiting;
36 int signals;
37 SDL_sem *wait_sem;
38 SDL_sem *wait_done;
39};
40
41/* Create a condition variable */
42DECLSPEC SDL_cond * SDLCALL SDL_CreateCond(void)
43{
44 SDL_cond *cond;
45
46 cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond));
47 if ( cond ) {
48 cond->lock = SDL_CreateMutex();
49 cond->wait_sem = SDL_CreateSemaphore(0);
50 cond->wait_done = SDL_CreateSemaphore(0);
51 cond->waiting = cond->signals = 0;
52 if ( ! cond->lock || ! cond->wait_sem || ! cond->wait_done ) {
53 SDL_DestroyCond(cond);
54 cond = NULL;
55 }
56 } else {
57 SDL_OutOfMemory();
58 }
59 return(cond);
60}
61
62/* Destroy a condition variable */
63DECLSPEC void SDLCALL SDL_DestroyCond(SDL_cond *cond)
64{
65 if ( cond ) {
66 if ( cond->wait_sem ) {
67 SDL_DestroySemaphore(cond->wait_sem);
68 }
69 if ( cond->wait_done ) {
70 SDL_DestroySemaphore(cond->wait_done);
71 }
72 if ( cond->lock ) {
73 SDL_DestroyMutex(cond->lock);
74 }
75 SDL_free(cond);
76 }
77}
78
79/* Restart one of the threads that are waiting on the condition variable */
80DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond *cond)
81{
82 if ( ! cond ) {
83 SDL_SetError("Passed a NULL condition variable");
84 return -1;
85 }
86
87 /* If there are waiting threads not already signalled, then
88 signal the condition and wait for the thread to respond.
89 */
90 SDL_LockMutex(cond->lock);
91 if ( cond->waiting > cond->signals ) {
92 ++cond->signals;
93 SDL_SemPost(cond->wait_sem);
94 SDL_UnlockMutex(cond->lock);
95 SDL_SemWait(cond->wait_done);
96 } else {
97 SDL_UnlockMutex(cond->lock);
98 }
99
100 return 0;
101}
102
103/* Restart all threads that are waiting on the condition variable */
104DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond *cond)
105{
106 if ( ! cond ) {
107 SDL_SetError("Passed a NULL condition variable");
108 return -1;
109 }
110
111 /* If there are waiting threads not already signalled, then
112 signal the condition and wait for the thread to respond.
113 */
114 SDL_LockMutex(cond->lock);
115 if ( cond->waiting > cond->signals ) {
116 int i, num_waiting;
117
118 num_waiting = (cond->waiting - cond->signals);
119 cond->signals = cond->waiting;
120 for ( i=0; i<num_waiting; ++i ) {
121 SDL_SemPost(cond->wait_sem);
122 }
123 /* Now all released threads are blocked here, waiting for us.
124 Collect them all (and win fabulous prizes!) :-)
125 */
126 SDL_UnlockMutex(cond->lock);
127 for ( i=0; i<num_waiting; ++i ) {
128 SDL_SemWait(cond->wait_done);
129 }
130 } else {
131 SDL_UnlockMutex(cond->lock);
132 }
133
134 return 0;
135}
136
137/* Wait on the condition variable for at most 'ms' milliseconds.
138 The mutex must be locked before entering this function!
139 The mutex is unlocked during the wait, and locked again after the wait.
140
141Typical use:
142
143Thread A:
144 SDL_LockMutex(lock);
145 while ( ! condition ) {
146 SDL_CondWait(cond);
147 }
148 SDL_UnlockMutex(lock);
149
150Thread B:
151 SDL_LockMutex(lock);
152 ...
153 condition = true;
154 ...
155 SDL_UnlockMutex(lock);
156 */
157DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms)
158{
159 int retval;
160
161 if ( ! cond ) {
162 SDL_SetError("Passed a NULL condition variable");
163 return -1;
164 }
165
166 /* Obtain the protection mutex, and increment the number of waiters.
167 This allows the signal mechanism to only perform a signal if there
168 are waiting threads.
169 */
170 SDL_LockMutex(cond->lock);
171 ++cond->waiting;
172 SDL_UnlockMutex(cond->lock);
173
174 /* Unlock the mutex, as is required by condition variable semantics */
175 SDL_UnlockMutex(mutex);
176
177 /* Wait for a signal */
178 if ( ms == SDL_MUTEX_MAXWAIT ) {
179 retval = SDL_SemWait(cond->wait_sem);
180 } else {
181 retval = SDL_SemWaitTimeout(cond->wait_sem, ms);
182 }
183
184 /* Let the signaler know we have completed the wait, otherwise
185 the signaler can race ahead and get the condition semaphore
186 if we are stopped between the mutex unlock and semaphore wait,
187 giving a deadlock. See the following URL for details:
188 http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html
189 */
190 SDL_LockMutex(cond->lock);
191 if ( cond->signals > 0 ) {
192 /* If we timed out, we need to eat a condition signal */
193 if ( retval > 0 ) {
194 SDL_SemWait(cond->wait_sem);
195 }
196 /* We always notify the signal thread that we are done */
197 SDL_SemPost(cond->wait_done);
198
199 /* Signal handshake complete */
200 --cond->signals;
201 }
202 --cond->waiting;
203 SDL_UnlockMutex(cond->lock);
204
205 /* Lock the mutex, as is required by condition variable semantics */
206 SDL_LockMutex(mutex);
207
208 return retval;
209}
210
211/* Wait on the condition variable forever */
212DECLSPEC int SDLCALL SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex)
213{
214 return SDL_CondWaitTimeout(cond, mutex, SDL_MUTEX_MAXWAIT);
215}
diff --git a/apps/plugins/sdl/src/thread/os2/SDL_syscond_c.h b/apps/plugins/sdl/src/thread/os2/SDL_syscond_c.h
deleted file mode 100644
index 1120b2d80d..0000000000
--- a/apps/plugins/sdl/src/thread/os2/SDL_syscond_c.h
+++ /dev/null
@@ -1,23 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
diff --git a/apps/plugins/sdl/src/thread/os2/SDL_sysmutex.c b/apps/plugins/sdl/src/thread/os2/SDL_sysmutex.c
deleted file mode 100644
index 1e21897656..0000000000
--- a/apps/plugins/sdl/src/thread/os2/SDL_sysmutex.c
+++ /dev/null
@@ -1,108 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Mutex functions using the OS/2 API */
25
26#define INCL_DOSERRORS
27#define INCL_DOSSEMAPHORES
28#include <os2.h>
29
30#include "SDL_mutex.h"
31
32
33struct SDL_mutex {
34 HMTX hmtxID;
35};
36
37/* Create a mutex */
38DECLSPEC SDL_mutex * SDLCALL SDL_CreateMutex(void)
39{
40 SDL_mutex *mutex;
41 APIRET ulrc;
42
43 /* Allocate mutex memory */
44 mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex));
45 if (mutex)
46 {
47 /* Create the mutex, with initial value signaled */
48 ulrc = DosCreateMutexSem(NULL, // Create unnamed semaphore
49 &(mutex->hmtxID), // Pointer to handle
50 0L, // Flags: create it private (not shared)
51 FALSE); // Initial value: unowned
52 if (ulrc!=NO_ERROR)
53 {
54 SDL_SetError("Couldn't create mutex");
55 SDL_free(mutex);
56 mutex = NULL;
57 }
58 } else {
59 SDL_OutOfMemory();
60 }
61 return(mutex);
62}
63
64/* Free the mutex */
65DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_mutex *mutex)
66{
67 if ( mutex )
68 {
69 if ( mutex->hmtxID )
70 {
71 DosCloseMutexSem(mutex->hmtxID);
72 mutex->hmtxID = 0;
73 }
74 SDL_free(mutex);
75 }
76}
77
78/* Lock the mutex */
79DECLSPEC int SDLCALL SDL_mutexP(SDL_mutex *mutex)
80{
81 if ( mutex == NULL )
82 {
83 SDL_SetError("Passed a NULL mutex");
84 return -1;
85 }
86 if ( DosRequestMutexSem(mutex->hmtxID, SEM_INDEFINITE_WAIT) != NO_ERROR )
87 {
88 SDL_SetError("Couldn't wait on mutex");
89 return -1;
90 }
91 return(0);
92}
93
94/* Unlock the mutex */
95DECLSPEC int SDLCALL SDL_mutexV(SDL_mutex *mutex)
96{
97 if ( mutex == NULL )
98 {
99 SDL_SetError("Passed a NULL mutex");
100 return -1;
101 }
102 if ( DosReleaseMutexSem(mutex->hmtxID) != NO_ERROR )
103 {
104 SDL_SetError("Couldn't release mutex");
105 return -1;
106 }
107 return(0);
108}
diff --git a/apps/plugins/sdl/src/thread/os2/SDL_syssem.c b/apps/plugins/sdl/src/thread/os2/SDL_syssem.c
deleted file mode 100644
index d6dfba67bb..0000000000
--- a/apps/plugins/sdl/src/thread/os2/SDL_syssem.c
+++ /dev/null
@@ -1,192 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Semaphore functions using the OS/2 API */
25
26#define INCL_DOS
27#define INCL_DOSERRORS
28#define INCL_DOSSEMAPHORES
29#include <os2.h>
30
31#include "SDL_thread.h"
32#include "SDL_timer.h"
33
34
35struct SDL_semaphore {
36 HMTX id;
37 HEV changed;
38 Uint32 value;
39};
40
41
42/* Create a semaphore */
43DECLSPEC SDL_sem * SDLCALL SDL_CreateSemaphore(Uint32 initial_value)
44{
45 SDL_sem *sem;
46 ULONG ulrc;
47
48 /* Allocate sem memory */
49 sem = (SDL_sem *)SDL_malloc(sizeof(*sem));
50 if ( sem ) {
51 /* Create the mutex semaphore */
52 ulrc = DosCreateMutexSem(NULL,&(sem->id),0,TRUE);
53 if ( ulrc ) {
54 SDL_SetError("Couldn't create semaphore");
55 SDL_free(sem);
56 sem = NULL;
57 } else
58 {
59 DosCreateEventSem(NULL, &(sem->changed), 0, FALSE);
60 sem->value = initial_value;
61 DosReleaseMutexSem(sem->id);
62 }
63 } else {
64 SDL_OutOfMemory();
65 }
66 return(sem);
67}
68
69/* Free the semaphore */
70DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_sem *sem)
71{
72 if ( sem ) {
73 if ( sem->id ) {
74 DosCloseEventSem(sem->changed);
75 DosCloseMutexSem(sem->id);
76 sem->id = 0;
77 }
78 SDL_free(sem);
79 }
80}
81
82DECLSPEC int SDLCALL SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
83{
84 ULONG ulrc;
85
86 if ( ! sem ) {
87 SDL_SetError("Passed a NULL sem");
88 return -1;
89 }
90
91 if ( timeout == SDL_MUTEX_MAXWAIT ) {
92 while (1) {
93 ulrc = DosRequestMutexSem(sem->id, SEM_INDEFINITE_WAIT);
94 if (ulrc) {
95 /* if error waiting mutex */
96 SDL_SetError("DosRequestMutexSem() failed");
97 return -1;
98 } else if (sem->value) {
99 sem->value--;
100 DosReleaseMutexSem(sem->id);
101 return 0;
102 } else {
103 ULONG ulPostCount;
104 DosResetEventSem(sem->changed, &ulPostCount);
105 DosReleaseMutexSem(sem->id);
106 /* continue waiting until somebody posts the semaphore */
107 DosWaitEventSem(sem->changed, SEM_INDEFINITE_WAIT);
108 }
109 }
110 } else
111 if ( timeout == 0 )
112 {
113 ulrc = DosRequestMutexSem(sem->id, SEM_INDEFINITE_WAIT);
114 if (ulrc==NO_ERROR)
115 {
116 if (sem->value)
117 {
118 sem->value--;
119 DosReleaseMutexSem(sem->id);
120 return 0;
121 } else
122 {
123 DosReleaseMutexSem(sem->id);
124 return SDL_MUTEX_TIMEDOUT;
125 }
126 } else
127 {
128 SDL_SetError("DosRequestMutexSem() failed");
129 return -1;
130 }
131 } else {
132 ulrc = DosRequestMutexSem(sem->id, SEM_INDEFINITE_WAIT);
133 if (ulrc) {
134 /* if error waiting mutex */
135 SDL_SetError("DosRequestMutexSem() failed");
136 return -1;
137 } else
138 if (sem->value) {
139 sem->value--;
140 DosReleaseMutexSem(sem->id);
141 return 0;
142 } else {
143 ULONG ulPostCount;
144 DosResetEventSem(sem->changed, &ulPostCount);
145 DosReleaseMutexSem(sem->id);
146 /* continue waiting until somebody posts the semaphore */
147 ulrc = DosWaitEventSem(sem->changed, timeout);
148 if (ulrc==NO_ERROR)
149 return 0;
150 else
151 return SDL_MUTEX_TIMEDOUT;
152 }
153 }
154 /* never reached */
155 return -1;
156}
157
158DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem *sem)
159{
160 return SDL_SemWaitTimeout(sem, 0);
161}
162
163DECLSPEC int SDLCALL SDL_SemWait(SDL_sem *sem)
164{
165 return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT);
166}
167
168/* Returns the current count of the semaphore */
169DECLSPEC Uint32 SDLCALL SDL_SemValue(SDL_sem *sem)
170{
171 if ( ! sem ) {
172 SDL_SetError("Passed a NULL sem");
173 return 0;
174 }
175 return sem->value;
176}
177
178DECLSPEC int SDLCALL SDL_SemPost(SDL_sem *sem)
179{
180 if ( ! sem ) {
181 SDL_SetError("Passed a NULL sem");
182 return -1;
183 }
184 if ( DosRequestMutexSem(sem->id,SEM_INDEFINITE_WAIT) ) {
185 SDL_SetError("DosRequestMutexSem() failed");
186 return -1;
187 }
188 sem->value++;
189 DosPostEventSem(sem->changed);
190 DosReleaseMutexSem(sem->id);
191 return 0;
192}
diff --git a/apps/plugins/sdl/src/thread/os2/SDL_systhread.c b/apps/plugins/sdl/src/thread/os2/SDL_systhread.c
deleted file mode 100644
index 33f815a5fb..0000000000
--- a/apps/plugins/sdl/src/thread/os2/SDL_systhread.c
+++ /dev/null
@@ -1,108 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* OS/2 thread management routines for SDL */
25
26#include <process.h>
27#define INCL_DOSERRORS
28#define INCL_DOSPROCESS
29#include <os2.h>
30
31#include "SDL_thread.h"
32#include "../SDL_systhread.h"
33#include "../SDL_thread_c.h"
34
35typedef struct ThreadStartParms
36{
37 void *args;
38 pfnSDL_CurrentEndThread pfnCurrentEndThread;
39} tThreadStartParms, *pThreadStartParms;
40
41static void threadfunc(void *pparm)
42{
43 pThreadStartParms pThreadParms = pparm;
44 pfnSDL_CurrentEndThread pfnCurrentEndThread = NULL;
45
46 // Call the thread function!
47 SDL_RunThread(pThreadParms->args);
48
49 // Get the current endthread we have to use!
50 if (pThreadParms)
51 {
52 pfnCurrentEndThread = pThreadParms->pfnCurrentEndThread;
53 SDL_free(pThreadParms);
54 }
55 // Call endthread!
56 if (pfnCurrentEndThread)
57 (*pfnCurrentEndThread)();
58}
59
60int SDL_SYS_CreateThread(SDL_Thread *thread, void *args, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread)
61{
62 pThreadStartParms pThreadParms = SDL_malloc(sizeof(tThreadStartParms));
63 if (!pThreadParms)
64 {
65 SDL_SetError("Not enough memory to create thread");
66 return(-1);
67 }
68
69 // Save the function which we will have to call to clear the RTL of calling app!
70 pThreadParms->pfnCurrentEndThread = pfnEndThread;
71 // Also save the real parameters we have to pass to thread function
72 pThreadParms->args = args;
73 // Start the thread using the runtime library of calling app!
74 thread->threadid = thread->handle = (*pfnBeginThread)(threadfunc, NULL, 512*1024, pThreadParms);
75 if ((int)thread->threadid <= 0)
76 {
77 SDL_SetError("Not enough resources to create thread");
78 return(-1);
79 }
80 return(0);
81}
82
83void SDL_SYS_SetupThread(void)
84{
85 return;
86}
87
88DECLSPEC Uint32 SDLCALL SDL_ThreadID(void)
89{
90 PTIB tib;
91 DosGetInfoBlocks(&tib, NULL);
92 return((Uint32) (tib->tib_ptib2->tib2_ultid));
93}
94
95void SDL_SYS_WaitThread(SDL_Thread *thread)
96{
97 TID tid = thread->handle;
98 DosWaitThread(&tid, DCWW_WAIT);
99}
100
101/* WARNING: This function is really a last resort.
102 * Threads should be signaled and then exit by themselves.
103 * TerminateThread() doesn't perform stack and DLL cleanup.
104 */
105void SDL_SYS_KillThread(SDL_Thread *thread)
106{
107 DosKillThread(thread->handle);
108}
diff --git a/apps/plugins/sdl/src/thread/os2/SDL_systhread_c.h b/apps/plugins/sdl/src/thread/os2/SDL_systhread_c.h
deleted file mode 100644
index 3b94dfed53..0000000000
--- a/apps/plugins/sdl/src/thread/os2/SDL_systhread_c.h
+++ /dev/null
@@ -1,28 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#define INCL_DOSPROCESS
25#include <os2.h>
26
27typedef TID SYS_ThreadHandle;
28
diff --git a/apps/plugins/sdl/src/thread/pth/SDL_syscond.c b/apps/plugins/sdl/src/thread/pth/SDL_syscond.c
deleted file mode 100644
index ede74aaeae..0000000000
--- a/apps/plugins/sdl/src/thread/pth/SDL_syscond.c
+++ /dev/null
@@ -1,164 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * GNU pth conditions variables
26 *
27 * Patrice Mandin
28 */
29
30#include <pth.h>
31
32#include "SDL_thread.h"
33#include "SDL_sysmutex_c.h"
34
35struct SDL_cond
36{
37 pth_cond_t condpth_p;
38};
39
40/* Create a condition variable */
41SDL_cond * SDL_CreateCond(void)
42{
43 SDL_cond *cond;
44
45 cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond));
46 if ( cond ) {
47 if ( pth_cond_init(&(cond->condpth_p)) < 0 ) {
48 SDL_SetError("pthread_cond_init() failed");
49 SDL_free(cond);
50 cond = NULL;
51 }
52 } else {
53 SDL_OutOfMemory();
54 }
55 return(cond);
56}
57
58/* Destroy a condition variable */
59void SDL_DestroyCond(SDL_cond *cond)
60{
61 if ( cond ) {
62 SDL_free(cond);
63 }
64}
65
66/* Restart one of the threads that are waiting on the condition variable */
67int SDL_CondSignal(SDL_cond *cond)
68{
69 int retval;
70
71 if ( ! cond ) {
72 SDL_SetError("Passed a NULL condition variable");
73 return -1;
74 }
75
76 retval = 0;
77 if ( pth_cond_notify(&(cond->condpth_p), FALSE) != 0 ) {
78 SDL_SetError("pth_cond_notify() failed");
79 retval = -1;
80 }
81 return retval;
82}
83
84/* Restart all threads that are waiting on the condition variable */
85int SDL_CondBroadcast(SDL_cond *cond)
86{
87 int retval;
88
89 if ( ! cond ) {
90 SDL_SetError("Passed a NULL condition variable");
91 return -1;
92 }
93
94 retval = 0;
95 if ( pth_cond_notify(&(cond->condpth_p), TRUE) != 0 ) {
96 SDL_SetError("pth_cond_notify() failed");
97 retval = -1;
98 }
99 return retval;
100}
101
102/* Wait on the condition variable for at most 'ms' milliseconds.
103 The mutex must be locked before entering this function!
104 The mutex is unlocked during the wait, and locked again after the wait.
105
106Typical use:
107
108Thread A:
109 SDL_LockMutex(lock);
110 while ( ! condition ) {
111 SDL_CondWait(cond);
112 }
113 SDL_UnlockMutex(lock);
114
115Thread B:
116 SDL_LockMutex(lock);
117 ...
118 condition = true;
119 ...
120 SDL_UnlockMutex(lock);
121 */
122int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms)
123{
124 int retval;
125 pth_event_t ev;
126 int sec;
127
128 if ( ! cond ) {
129 SDL_SetError("Passed a NULL condition variable");
130 return -1;
131 }
132
133 retval = 0;
134
135 sec = ms/1000;
136 ev = pth_event(PTH_EVENT_TIME, pth_timeout(sec,(ms-sec*1000)*1000));
137
138 if ( pth_cond_await(&(cond->condpth_p), &(mutex->mutexpth_p), ev) != 0 ) {
139 SDL_SetError("pth_cond_await() failed");
140 retval = -1;
141 }
142
143 pth_event_free(ev, PTH_FREE_ALL);
144
145 return retval;
146}
147
148/* Wait on the condition variable forever */
149int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex)
150{
151 int retval;
152
153 if ( ! cond ) {
154 SDL_SetError("Passed a NULL condition variable");
155 return -1;
156 }
157
158 retval = 0;
159 if ( pth_cond_await(&(cond->condpth_p), &(mutex->mutexpth_p), NULL) != 0 ) {
160 SDL_SetError("pth_cond_await() failed");
161 retval = -1;
162 }
163 return retval;
164}
diff --git a/apps/plugins/sdl/src/thread/pth/SDL_sysmutex.c b/apps/plugins/sdl/src/thread/pth/SDL_sysmutex.c
deleted file mode 100644
index ca83b92c24..0000000000
--- a/apps/plugins/sdl/src/thread/pth/SDL_sysmutex.c
+++ /dev/null
@@ -1,87 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * GNU pth mutexes
26 *
27 * Patrice Mandin
28 */
29
30#include <pth.h>
31
32#include "SDL_mutex.h"
33#include "SDL_sysmutex_c.h"
34
35/* Create a mutex */
36SDL_mutex *SDL_CreateMutex(void)
37{
38 SDL_mutex *mutex;
39
40 /* Allocate mutex memory */
41 mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex));
42 if ( mutex ) {
43 /* Create the mutex, with initial value signaled */
44 if (!pth_mutex_init(&(mutex->mutexpth_p))) {
45 SDL_SetError("Couldn't create mutex");
46 SDL_free(mutex);
47 mutex = NULL;
48 }
49 } else {
50 SDL_OutOfMemory();
51 }
52 return(mutex);
53}
54
55/* Free the mutex */
56void SDL_DestroyMutex(SDL_mutex *mutex)
57{
58 if ( mutex ) {
59 SDL_free(mutex);
60 }
61}
62
63/* Lock the mutex */
64int SDL_mutexP(SDL_mutex *mutex)
65{
66 if ( mutex == NULL ) {
67 SDL_SetError("Passed a NULL mutex");
68 return -1;
69 }
70
71 pth_mutex_acquire(&(mutex->mutexpth_p), FALSE, NULL);
72
73 return(0);
74}
75
76/* Unlock the mutex */
77int SDL_mutexV(SDL_mutex *mutex)
78{
79 if ( mutex == NULL ) {
80 SDL_SetError("Passed a NULL mutex");
81 return -1;
82 }
83
84 pth_mutex_release(&(mutex->mutexpth_p));
85
86 return(0);
87}
diff --git a/apps/plugins/sdl/src/thread/pth/SDL_sysmutex_c.h b/apps/plugins/sdl/src/thread/pth/SDL_sysmutex_c.h
deleted file mode 100644
index d29060e9ff..0000000000
--- a/apps/plugins/sdl/src/thread/pth/SDL_sysmutex_c.h
+++ /dev/null
@@ -1,31 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_SYSMUTEX_C_H_
25#define _SDL_SYSMUTEX_C_H_
26
27struct SDL_mutex {
28 pth_mutex_t mutexpth_p;
29};
30
31#endif /* _SDL_SYSMUTEX_C_H_ */
diff --git a/apps/plugins/sdl/src/thread/pth/SDL_systhread.c b/apps/plugins/sdl/src/thread/pth/SDL_systhread.c
deleted file mode 100644
index bfccaf340f..0000000000
--- a/apps/plugins/sdl/src/thread/pth/SDL_systhread.c
+++ /dev/null
@@ -1,103 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * GNU pth threads
26 *
27 * Patrice Mandin
28 */
29
30#include <pth.h>
31#include <signal.h>
32
33#include "SDL_thread.h"
34#include "../SDL_thread_c.h"
35#include "../SDL_systhread.h"
36
37/* List of signals to mask in the subthreads */
38static int sig_list[] = {
39 SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH,
40 SIGVTALRM, SIGPROF, 0
41};
42
43static void *RunThread(void *data)
44{
45 SDL_RunThread(data);
46 pth_exit((void*)0);
47 return((void *)0); /* Prevent compiler warning */
48}
49
50int SDL_SYS_CreateThread(SDL_Thread *thread, void *args)
51{
52 pth_attr_t type;
53
54 /* Create a new attribute */
55 type = pth_attr_new();
56 if ( type == NULL ) {
57 SDL_SetError("Couldn't initialize pth attributes");
58 return(-1);
59 }
60 pth_attr_set(type, PTH_ATTR_JOINABLE, TRUE);
61
62 /* Create the thread and go! */
63 thread->handle = pth_spawn(type, RunThread, args);
64 if ( thread->handle == NULL ) {
65 SDL_SetError("Not enough resources to create thread");
66 return(-1);
67 }
68 return(0);
69}
70
71void SDL_SYS_SetupThread(void)
72{
73 int i;
74 sigset_t mask;
75 int oldstate;
76
77 /* Mask asynchronous signals for this thread */
78 sigemptyset(&mask);
79 for ( i=0; sig_list[i]; ++i ) {
80 sigaddset(&mask, sig_list[i]);
81 }
82 pth_sigmask(SIG_BLOCK, &mask, 0);
83
84 /* Allow ourselves to be asynchronously cancelled */
85 pth_cancel_state(PTH_CANCEL_ASYNCHRONOUS, &oldstate);
86}
87
88/* WARNING: This may not work for systems with 64-bit pid_t */
89Uint32 SDL_ThreadID(void)
90{
91 return((Uint32)pth_self());
92}
93
94void SDL_SYS_WaitThread(SDL_Thread *thread)
95{
96 pth_join(thread->handle, NULL);
97}
98
99void SDL_SYS_KillThread(SDL_Thread *thread)
100{
101 pth_cancel(thread->handle);
102 pth_join(thread->handle, NULL);
103}
diff --git a/apps/plugins/sdl/src/thread/pth/SDL_systhread_c.h b/apps/plugins/sdl/src/thread/pth/SDL_systhread_c.h
deleted file mode 100644
index 50bb26df54..0000000000
--- a/apps/plugins/sdl/src/thread/pth/SDL_systhread_c.h
+++ /dev/null
@@ -1,31 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_SYSTHREAD_C_H_
25#define _SDL_SYSTHREAD_C_H_
26
27#include <pth.h>
28
29typedef pth_t SYS_ThreadHandle;
30
31#endif /* _SDL_SYSTHREAD_C_H_ */
diff --git a/apps/plugins/sdl/src/thread/pthread/SDL_syscond.c b/apps/plugins/sdl/src/thread/pthread/SDL_syscond.c
deleted file mode 100644
index 15bce96614..0000000000
--- a/apps/plugins/sdl/src/thread/pthread/SDL_syscond.c
+++ /dev/null
@@ -1,155 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <sys/time.h>
25#include <unistd.h>
26#include <errno.h>
27#include <pthread.h>
28
29#include "SDL_thread.h"
30#include "SDL_sysmutex_c.h"
31
32struct SDL_cond
33{
34 pthread_cond_t cond;
35};
36
37/* Create a condition variable */
38SDL_cond * SDL_CreateCond(void)
39{
40 SDL_cond *cond;
41
42 cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond));
43 if ( cond ) {
44 if ( pthread_cond_init(&cond->cond, NULL) < 0 ) {
45 SDL_SetError("pthread_cond_init() failed");
46 SDL_free(cond);
47 cond = NULL;
48 }
49 }
50 return(cond);
51}
52
53/* Destroy a condition variable */
54void SDL_DestroyCond(SDL_cond *cond)
55{
56 if ( cond ) {
57 pthread_cond_destroy(&cond->cond);
58 SDL_free(cond);
59 }
60}
61
62/* Restart one of the threads that are waiting on the condition variable */
63int SDL_CondSignal(SDL_cond *cond)
64{
65 int retval;
66
67 if ( ! cond ) {
68 SDL_SetError("Passed a NULL condition variable");
69 return -1;
70 }
71
72 retval = 0;
73 if ( pthread_cond_signal(&cond->cond) != 0 ) {
74 SDL_SetError("pthread_cond_signal() failed");
75 retval = -1;
76 }
77 return retval;
78}
79
80/* Restart all threads that are waiting on the condition variable */
81int SDL_CondBroadcast(SDL_cond *cond)
82{
83 int retval;
84
85 if ( ! cond ) {
86 SDL_SetError("Passed a NULL condition variable");
87 return -1;
88 }
89
90 retval = 0;
91 if ( pthread_cond_broadcast(&cond->cond) != 0 ) {
92 SDL_SetError("pthread_cond_broadcast() failed");
93 retval = -1;
94 }
95 return retval;
96}
97
98int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms)
99{
100 int retval;
101 struct timeval delta;
102 struct timespec abstime;
103
104 if ( ! cond ) {
105 SDL_SetError("Passed a NULL condition variable");
106 return -1;
107 }
108
109 gettimeofday(&delta, NULL);
110
111 abstime.tv_sec = delta.tv_sec + (ms/1000);
112 abstime.tv_nsec = (delta.tv_usec + (ms%1000) * 1000) * 1000;
113 if ( abstime.tv_nsec > 1000000000 ) {
114 abstime.tv_sec += 1;
115 abstime.tv_nsec -= 1000000000;
116 }
117
118 tryagain:
119 retval = pthread_cond_timedwait(&cond->cond, &mutex->id, &abstime);
120 switch (retval) {
121 case EINTR:
122 goto tryagain;
123 break;
124 case ETIMEDOUT:
125 retval = SDL_MUTEX_TIMEDOUT;
126 break;
127 case 0:
128 break;
129 default:
130 SDL_SetError("pthread_cond_timedwait() failed");
131 retval = -1;
132 break;
133 }
134 return retval;
135}
136
137/* Wait on the condition variable, unlocking the provided mutex.
138 The mutex must be locked before entering this function!
139 */
140int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex)
141{
142 int retval;
143
144 if ( ! cond ) {
145 SDL_SetError("Passed a NULL condition variable");
146 return -1;
147 }
148
149 retval = 0;
150 if ( pthread_cond_wait(&cond->cond, &mutex->id) != 0 ) {
151 SDL_SetError("pthread_cond_wait() failed");
152 retval = -1;
153 }
154 return retval;
155}
diff --git a/apps/plugins/sdl/src/thread/pthread/SDL_sysmutex.c b/apps/plugins/sdl/src/thread/pthread/SDL_sysmutex.c
deleted file mode 100644
index c3b8ce2c37..0000000000
--- a/apps/plugins/sdl/src/thread/pthread/SDL_sysmutex.c
+++ /dev/null
@@ -1,153 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <pthread.h>
25
26#include "SDL_thread.h"
27
28#if !SDL_THREAD_PTHREAD_RECURSIVE_MUTEX && \
29 !SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP
30#define FAKE_RECURSIVE_MUTEX
31#endif
32
33struct SDL_mutex {
34 pthread_mutex_t id;
35#if FAKE_RECURSIVE_MUTEX
36 int recursive;
37 pthread_t owner;
38#endif
39};
40
41SDL_mutex *SDL_CreateMutex (void)
42{
43 SDL_mutex *mutex;
44 pthread_mutexattr_t attr;
45
46 /* Allocate the structure */
47 mutex = (SDL_mutex *)SDL_calloc(1, sizeof(*mutex));
48 if ( mutex ) {
49 pthread_mutexattr_init(&attr);
50#if SDL_THREAD_PTHREAD_RECURSIVE_MUTEX
51 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
52#elif SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP
53 pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
54#else
55 /* No extra attributes necessary */
56#endif
57 if ( pthread_mutex_init(&mutex->id, &attr) != 0 ) {
58 SDL_SetError("pthread_mutex_init() failed");
59 SDL_free(mutex);
60 mutex = NULL;
61 }
62 } else {
63 SDL_OutOfMemory();
64 }
65 return(mutex);
66}
67
68void SDL_DestroyMutex(SDL_mutex *mutex)
69{
70 if ( mutex ) {
71 pthread_mutex_destroy(&mutex->id);
72 SDL_free(mutex);
73 }
74}
75
76/* Lock the mutex */
77int SDL_mutexP(SDL_mutex *mutex)
78{
79 int retval;
80#if FAKE_RECURSIVE_MUTEX
81 pthread_t this_thread;
82#endif
83
84 if ( mutex == NULL ) {
85 SDL_SetError("Passed a NULL mutex");
86 return -1;
87 }
88
89 retval = 0;
90#if FAKE_RECURSIVE_MUTEX
91 this_thread = pthread_self();
92 if ( mutex->owner == this_thread ) {
93 ++mutex->recursive;
94 } else {
95 /* The order of operations is important.
96 We set the locking thread id after we obtain the lock
97 so unlocks from other threads will fail.
98 */
99 if ( pthread_mutex_lock(&mutex->id) == 0 ) {
100 mutex->owner = this_thread;
101 mutex->recursive = 0;
102 } else {
103 SDL_SetError("pthread_mutex_lock() failed");
104 retval = -1;
105 }
106 }
107#else
108 if ( pthread_mutex_lock(&mutex->id) < 0 ) {
109 SDL_SetError("pthread_mutex_lock() failed");
110 retval = -1;
111 }
112#endif
113 return retval;
114}
115
116int SDL_mutexV(SDL_mutex *mutex)
117{
118 int retval;
119
120 if ( mutex == NULL ) {
121 SDL_SetError("Passed a NULL mutex");
122 return -1;
123 }
124
125 retval = 0;
126#if FAKE_RECURSIVE_MUTEX
127 /* We can only unlock the mutex if we own it */
128 if ( pthread_self() == mutex->owner ) {
129 if ( mutex->recursive ) {
130 --mutex->recursive;
131 } else {
132 /* The order of operations is important.
133 First reset the owner so another thread doesn't lock
134 the mutex and set the ownership before we reset it,
135 then release the lock semaphore.
136 */
137 mutex->owner = 0;
138 pthread_mutex_unlock(&mutex->id);
139 }
140 } else {
141 SDL_SetError("mutex not owned by this thread");
142 retval = -1;
143 }
144
145#else
146 if ( pthread_mutex_unlock(&mutex->id) < 0 ) {
147 SDL_SetError("pthread_mutex_unlock() failed");
148 retval = -1;
149 }
150#endif /* FAKE_RECURSIVE_MUTEX */
151
152 return retval;
153}
diff --git a/apps/plugins/sdl/src/thread/pthread/SDL_sysmutex_c.h b/apps/plugins/sdl/src/thread/pthread/SDL_sysmutex_c.h
deleted file mode 100644
index 5258890156..0000000000
--- a/apps/plugins/sdl/src/thread/pthread/SDL_sysmutex_c.h
+++ /dev/null
@@ -1,31 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_mutex_c_h
25#define _SDL_mutex_c_h
26
27struct SDL_mutex {
28 pthread_mutex_t id;
29};
30
31#endif /* _SDL_mutex_c_h */
diff --git a/apps/plugins/sdl/src/thread/pthread/SDL_syssem.c b/apps/plugins/sdl/src/thread/pthread/SDL_syssem.c
deleted file mode 100644
index a03870fa35..0000000000
--- a/apps/plugins/sdl/src/thread/pthread/SDL_syssem.c
+++ /dev/null
@@ -1,190 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <pthread.h>
25#include <semaphore.h>
26#include <errno.h>
27#include <sys/time.h>
28
29#include "SDL_thread.h"
30#include "SDL_timer.h"
31
32/* Wrapper around POSIX 1003.1b semaphores */
33
34#ifdef __MACOSX__
35/* Mac OS X doesn't support sem_getvalue() as of version 10.4 */
36#include "../generic/SDL_syssem.c"
37#else
38
39struct SDL_semaphore {
40 sem_t sem;
41};
42
43/* Create a semaphore, initialized with value */
44SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
45{
46 SDL_sem *sem = (SDL_sem *) SDL_malloc(sizeof(SDL_sem));
47 if ( sem ) {
48 if ( sem_init(&sem->sem, 0, initial_value) < 0 ) {
49 SDL_SetError("sem_init() failed");
50 SDL_free(sem);
51 sem = NULL;
52 }
53 } else {
54 SDL_OutOfMemory();
55 }
56 return sem;
57}
58
59void SDL_DestroySemaphore(SDL_sem *sem)
60{
61 if ( sem ) {
62 sem_destroy(&sem->sem);
63 SDL_free(sem);
64 }
65}
66
67int SDL_SemTryWait(SDL_sem *sem)
68{
69 int retval;
70
71 if ( ! sem ) {
72 SDL_SetError("Passed a NULL semaphore");
73 return -1;
74 }
75 retval = SDL_MUTEX_TIMEDOUT;
76 if ( sem_trywait(&sem->sem) == 0 ) {
77 retval = 0;
78 }
79 return retval;
80}
81
82int SDL_SemWait(SDL_sem *sem)
83{
84 int retval;
85
86 if ( ! sem ) {
87 SDL_SetError("Passed a NULL semaphore");
88 return -1;
89 }
90
91 while ( ((retval = sem_wait(&sem->sem)) == -1) && (errno == EINTR) ) {}
92 if ( retval < 0 ) {
93 SDL_SetError("sem_wait() failed");
94 }
95 return retval;
96}
97
98int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
99{
100 int retval;
101#ifdef HAVE_SEM_TIMEDWAIT
102 struct timeval now;
103 struct timespec ts_timeout;
104#else
105 Uint32 end;
106#endif
107
108 if ( ! sem ) {
109 SDL_SetError("Passed a NULL semaphore");
110 return -1;
111 }
112
113 /* Try the easy cases first */
114 if ( timeout == 0 ) {
115 return SDL_SemTryWait(sem);
116 }
117 if ( timeout == SDL_MUTEX_MAXWAIT ) {
118 return SDL_SemWait(sem);
119 }
120
121#ifdef HAVE_SEM_TIMEDWAIT
122 /* Setup the timeout. sem_timedwait doesn't wait for
123 * a lapse of time, but until we reach a certain time.
124 * This time is now plus the timeout.
125 */
126 gettimeofday(&now, NULL);
127
128 /* Add our timeout to current time */
129 now.tv_usec += (timeout % 1000) * 1000;
130 now.tv_sec += timeout / 1000;
131
132 /* Wrap the second if needed */
133 if ( now.tv_usec >= 1000000 ) {
134 now.tv_usec -= 1000000;
135 now.tv_sec ++;
136 }
137
138 /* Convert to timespec */
139 ts_timeout.tv_sec = now.tv_sec;
140 ts_timeout.tv_nsec = now.tv_usec * 1000;
141
142 /* Wait. */
143 do
144 retval = sem_timedwait(&sem->sem, &ts_timeout);
145 while (retval == -1 && errno == EINTR);
146
147 if (retval == -1)
148 SDL_SetError(strerror(errno));
149#else
150 end = SDL_GetTicks() + timeout;
151 while ((retval = SDL_SemTryWait(sem)) == SDL_MUTEX_TIMEDOUT) {
152 if ((SDL_GetTicks() - end) >= 0) {
153 break;
154 }
155 SDL_Delay(0);
156 }
157#endif /* HAVE_SEM_TIMEDWAIT */
158
159 return retval;
160}
161
162Uint32 SDL_SemValue(SDL_sem *sem)
163{
164 int ret = 0;
165 if ( sem ) {
166 sem_getvalue(&sem->sem, &ret);
167 if ( ret < 0 ) {
168 ret = 0;
169 }
170 }
171 return (Uint32)ret;
172}
173
174int SDL_SemPost(SDL_sem *sem)
175{
176 int retval;
177
178 if ( ! sem ) {
179 SDL_SetError("Passed a NULL semaphore");
180 return -1;
181 }
182
183 retval = sem_post(&sem->sem);
184 if ( retval < 0 ) {
185 SDL_SetError("sem_post() failed");
186 }
187 return retval;
188}
189
190#endif /* __MACOSX__ */
diff --git a/apps/plugins/sdl/src/thread/pthread/SDL_systhread.c b/apps/plugins/sdl/src/thread/pthread/SDL_systhread.c
deleted file mode 100644
index 40cc3b717d..0000000000
--- a/apps/plugins/sdl/src/thread/pthread/SDL_systhread.c
+++ /dev/null
@@ -1,120 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <pthread.h>
25#include <signal.h>
26
27#include "SDL_thread.h"
28#include "../SDL_thread_c.h"
29#include "../SDL_systhread.h"
30
31/* List of signals to mask in the subthreads */
32static int sig_list[] = {
33 SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH,
34 SIGVTALRM, SIGPROF, 0
35};
36
37#ifdef __RISCOS__
38/* RISC OS needs to know the main thread for
39 * it's timer and event processing. */
40int riscos_using_threads = 0;
41Uint32 riscos_main_thread = 0; /* Thread running events */
42#endif
43
44
45static void *RunThread(void *data)
46{
47 SDL_RunThread(data);
48 pthread_exit((void*)0);
49 return((void *)0); /* Prevent compiler warning */
50}
51
52int SDL_SYS_CreateThread(SDL_Thread *thread, void *args)
53{
54 pthread_attr_t type;
55
56 /* Set the thread attributes */
57 if ( pthread_attr_init(&type) != 0 ) {
58 SDL_SetError("Couldn't initialize pthread attributes");
59 return(-1);
60 }
61 pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);
62
63 /* Create the thread and go! */
64 if ( pthread_create(&thread->handle, &type, RunThread, args) != 0 ) {
65 SDL_SetError("Not enough resources to create thread");
66 return(-1);
67 }
68
69#ifdef __RISCOS__
70 if (riscos_using_threads == 0) {
71 riscos_using_threads = 1;
72 riscos_main_thread = SDL_ThreadID();
73 }
74#endif
75
76 return(0);
77}
78
79void SDL_SYS_SetupThread(void)
80{
81 int i;
82 sigset_t mask;
83
84 /* Mask asynchronous signals for this thread */
85 sigemptyset(&mask);
86 for ( i=0; sig_list[i]; ++i ) {
87 sigaddset(&mask, sig_list[i]);
88 }
89 pthread_sigmask(SIG_BLOCK, &mask, 0);
90
91#ifdef PTHREAD_CANCEL_ASYNCHRONOUS
92 /* Allow ourselves to be asynchronously cancelled */
93 { int oldstate;
94 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate);
95 }
96#endif
97}
98
99/* WARNING: This may not work for systems with 64-bit pid_t */
100Uint32 SDL_ThreadID(void)
101{
102 return((Uint32)((size_t)pthread_self()));
103}
104
105void SDL_SYS_WaitThread(SDL_Thread *thread)
106{
107 pthread_join(thread->handle, 0);
108}
109
110void SDL_SYS_KillThread(SDL_Thread *thread)
111{
112#ifdef PTHREAD_CANCEL_ASYNCHRONOUS
113 pthread_cancel(thread->handle);
114#else
115#ifdef __FREEBSD__
116#warning For some reason, this doesnt actually kill a thread - FreeBSD 3.2
117#endif
118 pthread_kill(thread->handle, SIGKILL);
119#endif
120}
diff --git a/apps/plugins/sdl/src/thread/pthread/SDL_systhread_c.h b/apps/plugins/sdl/src/thread/pthread/SDL_systhread_c.h
deleted file mode 100644
index 33ed750ff2..0000000000
--- a/apps/plugins/sdl/src/thread/pthread/SDL_systhread_c.h
+++ /dev/null
@@ -1,26 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <pthread.h>
25
26typedef pthread_t SYS_ThreadHandle;
diff --git a/apps/plugins/sdl/src/thread/riscos/SDL_syscond.c b/apps/plugins/sdl/src/thread/riscos/SDL_syscond.c
deleted file mode 100644
index ee5566647f..0000000000
--- a/apps/plugins/sdl/src/thread/riscos/SDL_syscond.c
+++ /dev/null
@@ -1,160 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* RISC OS implementations uses pthreads based on linux code */
25
26#if SDL_THREADS_DISABLED
27#include "../generic/SDL_syscond.c"
28#else
29#include <sys/time.h>
30#include <unistd.h>
31#include <pthread.h>
32
33#include "SDL_thread.h"
34#include "SDL_sysmutex_c.h"
35
36struct SDL_cond
37{
38 pthread_cond_t cond;
39};
40
41/* Create a condition variable */
42SDL_cond * SDL_CreateCond(void)
43{
44 SDL_cond *cond;
45
46 cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond));
47 if ( cond ) {
48 if ( pthread_cond_init(&cond->cond, NULL) < 0 ) {
49 SDL_SetError("pthread_cond_init() failed");
50 SDL_free(cond);
51 cond = NULL;
52 }
53 }
54 return(cond);
55}
56
57/* Destroy a condition variable */
58void SDL_DestroyCond(SDL_cond *cond)
59{
60 if ( cond ) {
61 pthread_cond_destroy(&cond->cond);
62 SDL_free(cond);
63 }
64}
65
66/* Restart one of the threads that are waiting on the condition variable */
67int SDL_CondSignal(SDL_cond *cond)
68{
69 int retval;
70
71 if ( ! cond ) {
72 SDL_SetError("Passed a NULL condition variable");
73 return -1;
74 }
75
76 retval = 0;
77 if ( pthread_cond_signal(&cond->cond) != 0 ) {
78 SDL_SetError("pthread_cond_signal() failed");
79 retval = -1;
80 }
81 return retval;
82}
83
84/* Restart all threads that are waiting on the condition variable */
85int SDL_CondBroadcast(SDL_cond *cond)
86{
87 int retval;
88
89 if ( ! cond ) {
90 SDL_SetError("Passed a NULL condition variable");
91 return -1;
92 }
93
94 retval = 0;
95 if ( pthread_cond_broadcast(&cond->cond) != 0 ) {
96 SDL_SetError("pthread_cond_broadcast() failed");
97 retval = -1;
98 }
99 return retval;
100}
101
102int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms)
103{
104 int retval;
105 struct timeval delta;
106 struct timespec abstime;
107
108 if ( ! cond ) {
109 SDL_SetError("Passed a NULL condition variable");
110 return -1;
111 }
112
113 gettimeofday(&delta, NULL);
114
115 abstime.tv_sec = delta.tv_sec + (ms/1000);
116 abstime.tv_nsec = (delta.tv_usec + (ms%1000) * 1000) * 1000;
117 if ( abstime.tv_nsec > 1000000000 ) {
118 abstime.tv_sec += 1;
119 abstime.tv_nsec -= 1000000000;
120 }
121
122 tryagain:
123 retval = pthread_cond_timedwait(&cond->cond, &mutex->id, &abstime);
124 switch (retval) {
125 case EINTR:
126 goto tryagain;
127 break;
128 case ETIMEDOUT:
129 retval = SDL_MUTEX_TIMEDOUT;
130 break;
131 case 0:
132 break;
133 default:
134 SDL_SetError("pthread_cond_timedwait() failed");
135 retval = -1;
136 break;
137 }
138 return retval;
139}
140
141/* Wait on the condition variable, unlocking the provided mutex.
142 The mutex must be locked before entering this function!
143 */
144int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex)
145{
146 int retval;
147
148 if ( ! cond ) {
149 SDL_SetError("Passed a NULL condition variable");
150 return -1;
151 }
152
153 retval = 0;
154 if ( pthread_cond_wait(&cond->cond, &mutex->id) != 0 ) {
155 SDL_SetError("pthread_cond_wait() failed");
156 retval = -1;
157 }
158 return retval;
159}
160#endif
diff --git a/apps/plugins/sdl/src/thread/riscos/SDL_sysmutex.c b/apps/plugins/sdl/src/thread/riscos/SDL_sysmutex.c
deleted file mode 100644
index e9ac139b36..0000000000
--- a/apps/plugins/sdl/src/thread/riscos/SDL_sysmutex.c
+++ /dev/null
@@ -1,153 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* RISC OS implementations uses pthreads based on linux code */
25
26#include "SDL_thread.h"
27
28#if SDL_THREADS_DISABLED
29#include "../generic/SDL_sysmutex.c"
30#else
31
32#include <pthread.h>
33
34struct SDL_mutex {
35 pthread_mutex_t id;
36#if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX
37 int recursive;
38 pthread_t owner;
39#endif
40};
41
42SDL_mutex *SDL_CreateMutex (void)
43{
44 SDL_mutex *mutex;
45 pthread_mutexattr_t attr;
46
47 /* Allocate the structure */
48 mutex = (SDL_mutex *)SDL_calloc(1, sizeof(*mutex));
49 if ( mutex ) {
50 pthread_mutexattr_init(&attr);
51#if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX
52 /* No extra attributes necessary */
53#else
54 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
55#endif /* SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX */
56 if ( pthread_mutex_init(&mutex->id, &attr) != 0 ) {
57 SDL_SetError("pthread_mutex_init() failed");
58 SDL_free(mutex);
59 mutex = NULL;
60 }
61 } else {
62 SDL_OutOfMemory();
63 }
64 return(mutex);
65}
66
67void SDL_DestroyMutex(SDL_mutex *mutex)
68{
69 if ( mutex ) {
70 pthread_mutex_destroy(&mutex->id);
71 SDL_free(mutex);
72 }
73}
74
75/* Lock the mutex */
76int SDL_mutexP(SDL_mutex *mutex)
77{
78 int retval;
79#if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX
80 pthread_t this_thread;
81#endif
82
83 if ( mutex == NULL ) {
84 SDL_SetError("Passed a NULL mutex");
85 return -1;
86 }
87
88 retval = 0;
89#if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX
90 this_thread = pthread_self();
91 if ( mutex->owner == this_thread ) {
92 ++mutex->recursive;
93 } else {
94 /* The order of operations is important.
95 We set the locking thread id after we obtain the lock
96 so unlocks from other threads will fail.
97 */
98 if ( pthread_mutex_lock(&mutex->id) == 0 ) {
99 mutex->owner = this_thread;
100 mutex->recursive = 0;
101 } else {
102 SDL_SetError("pthread_mutex_lock() failed");
103 retval = -1;
104 }
105 }
106#else
107 if ( pthread_mutex_lock(&mutex->id) < 0 ) {
108 SDL_SetError("pthread_mutex_lock() failed");
109 retval = -1;
110 }
111#endif
112 return retval;
113}
114
115int SDL_mutexV(SDL_mutex *mutex)
116{
117 int retval;
118
119 if ( mutex == NULL ) {
120 SDL_SetError("Passed a NULL mutex");
121 return -1;
122 }
123
124 retval = 0;
125#if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX
126 /* We can only unlock the mutex if we own it */
127 if ( pthread_self() == mutex->owner ) {
128 if ( mutex->recursive ) {
129 --mutex->recursive;
130 } else {
131 /* The order of operations is important.
132 First reset the owner so another thread doesn't lock
133 the mutex and set the ownership before we reset it,
134 then release the lock semaphore.
135 */
136 mutex->owner = 0;
137 pthread_mutex_unlock(&mutex->id);
138 }
139 } else {
140 SDL_SetError("mutex not owned by this thread");
141 retval = -1;
142 }
143
144#else
145 if ( pthread_mutex_unlock(&mutex->id) < 0 ) {
146 SDL_SetError("pthread_mutex_unlock() failed");
147 retval = -1;
148 }
149#endif /* SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX */
150
151 return retval;
152}
153#endif
diff --git a/apps/plugins/sdl/src/thread/riscos/SDL_sysmutex_c.h b/apps/plugins/sdl/src/thread/riscos/SDL_sysmutex_c.h
deleted file mode 100644
index 2391c3c108..0000000000
--- a/apps/plugins/sdl/src/thread/riscos/SDL_sysmutex_c.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_mutex_c_h
25#define _SDL_mutex_c_h
26
27#if !SDL_THREADS_DISABLED
28struct SDL_mutex {
29 pthread_mutex_t id;
30};
31#endif
32
33
34#endif /* _SDL_mutex_c_h */
diff --git a/apps/plugins/sdl/src/thread/riscos/SDL_syssem.c b/apps/plugins/sdl/src/thread/riscos/SDL_syssem.c
deleted file mode 100644
index 127211bf76..0000000000
--- a/apps/plugins/sdl/src/thread/riscos/SDL_syssem.c
+++ /dev/null
@@ -1,203 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23#include <errno.h>
24
25#include "SDL_config.h"
26
27/* RISC OS semiphores based on linux code */
28
29
30#include "SDL_timer.h"
31#include "SDL_thread.h"
32#include "SDL_systhread_c.h"
33
34#if !SDL_THREADS_DISABLED
35
36SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
37{
38 SDL_SetError("SDL not configured with thread support");
39 return (SDL_sem *)0;
40}
41
42void SDL_DestroySemaphore(SDL_sem *sem)
43{
44 return;
45}
46
47int SDL_SemTryWait(SDL_sem *sem)
48{
49 SDL_SetError("SDL not configured with thread support");
50 return -1;
51}
52
53int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
54{
55 SDL_SetError("SDL not configured with thread support");
56 return -1;
57}
58
59int SDL_SemWait(SDL_sem *sem)
60{
61 SDL_SetError("SDL not configured with thread support");
62 return -1;
63}
64
65Uint32 SDL_SemValue(SDL_sem *sem)
66{
67 return 0;
68}
69
70int SDL_SemPost(SDL_sem *sem)
71{
72 SDL_SetError("SDL not configured with thread support");
73 return -1;
74}
75
76#else
77
78
79#include <unistd.h> /* For getpid() */
80#include <pthread.h>
81#include <semaphore.h>
82
83struct SDL_semaphore {
84 sem_t *sem;
85 sem_t sem_data;
86};
87
88/* Create a semaphore, initialized with value */
89SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
90{
91 SDL_sem *sem = (SDL_sem *) SDL_malloc(sizeof(SDL_sem));
92 if ( sem ) {
93 if ( sem_init(&sem->sem_data, 0, initial_value) < 0 ) {
94 SDL_SetError("sem_init() failed");
95 SDL_free(sem);
96 sem = NULL;
97 } else {
98 sem->sem = &sem->sem_data;
99 }
100 } else {
101 SDL_OutOfMemory();
102 }
103 return sem;
104}
105
106void SDL_DestroySemaphore(SDL_sem *sem)
107{
108 if ( sem ) {
109 sem_destroy(sem->sem);
110 SDL_free(sem);
111 }
112}
113
114int SDL_SemTryWait(SDL_sem *sem)
115{
116 int retval;
117
118 if ( ! sem ) {
119 SDL_SetError("Passed a NULL semaphore");
120 return -1;
121 }
122 retval = SDL_MUTEX_TIMEDOUT;
123 if ( sem_trywait(sem->sem) == 0 ) {
124 retval = 0;
125 }
126 return retval;
127}
128
129int SDL_SemWait(SDL_sem *sem)
130{
131 int retval;
132
133 if ( ! sem ) {
134 SDL_SetError("Passed a NULL semaphore");
135 return -1;
136 }
137
138 while ( ((retval = sem_wait(sem->sem)) == -1) && (errno == EINTR) ) {}
139 if ( retval < 0 ) {
140 SDL_SetError("sem_wait() failed");
141 }
142 return retval;
143}
144
145int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
146{
147 int retval;
148
149 if ( ! sem ) {
150 SDL_SetError("Passed a NULL semaphore");
151 return -1;
152 }
153
154 /* Try the easy cases first */
155 if ( timeout == 0 ) {
156 return SDL_SemTryWait(sem);
157 }
158 if ( timeout == SDL_MUTEX_MAXWAIT ) {
159 return SDL_SemWait(sem);
160 }
161
162 /* Ack! We have to busy wait... */
163 timeout += SDL_GetTicks();
164 do {
165 retval = SDL_SemTryWait(sem);
166 if ( retval == 0 ) {
167 break;
168 }
169 SDL_Delay(1);
170 } while ( SDL_GetTicks() < timeout );
171
172 return retval;
173}
174
175Uint32 SDL_SemValue(SDL_sem *sem)
176{
177 int ret = 0;
178 if ( sem ) {
179 sem_getvalue(sem->sem, &ret);
180 if ( ret < 0 ) {
181 ret = 0;
182 }
183 }
184 return (Uint32)ret;
185}
186
187int SDL_SemPost(SDL_sem *sem)
188{
189 int retval;
190
191 if ( ! sem ) {
192 SDL_SetError("Passed a NULL semaphore");
193 return -1;
194 }
195
196 retval = sem_post(sem->sem);
197 if ( retval < 0 ) {
198 SDL_SetError("sem_post() failed");
199 }
200 return retval;
201}
202
203#endif /* !SDL_THREADS_DISABLED */
diff --git a/apps/plugins/sdl/src/thread/riscos/SDL_systhread.c b/apps/plugins/sdl/src/thread/riscos/SDL_systhread.c
deleted file mode 100644
index 38fc333ae8..0000000000
--- a/apps/plugins/sdl/src/thread/riscos/SDL_systhread.c
+++ /dev/null
@@ -1,144 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* RISC OS version based on pthreads linux source */
25
26#include "SDL_thread.h"
27#include "../SDL_systhread.h"
28
29#if SDL_THREADS_DISABLED
30
31int SDL_SYS_CreateThread(SDL_Thread *thread, void *args)
32{
33 SDL_SetError("Threads have not been compiled into this version of the library");
34 return(-1);
35}
36
37void SDL_SYS_SetupThread(void)
38{
39 return;
40}
41
42Uint32 SDL_ThreadID(void)
43{
44 return(0);
45}
46
47void SDL_SYS_WaitThread(SDL_Thread *thread)
48{
49 return;
50}
51
52void SDL_SYS_KillThread(SDL_Thread *thread)
53{
54 return;
55}
56
57#else
58
59#include <signal.h>
60
61/* List of signals to mask in the subthreads */
62static int sig_list[] = {
63 SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH,
64 SIGVTALRM, SIGPROF, 0
65};
66
67#include <pthread.h>
68
69int riscos_using_threads = 0;
70Uint32 riscos_main_thread = 0; /* Thread running events */
71
72static void *RunThread(void *data)
73{
74 SDL_RunThread(data);
75 pthread_exit((void*)0);
76 return((void *)0); /* Prevent compiler warning */
77}
78
79int SDL_SYS_CreateThread(SDL_Thread *thread, void *args)
80{
81 pthread_attr_t type;
82
83 /* Set the thread attributes */
84 if ( pthread_attr_init(&type) != 0 ) {
85 SDL_SetError("Couldn't initialize pthread attributes");
86 return(-1);
87 }
88 pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);
89
90 /* Create the thread and go! */
91 if ( pthread_create(&thread->handle, &type, RunThread, args) != 0 ) {
92 SDL_SetError("Not enough resources to create thread");
93 return(-1);
94 }
95
96 if (riscos_using_threads == 0)
97 {
98 riscos_using_threads = 1;
99 riscos_main_thread = SDL_ThreadID();
100 }
101
102 return(0);
103}
104
105void SDL_SYS_SetupThread(void)
106{
107 int i;
108 sigset_t mask;
109
110 /* Mask asynchronous signals for this thread */
111 sigemptyset(&mask);
112 for ( i=0; sig_list[i]; ++i ) {
113 sigaddset(&mask, sig_list[i]);
114 }
115 pthread_sigmask(SIG_BLOCK, &mask, 0);
116
117#ifdef PTHREAD_CANCEL_ASYNCHRONOUS
118 /* Allow ourselves to be asynchronously cancelled */
119 { int oldstate;
120 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate);
121 }
122#endif
123}
124
125Uint32 SDL_ThreadID(void)
126{
127 return((Uint32)pthread_self());
128}
129
130void SDL_SYS_WaitThread(SDL_Thread *thread)
131{
132 pthread_join(thread->handle, 0);
133}
134
135void SDL_SYS_KillThread(SDL_Thread *thread)
136{
137#ifdef PTHREAD_CANCEL_ASYNCHRONOUS
138 pthread_cancel(thread->handle);
139#else
140 pthread_kill(thread->handle, SIGKILL);
141#endif
142}
143
144#endif
diff --git a/apps/plugins/sdl/src/thread/riscos/SDL_systhread_c.h b/apps/plugins/sdl/src/thread/riscos/SDL_systhread_c.h
deleted file mode 100644
index 9e1d2c8c5c..0000000000
--- a/apps/plugins/sdl/src/thread/riscos/SDL_systhread_c.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#if SDL_THREADS_DISABLED
25
26typedef int SYS_ThreadHandle;
27
28#else
29
30#include <pthread.h>
31
32typedef pthread_t SYS_ThreadHandle;
33
34#endif
diff --git a/apps/plugins/sdl/src/thread/symbian/SDL_sysmutex.cpp b/apps/plugins/sdl/src/thread/symbian/SDL_sysmutex.cpp
deleted file mode 100644
index f4b1aeaad2..0000000000
--- a/apps/plugins/sdl/src/thread/symbian/SDL_sysmutex.cpp
+++ /dev/null
@@ -1,130 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_sysmutex.cpp
25
26 Epoc version by Markus Mertama (w@iki.fi)
27*/
28
29
30#ifdef SAVE_RCSID
31static char rcsid =
32 "@(#) $Id: SDL_sysmutex.c,v 1.1.2.3 2000/06/22 15:25:23 hercules Exp $";
33#endif
34
35/* Mutex functions using the Win32 API */
36
37//#include <stdio.h>
38//#include <stdlib.h>
39
40#include <e32std.h>
41
42#include "epoc_sdl.h"
43
44#include "SDL_error.h"
45#include "SDL_mutex.h"
46
47
48#ifdef EKA2 //???
49struct SDL_mutex
50 {
51 TInt handle;
52 };
53#else
54struct _SDL_mutex
55 {
56 TInt handle;
57 };
58#endif
59
60extern TInt CreateUnique(TInt (*aFunc)(const TDesC& aName, TAny*, TAny*), TAny*, TAny*);
61
62TInt NewMutex(const TDesC& aName, TAny* aPtr1, TAny*)
63 {
64 return ((RMutex*)aPtr1)->CreateGlobal(aName);
65 }
66
67void DeleteMutex(TAny* aMutex)
68 {
69 SDL_DestroyMutex ((SDL_mutex*) aMutex);
70 }
71
72/* Create a mutex */
73SDL_mutex *SDL_CreateMutex(void)
74{
75 RMutex rmutex;
76
77 TInt status = CreateUnique(NewMutex, &rmutex, NULL);
78 if(status != KErrNone)
79 {
80 SDL_SetError("Couldn't create mutex");
81 }
82 SDL_mutex* mutex = new /*(ELeave)*/ SDL_mutex;
83 mutex->handle = rmutex.Handle();
84 EpocSdlEnv::AppendCleanupItem(TSdlCleanupItem(DeleteMutex, mutex));
85 return(mutex);
86}
87
88/* Free the mutex */
89void SDL_DestroyMutex(SDL_mutex *mutex)
90{
91 if ( mutex )
92 {
93 RMutex rmutex;
94 rmutex.SetHandle(mutex->handle);
95 if(rmutex.IsHeld())
96 {
97 rmutex.Signal();
98 }
99 rmutex.Close();
100 EpocSdlEnv::RemoveCleanupItem(mutex);
101 delete(mutex);
102 mutex = NULL;
103 }
104}
105
106/* Lock the mutex */
107int SDL_mutexP(SDL_mutex *mutex)
108{
109 if ( mutex == NULL ) {
110 SDL_SetError("Passed a NULL mutex");
111 return -1;
112 }
113 RMutex rmutex;
114 rmutex.SetHandle(mutex->handle);
115 rmutex.Wait();
116 return(0);
117}
118
119/* Unlock the mutex */
120int SDL_mutexV(SDL_mutex *mutex)
121{
122 if ( mutex == NULL ) {
123 SDL_SetError("Passed a NULL mutex");
124 return -1;
125 }
126 RMutex rmutex;
127 rmutex.SetHandle(mutex->handle);
128 rmutex.Signal();
129 return(0);
130}
diff --git a/apps/plugins/sdl/src/thread/symbian/SDL_syssem.cpp b/apps/plugins/sdl/src/thread/symbian/SDL_syssem.cpp
deleted file mode 100644
index 00f9901ee5..0000000000
--- a/apps/plugins/sdl/src/thread/symbian/SDL_syssem.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_syssem.cpp
25
26 Epoc version by Markus Mertama (w@iki.fi)
27*/
28
29#ifdef SAVE_RCSID
30static char rcsid =
31 "@(#) $Id: SDL_syssem.c,v 1.1.2.4 2000/06/22 15:24:48 hercules Exp $";
32#endif
33
34/* Semaphore functions using the Win32 API */
35
36//#include <stdio.h>
37//#include <stdlib.h>
38#include <e32std.h>
39
40#include "SDL_error.h"
41#include "SDL_thread.h"
42
43
44#define SDL_MUTEX_TIMEOUT -2
45
46struct SDL_semaphore
47 {
48 TInt handle;
49 TInt count;
50 };
51
52
53extern TInt CreateUnique(TInt (*aFunc)(const TDesC& aName, TAny*, TAny*), TAny*, TAny*);
54#ifndef EKA2
55extern TInt NewThread(const TDesC& aName, TAny* aPtr1, TAny* aPtr2);
56#endif
57
58TInt NewSema(const TDesC& aName, TAny* aPtr1, TAny* aPtr2)
59 {
60 TInt value = *((TInt*) aPtr2);
61 return ((RSemaphore*)aPtr1)->CreateGlobal(aName, value);
62 }
63
64/* Create a semaphore */
65SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
66{
67 RSemaphore s;
68 TInt status = CreateUnique(NewSema, &s, &initial_value);
69 if(status != KErrNone)
70 {
71 SDL_SetError("Couldn't create semaphore");
72 }
73 SDL_semaphore* sem = new /*(ELeave)*/ SDL_semaphore;
74 sem->handle = s.Handle();
75 sem->count = initial_value;
76 return(sem);
77}
78
79/* Free the semaphore */
80void SDL_DestroySemaphore(SDL_sem *sem)
81{
82 if ( sem )
83 {
84 RSemaphore sema;
85 sema.SetHandle(sem->handle);
86 while(--sem->count)
87 sema.Signal();
88 sema.Close();
89 delete sem;
90 sem = NULL;
91 }
92}
93
94#ifndef EKA2
95
96 struct TInfo
97 {
98 TInfo(TInt aTime, TInt aHandle) :
99 iTime(aTime), iHandle(aHandle), iVal(0) {}
100 TInt iTime;
101 TInt iHandle;
102 TInt iVal;
103 };
104
105
106
107TBool ThreadRun(TAny* aInfo)
108 {
109 TInfo* info = STATIC_CAST(TInfo*, aInfo);
110 User::After(info->iTime);
111 RSemaphore sema;
112 sema.SetHandle(info->iHandle);
113 sema.Signal();
114 info->iVal = SDL_MUTEX_TIMEOUT;
115 return 0;
116 }
117
118#endif
119
120
121void _WaitAll(SDL_sem *sem)
122 {
123 //since SemTryWait may changed the counter.
124 //this may not be atomic, but hopes it works.
125 RSemaphore sema;
126 sema.SetHandle(sem->handle);
127 sema.Wait();
128 while(sem->count < 0)
129 {
130 sema.Wait();
131 }
132 }
133
134int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
135{
136 if ( ! sem ) {
137 SDL_SetError("Passed a NULL sem");
138 return -1;
139 }
140
141 if ( timeout == SDL_MUTEX_MAXWAIT )
142 {
143 _WaitAll(sem);
144 return SDL_MUTEX_MAXWAIT;
145 }
146
147#ifdef EKA2
148
149 RSemaphore sema;
150 sema.SetHandle(sem->handle);
151 if(KErrNone == sema.Wait(timeout))
152 return 0;
153 return -1;
154#else
155 RThread thread;
156
157 TInfo* info = new (ELeave)TInfo(timeout, sem->handle);
158
159 TInt status = CreateUnique(NewThread, &thread, info);
160
161 if(status != KErrNone)
162 return status;
163
164 thread.Resume();
165
166 _WaitAll(sem);
167
168 if(thread.ExitType() == EExitPending)
169 {
170 thread.Kill(SDL_MUTEX_TIMEOUT);
171 }
172
173 thread.Close();
174
175 return info->iVal;
176#endif
177}
178
179int SDL_SemTryWait(SDL_sem *sem)
180{
181 if(sem->count > 0)
182 {
183 sem->count--;
184 }
185 return SDL_MUTEX_TIMEOUT;
186}
187
188int SDL_SemWait(SDL_sem *sem)
189{
190 return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT);
191}
192
193/* Returns the current count of the semaphore */
194Uint32 SDL_SemValue(SDL_sem *sem)
195{
196 if ( ! sem ) {
197 SDL_SetError("Passed a NULL sem");
198 return 0;
199 }
200 return sem->count;
201}
202
203int SDL_SemPost(SDL_sem *sem)
204{
205 if ( ! sem ) {
206 SDL_SetError("Passed a NULL sem");
207 return -1;
208 }
209 sem->count++;
210 RSemaphore sema;
211 sema.SetHandle(sem->handle);
212 sema.Signal();
213 return 0;
214}
diff --git a/apps/plugins/sdl/src/thread/symbian/SDL_systhread.cpp b/apps/plugins/sdl/src/thread/symbian/SDL_systhread.cpp
deleted file mode 100644
index 5e7adc5540..0000000000
--- a/apps/plugins/sdl/src/thread/symbian/SDL_systhread.cpp
+++ /dev/null
@@ -1,146 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_systhread.cpp
25 Epoc thread management routines for SDL
26
27 Epoc version by Markus Mertama (w@iki.fi)
28*/
29
30#include "epoc_sdl.h"
31
32//#include <stdlib.h>
33//#include <stdio.h>
34
35
36
37extern "C" {
38#undef NULL
39#include "SDL_error.h"
40#include "SDL_thread.h"
41#include "SDL_systhread.h"
42#include "SDL_thread_c.h"
43 }
44
45#include <e32std.h>
46#include "epoc_sdl.h"
47
48
49static int object_count;
50
51int RunThread(TAny* data)
52{
53 CTrapCleanup* cleanup = CTrapCleanup::New();
54 TRAPD(err, SDL_RunThread(data));
55 EpocSdlEnv::CleanupItems();
56 delete cleanup;
57 return(err);
58}
59
60
61TInt NewThread(const TDesC& aName, TAny* aPtr1, TAny* aPtr2)
62 {
63 return ((RThread*)(aPtr1))->Create(aName,
64 RunThread,
65 KDefaultStackSize,
66 NULL,
67 aPtr2);
68 }
69
70int CreateUnique(TInt (*aFunc)(const TDesC& aName, TAny*, TAny*), TAny* aPtr1, TAny* aPtr2)
71 {
72 TBuf<16> name;
73 TInt status = KErrNone;
74 do
75 {
76 object_count++;
77 name.Format(_L("SDL_%x"), object_count);
78 status = aFunc(name, aPtr1, aPtr2);
79 }
80 while(status == KErrAlreadyExists);
81 return status;
82 }
83
84
85int SDL_SYS_CreateThread(SDL_Thread *thread, void *args)
86{
87 RThread rthread;
88
89 const TInt status = CreateUnique(NewThread, &rthread, args);
90 if (status != KErrNone)
91 {
92 delete(((RThread*)(thread->handle)));
93 thread->handle = NULL;
94 SDL_SetError("Not enough resources to create thread");
95 return(-1);
96 }
97 rthread.Resume();
98 thread->handle = rthread.Handle();
99 return(0);
100}
101
102void SDL_SYS_SetupThread(void)
103{
104 return;
105}
106
107Uint32 SDL_ThreadID(void)
108{
109 RThread current;
110 const TThreadId id = current.Id();
111 return id;
112}
113
114void SDL_SYS_WaitThread(SDL_Thread *thread)
115{
116 SDL_TRACE1("Close thread", thread);
117 RThread t;
118 const TInt err = t.Open(thread->threadid);
119 if(err == KErrNone && t.ExitType() == EExitPending)
120 {
121 TRequestStatus status;
122 t.Logon(status);
123 User::WaitForRequest(status);
124 }
125 t.Close();
126
127 /* RUndertaker taker;
128 taker.Create();
129 TRequestStatus status;
130 taker.Logon(status, thread->handle);
131 User::WaitForRequest(status);
132 taker.Close();*/
133 SDL_TRACE1("Closed thread", thread);
134}
135
136/* WARNING: This function is really a last resort.
137 * Threads should be signaled and then exit by themselves.
138 * TerminateThread() doesn't perform stack and DLL cleanup.
139 */
140void SDL_SYS_KillThread(SDL_Thread *thread)
141{
142 RThread rthread;
143 rthread.SetHandle(thread->handle);
144 rthread.Kill(0);
145 rthread.Close();
146}
diff --git a/apps/plugins/sdl/src/thread/symbian/SDL_systhread_c.h b/apps/plugins/sdl/src/thread/symbian/SDL_systhread_c.h
deleted file mode 100644
index f5f1729cda..0000000000
--- a/apps/plugins/sdl/src/thread/symbian/SDL_systhread_c.h
+++ /dev/null
@@ -1,30 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_systhread_c.h
25
26 Epoc version by Markus Mertama (w@iki.fi)
27*/
28
29typedef int SYS_ThreadHandle;
30
diff --git a/apps/plugins/sdl/src/thread/win32/SDL_sysmutex.c b/apps/plugins/sdl/src/thread/win32/SDL_sysmutex.c
deleted file mode 100644
index 1d7805c062..0000000000
--- a/apps/plugins/sdl/src/thread/win32/SDL_sysmutex.c
+++ /dev/null
@@ -1,95 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Mutex functions using the Win32 API */
25
26#define WIN32_LEAN_AND_MEAN
27#include <windows.h>
28
29#include "SDL_mutex.h"
30
31
32struct SDL_mutex {
33 HANDLE id;
34};
35
36/* Create a mutex */
37SDL_mutex *SDL_CreateMutex(void)
38{
39 SDL_mutex *mutex;
40
41 /* Allocate mutex memory */
42 mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex));
43 if ( mutex ) {
44 /* Create the mutex, with initial value signaled */
45 mutex->id = CreateMutex(NULL, FALSE, NULL);
46 if ( ! mutex->id ) {
47 SDL_SetError("Couldn't create mutex");
48 SDL_free(mutex);
49 mutex = NULL;
50 }
51 } else {
52 SDL_OutOfMemory();
53 }
54 return(mutex);
55}
56
57/* Free the mutex */
58void SDL_DestroyMutex(SDL_mutex *mutex)
59{
60 if ( mutex ) {
61 if ( mutex->id ) {
62 CloseHandle(mutex->id);
63 mutex->id = 0;
64 }
65 SDL_free(mutex);
66 }
67}
68
69/* Lock the mutex */
70int SDL_mutexP(SDL_mutex *mutex)
71{
72 if ( mutex == NULL ) {
73 SDL_SetError("Passed a NULL mutex");
74 return -1;
75 }
76 if ( WaitForSingleObject(mutex->id, INFINITE) == WAIT_FAILED ) {
77 SDL_SetError("Couldn't wait on mutex");
78 return -1;
79 }
80 return(0);
81}
82
83/* Unlock the mutex */
84int SDL_mutexV(SDL_mutex *mutex)
85{
86 if ( mutex == NULL ) {
87 SDL_SetError("Passed a NULL mutex");
88 return -1;
89 }
90 if ( ReleaseMutex(mutex->id) == FALSE ) {
91 SDL_SetError("Couldn't release mutex");
92 return -1;
93 }
94 return(0);
95}
diff --git a/apps/plugins/sdl/src/thread/win32/SDL_syssem.c b/apps/plugins/sdl/src/thread/win32/SDL_syssem.c
deleted file mode 100644
index 261d24cbfe..0000000000
--- a/apps/plugins/sdl/src/thread/win32/SDL_syssem.c
+++ /dev/null
@@ -1,164 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Semaphore functions using the Win32 API */
25
26#define WIN32_LEAN_AND_MEAN
27#include <windows.h>
28
29#include "SDL_thread.h"
30#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
31#include "win_ce_semaphore.h"
32#endif
33
34
35struct SDL_semaphore {
36#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
37 SYNCHHANDLE id;
38#else
39 HANDLE id;
40#endif
41 volatile LONG count;
42};
43
44
45/* Create a semaphore */
46SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
47{
48 SDL_sem *sem;
49
50 /* Allocate sem memory */
51 sem = (SDL_sem *)SDL_malloc(sizeof(*sem));
52 if ( sem ) {
53 /* Create the semaphore, with max value 32K */
54#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
55 sem->id = CreateSemaphoreCE(NULL, initial_value, 32*1024, NULL);
56#else
57 sem->id = CreateSemaphore(NULL, initial_value, 32*1024, NULL);
58#endif
59 sem->count = (LONG) initial_value;
60 if ( ! sem->id ) {
61 SDL_SetError("Couldn't create semaphore");
62 SDL_free(sem);
63 sem = NULL;
64 }
65 } else {
66 SDL_OutOfMemory();
67 }
68 return(sem);
69}
70
71/* Free the semaphore */
72void SDL_DestroySemaphore(SDL_sem *sem)
73{
74 if ( sem ) {
75 if ( sem->id ) {
76#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
77 CloseSynchHandle(sem->id);
78#else
79 CloseHandle(sem->id);
80#endif
81 sem->id = 0;
82 }
83 SDL_free(sem);
84 }
85}
86
87int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
88{
89 int retval;
90 DWORD dwMilliseconds;
91
92 if ( ! sem ) {
93 SDL_SetError("Passed a NULL sem");
94 return -1;
95 }
96
97 if ( timeout == SDL_MUTEX_MAXWAIT ) {
98 dwMilliseconds = INFINITE;
99 } else {
100 dwMilliseconds = (DWORD)timeout;
101 }
102#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
103 switch (WaitForSemaphoreCE(sem->id, dwMilliseconds)) {
104#else
105 switch (WaitForSingleObject(sem->id, dwMilliseconds)) {
106#endif
107 case WAIT_OBJECT_0:
108 InterlockedDecrement(&sem->count);
109 retval = 0;
110 break;
111 case WAIT_TIMEOUT:
112 retval = SDL_MUTEX_TIMEDOUT;
113 break;
114 default:
115 SDL_SetError("WaitForSingleObject() failed");
116 retval = -1;
117 break;
118 }
119 return retval;
120}
121
122int SDL_SemTryWait(SDL_sem *sem)
123{
124 return SDL_SemWaitTimeout(sem, 0);
125}
126
127int SDL_SemWait(SDL_sem *sem)
128{
129 return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT);
130}
131
132/* Returns the current count of the semaphore */
133Uint32 SDL_SemValue(SDL_sem *sem)
134{
135 if ( ! sem ) {
136 SDL_SetError("Passed a NULL sem");
137 return 0;
138 }
139 return (Uint32) sem->count;
140}
141
142int SDL_SemPost(SDL_sem *sem)
143{
144 if ( ! sem ) {
145 SDL_SetError("Passed a NULL sem");
146 return -1;
147 }
148 /* Increase the counter in the first place, because
149 * after a successful release the semaphore may
150 * immediately get destroyed by another thread which
151 * is waiting for this semaphore.
152 */
153 InterlockedIncrement(&sem->count);
154#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
155 if ( ReleaseSemaphoreCE(sem->id, 1, NULL) == FALSE ) {
156#else
157 if ( ReleaseSemaphore(sem->id, 1, NULL) == FALSE ) {
158#endif
159 InterlockedDecrement(&sem->count); /* restore */
160 SDL_SetError("ReleaseSemaphore() failed");
161 return -1;
162 }
163 return 0;
164}
diff --git a/apps/plugins/sdl/src/thread/win32/SDL_systhread.c b/apps/plugins/sdl/src/thread/win32/SDL_systhread.c
deleted file mode 100644
index 55cb88a58c..0000000000
--- a/apps/plugins/sdl/src/thread/win32/SDL_systhread.c
+++ /dev/null
@@ -1,162 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Win32 thread management routines for SDL */
25
26#define WIN32_LEAN_AND_MEAN
27#include <windows.h>
28
29#include "SDL_thread.h"
30#include "../SDL_thread_c.h"
31#include "../SDL_systhread.h"
32
33#ifndef SDL_PASSED_BEGINTHREAD_ENDTHREAD
34#ifndef _WIN32_WCE
35/* We'll use the C library from this DLL */
36#include <process.h>
37#endif
38
39#if defined(__WATCOMC__)
40/* This is for Watcom targets except OS2 */
41#if __WATCOMC__ < 1240
42#define __watcall
43#endif
44typedef unsigned long (__watcall *pfnSDL_CurrentBeginThread) (void *, unsigned,
45 unsigned (__stdcall *func)(void *), void *arg,
46 unsigned, unsigned *threadID);
47typedef void (__watcall *pfnSDL_CurrentEndThread)(unsigned code);
48#elif (defined(__MINGW32__) && (__GNUC__ < 4))
49typedef unsigned long (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned,
50 unsigned (__stdcall *func)(void *), void *arg,
51 unsigned, unsigned *threadID);
52typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code);
53#else
54typedef uintptr_t (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned,
55 unsigned (__stdcall *func)(void *), void *arg,
56 unsigned, unsigned *threadID);
57typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code);
58#endif
59#endif /* !SDL_PASSED_BEGINTHREAD_ENDTHREAD */
60
61
62typedef struct ThreadStartParms
63{
64 void *args;
65 pfnSDL_CurrentEndThread pfnCurrentEndThread;
66} tThreadStartParms, *pThreadStartParms;
67
68static DWORD RunThread(void *data)
69{
70 pThreadStartParms pThreadParms = (pThreadStartParms)data;
71 pfnSDL_CurrentEndThread pfnCurrentEndThread = NULL;
72
73 // Call the thread function!
74 SDL_RunThread(pThreadParms->args);
75
76 // Get the current endthread we have to use!
77 if (pThreadParms)
78 {
79 pfnCurrentEndThread = pThreadParms->pfnCurrentEndThread;
80 SDL_free(pThreadParms);
81 }
82 // Call endthread!
83 if (pfnCurrentEndThread)
84 (*pfnCurrentEndThread)(0);
85 return(0);
86}
87
88static DWORD WINAPI RunThreadViaCreateThread(LPVOID data)
89{
90 return RunThread(data);
91}
92
93static unsigned __stdcall RunThreadViaBeginThreadEx(void *data)
94{
95 return (unsigned) RunThread(data);
96}
97
98#ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
99int SDL_SYS_CreateThread(SDL_Thread *thread, void *args, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread)
100{
101#else
102int SDL_SYS_CreateThread(SDL_Thread *thread, void *args)
103{
104#ifdef _WIN32_WCE
105 pfnSDL_CurrentBeginThread pfnBeginThread = NULL;
106 pfnSDL_CurrentEndThread pfnEndThread = NULL;
107#else
108 pfnSDL_CurrentBeginThread pfnBeginThread = _beginthreadex;
109 pfnSDL_CurrentEndThread pfnEndThread = _endthreadex;
110#endif
111#endif /* SDL_PASSED_BEGINTHREAD_ENDTHREAD */
112 pThreadStartParms pThreadParms = (pThreadStartParms)SDL_malloc(sizeof(tThreadStartParms));
113 if (!pThreadParms) {
114 SDL_OutOfMemory();
115 return(-1);
116 }
117
118 // Save the function which we will have to call to clear the RTL of calling app!
119 pThreadParms->pfnCurrentEndThread = pfnEndThread;
120 // Also save the real parameters we have to pass to thread function
121 pThreadParms->args = args;
122
123 if (pfnBeginThread) {
124 unsigned threadid = 0;
125 thread->handle = (SYS_ThreadHandle)
126 ((size_t) pfnBeginThread(NULL, 0, RunThreadViaBeginThreadEx,
127 pThreadParms, 0, &threadid));
128 } else {
129 DWORD threadid = 0;
130 thread->handle = CreateThread(NULL, 0, RunThreadViaCreateThread, pThreadParms, 0, &threadid);
131 }
132 if (thread->handle == NULL) {
133 SDL_SetError("Not enough resources to create thread");
134 return(-1);
135 }
136 return(0);
137}
138
139void SDL_SYS_SetupThread(void)
140{
141 return;
142}
143
144Uint32 SDL_ThreadID(void)
145{
146 return((Uint32)GetCurrentThreadId());
147}
148
149void SDL_SYS_WaitThread(SDL_Thread *thread)
150{
151 WaitForSingleObject(thread->handle, INFINITE);
152 CloseHandle(thread->handle);
153}
154
155/* WARNING: This function is really a last resort.
156 * Threads should be signaled and then exit by themselves.
157 * TerminateThread() doesn't perform stack and DLL cleanup.
158 */
159void SDL_SYS_KillThread(SDL_Thread *thread)
160{
161 TerminateThread(thread->handle, FALSE);
162}
diff --git a/apps/plugins/sdl/src/thread/win32/SDL_systhread_c.h b/apps/plugins/sdl/src/thread/win32/SDL_systhread_c.h
deleted file mode 100644
index 10b0a7d6b5..0000000000
--- a/apps/plugins/sdl/src/thread/win32/SDL_systhread_c.h
+++ /dev/null
@@ -1,28 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#define WIN32_LEAN_AND_MEAN
25#include <windows.h>
26
27typedef HANDLE SYS_ThreadHandle;
28
diff --git a/apps/plugins/sdl/src/thread/win32/win_ce_semaphore.c b/apps/plugins/sdl/src/thread/win32/win_ce_semaphore.c
deleted file mode 100644
index 9db45c4391..0000000000
--- a/apps/plugins/sdl/src/thread/win32/win_ce_semaphore.c
+++ /dev/null
@@ -1,216 +0,0 @@
1/* win_ce_semaphore.c
2
3 Copyright (c) 1998, Johnson M. Hart
4 (with corrections 2001 by Rainer Loritz)
5 Permission is granted for any and all use providing that this
6 copyright is properly acknowledged.
7 There are no assurances of suitability for any use whatsoever.
8
9 WINDOWS CE: There is a collection of Windows CE functions to simulate
10 semaphores using only a mutex and an event. As Windows CE events cannot
11 be named, these simulated semaphores cannot be named either.
12
13 Implementation notes:
14 1. All required internal data structures are allocated on the process's heap.
15 2. Where appropriate, a new error code is returned (see the header
16 file), or, if the error is a Win32 error, that code is unchanged.
17 3. Notice the new handle type "SYNCHHANDLE" that has handles, counters,
18 and other information. This structure will grow as new objects are added
19 to this set; some members are specific to only one or two of the objects.
20 4. Mutexes are used for critical sections. These could be replaced with
21 CRITICAL_SECTION objects but then this would give up the time out
22 capability.
23 5. The implementation shows several interesting aspects of synchronization, some
24 of which are specific to Win32 and some of which are general. These are pointed
25 out in the comments as appropriate.
26 6. The wait function emulates WaitForSingleObject only. An emulation of
27 WaitForMultipleObjects is much harder to implement outside the kernel,
28 and it is not clear how to handle a mixture of WCE semaphores and normal
29 events and mutexes. */
30
31#define WIN32_LEAN_AND_MEAN
32#include <windows.h>
33
34#include "win_ce_semaphore.h"
35
36static SYNCHHANDLE CleanUp (SYNCHHANDLE hSynch, DWORD Flags);
37
38SYNCHHANDLE CreateSemaphoreCE (
39
40 LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, /* pointer to security attributes */
41 LONG lInitialCount, /* initial count */
42 LONG lMaximumCount, /* maximum count */
43 LPCTSTR lpName )
44
45/* Semaphore for use with Windows CE that does not support them directly.
46 Requires a counter, a mutex to protect the counter, and an
47 autoreset event.
48
49 Here are the rules that must always hold between the autoreset event
50 and the mutex (any violation of these rules by the CE semaphore functions
51 will, in all likelihood, result in a defect):
52 1. No thread can set, pulse, or reset the event,
53 nor can it access any part of the SYNCHHANDLE structure,
54 without first gaining ownership of the mutex.
55 BUT, a thread can wait on the event without owning the mutex
56 (this is clearly necessary or else the event could never be set).
57 2. The event is in a signaled state if and only if the current semaphore
58 count ("CurCount") is greater than zero.
59 3. The semaphore count is always >= 0 and <= the maximum count */
60
61{
62 SYNCHHANDLE hSynch = NULL, result = NULL;
63
64 __try
65 {
66 if (lInitialCount > lMaximumCount || lMaximumCount < 0 || lInitialCount < 0)
67 {
68 /* Bad parameters */
69 SetLastError (SYNCH_ERROR);
70 __leave;
71 }
72
73 hSynch = HeapAlloc (GetProcessHeap(), HEAP_ZERO_MEMORY, SYNCH_HANDLE_SIZE);
74 if (hSynch == NULL) __leave;
75
76 hSynch->MaxCount = lMaximumCount;
77 hSynch->CurCount = lInitialCount;
78 hSynch->lpName = lpName;
79
80 hSynch->hMutex = CreateMutex (lpSemaphoreAttributes, FALSE, NULL);
81
82 WaitForSingleObject (hSynch->hMutex, INFINITE);
83 /* Create the event. It is initially signaled if and only if the
84 initial count is > 0 */
85 hSynch->hEvent = CreateEvent (lpSemaphoreAttributes, FALSE,
86 lInitialCount > 0, NULL);
87 ReleaseMutex (hSynch->hMutex);
88 hSynch->hSemph = NULL;
89 }
90 __finally
91 {
92 /* Return with the handle, or, if there was any error, return
93 a null after closing any open handles and freeing any allocated memory. */
94 result=CleanUp(hSynch, 6 /* An event and a mutex, but no semaphore. */);
95 }
96
97 return result;
98}
99
100BOOL ReleaseSemaphoreCE (SYNCHHANDLE hSemCE, LONG cReleaseCount, LPLONG lpPreviousCount)
101/* Windows CE equivalent to ReleaseSemaphore. */
102{
103 BOOL Result = TRUE;
104
105 /* Gain access to the object to assure that the release count
106 would not cause the total count to exceed the maximum. */
107
108 __try
109 {
110 WaitForSingleObject (hSemCE->hMutex, INFINITE);
111 /* reply only if asked to */
112 if (lpPreviousCount!=NULL)
113 *lpPreviousCount = hSemCE->CurCount;
114 if (hSemCE->CurCount + cReleaseCount > hSemCE->MaxCount || cReleaseCount <= 0)
115 {
116 SetLastError (SYNCH_ERROR);
117 Result = FALSE;
118 __leave;
119 }
120 hSemCE->CurCount += cReleaseCount;
121
122 /* Set the autoreset event, releasing exactly one waiting thread, now or
123 in the future. */
124
125 SetEvent (hSemCE->hEvent);
126 }
127 __finally
128 {
129 ReleaseMutex (hSemCE->hMutex);
130 }
131
132 return Result;
133}
134
135DWORD WaitForSemaphoreCE (SYNCHHANDLE hSemCE, DWORD dwMilliseconds)
136 /* Windows CE semaphore equivalent of WaitForSingleObject. */
137{
138 DWORD WaitResult;
139
140 WaitResult = WaitForSingleObject (hSemCE->hMutex, dwMilliseconds);
141 if (WaitResult != WAIT_OBJECT_0 && WaitResult != WAIT_ABANDONED_0) return WaitResult;
142 while (hSemCE->CurCount <= 0)
143 {
144
145 /* The count is 0, and the thread must wait on the event (which, by
146 the rules, is currently reset) for semaphore resources to become
147 available. First, of course, the mutex must be released so that another
148 thread will be capable of setting the event. */
149
150 ReleaseMutex (hSemCE->hMutex);
151
152 /* Wait for the event to be signaled, indicating a semaphore state change.
153 The event is autoreset and signaled with a SetEvent (not PulseEvent)
154 so exactly one waiting thread (whether or not there is currently
155 a waiting thread) is released as a result of the SetEvent. */
156
157 WaitResult = WaitForSingleObject (hSemCE->hEvent, dwMilliseconds);
158 if (WaitResult != WAIT_OBJECT_0) return WaitResult;
159
160 /* This is where the properties of setting of an autoreset event is critical
161 to assure that, even if the semaphore state changes between the
162 preceding Wait and the next, and even if NO threads are waiting
163 on the event at the time of the SetEvent, at least one thread
164 will be released.
165 Pulsing a manual reset event would appear to work, but it would have
166 a defect which could appear if the semaphore state changed between
167 the two waits. */
168
169 WaitResult = WaitForSingleObject (hSemCE->hMutex, dwMilliseconds);
170 if (WaitResult != WAIT_OBJECT_0 && WaitResult != WAIT_ABANDONED_0) return WaitResult;
171
172 }
173 /* The count is not zero and this thread owns the mutex. */
174
175 hSemCE->CurCount--;
176 /* The event is now unsignaled, BUT, the semaphore count may not be
177 zero, in which case the event should be signaled again
178 before releasing the mutex. */
179
180 if (hSemCE->CurCount > 0) SetEvent (hSemCE->hEvent);
181 ReleaseMutex (hSemCE->hMutex);
182 return WaitResult;
183}
184
185BOOL CloseSynchHandle (SYNCHHANDLE hSynch)
186/* Close a synchronization handle.
187 Improvement: Test for a valid handle before dereferencing the handle. */
188{
189 BOOL Result = TRUE;
190 if (hSynch->hEvent != NULL) Result = Result && CloseHandle (hSynch->hEvent);
191 if (hSynch->hMutex != NULL) Result = Result && CloseHandle (hSynch->hMutex);
192 if (hSynch->hSemph != NULL) Result = Result && CloseHandle (hSynch->hSemph);
193 HeapFree (GetProcessHeap (), 0, hSynch);
194 return (Result);
195}
196
197static SYNCHHANDLE CleanUp (SYNCHHANDLE hSynch, DWORD Flags)
198{ /* Prepare to return from a create of a synchronization handle.
199 If there was any failure, free any allocated resources.
200 "Flags" indicates which Win32 objects are required in the
201 synchronization handle. */
202
203 BOOL ok = TRUE;
204
205 if (hSynch == NULL) return NULL;
206 if ((Flags & 4) == 1 && (hSynch->hEvent == NULL)) ok = FALSE;
207 if ((Flags & 2) == 1 && (hSynch->hMutex == NULL)) ok = FALSE;
208 if ((Flags & 1) == 1 && (hSynch->hEvent == NULL)) ok = FALSE;
209 if (!ok)
210 {
211 CloseSynchHandle (hSynch);
212 return NULL;
213 }
214 /* Everything worked */
215 return hSynch;
216}
diff --git a/apps/plugins/sdl/src/thread/win32/win_ce_semaphore.h b/apps/plugins/sdl/src/thread/win32/win_ce_semaphore.h
deleted file mode 100644
index af2d7b613d..0000000000
--- a/apps/plugins/sdl/src/thread/win32/win_ce_semaphore.h
+++ /dev/null
@@ -1,22 +0,0 @@
1/* win_ce_semaphore.h - header file to go with win_ce_semaphore.c */
2
3typedef struct _SYNCH_HANDLE_STRUCTURE {
4 HANDLE hEvent;
5 HANDLE hMutex;
6 HANDLE hSemph;
7 LONG MaxCount;
8 volatile LONG CurCount;
9 LPCTSTR lpName;
10} SYNCH_HANDLE_STRUCTURE, *SYNCHHANDLE;
11
12#define SYNCH_HANDLE_SIZE sizeof (SYNCH_HANDLE_STRUCTURE)
13
14 /* Error codes - all must have bit 29 set */
15#define SYNCH_ERROR 0X20000000 /* EXERCISE - REFINE THE ERROR NUMBERS */
16
17extern SYNCHHANDLE CreateSemaphoreCE (LPSECURITY_ATTRIBUTES, LONG, LONG, LPCTSTR);
18
19extern BOOL ReleaseSemaphoreCE (SYNCHHANDLE, LONG, LPLONG);
20extern DWORD WaitForSemaphoreCE (SYNCHHANDLE, DWORD);
21
22extern BOOL CloseSynchHandle (SYNCHHANDLE);
diff --git a/apps/plugins/sdl/src/timer/beos/SDL_systimer.c b/apps/plugins/sdl/src/timer/beos/SDL_systimer.c
deleted file mode 100644
index f4cf6c765e..0000000000
--- a/apps/plugins/sdl/src/timer/beos/SDL_systimer.c
+++ /dev/null
@@ -1,95 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_BEOS
25
26#include <be/kernel/OS.h>
27
28#include "SDL_thread.h"
29#include "SDL_timer.h"
30#include "../SDL_timer_c.h"
31
32static bigtime_t start;
33
34void SDL_StartTicks(void)
35{
36 /* Set first ticks value */
37 start = system_time();
38}
39
40Uint32 SDL_GetTicks(void)
41{
42 return((system_time()-start)/1000);
43}
44
45void SDL_Delay(Uint32 ms)
46{
47 snooze(ms*1000);
48}
49
50/* Data to handle a single periodic alarm */
51static int timer_alive = 0;
52static SDL_Thread *timer = NULL;
53
54static int RunTimer(void *unused)
55{
56 while ( timer_alive ) {
57 if ( SDL_timer_running ) {
58 SDL_ThreadedTimerCheck();
59 }
60 SDL_Delay(10);
61 }
62 return(0);
63}
64
65/* This is only called if the event thread is not running */
66int SDL_SYS_TimerInit(void)
67{
68 timer_alive = 1;
69 timer = SDL_CreateThread(RunTimer, NULL);
70 if ( timer == NULL )
71 return(-1);
72 return(SDL_SetTimerThreaded(1));
73}
74
75void SDL_SYS_TimerQuit(void)
76{
77 timer_alive = 0;
78 if ( timer ) {
79 SDL_WaitThread(timer, NULL);
80 timer = NULL;
81 }
82}
83
84int SDL_SYS_StartTimer(void)
85{
86 SDL_SetError("Internal logic error: BeOS uses threaded timer");
87 return(-1);
88}
89
90void SDL_SYS_StopTimer(void)
91{
92 return;
93}
94
95#endif /* SDL_TIMER_BEOS */
diff --git a/apps/plugins/sdl/src/timer/dc/SDL_systimer.c b/apps/plugins/sdl/src/timer/dc/SDL_systimer.c
deleted file mode 100644
index 386e158607..0000000000
--- a/apps/plugins/sdl/src/timer/dc/SDL_systimer.c
+++ /dev/null
@@ -1,100 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_DC
25
26#include <kos.h>
27
28#include "SDL_thread.h"
29#include "SDL_timer.h"
30#include "../SDL_timer_c.h"
31
32static unsigned start;
33
34/*
35 jif = ms * HZ /1000
36 ms = jif * 1000/HZ
37*/
38
39void SDL_StartTicks(void)
40{
41 /* Set first ticks value */
42 start = jiffies;
43}
44
45Uint32 SDL_GetTicks(void)
46{
47 return((jiffies-start)*1000/HZ);
48}
49
50void SDL_Delay(Uint32 ms)
51{
52 thd_sleep(ms);
53}
54
55/* Data to handle a single periodic alarm */
56static int timer_alive = 0;
57static SDL_Thread *timer = NULL;
58
59static int RunTimer(void *unused)
60{
61 while ( timer_alive ) {
62 if ( SDL_timer_running ) {
63 SDL_ThreadedTimerCheck();
64 }
65 SDL_Delay(10);
66 }
67 return(0);
68}
69
70/* This is only called if the event thread is not running */
71int SDL_SYS_TimerInit(void)
72{
73 timer_alive = 1;
74 timer = SDL_CreateThread(RunTimer, NULL);
75 if ( timer == NULL )
76 return(-1);
77 return(SDL_SetTimerThreaded(1));
78}
79
80void SDL_SYS_TimerQuit(void)
81{
82 timer_alive = 0;
83 if ( timer ) {
84 SDL_WaitThread(timer, NULL);
85 timer = NULL;
86 }
87}
88
89int SDL_SYS_StartTimer(void)
90{
91 SDL_SetError("Internal logic error: DC uses threaded timer");
92 return(-1);
93}
94
95void SDL_SYS_StopTimer(void)
96{
97 return;
98}
99
100#endif /* SDL_TIMER_DC */
diff --git a/apps/plugins/sdl/src/timer/macos/FastTimes.c b/apps/plugins/sdl/src/timer/macos/FastTimes.c
deleted file mode 100644
index 2da74b7d18..0000000000
--- a/apps/plugins/sdl/src/timer/macos/FastTimes.c
+++ /dev/null
@@ -1,352 +0,0 @@
1/* File "FastTimes.c" - Original code by Matt Slot <fprefect@ambrosiasw.com> */
2/* Created 4/24/99 - This file is hereby placed in the public domain */
3/* Updated 5/21/99 - Calibrate to VIA, add TBR support, renamed functions */
4/* Updated 10/4/99 - Use AbsoluteToNanoseconds() in case Absolute = double */
5/* Updated 2/15/00 - Check for native Time Manager, no need to calibrate */
6/* Updated 2/19/00 - Fixed default value for gScale under native Time Mgr */
7/* Updated 3/21/00 - Fixed ns conversion, create 2 different scale factors */
8/* Updated 5/03/00 - Added copyright and placed into PD. No code changes */
9/* Updated 8/01/00 - Made "Carbon-compatible" by replacing LMGetTicks() */
10
11/* This file is Copyright (C) Matt Slot, 1999-2012. It is hereby placed into
12 the public domain. The author makes no warranty as to fitness or stability */
13
14#include <Gestalt.h>
15#include <LowMem.h>
16#include <CodeFragments.h>
17#include <DriverServices.h>
18#include <Timer.h>
19
20#include "FastTimes.h"
21
22#ifdef TARGET_CPU_PPC
23#undef GENERATINGPOWERPC /* stop whining */
24#define GENERATINGPOWERPC TARGET_CPU_PPC
25#endif
26
27/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
28/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
29/*
30 On 680x0 machines, we just use Microseconds().
31
32 On PowerPC machines, we try several methods:
33 * DriverServicesLib is available on all PCI PowerMacs, and perhaps
34 some NuBus PowerMacs. If it is, we use UpTime() : Overhead = 2.1 µsec.
35 * The PowerPC 601 has a built-in "real time clock" RTC, and we fall
36 back to that, accessing it directly from asm. Overhead = 1.3 µsec.
37 * Later PowerPCs have an accurate "time base register" TBR, and we
38 fall back to that, access it from PowerPC asm. Overhead = 1.3 µsec.
39 * We can also try Microseconds() which is emulated : Overhead = 36 µsec.
40
41 On PowerPC machines, we avoid the following:
42 * OpenTransport is available on all PCI and some NuBus PowerMacs, but it
43 uses UpTime() if available and falls back to Microseconds() otherwise.
44 * InputSprocket is available on many PowerMacs, but again it uses
45 UpTime() if available and falls back to Microseconds() otherwise.
46
47 Another PowerPC note: certain configurations, especially 3rd party upgrade
48 cards, may return inaccurate timings for the CPU or memory bus -- causing
49 skew in various system routines (up to 20% drift!). The VIA chip is very
50 accurate, and it's the basis for the Time Manager and Microseconds().
51 Unfortunately, it's also very slow because the MacOS has to (a) switch to
52 68K and (b) poll for a VIA event.
53
54 We compensate for the drift by calibrating a floating point scale factor
55 between our fast method and the accurate timer at startup, then convert
56 each sample quickly on the fly. I'd rather not have the initialization
57 overhead -- but it's simply necessary for accurate timing. You can drop
58 it down to 30 ticks if you prefer, but that's as low as I'd recommend.
59
60 Under MacOS 9, "new world" Macs (iMacs, B+W G3s and G+W G4s) have a native
61 Time Manager implementation: UpTime(), Microseconds(), and TickCount() are
62 all based on the same underlying counter. This makes it silly to calibrate
63 UpTime() against TickCount(). We now check for this feature using Gestalt(),
64 and skip the whole calibration step if possible.
65
66*/
67/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
68/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
69
70#define RTCToNano(w) ((double) (w).hi * 1000000000.0 + (double) (w).lo)
71#define WideTo64bit(w) (*(UInt64 *) &(w))
72
73/* LMGetTicks() is not in Carbon and TickCount() has a fair bit of overhead,
74 so for speed we always read lowmem directly. This is a Mac OS X no-no, but
75 it always work on those systems that don't have a native Time Manager (ie,
76 anything before MacOS 9) -- regardless whether we are in Carbon or not! */
77#define MyLMGetTicks() (*(volatile UInt32 *) 0x16A)
78
79#if GENERATINGPOWERPC
80
81static asm UnsignedWide PollRTC(void);
82static asm UnsignedWide PollTBR(void);
83static Ptr FindFunctionInSharedLib(StringPtr libName, StringPtr funcName);
84
85static Boolean gInited = false;
86static Boolean gNative = false;
87static Boolean gUseRTC = false;
88static Boolean gUseTBR = false;
89static double gScaleUSec = 1.0 / 1000.0; /* 1 / ( nsec / usec) */
90static double gScaleMSec = 1.0 / 1000000.0; /* 1 / ( nsec / msec) */
91
92/* Functions loaded from DriverServicesLib */
93typedef AbsoluteTime (*UpTimeProcPtr)(void);
94typedef Nanoseconds (*A2NSProcPtr)(AbsoluteTime);
95static UpTimeProcPtr gUpTime = NULL;
96static A2NSProcPtr gA2NS = NULL;
97
98#endif /* GENERATINGPOWERPC */
99
100/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
101/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
102
103void FastInitialize() {
104 SInt32 result;
105
106 if (!gInited) {
107
108#if GENERATINGPOWERPC
109
110 /* Initialize the feature flags */
111 gNative = gUseRTC = gUseTBR = false;
112
113 /* We use CFM to find and load needed symbols from shared libraries, so
114 the application doesn't have to weak-link them, for convenience. */
115 gUpTime = (UpTimeProcPtr) FindFunctionInSharedLib(
116 "\pDriverServicesLib", "\pUpTime");
117 if (gUpTime) gA2NS = (A2NSProcPtr) FindFunctionInSharedLib(
118 "\pDriverServicesLib", "\pAbsoluteToNanoseconds");
119 if (!gA2NS) gUpTime = nil; /* Pedantic but necessary */
120
121 if (gUpTime) {
122 /* If we loaded UpTime(), then we need to know if the system has
123 a native implementation of the Time Manager. If so, then it's
124 pointless to calculate a scale factor against the missing VIA */
125
126 /* gestaltNativeTimeMgr = 4 in some future version of the headers */
127 if (!Gestalt(gestaltTimeMgrVersion, &result) &&
128 (result > gestaltExtendedTimeMgr))
129 gNative = true;
130 }
131 else {
132 /* If no DriverServicesLib, use Gestalt() to get the processor type.
133 Only NuBus PowerMacs with old System Software won't have DSL, so
134 we know it should either be a 601 or 603. */
135
136 /* Use the processor gestalt to determine which register to use */
137 if (!Gestalt(gestaltNativeCPUtype, &result)) {
138 if (result == gestaltCPU601) gUseRTC = true;
139 else if (result > gestaltCPU601) gUseTBR = true;
140 }
141 }
142
143 /* Now calculate a scale factor to keep us accurate. */
144 if ((gUpTime && !gNative) || gUseRTC || gUseTBR) {
145 UInt64 tick, usec1, usec2;
146 UnsignedWide wide;
147
148 /* Wait for the beginning of the very next tick */
149 for(tick = MyLMGetTicks() + 1; tick > MyLMGetTicks(); );
150
151 /* Poll the selected timer and prepare it (since we have time) */
152 wide = (gUpTime) ? (*gA2NS)((*gUpTime)()) :
153 ((gUseRTC) ? PollRTC() : PollTBR());
154 usec1 = (gUseRTC) ? RTCToNano(wide) : WideTo64bit(wide);
155
156 /* Wait for the exact 60th tick to roll over */
157 while(tick + 60 > MyLMGetTicks());
158
159 /* Poll the selected timer again and prepare it */
160 wide = (gUpTime) ? (*gA2NS)((*gUpTime)()) :
161 ((gUseRTC) ? PollRTC() : PollTBR());
162 usec2 = (gUseRTC) ? RTCToNano(wide) : WideTo64bit(wide);
163
164 /* Calculate a scale value that will give microseconds per second.
165 Remember, there are actually 60.15 ticks in a second, not 60. */
166 gScaleUSec = (60.0 * 1000000.0) / ((usec2 - usec1) * 60.15);
167 gScaleMSec = gScaleUSec / 1000.0;
168 }
169
170#endif /* GENERATINGPOWERPC */
171
172 /* We've initialized our globals */
173 gInited = true;
174 }
175 }
176
177/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
178/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
179
180UInt64 FastMicroseconds() {
181 UnsignedWide wide;
182 UInt64 usec;
183
184#if GENERATINGPOWERPC
185 /* Initialize globals the first time we are called */
186 if (!gInited) FastInitialize();
187
188 if (gNative) {
189 /* Use DriverServices if it's available -- it's fast and compatible */
190 wide = (*gA2NS)((*gUpTime)());
191 usec = (double) WideTo64bit(wide) * gScaleUSec + 0.5;
192 }
193 else if (gUpTime) {
194 /* Use DriverServices if it's available -- it's fast and compatible */
195 wide = (*gA2NS)((*gUpTime)());
196 usec = (double) WideTo64bit(wide) * gScaleUSec + 0.5;
197 }
198 else if (gUseTBR) {
199 /* On a recent PowerPC, we poll the TBR directly */
200 wide = PollTBR();
201 usec = (double) WideTo64bit(wide) * gScaleUSec + 0.5;
202 }
203 else if (gUseRTC) {
204 /* On a 601, we can poll the RTC instead */
205 wide = PollRTC();
206 usec = (double) RTCToNano(wide) * gScaleUSec + 0.5;
207 }
208 else
209#endif /* GENERATINGPOWERPC */
210 {
211 /* If all else fails, suffer the mixed mode overhead */
212 Microseconds(&wide);
213 usec = WideTo64bit(wide);
214 }
215
216 return(usec);
217 }
218
219/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
220/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
221
222UInt64 FastMilliseconds() {
223 UnsignedWide wide;
224 UInt64 msec;
225
226#if GENERATINGPOWERPC
227 /* Initialize globals the first time we are called */
228 if (!gInited) FastInitialize();
229
230 if (gNative) {
231 /* Use DriverServices if it's available -- it's fast and compatible */
232 wide = (*gA2NS)((*gUpTime)());
233 msec = (double) WideTo64bit(wide) * gScaleMSec + 0.5;
234 }
235 else if (gUpTime) {
236 /* Use DriverServices if it's available -- it's fast and compatible */
237 wide = (*gA2NS)((*gUpTime)());
238 msec = (double) WideTo64bit(wide) * gScaleMSec + 0.5;
239 }
240 else if (gUseTBR) {
241 /* On a recent PowerPC, we poll the TBR directly */
242 wide = PollTBR();
243 msec = (double) WideTo64bit(wide) * gScaleMSec + 0.5;
244 }
245 else if (gUseRTC) {
246 /* On a 601, we can poll the RTC instead */
247 wide = PollRTC();
248 msec = (double) RTCToNano(wide) * gScaleMSec + 0.5;
249 }
250 else
251#endif /* GENERATINGPOWERPC */
252 {
253 /* If all else fails, suffer the mixed mode overhead */
254 Microseconds(&wide);
255 msec = ((double) WideTo64bit(wide) + 500.0) / 1000.0;
256 }
257
258 return(msec);
259 }
260
261/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
262/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
263
264StringPtr FastMethod() {
265 StringPtr method = "\p<Unknown>";
266
267#if GENERATINGPOWERPC
268 /* Initialize globals the first time we are called */
269 if (!gInited) FastInitialize();
270
271 if (gNative) {
272 /* The Time Manager and UpTime() are entirely native on this machine */
273 method = "\pNative UpTime()";
274 }
275 else if (gUpTime) {
276 /* Use DriverServices if it's available -- it's fast and compatible */
277 method = "\pUpTime()";
278 }
279 else if (gUseTBR) {
280 /* On a recent PowerPC, we poll the TBR directly */
281 method = "\pPowerPC TBR";
282 }
283 else if (gUseRTC) {
284 /* On a 601, we can poll the RTC instead */
285 method = "\pPowerPC RTC";
286 }
287 else
288#endif /* GENERATINGPOWERPC */
289 {
290 /* If all else fails, suffer the mixed mode overhead */
291 method = "\pMicroseconds()";
292 }
293
294 return(method);
295 }
296
297/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
298/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
299#pragma mark -
300
301#if GENERATINGPOWERPC
302asm static UnsignedWide PollRTC_() {
303entry PollRTC /* Avoid CodeWarrior glue */
304 machine 601
305@AGAIN:
306 mfrtcu r4 /* RTCU = SPR 4 */
307 mfrtcl r5 /* RTCL = SPR 5 */
308 mfrtcu r6
309 cmpw r4,r6
310 bne @AGAIN
311 stw r4,0(r3)
312 stw r5,4(r3)
313 blr
314 }
315
316/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
317/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
318
319asm static UnsignedWide PollTBR_() {
320entry PollTBR /* Avoid CodeWarrior glue */
321 machine 604
322@AGAIN:
323 mftbu r4 /* TBRU = SPR 268 */
324 mftb r5 /* TBRL = SPR 269 */
325 mftbu r6
326 cmpw r4,r6
327 bne @AGAIN
328 stw r4,0(r3)
329 stw r5,4(r3)
330 blr
331 }
332
333/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
334/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
335
336static Ptr FindFunctionInSharedLib(StringPtr libName, StringPtr funcName) {
337 OSErr error = noErr;
338 Str255 errorStr;
339 Ptr func = NULL;
340 Ptr entry = NULL;
341 CFragSymbolClass symClass;
342 CFragConnectionID connID;
343
344 /* Find CFM containers for the current archecture -- CFM-PPC or CFM-68K */
345 if (/* error = */ GetSharedLibrary(libName, kCompiledCFragArch,
346 kLoadCFrag, &connID, &entry, errorStr)) return(NULL);
347 if (/* error = */ FindSymbol(connID, funcName, &func, &symClass))
348 return(NULL);
349
350 return(func);
351 }
352#endif /* GENERATINGPOWERPC */
diff --git a/apps/plugins/sdl/src/timer/macos/FastTimes.h b/apps/plugins/sdl/src/timer/macos/FastTimes.h
deleted file mode 100644
index d25744c330..0000000000
--- a/apps/plugins/sdl/src/timer/macos/FastTimes.h
+++ /dev/null
@@ -1,27 +0,0 @@
1/* File "FastTimes.h" - Original code by Matt Slot <fprefect@ambrosiasw.com> */
2#include "SDL_config.h"
3/* Created 4/24/99 - This file is hereby placed in the public domain */
4/* Updated 5/21/99 - Calibrate to VIA, add TBR support, renamed functions */
5/* Updated 10/4/99 - Use AbsoluteToNanoseconds() in case Absolute = double */
6/* Updated 2/15/00 - Check for native Time Manager, no need to calibrate */
7/* Updated 3/21/00 - Fixed ns conversion, create 2 different scale factors */
8/* Updated 5/03/00 - Added copyright and placed into PD. No code changes */
9
10/* This file is Copyright (C) Matt Slot, 1999-2012. It is hereby placed into
11 the public domain. The author makes no warranty as to fitness or stability */
12
13#ifndef __FAST_TIMES_HEADER__
14#define __FAST_TIMES_HEADER__
15
16/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
17/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
18
19extern void FastInitialize(void);
20extern UInt64 FastMicroseconds(void);
21extern UInt64 FastMilliseconds(void);
22extern StringPtr FastMethod(void);
23
24/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
25/* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */
26
27#endif /* __FAST_TIMES_HEADER__ */
diff --git a/apps/plugins/sdl/src/timer/macos/SDL_MPWtimer.c b/apps/plugins/sdl/src/timer/macos/SDL_MPWtimer.c
deleted file mode 100644
index 114b6c7c0a..0000000000
--- a/apps/plugins/sdl/src/timer/macos/SDL_MPWtimer.c
+++ /dev/null
@@ -1,152 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_MACOS
25
26#include <Types.h>
27#include <Timer.h>
28#include <OSUtils.h>
29#include <Gestalt.h>
30#include <Processes.h>
31
32#include <LowMem.h>
33
34#include "SDL_timer.h"
35#include "../SDL_timer_c.h"
36
37#define MS_PER_TICK (1000/60) /* MacOS tick = 1/60 second */
38
39/* Note: This is only a step above the original 1/60s implementation.
40 * For a good implementation, see FastTimes.[ch], by Matt Slot.
41 */
42#define USE_MICROSECONDS
43#define WideTo64bit(w) (*(UInt64 *) &(w))
44
45UInt64 start;
46
47void SDL_StartTicks(void)
48{
49#ifdef USE_MICROSECONDS
50 UnsignedWide now;
51
52 Microseconds(&now);
53 start = WideTo64bit(now);
54#else
55 /* FIXME: Should we implement a wrapping algorithm, like Win32? */
56#endif
57}
58
59Uint32 SDL_GetTicks(void)
60{
61#ifdef USE_MICROSECONDS
62 UnsignedWide now;
63
64 Microseconds(&now);
65 return (Uint32)((WideTo64bit(now)-start)/1000);
66#else
67 return(LMGetTicks()*MS_PER_TICK);
68#endif
69}
70
71void SDL_Delay(Uint32 ms)
72{
73#ifdef USE_MICROSECONDS
74 Uint32 end_ms;
75
76 end_ms = SDL_GetTicks() + ms;
77 do {
78 /* FIXME: Yield CPU? */ ;
79 } while ( SDL_GetTicks() < end_ms );
80#else
81 UInt32 unused; /* MJS */
82 Delay(ms/MS_PER_TICK, &unused);
83#endif
84}
85
86
87/* Data to handle a single periodic alarm */
88typedef struct _ExtendedTimerRec
89{
90 TMTask tmTask;
91 ProcessSerialNumber taskPSN;
92} ExtendedTimerRec, *ExtendedTimerPtr;
93
94static ExtendedTimerRec gExtendedTimerRec;
95
96
97int SDL_SYS_TimerInit(void)
98{
99 /* We don't need a setup? */
100 return(0);
101}
102
103void SDL_SYS_TimerQuit(void)
104{
105 /* We don't need a cleanup? */
106 return;
107}
108
109/* Our Stub routine to set up and then call the real routine. */
110pascal void TimerCallbackProc(TMTaskPtr tmTaskPtr)
111{
112 Uint32 ms;
113
114 WakeUpProcess(&((ExtendedTimerPtr) tmTaskPtr)->taskPSN);
115
116 ms = SDL_alarm_callback(SDL_alarm_interval);
117 if ( ms ) {
118 SDL_alarm_interval = ROUND_RESOLUTION(ms);
119 PrimeTime((QElemPtr)&gExtendedTimerRec.tmTask,
120 SDL_alarm_interval);
121 } else {
122 SDL_alarm_interval = 0;
123 }
124}
125
126int SDL_SYS_StartTimer(void)
127{
128 /*
129 * Configure the global structure that stores the timing information.
130 */
131 gExtendedTimerRec.tmTask.qLink = NULL;
132 gExtendedTimerRec.tmTask.qType = 0;
133 gExtendedTimerRec.tmTask.tmAddr = NewTimerUPP(TimerCallbackProc);
134 gExtendedTimerRec.tmTask.tmCount = 0;
135 gExtendedTimerRec.tmTask.tmWakeUp = 0;
136 gExtendedTimerRec.tmTask.tmReserved = 0;
137 GetCurrentProcess(&gExtendedTimerRec.taskPSN);
138
139 /* Install the task record */
140 InsXTime((QElemPtr)&gExtendedTimerRec.tmTask);
141
142 /* Go! */
143 PrimeTime((QElemPtr)&gExtendedTimerRec.tmTask, SDL_alarm_interval);
144 return(0);
145}
146
147void SDL_SYS_StopTimer(void)
148{
149 RmvTime((QElemPtr)&gExtendedTimerRec.tmTask);
150}
151
152#endif /* SDL_TIMER_MACOS */
diff --git a/apps/plugins/sdl/src/timer/macos/SDL_systimer.c b/apps/plugins/sdl/src/timer/macos/SDL_systimer.c
deleted file mode 100644
index 7a8063e57d..0000000000
--- a/apps/plugins/sdl/src/timer/macos/SDL_systimer.c
+++ /dev/null
@@ -1,186 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_MACOS
25
26#include <Types.h>
27#include <Timer.h>
28#include <OSUtils.h>
29#include <Gestalt.h>
30#include <Processes.h>
31
32#include <LowMem.h>
33
34#include "SDL_timer.h"
35#include "../SDL_timer_c.h"
36
37#include "FastTimes.h"
38
39#if TARGET_API_MAC_CARBON
40#define NewTimerProc NewTimerUPP
41#endif
42
43#define MS_PER_TICK (1000.0/60.0) /* MacOS tick = 1/60 second */
44
45
46#define kTwoPower32 (4294967296.0) /* 2^32 */
47
48static double start_tick;
49static int is_fast_inited = 0;
50
51void SDL_StartTicks(void)
52{
53 if ( ! is_fast_inited ) // important to check or FastTime may hang machine!
54 SDL_SYS_TimerInit();
55
56 start_tick = FastMicroseconds();
57}
58
59Uint32 SDL_GetTicks(void)
60{
61
62 if ( ! is_fast_inited )
63 SDL_SYS_TimerInit();
64
65 return FastMilliseconds();
66}
67
68void SDL_Delay(Uint32 ms)
69{
70 Uint32 stop, now;
71
72 stop = SDL_GetTicks() + ms;
73 do {
74 #if TARGET_API_MAC_CARBON
75 MPYield();
76 #else
77 SystemTask();
78 #endif
79
80 now = SDL_GetTicks();
81
82 } while ( stop > now );
83}
84
85/*
86void SDL_StartTicks(void)
87{
88 // FIXME: Should we implement a wrapping algorithm, like Win32?
89}
90
91Uint32 SDL_GetTicks(void)
92{
93 UnsignedWide ms;
94
95 Microseconds (&ms);
96
97 return ( ms.lo / 1000 );
98}
99
100void SDL_Delay(Uint32 ms)
101{
102
103 UnsignedWide microsecs;
104 UInt32 stop;
105
106 Microseconds (&microsecs);
107
108 stop = microsecs.lo + (ms * 1000);
109
110 while ( stop > microsecs.lo ) {
111
112 SystemTask ();
113
114 Microseconds (&microsecs);
115 }
116
117}*/
118
119/* Data to handle a single periodic alarm */
120typedef struct _ExtendedTimerRec
121{
122 TMTask tmTask;
123 ProcessSerialNumber taskPSN;
124} ExtendedTimerRec, *ExtendedTimerPtr;
125
126static ExtendedTimerRec gExtendedTimerRec;
127
128
129int SDL_SYS_TimerInit(void)
130{
131 FastInitialize ();
132 is_fast_inited = 1;
133
134 return(0);
135}
136
137void SDL_SYS_TimerQuit(void)
138{
139 /* We don't need a cleanup? */
140 return;
141}
142
143/* Our Stub routine to set up and then call the real routine. */
144pascal void TimerCallbackProc(TMTaskPtr tmTaskPtr)
145{
146 Uint32 ms;
147
148 WakeUpProcess(&((ExtendedTimerPtr) tmTaskPtr)->taskPSN);
149
150 ms = SDL_alarm_callback(SDL_alarm_interval);
151 if ( ms ) {
152 SDL_alarm_interval = ROUND_RESOLUTION(ms);
153 PrimeTime((QElemPtr)&gExtendedTimerRec.tmTask,
154 SDL_alarm_interval);
155 } else {
156 SDL_alarm_interval = 0;
157 }
158}
159
160int SDL_SYS_StartTimer(void)
161{
162 /*
163 * Configure the global structure that stores the timing information.
164 */
165 gExtendedTimerRec.tmTask.qLink = NULL;
166 gExtendedTimerRec.tmTask.qType = 0;
167 gExtendedTimerRec.tmTask.tmAddr = NewTimerProc(TimerCallbackProc);
168 gExtendedTimerRec.tmTask.tmCount = 0;
169 gExtendedTimerRec.tmTask.tmWakeUp = 0;
170 gExtendedTimerRec.tmTask.tmReserved = 0;
171 GetCurrentProcess(&gExtendedTimerRec.taskPSN);
172
173 /* Install the task record */
174 InsXTime((QElemPtr)&gExtendedTimerRec.tmTask);
175
176 /* Go! */
177 PrimeTime((QElemPtr)&gExtendedTimerRec.tmTask, SDL_alarm_interval);
178 return(0);
179}
180
181void SDL_SYS_StopTimer(void)
182{
183 RmvTime((QElemPtr)&gExtendedTimerRec.tmTask);
184}
185
186#endif /* SDL_TIMER_MACOS */
diff --git a/apps/plugins/sdl/src/timer/mint/SDL_systimer.c b/apps/plugins/sdl/src/timer/mint/SDL_systimer.c
deleted file mode 100644
index 01e7a410c1..0000000000
--- a/apps/plugins/sdl/src/timer/mint/SDL_systimer.c
+++ /dev/null
@@ -1,149 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_MINT
25
26/*
27 * TOS/MiNT timer driver
28 * based on vbl vector
29 *
30 * Patrice Mandin
31 */
32
33#include <stdio.h>
34#include <sys/time.h>
35#include <signal.h>
36#include <unistd.h>
37#include <string.h>
38#include <errno.h>
39
40#include <mint/cookie.h>
41#include <mint/sysvars.h>
42#include <mint/osbind.h>
43#include <mint/mintbind.h>
44
45#include "SDL_timer.h"
46#include "../SDL_timer_c.h"
47#include "SDL_thread.h"
48
49#include "../../video/ataricommon/SDL_atarisuper.h"
50
51#include "SDL_vbltimer_s.h"
52
53/* from audio/mint */
54void SDL_MintAudio_CheckFpu(void);
55
56/* The first ticks value of the application */
57static Uint32 start;
58static SDL_bool read_hz200_from_vbl = SDL_FALSE;
59static int mint_present; /* can we use Syield() ? */
60
61void SDL_StartTicks(void)
62{
63 void *old_stack;
64 long dummy;
65
66 /* Set first ticks value */
67 old_stack = (void *)Super(0);
68 start = *((volatile long *)_hz_200);
69 SuperToUser(old_stack);
70
71 start *= 5; /* One _hz_200 tic is 5ms */
72
73 mint_present = (Getcookie(C_MiNT, &dummy) == C_FOUND);
74}
75
76Uint32 SDL_GetTicks (void)
77{
78 Uint32 now = start;
79
80 if (read_hz200_from_vbl) {
81 now = SDL_Atari_hz200;
82 } else {
83 void *old_stack = (void *)Super(0);
84 now = *((volatile long *)_hz_200);
85 SuperToUser(old_stack);
86 }
87
88 return((now*5)-start);
89}
90
91void SDL_Delay (Uint32 ms)
92{
93 Uint32 now;
94
95 now = SDL_GetTicks();
96 while ((SDL_GetTicks()-now)<ms){
97 if (mint_present) {
98 Syield();
99 }
100 }
101}
102
103/* Data to handle a single periodic alarm */
104static SDL_bool timer_installed=SDL_FALSE;
105
106/* This is only called if the event thread is not running */
107int SDL_SYS_TimerInit(void)
108{
109 void *old_stack;
110
111 SDL_MintAudio_CheckFpu();
112
113 /* Install RunTimer in vbl vector */
114 old_stack = (void *)Super(0);
115 timer_installed = !SDL_AtariVblInstall(SDL_ThreadedTimerCheck);
116 SuperToUser(old_stack);
117
118 if (!timer_installed) {
119 return(-1);
120 }
121
122 read_hz200_from_vbl = SDL_TRUE;
123 return(SDL_SetTimerThreaded(0));
124}
125
126void SDL_SYS_TimerQuit(void)
127{
128 /* Uninstall RunTimer vbl vector */
129 if (timer_installed) {
130 void *old_stack = (void *)Super(0);
131 SDL_AtariVblUninstall(SDL_ThreadedTimerCheck);
132 SuperToUser(old_stack);
133 timer_installed = SDL_FALSE;
134 }
135 read_hz200_from_vbl = SDL_FALSE;
136}
137
138int SDL_SYS_StartTimer(void)
139{
140 SDL_SetError("Internal logic error: MiNT uses vbl timer");
141 return(-1);
142}
143
144void SDL_SYS_StopTimer(void)
145{
146 return;
147}
148
149#endif /* SDL_TIMER_MINT */
diff --git a/apps/plugins/sdl/src/timer/mint/SDL_vbltimer.S b/apps/plugins/sdl/src/timer/mint/SDL_vbltimer.S
deleted file mode 100644
index 7837afce08..0000000000
--- a/apps/plugins/sdl/src/timer/mint/SDL_vbltimer.S
+++ /dev/null
@@ -1,228 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/*
24 * VBL queue routine
25 *
26 * Patrice Mandin
27 */
28
29#define _vbl_queue 0x456
30#define _hz_200 0x4ba
31
32 .text
33
34 .globl _SDL_AtariVblInstall
35 .globl _SDL_AtariVblUninstall
36
37 .globl _SDL_MintAudio_hasfpu
38
39/*--- Save/restore FPU context ---*/
40
41#if defined(__mcoldfire__)
42
43#define SAVE_FPU_CONTEXT \
44 lea sp@(-216),sp; \
45 fsave sp@; \
46 fmovel fpiar,sp@-; \
47 lea sp@(-64),sp; \
48 fmovemd fp0-fp7,sp@
49
50#define RESTORE_FPU_CONTEXT \
51 fmovemd sp@,fp0-fp7; \
52 lea sp@(64),sp; \
53 fmovel sp@+,fpiar; \
54 frestore sp@; \
55 lea sp@(216),sp
56
57#else
58
59#define SAVE_FPU_CONTEXT \
60 .chip 68k/68881; \
61 fsave sp@-; \
62 fmoveml fpcr/fpsr/fpiar,sp@-; \
63 fmovemx fp0-fp7,sp@-; \
64 .chip 68k
65
66#define RESTORE_FPU_CONTEXT \
67 .chip 68k/68881; \
68 fmovemx sp@+,fp0-fp7; \
69 fmoveml sp@+,fpcr/fpsr/fpiar; \
70 frestore sp@+; \
71 .chip 68k
72
73#endif
74
75/*--- Vector installer ---*/
76
77_SDL_AtariVblInstall:
78#if defined(__mcoldfire__)
79 movel sp@(4),d0
80 movel d0,my_vector
81#else
82 movel sp@(4),my_vector
83#endif
84
85 lea _my_vbl,a0
86
87 clrw vbl_mutex
88#if defined(__mcoldfire__)
89 movel _hz_200.w,d0
90 movel d0, _SDL_Atari_hz200
91#else
92 movel _hz_200.w, _SDL_Atari_hz200
93#endif
94
95 /* Stop interrupts */
96
97 movew #0x2700,sr
98
99 /* Read vbl_queue pointer */
100 movel _vbl_queue.w,a1
101
102 /* Search a free place */
103 moveq #7,d0
104bcl_search_place:
105 movel (a1),d1
106 beqs place_found
107 addql #4,a1
108#if defined(__mcoldfire__)
109 subql #1,d0
110 bpls bcl_search_place
111#else
112 dbra d0,bcl_search_place
113#endif
114
115 /* Not found */
116 moveq #1,d0
117 bras exit_vbl_queue
118
119 /* Then install ourselves */
120place_found:
121 movel a0,(a1)
122 moveq #0,d0
123
124exit_vbl_queue:
125 /* Restart interrupts */
126 movew #0x2300,sr
127
128 rts
129
130/*--- Vector uninstaller ---*/
131
132_SDL_AtariVblUninstall:
133 movel sp@(4),d0
134 cmpl my_vector,d0
135 bnes badvector
136
137 movel #_my_vbl,d0
138
139 /* Stop interrupts */
140
141 movew #0x2700,sr
142
143 /* Read vbl_queue pointer */
144 movel _vbl_queue.w,a1
145
146 /* Search where we are */
147 moveq #7,d1
148bcl2_search_place:
149 cmpl (a1),d0
150 bnes next_place
151 clrl (a1)
152 moveq #0,d1
153next_place:
154 addql #4,a1
155#if defined(__mcoldfire__)
156 subql #1,d1
157 bpls bcl_search_place
158#else
159 dbra d1,bcl2_search_place
160#endif
161
162 /* Restart interrupts */
163 movew #0x2300,sr
164badvector:
165 rts
166
167/*--- Our vbl ---*/
168
169_my_vbl:
170#if defined(__mcoldfire__)
171 lea sp@(-60),sp
172 moveml d0-d7/a0-a6,sp@
173#else
174 moveml d0-d7/a0-a6,sp@-
175#endif
176
177 /* Update _hz_200 */
178#if defined(__mcoldfire__)
179 movel _hz_200.w,d0
180 movel d0, _SDL_Atari_hz200
181#else
182 movel _hz_200.w, _SDL_Atari_hz200
183#endif
184
185 /* Verify if this is not already running */
186
187 tstw vbl_mutex
188 bnes vbl_end
189#if defined(__mcoldfire__)
190 movew vbl_mutex,d0
191 notl d0
192 movew d0,vbl_mutex
193#else
194 notw vbl_mutex
195#endif
196
197 /* Save FPU if needed */
198 tstw _SDL_MintAudio_hasfpu
199 beqs SDL_AtariVbl_nofpu1
200 SAVE_FPU_CONTEXT
201SDL_AtariVbl_nofpu1:
202
203 movel my_vector,a0
204 jsr a0@
205
206 /* Restore FPU if needed */
207 tstw _SDL_MintAudio_hasfpu
208 beqs SDL_AtariVbl_Xbios_nofpu2
209 RESTORE_FPU_CONTEXT
210SDL_AtariVbl_Xbios_nofpu2:
211
212 clrw vbl_mutex
213vbl_end:
214#if defined(__mcoldfire__)
215 moveml sp@,d0-d7/a0-a6
216 lea sp@(60),sp
217#else
218 moveml sp@+,d0-d7/a0-a6
219#endif
220 rts
221
222 .data
223 .even
224 .comm _SDL_Atari_hz200,4*1
225 .even
226 .comm vbl_mutex,2*1
227 .even
228 .comm my_vector,4*1
diff --git a/apps/plugins/sdl/src/timer/mint/SDL_vbltimer_s.h b/apps/plugins/sdl/src/timer/mint/SDL_vbltimer_s.h
deleted file mode 100644
index 011c138ddb..0000000000
--- a/apps/plugins/sdl/src/timer/mint/SDL_vbltimer_s.h
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * TOS/MiNT timer driver
26 * based on vbl vector
27 *
28 * Patrice Mandin
29 */
30
31extern volatile long SDL_Atari_hz200;
32
33/* Functions prototypes */
34extern int SDL_AtariVblInstall(void *newvector);
35extern void SDL_AtariVblUninstall(void *newvector);
diff --git a/apps/plugins/sdl/src/timer/nds/SDL_systimer.c b/apps/plugins/sdl/src/timer/nds/SDL_systimer.c
deleted file mode 100644
index bf54f42b85..0000000000
--- a/apps/plugins/sdl/src/timer/nds/SDL_systimer.c
+++ /dev/null
@@ -1,73 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_thread.h"
25#include "SDL_timer.h"
26#include "SDL_error.h"
27#include "../SDL_timer_c.h"
28
29#include <nds.h>
30
31#define timers2ms(tlow,thigh)(tlow | (thigh<<16)) >> 5
32
33
34void SDL_StartTicks(void)
35{
36 TIMER0_DATA=0;
37 TIMER1_DATA=0;
38 TIMER0_CR=TIMER_ENABLE|TIMER_DIV_1024;
39 TIMER1_CR=TIMER_ENABLE|TIMER_CASCADE;
40}
41
42Uint32 SDL_GetTicks(void)
43{
44 return timers2ms(TIMER0_DATA, TIMER1_DATA);
45}
46
47void SDL_Delay(Uint32 ms)
48{
49 Uint32 now;
50 now=timers2ms(TIMER0_DATA, TIMER1_DATA);
51 while((Uint32)timers2ms(TIMER0_DATA, TIMER1_DATA)<now+ms);
52
53}
54
55/* This is only called if the event thread is not running */
56int SDL_SYS_TimerInit(void)
57{
58 return 0;
59}
60
61void SDL_SYS_TimerQuit(void)
62{
63}
64
65int SDL_SYS_StartTimer(void)
66{
67 SDL_SetError("Timers not implemented on NDS");
68 return -1;
69}
70
71void SDL_SYS_StopTimer(void)
72{
73}
diff --git a/apps/plugins/sdl/src/timer/os2/SDL_systimer.c b/apps/plugins/sdl/src/timer/os2/SDL_systimer.c
deleted file mode 100644
index c82d53146d..0000000000
--- a/apps/plugins/sdl/src/timer/os2/SDL_systimer.c
+++ /dev/null
@@ -1,227 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_OS2
25
26#define INCL_DOSMISC
27#define INCL_DOSERRORS
28#define INCL_DOSSEMAPHORES
29#define INCL_DOSDATETIME
30#define INCL_DOSPROCESS
31#define INCL_DOSPROFILE
32#define INCL_DOSEXCEPTIONS
33#include <os2.h>
34
35#include "SDL_thread.h"
36#include "SDL_timer.h"
37#include "../SDL_timer_c.h"
38
39
40#define TIME_WRAP_VALUE (~(DWORD)0)
41
42/* The first high-resolution ticks value of the application */
43static long long hires_start_ticks;
44/* The number of ticks per second of the high-resolution performance counter */
45static ULONG hires_ticks_per_second;
46
47void SDL_StartTicks(void)
48{
49 DosTmrQueryFreq(&hires_ticks_per_second);
50 DosTmrQueryTime((PQWORD)&hires_start_ticks);
51}
52
53DECLSPEC Uint32 SDLCALL SDL_GetTicks(void)
54{
55 long long hires_now;
56 ULONG ticks = ticks;
57
58 DosTmrQueryTime((PQWORD)&hires_now);
59/*
60 hires_now -= hires_start_ticks;
61 hires_now *= 1000;
62 hires_now /= hires_ticks_per_second;
63*/
64 /* inline asm to avoid runtime inclusion */
65 _asm {
66 push edx
67 push eax
68 mov eax, dword ptr hires_now
69 mov edx, dword ptr hires_now+4
70 sub eax, dword ptr hires_start_ticks
71 sbb edx, dword ptr hires_start_ticks+4
72 mov ebx,1000
73 mov ecx,edx
74 mul ebx
75 push eax
76 push edx
77 mov eax,ecx
78 mul ebx
79 pop eax
80 add edx,eax
81 pop eax
82 mov ebx, dword ptr hires_ticks_per_second
83 div ebx
84 mov dword ptr ticks, eax
85 pop edx
86 pop eax
87 }
88
89 return ticks;
90
91}
92
93/* High resolution sleep, originally made by Ilya Zakharevich */
94DECLSPEC void SDLCALL SDL_Delay(Uint32 ms)
95{
96 /* This is similar to DosSleep(), but has 8ms granularity in time-critical
97 threads even on Warp3. */
98 HEV hevEvent1 = 0; /* Event semaphore handle */
99 HTIMER htimerEvent1 = 0; /* Timer handle */
100 APIRET rc = NO_ERROR; /* Return code */
101 int ret = 1;
102 ULONG priority = 0, nesting; /* Shut down the warnings */
103 PPIB pib;
104 PTIB tib;
105 char *e = NULL;
106 APIRET badrc;
107 int switch_priority = 50;
108
109 DosCreateEventSem(NULL, /* Unnamed */
110 &hevEvent1, /* Handle of semaphore returned */
111 DC_SEM_SHARED, /* Shared needed for DosAsyncTimer */
112 FALSE); /* Semaphore is in RESET state */
113
114 if (ms >= switch_priority)
115 switch_priority = 0;
116 if (switch_priority)
117 {
118 if (DosGetInfoBlocks(&tib, &pib)!=NO_ERROR)
119 switch_priority = 0;
120 else
121 {
122 /* In Warp3, to switch scheduling to 8ms step, one needs to do
123 DosAsyncTimer() in time-critical thread. On laters versions,
124 more and more cases of wait-for-something are covered.
125
126 It turns out that on Warp3fp42 it is the priority at the time
127 of DosAsyncTimer() which matters. Let's hope that this works
128 with later versions too... XXXX
129 */
130 priority = (tib->tib_ptib2->tib2_ulpri);
131 if ((priority & 0xFF00) == 0x0300) /* already time-critical */
132 switch_priority = 0;
133 /* Make us time-critical. Just modifying TIB is not enough... */
134 /* tib->tib_ptib2->tib2_ulpri = 0x0300;*/
135 /* We do not want to run at high priority if a signal causes us
136 to longjmp() out of this section... */
137 if (DosEnterMustComplete(&nesting))
138 switch_priority = 0;
139 else
140 DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, 0);
141 }
142 }
143
144 if ((badrc = DosAsyncTimer(ms,
145 (HSEM) hevEvent1, /* Semaphore to post */
146 &htimerEvent1))) /* Timer handler (returned) */
147 e = "DosAsyncTimer";
148
149 if (switch_priority && tib->tib_ptib2->tib2_ulpri == 0x0300)
150 {
151 /* Nobody switched priority while we slept... Ignore errors... */
152 /* tib->tib_ptib2->tib2_ulpri = priority; */ /* Get back... */
153 if (!(rc = DosSetPriority(PRTYS_THREAD, (priority>>8) & 0xFF, 0, 0)))
154 rc = DosSetPriority(PRTYS_THREAD, 0, priority & 0xFF, 0);
155 }
156 if (switch_priority)
157 rc = DosExitMustComplete(&nesting); /* Ignore errors */
158
159 /* The actual blocking call is made with "normal" priority. This way we
160 should not bother with DosSleep(0) etc. to compensate for us interrupting
161 higher-priority threads. The goal is to prohibit the system spending too
162 much time halt()ing, not to run us "no matter what". */
163 if (!e) /* Wait for AsyncTimer event */
164 badrc = DosWaitEventSem(hevEvent1, SEM_INDEFINITE_WAIT);
165
166 if (e) ; /* Do nothing */
167 else if (badrc == ERROR_INTERRUPT)
168 ret = 0;
169 else if (badrc)
170 e = "DosWaitEventSem";
171 if ((rc = DosCloseEventSem(hevEvent1)) && !e) { /* Get rid of semaphore */
172 e = "DosCloseEventSem";
173 badrc = rc;
174 }
175 if (e)
176 {
177 SDL_SetError("[SDL_Delay] : Had error in %s(), rc is 0x%x\n", e, badrc);
178 }
179}
180
181/* Data to handle a single periodic alarm */
182static int timer_alive = 0;
183static SDL_Thread *timer = NULL;
184
185static int SDLCALL RunTimer(void *unused)
186{
187 DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, 0);
188 while ( timer_alive ) {
189 if ( SDL_timer_running ) {
190 SDL_ThreadedTimerCheck();
191 }
192 SDL_Delay(10);
193 }
194 return(0);
195}
196
197/* This is only called if the event thread is not running */
198int SDL_SYS_TimerInit(void)
199{
200 timer_alive = 1;
201 timer = SDL_CreateThread(RunTimer, NULL);
202 if ( timer == NULL )
203 return(-1);
204 return(SDL_SetTimerThreaded(1));
205}
206
207void SDL_SYS_TimerQuit(void)
208{
209 timer_alive = 0;
210 if ( timer ) {
211 SDL_WaitThread(timer, NULL);
212 timer = NULL;
213 }
214}
215
216int SDL_SYS_StartTimer(void)
217{
218 SDL_SetError("Internal logic error: OS/2 uses threaded timer");
219 return(-1);
220}
221
222void SDL_SYS_StopTimer(void)
223{
224 return;
225}
226
227#endif /* SDL_TIMER_OS2 */
diff --git a/apps/plugins/sdl/src/timer/riscos/SDL_systimer.c b/apps/plugins/sdl/src/timer/riscos/SDL_systimer.c
deleted file mode 100644
index 25ba65f784..0000000000
--- a/apps/plugins/sdl/src/timer/riscos/SDL_systimer.c
+++ /dev/null
@@ -1,233 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_RISCOS
25
26#include <stdio.h>
27#include <time.h>
28#include <sys/time.h>
29#include <unistd.h>
30#include <string.h>
31#include <errno.h>
32
33#include "SDL_timer.h"
34#include "../SDL_timer_c.h"
35
36#if SDL_THREADS_DISABLED
37/* Timer SDL_arraysize(Timer ),start/reset time */
38static Uint32 timerStart;
39/* Timer running function */
40void RISCOS_CheckTimer();
41#else
42#include <pthread.h>
43extern Uint32 riscos_main_thread;
44extern int riscos_using_threads;
45extern Uint32 SDL_ThreadID();
46extern Uint32 SDL_EventThreadID(void);
47#endif
48
49
50extern void RISCOS_BackgroundTasks(void);
51
52/* The first ticks value of the application */
53clock_t start;
54
55void SDL_StartTicks(void)
56{
57 /* Set first ticks value */
58 start = clock();
59}
60
61Uint32 SDL_GetTicks (void)
62{
63 clock_t ticks;
64
65 ticks=clock()-start;
66
67
68#if CLOCKS_PER_SEC == 1000
69
70 return(ticks);
71
72#elif CLOCKS_PER_SEC == 100
73
74 return (ticks * 10);
75
76#else
77
78 return ticks*(1000/CLOCKS_PER_SEC);
79
80#endif
81
82}
83
84void SDL_Delay (Uint32 ms)
85{
86 Uint32 now,then,elapsed;
87#if !SDL_THREADS_DISABLED
88 int is_event_thread;
89 if (riscos_using_threads)
90 {
91 is_event_thread = 0;
92 if (SDL_EventThreadID())
93 {
94 if (SDL_EventThreadID() == SDL_ThreadID()) is_event_thread = 1;
95 } else if (SDL_ThreadID() == riscos_main_thread) is_event_thread = 1;
96 } else is_event_thread = 1;
97#endif
98
99 /*TODO: Next version of Unixlib may allow us to use usleep here */
100 /* for non event threads */
101
102 /* Set the timeout interval - Linux only needs to do this once */
103 then = SDL_GetTicks();
104
105 do {
106 /* Do background tasks required while sleeping as we are not multithreaded */
107#if SDL_THREADS_DISABLED
108 RISCOS_BackgroundTasks();
109#else
110 /* For threaded build only run background tasks in event thread */
111 if (is_event_thread) RISCOS_BackgroundTasks();
112#endif
113
114 /* Calculate the time interval left (in case of interrupt) */
115 now = SDL_GetTicks();
116 elapsed = (now-then);
117 then = now;
118 if ( elapsed >= ms ) {
119 break;
120 }
121 ms -= elapsed;
122#if !SDL_THREADS_DISABLED
123 /* Need to yield to let other threads have a go */
124 if (riscos_using_threads) pthread_yield();
125#endif
126
127 } while ( 1 );
128}
129
130#if SDL_THREADS_DISABLED
131
132/* Non-threaded version of timer */
133
134int SDL_SYS_TimerInit(void)
135{
136 return(0);
137}
138
139void SDL_SYS_TimerQuit(void)
140{
141 SDL_SetTimer(0, NULL);
142}
143
144int SDL_SYS_StartTimer(void)
145{
146 timerStart = SDL_GetTicks();
147
148 return(0);
149}
150
151void SDL_SYS_StopTimer(void)
152{
153 /* Don't need to do anything as we use SDL_timer_running
154 to detect if we need to check the timer */
155}
156
157
158void RISCOS_CheckTimer()
159{
160 if (SDL_timer_running && SDL_GetTicks() - timerStart >= SDL_alarm_interval)
161 {
162 Uint32 ms;
163
164 ms = SDL_alarm_callback(SDL_alarm_interval);
165 if ( ms != SDL_alarm_interval )
166 {
167 if ( ms )
168 {
169 SDL_alarm_interval = ROUND_RESOLUTION(ms);
170 } else
171 {
172 SDL_alarm_interval = 0;
173 SDL_timer_running = 0;
174 }
175 }
176 if (SDL_alarm_interval) timerStart = SDL_GetTicks();
177 }
178}
179
180#else
181
182/* Threaded version of timer - based on code for linux */
183
184#include "SDL_thread.h"
185
186/* Data to handle a single periodic alarm */
187static int timer_alive = 0;
188static SDL_Thread *timer = NULL;
189
190static int RunTimer(void *unused)
191{
192 while ( timer_alive ) {
193 if ( SDL_timer_running ) {
194 SDL_ThreadedTimerCheck();
195 }
196 SDL_Delay(1);
197 }
198 return(0);
199}
200
201/* This is only called if the event thread is not running */
202int SDL_SYS_TimerInit(void)
203{
204 timer_alive = 1;
205 timer = SDL_CreateThread(RunTimer, NULL);
206 if ( timer == NULL )
207 return(-1);
208 return(SDL_SetTimerThreaded(1));
209}
210
211void SDL_SYS_TimerQuit(void)
212{
213 timer_alive = 0;
214 if ( timer ) {
215 SDL_WaitThread(timer, NULL);
216 timer = NULL;
217 }
218}
219
220int SDL_SYS_StartTimer(void)
221{
222 SDL_SetError("Internal logic error: RISC OS uses threaded timer");
223 return(-1);
224}
225
226void SDL_SYS_StopTimer(void)
227{
228 return;
229}
230
231#endif /* SDL_THREADS_DISABLED */
232
233#endif /* SDL_TIMER_RISCOS */
diff --git a/apps/plugins/sdl/src/timer/symbian/SDL_systimer.cpp b/apps/plugins/sdl/src/timer/symbian/SDL_systimer.cpp
deleted file mode 100644
index a5bb749cac..0000000000
--- a/apps/plugins/sdl/src/timer/symbian/SDL_systimer.cpp
+++ /dev/null
@@ -1,114 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_systimer.cpp
25
26 Epoc version by Hannu Viitala (hannu.j.viitala@mbnet.fi)
27 Markus Mertama
28*/
29
30#include <e32std.h>
31#include <e32hal.h>
32
33extern "C" {
34#include "SDL_error.h"
35#include "SDL_thread.h"
36#include "SDL_timer.h"
37#include "SDL_timer_c.h"
38
39static TUint start = 0;
40static TInt tickPeriodMilliSeconds;
41
42
43void SDL_StartTicks(void)
44 {
45 /* Set first ticks value */
46 start = User::TickCount();
47
48 TTimeIntervalMicroSeconds32 period;
49 TInt tmp = UserHal::TickPeriod(period);
50 tickPeriodMilliSeconds = period.Int() / 1000;
51 }
52
53Uint32 SDL_GetTicks(void)
54 {
55 TUint deltaTics = User::TickCount() - start;
56 return(deltaTics * tickPeriodMilliSeconds);
57 }
58
59void SDL_Delay(Uint32 ms)
60 {
61 User::After(TTimeIntervalMicroSeconds32(ms*1000));
62 }
63
64/* Data to handle a single periodic alarm */
65static int timer_alive = 0;
66static SDL_Thread *timer = NULL;
67
68static int RunTimer(void *unused)
69 {
70 while ( timer_alive )
71 {
72 if (SDL_timer_running)
73 {
74 SDL_ThreadedTimerCheck();
75 }
76 SDL_Delay(10);
77 }
78 return(0);
79 }
80
81/* This is only called if the event thread is not running */
82int SDL_SYS_TimerInit(void)
83 {
84 if(timer != NULL)
85 return (-1);
86 timer_alive = 1;
87 timer = SDL_CreateThread(RunTimer, NULL);
88 if ( timer == NULL )
89 return(-1);
90 return(SDL_SetTimerThreaded(1));
91 }
92
93void SDL_SYS_TimerQuit(void)
94 {
95 timer_alive = 0;
96 if ( timer )
97 {
98 SDL_WaitThread(timer, NULL);
99 timer = NULL;
100 }
101 }
102
103int SDL_SYS_StartTimer(void)
104 {
105 SDL_SetError("Internal logic error: Epoc uses threaded timer");
106 return(-1);
107 }
108
109void SDL_SYS_StopTimer(void)
110 {
111 return;
112 }
113
114} // extern "C"
diff --git a/apps/plugins/sdl/src/timer/unix/SDL_systimer.c b/apps/plugins/sdl/src/timer/unix/SDL_systimer.c
deleted file mode 100644
index 80b22283b6..0000000000
--- a/apps/plugins/sdl/src/timer/unix/SDL_systimer.c
+++ /dev/null
@@ -1,240 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_UNIX
25
26#include <stdio.h>
27#include <sys/time.h>
28#include <signal.h>
29#include <unistd.h>
30#include <string.h>
31#include <errno.h>
32
33#include "SDL_timer.h"
34#include "../SDL_timer_c.h"
35
36/* The clock_gettime provides monotonous time, so we should use it if
37 it's available. The clock_gettime function is behind ifdef
38 for __USE_POSIX199309
39 Tommi Kyntola (tommi.kyntola@ray.fi) 27/09/2005
40*/
41#if HAVE_NANOSLEEP || HAVE_CLOCK_GETTIME
42#include <time.h>
43#endif
44
45#if SDL_THREAD_PTH
46#include <pth.h>
47#endif
48
49#if SDL_THREADS_DISABLED
50#define USE_ITIMER
51#endif
52
53/* The first ticks value of the application */
54#ifdef HAVE_CLOCK_GETTIME
55static struct timespec start;
56#else
57static struct timeval start;
58#endif /* HAVE_CLOCK_GETTIME */
59
60
61void SDL_StartTicks(void)
62{
63 /* Set first ticks value */
64#if HAVE_CLOCK_GETTIME
65 clock_gettime(CLOCK_MONOTONIC,&start);
66#else
67 gettimeofday(&start, NULL);
68#endif
69}
70
71Uint32 SDL_GetTicks (void)
72{
73#if HAVE_CLOCK_GETTIME
74 Uint32 ticks;
75 struct timespec now;
76 clock_gettime(CLOCK_MONOTONIC,&now);
77 ticks=(now.tv_sec-start.tv_sec)*1000+(now.tv_nsec-start.tv_nsec)/1000000;
78 return(ticks);
79#else
80 Uint32 ticks;
81 struct timeval now;
82 gettimeofday(&now, NULL);
83 ticks=(now.tv_sec-start.tv_sec)*1000+(now.tv_usec-start.tv_usec)/1000;
84 return(ticks);
85#endif
86}
87
88void SDL_Delay (Uint32 ms)
89{
90#if SDL_THREAD_PTH
91 pth_time_t tv;
92 tv.tv_sec = ms/1000;
93 tv.tv_usec = (ms%1000)*1000;
94 pth_nap(tv);
95#else
96 int was_error;
97
98#if HAVE_NANOSLEEP
99 struct timespec elapsed, tv;
100#else
101 struct timeval tv;
102 Uint32 then, now, elapsed;
103#endif
104
105 /* Set the timeout interval */
106#if HAVE_NANOSLEEP
107 elapsed.tv_sec = ms/1000;
108 elapsed.tv_nsec = (ms%1000)*1000000;
109#else
110 then = SDL_GetTicks();
111#endif
112 do {
113 errno = 0;
114
115#if HAVE_NANOSLEEP
116 tv.tv_sec = elapsed.tv_sec;
117 tv.tv_nsec = elapsed.tv_nsec;
118 was_error = nanosleep(&tv, &elapsed);
119#else
120 /* Calculate the time interval left (in case of interrupt) */
121 now = SDL_GetTicks();
122 elapsed = (now-then);
123 then = now;
124 if ( elapsed >= ms ) {
125 break;
126 }
127 ms -= elapsed;
128 tv.tv_sec = ms/1000;
129 tv.tv_usec = (ms%1000)*1000;
130
131 was_error = select(0, NULL, NULL, NULL, &tv);
132#endif /* HAVE_NANOSLEEP */
133 } while ( was_error && (errno == EINTR) );
134#endif /* SDL_THREAD_PTH */
135}
136
137#ifdef USE_ITIMER
138
139static void HandleAlarm(int sig)
140{
141 Uint32 ms;
142
143 if ( SDL_alarm_callback ) {
144 ms = (*SDL_alarm_callback)(SDL_alarm_interval);
145 if ( ms != SDL_alarm_interval ) {
146 SDL_SetTimer(ms, SDL_alarm_callback);
147 }
148 }
149}
150
151int SDL_SYS_TimerInit(void)
152{
153 struct sigaction action;
154
155 /* Set the alarm handler (Linux specific) */
156 SDL_memset(&action, 0, sizeof(action));
157 action.sa_handler = HandleAlarm;
158 action.sa_flags = SA_RESTART;
159 sigemptyset(&action.sa_mask);
160 sigaction(SIGALRM, &action, NULL);
161 return(0);
162}
163
164void SDL_SYS_TimerQuit(void)
165{
166 SDL_SetTimer(0, NULL);
167}
168
169int SDL_SYS_StartTimer(void)
170{
171 struct itimerval timer;
172
173 timer.it_value.tv_sec = (SDL_alarm_interval/1000);
174 timer.it_value.tv_usec = (SDL_alarm_interval%1000)*1000;
175 timer.it_interval.tv_sec = (SDL_alarm_interval/1000);
176 timer.it_interval.tv_usec = (SDL_alarm_interval%1000)*1000;
177 setitimer(ITIMER_REAL, &timer, NULL);
178 return(0);
179}
180
181void SDL_SYS_StopTimer(void)
182{
183 struct itimerval timer;
184
185 SDL_memset(&timer, 0, (sizeof timer));
186 setitimer(ITIMER_REAL, &timer, NULL);
187}
188
189#else /* USE_ITIMER */
190
191#include "SDL_thread.h"
192
193/* Data to handle a single periodic alarm */
194static int timer_alive = 0;
195static SDL_Thread *timer = NULL;
196
197static int RunTimer(void *unused)
198{
199 while ( timer_alive ) {
200 if ( SDL_timer_running ) {
201 SDL_ThreadedTimerCheck();
202 }
203 SDL_Delay(1);
204 }
205 return(0);
206}
207
208/* This is only called if the event thread is not running */
209int SDL_SYS_TimerInit(void)
210{
211 timer_alive = 1;
212 timer = SDL_CreateThread(RunTimer, NULL);
213 if ( timer == NULL )
214 return(-1);
215 return(SDL_SetTimerThreaded(1));
216}
217
218void SDL_SYS_TimerQuit(void)
219{
220 timer_alive = 0;
221 if ( timer ) {
222 SDL_WaitThread(timer, NULL);
223 timer = NULL;
224 }
225}
226
227int SDL_SYS_StartTimer(void)
228{
229 SDL_SetError("Internal logic error: Linux uses threaded timer");
230 return(-1);
231}
232
233void SDL_SYS_StopTimer(void)
234{
235 return;
236}
237
238#endif /* USE_ITIMER */
239
240#endif /* SDL_TIMER_UNIX */
diff --git a/apps/plugins/sdl/src/timer/win32/SDL_systimer.c b/apps/plugins/sdl/src/timer/win32/SDL_systimer.c
deleted file mode 100644
index b025e2e7c5..0000000000
--- a/apps/plugins/sdl/src/timer/win32/SDL_systimer.c
+++ /dev/null
@@ -1,160 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_WIN32
25
26#define WIN32_LEAN_AND_MEAN
27#include <windows.h>
28#include <mmsystem.h>
29
30#include "SDL_timer.h"
31#include "../SDL_timer_c.h"
32
33#ifdef _WIN32_WCE
34 #error This is WinCE. Please use src/timer/wince/SDL_systimer.c instead.
35#endif
36
37#define TIME_WRAP_VALUE (~(DWORD)0)
38
39/* The first (low-resolution) ticks value of the application */
40static DWORD start;
41
42#ifndef USE_GETTICKCOUNT
43/* Store if a high-resolution performance counter exists on the system */
44static BOOL hires_timer_available;
45/* The first high-resolution ticks value of the application */
46static LARGE_INTEGER hires_start_ticks;
47/* The number of ticks per second of the high-resolution performance counter */
48static LARGE_INTEGER hires_ticks_per_second;
49#endif
50
51void SDL_StartTicks(void)
52{
53 /* Set first ticks value */
54#ifdef USE_GETTICKCOUNT
55 start = GetTickCount();
56#else
57#if 0 /* Apparently there are problems with QPC on Win2K */
58 if (QueryPerformanceFrequency(&hires_ticks_per_second) == TRUE)
59 {
60 hires_timer_available = TRUE;
61 QueryPerformanceCounter(&hires_start_ticks);
62 }
63 else
64#endif
65 {
66 hires_timer_available = FALSE;
67 timeBeginPeriod(1); /* use 1 ms timer precision */
68 start = timeGetTime();
69 }
70#endif
71}
72
73Uint32 SDL_GetTicks(void)
74{
75 DWORD now, ticks;
76#ifndef USE_GETTICKCOUNT
77 LARGE_INTEGER hires_now;
78#endif
79
80#ifdef USE_GETTICKCOUNT
81 now = GetTickCount();
82#else
83 if (hires_timer_available)
84 {
85 QueryPerformanceCounter(&hires_now);
86
87 hires_now.QuadPart -= hires_start_ticks.QuadPart;
88 hires_now.QuadPart *= 1000;
89 hires_now.QuadPart /= hires_ticks_per_second.QuadPart;
90
91 return (DWORD)hires_now.QuadPart;
92 }
93 else
94 {
95 now = timeGetTime();
96 }
97#endif
98
99 if ( now < start ) {
100 ticks = (TIME_WRAP_VALUE-start) + now;
101 } else {
102 ticks = (now - start);
103 }
104 return(ticks);
105}
106
107void SDL_Delay(Uint32 ms)
108{
109 Sleep(ms);
110}
111
112/* Data to handle a single periodic alarm */
113static UINT timerID = 0;
114
115static void CALLBACK HandleAlarm(UINT uID, UINT uMsg, DWORD_PTR dwUser,
116 DWORD_PTR dw1, DWORD_PTR dw2)
117{
118 SDL_ThreadedTimerCheck();
119}
120
121
122int SDL_SYS_TimerInit(void)
123{
124 MMRESULT result;
125
126 /* Set timer resolution */
127 result = timeBeginPeriod(TIMER_RESOLUTION);
128 if ( result != TIMERR_NOERROR ) {
129 SDL_SetError("Warning: Can't set %d ms timer resolution",
130 TIMER_RESOLUTION);
131 }
132 /* Allow 10 ms of drift so we don't chew on CPU */
133 timerID = timeSetEvent(TIMER_RESOLUTION,1,HandleAlarm,0,TIME_PERIODIC);
134 if ( ! timerID ) {
135 SDL_SetError("timeSetEvent() failed");
136 return(-1);
137 }
138 return(SDL_SetTimerThreaded(1));
139}
140
141void SDL_SYS_TimerQuit(void)
142{
143 if ( timerID ) {
144 timeKillEvent(timerID);
145 }
146 timeEndPeriod(TIMER_RESOLUTION);
147}
148
149int SDL_SYS_StartTimer(void)
150{
151 SDL_SetError("Internal logic error: Win32 uses threaded timer");
152 return(-1);
153}
154
155void SDL_SYS_StopTimer(void)
156{
157 return;
158}
159
160#endif /* SDL_TIMER_WIN32 */
diff --git a/apps/plugins/sdl/src/timer/wince/SDL_systimer.c b/apps/plugins/sdl/src/timer/wince/SDL_systimer.c
deleted file mode 100644
index 2b018b0ed5..0000000000
--- a/apps/plugins/sdl/src/timer/wince/SDL_systimer.c
+++ /dev/null
@@ -1,198 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifdef SDL_TIMER_WINCE
25
26#define WIN32_LEAN_AND_MEAN
27#include <windows.h>
28#include <mmsystem.h>
29
30#include "SDL_thread.h"
31#include "SDL_timer.h"
32#include "../SDL_timer_c.h"
33
34static Uint64 start_date;
35static Uint64 start_ticks;
36
37static Uint64 wce_ticks(void)
38{
39 return((Uint64)GetTickCount());
40}
41
42static Uint64 wce_date(void)
43{
44 union
45 {
46 FILETIME ftime;
47 Uint64 itime;
48 } ftime;
49 SYSTEMTIME stime;
50
51 GetSystemTime(&stime);
52 SystemTimeToFileTime(&stime,&ftime.ftime);
53 ftime.itime/=10000; // Convert 100ns intervals to 1ms intervals
54 // Remove ms portion, which can't be relied on
55 ftime.itime -= (ftime.itime % 1000);
56 return(ftime.itime);
57}
58
59static Sint32 wce_rel_ticks(void)
60{
61 return((Sint32)(wce_ticks()-start_ticks));
62}
63
64static Sint32 wce_rel_date(void)
65{
66 return((Sint32)(wce_date()-start_date));
67}
68
69/* Return time in ms relative to when SDL was started */
70Uint32 SDL_GetTicks()
71{
72 Sint32 offset=wce_rel_date()-wce_rel_ticks();
73 if((offset < -1000) || (offset > 1000))
74 {
75// fprintf(stderr,"Time desync(%+d), resyncing\n",offset/1000);
76 start_ticks-=offset;
77 }
78
79 return((Uint32)wce_rel_ticks());
80}
81
82/* Give up approx. givem milliseconds to the OS. */
83void SDL_Delay(Uint32 ms)
84{
85 Sleep(ms);
86}
87
88/* Recard start-time of application for reference */
89void SDL_StartTicks(void)
90{
91 start_date=wce_date();
92 start_ticks=wce_ticks();
93}
94
95static UINT WIN_timer;
96
97#if ( _WIN32_WCE <= 420 )
98
99static HANDLE timersThread = 0;
100static HANDLE timersQuitEvent = 0;
101
102DWORD TimersThreadProc(void *data)
103{
104 while(WaitForSingleObject(timersQuitEvent, 10) == WAIT_TIMEOUT)
105 {
106 SDL_ThreadedTimerCheck();
107 }
108 return 0;
109}
110
111int SDL_SYS_TimerInit(void)
112{
113 // create a thread to process a threaded timers
114 // SetTimer does not suit the needs because
115 // TimerCallbackProc will be called only when WM_TIMER occured
116
117 timersQuitEvent = CreateEvent(0, TRUE, FALSE, 0);
118 if( !timersQuitEvent )
119 {
120 SDL_SetError("Cannot create event for timers thread");
121 return -1;
122 }
123 timersThread = CreateThread(NULL, 0, TimersThreadProc, 0, 0, 0);
124 if( !timersThread )
125 {
126 SDL_SetError("Cannot create timers thread, check amount of RAM available");
127 return -1;
128 }
129 SetThreadPriority(timersThread, THREAD_PRIORITY_HIGHEST);
130
131 return(SDL_SetTimerThreaded(1));
132}
133
134void SDL_SYS_TimerQuit(void)
135{
136 SetEvent(timersQuitEvent);
137 if( WaitForSingleObject(timersThread, 2000) == WAIT_TIMEOUT )
138 TerminateThread(timersThread, 0);
139 CloseHandle(timersThread);
140 CloseHandle(timersQuitEvent);
141 return;
142}
143
144#else
145
146#pragma comment(lib, "mmtimer.lib")
147
148/* Data to handle a single periodic alarm */
149static UINT timerID = 0;
150
151static void CALLBACK HandleAlarm(UINT uID, UINT uMsg, DWORD dwUser,
152 DWORD dw1, DWORD dw2)
153{
154 SDL_ThreadedTimerCheck();
155}
156
157
158int SDL_SYS_TimerInit(void)
159{
160 MMRESULT result;
161
162 /* Set timer resolution */
163 result = timeBeginPeriod(TIMER_RESOLUTION);
164 if ( result != TIMERR_NOERROR ) {
165 SDL_SetError("Warning: Can't set %d ms timer resolution",
166 TIMER_RESOLUTION);
167 }
168 /* Allow 10 ms of drift so we don't chew on CPU */
169 timerID = timeSetEvent(TIMER_RESOLUTION,1,HandleAlarm,0,TIME_PERIODIC);
170 if ( ! timerID ) {
171 SDL_SetError("timeSetEvent() failed");
172 return(-1);
173 }
174 return(SDL_SetTimerThreaded(1));
175}
176
177void SDL_SYS_TimerQuit(void)
178{
179 if ( timerID ) {
180 timeKillEvent(timerID);
181 }
182 timeEndPeriod(TIMER_RESOLUTION);
183}
184
185#endif
186
187int SDL_SYS_StartTimer(void)
188{
189 SDL_SetError("Internal logic error: WinCE uses threaded timer");
190 return(-1);
191}
192
193void SDL_SYS_StopTimer(void)
194{
195 return;
196}
197
198#endif /* SDL_TIMER_WINCE */
diff --git a/apps/plugins/sdl/src/video/Xext/README b/apps/plugins/sdl/src/video/Xext/README
deleted file mode 100644
index a16ea68444..0000000000
--- a/apps/plugins/sdl/src/video/Xext/README
+++ /dev/null
@@ -1,10 +0,0 @@
1
2The reason these libraries are built outside of the standard XFree86
3tree is so that they can be linked as shared object code directly into
4SDL without causing any symbol collisions with code in the application.
5
6You can't link static library code into shared libraries on non-x86
7Linux platforms. Since these libraries haven't become standard yet,
8we'll just include them directly.
9
10These sources are synchronized with XFree86 4.2.1
diff --git a/apps/plugins/sdl/src/video/Xext/XME/xme.c b/apps/plugins/sdl/src/video/Xext/XME/xme.c
deleted file mode 100644
index 2cead35ada..0000000000
--- a/apps/plugins/sdl/src/video/Xext/XME/xme.c
+++ /dev/null
@@ -1,410 +0,0 @@
1/*
2 * Copyright 1993-2001 by Xi Graphics, Inc.
3 * All Rights Reserved.
4 *
5 * Please see the LICENSE file accompanying this distribution for licensing
6 * information.
7 *
8 * Please send any bug fixes and modifications to src@xig.com.
9 *
10 * $XiGId: xme.c,v 1.2 2001/11/30 21:56:59 jon Exp $
11 *
12 */
13
14#define NEED_EVENTS
15#define NEED_REPLIES
16
17/* Apparently some X11 systems can't include this multiple times... */
18#ifndef SDL_INCLUDED_XLIBINT_H
19#define SDL_INCLUDED_XLIBINT_H 1
20#include <X11/Xlibint.h>
21#endif
22
23#include <X11/Xthreads.h>
24#include <X11/Xmd.h>
25#include <X11/Xproto.h>
26#include "../extensions/Xext.h"
27#include "../extensions/extutil.h"
28
29/*****************************************************************************/
30
31
32#define XIGMISC_PROTOCOL_NAME "XiG-SUNDRY-NONSTANDARD"
33#define XIGMISC_MAJOR_VERSION 2
34#define XIGMISC_MINOR_VERSION 0
35
36#define XiGMiscNumberEvents 0
37
38#define X_XiGMiscQueryVersion 0
39#define X_XiGMiscQueryViews 1
40#define X_XiGMiscQueryResolutions 2
41#define X_XiGMiscChangeResolution 3
42#define X_XiGMiscFullScreen 4
43
44#define sz_xXiGMiscQueryVersionReq 8
45#define sz_xXiGMiscQueryViewsReq 8
46#define sz_xXiGMiscQueryResolutionsReq 8
47#define sz_xXiGMiscChangeResolutionReq 16
48#define sz_xXiGMiscFullScreenReq 16
49
50#define sz_xXiGMiscQueryVersionReply 32
51#define sz_xXiGMiscQueryViewsReply 32
52#define sz_xXiGMiscQueryResolutionsReply 32
53#define sz_xXiGMiscQueryFullScreenReply 32
54
55/*******************************************************************/
56
57typedef struct {
58 CARD8 reqType; /* always codes->major_opcode */
59 CARD8 xigmiscReqType; /* always X_XiGMiscQueryVersion */
60 CARD16 length;
61 CARD16 major;
62 CARD16 minor;
63} xXiGMiscQueryVersionReq;
64
65typedef struct {
66 CARD8 reqType; /* always codes->major_opcode */
67 CARD8 xigmiscReqType; /* always X_XiGMiscQueryViews */
68 CARD16 length;
69 CARD8 screen;
70 CARD8 pad0;
71 CARD16 pad1;
72} xXiGMiscQueryViewsReq;
73
74typedef struct {
75 CARD8 reqType; /* always codes->major_opcode */
76 CARD8 xigmiscReqType; /* always X_XiGMiscQueryResolutions */
77 CARD16 length;
78 CARD8 screen;
79 CARD8 view;
80 CARD16 pad0;
81} xXiGMiscQueryResolutionsReq;
82
83typedef struct {
84 CARD8 reqType; /* always codes->major_opcode */
85 CARD8 xigmiscReqType; /* always X_XiGMiscChangeResolution */
86 CARD16 length;
87 CARD8 screen;
88 CARD8 view;
89 CARD16 pad0;
90 CARD16 width;
91 CARD16 height;
92 INT32 refresh;
93} xXiGMiscChangeResolutionReq;
94
95typedef struct {
96 CARD8 reqType; /* always codes->major_opcode */
97 CARD8 xigmiscReqType; /* always X_XiGMiscFullScreen */
98 CARD16 length;
99 CARD8 screen;
100 CARD8 pad0;
101 CARD16 pad1;
102 CARD32 window;
103 CARD32 cmap;
104} xXiGMiscFullScreenReq;
105
106/*******************************************************************/
107
108typedef struct {
109 BYTE type; /* X_Reply */
110 CARD8 pad0;
111 CARD16 sequenceNumber;
112 CARD32 length;
113 CARD16 major;
114 CARD16 minor;
115 CARD32 pad1;
116 CARD32 pad2;
117 CARD32 pad3;
118 CARD32 pad4;
119 CARD32 pad5;
120} xXiGMiscQueryVersionReply;
121
122typedef struct {
123 BYTE type; /* X_Reply */
124 CARD8 pad0;
125 CARD16 sequenceNumber;
126 CARD32 length;
127 CARD32 nviews;
128 CARD32 pad1;
129 CARD32 pad2;
130 CARD32 pad3;
131 CARD32 pad4;
132 CARD32 pad5;
133} xXiGMiscQueryViewsReply;
134
135typedef struct {
136 BYTE type; /* X_Reply */
137 CARD8 pad0;
138 CARD16 sequenceNumber;
139 CARD32 length;
140 CARD16 active;
141 CARD16 nresolutions;
142 CARD32 pad1;
143 CARD32 pad2;
144 CARD32 pad3;
145 CARD32 pad4;
146 CARD32 pad5;
147} xXiGMiscQueryResolutionsReply;
148
149typedef struct {
150 BYTE type; /* X_Reply */
151 BOOL success;
152 CARD16 sequenceNumber;
153 CARD32 length;
154 CARD32 pad1;
155 CARD32 pad2;
156 CARD32 pad3;
157 CARD32 pad4;
158 CARD32 pad5;
159 CARD32 pad6;
160} xXiGMiscFullScreenReply;
161
162/*******************************************************************/
163
164typedef struct {
165 INT16 x;
166 INT16 y;
167 CARD16 w;
168 CARD16 h;
169} XiGMiscViewInfo;
170
171typedef struct {
172 CARD16 width;
173 CARD16 height;
174 INT32 refresh;
175} XiGMiscResolutionInfo;
176
177/*****************************************************************************/
178
179static XExtensionInfo *xigmisc_info = NULL;
180static char *xigmisc_extension_name = XIGMISC_PROTOCOL_NAME;
181
182#define XiGMiscCheckExtension(dpy,i,val) \
183 XextCheckExtension (dpy, i, xigmisc_extension_name, val)
184#define XiGMiscSimpleCheckExtension(dpy,i) \
185 XextSimpleCheckExtension (dpy, i, xigmisc_extension_name)
186
187#if defined(__STDC__) && !defined(UNIXCPP)
188#define XiGMiscGetReq(name,req,info) GetReq (name, req); \
189 req->reqType = info->codes->major_opcode; \
190 req->xigmiscReqType = X_##name;
191
192#define XiGMiscGetReqExtra(name,n,req,info) GetReqExtra (name, n, req); \
193 req->reqType = info->codes->major_opcode; \
194 req->xigmicReqType = X_##name;
195#else
196#define XiGMiscGetReq(name,req,info) GetReq (name, req); \
197 req->reqType = info->codes->major_opcode; \
198 req->xigmiscReqType = X_/**/name;
199#define XiGMiscGetReqExtra(name,n,req,info) GetReqExtra (name, n, req); \
200 req->reqType = info->codes->major_opcode; \
201 req->xigmiscReqType = X_/**/name;
202#endif
203
204
205
206/*
207 * find_display - locate the display info block
208 */
209static int XiGMiscCloseDisplay();
210
211static XExtensionHooks xigmisc_extension_hooks = {
212 NULL, /* create_gc */
213 NULL, /* copy_gc */
214 NULL, /* flush_gc */
215 NULL, /* free_gc */
216 NULL, /* create_font */
217 NULL, /* free_font */
218 XiGMiscCloseDisplay, /* close_display */
219 NULL, /* wire_to_event */
220 NULL, /* event_to_wire */
221 NULL, /* error */
222 NULL, /* error_string */
223};
224
225
226static XEXT_GENERATE_CLOSE_DISPLAY (XiGMiscCloseDisplay, xigmisc_info)
227
228static XEXT_GENERATE_FIND_DISPLAY (XiGMiscFindDisplay, xigmisc_info,
229 xigmisc_extension_name,
230 &xigmisc_extension_hooks, XiGMiscNumberEvents, NULL)
231
232
233/*****************************************************************************/
234
235Bool XiGMiscQueryVersion(Display *dpy, int *major, int *minor)
236{
237 int opcode, event, error;
238 xXiGMiscQueryVersionReq *req;
239 xXiGMiscQueryVersionReply rep;
240 XExtDisplayInfo *info = XiGMiscFindDisplay(dpy);
241
242 if (!XQueryExtension(dpy, XIGMISC_PROTOCOL_NAME, &opcode, &event, &error))
243 return xFalse;
244
245 XiGMiscCheckExtension(dpy, info, xFalse);
246
247 LockDisplay (dpy);
248 XiGMiscGetReq (XiGMiscQueryVersion, req, info);
249
250 req->major = XIGMISC_MAJOR_VERSION;
251 req->minor = XIGMISC_MINOR_VERSION;
252
253 if (!_XReply (dpy, (xReply *)&rep, 0, xTrue)) {
254 UnlockDisplay(dpy);
255 SyncHandle();
256 return xFalse;
257 }
258
259 *major = rep.major;
260 *minor = rep.minor;
261 UnlockDisplay(dpy);
262 SyncHandle();
263
264 return xTrue;
265}
266
267int XiGMiscQueryViews(Display *dpy, int screen, XiGMiscViewInfo **pviews)
268{
269 int n, size;
270 XiGMiscViewInfo *views;
271 xXiGMiscQueryViewsReq *req;
272 xXiGMiscQueryViewsReply rep;
273 XExtDisplayInfo *info = XiGMiscFindDisplay(dpy);
274 XiGMiscCheckExtension(dpy, info, 0);
275
276 LockDisplay (dpy);
277 XiGMiscGetReq (XiGMiscQueryViews, req, info);
278 req->screen = screen;
279
280 if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
281 UnlockDisplay(dpy);
282 SyncHandle();
283 return 0;
284 }
285
286 n = rep.nviews;
287
288 if (n > 0) {
289 size = sizeof(XiGMiscViewInfo) * n;
290 views = (XiGMiscViewInfo*)Xmalloc(size);
291 if (!views) {
292 _XEatData(dpy, (unsigned long)size);
293 UnlockDisplay(dpy);
294 SyncHandle();
295 return 0;
296 }
297
298 _XReadPad(dpy, (void*)views, size);
299
300 *pviews = views;
301 }
302
303 UnlockDisplay(dpy);
304 SyncHandle();
305
306 return n;
307}
308
309int XiGMiscQueryResolutions(Display *dpy, int screen, int view, int *pactive, XiGMiscResolutionInfo **presolutions)
310{
311 int n, size;
312 XiGMiscResolutionInfo *resolutions;
313 xXiGMiscQueryResolutionsReq *req;
314 xXiGMiscQueryResolutionsReply rep;
315 XExtDisplayInfo *info = XiGMiscFindDisplay(dpy);
316 XiGMiscCheckExtension(dpy, info, 0);
317
318 LockDisplay (dpy);
319 XiGMiscGetReq (XiGMiscQueryResolutions, req, info);
320 req->screen = screen;
321 req->view = view;
322
323 if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
324 UnlockDisplay(dpy);
325 SyncHandle();
326 return 0;
327 }
328
329 n = rep.nresolutions;
330
331 if (n > 0) {
332 size = sizeof(XiGMiscResolutionInfo) * n;
333 resolutions = (XiGMiscResolutionInfo*)Xmalloc(size);
334 if (!resolutions) {
335 _XEatData(dpy, (unsigned long)size);
336 UnlockDisplay(dpy);
337 SyncHandle();
338 return 0;
339 }
340
341 _XReadPad(dpy, (void*)resolutions, size);
342
343 *presolutions = resolutions;
344 *pactive = rep.active;
345 }
346
347 UnlockDisplay(dpy);
348 SyncHandle();
349
350 return n;
351}
352
353void XiGMiscChangeResolution(Display *dpy, int screen, int view, int width, int height, int refresh)
354{
355 xXiGMiscChangeResolutionReq *req;
356 XExtDisplayInfo *info = XiGMiscFindDisplay(dpy);
357
358 XiGMiscSimpleCheckExtension(dpy, info);
359
360 LockDisplay (dpy);
361 XiGMiscGetReq (XiGMiscChangeResolution, req, info);
362 req->screen = screen;
363 req->view = view;
364 req->width = width;
365 req->height = height;
366 req->refresh = refresh;
367
368 UnlockDisplay(dpy);
369 SyncHandle();
370}
371
372
373Bool XiGMiscFullScreen(Display *dpy, int screen, XID window, XID cmap)
374{
375 xXiGMiscFullScreenReq *req;
376 xXiGMiscFullScreenReply rep;
377 XExtDisplayInfo *info = XiGMiscFindDisplay(dpy);
378
379 XiGMiscCheckExtension(dpy, info, xFalse);
380
381 LockDisplay (dpy);
382 XiGMiscGetReq (XiGMiscFullScreen, req, info);
383 req->screen = screen;
384 req->pad0 = 0;
385 req->pad1 = 0;
386 req->window = window;
387 req->cmap = cmap;
388
389 if (!_XReply (dpy, (xReply *)&rep, 0, xTrue)) {
390 UnlockDisplay(dpy);
391 SyncHandle();
392 return xFalse;
393 }
394
395 UnlockDisplay(dpy);
396 SyncHandle();
397
398 return (rep.success ? xTrue : xFalse);
399}
400
401
402/* SDL addition from Ryan: free memory used by xme. */
403void XiGMiscDestroy(void)
404{
405 if (xigmisc_info) {
406 XextDestroyExtension(xigmisc_info);
407 xigmisc_info = NULL;
408 }
409}
410
diff --git a/apps/plugins/sdl/src/video/Xext/Xinerama/Xinerama.c b/apps/plugins/sdl/src/video/Xext/Xinerama/Xinerama.c
deleted file mode 100644
index 4ff42ebfe9..0000000000
--- a/apps/plugins/sdl/src/video/Xext/Xinerama/Xinerama.c
+++ /dev/null
@@ -1,324 +0,0 @@
1/* $Xorg: XPanoramiX.c,v 1.4 2000/08/17 19:45:51 cpqbld Exp $ */
2/*****************************************************************
3Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts.
4Permission is hereby granted, free of charge, to any person obtaining a copy
5of this software and associated documentation files (the "Software"), to deal
6in the Software without restriction, including without limitation the rights
7to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8copies of the Software.
9
10The above copyright notice and this permission notice shall be included in
11all copies or substantial portions of the Software.
12
13THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING,
17BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL DAMAGES, OR OTHER LIABILITY,
18WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
19IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20
21Except as contained in this notice, the name of Digital Equipment Corporation
22shall not be used in advertising or otherwise to promote the sale, use or other
23dealings in this Software without prior written authorization from Digital
24Equipment Corporation.
25******************************************************************/
26/* $XFree86: xc/lib/Xinerama/Xinerama.c,v 1.2 2001/07/23 17:20:28 dawes Exp $ */
27
28#define NEED_EVENTS
29#define NEED_REPLIES
30
31/* Apparently some X11 systems can't include this multiple times... */
32#ifndef SDL_INCLUDED_XLIBINT_H
33#define SDL_INCLUDED_XLIBINT_H 1
34#include <X11/Xlibint.h>
35#endif
36
37#include <X11/Xutil.h>
38#include "../extensions/Xext.h"
39#include "../extensions/extutil.h" /* in ../include */
40#include "../extensions/panoramiXext.h"
41#include "../extensions/panoramiXproto.h" /* in ../include */
42#include "../extensions/Xinerama.h"
43
44static XExtensionInfo _panoramiX_ext_info_data;
45static XExtensionInfo *panoramiX_ext_info = &_panoramiX_ext_info_data;
46static /* const */ char *panoramiX_extension_name = PANORAMIX_PROTOCOL_NAME;
47
48#define PanoramiXCheckExtension(dpy,i,val) \
49 XextCheckExtension (dpy, i, panoramiX_extension_name, val)
50#define PanoramiXSimpleCheckExtension(dpy,i) \
51 XextSimpleCheckExtension (dpy, i, panoramiX_extension_name)
52
53static int close_display();
54static /* const */ XExtensionHooks panoramiX_extension_hooks = {
55 NULL, /* create_gc */
56 NULL, /* copy_gc */
57 NULL, /* flush_gc */
58 NULL, /* free_gc */
59 NULL, /* create_font */
60 NULL, /* free_font */
61 close_display, /* close_display */
62 NULL, /* wire_to_event */
63 NULL, /* event_to_wire */
64 NULL, /* error */
65 NULL, /* error_string */
66};
67
68static XEXT_GENERATE_FIND_DISPLAY (find_display, panoramiX_ext_info,
69 panoramiX_extension_name,
70 &panoramiX_extension_hooks,
71 0, NULL)
72
73static XEXT_GENERATE_CLOSE_DISPLAY (close_display, panoramiX_ext_info)
74
75
76
77/****************************************************************************
78 * *
79 * PanoramiX public interfaces *
80 * *
81 ****************************************************************************/
82
83Bool SDL_NAME(XPanoramiXQueryExtension) (
84 Display *dpy,
85 int *event_basep,
86 int *error_basep
87)
88{
89 XExtDisplayInfo *info = find_display (dpy);
90
91 if (XextHasExtension(info)) {
92 *event_basep = info->codes->first_event;
93 *error_basep = info->codes->first_error;
94 return True;
95 } else {
96 return False;
97 }
98}
99
100
101Status SDL_NAME(XPanoramiXQueryVersion)(
102 Display *dpy,
103 int *major_versionp,
104 int *minor_versionp
105)
106{
107 XExtDisplayInfo *info = find_display (dpy);
108 xPanoramiXQueryVersionReply rep;
109 register xPanoramiXQueryVersionReq *req;
110
111 PanoramiXCheckExtension (dpy, info, 0);
112
113 LockDisplay (dpy);
114 GetReq (PanoramiXQueryVersion, req);
115 req->reqType = info->codes->major_opcode;
116 req->panoramiXReqType = X_PanoramiXQueryVersion;
117 req->clientMajor = PANORAMIX_MAJOR_VERSION;
118 req->clientMinor = PANORAMIX_MINOR_VERSION;
119 if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
120 UnlockDisplay (dpy);
121 SyncHandle ();
122 return 0;
123 }
124 *major_versionp = rep.majorVersion;
125 *minor_versionp = rep.minorVersion;
126 UnlockDisplay (dpy);
127 SyncHandle ();
128 return 1;
129}
130
131SDL_NAME(XPanoramiXInfo) *SDL_NAME(XPanoramiXAllocInfo)(void)
132{
133 return (SDL_NAME(XPanoramiXInfo) *) Xmalloc (sizeof (SDL_NAME(XPanoramiXInfo)));
134}
135
136Status SDL_NAME(XPanoramiXGetState) (
137 Display *dpy,
138 Drawable drawable,
139 SDL_NAME(XPanoramiXInfo) *panoramiX_info
140)
141{
142 XExtDisplayInfo *info = find_display (dpy);
143 xPanoramiXGetStateReply rep;
144 register xPanoramiXGetStateReq *req;
145
146 PanoramiXCheckExtension (dpy, info, 0);
147
148 LockDisplay (dpy);
149 GetReq (PanoramiXGetState, req);
150 req->reqType = info->codes->major_opcode;
151 req->panoramiXReqType = X_PanoramiXGetState;
152 req->window = drawable;
153 if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
154 UnlockDisplay (dpy);
155 SyncHandle ();
156 return 0;
157 }
158 UnlockDisplay (dpy);
159 SyncHandle ();
160 panoramiX_info->window = rep.window;
161 panoramiX_info->State = rep.state;
162 return 1;
163}
164
165Status SDL_NAME(XPanoramiXGetScreenCount) (
166 Display *dpy,
167 Drawable drawable,
168 SDL_NAME(XPanoramiXInfo) *panoramiX_info
169)
170{
171 XExtDisplayInfo *info = find_display (dpy);
172 xPanoramiXGetScreenCountReply rep;
173 register xPanoramiXGetScreenCountReq *req;
174
175 PanoramiXCheckExtension (dpy, info, 0);
176
177 LockDisplay (dpy);
178 GetReq (PanoramiXGetScreenCount, req);
179 req->reqType = info->codes->major_opcode;
180 req->panoramiXReqType = X_PanoramiXGetScreenCount;
181 req->window = drawable;
182 if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
183 UnlockDisplay (dpy);
184 SyncHandle ();
185 return 0;
186 }
187 UnlockDisplay (dpy);
188 SyncHandle ();
189 panoramiX_info->window = rep.window;
190 panoramiX_info->ScreenCount = rep.ScreenCount;
191 return 1;
192}
193
194Status SDL_NAME(XPanoramiXGetScreenSize) (
195 Display *dpy,
196 Drawable drawable,
197 int screen_num,
198 SDL_NAME(XPanoramiXInfo) *panoramiX_info
199)
200{
201 XExtDisplayInfo *info = find_display (dpy);
202 xPanoramiXGetScreenSizeReply rep;
203 register xPanoramiXGetScreenSizeReq *req;
204
205 PanoramiXCheckExtension (dpy, info, 0);
206
207 LockDisplay (dpy);
208 GetReq (PanoramiXGetScreenSize, req);
209 req->reqType = info->codes->major_opcode;
210 req->panoramiXReqType = X_PanoramiXGetScreenSize;
211 req->window = drawable;
212 req->screen = screen_num; /* need to define */
213 if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
214 UnlockDisplay (dpy);
215 SyncHandle ();
216 return 0;
217 }
218 UnlockDisplay (dpy);
219 SyncHandle ();
220 panoramiX_info->window = rep.window;
221 panoramiX_info->screen = rep.screen;
222 panoramiX_info->width = rep.width;
223 panoramiX_info->height = rep.height;
224 return 1;
225}
226
227/*******************************************************************\
228 Alternate interface to make up for shortcomings in the original,
229 namely, the omission of the screen origin. The new interface is
230 in the "Xinerama" namespace instead of "PanoramiX".
231\*******************************************************************/
232
233Bool SDL_NAME(XineramaQueryExtension) (
234 Display *dpy,
235 int *event_base,
236 int *error_base
237)
238{
239 return SDL_NAME(XPanoramiXQueryExtension)(dpy, event_base, error_base);
240}
241
242Status SDL_NAME(XineramaQueryVersion)(
243 Display *dpy,
244 int *major,
245 int *minor
246)
247{
248 return SDL_NAME(XPanoramiXQueryVersion)(dpy, major, minor);
249}
250
251Bool SDL_NAME(XineramaIsActive)(Display *dpy)
252{
253 xXineramaIsActiveReply rep;
254 xXineramaIsActiveReq *req;
255 XExtDisplayInfo *info = find_display (dpy);
256
257 if(!XextHasExtension(info))
258 return False; /* server doesn't even have the extension */
259
260 LockDisplay (dpy);
261 GetReq (XineramaIsActive, req);
262 req->reqType = info->codes->major_opcode;
263 req->panoramiXReqType = X_XineramaIsActive;
264 if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
265 UnlockDisplay (dpy);
266 SyncHandle ();
267 return False;
268 }
269 UnlockDisplay (dpy);
270 SyncHandle ();
271 return rep.state;
272}
273
274#include <stdio.h>
275
276SDL_NAME(XineramaScreenInfo) *
277SDL_NAME(XineramaQueryScreens)(
278 Display *dpy,
279 int *number
280)
281{
282 XExtDisplayInfo *info = find_display (dpy);
283 xXineramaQueryScreensReply rep;
284 xXineramaQueryScreensReq *req;
285 SDL_NAME(XineramaScreenInfo) *scrnInfo = NULL;
286
287 PanoramiXCheckExtension (dpy, info, 0);
288
289 LockDisplay (dpy);
290 GetReq (XineramaQueryScreens, req);
291 req->reqType = info->codes->major_opcode;
292 req->panoramiXReqType = X_XineramaQueryScreens;
293 if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
294 UnlockDisplay (dpy);
295 SyncHandle ();
296 return NULL;
297 }
298
299 if(rep.number) {
300 if((scrnInfo = Xmalloc(sizeof(SDL_NAME(XineramaScreenInfo)) * rep.number))) {
301 xXineramaScreenInfo scratch;
302 int i;
303
304 for(i = 0; i < rep.number; i++) {
305 _XRead(dpy, (char*)(&scratch), sz_XineramaScreenInfo);
306 scrnInfo[i].screen_number = i;
307 scrnInfo[i].x_org = scratch.x_org;
308 scrnInfo[i].y_org = scratch.y_org;
309 scrnInfo[i].width = scratch.width;
310 scrnInfo[i].height = scratch.height;
311 }
312
313 *number = rep.number;
314 } else
315 _XEatData(dpy, rep.length << 2);
316 }
317
318 UnlockDisplay (dpy);
319 SyncHandle ();
320 return scrnInfo;
321}
322
323
324
diff --git a/apps/plugins/sdl/src/video/Xext/Xv/Xv.c b/apps/plugins/sdl/src/video/Xext/Xv/Xv.c
deleted file mode 100644
index 7147b9e8cb..0000000000
--- a/apps/plugins/sdl/src/video/Xext/Xv/Xv.c
+++ /dev/null
@@ -1,1151 +0,0 @@
1/***********************************************************
2Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts,
3and the Massachusetts Institute of Technology, Cambridge, Massachusetts.
4
5 All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Digital or MIT not be
12used in advertising or publicity pertaining to distribution of the
13software without specific, written prior permission.
14
15DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
16ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
17DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
18ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
19WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
20ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
21SOFTWARE.
22
23******************************************************************/
24/* $XFree86: xc/lib/Xv/Xv.c,v 1.15 2001/05/11 08:23:22 alanh Exp $ */
25/*
26** File:
27**
28** Xv.c --- Xv library extension module.
29**
30** Author:
31**
32** David Carver (Digital Workstation Engineering/Project Athena)
33**
34** Revisions:
35**
36** 26.06.91 Carver
37** - changed XvFreeAdaptors to XvFreeAdaptorInfo
38** - changed XvFreeEncodings to XvFreeEncodingInfo
39**
40** 11.06.91 Carver
41** - changed SetPortControl to SetPortAttribute
42** - changed GetPortControl to GetPortAttribute
43** - changed QueryBestSize
44**
45** 15.05.91 Carver
46** - version 2.0 upgrade
47**
48** 240.01.91 Carver
49** - version 1.4 upgrade
50**
51*/
52
53#include <stdio.h>
54#include "Xvlibint.h"
55#include "../extensions/Xext.h"
56#include <X11/extensions/XShm.h>
57#include "../extensions/extutil.h"
58
59static XExtensionInfo _xv_info_data;
60static XExtensionInfo *xv_info = &_xv_info_data;
61static char *xv_extension_name = XvName;
62
63#define XvCheckExtension(dpy, i, val) \
64 XextCheckExtension(dpy, i, xv_extension_name, val)
65
66static char *xv_error_string();
67static int xv_close_display();
68static Bool xv_wire_to_event();
69
70static XExtensionHooks xv_extension_hooks = {
71 NULL, /* create_gc */
72 NULL, /* copy_gc */
73 NULL, /* flush_gc */
74 NULL, /* free_gc */
75 NULL, /* create_font */
76 NULL, /* free_font */
77 xv_close_display, /* close_display */
78 xv_wire_to_event, /* wire_to_event */
79 NULL, /* event_to_wire */
80 NULL, /* error */
81 xv_error_string /* error_string */
82};
83
84
85static char *xv_error_list[] =
86{
87 "BadPort", /* XvBadPort */
88 "BadEncoding", /* XvBadEncoding */
89 "BadControl" /* XvBadControl */
90};
91
92static XEXT_GENERATE_CLOSE_DISPLAY (xv_close_display, xv_info)
93
94
95static XEXT_GENERATE_FIND_DISPLAY (xv_find_display, xv_info,
96 xv_extension_name,
97 &xv_extension_hooks,
98 XvNumEvents, NULL)
99
100
101static XEXT_GENERATE_ERROR_STRING (xv_error_string, xv_extension_name,
102 XvNumErrors, xv_error_list)
103
104
105int
106SDL_NAME(XvQueryExtension)(
107 Display *dpy,
108 unsigned int *p_version,
109 unsigned int *p_revision,
110 unsigned int *p_requestBase,
111 unsigned int *p_eventBase,
112 unsigned int *p_errorBase
113){
114 XExtDisplayInfo *info = xv_find_display(dpy);
115 xvQueryExtensionReq *req;
116 xvQueryExtensionReply rep;
117
118 XvCheckExtension(dpy, info, XvBadExtension);
119
120 LockDisplay(dpy);
121
122 XvGetReq(QueryExtension, req);
123
124 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
125 UnlockDisplay(dpy);
126 SyncHandle();
127 return XvBadExtension;
128 }
129
130 *p_version = rep.version;
131 *p_revision = rep.revision;
132 *p_requestBase = info->codes->major_opcode;
133 *p_eventBase = info->codes->first_event;
134 *p_errorBase = info->codes->first_error;
135
136 UnlockDisplay(dpy);
137 SyncHandle();
138
139 return Success;
140}
141
142int
143SDL_NAME(XvQueryAdaptors)(
144 Display *dpy,
145 Window window,
146 unsigned int *p_nAdaptors,
147 SDL_NAME(XvAdaptorInfo) **p_pAdaptors
148){
149 XExtDisplayInfo *info = xv_find_display(dpy);
150 xvQueryAdaptorsReq *req;
151 xvQueryAdaptorsReply rep;
152 int size,ii,jj;
153 char *name;
154 SDL_NAME(XvAdaptorInfo) *pas, *pa;
155 SDL_NAME(XvFormat) *pfs, *pf;
156 char *buffer;
157 union
158 {
159 char *buffer;
160 char *string;
161 xvAdaptorInfo *pa;
162 xvFormat *pf;
163 } u;
164
165 XvCheckExtension(dpy, info, XvBadExtension);
166
167 LockDisplay(dpy);
168
169 XvGetReq(QueryAdaptors, req);
170 req->window = window;
171
172 /* READ THE REPLY */
173
174 if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) {
175 UnlockDisplay(dpy);
176 SyncHandle();
177 return(XvBadReply);
178 }
179
180 size = rep.length << 2;
181 if ( (buffer = (char *)Xmalloc ((unsigned) size)) == NULL) {
182 UnlockDisplay(dpy);
183 SyncHandle();
184 return(XvBadAlloc);
185 }
186 _XRead (dpy, buffer, size);
187
188 u.buffer = buffer;
189
190 /* GET INPUT ADAPTORS */
191
192 if (rep.num_adaptors == 0) {
193 pas = NULL;
194 } else {
195 size = rep.num_adaptors*sizeof(SDL_NAME(XvAdaptorInfo));
196 if ((pas=(SDL_NAME(XvAdaptorInfo) *)Xmalloc(size))==NULL) {
197 Xfree(buffer);
198 UnlockDisplay(dpy);
199 SyncHandle();
200 return(XvBadAlloc);
201 }
202 }
203
204 /* INIT ADAPTOR FIELDS */
205
206 pa = pas;
207 for (ii=0; ii<rep.num_adaptors; ii++) {
208 pa->num_adaptors = 0;
209 pa->name = (char *)NULL;
210 pa->formats = (SDL_NAME(XvFormat) *)NULL;
211 pa++;
212 }
213
214 pa = pas;
215 for (ii=0; ii<rep.num_adaptors; ii++) {
216 pa->type = u.pa->type;
217 pa->base_id = u.pa->base_id;
218 pa->num_ports = u.pa->num_ports;
219 pa->num_formats = u.pa->num_formats;
220 pa->num_adaptors = rep.num_adaptors - ii;
221
222 /* GET ADAPTOR NAME */
223
224 size = u.pa->name_size;
225 u.buffer += (sz_xvAdaptorInfo + 3) & ~3;
226
227 if ( (name = (char *)Xmalloc(size+1)) == NULL)
228 {
229 SDL_NAME(XvFreeAdaptorInfo)(pas);
230 Xfree(buffer);
231 UnlockDisplay(dpy);
232 SyncHandle();
233 return(XvBadAlloc);
234 }
235 SDL_strlcpy(name, u.string, size);
236 pa->name = name;
237
238 u.buffer += (size + 3) & ~3;
239
240 /* GET FORMATS */
241
242 size = pa->num_formats*sizeof(SDL_NAME(XvFormat));
243 if ((pfs=(SDL_NAME(XvFormat) *)Xmalloc(size))==NULL) {
244 SDL_NAME(XvFreeAdaptorInfo)(pas);
245 Xfree(buffer);
246 UnlockDisplay(dpy);
247 SyncHandle();
248 return(XvBadAlloc);
249 }
250
251 pf = pfs;
252 for (jj=0; jj<pa->num_formats; jj++) {
253 pf->depth = u.pf->depth;
254 pf->visual_id = u.pf->visual;
255 pf++;
256
257 u.buffer += (sz_xvFormat + 3) & ~3;
258 }
259
260 pa->formats = pfs;
261
262 pa++;
263
264 }
265
266 *p_nAdaptors = rep.num_adaptors;
267 *p_pAdaptors = pas;
268
269 Xfree(buffer);
270 UnlockDisplay(dpy);
271 SyncHandle();
272
273 return (Success);
274}
275
276
277void
278SDL_NAME(XvFreeAdaptorInfo)(SDL_NAME(XvAdaptorInfo) *pAdaptors)
279{
280
281 SDL_NAME(XvAdaptorInfo) *pa;
282 int ii;
283
284 if (!pAdaptors) return;
285
286 pa = pAdaptors;
287
288 for (ii=0; ii<pAdaptors->num_adaptors; ii++, pa++)
289 {
290 if (pa->name)
291 {
292 Xfree(pa->name);
293 }
294 if (pa->formats)
295 {
296 Xfree(pa->formats);
297 }
298 }
299
300 Xfree(pAdaptors);
301}
302
303int
304SDL_NAME(XvQueryEncodings)(
305 Display *dpy,
306 XvPortID port,
307 unsigned int *p_nEncodings,
308 SDL_NAME(XvEncodingInfo) **p_pEncodings
309){
310 XExtDisplayInfo *info = xv_find_display(dpy);
311 xvQueryEncodingsReq *req;
312 xvQueryEncodingsReply rep;
313 int size, jj;
314 char *name;
315 SDL_NAME(XvEncodingInfo) *pes, *pe;
316 char *buffer;
317 union
318 {
319 char *buffer;
320 char *string;
321 xvEncodingInfo *pe;
322 } u;
323
324 XvCheckExtension(dpy, info, XvBadExtension);
325
326 LockDisplay(dpy);
327
328 XvGetReq(QueryEncodings, req);
329 req->port = port;
330
331 /* READ THE REPLY */
332
333 if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) {
334 UnlockDisplay(dpy);
335 SyncHandle();
336 return(XvBadReply);
337 }
338
339 size = rep.length << 2;
340 if ( (buffer = (char *)Xmalloc ((unsigned) size)) == NULL) {
341 UnlockDisplay(dpy);
342 SyncHandle();
343 return(XvBadAlloc);
344 }
345 _XRead (dpy, buffer, size);
346
347 u.buffer = buffer;
348
349 /* GET ENCODINGS */
350
351 size = rep.num_encodings*sizeof(SDL_NAME(XvEncodingInfo));
352 if ( (pes = (SDL_NAME(XvEncodingInfo) *)Xmalloc(size)) == NULL) {
353 Xfree(buffer);
354 UnlockDisplay(dpy);
355 SyncHandle();
356 return(XvBadAlloc);
357 }
358
359 /* INITIALIZE THE ENCODING POINTER */
360
361 pe = pes;
362 for (jj=0; jj<rep.num_encodings; jj++) {
363 pe->name = (char *)NULL;
364 pe->num_encodings = 0;
365 pe++;
366 }
367
368 pe = pes;
369 for (jj=0; jj<rep.num_encodings; jj++) {
370 pe->encoding_id = u.pe->encoding;
371 pe->width = u.pe->width;
372 pe->height = u.pe->height;
373 pe->rate.numerator = u.pe->rate.numerator;
374 pe->rate.denominator = u.pe->rate.denominator;
375 pe->num_encodings = rep.num_encodings - jj;
376
377 size = u.pe->name_size;
378 u.buffer += (sz_xvEncodingInfo + 3) & ~3;
379
380 if ( (name = (char *)Xmalloc(size+1)) == NULL) {
381 Xfree(buffer);
382 UnlockDisplay(dpy);
383 SyncHandle();
384 return(XvBadAlloc);
385 }
386 SDL_strlcpy(name, u.string, size);
387 pe->name = name;
388 pe++;
389
390 u.buffer += (size + 3) & ~3;
391 }
392
393 *p_nEncodings = rep.num_encodings;
394 *p_pEncodings = pes;
395
396 Xfree(buffer);
397 UnlockDisplay(dpy);
398 SyncHandle();
399
400 return (Success);
401}
402
403void
404SDL_NAME(XvFreeEncodingInfo)(SDL_NAME(XvEncodingInfo) *pEncodings)
405{
406
407 SDL_NAME(XvEncodingInfo) *pe;
408 int ii;
409
410 if (!pEncodings) return;
411
412 pe = pEncodings;
413
414 for (ii=0; ii<pEncodings->num_encodings; ii++, pe++) {
415 if (pe->name) Xfree(pe->name);
416 }
417
418 Xfree(pEncodings);
419}
420
421int
422SDL_NAME(XvPutVideo)(
423 Display *dpy,
424 XvPortID port,
425 Drawable d,
426 GC gc,
427 int vx, int vy,
428 unsigned int vw, unsigned int vh,
429 int dx, int dy,
430 unsigned int dw, unsigned int dh
431){
432 XExtDisplayInfo *info = xv_find_display(dpy);
433 xvPutVideoReq *req;
434
435 XvCheckExtension(dpy, info, XvBadExtension);
436
437 LockDisplay(dpy);
438
439 FlushGC(dpy, gc);
440
441 XvGetReq(PutVideo, req);
442
443 req->port = port;
444 req->drawable = d;
445 req->gc = gc->gid;
446 req->vid_x = vx;
447 req->vid_y = vy;
448 req->vid_w = vw;
449 req->vid_h = vh;
450 req->drw_x = dx;
451 req->drw_y = dy;
452 req->drw_w = dw;
453 req->drw_h = dh;
454
455 UnlockDisplay(dpy);
456 SyncHandle();
457
458 return Success;
459}
460
461int
462SDL_NAME(XvPutStill)(
463 Display *dpy,
464 XvPortID port,
465 Drawable d,
466 GC gc,
467 int vx, int vy,
468 unsigned int vw, unsigned int vh,
469 int dx, int dy,
470 unsigned int dw, unsigned int dh
471){
472 XExtDisplayInfo *info = xv_find_display(dpy);
473 xvPutStillReq *req;
474
475 XvCheckExtension(dpy, info, XvBadExtension);
476
477 LockDisplay(dpy);
478
479 FlushGC(dpy, gc);
480
481 XvGetReq(PutStill, req);
482 req->port = port;
483 req->drawable = d;
484 req->gc = gc->gid;
485 req->vid_x = vx;
486 req->vid_y = vy;
487 req->vid_w = vw;
488 req->vid_h = vh;
489 req->drw_x = dx;
490 req->drw_y = dy;
491 req->drw_w = dw;
492 req->drw_h = dh;
493
494 UnlockDisplay(dpy);
495 SyncHandle();
496
497 return Success;
498}
499
500int
501SDL_NAME(XvGetVideo)(
502 Display *dpy,
503 XvPortID port,
504 Drawable d,
505 GC gc,
506 int vx, int vy,
507 unsigned int vw, unsigned int vh,
508 int dx, int dy,
509 unsigned int dw, unsigned int dh
510){
511 XExtDisplayInfo *info = xv_find_display(dpy);
512 xvGetVideoReq *req;
513
514 XvCheckExtension(dpy, info, XvBadExtension);
515
516 LockDisplay(dpy);
517
518 FlushGC(dpy, gc);
519
520 XvGetReq(GetVideo, req);
521 req->port = port;
522 req->drawable = d;
523 req->gc = gc->gid;
524 req->vid_x = vx;
525 req->vid_y = vy;
526 req->vid_w = vw;
527 req->vid_h = vh;
528 req->drw_x = dx;
529 req->drw_y = dy;
530 req->drw_w = dw;
531 req->drw_h = dh;
532
533 UnlockDisplay(dpy);
534 SyncHandle();
535
536 return Success;
537}
538
539int
540SDL_NAME(XvGetStill)(
541 Display *dpy,
542 XvPortID port,
543 Drawable d,
544 GC gc,
545 int vx, int vy,
546 unsigned int vw, unsigned int vh,
547 int dx, int dy,
548 unsigned int dw, unsigned int dh
549){
550 XExtDisplayInfo *info = xv_find_display(dpy);
551 xvGetStillReq *req;
552
553 XvCheckExtension(dpy, info, XvBadExtension);
554
555 LockDisplay(dpy);
556
557 FlushGC(dpy, gc);
558
559 XvGetReq(GetStill, req);
560 req->port = port;
561 req->drawable = d;
562 req->gc = gc->gid;
563 req->vid_x = vx;
564 req->vid_y = vy;
565 req->vid_w = vw;
566 req->vid_h = vh;
567 req->drw_x = dx;
568 req->drw_y = dy;
569 req->drw_w = dw;
570 req->drw_h = dh;
571
572 UnlockDisplay(dpy);
573 SyncHandle();
574
575 return Success;
576}
577
578int
579SDL_NAME(XvStopVideo)(
580 Display *dpy,
581 XvPortID port,
582 Drawable draw
583){
584 XExtDisplayInfo *info = xv_find_display(dpy);
585 xvStopVideoReq *req;
586
587 XvCheckExtension(dpy, info, XvBadExtension);
588
589 LockDisplay(dpy);
590
591 XvGetReq(StopVideo, req);
592 req->port = port;
593 req->drawable = draw;
594
595 UnlockDisplay(dpy);
596 SyncHandle();
597
598 return Success;
599}
600
601int
602SDL_NAME(XvGrabPort)(
603 Display *dpy,
604 XvPortID port,
605 Time time
606){
607 XExtDisplayInfo *info = xv_find_display(dpy);
608 int result;
609 xvGrabPortReply rep;
610 xvGrabPortReq *req;
611
612 XvCheckExtension(dpy, info, XvBadExtension);
613
614 LockDisplay(dpy);
615
616 XvGetReq(GrabPort, req);
617 req->port = port;
618 req->time = time;
619
620 if (_XReply (dpy, (xReply *) &rep, 0, xTrue) == 0)
621 rep.result = GrabSuccess;
622
623 result = rep.result;
624
625 UnlockDisplay(dpy);
626 SyncHandle();
627
628 return result;
629}
630
631int
632SDL_NAME(XvUngrabPort)(
633 Display *dpy,
634 XvPortID port,
635 Time time
636){
637 XExtDisplayInfo *info = xv_find_display(dpy);
638 xvUngrabPortReq *req;
639
640 XvCheckExtension(dpy, info, XvBadExtension);
641
642 LockDisplay(dpy);
643
644 XvGetReq(UngrabPort, req);
645 req->port = port;
646 req->time = time;
647
648 UnlockDisplay(dpy);
649 SyncHandle();
650
651 return Success;
652}
653
654int
655SDL_NAME(XvSelectVideoNotify)(
656 Display *dpy,
657 Drawable drawable,
658 Bool onoff
659){
660 XExtDisplayInfo *info = xv_find_display(dpy);
661 xvSelectVideoNotifyReq *req;
662
663 XvCheckExtension(dpy, info, XvBadExtension);
664
665 LockDisplay(dpy);
666
667 XvGetReq(SelectVideoNotify, req);
668 req->drawable = drawable;
669 req->onoff = onoff;
670
671 UnlockDisplay(dpy);
672 SyncHandle();
673
674 return Success;
675}
676
677int
678SDL_NAME(XvSelectPortNotify)(
679 Display *dpy,
680 XvPortID port,
681 Bool onoff
682){
683 XExtDisplayInfo *info = xv_find_display(dpy);
684 xvSelectPortNotifyReq *req;
685
686 XvCheckExtension(dpy, info, XvBadExtension);
687
688 LockDisplay(dpy);
689
690 XvGetReq(SelectPortNotify, req);
691 req->port = port;
692 req->onoff = onoff;
693
694 UnlockDisplay(dpy);
695 SyncHandle();
696
697 return Success;
698}
699
700int
701SDL_NAME(XvSetPortAttribute) (
702 Display *dpy,
703 XvPortID port,
704 Atom attribute,
705 int value
706)
707{
708 XExtDisplayInfo *info = xv_find_display(dpy);
709 xvSetPortAttributeReq *req;
710
711 XvCheckExtension(dpy, info, XvBadExtension);
712
713 LockDisplay(dpy);
714
715 XvGetReq(SetPortAttribute, req);
716 req->port = port;
717 req->attribute = attribute;
718 req->value = value;
719
720 UnlockDisplay(dpy);
721 SyncHandle();
722
723 return (Success);
724}
725
726int
727SDL_NAME(XvGetPortAttribute) (
728 Display *dpy,
729 XvPortID port,
730 Atom attribute,
731 int *p_value
732)
733{
734 XExtDisplayInfo *info = xv_find_display(dpy);
735 xvGetPortAttributeReq *req;
736 xvGetPortAttributeReply rep;
737
738 XvCheckExtension(dpy, info, XvBadExtension);
739
740 LockDisplay(dpy);
741
742 XvGetReq(GetPortAttribute, req);
743 req->port = port;
744 req->attribute = attribute;
745
746 /* READ THE REPLY */
747
748 if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) {
749 UnlockDisplay(dpy);
750 SyncHandle();
751 return(XvBadReply);
752 }
753
754 *p_value = rep.value;
755
756 UnlockDisplay(dpy);
757 SyncHandle();
758
759 return (Success);
760}
761
762int
763SDL_NAME(XvQueryBestSize)(
764 Display *dpy,
765 XvPortID port,
766 Bool motion,
767 unsigned int vid_w,
768 unsigned int vid_h,
769 unsigned int drw_w,
770 unsigned int drw_h,
771 unsigned int *p_actual_width,
772 unsigned int *p_actual_height
773)
774{
775 XExtDisplayInfo *info = xv_find_display(dpy);
776 xvQueryBestSizeReq *req;
777 xvQueryBestSizeReply rep;
778
779 XvCheckExtension(dpy, info, XvBadExtension);
780
781 LockDisplay(dpy);
782
783 XvGetReq(QueryBestSize, req);
784 req->port = port;
785 req->motion = motion;
786 req->vid_w = vid_w;
787 req->vid_h = vid_h;
788 req->drw_w = drw_w;
789 req->drw_h = drw_h;
790
791 /* READ THE REPLY */
792
793 if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) {
794 UnlockDisplay(dpy);
795 SyncHandle();
796 return(XvBadReply);
797 }
798
799 *p_actual_width = rep.actual_width;
800 *p_actual_height = rep.actual_height;
801
802 UnlockDisplay(dpy);
803 SyncHandle();
804
805 return (Success);
806}
807
808
809SDL_NAME(XvAttribute)*
810SDL_NAME(XvQueryPortAttributes)(Display *dpy, XvPortID port, int *num)
811{
812 XExtDisplayInfo *info = xv_find_display(dpy);
813 xvQueryPortAttributesReq *req;
814 xvQueryPortAttributesReply rep;
815 SDL_NAME(XvAttribute) *ret = NULL;
816
817 *num = 0;
818
819 XvCheckExtension(dpy, info, NULL);
820
821 LockDisplay(dpy);
822
823 XvGetReq(QueryPortAttributes, req);
824 req->port = port;
825
826 /* READ THE REPLY */
827
828 if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) {
829 UnlockDisplay(dpy);
830 SyncHandle();
831 return ret;
832 }
833
834 if(rep.num_attributes) {
835 int size = (rep.num_attributes * sizeof(SDL_NAME(XvAttribute))) + rep.text_size;
836
837 if((ret = Xmalloc(size))) {
838 char* marker = (char*)(&ret[rep.num_attributes]);
839 xvAttributeInfo Info;
840 int i;
841
842 for(i = 0; i < rep.num_attributes; i++) {
843 _XRead(dpy, (char*)(&Info), sz_xvAttributeInfo);
844 ret[i].flags = (int)Info.flags;
845 ret[i].min_value = Info.min;
846 ret[i].max_value = Info.max;
847 ret[i].name = marker;
848 _XRead(dpy, marker, Info.size);
849 marker += Info.size;
850 (*num)++;
851 }
852 } else
853 _XEatData(dpy, rep.length << 2);
854 }
855
856 UnlockDisplay(dpy);
857 SyncHandle();
858
859 return ret;
860}
861
862SDL_NAME(XvImageFormatValues) * SDL_NAME(XvListImageFormats) (
863 Display *dpy,
864 XvPortID port,
865 int *num
866){
867 XExtDisplayInfo *info = xv_find_display(dpy);
868 xvListImageFormatsReq *req;
869 xvListImageFormatsReply rep;
870 SDL_NAME(XvImageFormatValues) *ret = NULL;
871
872 *num = 0;
873
874 XvCheckExtension(dpy, info, NULL);
875
876 LockDisplay(dpy);
877
878 XvGetReq(ListImageFormats, req);
879 req->port = port;
880
881 /* READ THE REPLY */
882
883 if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) {
884 UnlockDisplay(dpy);
885 SyncHandle();
886 return NULL;
887 }
888
889 if(rep.num_formats) {
890 int size = (rep.num_formats * sizeof(SDL_NAME(XvImageFormatValues)));
891
892 if((ret = Xmalloc(size))) {
893 xvImageFormatInfo Info;
894 int i;
895
896 for(i = 0; i < rep.num_formats; i++) {
897 _XRead(dpy, (char*)(&Info), sz_xvImageFormatInfo);
898 ret[i].id = Info.id;
899 ret[i].type = Info.type;
900 ret[i].byte_order = Info.byte_order;
901 memcpy(&(ret[i].guid[0]), &(Info.guid[0]), 16);
902 ret[i].bits_per_pixel = Info.bpp;
903 ret[i].format = Info.format;
904 ret[i].num_planes = Info.num_planes;
905 ret[i].depth = Info.depth;
906 ret[i].red_mask = Info.red_mask;
907 ret[i].green_mask = Info.green_mask;
908 ret[i].blue_mask = Info.blue_mask;
909 ret[i].y_sample_bits = Info.y_sample_bits;
910 ret[i].u_sample_bits = Info.u_sample_bits;
911 ret[i].v_sample_bits = Info.v_sample_bits;
912 ret[i].horz_y_period = Info.horz_y_period;
913 ret[i].horz_u_period = Info.horz_u_period;
914 ret[i].horz_v_period = Info.horz_v_period;
915 ret[i].vert_y_period = Info.vert_y_period;
916 ret[i].vert_u_period = Info.vert_u_period;
917 ret[i].vert_v_period = Info.vert_v_period;
918 memcpy(&(ret[i].component_order[0]), &(Info.comp_order[0]), 32);
919 ret[i].scanline_order = Info.scanline_order;
920 (*num)++;
921 }
922 } else
923 _XEatData(dpy, rep.length << 2);
924 }
925
926 UnlockDisplay(dpy);
927 SyncHandle();
928
929 return ret;
930}
931
932SDL_NAME(XvImage) * SDL_NAME(XvCreateImage) (
933 Display *dpy,
934 XvPortID port,
935 int id,
936 char *data,
937 int width,
938 int height
939) {
940 XExtDisplayInfo *info = xv_find_display(dpy);
941 xvQueryImageAttributesReq *req;
942 xvQueryImageAttributesReply rep;
943 SDL_NAME(XvImage) *ret = NULL;
944
945 XvCheckExtension(dpy, info, NULL);
946
947 LockDisplay(dpy);
948
949 XvGetReq(QueryImageAttributes, req);
950 req->id = id;
951 req->port = port;
952 req->width = width;
953 req->height = height;
954
955 /* READ THE REPLY */
956
957 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
958 UnlockDisplay(dpy);
959 SyncHandle();
960 return NULL;
961 }
962
963 if((ret = (SDL_NAME(XvImage)*)Xmalloc(sizeof(SDL_NAME(XvImage)) + (rep.num_planes << 3)))) {
964 ret->id = id;
965 ret->width = rep.width;
966 ret->height = rep.height;
967 ret->data_size = rep.data_size;
968 ret->num_planes = rep.num_planes;
969 ret->pitches = (int*)(&ret[1]);
970 ret->offsets = ret->pitches + rep.num_planes;
971 ret->data = data;
972 ret->obdata = NULL;
973 _XRead(dpy, (char*)(ret->pitches), rep.num_planes << 2);
974 _XRead(dpy, (char*)(ret->offsets), rep.num_planes << 2);
975 } else
976 _XEatData(dpy, rep.length << 2);
977
978 UnlockDisplay(dpy);
979 SyncHandle();
980 return ret;
981}
982
983SDL_NAME(XvImage) * SDL_NAME(XvShmCreateImage) (
984 Display *dpy,
985 XvPortID port,
986 int id,
987 char *data,
988 int width,
989 int height,
990 XShmSegmentInfo *shminfo
991){
992 SDL_NAME(XvImage) *ret;
993
994 ret = SDL_NAME(XvCreateImage)(dpy, port, id, data, width, height);
995
996 if(ret) ret->obdata = (XPointer)shminfo;
997
998 return ret;
999}
1000
1001int SDL_NAME(XvPutImage) (
1002 Display *dpy,
1003 XvPortID port,
1004 Drawable d,
1005 GC gc,
1006 SDL_NAME(XvImage) *image,
1007 int src_x,
1008 int src_y,
1009 unsigned int src_w,
1010 unsigned int src_h,
1011 int dest_x,
1012 int dest_y,
1013 unsigned int dest_w,
1014 unsigned int dest_h
1015){
1016 XExtDisplayInfo *info = xv_find_display(dpy);
1017 xvPutImageReq *req;
1018 int len;
1019
1020 XvCheckExtension(dpy, info, XvBadExtension);
1021
1022 LockDisplay(dpy);
1023
1024 FlushGC(dpy, gc);
1025
1026 XvGetReq(PutImage, req);
1027
1028 req->port = port;
1029 req->drawable = d;
1030 req->gc = gc->gid;
1031 req->id = image->id;
1032 req->src_x = src_x;
1033 req->src_y = src_y;
1034 req->src_w = src_w;
1035 req->src_h = src_h;
1036 req->drw_x = dest_x;
1037 req->drw_y = dest_y;
1038 req->drw_w = dest_w;
1039 req->drw_h = dest_h;
1040 req->width = image->width;
1041 req->height = image->height;
1042
1043 len = (image->data_size + 3) >> 2;
1044 SetReqLen(req, len, len);
1045
1046 /* Yes it's kindof lame that we are sending the whole thing,
1047 but for video all of it may be needed even if displaying
1048 only a subsection, and I don't want to go through the
1049 trouble of creating subregions to send */
1050 Data(dpy, (char *)image->data, image->data_size);
1051
1052 UnlockDisplay(dpy);
1053 SyncHandle();
1054
1055 return Success;
1056}
1057
1058int SDL_NAME(XvShmPutImage) (
1059 Display *dpy,
1060 XvPortID port,
1061 Drawable d,
1062 GC gc,
1063 SDL_NAME(XvImage) *image,
1064 int src_x,
1065 int src_y,
1066 unsigned int src_w,
1067 unsigned int src_h,
1068 int dest_x,
1069 int dest_y,
1070 unsigned int dest_w,
1071 unsigned int dest_h,
1072 Bool send_event
1073){
1074 XExtDisplayInfo *info = xv_find_display(dpy);
1075 XShmSegmentInfo *shminfo = (XShmSegmentInfo *)image->obdata;
1076 xvShmPutImageReq *req;
1077
1078 XvCheckExtension(dpy, info, XvBadExtension);
1079
1080 LockDisplay(dpy);
1081
1082 FlushGC(dpy, gc);
1083
1084 XvGetReq(ShmPutImage, req);
1085
1086 req->port = port;
1087 req->drawable = d;
1088 req->gc = gc->gid;
1089 req->shmseg = shminfo->shmseg;
1090 req->id = image->id;
1091 req->src_x = src_x;
1092 req->src_y = src_y;
1093 req->src_w = src_w;
1094 req->src_h = src_h;
1095 req->drw_x = dest_x;
1096 req->drw_y = dest_y;
1097 req->drw_w = dest_w;
1098 req->drw_h = dest_h;
1099 req->offset = image->data - shminfo->shmaddr;
1100 req->width = image->width;
1101 req->height = image->height;
1102 req->send_event = send_event;
1103
1104 UnlockDisplay(dpy);
1105 SyncHandle();
1106
1107 return Success;
1108}
1109
1110
1111static Bool
1112xv_wire_to_event(Display *dpy, XEvent *host, xEvent *wire)
1113{
1114 XExtDisplayInfo *info = xv_find_display(dpy);
1115 SDL_NAME(XvEvent) *re = (SDL_NAME(XvEvent) *)host;
1116 xvEvent *event = (xvEvent *)wire;
1117
1118 XvCheckExtension(dpy, info, False);
1119
1120 switch((event->u.u.type & 0x7F) - info->codes->first_event)
1121 {
1122 case XvVideoNotify:
1123 re->xvvideo.type = event->u.u.type & 0x7f;
1124 re->xvvideo.serial =
1125 _XSetLastRequestRead(dpy, (xGenericReply *)event);
1126 re->xvvideo.send_event = ((event->u.u.type & 0x80) != 0);
1127 re->xvvideo.display = dpy;
1128 re->xvvideo.time = event->u.videoNotify.time;
1129 re->xvvideo.reason = event->u.videoNotify.reason;
1130 re->xvvideo.drawable = event->u.videoNotify.drawable;
1131 re->xvvideo.port_id = event->u.videoNotify.port;
1132 break;
1133 case XvPortNotify:
1134 re->xvport.type = event->u.u.type & 0x7f;
1135 re->xvport.serial =
1136 _XSetLastRequestRead(dpy, (xGenericReply *)event);
1137 re->xvport.send_event = ((event->u.u.type & 0x80) != 0);
1138 re->xvport.display = dpy;
1139 re->xvport.time = event->u.portNotify.time;
1140 re->xvport.port_id = event->u.portNotify.port;
1141 re->xvport.attribute = event->u.portNotify.attribute;
1142 re->xvport.value = event->u.portNotify.value;
1143 break;
1144 default:
1145 return False;
1146 }
1147
1148 return (True);
1149}
1150
1151
diff --git a/apps/plugins/sdl/src/video/Xext/Xv/Xvlibint.h b/apps/plugins/sdl/src/video/Xext/Xv/Xvlibint.h
deleted file mode 100644
index 20df706dc7..0000000000
--- a/apps/plugins/sdl/src/video/Xext/Xv/Xvlibint.h
+++ /dev/null
@@ -1,81 +0,0 @@
1/***********************************************************
2Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts,
3and the Massachusetts Institute of Technology, Cambridge, Massachusetts.
4
5 All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Digital or MIT not be
12used in advertising or publicity pertaining to distribution of the
13software without specific, written prior permission.
14
15DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
16ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
17DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
18ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
19WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
20ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
21SOFTWARE.
22
23******************************************************************/
24/* $XFree86: xc/lib/Xv/Xvlibint.h,v 1.5 2001/07/25 15:04:53 dawes Exp $ */
25
26#ifndef XVLIBINT_H
27#define XVLIBINT_H
28/*
29** File:
30**
31** Xvlibint.h --- Xv library internal header file
32**
33** Author:
34**
35** David Carver (Digital Workstation Engineering/Project Athena)
36**
37** Revisions:
38**
39** 01.24.91 Carver
40** - version 1.4 upgrade
41**
42*/
43
44#define NEED_REPLIES
45
46/* Apparently some X11 systems can't include this multiple times... */
47#ifndef SDL_INCLUDED_XLIBINT_H
48#define SDL_INCLUDED_XLIBINT_H 1
49#include <X11/Xlibint.h>
50#endif
51
52#include "../extensions/Xvproto.h"
53#include "../extensions/Xvlib.h"
54
55#if !defined(UNIXCPP)
56#define XvGetReq(name, req) \
57 WORD64ALIGN\
58 if ((dpy->bufptr + SIZEOF(xv##name##Req)) > dpy->bufmax)\
59 _XFlush(dpy);\
60 req = (xv##name##Req *)(dpy->last_req = dpy->bufptr);\
61 req->reqType = info->codes->major_opcode;\
62 req->xvReqType = xv_##name; \
63 req->length = (SIZEOF(xv##name##Req))>>2;\
64 dpy->bufptr += SIZEOF(xv##name##Req);\
65 dpy->request++
66
67#else /* non-ANSI C uses empty comment instead of "##" for token concatenation */
68#define XvGetReq(name, req) \
69 WORD64ALIGN\
70 if ((dpy->bufptr + SIZEOF(xv/**/name/**/Req)) > dpy->bufmax)\
71 _XFlush(dpy);\
72 req = (xv/**/name/**/Req *)(dpy->last_req = dpy->bufptr);\
73 req->reqType = info->codes->major_opcode;\
74 req->xvReqType = xv_/**/name;\
75 req->length = (SIZEOF(xv/**/name/**/Req))>>2;\
76 dpy->bufptr += SIZEOF(xv/**/name/**/Req);\
77 dpy->request++
78#endif
79
80
81#endif /* XVLIBINT_H */
diff --git a/apps/plugins/sdl/src/video/Xext/Xxf86dga/XF86DGA.c b/apps/plugins/sdl/src/video/Xext/Xxf86dga/XF86DGA.c
deleted file mode 100644
index fc729f1257..0000000000
--- a/apps/plugins/sdl/src/video/Xext/Xxf86dga/XF86DGA.c
+++ /dev/null
@@ -1,721 +0,0 @@
1/* $XFree86: xc/lib/Xxf86dga/XF86DGA.c,v 3.19 2001/08/18 02:41:30 dawes Exp $ */
2/*
3
4Copyright (c) 1995 Jon Tombs
5Copyright (c) 1995,1996 The XFree86 Project, Inc
6
7*/
8
9/* THIS IS NOT AN X CONSORTIUM STANDARD */
10
11#ifdef __EMX__ /* needed here to override certain constants in X headers */
12#define INCL_DOS
13#define INCL_DOSIOCTL
14#include <os2.h>
15#endif
16
17#if defined(linux)
18#define HAS_MMAP_ANON
19#include <sys/types.h>
20#include <sys/mman.h>
21/*#include <asm/page.h>*/ /* PAGE_SIZE */
22#define HAS_SC_PAGESIZE /* _SC_PAGESIZE may be an enum for Linux */
23#define HAS_GETPAGESIZE
24#endif /* linux */
25
26#if defined(CSRG_BASED)
27#define HAS_MMAP_ANON
28#define HAS_GETPAGESIZE
29#include <sys/types.h>
30#include <sys/mman.h>
31#endif /* CSRG_BASED */
32
33#if defined(DGUX)
34#define HAS_GETPAGESIZE
35#define MMAP_DEV_ZERO
36#include <sys/types.h>
37#include <sys/mman.h>
38#include <unistd.h>
39#endif /* DGUX */
40
41#if defined(SVR4) && !defined(DGUX)
42#define MMAP_DEV_ZERO
43#include <sys/types.h>
44#include <sys/mman.h>
45#include <unistd.h>
46#endif /* SVR4 && !DGUX */
47
48#if defined(sun) && !defined(SVR4) /* SunOS */
49#define MMAP_DEV_ZERO /* doesn't SunOS have MAP_ANON ?? */
50#define HAS_GETPAGESIZE
51#include <sys/types.h>
52#include <sys/mman.h>
53#endif /* sun && !SVR4 */
54
55#ifdef XNO_SYSCONF
56#undef _SC_PAGESIZE
57#endif
58
59#define NEED_EVENTS
60#define NEED_REPLIES
61
62/* Apparently some X11 systems can't include this multiple times... */
63#ifndef SDL_INCLUDED_XLIBINT_H
64#define SDL_INCLUDED_XLIBINT_H 1
65#include <X11/Xlibint.h>
66#endif
67
68#include "../extensions/xf86dga.h"
69#include "../extensions/xf86dgastr.h"
70#include "../extensions/Xext.h"
71#include "../extensions/extutil.h"
72
73extern XExtDisplayInfo* SDL_NAME(xdga_find_display)(Display*);
74extern char *SDL_NAME(xdga_extension_name);
75
76#define XF86DGACheckExtension(dpy,i,val) \
77 XextCheckExtension (dpy, i, SDL_NAME(xdga_extension_name), val)
78
79/*****************************************************************************
80 * *
81 * public XFree86-DGA Extension routines *
82 * *
83 *****************************************************************************/
84
85Bool SDL_NAME(XF86DGAQueryExtension) (
86 Display *dpy,
87 int *event_basep,
88 int *error_basep
89){
90 return SDL_NAME(XDGAQueryExtension)(dpy, event_basep, error_basep);
91}
92
93Bool SDL_NAME(XF86DGAQueryVersion)(
94 Display* dpy,
95 int* majorVersion,
96 int* minorVersion
97){
98 return SDL_NAME(XDGAQueryVersion)(dpy, majorVersion, minorVersion);
99}
100
101Bool SDL_NAME(XF86DGAGetVideoLL)(
102 Display* dpy,
103 int screen,
104 int *offset,
105 int *width,
106 int *bank_size,
107 int *ram_size
108){
109 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
110 xXF86DGAGetVideoLLReply rep;
111 xXF86DGAGetVideoLLReq *req;
112
113 XF86DGACheckExtension (dpy, info, False);
114
115 LockDisplay(dpy);
116 GetReq(XF86DGAGetVideoLL, req);
117 req->reqType = info->codes->major_opcode;
118 req->dgaReqType = X_XF86DGAGetVideoLL;
119 req->screen = screen;
120 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
121 UnlockDisplay(dpy);
122 SyncHandle();
123 return False;
124 }
125
126 *offset = /*(char *)*/rep.offset;
127 *width = rep.width;
128 *bank_size = rep.bank_size;
129 *ram_size = rep.ram_size;
130
131 UnlockDisplay(dpy);
132 SyncHandle();
133 return True;
134}
135
136
137Bool SDL_NAME(XF86DGADirectVideoLL)(
138 Display* dpy,
139 int screen,
140 int enable
141){
142 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
143 xXF86DGADirectVideoReq *req;
144
145 XF86DGACheckExtension (dpy, info, False);
146
147 LockDisplay(dpy);
148 GetReq(XF86DGADirectVideo, req);
149 req->reqType = info->codes->major_opcode;
150 req->dgaReqType = X_XF86DGADirectVideo;
151 req->screen = screen;
152 req->enable = enable;
153 UnlockDisplay(dpy);
154 SyncHandle();
155 XSync(dpy,False);
156 return True;
157}
158
159Bool SDL_NAME(XF86DGAGetViewPortSize)(
160 Display* dpy,
161 int screen,
162 int *width,
163 int *height
164){
165 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
166 xXF86DGAGetViewPortSizeReply rep;
167 xXF86DGAGetViewPortSizeReq *req;
168
169 XF86DGACheckExtension (dpy, info, False);
170
171 LockDisplay(dpy);
172 GetReq(XF86DGAGetViewPortSize, req);
173 req->reqType = info->codes->major_opcode;
174 req->dgaReqType = X_XF86DGAGetViewPortSize;
175 req->screen = screen;
176 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
177 UnlockDisplay(dpy);
178 SyncHandle();
179 return False;
180 }
181
182 *width = rep.width;
183 *height = rep.height;
184
185 UnlockDisplay(dpy);
186 SyncHandle();
187 return True;
188}
189
190
191Bool SDL_NAME(XF86DGASetViewPort)(
192 Display* dpy,
193 int screen,
194 int x,
195 int y
196){
197 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
198 xXF86DGASetViewPortReq *req;
199
200 XF86DGACheckExtension (dpy, info, False);
201
202 LockDisplay(dpy);
203 GetReq(XF86DGASetViewPort, req);
204 req->reqType = info->codes->major_opcode;
205 req->dgaReqType = X_XF86DGASetViewPort;
206 req->screen = screen;
207 req->x = x;
208 req->y = y;
209 UnlockDisplay(dpy);
210 SyncHandle();
211 XSync(dpy,False);
212 return True;
213}
214
215
216Bool SDL_NAME(XF86DGAGetVidPage)(
217 Display* dpy,
218 int screen,
219 int *vpage
220){
221 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
222 xXF86DGAGetVidPageReply rep;
223 xXF86DGAGetVidPageReq *req;
224
225 XF86DGACheckExtension (dpy, info, False);
226
227 LockDisplay(dpy);
228 GetReq(XF86DGAGetVidPage, req);
229 req->reqType = info->codes->major_opcode;
230 req->dgaReqType = X_XF86DGAGetVidPage;
231 req->screen = screen;
232 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
233 UnlockDisplay(dpy);
234 SyncHandle();
235 return False;
236 }
237
238 *vpage = rep.vpage;
239 UnlockDisplay(dpy);
240 SyncHandle();
241 return True;
242}
243
244
245Bool SDL_NAME(XF86DGASetVidPage)(
246 Display* dpy,
247 int screen,
248 int vpage
249){
250 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
251 xXF86DGASetVidPageReq *req;
252
253 XF86DGACheckExtension (dpy, info, False);
254
255 LockDisplay(dpy);
256 GetReq(XF86DGASetVidPage, req);
257 req->reqType = info->codes->major_opcode;
258 req->dgaReqType = X_XF86DGASetVidPage;
259 req->screen = screen;
260 req->vpage = vpage;
261 UnlockDisplay(dpy);
262 SyncHandle();
263 XSync(dpy,False);
264 return True;
265}
266
267Bool SDL_NAME(XF86DGAInstallColormap)(
268 Display* dpy,
269 int screen,
270 Colormap cmap
271){
272 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
273 xXF86DGAInstallColormapReq *req;
274
275 XF86DGACheckExtension (dpy, info, False);
276
277 LockDisplay(dpy);
278 GetReq(XF86DGAInstallColormap, req);
279 req->reqType = info->codes->major_opcode;
280 req->dgaReqType = X_XF86DGAInstallColormap;
281 req->screen = screen;
282 req->id = cmap;
283 UnlockDisplay(dpy);
284 SyncHandle();
285 XSync(dpy,False);
286 return True;
287}
288
289Bool SDL_NAME(XF86DGAQueryDirectVideo)(
290 Display *dpy,
291 int screen,
292 int *flags
293){
294 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
295 xXF86DGAQueryDirectVideoReply rep;
296 xXF86DGAQueryDirectVideoReq *req;
297
298 XF86DGACheckExtension (dpy, info, False);
299
300 LockDisplay(dpy);
301 GetReq(XF86DGAQueryDirectVideo, req);
302 req->reqType = info->codes->major_opcode;
303 req->dgaReqType = X_XF86DGAQueryDirectVideo;
304 req->screen = screen;
305 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
306 UnlockDisplay(dpy);
307 SyncHandle();
308 return False;
309 }
310 *flags = rep.flags;
311 UnlockDisplay(dpy);
312 SyncHandle();
313 return True;
314}
315
316Bool SDL_NAME(XF86DGAViewPortChanged)(
317 Display *dpy,
318 int screen,
319 int n
320){
321 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
322 xXF86DGAViewPortChangedReply rep;
323 xXF86DGAViewPortChangedReq *req;
324
325 XF86DGACheckExtension (dpy, info, False);
326
327 LockDisplay(dpy);
328 GetReq(XF86DGAViewPortChanged, req);
329 req->reqType = info->codes->major_opcode;
330 req->dgaReqType = X_XF86DGAViewPortChanged;
331 req->screen = screen;
332 req->n = n;
333 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
334 UnlockDisplay(dpy);
335 SyncHandle();
336 return False;
337 }
338 UnlockDisplay(dpy);
339 SyncHandle();
340 return rep.result;
341}
342
343
344
345/* Helper functions */
346
347#include <X11/Xmd.h>
348#include "../extensions/xf86dga.h"
349#include <stdlib.h>
350#include <stdio.h>
351#include <fcntl.h>
352#if defined(ISC)
353# define HAS_SVR3_MMAP
354# include <sys/types.h>
355# include <errno.h>
356
357# include <sys/at_ansi.h>
358# include <sys/kd.h>
359
360# include <sys/sysmacros.h>
361# include <sys/immu.h>
362# include <sys/region.h>
363
364# include <sys/mmap.h>
365#else
366# if !defined(Lynx)
367# if !defined(__EMX__)
368# include <sys/mman.h>
369# endif
370# else
371# include <sys/types.h>
372# include <errno.h>
373# include <smem.h>
374# endif
375#endif
376#include <sys/wait.h>
377#include <signal.h>
378#include <unistd.h>
379
380#if defined(SVR4) && !defined(sun) && !defined(SCO325)
381#define DEV_MEM "/dev/pmem"
382#elif defined(SVR4) && defined(sun)
383#define DEV_MEM "/dev/xsvc"
384#else
385#define DEV_MEM "/dev/mem"
386#endif
387
388typedef struct {
389 unsigned long physaddr; /* actual requested physical address */
390 unsigned long size; /* actual requested map size */
391 unsigned long delta; /* delta to account for page alignment */
392 void * vaddr; /* mapped address, without the delta */
393 int refcount; /* reference count */
394} MapRec, *MapPtr;
395
396typedef struct {
397 Display * display;
398 int screen;
399 MapPtr map;
400} ScrRec, *ScrPtr;
401
402static int mapFd = -1;
403static int numMaps = 0;
404static int numScrs = 0;
405static MapPtr *mapList = NULL;
406static ScrPtr *scrList = NULL;
407
408static MapPtr
409AddMap(void)
410{
411 MapPtr *old;
412
413 old = mapList;
414 mapList = realloc(mapList, sizeof(MapPtr) * (numMaps + 1));
415 if (!mapList) {
416 mapList = old;
417 return NULL;
418 }
419 mapList[numMaps] = malloc(sizeof(MapRec));
420 if (!mapList[numMaps])
421 return NULL;
422 return mapList[numMaps++];
423}
424
425static ScrPtr
426AddScr(void)
427{
428 ScrPtr *old;
429
430 old = scrList;
431 scrList = realloc(scrList, sizeof(ScrPtr) * (numScrs + 1));
432 if (!scrList) {
433 scrList = old;
434 return NULL;
435 }
436 scrList[numScrs] = malloc(sizeof(ScrRec));
437 if (!scrList[numScrs])
438 return NULL;
439 return scrList[numScrs++];
440}
441
442static MapPtr
443FindMap(unsigned long address, unsigned long size)
444{
445 int i;
446
447 for (i = 0; i < numMaps; i++) {
448 if (mapList[i]->physaddr == address &&
449 mapList[i]->size == size)
450 return mapList[i];
451 }
452 return NULL;
453}
454
455static ScrPtr
456FindScr(Display *display, int screen)
457{
458 int i;
459
460 for (i = 0; i < numScrs; i++) {
461 if (scrList[i]->display == display &&
462 scrList[i]->screen == screen)
463 return scrList[i];
464 }
465 return NULL;
466}
467
468static void *
469MapPhysAddress(unsigned long address, unsigned long size)
470{
471 unsigned long offset, delta;
472 int pagesize = -1;
473 void *vaddr;
474 MapPtr mp;
475#if defined(ISC) && defined(HAS_SVR3_MMAP)
476 struct kd_memloc mloc;
477#elif defined(__EMX__)
478 APIRET rc;
479 ULONG action;
480 HFILE hfd;
481#endif
482
483 if ((mp = FindMap(address, size))) {
484 mp->refcount++;
485 return (void *)((unsigned long)mp->vaddr + mp->delta);
486 }
487
488#if defined(_SC_PAGESIZE) && defined(HAS_SC_PAGESIZE)
489 pagesize = sysconf(_SC_PAGESIZE);
490#endif
491#ifdef _SC_PAGE_SIZE
492 if (pagesize == -1)
493 pagesize = sysconf(_SC_PAGE_SIZE);
494#endif
495#ifdef HAS_GETPAGESIZE
496 if (pagesize == -1)
497 pagesize = getpagesize();
498#endif
499#ifdef PAGE_SIZE
500 if (pagesize == -1)
501 pagesize = PAGE_SIZE;
502#endif
503 if (pagesize == -1)
504 pagesize = 4096;
505
506 delta = address % pagesize;
507 offset = address - delta;
508
509#if defined(ISC) && defined(HAS_SVR3_MMAP)
510 if (mapFd < 0) {
511 if ((mapFd = open("/dev/mmap", O_RDWR)) < 0)
512 return NULL;
513 }
514 mloc.vaddr = (char *)0;
515 mloc.physaddr = (char *)offset;
516 mloc.length = size + delta;
517 mloc.ioflg=1;
518
519 if ((vaddr = (void *)ioctl(mapFd, MAP, &mloc)) == (void *)-1)
520 return NULL;
521#elif defined (__EMX__)
522 /*
523 * Dragon warning here! /dev/pmap$ is never closed, except on progam exit.
524 * Consecutive calling of this routine will make PMAP$ driver run out
525 * of memory handles. Some umap/close mechanism should be provided
526 */
527
528 rc = DosOpen("/dev/pmap$", &hfd, &action, 0, FILE_NORMAL, FILE_OPEN,
529 OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE, (PEAOP2)NULL);
530 if (rc != 0)
531 return NULL;
532 {
533 struct map_ioctl {
534 union {
535 ULONG phys;
536 void* user;
537 } a;
538 ULONG size;
539 } pmap,dmap;
540 ULONG plen,dlen;
541#define XFREE86_PMAP 0x76
542#define PMAP_MAP 0x44
543
544 pmap.a.phys = offset;
545 pmap.size = size + delta;
546 rc = DosDevIOCtl(hfd, XFREE86_PMAP, PMAP_MAP,
547 (PULONG)&pmap, sizeof(pmap), &plen,
548 (PULONG)&dmap, sizeof(dmap), &dlen);
549 if (rc == 0) {
550 vaddr = dmap.a.user;
551 }
552 }
553 if (rc != 0)
554 return NULL;
555#elif defined (Lynx)
556 vaddr = (void *)smem_create("XF86DGA", (char *)offset,
557 size + delta, SM_READ|SM_WRITE);
558#else
559#ifndef MAP_FILE
560#define MAP_FILE 0
561#endif
562 if (mapFd < 0) {
563 if ((mapFd = open(DEV_MEM, O_RDWR)) < 0)
564 return NULL;
565 }
566 vaddr = (void *)mmap(NULL, size + delta, PROT_READ | PROT_WRITE,
567 MAP_FILE | MAP_SHARED, mapFd, (off_t)offset);
568 if (vaddr == (void *)-1)
569 return NULL;
570#endif
571
572 if (!vaddr) {
573 if (!(mp = AddMap()))
574 return NULL;
575 mp->physaddr = address;
576 mp->size = size;
577 mp->delta = delta;
578 mp->vaddr = vaddr;
579 mp->refcount = 1;
580 }
581 return (void *)((unsigned long)vaddr + delta);
582}
583
584/*
585 * Still need to find a clean way of detecting the death of a DGA app
586 * and returning things to normal - Jon
587 * This is here to help debugging without rebooting... Also C-A-BS
588 * should restore text mode.
589 */
590
591int
592SDL_NAME(XF86DGAForkApp)(int screen)
593{
594 pid_t pid;
595 int status;
596 int i;
597
598 /* fork the app, parent hangs around to clean up */
599 if ((pid = fork()) > 0) {
600 ScrPtr sp;
601
602 waitpid(pid, &status, 0);
603 for (i = 0; i < numScrs; i++) {
604 sp = scrList[i];
605 SDL_NAME(XF86DGADirectVideoLL)(sp->display, sp->screen, 0);
606 XSync(sp->display, False);
607 }
608 if (WIFEXITED(status))
609 _exit(0);
610 else
611 _exit(-1);
612 }
613 return pid;
614}
615
616
617Bool
618SDL_NAME(XF86DGADirectVideo)(
619 Display *dis,
620 int screen,
621 int enable
622){
623 ScrPtr sp;
624 MapPtr mp = NULL;
625
626 if ((sp = FindScr(dis, screen)))
627 mp = sp->map;
628
629 if (enable & XF86DGADirectGraphics) {
630#if !defined(ISC) && !defined(HAS_SVR3_MMAP) && !defined(Lynx) \
631 && !defined(__EMX__)
632 if (mp && mp->vaddr)
633 mprotect(mp->vaddr, mp->size + mp->delta, PROT_READ | PROT_WRITE);
634#endif
635 } else {
636#if !defined(ISC) && !defined(HAS_SVR3_MMAP) && !defined(Lynx) \
637 && !defined(__EMX__)
638 if (mp && mp->vaddr)
639 mprotect(mp->vaddr, mp->size + mp->delta, PROT_READ);
640#elif defined(Lynx)
641 /* XXX this doesn't allow enable after disable */
642 smem_create(NULL, mp->vaddr, mp->size + mp->delta, SM_DETACH);
643 smem_remove("XF86DGA");
644#endif
645 }
646
647 SDL_NAME(XF86DGADirectVideoLL)(dis, screen, enable);
648 return 1;
649}
650
651
652static void
653XF86cleanup(int sig)
654{
655 ScrPtr sp;
656 int i;
657 static char beenhere = 0;
658
659 if (beenhere)
660 _exit(3);
661 beenhere = 1;
662
663 for (i = 0; i < numScrs; i++) {
664 sp = scrList[i];
665 SDL_NAME(XF86DGADirectVideo)(sp->display, sp->screen, 0);
666 XSync(sp->display, False);
667 }
668 _exit(3);
669}
670
671Bool
672SDL_NAME(XF86DGAGetVideo)(
673 Display *dis,
674 int screen,
675 char **addr,
676 int *width,
677 int *bank,
678 int *ram
679){
680 /*unsigned long*/ int offset;
681 static int beenHere = 0;
682 ScrPtr sp;
683 MapPtr mp;
684
685 if (!(sp = FindScr(dis, screen))) {
686 if (!(sp = AddScr())) {
687 fprintf(stderr, "XF86DGAGetVideo: malloc failure\n");
688 exit(-2);
689 }
690 sp->display = dis;
691 sp->screen = screen;
692 sp->map = NULL;
693 }
694
695 SDL_NAME(XF86DGAGetVideoLL)(dis, screen , &offset, width, bank, ram);
696
697 *addr = MapPhysAddress(offset, *bank);
698 if (*addr == NULL) {
699 fprintf(stderr, "XF86DGAGetVideo: failed to map video memory (%s)\n",
700 strerror(errno));
701 exit(-2);
702 }
703
704 if ((mp = FindMap(offset, *bank)))
705 sp->map = mp;
706
707 if (!beenHere) {
708 beenHere = 1;
709 atexit((void(*)(void))XF86cleanup);
710 /* one shot XF86cleanup attempts */
711 signal(SIGSEGV, XF86cleanup);
712#ifdef SIGBUS
713 signal(SIGBUS, XF86cleanup);
714#endif
715 signal(SIGHUP, XF86cleanup);
716 signal(SIGFPE, XF86cleanup);
717 }
718
719 return 1;
720}
721
diff --git a/apps/plugins/sdl/src/video/Xext/Xxf86dga/XF86DGA2.c b/apps/plugins/sdl/src/video/Xext/Xxf86dga/XF86DGA2.c
deleted file mode 100644
index 11d4fddc6a..0000000000
--- a/apps/plugins/sdl/src/video/Xext/Xxf86dga/XF86DGA2.c
+++ /dev/null
@@ -1,993 +0,0 @@
1/* $XFree86: xc/lib/Xxf86dga/XF86DGA2.c,v 1.18 2001/08/17 13:27:51 dawes Exp $ */
2/*
3
4Copyright (c) 1995 Jon Tombs
5Copyright (c) 1995,1996 The XFree86 Project, Inc
6
7*/
8
9/* THIS IS NOT AN X CONSORTIUM STANDARD */
10
11#ifdef __EMX__ /* needed here to override certain constants in X headers */
12#define INCL_DOS
13#define INCL_DOSIOCTL
14#include <os2.h>
15#endif
16
17#define NEED_EVENTS
18#define NEED_REPLIES
19
20/* Apparently some X11 systems can't include this multiple times... */
21#ifndef SDL_INCLUDED_XLIBINT_H
22#define SDL_INCLUDED_XLIBINT_H 1
23#include <X11/Xlibint.h>
24#endif
25
26#include "../extensions/xf86dga.h"
27#include "../extensions/xf86dgastr.h"
28#include "../extensions/Xext.h"
29#include "../extensions/extutil.h"
30#include <stdio.h>
31
32#if defined(ENABLE_FBCON) /* Needed for framebuffer console support */
33#include <sys/ioctl.h>
34#include <linux/fb.h>
35#endif
36
37/* If you change this, change the Bases[] array below as well */
38#define MAX_HEADS 16
39
40char *SDL_NAME(xdga_extension_name) = XF86DGANAME;
41
42static XExtensionInfo _xdga_info_data;
43static XExtensionInfo *xdga_info = &_xdga_info_data;
44
45
46Bool SDL_NAME(XDGAMapFramebuffer)(int, char *, unsigned char*, CARD32, CARD32, CARD32);
47void SDL_NAME(XDGAUnmapFramebuffer)(int);
48unsigned char* SDL_NAME(XDGAGetMappedMemory)(int);
49
50#define XDGACheckExtension(dpy,i,val) \
51 XextCheckExtension (dpy, i, SDL_NAME(xdga_extension_name), val)
52
53/*****************************************************************************
54 * *
55 * private utility routines *
56 * *
57 *****************************************************************************/
58
59static int xdga_close_display(Display *dpy, XExtCodes *codes);
60static Bool xdga_wire_to_event(Display *dpy, XEvent *event, xEvent *wire_ev);
61static Status xdga_event_to_wire(Display *dpy, XEvent *event, xEvent *wire_ev);
62
63static XExtensionHooks xdga_extension_hooks = {
64 NULL, /* create_gc */
65 NULL, /* copy_gc */
66 NULL, /* flush_gc */
67 NULL, /* free_gc */
68 NULL, /* create_font */
69 NULL, /* free_font */
70 xdga_close_display, /* close_display */
71 xdga_wire_to_event, /* wire_to_event */
72 xdga_event_to_wire, /* event_to_wire */
73 NULL, /* error */
74 NULL, /* error_string */
75};
76
77static XEXT_GENERATE_CLOSE_DISPLAY (xdga_close_display, xdga_info)
78
79
80XEXT_GENERATE_FIND_DISPLAY (SDL_NAME(xdga_find_display), xdga_info,
81 "XFree86-DGA",
82 &xdga_extension_hooks,
83 0, NULL)
84
85
86static Status
87xdga_event_to_wire(
88 Display *dpy,
89 XEvent *event,
90 xEvent *wire_ev
91){
92 return True;
93}
94
95static Bool
96xdga_wire_to_event(
97 Display *dpy,
98 XEvent *event,
99 xEvent *wire_ev
100){
101 dgaEvent *wire = (dgaEvent *) wire_ev;
102 SDL_NAME(XDGAButtonEvent) *bevent;
103 SDL_NAME(XDGAKeyEvent) *kevent;
104 SDL_NAME(XDGAMotionEvent) *mevent;
105 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
106
107 XDGACheckExtension (dpy, info, False);
108
109 switch((wire->u.u.type & 0x7f) - info->codes->first_event) {
110 case MotionNotify:
111 mevent = (SDL_NAME(XDGAMotionEvent)*)event;
112 mevent->type = wire->u.u.type & 0x7F;
113 mevent->serial = _XSetLastRequestRead(dpy, (xGenericReply *)wire);
114 mevent->display = dpy;
115 mevent->screen = wire->u.event.screen;
116 mevent->time = wire->u.event.time;
117 mevent->state = wire->u.event.state;
118 mevent->dx = wire->u.event.dx;
119 mevent->dy = wire->u.event.dy;
120 return True;
121 case ButtonPress:
122 case ButtonRelease:
123 bevent = (SDL_NAME(XDGAButtonEvent)*)event;
124 bevent->type = wire->u.u.type & 0x7F;
125 bevent->serial = _XSetLastRequestRead(dpy, (xGenericReply *)wire);
126 bevent->display = dpy;
127 bevent->screen = wire->u.event.screen;
128 bevent->time = wire->u.event.time;
129 bevent->state = wire->u.event.state;
130 bevent->button = wire->u.u.detail;
131 return True;
132 case KeyPress:
133 case KeyRelease:
134 kevent = (SDL_NAME(XDGAKeyEvent)*)event;
135 kevent->type = wire->u.u.type & 0x7F;
136 kevent->serial = _XSetLastRequestRead(dpy, (xGenericReply *)wire);
137 kevent->display = dpy;
138 kevent->screen = wire->u.event.screen;
139 kevent->time = wire->u.event.time;
140 kevent->state = wire->u.event.state;
141 kevent->keycode = wire->u.u.detail;
142 return True;
143 }
144
145 return False;
146}
147
148
149Bool SDL_NAME(XDGAQueryExtension) (
150 Display *dpy,
151 int *event_basep,
152 int *error_basep
153){
154 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
155
156 if (XextHasExtension(info)) {
157 *event_basep = info->codes->first_event;
158 *error_basep = info->codes->first_error;
159 return True;
160 } else {
161 return False;
162 }
163}
164
165
166Bool SDL_NAME(XDGAQueryVersion)(
167 Display *dpy,
168 int *majorVersion,
169 int *minorVersion
170){
171 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
172 xXDGAQueryVersionReply rep;
173 xXDGAQueryVersionReq *req;
174
175 XDGACheckExtension (dpy, info, False);
176
177 LockDisplay(dpy);
178 GetReq(XDGAQueryVersion, req);
179 req->reqType = info->codes->major_opcode;
180 req->dgaReqType = X_XDGAQueryVersion;
181 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
182 UnlockDisplay(dpy);
183 SyncHandle();
184 return False;
185 }
186 *majorVersion = rep.majorVersion;
187 *minorVersion = rep.minorVersion;
188 UnlockDisplay(dpy);
189 SyncHandle();
190 if (*majorVersion >= 2)
191 {
192 int i, j;
193
194 for (i = 0, j = info->codes->first_event;
195 i < XF86DGANumberEvents;
196 i++, j++)
197 {
198 XESetWireToEvent(dpy, j, xdga_wire_to_event);
199 XESetEventToWire(dpy, j, xdga_event_to_wire);
200 }
201 SDL_NAME(XDGASetClientVersion)(dpy);
202 }
203 return True;
204}
205
206Bool SDL_NAME(XDGASetClientVersion)(
207 Display *dpy
208){
209 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
210 xXDGASetClientVersionReq *req;
211
212 XDGACheckExtension (dpy, info, False);
213
214 LockDisplay(dpy);
215 GetReq(XDGASetClientVersion, req);
216 req->reqType = info->codes->major_opcode;
217 req->dgaReqType = X_XDGASetClientVersion;
218 req->major = XDGA_MAJOR_VERSION;
219 req->minor = XDGA_MINOR_VERSION;
220 UnlockDisplay(dpy);
221 SyncHandle();
222 return True;
223}
224
225Bool SDL_NAME(XDGAOpenFramebuffer)(
226 Display *dpy,
227 int screen
228){
229 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
230 xXDGAOpenFramebufferReply rep;
231 xXDGAOpenFramebufferReq *req;
232 char *deviceName = NULL;
233 Bool ret;
234
235 XDGACheckExtension (dpy, info, False);
236
237 LockDisplay(dpy);
238 GetReq(XDGAOpenFramebuffer, req);
239 req->reqType = info->codes->major_opcode;
240 req->dgaReqType = X_XDGAOpenFramebuffer;
241 req->screen = screen;
242 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
243 UnlockDisplay(dpy);
244 SyncHandle();
245 return False;
246 }
247
248 if(rep.length) {
249 deviceName = Xmalloc(rep.length << 2);
250 _XRead(dpy, deviceName, rep.length << 2);
251 }
252
253 ret = SDL_NAME(XDGAMapFramebuffer)(screen, deviceName,
254 (unsigned char*)(long)rep.mem1,
255 rep.size, rep.offset, rep.extra);
256
257 if(deviceName)
258 Xfree(deviceName);
259
260 UnlockDisplay(dpy);
261 SyncHandle();
262 return ret;
263}
264
265void SDL_NAME(XDGACloseFramebuffer)(
266 Display *dpy,
267 int screen
268){
269 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
270 xXDGACloseFramebufferReq *req;
271
272 XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name));
273
274 SDL_NAME(XDGAUnmapFramebuffer)(screen);
275
276 LockDisplay(dpy);
277 GetReq(XDGACloseFramebuffer, req);
278 req->reqType = info->codes->major_opcode;
279 req->dgaReqType = X_XDGACloseFramebuffer;
280 req->screen = screen;
281 UnlockDisplay(dpy);
282 SyncHandle();
283}
284
285
286
287SDL_NAME(XDGAMode)* SDL_NAME(XDGAQueryModes)(
288 Display *dpy,
289 int screen,
290 int *num
291){
292 XExtDisplayInfo *dinfo = SDL_NAME(xdga_find_display) (dpy);
293 xXDGAQueryModesReply rep;
294 xXDGAQueryModesReq *req;
295 SDL_NAME(XDGAMode) *modes = NULL;
296
297 *num = 0;
298
299 XDGACheckExtension (dpy, dinfo, NULL);
300
301 LockDisplay(dpy);
302 GetReq(XDGAQueryModes, req);
303 req->reqType = dinfo->codes->major_opcode;
304 req->dgaReqType = X_XDGAQueryModes;
305 req->screen = screen;
306
307 if (_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
308 if(rep.length) {
309 xXDGAModeInfo info;
310 int i, size;
311 char *offset;
312
313 size = rep.length << 2;
314 size -= rep.number * sz_xXDGAModeInfo; /* find text size */
315 modes = (SDL_NAME(XDGAMode)*)Xmalloc((rep.number * sizeof(SDL_NAME(XDGAMode))) + size);
316 offset = (char*)(&modes[rep.number]); /* start of text */
317
318
319 if(modes) {
320 for(i = 0; i < rep.number; i++) {
321 _XRead(dpy, (char*)(&info), sz_xXDGAModeInfo);
322
323 modes[i].num = info.num;
324 modes[i].verticalRefresh =
325 (float)info.vsync_num / (float)info.vsync_den;
326 modes[i].flags = info.flags;
327 modes[i].imageWidth = info.image_width;
328 modes[i].imageHeight = info.image_height;
329 modes[i].pixmapWidth = info.pixmap_width;
330 modes[i].pixmapHeight = info.pixmap_height;
331 modes[i].bytesPerScanline = info.bytes_per_scanline;
332 modes[i].byteOrder = info.byte_order;
333 modes[i].depth = info.depth;
334 modes[i].bitsPerPixel = info.bpp;
335 modes[i].redMask = info.red_mask;
336 modes[i].greenMask = info.green_mask;
337 modes[i].blueMask = info.blue_mask;
338 modes[i].visualClass = info.visual_class;
339 modes[i].viewportWidth = info.viewport_width;
340 modes[i].viewportHeight = info.viewport_height;
341 modes[i].xViewportStep = info.viewport_xstep;
342 modes[i].yViewportStep = info.viewport_ystep;
343 modes[i].maxViewportX = info.viewport_xmax;
344 modes[i].maxViewportY = info.viewport_ymax;
345 modes[i].viewportFlags = info.viewport_flags;
346 modes[i].reserved1 = info.reserved1;
347 modes[i].reserved2 = info.reserved2;
348
349 _XRead(dpy, offset, info.name_size);
350 modes[i].name = offset;
351 offset += info.name_size;
352 }
353 *num = rep.number;
354 } else
355 _XEatData(dpy, rep.length << 2);
356 }
357 }
358
359 UnlockDisplay(dpy);
360 SyncHandle();
361
362 return modes;
363}
364
365
366SDL_NAME(XDGADevice) *
367SDL_NAME(XDGASetMode)(
368 Display *dpy,
369 int screen,
370 int mode
371){
372 XExtDisplayInfo *dinfo = SDL_NAME(xdga_find_display) (dpy);
373 xXDGASetModeReply rep;
374 xXDGASetModeReq *req;
375 SDL_NAME(XDGADevice) *dev = NULL;
376 Pixmap pid;
377
378 XDGACheckExtension (dpy, dinfo, NULL);
379
380 LockDisplay(dpy);
381 GetReq(XDGASetMode, req);
382 req->reqType = dinfo->codes->major_opcode;
383 req->dgaReqType = X_XDGASetMode;
384 req->screen = screen;
385 req->mode = mode;
386 req->pid = pid = XAllocID(dpy);
387
388 if (_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
389 if(rep.length) {
390 xXDGAModeInfo info;
391 int size;
392
393 size = rep.length << 2;
394 size -= sz_xXDGAModeInfo; /* get text size */
395
396 dev = (SDL_NAME(XDGADevice)*)Xmalloc(sizeof(SDL_NAME(XDGADevice)) + size);
397
398 if(dev) {
399 _XRead(dpy, (char*)(&info), sz_xXDGAModeInfo);
400
401 dev->mode.num = info.num;
402 dev->mode.verticalRefresh =
403 (float)info.vsync_num / (float)info.vsync_den;
404 dev->mode.flags = info.flags;
405 dev->mode.imageWidth = info.image_width;
406 dev->mode.imageHeight = info.image_height;
407 dev->mode.pixmapWidth = info.pixmap_width;
408 dev->mode.pixmapHeight = info.pixmap_height;
409 dev->mode.bytesPerScanline = info.bytes_per_scanline;
410 dev->mode.byteOrder = info.byte_order;
411 dev->mode.depth = info.depth;
412 dev->mode.bitsPerPixel = info.bpp;
413 dev->mode.redMask = info.red_mask;
414 dev->mode.greenMask = info.green_mask;
415 dev->mode.blueMask = info.blue_mask;
416 dev->mode.visualClass = info.visual_class;
417 dev->mode.viewportWidth = info.viewport_width;
418 dev->mode.viewportHeight = info.viewport_height;
419 dev->mode.xViewportStep = info.viewport_xstep;
420 dev->mode.yViewportStep = info.viewport_ystep;
421 dev->mode.maxViewportX = info.viewport_xmax;
422 dev->mode.maxViewportY = info.viewport_ymax;
423 dev->mode.viewportFlags = info.viewport_flags;
424 dev->mode.reserved1 = info.reserved1;
425 dev->mode.reserved2 = info.reserved2;
426
427 dev->mode.name = (char*)(&dev[1]);
428 _XRead(dpy, dev->mode.name, info.name_size);
429
430 dev->pixmap = (rep.flags & XDGAPixmap) ? pid : 0;
431 dev->data = SDL_NAME(XDGAGetMappedMemory)(screen);
432
433 if(dev->data)
434 dev->data += rep.offset;
435 }
436 /* not sure what to do if the allocation fails */
437 }
438 }
439
440 UnlockDisplay(dpy);
441 SyncHandle();
442
443 return dev;
444}
445
446
447void SDL_NAME(XDGASetViewport)(
448 Display *dpy,
449 int screen,
450 int x,
451 int y,
452 int flags
453){
454 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
455 xXDGASetViewportReq *req;
456
457 XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name));
458
459 LockDisplay(dpy);
460 GetReq(XDGASetViewport, req);
461 req->reqType = info->codes->major_opcode;
462 req->dgaReqType = X_XDGASetViewport;
463 req->screen = screen;
464 req->x = x;
465 req->y = y;
466 req->flags = flags;
467 UnlockDisplay(dpy);
468 SyncHandle();
469}
470
471
472void SDL_NAME(XDGAInstallColormap)(
473 Display *dpy,
474 int screen,
475 Colormap cmap
476){
477 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
478 xXDGAInstallColormapReq *req;
479
480 XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name));
481
482 LockDisplay(dpy);
483 GetReq(XDGAInstallColormap, req);
484 req->reqType = info->codes->major_opcode;
485 req->dgaReqType = X_XDGAInstallColormap;
486 req->screen = screen;
487 req->cmap = cmap;
488 UnlockDisplay(dpy);
489 SyncHandle();
490}
491
492void SDL_NAME(XDGASelectInput)(
493 Display *dpy,
494 int screen,
495 long mask
496){
497 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
498 xXDGASelectInputReq *req;
499
500 XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name));
501
502 LockDisplay(dpy);
503 GetReq(XDGASelectInput, req);
504 req->reqType = info->codes->major_opcode;
505 req->dgaReqType = X_XDGASelectInput;
506 req->screen = screen;
507 req->mask = mask;
508 UnlockDisplay(dpy);
509 SyncHandle();
510}
511
512void SDL_NAME(XDGAFillRectangle)(
513 Display *dpy,
514 int screen,
515 int x,
516 int y,
517 unsigned int width,
518 unsigned int height,
519 unsigned long color
520){
521 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
522 xXDGAFillRectangleReq *req;
523
524 XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name));
525
526 LockDisplay(dpy);
527 GetReq(XDGAFillRectangle, req);
528 req->reqType = info->codes->major_opcode;
529 req->dgaReqType = X_XDGAFillRectangle;
530 req->screen = screen;
531 req->x = x;
532 req->y = y;
533 req->width = width;
534 req->height = height;
535 req->color = color;
536 UnlockDisplay(dpy);
537 SyncHandle();
538}
539
540void SDL_NAME(XDGACopyArea)(
541 Display *dpy,
542 int screen,
543 int srcx,
544 int srcy,
545 unsigned int width,
546 unsigned int height,
547 int dstx,
548 int dsty
549){
550 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
551 xXDGACopyAreaReq *req;
552
553 XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name));
554
555 LockDisplay(dpy);
556 GetReq(XDGACopyArea, req);
557 req->reqType = info->codes->major_opcode;
558 req->dgaReqType = X_XDGACopyArea;
559 req->screen = screen;
560 req->srcx = srcx;
561 req->srcy = srcy;
562 req->width = width;
563 req->height = height;
564 req->dstx = dstx;
565 req->dsty = dsty;
566 UnlockDisplay(dpy);
567 SyncHandle();
568}
569
570void SDL_NAME(XDGACopyTransparentArea)(
571 Display *dpy,
572 int screen,
573 int srcx,
574 int srcy,
575 unsigned int width,
576 unsigned int height,
577 int dstx,
578 int dsty,
579 unsigned long key
580){
581 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
582 xXDGACopyTransparentAreaReq *req;
583
584 XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name));
585
586 LockDisplay(dpy);
587 GetReq(XDGACopyTransparentArea, req);
588 req->reqType = info->codes->major_opcode;
589 req->dgaReqType = X_XDGACopyTransparentArea;
590 req->screen = screen;
591 req->srcx = srcx;
592 req->srcy = srcy;
593 req->width = width;
594 req->height = height;
595 req->dstx = dstx;
596 req->dsty = dsty;
597 req->key = key;
598 UnlockDisplay(dpy);
599 SyncHandle();
600}
601
602
603int SDL_NAME(XDGAGetViewportStatus)(
604 Display *dpy,
605 int screen
606){
607 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
608 xXDGAGetViewportStatusReply rep;
609 xXDGAGetViewportStatusReq *req;
610 int status = 0;
611
612 XDGACheckExtension (dpy, info, 0);
613
614 LockDisplay(dpy);
615 GetReq(XDGAGetViewportStatus, req);
616 req->reqType = info->codes->major_opcode;
617 req->dgaReqType = X_XDGAGetViewportStatus;
618 req->screen = screen;
619 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse))
620 status = rep.status;
621 UnlockDisplay(dpy);
622 SyncHandle();
623 return status;
624}
625
626void SDL_NAME(XDGASync)(
627 Display *dpy,
628 int screen
629){
630 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
631 xXDGASyncReply rep;
632 xXDGASyncReq *req;
633
634 XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name));
635
636 LockDisplay(dpy);
637 GetReq(XDGASync, req);
638 req->reqType = info->codes->major_opcode;
639 req->dgaReqType = X_XDGASync;
640 req->screen = screen;
641 _XReply(dpy, (xReply *)&rep, 0, xFalse);
642 UnlockDisplay(dpy);
643 SyncHandle();
644}
645
646
647void SDL_NAME(XDGAChangePixmapMode)(
648 Display *dpy,
649 int screen,
650 int *x,
651 int *y,
652 int mode
653){
654 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
655 xXDGAChangePixmapModeReq *req;
656 xXDGAChangePixmapModeReply rep;
657
658 XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name));
659
660 LockDisplay(dpy);
661 GetReq(XDGAChangePixmapMode, req);
662 req->reqType = info->codes->major_opcode;
663 req->dgaReqType = X_XDGAChangePixmapMode;
664 req->screen = screen;
665 req->x = *x;
666 req->y = *y;
667 req->flags = mode;
668 _XReply(dpy, (xReply *)&rep, 0, xFalse);
669 *x = rep.x;
670 *y = rep.y;
671 UnlockDisplay(dpy);
672 SyncHandle();
673}
674
675Colormap SDL_NAME(XDGACreateColormap)(
676 Display *dpy,
677 int screen,
678 SDL_NAME(XDGADevice) *dev,
679 int alloc
680){
681 XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy);
682 xXDGACreateColormapReq *req;
683 Colormap cid;
684
685 XDGACheckExtension (dpy, info, -1);
686
687 LockDisplay(dpy);
688 GetReq(XDGACreateColormap, req);
689 req->reqType = info->codes->major_opcode;
690 req->dgaReqType = X_XDGACreateColormap;
691 req->screen = screen;
692 req->mode = dev->mode.num;
693 req->alloc = alloc;
694 cid = req->id = XAllocID(dpy);
695 UnlockDisplay(dpy);
696 SyncHandle();
697
698 return cid;
699}
700
701
702void SDL_NAME(XDGAKeyEventToXKeyEvent)(
703 SDL_NAME(XDGAKeyEvent)* dk,
704 XKeyEvent* xk
705){
706 xk->type = dk->type;
707 xk->serial = dk->serial;
708 xk->send_event = False;
709 xk->display = dk->display;
710 xk->window = RootWindow(dk->display, dk->screen);
711 xk->root = xk->window;
712 xk->subwindow = None;
713 xk->time = dk->time;
714 xk->x = xk->y = xk->x_root = xk->y_root = 0;
715 xk->state = dk->state;
716 xk->keycode = dk->keycode;
717 xk->same_screen = True;
718}
719
720#include <X11/Xmd.h>
721#include <stdlib.h>
722#include <stdio.h>
723#include <fcntl.h>
724#if defined(ISC)
725# define HAS_SVR3_MMAP
726# include <sys/types.h>
727# include <errno.h>
728
729# include <sys/at_ansi.h>
730# include <sys/kd.h>
731
732# include <sys/sysmacros.h>
733# include <sys/immu.h>
734# include <sys/region.h>
735
736# include <sys/mmap.h>
737#else
738# if !defined(Lynx)
739# if !defined(__EMX__)
740# include <sys/mman.h>
741# endif
742# else
743# include <sys/types.h>
744# include <errno.h>
745# include <smem.h>
746# endif
747#endif
748#include <sys/wait.h>
749#include <signal.h>
750#include <unistd.h>
751
752#if defined(SVR4) && !defined(sun) && !defined(SCO325)
753#define DEV_MEM "/dev/pmem"
754#elif defined(SVR4) && defined(sun)
755#define DEV_MEM "/dev/xsvc"
756#else
757#define DEV_MEM "/dev/mem"
758#endif
759
760
761
762typedef struct _DGAMapRec{
763 unsigned char *physical;
764 unsigned char *virtual;
765 CARD32 size;
766 int fd;
767 int screen;
768 struct _DGAMapRec *next;
769} DGAMapRec, *DGAMapPtr;
770
771static Bool
772DGAMapPhysical(int, char*, unsigned char*, CARD32, CARD32, CARD32, DGAMapPtr);
773static void DGAUnmapPhysical(DGAMapPtr);
774
775static DGAMapPtr _Maps = NULL;
776
777
778unsigned char*
779SDL_NAME(XDGAGetMappedMemory)(int screen)
780{
781 DGAMapPtr pMap = _Maps;
782 unsigned char *pntr = NULL;
783
784 while(pMap != NULL) {
785 if(pMap->screen == screen) {
786 pntr = pMap->virtual;
787 break;
788 }
789 pMap = pMap->next;
790 }
791
792 return pntr;
793}
794
795Bool
796SDL_NAME(XDGAMapFramebuffer)(
797 int screen,
798 char *name, /* optional device name */
799 unsigned char* base, /* physical memory */
800 CARD32 size, /* size */
801 CARD32 offset, /* optional offset */
802 CARD32 extra /* optional extra data */
803){
804 DGAMapPtr pMap = _Maps;
805 Bool result;
806
807 /* is it already mapped ? */
808 while(pMap != NULL) {
809 if(pMap->screen == screen)
810 return True;
811 pMap = pMap->next;
812 }
813
814 if(extra & XDGANeedRoot) {
815 /* we should probably check if we have root permissions and
816 return False here */
817
818 }
819
820 pMap = (DGAMapPtr)Xmalloc(sizeof(DGAMapRec));
821
822 result = DGAMapPhysical(screen, name, base, size, offset, extra, pMap);
823
824 if(result) {
825 pMap->next = _Maps;
826 _Maps = pMap;
827 } else
828 Xfree(pMap);
829
830 return result;
831}
832
833void
834SDL_NAME(XDGAUnmapFramebuffer)(int screen)
835{
836 DGAMapPtr pMap = _Maps;
837 DGAMapPtr pPrev = NULL;
838
839 /* is it already mapped */
840 while(pMap != NULL) {
841 if(pMap->screen == screen)
842 break;
843 pPrev = pMap;
844 pMap = pMap->next;
845 }
846
847 if(!pMap)
848 return;
849
850 DGAUnmapPhysical(pMap);
851
852 if(!pPrev)
853 _Maps = pMap->next;
854 else
855 pPrev->next = pMap->next;
856
857 Xfree(pMap);
858}
859
860
861static Bool
862DGAMapPhysical(
863 int screen,
864 char *name, /* optional device name */
865 unsigned char* base, /* physical memory */
866 CARD32 size, /* size */
867 CARD32 offset, /* optional offset */
868 CARD32 extra, /* optional extra data */
869 DGAMapPtr pMap
870) {
871#if defined(ISC) && defined(HAS_SVR3_MMAP)
872 struct kd_memloc mloc;
873#elif defined(__EMX__)
874 APIRET rc;
875 ULONG action;
876 HFILE hfd;
877#endif
878
879 base += offset;
880
881 pMap->screen = screen;
882 pMap->physical = base;
883 pMap->size = size;
884
885#if defined(ISC) && defined(HAS_SVR3_MMAP)
886 if ((pMap->fd = open("/dev/mmap", O_RDWR)) < 0)
887 return False;
888 mloc.vaddr = (char *)0;
889 mloc.physaddr = (char *)base;
890 mloc.length = size;
891 mloc.ioflg=1;
892
893 if ((pMap->virtual = (void *)ioctl(pMap->fd, MAP, &mloc)) == (void *)-1)
894 return False;
895#elif defined (__EMX__)
896 /*
897 * Dragon warning here! /dev/pmap$ is never closed, except on progam exit.
898 * Consecutive calling of this routine will make PMAP$ driver run out
899 * of memory handles. Some umap/close mechanism should be provided
900 */
901
902 rc = DosOpen("/dev/pmap$", &hfd, &action, 0, FILE_NORMAL, FILE_OPEN,
903 OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE, (PEAOP2)NULL);
904 if (rc != 0)
905 return False;
906 {
907 struct map_ioctl {
908 union {
909 ULONG phys;
910 void* user;
911 } a;
912 ULONG size;
913 } pmap,dmap;
914 ULONG plen,dlen;
915#define XFREE86_PMAP 0x76
916#define PMAP_MAP 0x44
917
918 pmap.a.phys = base;
919 pmap.size = size;
920 rc = DosDevIOCtl(hfd, XFREE86_PMAP, PMAP_MAP,
921 (PULONG)&pmap, sizeof(pmap), &plen,
922 (PULONG)&dmap, sizeof(dmap), &dlen);
923 if (rc == 0) {
924 pMap->virtual = dmap.a.user;
925 }
926 }
927 if (rc != 0)
928 return False;
929#elif defined (Lynx)
930 pMap->virtual = smem_create("XF86DGA", (char*)base, size, SM_READ|SM_WRITE);
931#else
932#ifndef MAP_FILE
933#define MAP_FILE 0
934#endif
935 if (!name)
936 name = DEV_MEM;
937 if ((pMap->fd = open(name, O_RDWR)) < 0)
938#if defined(ENABLE_FBCON)
939 { /* /dev/fb0 fallback added by Sam Lantinga <hercules@lokigames.com> */
940 /* Try to fall back to /dev/fb on Linux - FIXME: verify the device */
941 struct fb_fix_screeninfo finfo;
942
943 if ((pMap->fd = open("/dev/fb0", O_RDWR)) < 0) {
944 return False;
945 }
946 /* The useable framebuffer console memory may not be the whole
947 framebuffer that X has access to. :-(
948 */
949 if ( ioctl(pMap->fd, FBIOGET_FSCREENINFO, &finfo) < 0 ) {
950 close(pMap->fd);
951 return False;
952 }
953 /* Warning: On PPC, the size and virtual need to be offset by:
954 (((long)finfo.smem_start) -
955 (((long)finfo.smem_start)&~(PAGE_SIZE-1)))
956 */
957 base = 0;
958 size = pMap->size = finfo.smem_len;
959 }
960#else
961 return False;
962#endif
963 pMap->virtual = mmap(NULL, size, PROT_READ | PROT_WRITE,
964 MAP_FILE | MAP_SHARED, pMap->fd, (off_t)((size_t)base));
965 if (pMap->virtual == (void *)-1)
966 return False;
967#endif
968
969#if !defined(ISC) && !defined(HAS_SVR3_MMAP) && !defined(Lynx) \
970 && !defined(__EMX__)
971 mprotect(pMap->virtual, size, PROT_READ | PROT_WRITE);
972#endif
973
974 return True;
975}
976
977
978
979static void
980DGAUnmapPhysical(DGAMapPtr pMap)
981{
982#if !defined(ISC) && !defined(HAS_SVR3_MMAP) && !defined(Lynx) \
983 && !defined(__EMX__)
984 mprotect(pMap->virtual,pMap->size, PROT_READ);
985#elif defined(Lynx)
986 /* XXX this doesn't allow enable after disable */
987 smem_create(NULL, pMap->virtual, pMap->size, SM_DETACH);
988 smem_remove("XF86DGA");
989#endif
990
991
992 /* We need to unmap and close too !!!!!!!!!!*/
993}
diff --git a/apps/plugins/sdl/src/video/Xext/Xxf86vm/XF86VMode.c b/apps/plugins/sdl/src/video/Xext/Xxf86vm/XF86VMode.c
deleted file mode 100644
index 5cb21905af..0000000000
--- a/apps/plugins/sdl/src/video/Xext/Xxf86vm/XF86VMode.c
+++ /dev/null
@@ -1,1226 +0,0 @@
1/* $XConsortium: XF86VMode.c /main/2 1995/11/14 18:17:58 kaleb $ */
2/* $XFree86: xc/lib/Xxf86vm/XF86VMode.c,v 3.32 2001/07/25 15:04:54 dawes Exp $ */
3/*
4
5Copyright (c) 1995 Kaleb S. KEITHLEY
6
7Permission is hereby granted, free of charge, to any person obtaining
8a copy of this software and associated documentation files (the
9"Software"), to deal in the Software without restriction, including
10without limitation the rights to use, copy, modify, merge, publish,
11distribute, sublicense, and/or sell copies of the Software, and to
12permit persons to whom the Software is furnished to do so, subject to
13the following conditions:
14
15The above copyright notice and this permission notice shall be
16included in all copies or substantial portions of the Software.
17
18THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21IN NO EVENT SHALL Kaleb S. KEITHLEY BE LIABLE FOR ANY CLAIM, DAMAGES
22OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24OTHER DEALINGS IN THE SOFTWARE.
25
26Except as contained in this notice, the name of Kaleb S. KEITHLEY
27shall not be used in advertising or otherwise to promote the sale, use
28or other dealings in this Software without prior written authorization
29from Kaleb S. KEITHLEY.
30
31*/
32/* $XConsortium: XF86VMode.c /main/4 1996/01/16 07:52:25 kaleb CHECKEDOUT $ */
33
34/* THIS IS NOT AN X CONSORTIUM STANDARD */
35
36#define NEED_EVENTS
37#define NEED_REPLIES
38
39#ifndef XBUILD_IN_CLIENT
40/* Apparently some X11 systems can't include this multiple times... */
41#ifndef SDL_INCLUDED_XLIBINT_H
42#define SDL_INCLUDED_XLIBINT_H 1
43#include <X11/Xlibint.h>
44#endif
45#include "../extensions/xf86vmstr.h"
46#include "../extensions/Xext.h"
47#include "../extensions/extutil.h"
48#else
49#include "include/extensions/xf86vmstr.h"
50#include "include/extensions/Xext.h"
51#include "include/extensions/extutil.h"
52#endif
53
54#ifdef DEBUG
55#include <stdio.h>
56#endif
57
58#ifndef MODE_BAD
59#define MODE_BAD 255
60#endif
61
62static XExtensionInfo _xf86vidmode_info_data;
63static XExtensionInfo *xf86vidmode_info = &_xf86vidmode_info_data;
64static char *xf86vidmode_extension_name = XF86VIDMODENAME;
65
66#define XF86VidModeCheckExtension(dpy,i,val) \
67 XextCheckExtension (dpy, i, xf86vidmode_extension_name, val)
68
69/*****************************************************************************
70 * *
71 * private utility routines *
72 * *
73 *****************************************************************************/
74
75static XEXT_CLOSE_DISPLAY_PROTO(close_display);
76static /* const */ XExtensionHooks xf86vidmode_extension_hooks = {
77 NULL, /* create_gc */
78 NULL, /* copy_gc */
79 NULL, /* flush_gc */
80 NULL, /* free_gc */
81 NULL, /* create_font */
82 NULL, /* free_font */
83 close_display, /* close_display */
84 NULL, /* wire_to_event */
85 NULL, /* event_to_wire */
86 NULL, /* error */
87 NULL, /* error_string */
88};
89
90static XEXT_GENERATE_FIND_DISPLAY (find_display, xf86vidmode_info,
91 xf86vidmode_extension_name,
92 &xf86vidmode_extension_hooks,
93 0, NULL)
94
95static XEXT_GENERATE_CLOSE_DISPLAY (close_display, xf86vidmode_info)
96
97
98/*****************************************************************************
99 * *
100 * public XFree86-VidMode Extension routines *
101 * *
102 *****************************************************************************/
103
104Bool
105SDL_NAME(XF86VidModeQueryExtension) (dpy, event_basep, error_basep)
106 Display *dpy;
107 int *event_basep, *error_basep;
108{
109 XExtDisplayInfo *info = find_display (dpy);
110
111 if (XextHasExtension(info)) {
112 *event_basep = info->codes->first_event;
113 *error_basep = info->codes->first_error;
114 return True;
115 } else {
116 return False;
117 }
118}
119
120Bool
121SDL_NAME(XF86VidModeQueryVersion)(dpy, majorVersion, minorVersion)
122 Display* dpy;
123 int* majorVersion;
124 int* minorVersion;
125{
126 XExtDisplayInfo *info = find_display (dpy);
127 xXF86VidModeQueryVersionReply rep;
128 xXF86VidModeQueryVersionReq *req;
129
130 XF86VidModeCheckExtension (dpy, info, False);
131
132 LockDisplay(dpy);
133 GetReq(XF86VidModeQueryVersion, req);
134 req->reqType = info->codes->major_opcode;
135 req->xf86vidmodeReqType = X_XF86VidModeQueryVersion;
136 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
137 UnlockDisplay(dpy);
138 SyncHandle();
139 return False;
140 }
141 *majorVersion = rep.majorVersion;
142 *minorVersion = rep.minorVersion;
143 UnlockDisplay(dpy);
144 SyncHandle();
145 if (*majorVersion >= 2)
146 SDL_NAME(XF86VidModeSetClientVersion)(dpy);
147 return True;
148}
149
150Bool
151SDL_NAME(XF86VidModeSetClientVersion)(Display *dpy)
152{
153 XExtDisplayInfo *info = find_display(dpy);
154 xXF86VidModeSetClientVersionReq *req;
155
156 XF86VidModeCheckExtension(dpy, info, False);
157
158 LockDisplay(dpy);
159 GetReq(XF86VidModeSetClientVersion, req);
160 req->reqType = info->codes->major_opcode;
161 req->xf86vidmodeReqType = X_XF86VidModeSetClientVersion;
162 req->major = XF86VIDMODE_MAJOR_VERSION;
163 req->minor = XF86VIDMODE_MINOR_VERSION;
164 UnlockDisplay(dpy);
165 SyncHandle();
166 return True;
167}
168
169Bool
170SDL_NAME(XF86VidModeSetGamma)(Display *dpy, int screen, SDL_NAME(XF86VidModeGamma) *Gamma)
171{
172 XExtDisplayInfo *info = find_display(dpy);
173 xXF86VidModeSetGammaReq *req;
174
175 XF86VidModeCheckExtension(dpy, info, False);
176
177 LockDisplay(dpy);
178 GetReq(XF86VidModeSetGamma, req);
179 req->reqType = info->codes->major_opcode;
180 req->xf86vidmodeReqType = X_XF86VidModeSetGamma;
181 req->screen = screen;
182 req->red = (CARD32)(Gamma->red * 10000.);
183 req->green = (CARD32)(Gamma->green * 10000.);
184 req->blue = (CARD32)(Gamma->blue * 10000.);
185 UnlockDisplay(dpy);
186 SyncHandle();
187 return True;
188}
189
190Bool
191SDL_NAME(XF86VidModeGetGamma)(Display *dpy, int screen, SDL_NAME(XF86VidModeGamma) *Gamma)
192{
193 XExtDisplayInfo *info = find_display (dpy);
194 xXF86VidModeGetGammaReply rep;
195 xXF86VidModeGetGammaReq *req;
196
197 XF86VidModeCheckExtension (dpy, info, False);
198
199 LockDisplay(dpy);
200 GetReq(XF86VidModeGetGamma, req);
201 req->reqType = info->codes->major_opcode;
202 req->xf86vidmodeReqType = X_XF86VidModeGetGamma;
203 req->screen = screen;
204 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
205 UnlockDisplay(dpy);
206 SyncHandle();
207 return False;
208 }
209 Gamma->red = ((float)rep.red) / 10000.;
210 Gamma->green = ((float)rep.green) / 10000.;
211 Gamma->blue = ((float)rep.blue) / 10000.;
212 UnlockDisplay(dpy);
213 SyncHandle();
214 return True;
215}
216
217Bool
218SDL_NAME(XF86VidModeGetModeLine)(dpy, screen, dotclock, modeline)
219 Display* dpy;
220 int screen;
221 int* dotclock;
222 SDL_NAME(XF86VidModeModeLine)* modeline;
223{
224 XExtDisplayInfo *info = find_display (dpy);
225 xXF86VidModeGetModeLineReply rep;
226 xXF86OldVidModeGetModeLineReply oldrep;
227 xXF86VidModeGetModeLineReq *req;
228 int majorVersion, minorVersion;
229
230 XF86VidModeCheckExtension (dpy, info, False);
231 SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion);
232
233 LockDisplay(dpy);
234 GetReq(XF86VidModeGetModeLine, req);
235 req->reqType = info->codes->major_opcode;
236 req->xf86vidmodeReqType = X_XF86VidModeGetModeLine;
237 req->screen = screen;
238
239 if (majorVersion < 2) {
240 if (!_XReply(dpy, (xReply *)&oldrep,
241 (SIZEOF(xXF86OldVidModeGetModeLineReply) - SIZEOF(xReply)) >> 2, xFalse)) {
242 UnlockDisplay(dpy);
243 SyncHandle();
244 return False;
245 }
246 *dotclock = oldrep.dotclock;
247 modeline->hdisplay = oldrep.hdisplay;
248 modeline->hsyncstart = oldrep.hsyncstart;
249 modeline->hsyncend = oldrep.hsyncend;
250 modeline->htotal = oldrep.htotal;
251 modeline->hskew = 0;
252 modeline->vdisplay = oldrep.vdisplay;
253 modeline->vsyncstart = oldrep.vsyncstart;
254 modeline->vsyncend = oldrep.vsyncend;
255 modeline->vtotal = oldrep.vtotal;
256 modeline->flags = oldrep.flags;
257 modeline->privsize = oldrep.privsize;
258 } else {
259 if (!_XReply(dpy, (xReply *)&rep,
260 (SIZEOF(xXF86VidModeGetModeLineReply) - SIZEOF(xReply)) >> 2, xFalse)) {
261 UnlockDisplay(dpy);
262 SyncHandle();
263 return False;
264 }
265 *dotclock = rep.dotclock;
266 modeline->hdisplay = rep.hdisplay;
267 modeline->hsyncstart = rep.hsyncstart;
268 modeline->hsyncend = rep.hsyncend;
269 modeline->htotal = rep.htotal;
270 modeline->hskew = rep.hskew;
271 modeline->vdisplay = rep.vdisplay;
272 modeline->vsyncstart = rep.vsyncstart;
273 modeline->vsyncend = rep.vsyncend;
274 modeline->vtotal = rep.vtotal;
275 modeline->flags = rep.flags;
276 modeline->privsize = rep.privsize;
277 }
278
279 if (modeline->privsize > 0) {
280 if (!(modeline->private = Xcalloc(modeline->privsize, sizeof(INT32)))) {
281 _XEatData(dpy, (modeline->privsize) * sizeof(INT32));
282 Xfree(modeline->private);
283 return False;
284 }
285 _XRead(dpy, (char*)modeline->private, modeline->privsize * sizeof(INT32));
286 } else {
287 modeline->private = NULL;
288 }
289 UnlockDisplay(dpy);
290 SyncHandle();
291 return True;
292}
293
294Bool
295SDL_NAME(XF86VidModeGetAllModeLines)(dpy, screen, modecount, modelinesPtr)
296 Display* dpy;
297 int screen;
298 int* modecount;
299 SDL_NAME(XF86VidModeModeInfo) ***modelinesPtr;
300{
301 XExtDisplayInfo *info = find_display (dpy);
302 xXF86VidModeGetAllModeLinesReply rep;
303 xXF86VidModeGetAllModeLinesReq *req;
304 SDL_NAME(XF86VidModeModeInfo) *mdinfptr, **modelines;
305 xXF86VidModeModeInfo xmdline;
306 xXF86OldVidModeModeInfo oldxmdline;
307 int i;
308 int majorVersion, minorVersion;
309 Bool protocolBug = False;
310
311 XF86VidModeCheckExtension (dpy, info, False);
312
313 /*
314 * Note: There was a bug in the protocol implementation in versions
315 * 0.x with x < 8 (the .private field wasn't being passed over the wire).
316 * Check the server's version, and accept the old format if appropriate.
317 */
318
319 SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion);
320 if (majorVersion == 0 && minorVersion < 8) {
321 protocolBug = True;
322#ifdef DEBUG
323 fprintf(stderr, "XF86VidModeGetAllModeLines: Warning: Xserver is"
324 "running an old version (%d.%d)\n", majorVersion,
325 minorVersion);
326#endif
327 }
328
329 LockDisplay(dpy);
330 GetReq(XF86VidModeGetAllModeLines, req);
331 req->reqType = info->codes->major_opcode;
332 req->xf86vidmodeReqType = X_XF86VidModeGetAllModeLines;
333 req->screen = screen;
334 if (!_XReply(dpy, (xReply *)&rep,
335 (SIZEOF(xXF86VidModeGetAllModeLinesReply) - SIZEOF(xReply)) >> 2, xFalse)) {
336 UnlockDisplay(dpy);
337 SyncHandle();
338 return False;
339 }
340
341 *modecount = rep.modecount;
342
343 if (!(modelines = (SDL_NAME(XF86VidModeModeInfo) **) Xcalloc(rep.modecount,
344 sizeof(SDL_NAME(XF86VidModeModeInfo) *)
345 +sizeof(SDL_NAME(XF86VidModeModeInfo))))) {
346 if (majorVersion < 2)
347 _XEatData(dpy, (rep.modecount) * sizeof(xXF86OldVidModeModeInfo));
348 else
349 _XEatData(dpy, (rep.modecount) * sizeof(xXF86VidModeModeInfo));
350 Xfree(modelines);
351 UnlockDisplay(dpy);
352 SyncHandle();
353 return False;
354 }
355 mdinfptr = (SDL_NAME(XF86VidModeModeInfo) *) (
356 (char *) modelines
357 + rep.modecount*sizeof(SDL_NAME(XF86VidModeModeInfo) *)
358 );
359
360 for (i = 0; i < rep.modecount; i++) {
361 modelines[i] = mdinfptr++;
362 if (majorVersion < 2) {
363 _XRead(dpy, (char*)&oldxmdline, sizeof(xXF86OldVidModeModeInfo));
364 modelines[i]->dotclock = oldxmdline.dotclock;
365 modelines[i]->hdisplay = oldxmdline.hdisplay;
366 modelines[i]->hsyncstart = oldxmdline.hsyncstart;
367 modelines[i]->hsyncend = oldxmdline.hsyncend;
368 modelines[i]->htotal = oldxmdline.htotal;
369 modelines[i]->hskew = 0;
370 modelines[i]->vdisplay = oldxmdline.vdisplay;
371 modelines[i]->vsyncstart = oldxmdline.vsyncstart;
372 modelines[i]->vsyncend = oldxmdline.vsyncend;
373 modelines[i]->vtotal = oldxmdline.vtotal;
374 modelines[i]->flags = oldxmdline.flags;
375 if (protocolBug) {
376 modelines[i]->privsize = 0;
377 modelines[i]->private = NULL;
378 } else {
379 modelines[i]->privsize = oldxmdline.privsize;
380 if (oldxmdline.privsize > 0) {
381 if (!(modelines[i]->private =
382 Xcalloc(oldxmdline.privsize, sizeof(INT32)))) {
383 _XEatData(dpy, (oldxmdline.privsize) * sizeof(INT32));
384 Xfree(modelines[i]->private);
385 } else {
386 _XRead(dpy, (char*)modelines[i]->private,
387 oldxmdline.privsize * sizeof(INT32));
388 }
389 } else {
390 modelines[i]->private = NULL;
391 }
392 }
393 } else {
394 _XRead(dpy, (char*)&xmdline, sizeof(xXF86VidModeModeInfo));
395 modelines[i]->dotclock = xmdline.dotclock;
396 modelines[i]->hdisplay = xmdline.hdisplay;
397 modelines[i]->hsyncstart = xmdline.hsyncstart;
398 modelines[i]->hsyncend = xmdline.hsyncend;
399 modelines[i]->htotal = xmdline.htotal;
400 modelines[i]->hskew = xmdline.hskew;
401 modelines[i]->vdisplay = xmdline.vdisplay;
402 modelines[i]->vsyncstart = xmdline.vsyncstart;
403 modelines[i]->vsyncend = xmdline.vsyncend;
404 modelines[i]->vtotal = xmdline.vtotal;
405 modelines[i]->flags = xmdline.flags;
406 if (protocolBug) {
407 modelines[i]->privsize = 0;
408 modelines[i]->private = NULL;
409 } else {
410 modelines[i]->privsize = xmdline.privsize;
411 if (xmdline.privsize > 0) {
412 if (!(modelines[i]->private =
413 Xcalloc(xmdline.privsize, sizeof(INT32)))) {
414 _XEatData(dpy, (xmdline.privsize) * sizeof(INT32));
415 Xfree(modelines[i]->private);
416 } else {
417 _XRead(dpy, (char*)modelines[i]->private,
418 xmdline.privsize * sizeof(INT32));
419 }
420 } else {
421 modelines[i]->private = NULL;
422 }
423 }
424 }
425 }
426 *modelinesPtr = modelines;
427 UnlockDisplay(dpy);
428 SyncHandle();
429 return True;
430}
431
432/*
433 * GetReq replacement for use with VidMode protocols earlier than 2.0
434 */
435#if !defined(UNIXCPP) || defined(ANSICPP)
436#define GetOldReq(name, oldname, req) \
437 WORD64ALIGN\
438 if ((dpy->bufptr + SIZEOF(x##oldname##Req)) > dpy->bufmax)\
439 _XFlush(dpy);\
440 req = (x##oldname##Req *)(dpy->last_req = dpy->bufptr);\
441 req->reqType = X_##name;\
442 req->length = (SIZEOF(x##oldname##Req))>>2;\
443 dpy->bufptr += SIZEOF(x##oldname##Req);\
444 dpy->request++
445
446#else /* non-ANSI C uses empty comment instead of "##" for token concatenation */
447#define GetOldReq(name, oldname, req) \
448 WORD64ALIGN\
449 if ((dpy->bufptr + SIZEOF(x/**/oldname/**/Req)) > dpy->bufmax)\
450 _XFlush(dpy);\
451 req = (x/**/oldname/**/Req *)(dpy->last_req = dpy->bufptr);\
452 req->reqType = X_/**/name;\
453 req->length = (SIZEOF(x/**/oldname/**/Req))>>2;\
454 dpy->bufptr += SIZEOF(x/**/oldname/**/Req);\
455 dpy->request++
456#endif
457
458Bool
459SDL_NAME(XF86VidModeAddModeLine) (dpy, screen, newmodeline, aftermodeline)
460 Display *dpy;
461 int screen;
462 SDL_NAME(XF86VidModeModeInfo)* newmodeline;
463 SDL_NAME(XF86VidModeModeInfo)* aftermodeline;
464{
465 XExtDisplayInfo *info = find_display (dpy);
466 xXF86VidModeAddModeLineReq *req;
467 xXF86OldVidModeAddModeLineReq *oldreq;
468 int majorVersion, minorVersion;
469
470 XF86VidModeCheckExtension (dpy, info, False);
471 SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion);
472
473 LockDisplay(dpy);
474 if (majorVersion < 2) {
475 GetOldReq(XF86VidModeAddModeLine, XF86OldVidModeAddModeLine, oldreq);
476 oldreq->reqType = info->codes->major_opcode;
477 oldreq->xf86vidmodeReqType = X_XF86VidModeAddModeLine;
478 oldreq->screen = screen;
479 oldreq->dotclock = newmodeline->dotclock;
480 oldreq->hdisplay = newmodeline->hdisplay;
481 oldreq->hsyncstart = newmodeline->hsyncstart;
482 oldreq->hsyncend = newmodeline->hsyncend;
483 oldreq->htotal = newmodeline->htotal;
484 oldreq->vdisplay = newmodeline->vdisplay;
485 oldreq->vsyncstart = newmodeline->vsyncstart;
486 oldreq->vsyncend = newmodeline->vsyncend;
487 oldreq->vtotal = newmodeline->vtotal;
488 oldreq->flags = newmodeline->flags;
489 oldreq->privsize = newmodeline->privsize;
490 if (aftermodeline != NULL) {
491 oldreq->after_dotclock = aftermodeline->dotclock;
492 oldreq->after_hdisplay = aftermodeline->hdisplay;
493 oldreq->after_hsyncstart = aftermodeline->hsyncstart;
494 oldreq->after_hsyncend = aftermodeline->hsyncend;
495 oldreq->after_htotal = aftermodeline->htotal;
496 oldreq->after_vdisplay = aftermodeline->vdisplay;
497 oldreq->after_vsyncstart = aftermodeline->vsyncstart;
498 oldreq->after_vsyncend = aftermodeline->vsyncend;
499 oldreq->after_vtotal = aftermodeline->vtotal;
500 oldreq->after_flags = aftermodeline->flags;
501 } else {
502 oldreq->after_dotclock = 0;
503 oldreq->after_hdisplay = 0;
504 oldreq->after_hsyncstart = 0;
505 oldreq->after_hsyncend = 0;
506 oldreq->after_htotal = 0;
507 oldreq->after_vdisplay = 0;
508 oldreq->after_vsyncstart = 0;
509 oldreq->after_vsyncend = 0;
510 oldreq->after_vtotal = 0;
511 oldreq->after_flags = 0;
512 }
513 if (newmodeline->privsize) {
514 oldreq->length += newmodeline->privsize;
515 Data32(dpy, (long *) newmodeline->private,
516 newmodeline->privsize * sizeof(INT32));
517 }
518 } else {
519 GetReq(XF86VidModeAddModeLine, req);
520 req->reqType = info->codes->major_opcode;
521 req->xf86vidmodeReqType = X_XF86VidModeAddModeLine;
522 req->screen = screen;
523 req->dotclock = newmodeline->dotclock;
524 req->hdisplay = newmodeline->hdisplay;
525 req->hsyncstart = newmodeline->hsyncstart;
526 req->hsyncend = newmodeline->hsyncend;
527 req->htotal = newmodeline->htotal;
528 req->hskew = newmodeline->hskew;
529 req->vdisplay = newmodeline->vdisplay;
530 req->vsyncstart = newmodeline->vsyncstart;
531 req->vsyncend = newmodeline->vsyncend;
532 req->vtotal = newmodeline->vtotal;
533 req->flags = newmodeline->flags;
534 req->privsize = newmodeline->privsize;
535 if (aftermodeline != NULL) {
536 req->after_dotclock = aftermodeline->dotclock;
537 req->after_hdisplay = aftermodeline->hdisplay;
538 req->after_hsyncstart = aftermodeline->hsyncstart;
539 req->after_hsyncend = aftermodeline->hsyncend;
540 req->after_htotal = aftermodeline->htotal;
541 req->after_hskew = aftermodeline->hskew;
542 req->after_vdisplay = aftermodeline->vdisplay;
543 req->after_vsyncstart = aftermodeline->vsyncstart;
544 req->after_vsyncend = aftermodeline->vsyncend;
545 req->after_vtotal = aftermodeline->vtotal;
546 req->after_flags = aftermodeline->flags;
547 } else {
548 req->after_dotclock = 0;
549 req->after_hdisplay = 0;
550 req->after_hsyncstart = 0;
551 req->after_hsyncend = 0;
552 req->after_htotal = 0;
553 req->after_hskew = 0;
554 req->after_vdisplay = 0;
555 req->after_vsyncstart = 0;
556 req->after_vsyncend = 0;
557 req->after_vtotal = 0;
558 req->after_flags = 0;
559 }
560 if (newmodeline->privsize) {
561 req->length += newmodeline->privsize;
562 Data32(dpy, (long *) newmodeline->private,
563 newmodeline->privsize * sizeof(INT32));
564 }
565 }
566 UnlockDisplay(dpy);
567 SyncHandle();
568 return True;
569}
570
571Bool
572SDL_NAME(XF86VidModeDeleteModeLine) (dpy, screen, modeline)
573 Display *dpy;
574 int screen;
575 SDL_NAME(XF86VidModeModeInfo)* modeline;
576{
577 XExtDisplayInfo *info = find_display (dpy);
578 xXF86VidModeDeleteModeLineReq *req;
579 xXF86OldVidModeDeleteModeLineReq *oldreq;
580 int majorVersion, minorVersion;
581
582 XF86VidModeCheckExtension (dpy, info, 0);
583 SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion);
584
585 LockDisplay(dpy);
586 if (majorVersion < 2) {
587 GetOldReq(XF86VidModeDeleteModeLine, XF86OldVidModeDeleteModeLine, oldreq);
588 oldreq->reqType = info->codes->major_opcode;
589 oldreq->xf86vidmodeReqType = X_XF86VidModeDeleteModeLine;
590 oldreq->screen = screen;
591 oldreq->dotclock = modeline->dotclock;
592 oldreq->hdisplay = modeline->hdisplay;
593 oldreq->hsyncstart = modeline->hsyncstart;
594 oldreq->hsyncend = modeline->hsyncend;
595 oldreq->htotal = modeline->htotal;
596 oldreq->vdisplay = modeline->vdisplay;
597 oldreq->vsyncstart = modeline->vsyncstart;
598 oldreq->vsyncend = modeline->vsyncend;
599 oldreq->vtotal = modeline->vtotal;
600 oldreq->flags = modeline->flags;
601 oldreq->privsize = modeline->privsize;
602 if (modeline->privsize) {
603 oldreq->length += modeline->privsize;
604 Data32(dpy, (long *) modeline->private,
605 modeline->privsize * sizeof(INT32));
606 }
607 } else {
608 GetReq(XF86VidModeDeleteModeLine, req);
609 req->reqType = info->codes->major_opcode;
610 req->xf86vidmodeReqType = X_XF86VidModeDeleteModeLine;
611 req->screen = screen;
612 req->dotclock = modeline->dotclock;
613 req->hdisplay = modeline->hdisplay;
614 req->hsyncstart = modeline->hsyncstart;
615 req->hsyncend = modeline->hsyncend;
616 req->htotal = modeline->htotal;
617 req->hskew = modeline->hskew;
618 req->vdisplay = modeline->vdisplay;
619 req->vsyncstart = modeline->vsyncstart;
620 req->vsyncend = modeline->vsyncend;
621 req->vtotal = modeline->vtotal;
622 req->flags = modeline->flags;
623 req->privsize = modeline->privsize;
624 if (modeline->privsize) {
625 req->length += modeline->privsize;
626 Data32(dpy, (long *) modeline->private,
627 modeline->privsize * sizeof(INT32));
628 }
629 }
630 UnlockDisplay(dpy);
631 SyncHandle();
632 return True;
633}
634
635Bool
636SDL_NAME(XF86VidModeModModeLine) (dpy, screen, modeline)
637 Display *dpy;
638 int screen;
639 SDL_NAME(XF86VidModeModeLine)* modeline;
640{
641 XExtDisplayInfo *info = find_display (dpy);
642 xXF86VidModeModModeLineReq *req;
643 xXF86OldVidModeModModeLineReq *oldreq;
644 int majorVersion, minorVersion;
645
646 XF86VidModeCheckExtension (dpy, info, 0);
647 SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion);
648
649 LockDisplay(dpy);
650 if (majorVersion < 2) {
651 GetOldReq(XF86VidModeModModeLine, XF86OldVidModeModModeLine, oldreq);
652 oldreq->reqType = info->codes->major_opcode;
653 oldreq->xf86vidmodeReqType = X_XF86VidModeModModeLine;
654 oldreq->screen = screen;
655 oldreq->hdisplay = modeline->hdisplay;
656 oldreq->hsyncstart = modeline->hsyncstart;
657 oldreq->hsyncend = modeline->hsyncend;
658 oldreq->htotal = modeline->htotal;
659 oldreq->vdisplay = modeline->vdisplay;
660 oldreq->vsyncstart = modeline->vsyncstart;
661 oldreq->vsyncend = modeline->vsyncend;
662 oldreq->vtotal = modeline->vtotal;
663 oldreq->flags = modeline->flags;
664 oldreq->privsize = modeline->privsize;
665 if (modeline->privsize) {
666 oldreq->length += modeline->privsize;
667 Data32(dpy, (long *) modeline->private,
668 modeline->privsize * sizeof(INT32));
669 }
670 } else {
671 GetReq(XF86VidModeModModeLine, req);
672 req->reqType = info->codes->major_opcode;
673 req->xf86vidmodeReqType = X_XF86VidModeModModeLine;
674 req->screen = screen;
675 req->hdisplay = modeline->hdisplay;
676 req->hsyncstart = modeline->hsyncstart;
677 req->hsyncend = modeline->hsyncend;
678 req->htotal = modeline->htotal;
679 req->hskew = modeline->hskew;
680 req->vdisplay = modeline->vdisplay;
681 req->vsyncstart = modeline->vsyncstart;
682 req->vsyncend = modeline->vsyncend;
683 req->vtotal = modeline->vtotal;
684 req->flags = modeline->flags;
685 req->privsize = modeline->privsize;
686 if (modeline->privsize) {
687 req->length += modeline->privsize;
688 Data32(dpy, (long *) modeline->private,
689 modeline->privsize * sizeof(INT32));
690 }
691 }
692 UnlockDisplay(dpy);
693 SyncHandle();
694 return True;
695}
696
697Status
698SDL_NAME(XF86VidModeValidateModeLine) (dpy, screen, modeline)
699 Display *dpy;
700 int screen;
701 SDL_NAME(XF86VidModeModeInfo)* modeline;
702{
703 XExtDisplayInfo *info = find_display (dpy);
704 xXF86VidModeValidateModeLineReq *req;
705 xXF86OldVidModeValidateModeLineReq *oldreq;
706 xXF86VidModeValidateModeLineReply rep;
707 int majorVersion, minorVersion;
708
709 XF86VidModeCheckExtension (dpy, info, 0);
710 SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion);
711
712 LockDisplay(dpy);
713
714 if (majorVersion < 2) {
715 GetOldReq(XF86VidModeValidateModeLine, XF86OldVidModeValidateModeLine, oldreq);
716 oldreq->reqType = info->codes->major_opcode;
717 oldreq->xf86vidmodeReqType = X_XF86VidModeValidateModeLine;
718 oldreq->screen = screen;
719 oldreq->dotclock = modeline->dotclock;
720 oldreq->hdisplay = modeline->hdisplay;
721 oldreq->hsyncstart = modeline->hsyncstart;
722 oldreq->hsyncend = modeline->hsyncend;
723 oldreq->htotal = modeline->htotal;
724 oldreq->vdisplay = modeline->vdisplay;
725 oldreq->vsyncstart = modeline->vsyncstart;
726 oldreq->vsyncend = modeline->vsyncend;
727 oldreq->vtotal = modeline->vtotal;
728 oldreq->flags = modeline->flags;
729 oldreq->privsize = modeline->privsize;
730 if (modeline->privsize) {
731 oldreq->length += modeline->privsize;
732 Data32(dpy, (long *) modeline->private,
733 modeline->privsize * sizeof(INT32));
734 }
735 } else {
736 GetReq(XF86VidModeValidateModeLine, req);
737 req->reqType = info->codes->major_opcode;
738 req->xf86vidmodeReqType = X_XF86VidModeValidateModeLine;
739 req->screen = screen;
740 req->dotclock = modeline->dotclock;
741 req->hdisplay = modeline->hdisplay;
742 req->hsyncstart = modeline->hsyncstart;
743 req->hsyncend = modeline->hsyncend;
744 req->htotal = modeline->htotal;
745 req->hskew = modeline->hskew;
746 req->vdisplay = modeline->vdisplay;
747 req->vsyncstart = modeline->vsyncstart;
748 req->vsyncend = modeline->vsyncend;
749 req->vtotal = modeline->vtotal;
750 req->flags = modeline->flags;
751 req->privsize = modeline->privsize;
752 if (modeline->privsize) {
753 req->length += modeline->privsize;
754 Data32(dpy, (long *) modeline->private,
755 modeline->privsize * sizeof(INT32));
756 }
757 }
758 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
759 UnlockDisplay(dpy);
760 SyncHandle();
761 return MODE_BAD;
762 }
763 UnlockDisplay(dpy);
764 SyncHandle();
765 return rep.status;
766}
767
768Bool
769SDL_NAME(XF86VidModeSwitchMode)(dpy, screen, zoom)
770 Display* dpy;
771 int screen;
772 int zoom;
773{
774 XExtDisplayInfo *info = find_display (dpy);
775 xXF86VidModeSwitchModeReq *req;
776
777 XF86VidModeCheckExtension (dpy, info, False);
778
779 LockDisplay(dpy);
780 GetReq(XF86VidModeSwitchMode, req);
781 req->reqType = info->codes->major_opcode;
782 req->xf86vidmodeReqType = X_XF86VidModeSwitchMode;
783 req->screen = screen;
784 req->zoom = zoom;
785 UnlockDisplay(dpy);
786 SyncHandle();
787 return True;
788}
789
790Bool
791SDL_NAME(XF86VidModeSwitchToMode)(dpy, screen, modeline)
792 Display* dpy;
793 int screen;
794 SDL_NAME(XF86VidModeModeInfo)* modeline;
795{
796 XExtDisplayInfo *info = find_display (dpy);
797 xXF86VidModeSwitchToModeReq *req;
798 xXF86OldVidModeSwitchToModeReq *oldreq;
799 int majorVersion, minorVersion;
800 Bool protocolBug = False;
801
802 XF86VidModeCheckExtension (dpy, info, False);
803
804 /*
805 * Note: There was a bug in the protocol implementation in versions
806 * 0.x with x < 8 (the .private field wasn't expected to be sent over
807 * the wire). Check the server's version, and accept the old format
808 * if appropriate.
809 */
810
811 SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion);
812 if (majorVersion == 0 && minorVersion < 8) {
813 protocolBug = True;
814#ifdef DEBUG
815 fprintf(stderr, "XF86VidModeSwitchToMode: Warning: Xserver is"
816 "running an old version (%d.%d)\n", majorVersion,
817 minorVersion);
818#endif
819 }
820
821 LockDisplay(dpy);
822 if (majorVersion < 2) {
823 GetOldReq(XF86VidModeSwitchToMode, XF86OldVidModeSwitchToMode, oldreq);
824 oldreq->reqType = info->codes->major_opcode;
825 oldreq->xf86vidmodeReqType = X_XF86VidModeSwitchToMode;
826 oldreq->screen = screen;
827 oldreq->dotclock = modeline->dotclock;
828 oldreq->hdisplay = modeline->hdisplay;
829 oldreq->hsyncstart = modeline->hsyncstart;
830 oldreq->hsyncend = modeline->hsyncend;
831 oldreq->htotal = modeline->htotal;
832 oldreq->vdisplay = modeline->vdisplay;
833 oldreq->vsyncstart = modeline->vsyncstart;
834 oldreq->vsyncend = modeline->vsyncend;
835 oldreq->vtotal = modeline->vtotal;
836 oldreq->flags = modeline->flags;
837 if (protocolBug) {
838 oldreq->privsize = 0;
839 } else {
840 oldreq->privsize = modeline->privsize;
841 if (modeline->privsize) {
842 oldreq->length += modeline->privsize;
843 Data32(dpy, (long *) modeline->private,
844 modeline->privsize * sizeof(INT32));
845 }
846 }
847 } else {
848 GetReq(XF86VidModeSwitchToMode, req);
849 req->reqType = info->codes->major_opcode;
850 req->xf86vidmodeReqType = X_XF86VidModeSwitchToMode;
851 req->screen = screen;
852 req->dotclock = modeline->dotclock;
853 req->hdisplay = modeline->hdisplay;
854 req->hsyncstart = modeline->hsyncstart;
855 req->hsyncend = modeline->hsyncend;
856 req->htotal = modeline->htotal;
857 req->hskew = modeline->hskew;
858 req->vdisplay = modeline->vdisplay;
859 req->vsyncstart = modeline->vsyncstart;
860 req->vsyncend = modeline->vsyncend;
861 req->vtotal = modeline->vtotal;
862 req->flags = modeline->flags;
863 if (protocolBug) {
864 req->privsize = 0;
865 } else {
866 req->privsize = modeline->privsize;
867 if (modeline->privsize) {
868 req->length += modeline->privsize;
869 Data32(dpy, (long *) modeline->private,
870 modeline->privsize * sizeof(INT32));
871 }
872 }
873 }
874 UnlockDisplay(dpy);
875 SyncHandle();
876 return True;
877}
878
879Bool
880SDL_NAME(XF86VidModeLockModeSwitch)(dpy, screen, lock)
881 Display* dpy;
882 int screen;
883 int lock;
884{
885 XExtDisplayInfo *info = find_display (dpy);
886 xXF86VidModeLockModeSwitchReq *req;
887
888 XF86VidModeCheckExtension (dpy, info, False);
889
890 LockDisplay(dpy);
891 GetReq(XF86VidModeLockModeSwitch, req);
892 req->reqType = info->codes->major_opcode;
893 req->xf86vidmodeReqType = X_XF86VidModeLockModeSwitch;
894 req->screen = screen;
895 req->lock = lock;
896 UnlockDisplay(dpy);
897 SyncHandle();
898 return True;
899}
900
901Bool
902SDL_NAME(XF86VidModeGetMonitor)(dpy, screen, monitor)
903 Display* dpy;
904 int screen;
905 SDL_NAME(XF86VidModeMonitor)* monitor;
906{
907 XExtDisplayInfo *info = find_display (dpy);
908 xXF86VidModeGetMonitorReply rep;
909 xXF86VidModeGetMonitorReq *req;
910 CARD32 syncrange;
911 int i;
912
913 XF86VidModeCheckExtension (dpy, info, False);
914
915 LockDisplay(dpy);
916 GetReq(XF86VidModeGetMonitor, req);
917 req->reqType = info->codes->major_opcode;
918 req->xf86vidmodeReqType = X_XF86VidModeGetMonitor;
919 req->screen = screen;
920 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
921 UnlockDisplay(dpy);
922 SyncHandle();
923 return False;
924 }
925 monitor->nhsync = rep.nhsync;
926 monitor->nvsync = rep.nvsync;
927#if 0
928 monitor->bandwidth = (float)rep.bandwidth / 1e6;
929#endif
930 if (rep.vendorLength) {
931 if (!(monitor->vendor = (char *)Xcalloc(rep.vendorLength + 1, 1))) {
932 _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 +
933 ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3));
934 UnlockDisplay(dpy);
935 SyncHandle();
936 return False;
937 }
938 } else {
939 monitor->vendor = NULL;
940 }
941 if (rep.modelLength) {
942 if (!(monitor->model = Xcalloc(rep.modelLength + 1, 1))) {
943 _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 +
944 ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3));
945 if (monitor->vendor)
946 Xfree(monitor->vendor);
947 UnlockDisplay(dpy);
948 SyncHandle();
949 return False;
950 }
951 } else {
952 monitor->model = NULL;
953 }
954 if (!(monitor->hsync = Xcalloc(rep.nhsync, sizeof(SDL_NAME(XF86VidModeSyncRange))))) {
955 _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 +
956 ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3));
957
958 if (monitor->vendor)
959 Xfree(monitor->vendor);
960 if (monitor->model)
961 Xfree(monitor->model);
962 UnlockDisplay(dpy);
963 SyncHandle();
964 return False;
965 }
966 if (!(monitor->vsync = Xcalloc(rep.nvsync, sizeof(SDL_NAME(XF86VidModeSyncRange))))) {
967 _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 +
968 ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3));
969 if (monitor->vendor)
970 Xfree(monitor->vendor);
971 if (monitor->model)
972 Xfree(monitor->model);
973 Xfree(monitor->hsync);
974 UnlockDisplay(dpy);
975 SyncHandle();
976 return False;
977 }
978 for (i = 0; i < rep.nhsync; i++) {
979 _XRead(dpy, (char *)&syncrange, 4);
980 monitor->hsync[i].lo = (float)(syncrange & 0xFFFF) / 100.0;
981 monitor->hsync[i].hi = (float)(syncrange >> 16) / 100.0;
982 }
983 for (i = 0; i < rep.nvsync; i++) {
984 _XRead(dpy, (char *)&syncrange, 4);
985 monitor->vsync[i].lo = (float)(syncrange & 0xFFFF) / 100.0;
986 monitor->vsync[i].hi = (float)(syncrange >> 16) / 100.0;
987 }
988 if (rep.vendorLength)
989 _XReadPad(dpy, monitor->vendor, rep.vendorLength);
990 else
991 monitor->vendor = "";
992 if (rep.modelLength)
993 _XReadPad(dpy, monitor->model, rep.modelLength);
994 else
995 monitor->model = "";
996
997 UnlockDisplay(dpy);
998 SyncHandle();
999 return True;
1000}
1001
1002Bool
1003SDL_NAME(XF86VidModeGetViewPort)(dpy, screen, x, y)
1004 Display* dpy;
1005 int screen;
1006 int *x, *y;
1007{
1008 XExtDisplayInfo *info = find_display (dpy);
1009 xXF86VidModeGetViewPortReply rep;
1010 xXF86VidModeGetViewPortReq *req;
1011 int majorVersion, minorVersion;
1012 Bool protocolBug = False;
1013
1014 XF86VidModeCheckExtension (dpy, info, False);
1015
1016 /*
1017 * Note: There was a bug in the protocol implementation in versions
1018 * 0.x with x < 8 (no reply was sent, so the client would hang)
1019 * Check the server's version, and don't wait for a reply with older
1020 * versions.
1021 */
1022
1023 SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion);
1024 if (majorVersion == 0 && minorVersion < 8) {
1025 protocolBug = True;
1026#ifdef DEBUG
1027 fprintf(stderr, "XF86VidModeGetViewPort: Warning: Xserver is"
1028 "running an old version (%d.%d)\n", majorVersion,
1029 minorVersion);
1030#endif
1031 }
1032 LockDisplay(dpy);
1033 GetReq(XF86VidModeGetViewPort, req);
1034 req->reqType = info->codes->major_opcode;
1035 req->xf86vidmodeReqType = X_XF86VidModeGetViewPort;
1036 req->screen = screen;
1037 if (protocolBug) {
1038 *x = 0;
1039 *y = 0;
1040 } else {
1041 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
1042 UnlockDisplay(dpy);
1043 SyncHandle();
1044 return False;
1045 }
1046 *x = rep.x;
1047 *y = rep.y;
1048 }
1049
1050 UnlockDisplay(dpy);
1051 SyncHandle();
1052 return True;
1053}
1054
1055Bool
1056SDL_NAME(XF86VidModeSetViewPort)(dpy, screen, x, y)
1057 Display* dpy;
1058 int screen;
1059 int x, y;
1060{
1061 XExtDisplayInfo *info = find_display (dpy);
1062 xXF86VidModeSetViewPortReq *req;
1063
1064 XF86VidModeCheckExtension (dpy, info, False);
1065
1066 LockDisplay(dpy);
1067 GetReq(XF86VidModeSetViewPort, req);
1068 req->reqType = info->codes->major_opcode;
1069 req->xf86vidmodeReqType = X_XF86VidModeSetViewPort;
1070 req->screen = screen;
1071 req->x = x;
1072 req->y = y;
1073
1074 UnlockDisplay(dpy);
1075 SyncHandle();
1076 return True;
1077}
1078
1079Bool
1080SDL_NAME(XF86VidModeGetDotClocks)(dpy, screen,
1081 flagsPtr, numclocksPtr, maxclocksPtr, clocksPtr)
1082 Display* dpy;
1083 int screen;
1084 int *flagsPtr, *numclocksPtr, *maxclocksPtr, *clocksPtr[];
1085{
1086 XExtDisplayInfo *info = find_display (dpy);
1087 xXF86VidModeGetDotClocksReply rep;
1088 xXF86VidModeGetDotClocksReq *req;
1089 int i, *dotclocks;
1090 CARD32 dotclk;
1091
1092 XF86VidModeCheckExtension (dpy, info, False);
1093
1094 LockDisplay(dpy);
1095 GetReq(XF86VidModeGetDotClocks, req);
1096 req->reqType = info->codes->major_opcode;
1097 req->xf86vidmodeReqType = X_XF86VidModeGetDotClocks;
1098 req->screen = screen;
1099 if (!_XReply(dpy, (xReply *)&rep,
1100 (SIZEOF(xXF86VidModeGetDotClocksReply) - SIZEOF(xReply)) >> 2, xFalse))
1101 {
1102 UnlockDisplay(dpy);
1103 SyncHandle();
1104 return False;
1105 }
1106 *numclocksPtr = rep.clocks;
1107 *maxclocksPtr = rep.maxclocks;
1108 *flagsPtr = rep.flags;
1109
1110 if (!(dotclocks = (int*) Xcalloc(rep.clocks, sizeof(int)))) {
1111 _XEatData(dpy, (rep.clocks) * 4);
1112 Xfree(dotclocks);
1113 UnlockDisplay(dpy);
1114 SyncHandle();
1115 return False;
1116 }
1117
1118 for (i = 0; i < rep.clocks; i++) {
1119 _XRead(dpy, (char*)&dotclk, 4);
1120 dotclocks[i] = dotclk;
1121 }
1122 *clocksPtr = dotclocks;
1123 UnlockDisplay(dpy);
1124 SyncHandle();
1125 return True;
1126}
1127
1128Bool
1129SDL_NAME(XF86VidModeSetGammaRamp) (
1130 Display *dpy,
1131 int screen,
1132 int size,
1133 unsigned short *red,
1134 unsigned short *green,
1135 unsigned short *blue
1136)
1137{
1138 int length = (size + 1) & ~1;
1139 XExtDisplayInfo *info = find_display (dpy);
1140 xXF86VidModeSetGammaRampReq *req;
1141
1142 XF86VidModeCheckExtension (dpy, info, False);
1143 LockDisplay(dpy);
1144 GetReq(XF86VidModeSetGammaRamp, req);
1145 req->reqType = info->codes->major_opcode;
1146 req->xf86vidmodeReqType = X_XF86VidModeSetGammaRamp;
1147 req->screen = screen;
1148 req->length += (length >> 1) * 3;
1149 req->size = size;
1150 _XSend(dpy, (char*)red, size * 2);
1151 _XSend(dpy, (char*)green, size * 2);
1152 _XSend(dpy, (char*)blue, size * 2);
1153 UnlockDisplay(dpy);
1154 SyncHandle();
1155 return True;
1156}
1157
1158
1159Bool
1160SDL_NAME(XF86VidModeGetGammaRamp) (
1161 Display *dpy,
1162 int screen,
1163 int size,
1164 unsigned short *red,
1165 unsigned short *green,
1166 unsigned short *blue
1167)
1168{
1169 XExtDisplayInfo *info = find_display (dpy);
1170 xXF86VidModeGetGammaRampReq *req;
1171 xXF86VidModeGetGammaRampReply rep;
1172
1173 XF86VidModeCheckExtension (dpy, info, False);
1174
1175 LockDisplay(dpy);
1176 GetReq(XF86VidModeGetGammaRamp, req);
1177 req->reqType = info->codes->major_opcode;
1178 req->xf86vidmodeReqType = X_XF86VidModeGetGammaRamp;
1179 req->screen = screen;
1180 req->size = size;
1181 if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
1182 UnlockDisplay (dpy);
1183 SyncHandle ();
1184 return False;
1185 }
1186 if(rep.size) {
1187 _XRead(dpy, (char*)red, rep.size << 1);
1188 _XRead(dpy, (char*)green, rep.size << 1);
1189 _XRead(dpy, (char*)blue, rep.size << 1);
1190 }
1191
1192 UnlockDisplay(dpy);
1193 SyncHandle();
1194 return True;
1195}
1196
1197Bool SDL_NAME(XF86VidModeGetGammaRampSize)(
1198 Display *dpy,
1199 int screen,
1200 int *size
1201)
1202{
1203 XExtDisplayInfo *info = find_display (dpy);
1204 xXF86VidModeGetGammaRampSizeReq *req;
1205 xXF86VidModeGetGammaRampSizeReply rep;
1206
1207 *size = 0;
1208
1209 XF86VidModeCheckExtension (dpy, info, False);
1210
1211 LockDisplay(dpy);
1212 GetReq(XF86VidModeGetGammaRampSize, req);
1213 req->reqType = info->codes->major_opcode;
1214 req->xf86vidmodeReqType = X_XF86VidModeGetGammaRampSize;
1215 req->screen = screen;
1216 if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
1217 UnlockDisplay (dpy);
1218 SyncHandle ();
1219 return False;
1220 }
1221 *size = rep.size;
1222 UnlockDisplay(dpy);
1223 SyncHandle();
1224 return True;
1225}
1226
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/Xext.h b/apps/plugins/sdl/src/video/Xext/extensions/Xext.h
deleted file mode 100644
index 9edf3194b4..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/Xext.h
+++ /dev/null
@@ -1,50 +0,0 @@
1/*
2Copyright 1989, 1998 The Open Group
3
4Permission to use, copy, modify, distribute, and sell this software and its
5documentation for any purpose is hereby granted without fee, provided that
6the above copyright notice appear in all copies and that both that
7copyright notice and this permission notice appear in supporting
8documentation.
9
10The above copyright notice and this permission notice shall be included in
11all copies or substantial portions of the Software.
12
13THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
17AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
20Except as contained in this notice, the name of The Open Group shall not be
21used in advertising or otherwise to promote the sale, use or other dealings
22in this Software without prior written authorization from The Open Group.
23 */
24/* $XFree86: xc/include/extensions/Xext.h,v 1.7 2005/01/27 03:03:09 dawes Exp $ */
25
26#ifndef _XEXT_H_
27#define _XEXT_H_
28
29#include <X11/Xfuncproto.h>
30
31_XFUNCPROTOBEGIN
32
33typedef int (*XExtensionErrorHandler)(Display *, _Xconst char *,
34 _Xconst char *);
35
36extern XExtensionErrorHandler XSetExtensionErrorHandler(
37 XExtensionErrorHandler handler
38);
39
40extern int XMissingExtension(
41 Display* /* dpy */,
42 _Xconst char* /* ext_name */
43);
44
45_XFUNCPROTOEND
46
47#define X_EXTENSION_UNKNOWN "unknown"
48#define X_EXTENSION_MISSING "missing"
49
50#endif /* _XEXT_H_ */
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/Xinerama.h b/apps/plugins/sdl/src/video/Xext/extensions/Xinerama.h
deleted file mode 100644
index 54f2fe17d2..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/Xinerama.h
+++ /dev/null
@@ -1,46 +0,0 @@
1/* $XFree86: xc/include/extensions/Xinerama.h,v 3.2 2000/03/01 01:04:20 dawes Exp $ */
2
3#ifndef _Xinerama_h
4#define _Xinerama_h
5
6#include "SDL_name.h"
7
8typedef struct {
9 int screen_number;
10 short x_org;
11 short y_org;
12 short width;
13 short height;
14} SDL_NAME(XineramaScreenInfo);
15
16Bool SDL_NAME(XineramaQueryExtension) (
17 Display *dpy,
18 int *event_base,
19 int *error_base
20);
21
22Status SDL_NAME(XineramaQueryVersion)(
23 Display *dpy,
24 int *major,
25 int *minor
26);
27
28Bool SDL_NAME(XineramaIsActive)(Display *dpy);
29
30
31/*
32 Returns the number of heads and a pointer to an array of
33 structures describing the position and size of the individual
34 heads. Returns NULL and number = 0 if Xinerama is not active.
35
36 Returned array should be freed with XFree().
37*/
38
39SDL_NAME(XineramaScreenInfo) *
40SDL_NAME(XineramaQueryScreens)(
41 Display *dpy,
42 int *number
43);
44
45#endif /* _Xinerama_h */
46
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/Xv.h b/apps/plugins/sdl/src/video/Xext/extensions/Xv.h
deleted file mode 100644
index a6a027195f..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/Xv.h
+++ /dev/null
@@ -1,129 +0,0 @@
1/***********************************************************
2Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts,
3and the Massachusetts Institute of Technology, Cambridge, Massachusetts.
4
5 All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Digital or MIT not be
12used in advertising or publicity pertaining to distribution of the
13software without specific, written prior permission.
14
15DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
16ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
17DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
18ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
19WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
20ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
21SOFTWARE.
22
23******************************************************************/
24/* $XFree86: xc/include/extensions/Xv.h,v 1.5 1999/12/11 19:28:48 mvojkovi Exp $ */
25
26#ifndef XV_H
27#define XV_H
28/*
29** File:
30**
31** Xv.h --- Xv shared library and server header file
32**
33** Author:
34**
35** David Carver (Digital Workstation Engineering/Project Athena)
36**
37** Revisions:
38**
39** 05.15.91 Carver
40** - version 2.0 upgrade
41**
42** 01.24.91 Carver
43** - version 1.4 upgrade
44**
45*/
46
47#include <X11/X.h>
48
49#define XvName "XVideo"
50#define XvVersion 2
51#define XvRevision 2
52
53/* Symbols */
54
55typedef XID XvPortID;
56typedef XID XvEncodingID;
57
58#define XvNone 0
59
60#define XvInput 0
61#define XvOutput 1
62
63#define XvInputMask (1L<<XvInput)
64#define XvOutputMask (1L<<XvOutput)
65#define XvVideoMask 0x00000004
66#define XvStillMask 0x00000008
67#define XvImageMask 0x00000010
68
69/* These two are not client viewable */
70#define XvPixmapMask 0x00010000
71#define XvWindowMask 0x00020000
72
73
74#define XvGettable 0x01
75#define XvSettable 0x02
76
77#define XvRGB 0
78#define XvYUV 1
79
80#define XvPacked 0
81#define XvPlanar 1
82
83#define XvTopToBottom 0
84#define XvBottomToTop 1
85
86
87/* Events */
88
89#define XvVideoNotify 0
90#define XvPortNotify 1
91#define XvNumEvents 2
92
93/* Video Notify Reasons */
94
95#define XvStarted 0
96#define XvStopped 1
97#define XvBusy 2
98#define XvPreempted 3
99#define XvHardError 4
100#define XvLastReason 4
101
102#define XvNumReasons (XvLastReason + 1)
103
104#define XvStartedMask (1L<<XvStarted)
105#define XvStoppedMask (1L<<XvStopped)
106#define XvBusyMask (1L<<XvBusy)
107#define XvPreemptedMask (1L<<XvPreempted)
108#define XvHardErrorMask (1L<<XvHardError)
109
110#define XvAnyReasonMask ((1L<<XvNumReasons) - 1)
111#define XvNoReasonMask 0
112
113/* Errors */
114
115#define XvBadPort 0
116#define XvBadEncoding 1
117#define XvBadControl 2
118#define XvNumErrors 3
119
120/* Status */
121
122#define XvBadExtension 1
123#define XvAlreadyGrabbed 2
124#define XvInvalidTime 3
125#define XvBadReply 4
126#define XvBadAlloc 5
127
128#endif /* XV_H */
129
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/Xvlib.h b/apps/plugins/sdl/src/video/Xext/extensions/Xvlib.h
deleted file mode 100644
index 0d0a55da40..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/Xvlib.h
+++ /dev/null
@@ -1,433 +0,0 @@
1/***********************************************************
2Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts,
3and the Massachusetts Institute of Technology, Cambridge, Massachusetts.
4
5 All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Digital or MIT not be
12used in advertising or publicity pertaining to distribution of the
13software without specific, written prior permission.
14
15DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
16ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
17DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
18ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
19WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
20ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
21SOFTWARE.
22
23******************************************************************/
24/* $XFree86: xc/include/extensions/Xvlib.h,v 1.3 1999/12/11 19:28:48 mvojkovi Exp $ */
25
26#ifndef XVLIB_H
27#define XVLIB_H
28/*
29** File:
30**
31** Xvlib.h --- Xv library public header file
32**
33** Author:
34**
35** David Carver (Digital Workstation Engineering/Project Athena)
36**
37** Revisions:
38**
39** 26.06.91 Carver
40** - changed XvFreeAdaptors to XvFreeAdaptorInfo
41** - changed XvFreeEncodings to XvFreeEncodingInfo
42**
43** 11.06.91 Carver
44** - changed SetPortControl to SetPortAttribute
45** - changed GetPortControl to GetPortAttribute
46** - changed QueryBestSize
47**
48** 05.15.91 Carver
49** - version 2.0 upgrade
50**
51** 01.24.91 Carver
52** - version 1.4 upgrade
53**
54*/
55
56#include <X11/Xfuncproto.h>
57#include "Xv.h"
58#include "SDL_name.h"
59
60typedef struct {
61 int numerator;
62 int denominator;
63} SDL_NAME(XvRational);
64
65typedef struct {
66 int flags; /* XvGettable, XvSettable */
67 int min_value;
68 int max_value;
69 char *name;
70} SDL_NAME(XvAttribute);
71
72typedef struct {
73 XvEncodingID encoding_id;
74 char *name;
75 unsigned long width;
76 unsigned long height;
77 SDL_NAME(XvRational) rate;
78 unsigned long num_encodings;
79} SDL_NAME(XvEncodingInfo);
80
81typedef struct {
82 char depth;
83 unsigned long visual_id;
84} SDL_NAME(XvFormat);
85
86typedef struct {
87 XvPortID base_id;
88 unsigned long num_ports;
89 char type;
90 char *name;
91 unsigned long num_formats;
92 SDL_NAME(XvFormat) *formats;
93 unsigned long num_adaptors;
94} SDL_NAME(XvAdaptorInfo);
95
96typedef struct {
97 int type;
98 unsigned long serial; /* # of last request processed by server */
99 Bool send_event; /* true if this came from a SendEvent request */
100 Display *display; /* Display the event was read from */
101 Drawable drawable; /* drawable */
102 unsigned long reason; /* what generated this event */
103 XvPortID port_id; /* what port */
104 Time time; /* milliseconds */
105} SDL_NAME(XvVideoNotifyEvent);
106
107typedef struct {
108 int type;
109 unsigned long serial; /* # of last request processed by server */
110 Bool send_event; /* true if this came from a SendEvent request */
111 Display *display; /* Display the event was read from */
112 XvPortID port_id; /* what port */
113 Time time; /* milliseconds */
114 Atom attribute; /* atom that identifies attribute */
115 long value; /* value of attribute */
116} SDL_NAME(XvPortNotifyEvent);
117
118typedef union {
119 int type;
120 SDL_NAME(XvVideoNotifyEvent) xvvideo;
121 SDL_NAME(XvPortNotifyEvent) xvport;
122 long pad[24];
123} SDL_NAME(XvEvent);
124
125typedef struct {
126 int id; /* Unique descriptor for the format */
127 int type; /* XvRGB, XvYUV */
128 int byte_order; /* LSBFirst, MSBFirst */
129 char guid[16]; /* Globally Unique IDentifier */
130 int bits_per_pixel;
131 int format; /* XvPacked, XvPlanar */
132 int num_planes;
133
134 /* for RGB formats only */
135 int depth;
136 unsigned int red_mask;
137 unsigned int green_mask;
138 unsigned int blue_mask;
139
140 /* for YUV formats only */
141 unsigned int y_sample_bits;
142 unsigned int u_sample_bits;
143 unsigned int v_sample_bits;
144 unsigned int horz_y_period;
145 unsigned int horz_u_period;
146 unsigned int horz_v_period;
147 unsigned int vert_y_period;
148 unsigned int vert_u_period;
149 unsigned int vert_v_period;
150 char component_order[32]; /* eg. UYVY */
151 int scanline_order; /* XvTopToBottom, XvBottomToTop */
152} SDL_NAME(XvImageFormatValues);
153
154typedef struct {
155 int id;
156 int width, height;
157 int data_size; /* bytes */
158 int num_planes;
159 int *pitches; /* bytes */
160 int *offsets; /* bytes */
161 char *data;
162 XPointer obdata;
163} SDL_NAME(XvImage);
164
165_XFUNCPROTOBEGIN
166
167extern int SDL_NAME(XvQueryExtension)(
168#if NeedFunctionPrototypes
169 Display* /* display */,
170 unsigned int* /* p_version */,
171 unsigned int* /* p_revision */,
172 unsigned int* /* p_requestBase */,
173 unsigned int* /* p_eventBase */,
174 unsigned int* /* p_errorBase */
175#endif
176);
177
178extern int SDL_NAME(XvQueryAdaptors)(
179#if NeedFunctionPrototypes
180 Display* /* display */,
181 Window /* window */,
182 unsigned int* /* p_nAdaptors */,
183 SDL_NAME(XvAdaptorInfo)** /* p_pAdaptors */
184#endif
185);
186
187extern int SDL_NAME(XvQueryEncodings)(
188#if NeedFunctionPrototypes
189 Display* /* display */,
190 XvPortID /* port */,
191 unsigned int* /* p_nEncoding */,
192 SDL_NAME(XvEncodingInfo)** /* p_pEncoding */
193#endif
194);
195
196extern int SDL_NAME(XvPutVideo)(
197#if NeedFunctionPrototypes
198 Display* /* display */,
199 XvPortID /* port */,
200 Drawable /* d */,
201 GC /* gc */,
202 int /* vx */,
203 int /* vy */,
204 unsigned int /* vw */,
205 unsigned int /* vh */,
206 int /* dx */,
207 int /* dy */,
208 unsigned int /* dw */,
209 unsigned int /* dh */
210#endif
211);
212
213extern int SDL_NAME(XvPutStill)(
214#if NeedFunctionPrototypes
215 Display* /* display */,
216 XvPortID /* port */,
217 Drawable /* d */,
218 GC /* gc */,
219 int /* vx */,
220 int /* vy */,
221 unsigned int /* vw */,
222 unsigned int /* vh */,
223 int /* dx */,
224 int /* dy */,
225 unsigned int /* dw */,
226 unsigned int /* dh */
227#endif
228);
229
230extern int SDL_NAME(XvGetVideo)(
231#if NeedFunctionPrototypes
232 Display* /* display */,
233 XvPortID /* port */,
234 Drawable /* d */,
235 GC /* gc */,
236 int /* vx */,
237 int /* vy */,
238 unsigned int /* vw */,
239 unsigned int /* vh */,
240 int /* dx */,
241 int /* dy */,
242 unsigned int /* dw */,
243 unsigned int /* dh */
244#endif
245);
246
247extern int SDL_NAME(XvGetStill)(
248#if NeedFunctionPrototypes
249 Display* /* display */,
250 XvPortID /* port */,
251 Drawable /* d */,
252 GC /* gc */,
253 int /* vx */,
254 int /* vy */,
255 unsigned int /* vw */,
256 unsigned int /* vh */,
257 int /* dx */,
258 int /* dy */,
259 unsigned int /* dw */,
260 unsigned int /* dh */
261#endif
262);
263
264extern int SDL_NAME(XvStopVideo)(
265#if NeedFunctionPrototypes
266 Display* /* display */,
267 XvPortID /* port */,
268 Drawable /* drawable */
269#endif
270);
271
272extern int SDL_NAME(XvGrabPort)(
273#if NeedFunctionPrototypes
274 Display* /* display */,
275 XvPortID /* port */,
276 Time /* time */
277#endif
278);
279
280extern int SDL_NAME(XvUngrabPort)(
281#if NeedFunctionPrototypes
282 Display* /* display */,
283 XvPortID /* port */,
284 Time /* time */
285#endif
286);
287
288extern int SDL_NAME(XvSelectVideoNotify)(
289#if NeedFunctionPrototypes
290 Display* /* display */,
291 Drawable /* drawable */,
292 Bool /* onoff */
293#endif
294);
295
296extern int SDL_NAME(XvSelectPortNotify)(
297#if NeedFunctionPrototypes
298 Display* /* display */,
299 XvPortID /* port */,
300 Bool /* onoff */
301#endif
302);
303
304extern int SDL_NAME(XvSetPortAttribute)(
305#if NeedFunctionPrototypes
306 Display* /* display */,
307 XvPortID /* port */,
308 Atom /* attribute */,
309 int /* value */
310#endif
311);
312
313extern int SDL_NAME(XvGetPortAttribute)(
314#if NeedFunctionPrototypes
315 Display* /* display */,
316 XvPortID /* port */,
317 Atom /* attribute */,
318 int* /* p_value */
319#endif
320);
321
322extern int SDL_NAME(XvQueryBestSize)(
323#if NeedFunctionPrototypes
324 Display* /* display */,
325 XvPortID /* port */,
326 Bool /* motion */,
327 unsigned int /* vid_w */,
328 unsigned int /* vid_h */,
329 unsigned int /* drw_w */,
330 unsigned int /* drw_h */,
331 unsigned int* /* p_actual_width */,
332 unsigned int* /* p_actual_width */
333#endif
334);
335
336extern SDL_NAME(XvAttribute)* SDL_NAME(XvQueryPortAttributes)(
337#if NeedFunctionPrototypes
338 Display* /* display */,
339 XvPortID /* port */,
340 int* /* number */
341#endif
342);
343
344
345extern void SDL_NAME(XvFreeAdaptorInfo)(
346#if NeedFunctionPrototypes
347 SDL_NAME(XvAdaptorInfo)* /* adaptors */
348#endif
349);
350
351extern void SDL_NAME(XvFreeEncodingInfo)(
352#if NeedFunctionPrototypes
353 SDL_NAME(XvEncodingInfo)* /* encodings */
354#endif
355);
356
357
358extern SDL_NAME(XvImageFormatValues) * SDL_NAME(XvListImageFormats) (
359#if NeedFunctionPrototypes
360 Display *display,
361 XvPortID port_id,
362 int *count_return
363#endif
364);
365
366extern SDL_NAME(XvImage) * SDL_NAME(XvCreateImage) (
367#if NeedFunctionPrototypes
368 Display *display,
369 XvPortID port,
370 int id,
371 char *data,
372 int width,
373 int height
374#endif
375);
376
377extern int SDL_NAME(XvPutImage) (
378#if NeedFunctionPrototypes
379 Display *display,
380 XvPortID id,
381 Drawable d,
382 GC gc,
383 SDL_NAME(XvImage) *image,
384 int src_x,
385 int src_y,
386 unsigned int src_w,
387 unsigned int src_h,
388 int dest_x,
389 int dest_y,
390 unsigned int dest_w,
391 unsigned int dest_h
392#endif
393);
394
395extern int SDL_NAME(XvShmPutImage) (
396#if NeedFunctionPrototypes
397 Display *display,
398 XvPortID id,
399 Drawable d,
400 GC gc,
401 SDL_NAME(XvImage) *image,
402 int src_x,
403 int src_y,
404 unsigned int src_w,
405 unsigned int src_h,
406 int dest_x,
407 int dest_y,
408 unsigned int dest_w,
409 unsigned int dest_h,
410 Bool send_event
411#endif
412);
413
414#ifdef _XSHM_H_
415
416extern SDL_NAME(XvImage) * SDL_NAME(XvShmCreateImage) (
417#if NeedFunctionPrototypes
418 Display *display,
419 XvPortID port,
420 int id,
421 char* data,
422 int width,
423 int height,
424 XShmSegmentInfo *shminfo
425#endif
426);
427
428#endif
429
430
431_XFUNCPROTOEND
432
433#endif /* XVLIB_H */
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/Xvproto.h b/apps/plugins/sdl/src/video/Xext/extensions/Xvproto.h
deleted file mode 100644
index b4d8f22cdc..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/Xvproto.h
+++ /dev/null
@@ -1,604 +0,0 @@
1/***********************************************************
2Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts,
3and the Massachusetts Institute of Technology, Cambridge, Massachusetts.
4
5 All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Digital or MIT not be
12used in advertising or publicity pertaining to distribution of the
13software without specific, written prior permission.
14
15DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
16ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
17DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
18ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
19WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
20ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
21SOFTWARE.
22
23******************************************************************/
24/* $XFree86: xc/include/extensions/Xvproto.h,v 1.6 2001/05/07 21:37:12 tsi Exp $ */
25
26#ifndef XVPROTO_H
27#define XVPROTO_H
28/*
29** File:
30**
31** Xvproto.h --- Xv protocol header file
32**
33** Author:
34**
35** David Carver (Digital Workstation Engineering/Project Athena)
36**
37** Revisions:
38**
39** 11.06.91 Carver
40** - changed SetPortControl to SetPortAttribute
41** - changed GetPortControl to GetPortAttribute
42** - changed QueryBestSize
43**
44** 15.05.91 Carver
45** - version 2.0 upgrade
46**
47** 24.01.91 Carver
48** - version 1.4 upgrade
49**
50*/
51
52#include <X11/Xmd.h>
53
54/* Symbols: These are undefined at the end of this file to restore the
55 values they have in Xv.h */
56
57#define XvPortID CARD32
58#define XvEncodingID CARD32
59#define ShmSeg CARD32
60#define VisualID CARD32
61#define Drawable CARD32
62#define GContext CARD32
63#define Time CARD32
64#define Atom CARD32
65
66/* Structures */
67
68typedef struct {
69 INT32 numerator B32;
70 INT32 denominator B32;
71} xvRational;
72#define sz_xvRational 8
73
74typedef struct {
75 XvPortID base_id B32;
76 CARD16 name_size B16;
77 CARD16 num_ports B16;
78 CARD16 num_formats B16;
79 CARD8 type;
80 CARD8 pad;
81} xvAdaptorInfo;
82#define sz_xvAdaptorInfo 12
83
84typedef struct {
85 XvEncodingID encoding B32;
86 CARD16 name_size B16;
87 CARD16 width B16, height B16;
88 xvRational rate;
89 CARD16 pad B16;
90} xvEncodingInfo;
91#define sz_xvEncodingInfo (12 + sz_xvRational)
92
93typedef struct {
94 VisualID visual B32;
95 CARD8 depth;
96 CARD8 pad1;
97 CARD16 pad2 B16;
98} xvFormat;
99#define sz_xvFormat 8
100
101typedef struct {
102 CARD32 flags B32;
103 INT32 min B32;
104 INT32 max B32;
105 CARD32 size B32;
106} xvAttributeInfo;
107#define sz_xvAttributeInfo 16
108
109typedef struct {
110 CARD32 id B32;
111 CARD8 type;
112 CARD8 byte_order;
113 CARD16 pad1 B16;
114 CARD8 guid[16];
115 CARD8 bpp;
116 CARD8 num_planes;
117 CARD16 pad2 B16;
118 CARD8 depth;
119 CARD8 pad3;
120 CARD16 pad4 B16;
121 CARD32 red_mask B32;
122 CARD32 green_mask B32;
123 CARD32 blue_mask B32;
124 CARD8 format;
125 CARD8 pad5;
126 CARD16 pad6 B16;
127 CARD32 y_sample_bits B32;
128 CARD32 u_sample_bits B32;
129 CARD32 v_sample_bits B32;
130 CARD32 horz_y_period B32;
131 CARD32 horz_u_period B32;
132 CARD32 horz_v_period B32;
133 CARD32 vert_y_period B32;
134 CARD32 vert_u_period B32;
135 CARD32 vert_v_period B32;
136 CARD8 comp_order[32];
137 CARD8 scanline_order;
138 CARD8 pad7;
139 CARD16 pad8 B16;
140 CARD32 pad9 B32;
141 CARD32 pad10 B32;
142} xvImageFormatInfo;
143#define sz_xvImageFormatInfo 128
144
145
146/* Requests */
147
148#define xv_QueryExtension 0
149#define xv_QueryAdaptors 1
150#define xv_QueryEncodings 2
151#define xv_GrabPort 3
152#define xv_UngrabPort 4
153#define xv_PutVideo 5
154#define xv_PutStill 6
155#define xv_GetVideo 7
156#define xv_GetStill 8
157#define xv_StopVideo 9
158#define xv_SelectVideoNotify 10
159#define xv_SelectPortNotify 11
160#define xv_QueryBestSize 12
161#define xv_SetPortAttribute 13
162#define xv_GetPortAttribute 14
163#define xv_QueryPortAttributes 15
164#define xv_ListImageFormats 16
165#define xv_QueryImageAttributes 17
166#define xv_PutImage 18
167#define xv_ShmPutImage 19
168#define xv_LastRequest xv_ShmPutImage
169
170#define xvNumRequests (xv_LastRequest + 1)
171
172typedef struct {
173 CARD8 reqType;
174 CARD8 xvReqType;
175 CARD16 length B16;
176} xvQueryExtensionReq;
177#define sz_xvQueryExtensionReq 4
178
179typedef struct {
180 CARD8 reqType;
181 CARD8 xvReqType;
182 CARD16 length B16;
183 CARD32 window B32;
184} xvQueryAdaptorsReq;
185#define sz_xvQueryAdaptorsReq 8
186
187typedef struct {
188 CARD8 reqType;
189 CARD8 xvReqType;
190 CARD16 length B16;
191 CARD32 port B32;
192} xvQueryEncodingsReq;
193#define sz_xvQueryEncodingsReq 8
194
195typedef struct {
196 CARD8 reqType;
197 CARD8 xvReqType;
198 CARD16 length B16;
199 XvPortID port B32;
200 Drawable drawable B32;
201 GContext gc B32;
202 INT16 vid_x B16;
203 INT16 vid_y B16;
204 CARD16 vid_w B16;
205 CARD16 vid_h B16;
206 INT16 drw_x B16;
207 INT16 drw_y B16;
208 CARD16 drw_w B16;
209 CARD16 drw_h B16;
210} xvPutVideoReq;
211#define sz_xvPutVideoReq 32
212
213typedef struct {
214 CARD8 reqType;
215 CARD8 xvReqType;
216 CARD16 length B16;
217 XvPortID port B32;
218 Drawable drawable B32;
219 GContext gc B32;
220 INT16 vid_x B16;
221 INT16 vid_y B16;
222 CARD16 vid_w B16;
223 CARD16 vid_h B16;
224 INT16 drw_x B16;
225 INT16 drw_y B16;
226 CARD16 drw_w B16;
227 CARD16 drw_h B16;
228} xvPutStillReq;
229#define sz_xvPutStillReq 32
230
231typedef struct {
232 CARD8 reqType;
233 CARD8 xvReqType;
234 CARD16 length B16;
235 XvPortID port B32;
236 Drawable drawable B32;
237 GContext gc B32;
238 INT16 vid_x B16;
239 INT16 vid_y B16;
240 CARD16 vid_w B16;
241 CARD16 vid_h B16;
242 INT16 drw_x B16;
243 INT16 drw_y B16;
244 CARD16 drw_w B16;
245 CARD16 drw_h B16;
246} xvGetVideoReq;
247#define sz_xvGetVideoReq 32
248
249typedef struct {
250 CARD8 reqType;
251 CARD8 xvReqType;
252 CARD16 length B16;
253 XvPortID port B32;
254 Drawable drawable B32;
255 GContext gc B32;
256 INT16 vid_x B16;
257 INT16 vid_y B16;
258 CARD16 vid_w B16;
259 CARD16 vid_h B16;
260 INT16 drw_x B16;
261 INT16 drw_y B16;
262 CARD16 drw_w B16;
263 CARD16 drw_h B16;
264} xvGetStillReq;
265#define sz_xvGetStillReq 32
266
267typedef struct {
268 CARD8 reqType;
269 CARD8 xvReqType;
270 CARD16 length B16;
271 XvPortID port B32;
272 Time time B32;
273} xvGrabPortReq;
274#define sz_xvGrabPortReq 12
275
276typedef struct {
277 CARD8 reqType;
278 CARD8 xvReqType;
279 CARD16 length B16;
280 XvPortID port B32;
281 Time time B32;
282} xvUngrabPortReq;
283#define sz_xvUngrabPortReq 12
284
285typedef struct {
286 CARD8 reqType;
287 CARD8 xvReqType;
288 CARD16 length B16;
289 Drawable drawable B32;
290 BOOL onoff;
291 CARD8 pad1;
292 CARD16 pad2;
293} xvSelectVideoNotifyReq;
294#define sz_xvSelectVideoNotifyReq 12
295
296typedef struct {
297 CARD8 reqType;
298 CARD8 xvReqType;
299 CARD16 length B16;
300 XvPortID port B32;
301 BOOL onoff;
302 CARD8 pad1;
303 CARD16 pad2;
304} xvSelectPortNotifyReq;
305#define sz_xvSelectPortNotifyReq 12
306
307typedef struct {
308 CARD8 reqType;
309 CARD8 xvReqType;
310 CARD16 length B16;
311 XvPortID port B32;
312 Drawable drawable B32;
313} xvStopVideoReq;
314#define sz_xvStopVideoReq 12
315
316typedef struct {
317 CARD8 reqType;
318 CARD8 xvReqType;
319 CARD16 length B16;
320 XvPortID port B32;
321 Atom attribute B32;
322 INT32 value B32;
323} xvSetPortAttributeReq;
324#define sz_xvSetPortAttributeReq 16
325
326typedef struct {
327 CARD8 reqType;
328 CARD8 xvReqType;
329 CARD16 length B16;
330 XvPortID port B32;
331 Atom attribute B32;
332} xvGetPortAttributeReq;
333#define sz_xvGetPortAttributeReq 12
334
335typedef struct {
336 CARD8 reqType;
337 CARD8 xvReqType;
338 CARD16 length B16;
339 XvPortID port B32;
340 CARD16 vid_w B16;
341 CARD16 vid_h B16;
342 CARD16 drw_w B16;
343 CARD16 drw_h B16;
344 CARD8 motion;
345 CARD8 pad1;
346 CARD16 pad2 B16;
347} xvQueryBestSizeReq;
348#define sz_xvQueryBestSizeReq 20
349
350typedef struct {
351 CARD8 reqType;
352 CARD8 xvReqType;
353 CARD16 length B16;
354 XvPortID port B32;
355} xvQueryPortAttributesReq;
356#define sz_xvQueryPortAttributesReq 8
357
358typedef struct {
359 CARD8 reqType;
360 CARD8 xvReqType;
361 CARD16 length B16;
362 XvPortID port B32;
363 Drawable drawable B32;
364 GContext gc B32;
365 CARD32 id B32;
366 INT16 src_x B16;
367 INT16 src_y B16;
368 CARD16 src_w B16;
369 CARD16 src_h B16;
370 INT16 drw_x B16;
371 INT16 drw_y B16;
372 CARD16 drw_w B16;
373 CARD16 drw_h B16;
374 CARD16 width B16;
375 CARD16 height B16;
376} xvPutImageReq;
377#define sz_xvPutImageReq 40
378
379typedef struct {
380 CARD8 reqType;
381 CARD8 xvReqType;
382 CARD16 length B16;
383 XvPortID port B32;
384 Drawable drawable B32;
385 GContext gc B32;
386 ShmSeg shmseg B32;
387 CARD32 id B32;
388 CARD32 offset B32;
389 INT16 src_x B16;
390 INT16 src_y B16;
391 CARD16 src_w B16;
392 CARD16 src_h B16;
393 INT16 drw_x B16;
394 INT16 drw_y B16;
395 CARD16 drw_w B16;
396 CARD16 drw_h B16;
397 CARD16 width B16;
398 CARD16 height B16;
399 CARD8 send_event;
400 CARD8 pad1;
401 CARD16 pad2 B16;
402} xvShmPutImageReq;
403#define sz_xvShmPutImageReq 52
404
405typedef struct {
406 CARD8 reqType;
407 CARD8 xvReqType;
408 CARD16 length B16;
409 XvPortID port B32;
410} xvListImageFormatsReq;
411#define sz_xvListImageFormatsReq 8
412
413typedef struct {
414 CARD8 reqType;
415 CARD8 xvReqType;
416 CARD16 length B16;
417 CARD32 port B32;
418 CARD32 id B32;
419 CARD16 width B16;
420 CARD16 height B16;
421} xvQueryImageAttributesReq;
422#define sz_xvQueryImageAttributesReq 16
423
424
425/* Replies */
426
427typedef struct _QueryExtensionReply {
428 BYTE type; /* X_Reply */
429 CARD8 padb1;
430 CARD16 sequenceNumber B16;
431 CARD32 length B32;
432 CARD16 version B16;
433 CARD16 revision B16;
434 CARD32 padl4 B32;
435 CARD32 padl5 B32;
436 CARD32 padl6 B32;
437 CARD32 padl7 B32;
438 CARD32 padl8 B32;
439} xvQueryExtensionReply;
440#define sz_xvQueryExtensionReply 32
441
442typedef struct _QueryAdaptorsReply {
443 BYTE type; /* X_Reply */
444 CARD8 padb1;
445 CARD16 sequenceNumber B16;
446 CARD32 length B32;
447 CARD16 num_adaptors B16;
448 CARD16 pads3 B16;
449 CARD32 padl4 B32;
450 CARD32 padl5 B32;
451 CARD32 padl6 B32;
452 CARD32 padl7 B32;
453 CARD32 padl8 B32;
454} xvQueryAdaptorsReply;
455#define sz_xvQueryAdaptorsReply 32
456
457typedef struct _QueryEncodingsReply {
458 BYTE type; /* X_Reply */
459 CARD8 padb1;
460 CARD16 sequenceNumber B16;
461 CARD32 length B32;
462 CARD16 num_encodings B16;
463 CARD32 padl3 B32;
464 CARD32 padl4 B32;
465 CARD32 padl5 B32;
466 CARD32 padl6 B32;
467 CARD32 padl7 B32;
468 CARD32 padl8 B32;
469} xvQueryEncodingsReply;
470#define sz_xvQueryEncodingsReply 32
471
472typedef struct {
473 BYTE type; /* X_Reply */
474 BYTE result;
475 CARD16 sequenceNumber B16;
476 CARD32 length B32; /* 0 */
477 CARD32 padl3 B32;
478 CARD32 padl4 B32;
479 CARD32 padl5 B32;
480 CARD32 padl6 B32;
481 CARD32 padl7 B32;
482 CARD32 padl8 B32;
483} xvGrabPortReply;
484#define sz_xvGrabPortReply 32
485
486typedef struct {
487 BYTE type; /* X_Reply */
488 BYTE padb1;
489 CARD16 sequenceNumber B16;
490 CARD32 length B32; /* 0 */
491 INT32 value B32;
492 CARD32 padl4 B32;
493 CARD32 padl5 B32;
494 CARD32 padl6 B32;
495 CARD32 padl7 B32;
496 CARD32 padl8 B32;
497} xvGetPortAttributeReply;
498#define sz_xvGetPortAttributeReply 32
499
500typedef struct {
501 BYTE type; /* X_Reply */
502 BYTE padb1;
503 CARD16 sequenceNumber B16;
504 CARD32 length B32; /* 0 */
505 CARD16 actual_width B16;
506 CARD16 actual_height B16;
507 CARD32 padl4 B32;
508 CARD32 padl5 B32;
509 CARD32 padl6 B32;
510 CARD32 padl7 B32;
511 CARD32 padl8 B32;
512} xvQueryBestSizeReply;
513#define sz_xvQueryBestSizeReply 32
514
515typedef struct {
516 BYTE type; /* X_Reply */
517 BYTE padb1;
518 CARD16 sequenceNumber B16;
519 CARD32 length B32; /* 0 */
520 CARD32 num_attributes B32;
521 CARD32 text_size B32;
522 CARD32 padl5 B32;
523 CARD32 padl6 B32;
524 CARD32 padl7 B32;
525 CARD32 padl8 B32;
526} xvQueryPortAttributesReply;
527#define sz_xvQueryPortAttributesReply 32
528
529typedef struct {
530 BYTE type; /* X_Reply */
531 BYTE padb1;
532 CARD16 sequenceNumber B16;
533 CARD32 length B32;
534 CARD32 num_formats B32;
535 CARD32 padl4 B32;
536 CARD32 padl5 B32;
537 CARD32 padl6 B32;
538 CARD32 padl7 B32;
539 CARD32 padl8 B32;
540} xvListImageFormatsReply;
541#define sz_xvListImageFormatsReply 32
542
543typedef struct {
544 BYTE type; /* X_Reply */
545 BYTE padb1;
546 CARD16 sequenceNumber B16;
547 CARD32 length B32;
548 CARD32 num_planes B32;
549 CARD32 data_size B32;
550 CARD16 width B16;
551 CARD16 height B16;
552 CARD32 padl6 B32;
553 CARD32 padl7 B32;
554 CARD32 padl8 B32;
555} xvQueryImageAttributesReply;
556#define sz_xvQueryImageAttributesReply 32
557
558/* DEFINE EVENT STRUCTURE */
559
560typedef struct {
561 union {
562 struct {
563 BYTE type;
564 BYTE detail;
565 CARD16 sequenceNumber B16;
566 } u;
567 struct {
568 BYTE type;
569 BYTE reason;
570 CARD16 sequenceNumber B16;
571 Time time B32;
572 Drawable drawable B32;
573 XvPortID port B32;
574 CARD32 padl5 B32;
575 CARD32 padl6 B32;
576 CARD32 padl7 B32;
577 CARD32 padl8 B32;
578 } videoNotify;
579 struct {
580 BYTE type;
581 BYTE padb1;
582 CARD16 sequenceNumber B16;
583 Time time B32;
584 XvPortID port B32;
585 Atom attribute B32;
586 INT32 value B32;
587 CARD32 padl6 B32;
588 CARD32 padl7 B32;
589 CARD32 padl8 B32;
590 } portNotify;
591 } u;
592} xvEvent;
593
594#undef XvPortID
595#undef XvEncodingID
596#undef ShmSeg
597#undef VisualID
598#undef Drawable
599#undef GContext
600#undef Time
601#undef Atom
602
603#endif /* XVPROTO_H */
604
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/extutil.h b/apps/plugins/sdl/src/video/Xext/extensions/extutil.h
deleted file mode 100644
index f3a741ea22..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/extutil.h
+++ /dev/null
@@ -1,226 +0,0 @@
1/*
2 * $Xorg: extutil.h,v 1.4 2001/02/09 02:03:24 xorgcvs Exp $
3 *
4Copyright 1989, 1998 The Open Group
5
6Permission to use, copy, modify, distribute, and sell this software and its
7documentation for any purpose is hereby granted without fee, provided that
8the above copyright notice appear in all copies and that both that
9copyright notice and this permission notice appear in supporting
10documentation.
11
12The above copyright notice and this permission notice shall be included in
13all copies or substantial portions of the Software.
14
15THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
19AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22Except as contained in this notice, the name of The Open Group shall not be
23used in advertising or otherwise to promote the sale, use or other dealings
24in this Software without prior written authorization from The Open Group.
25 *
26 * Author: Jim Fulton, MIT The Open Group
27 *
28 * Xlib Extension-Writing Utilities
29 *
30 * This package contains utilities for writing the client API for various
31 * protocol extensions. THESE INTERFACES ARE NOT PART OF THE X STANDARD AND
32 * ARE SUBJECT TO CHANGE!
33 */
34/* $XFree86: xc/include/extensions/extutil.h,v 1.9 2001/12/14 19:53:28 dawes Exp $ */
35
36#ifndef _EXTUTIL_H_
37#define _EXTUTIL_H_
38
39#include "SDL_stdinc.h" /* For portable string functions */
40
41#include "./Xext.h"
42
43/*
44 * We need to keep a list of open displays since the Xlib display list isn't
45 * public. We also have to per-display info in a separate block since it isn't
46 * stored directly in the Display structure.
47 */
48typedef struct _XExtDisplayInfo {
49 struct _XExtDisplayInfo *next; /* keep a linked list */
50 Display *display; /* which display this is */
51 XExtCodes *codes; /* the extension protocol codes */
52 XPointer data; /* extra data for extension to use */
53} XExtDisplayInfo;
54
55typedef struct _XExtensionInfo {
56 XExtDisplayInfo *head; /* start of list */
57 XExtDisplayInfo *cur; /* most recently used */
58 int ndisplays; /* number of displays */
59} XExtensionInfo;
60
61typedef struct _XExtensionHooks {
62 int (*create_gc)(
63#if NeedNestedPrototypes
64 Display* /* display */,
65 GC /* gc */,
66 XExtCodes* /* codes */
67#endif
68);
69 int (*copy_gc)(
70#if NeedNestedPrototypes
71 Display* /* display */,
72 GC /* gc */,
73 XExtCodes* /* codes */
74#endif
75);
76 int (*flush_gc)(
77#if NeedNestedPrototypes
78 Display* /* display */,
79 GC /* gc */,
80 XExtCodes* /* codes */
81#endif
82);
83 int (*free_gc)(
84#if NeedNestedPrototypes
85 Display* /* display */,
86 GC /* gc */,
87 XExtCodes* /* codes */
88#endif
89);
90 int (*create_font)(
91#if NeedNestedPrototypes
92 Display* /* display */,
93 XFontStruct* /* fs */,
94 XExtCodes* /* codes */
95#endif
96);
97 int (*free_font)(
98#if NeedNestedPrototypes
99 Display* /* display */,
100 XFontStruct* /* fs */,
101 XExtCodes* /* codes */
102#endif
103);
104 int (*close_display)(
105#if NeedNestedPrototypes
106 Display* /* display */,
107 XExtCodes* /* codes */
108#endif
109);
110 Bool (*wire_to_event)(
111#if NeedNestedPrototypes
112 Display* /* display */,
113 XEvent* /* re */,
114 xEvent* /* event */
115#endif
116);
117 Status (*event_to_wire)(
118#if NeedNestedPrototypes
119 Display* /* display */,
120 XEvent* /* re */,
121 xEvent* /* event */
122#endif
123);
124 int (*error)(
125#if NeedNestedPrototypes
126 Display* /* display */,
127 xError* /* err */,
128 XExtCodes* /* codes */,
129 int* /* ret_code */
130#endif
131);
132 char *(*error_string)(
133#if NeedNestedPrototypes
134 Display* /* display */,
135 int /* code */,
136 XExtCodes* /* codes */,
137 char* /* buffer */,
138 int /* nbytes */
139#endif
140);
141} XExtensionHooks;
142
143extern XExtensionInfo *XextCreateExtension(
144#if NeedFunctionPrototypes
145 void
146#endif
147);
148extern void XextDestroyExtension(
149#if NeedFunctionPrototypes
150 XExtensionInfo* /* info */
151#endif
152);
153extern XExtDisplayInfo *XextAddDisplay(
154#if NeedFunctionPrototypes
155 XExtensionInfo* /* extinfo */,
156 Display* /* dpy */,
157 char* /* ext_name */,
158 XExtensionHooks* /* hooks */,
159 int /* nevents */,
160 XPointer /* data */
161#endif
162);
163extern int XextRemoveDisplay(
164#if NeedFunctionPrototypes
165 XExtensionInfo* /* extinfo */,
166 Display* /* dpy */
167#endif
168);
169extern XExtDisplayInfo *XextFindDisplay(
170#if NeedFunctionPrototypes
171 XExtensionInfo* /* extinfo */,
172 Display* /* dpy */
173#endif
174);
175
176#define XextHasExtension(i) ((i) && ((i)->codes))
177#define XextCheckExtension(dpy,i,name,val) \
178 if (!XextHasExtension(i)) { XMissingExtension (dpy, name); return val; }
179#define XextSimpleCheckExtension(dpy,i,name) \
180 if (!XextHasExtension(i)) { XMissingExtension (dpy, name); return; }
181
182
183/*
184 * helper macros to generate code that is common to all extensions; caller
185 * should prefix it with static if extension source is in one file; this
186 * could be a utility function, but have to stack 6 unused arguments for
187 * something that is called many, many times would be bad.
188 */
189#define XEXT_GENERATE_FIND_DISPLAY(proc,extinfo,extname,hooks,nev,data) \
190XExtDisplayInfo *proc (Display *dpy) \
191{ \
192 XExtDisplayInfo *dpyinfo; \
193 if (!extinfo) { if (!(extinfo = XextCreateExtension())) return NULL; } \
194 if (!(dpyinfo = XextFindDisplay (extinfo, dpy))) \
195 dpyinfo = XextAddDisplay (extinfo,dpy,extname,hooks,nev,data); \
196 return dpyinfo; \
197}
198
199#define XEXT_FIND_DISPLAY_PROTO(proc) \
200 XExtDisplayInfo *proc(Display *dpy)
201
202#define XEXT_GENERATE_CLOSE_DISPLAY(proc,extinfo) \
203int proc (Display *dpy, XExtCodes *codes) \
204{ \
205 return XextRemoveDisplay (extinfo, dpy); \
206}
207
208#define XEXT_CLOSE_DISPLAY_PROTO(proc) \
209 int proc(Display *dpy, XExtCodes *codes)
210
211#define XEXT_GENERATE_ERROR_STRING(proc,extname,nerr,errl) \
212char *proc (Display *dpy, int code, XExtCodes *codes, char *buf, int n) \
213{ \
214 code -= codes->first_error; \
215 if (code >= 0 && code < nerr) { \
216 char tmp[256]; \
217 SDL_snprintf (tmp, SDL_arraysize(tmp), "%s.%d", extname, code); \
218 XGetErrorDatabaseText (dpy, "XProtoError", tmp, errl[code], buf, n); \
219 return buf; \
220 } \
221 return (char *)0; \
222}
223
224#define XEXT_ERROR_STRING_PROTO(proc) \
225 char *proc(Display *dpy, int code, XExtCodes *codes, char *buf, int n)
226#endif
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/panoramiXext.h b/apps/plugins/sdl/src/video/Xext/extensions/panoramiXext.h
deleted file mode 100644
index e89d8917bb..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/panoramiXext.h
+++ /dev/null
@@ -1,52 +0,0 @@
1/* $Xorg: panoramiXext.h,v 1.4 2000/08/18 04:05:45 coskrey Exp $ */
2/*****************************************************************
3Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts.
4Permission is hereby granted, free of charge, to any person obtaining a copy
5of this software and associated documentation files (the "Software"), to deal
6in the Software without restriction, including without limitation the rights
7to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8copies of the Software.
9
10The above copyright notice and this permission notice shall be included in
11all copies or substantial portions of the Software.
12
13THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING,
17BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL DAMAGES, OR OTHER LIABILITY,
18WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
19IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20
21Except as contained in this notice, the name of Digital Equipment Corporation
22shall not be used in advertising or otherwise to promote the sale, use or other
23dealings in this Software without prior written authorization from Digital
24Equipment Corporation.
25******************************************************************/
26/*
27 * PanoramiX definitions
28 */
29/* $XFree86: xc/include/extensions/panoramiXext.h,v 3.6 2001/01/17 17:53:22 dawes Exp $ */
30
31#include "SDL_name.h"
32
33/* THIS IS NOT AN X PROJECT TEAM SPECIFICATION */
34
35#define PANORAMIX_MAJOR_VERSION 1 /* current version number */
36#define PANORAMIX_MINOR_VERSION 1
37
38typedef struct {
39 Window window; /* PanoramiX window - may not exist */
40 int screen;
41 int State; /* PanroamiXOff, PanoramiXOn */
42 int width; /* width of this screen */
43 int height; /* height of this screen */
44 int ScreenCount; /* real physical number of screens */
45 XID eventMask; /* selected events for this client */
46} SDL_NAME(XPanoramiXInfo);
47
48extern SDL_NAME(XPanoramiXInfo) *SDL_NAME(XPanoramiXAllocInfo) (
49#if NeedFunctionPrototypes
50 void
51#endif
52);
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/panoramiXproto.h b/apps/plugins/sdl/src/video/Xext/extensions/panoramiXproto.h
deleted file mode 100644
index fe3826eb3b..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/panoramiXproto.h
+++ /dev/null
@@ -1,192 +0,0 @@
1/* $Xorg: panoramiXproto.h,v 1.4 2000/08/18 04:05:45 coskrey Exp $ */
2/*****************************************************************
3Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts.
4Permission is hereby granted, free of charge, to any person obtaining a copy
5of this software and associated documentation files (the "Software"), to deal
6in the Software without restriction, including without limitation the rights
7to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8copies of the Software.
9
10The above copyright notice and this permission notice shall be included in
11all copies or substantial portions of the Software.
12
13THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING,
17BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL DAMAGES, OR OTHER LIABILITY,
18WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
19IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20
21Except as contained in this notice, the name of Digital Equipment Corporation
22shall not be used in advertising or otherwise to promote the sale, use or other
23dealings in this Software without prior written authorization from Digital
24Equipment Corporation.
25******************************************************************/
26/* $XFree86: xc/include/extensions/panoramiXproto.h,v 3.6 2001/01/17 17:53:22 dawes Exp $ */
27
28/* THIS IS NOT AN X PROJECT TEAM SPECIFICATION */
29
30#ifndef _PANORAMIXPROTO_H_
31#define _PANORAMIXPROTO_H_
32
33#define PANORAMIX_PROTOCOL_NAME "XINERAMA"
34
35#define X_PanoramiXQueryVersion 0
36#define X_PanoramiXGetState 1
37#define X_PanoramiXGetScreenCount 2
38#define X_PanoramiXGetScreenSize 3
39
40#define X_XineramaIsActive 4
41#define X_XineramaQueryScreens 5
42
43typedef struct _PanoramiXQueryVersion {
44 CARD8 reqType; /* always PanoramiXReqCode */
45 CARD8 panoramiXReqType; /* always X_PanoramiXQueryVersion */
46 CARD16 length B16;
47 CARD8 clientMajor;
48 CARD8 clientMinor;
49 CARD16 unused B16;
50} xPanoramiXQueryVersionReq;
51
52#define sz_xPanoramiXQueryVersionReq 8
53
54typedef struct {
55 CARD8 type; /* must be X_Reply */
56 CARD8 pad1; /* unused */
57 CARD16 sequenceNumber B16; /* last sequence number */
58 CARD32 length B32; /* 0 */
59 CARD16 majorVersion B16;
60 CARD16 minorVersion B16;
61 CARD32 pad2 B32; /* unused */
62 CARD32 pad3 B32; /* unused */
63 CARD32 pad4 B32; /* unused */
64 CARD32 pad5 B32; /* unused */
65 CARD32 pad6 B32; /* unused */
66} xPanoramiXQueryVersionReply;
67
68#define sz_xPanoramiXQueryVersionReply 32
69
70
71typedef struct _PanoramiXGetState {
72 CARD8 reqType; /* always PanoramiXReqCode */
73 CARD8 panoramiXReqType; /* always X_PanoramiXGetState */
74 CARD16 length B16;
75 CARD32 window B32;
76} xPanoramiXGetStateReq;
77#define sz_xPanoramiXGetStateReq 8
78
79typedef struct {
80 BYTE type;
81 BYTE state;
82 CARD16 sequenceNumber B16;
83 CARD32 length B32;
84 CARD32 window B32;
85 CARD32 pad1 B32; /* unused */
86 CARD32 pad2 B32; /* unused */
87 CARD32 pad3 B32; /* unused */
88 CARD32 pad4 B32; /* unused */
89 CARD32 pad5 B32; /* unused */
90} xPanoramiXGetStateReply;
91
92#define sz_panoramiXGetStateReply 32
93
94typedef struct _PanoramiXGetScreenCount {
95 CARD8 reqType; /* always PanoramiXReqCode */
96 CARD8 panoramiXReqType; /* always X_PanoramiXGetScreenCount */
97 CARD16 length B16;
98 CARD32 window B32;
99} xPanoramiXGetScreenCountReq;
100#define sz_xPanoramiXGetScreenCountReq 8
101
102typedef struct {
103 BYTE type;
104 BYTE ScreenCount;
105 CARD16 sequenceNumber B16;
106 CARD32 length B32;
107 CARD32 window B32;
108 CARD32 pad1 B32; /* unused */
109 CARD32 pad2 B32; /* unused */
110 CARD32 pad3 B32; /* unused */
111 CARD32 pad4 B32; /* unused */
112 CARD32 pad5 B32; /* unused */
113} xPanoramiXGetScreenCountReply;
114#define sz_panoramiXGetScreenCountReply 32
115
116typedef struct _PanoramiXGetScreenSize {
117 CARD8 reqType; /* always PanoramiXReqCode */
118 CARD8 panoramiXReqType; /* always X_PanoramiXGetState */
119 CARD16 length B16;
120 CARD32 window B32;
121 CARD32 screen B32;
122} xPanoramiXGetScreenSizeReq;
123#define sz_xPanoramiXGetScreenSizeReq 12
124
125typedef struct {
126 BYTE type;
127 CARD8 pad1;
128 CARD16 sequenceNumber B16;
129 CARD32 length B32;
130 CARD32 width B32;
131 CARD32 height B32;
132 CARD32 window B32;
133 CARD32 screen B32;
134 CARD32 pad2 B32; /* unused */
135 CARD32 pad3 B32; /* unused */
136} xPanoramiXGetScreenSizeReply;
137#define sz_panoramiXGetScreenSizeReply 32
138
139/************ Alternate protocol ******************/
140
141typedef struct {
142 CARD8 reqType;
143 CARD8 panoramiXReqType;
144 CARD16 length B16;
145} xXineramaIsActiveReq;
146#define sz_xXineramaIsActiveReq 4
147
148typedef struct {
149 BYTE type;
150 CARD8 pad1;
151 CARD16 sequenceNumber B16;
152 CARD32 length B32;
153 CARD32 state B32;
154 CARD32 pad2 B32;
155 CARD32 pad3 B32;
156 CARD32 pad4 B32;
157 CARD32 pad5 B32;
158 CARD32 pad6 B32;
159} xXineramaIsActiveReply;
160#define sz_XineramaIsActiveReply 32
161
162
163typedef struct {
164 CARD8 reqType;
165 CARD8 panoramiXReqType;
166 CARD16 length B16;
167} xXineramaQueryScreensReq;
168#define sz_xXineramaQueryScreensReq 4
169
170typedef struct {
171 BYTE type;
172 CARD8 pad1;
173 CARD16 sequenceNumber B16;
174 CARD32 length B32;
175 CARD32 number B32;
176 CARD32 pad2 B32;
177 CARD32 pad3 B32;
178 CARD32 pad4 B32;
179 CARD32 pad5 B32;
180 CARD32 pad6 B32;
181} xXineramaQueryScreensReply;
182#define sz_XineramaQueryScreensReply 32
183
184typedef struct {
185 INT16 x_org B16;
186 INT16 y_org B16;
187 CARD16 width B16;
188 CARD16 height B16;
189} xXineramaScreenInfo;
190#define sz_XineramaScreenInfo 8
191
192#endif
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/xf86dga.h b/apps/plugins/sdl/src/video/Xext/extensions/xf86dga.h
deleted file mode 100644
index c71ef4b14a..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/xf86dga.h
+++ /dev/null
@@ -1,265 +0,0 @@
1/*
2 Copyright (c) 1999 XFree86 Inc
3*/
4/* $XFree86: xc/include/extensions/xf86dga.h,v 3.21 2001/08/01 00:44:36 tsi Exp $ */
5
6#ifndef _XF86DGA_H_
7#define _XF86DGA_H_
8
9#include <X11/Xfuncproto.h>
10#include "xf86dga1.h"
11#include "SDL_name.h"
12
13#define X_XDGAQueryVersion 0
14
15/* 1 through 9 are in xf86dga1.h */
16
17/* 10 and 11 are reserved to avoid conflicts with rogue DGA extensions */
18
19#define X_XDGAQueryModes 12
20#define X_XDGASetMode 13
21#define X_XDGASetViewport 14
22#define X_XDGAInstallColormap 15
23#define X_XDGASelectInput 16
24#define X_XDGAFillRectangle 17
25#define X_XDGACopyArea 18
26#define X_XDGACopyTransparentArea 19
27#define X_XDGAGetViewportStatus 20
28#define X_XDGASync 21
29#define X_XDGAOpenFramebuffer 22
30#define X_XDGACloseFramebuffer 23
31#define X_XDGASetClientVersion 24
32#define X_XDGAChangePixmapMode 25
33#define X_XDGACreateColormap 26
34
35
36#define XDGAConcurrentAccess 0x00000001
37#define XDGASolidFillRect 0x00000002
38#define XDGABlitRect 0x00000004
39#define XDGABlitTransRect 0x00000008
40#define XDGAPixmap 0x00000010
41
42#define XDGAInterlaced 0x00010000
43#define XDGADoublescan 0x00020000
44
45#define XDGAFlipImmediate 0x00000001
46#define XDGAFlipRetrace 0x00000002
47
48#define XDGANeedRoot 0x00000001
49
50#define XF86DGANumberEvents 7
51
52#define XDGAPixmapModeLarge 0
53#define XDGAPixmapModeSmall 1
54
55#define XF86DGAClientNotLocal 0
56#define XF86DGANoDirectVideoMode 1
57#define XF86DGAScreenNotActive 2
58#define XF86DGADirectNotActivated 3
59#define XF86DGAOperationNotSupported 4
60#define XF86DGANumberErrors (XF86DGAOperationNotSupported + 1)
61
62
63typedef struct {
64 int num; /* A unique identifier for the mode (num > 0) */
65 char *name; /* name of mode given in the XF86Config */
66 float verticalRefresh;
67 int flags; /* DGA_CONCURRENT_ACCESS, etc... */
68 int imageWidth; /* linear accessible portion (pixels) */
69 int imageHeight;
70 int pixmapWidth; /* Xlib accessible portion (pixels) */
71 int pixmapHeight; /* both fields ignored if no concurrent access */
72 int bytesPerScanline;
73 int byteOrder; /* MSBFirst, LSBFirst */
74 int depth;
75 int bitsPerPixel;
76 unsigned long redMask;
77 unsigned long greenMask;
78 unsigned long blueMask;
79 short visualClass;
80 int viewportWidth;
81 int viewportHeight;
82 int xViewportStep; /* viewport position granularity */
83 int yViewportStep;
84 int maxViewportX; /* max viewport origin */
85 int maxViewportY;
86 int viewportFlags; /* types of page flipping possible */
87 int reserved1;
88 int reserved2;
89} SDL_NAME(XDGAMode);
90
91
92typedef struct {
93 SDL_NAME(XDGAMode) mode;
94 unsigned char *data;
95 Pixmap pixmap;
96} SDL_NAME(XDGADevice);
97
98
99#ifndef _XF86DGA_SERVER_
100_XFUNCPROTOBEGIN
101
102typedef struct {
103 int type;
104 unsigned long serial;
105 Display *display;
106 int screen;
107 Time time;
108 unsigned int state;
109 unsigned int button;
110} SDL_NAME(XDGAButtonEvent);
111
112typedef struct {
113 int type;
114 unsigned long serial;
115 Display *display;
116 int screen;
117 Time time;
118 unsigned int state;
119 unsigned int keycode;
120} SDL_NAME(XDGAKeyEvent);
121
122typedef struct {
123 int type;
124 unsigned long serial;
125 Display *display;
126 int screen;
127 Time time;
128 unsigned int state;
129 int dx;
130 int dy;
131} SDL_NAME(XDGAMotionEvent);
132
133typedef union {
134 int type;
135 SDL_NAME(XDGAButtonEvent) xbutton;
136 SDL_NAME(XDGAKeyEvent) xkey;
137 SDL_NAME(XDGAMotionEvent) xmotion;
138 long pad[24];
139} SDL_NAME(XDGAEvent);
140
141Bool SDL_NAME(XDGAQueryExtension)(
142 Display *dpy,
143 int *eventBase,
144 int *erroBase
145);
146
147Bool SDL_NAME(XDGAQueryVersion)(
148 Display *dpy,
149 int *majorVersion,
150 int *minorVersion
151);
152
153SDL_NAME(XDGAMode)* SDL_NAME(XDGAQueryModes)(
154 Display *dpy,
155 int screen,
156 int *num
157);
158
159SDL_NAME(XDGADevice)* SDL_NAME(XDGASetMode)(
160 Display *dpy,
161 int screen,
162 int mode
163);
164
165Bool SDL_NAME(XDGAOpenFramebuffer)(
166 Display *dpy,
167 int screen
168);
169
170void SDL_NAME(XDGACloseFramebuffer)(
171 Display *dpy,
172 int screen
173);
174
175void SDL_NAME(XDGASetViewport)(
176 Display *dpy,
177 int screen,
178 int x,
179 int y,
180 int flags
181);
182
183void SDL_NAME(XDGAInstallColormap)(
184 Display *dpy,
185 int screen,
186 Colormap cmap
187);
188
189Colormap SDL_NAME(XDGACreateColormap)(
190 Display *dpy,
191 int screen,
192 SDL_NAME(XDGADevice) *device,
193 int alloc
194);
195
196void SDL_NAME(XDGASelectInput)(
197 Display *dpy,
198 int screen,
199 long event_mask
200);
201
202void SDL_NAME(XDGAFillRectangle)(
203 Display *dpy,
204 int screen,
205 int x,
206 int y,
207 unsigned int width,
208 unsigned int height,
209 unsigned long color
210);
211
212
213void SDL_NAME(XDGACopyArea)(
214 Display *dpy,
215 int screen,
216 int srcx,
217 int srcy,
218 unsigned int width,
219 unsigned int height,
220 int dstx,
221 int dsty
222);
223
224
225void SDL_NAME(XDGACopyTransparentArea)(
226 Display *dpy,
227 int screen,
228 int srcx,
229 int srcy,
230 unsigned int width,
231 unsigned int height,
232 int dstx,
233 int dsty,
234 unsigned long key
235);
236
237int SDL_NAME(XDGAGetViewportStatus)(
238 Display *dpy,
239 int screen
240);
241
242void SDL_NAME(XDGASync)(
243 Display *dpy,
244 int screen
245);
246
247Bool SDL_NAME(XDGASetClientVersion)(
248 Display *dpy
249);
250
251void SDL_NAME(XDGAChangePixmapMode)(
252 Display *dpy,
253 int screen,
254 int *x,
255 int *y,
256 int mode
257);
258
259
260void SDL_NAME(XDGAKeyEventToXKeyEvent)(SDL_NAME(XDGAKeyEvent)* dk, XKeyEvent* xk);
261
262
263_XFUNCPROTOEND
264#endif /* _XF86DGA_SERVER_ */
265#endif /* _XF86DGA_H_ */
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/xf86dga1.h b/apps/plugins/sdl/src/video/Xext/extensions/xf86dga1.h
deleted file mode 100644
index 4a49e9f385..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/xf86dga1.h
+++ /dev/null
@@ -1,169 +0,0 @@
1/* $XFree86: xc/include/extensions/xf86dga1.h,v 1.2 1999/04/17 07:05:41 dawes Exp $ */
2/*
3
4Copyright (c) 1995 Jon Tombs
5Copyright (c) 1995 XFree86 Inc
6
7*/
8
9/************************************************************************
10
11 THIS IS THE OLD DGA API AND IS OBSOLETE. PLEASE DO NOT USE IT ANYMORE
12
13************************************************************************/
14
15#ifndef _XF86DGA1_H_
16#define _XF86DGA1_H_
17
18#include <X11/Xfuncproto.h>
19#include "SDL_name.h"
20
21#define X_XF86DGAQueryVersion 0
22#define X_XF86DGAGetVideoLL 1
23#define X_XF86DGADirectVideo 2
24#define X_XF86DGAGetViewPortSize 3
25#define X_XF86DGASetViewPort 4
26#define X_XF86DGAGetVidPage 5
27#define X_XF86DGASetVidPage 6
28#define X_XF86DGAInstallColormap 7
29#define X_XF86DGAQueryDirectVideo 8
30#define X_XF86DGAViewPortChanged 9
31
32#define XF86DGADirectPresent 0x0001
33#define XF86DGADirectGraphics 0x0002
34#define XF86DGADirectMouse 0x0004
35#define XF86DGADirectKeyb 0x0008
36#define XF86DGAHasColormap 0x0100
37#define XF86DGADirectColormap 0x0200
38
39
40
41
42#ifndef _XF86DGA_SERVER_
43
44_XFUNCPROTOBEGIN
45
46Bool SDL_NAME(XF86DGAQueryVersion)(
47#if NeedFunctionPrototypes
48 Display* /* dpy */,
49 int* /* majorVersion */,
50 int* /* minorVersion */
51#endif
52);
53
54Bool SDL_NAME(XF86DGAQueryExtension)(
55#if NeedFunctionPrototypes
56 Display* /* dpy */,
57 int* /* event_base */,
58 int* /* error_base */
59#endif
60);
61
62Status SDL_NAME(XF86DGAGetVideoLL)(
63#if NeedFunctionPrototypes
64 Display* /* dpy */,
65 int /* screen */,
66 int * /* base addr */,
67 int * /* width */,
68 int * /* bank_size */,
69 int * /* ram_size */
70#endif
71);
72
73Status SDL_NAME(XF86DGAGetVideo)(
74#if NeedFunctionPrototypes
75 Display* /* dpy */,
76 int /* screen */,
77 char ** /* base addr */,
78 int * /* width */,
79 int * /* bank_size */,
80 int * /* ram_size */
81#endif
82);
83
84Status SDL_NAME(XF86DGADirectVideo)(
85#if NeedFunctionPrototypes
86 Display* /* dpy */,
87 int /* screen */,
88 int /* enable */
89#endif
90);
91
92Status SDL_NAME(XF86DGADirectVideoLL)(
93#if NeedFunctionPrototypes
94 Display* /* dpy */,
95 int /* screen */,
96 int /* enable */
97#endif
98);
99
100Status SDL_NAME(XF86DGAGetViewPortSize)(
101#if NeedFunctionPrototypes
102 Display* /* dpy */,
103 int /* screen */,
104 int * /* width */,
105 int * /* height */
106#endif
107);
108
109Status SDL_NAME(XF86DGASetViewPort)(
110#if NeedFunctionPrototypes
111 Display* /* dpy */,
112 int /* screen */,
113 int x /* X */,
114 int y /* Y */
115#endif
116);
117
118Status SDL_NAME(XF86DGAGetVidPage)(
119#if NeedFunctionPrototypes
120 Display* /* dpy */,
121 int /* screen */,
122 int * /* vid page */
123#endif
124);
125
126Status SDL_NAME(XF86DGASetVidPage)(
127#if NeedFunctionPrototypes
128 Display* /* dpy */,
129 int /* screen */,
130 int /* vid page */
131#endif
132);
133
134Status SDL_NAME(XF86DGAInstallColormap)(
135#if NeedFunctionPrototypes
136 Display* /* dpy */,
137 int /* screen */,
138 Colormap /*Colormap */
139#endif
140);
141
142int SDL_NAME(XF86DGAForkApp)(
143#if NeedFunctionPrototypes
144 int screen
145#endif
146);
147
148Status SDL_NAME(XF86DGAQueryDirectVideo)(
149#if NeedFunctionPrototypes
150 Display * /* dpy */,
151 int /* screen */,
152 int * /* flags */
153#endif
154);
155
156Bool SDL_NAME(XF86DGAViewPortChanged)(
157#if NeedFunctionPrototypes
158 Display * /* dpy */,
159 int /* screen */,
160 int /* n */
161#endif
162);
163
164
165_XFUNCPROTOEND
166
167#endif /* _XF86DGA_SERVER_ */
168
169#endif /* _XF86DGA1_H_ */
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/xf86dga1str.h b/apps/plugins/sdl/src/video/Xext/extensions/xf86dga1str.h
deleted file mode 100644
index 5695fbd13b..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/xf86dga1str.h
+++ /dev/null
@@ -1,194 +0,0 @@
1/* $XFree86: xc/include/extensions/xf86dga1str.h,v 1.2 1999/05/03 12:15:37 dawes Exp $ */
2/*
3
4Copyright (c) 1995 Jon Tombs
5Copyright (c) 1995 XFree86 Inc.
6
7*/
8
9#ifndef _XF86DGASTR1_H_
10#define _XF86DGASTR1_H_
11
12typedef struct _XF86DGAQueryVersion {
13 CARD8 reqType; /* always DGAReqCode */
14 CARD8 dgaReqType; /* always X_DGAQueryVersion */
15 CARD16 length B16;
16} xXF86DGAQueryVersionReq;
17#define sz_xXF86DGAQueryVersionReq 4
18
19typedef struct {
20 BYTE type; /* X_Reply */
21 BOOL pad1;
22 CARD16 sequenceNumber B16;
23 CARD32 length B32;
24 CARD16 majorVersion B16; /* major version of DGA protocol */
25 CARD16 minorVersion B16; /* minor version of DGA protocol */
26 CARD32 pad2 B32;
27 CARD32 pad3 B32;
28 CARD32 pad4 B32;
29 CARD32 pad5 B32;
30 CARD32 pad6 B32;
31} xXF86DGAQueryVersionReply;
32#define sz_xXF86DGAQueryVersionReply 32
33
34typedef struct _XF86DGAGetVideoLL {
35 CARD8 reqType; /* always DGAReqCode */
36 CARD8 dgaReqType; /* always X_XF86DGAGetVideoLL */
37 CARD16 length B16;
38 CARD16 screen B16;
39 CARD16 pad B16;
40} xXF86DGAGetVideoLLReq;
41#define sz_xXF86DGAGetVideoLLReq 8
42
43typedef struct _XF86DGAInstallColormap{
44 CARD8 reqType;
45 CARD8 dgaReqType;
46 CARD16 length B16;
47 CARD16 screen B16;
48 CARD16 pad2;
49 CARD32 id B32; /* colormap. */
50} xXF86DGAInstallColormapReq;
51#define sz_xXF86DGAInstallColormapReq 12
52
53
54typedef struct {
55 BYTE type;
56 BOOL pad1;
57 CARD16 sequenceNumber B16;
58 CARD32 length B32;
59 CARD32 offset B32;
60 CARD32 width B32;
61 CARD32 bank_size B32;
62 CARD32 ram_size B32;
63 CARD32 pad4 B32;
64 CARD32 pad5 B32;
65} xXF86DGAGetVideoLLReply;
66#define sz_xXF86DGAGetVideoLLReply 32
67
68typedef struct _XF86DGADirectVideo {
69 CARD8 reqType; /* always DGAReqCode */
70 CARD8 dgaReqType; /* always X_XF86DGADirectVideo */
71 CARD16 length B16;
72 CARD16 screen B16;
73 CARD16 enable B16;
74} xXF86DGADirectVideoReq;
75#define sz_xXF86DGADirectVideoReq 8
76
77
78typedef struct _XF86DGAGetViewPortSize {
79 CARD8 reqType; /* always DGAReqCode */
80 CARD8 dgaReqType; /* always X_XF86DGAGetViewPort */
81 CARD16 length B16;
82 CARD16 screen B16;
83 CARD16 pad B16;
84} xXF86DGAGetViewPortSizeReq;
85#define sz_xXF86DGAGetViewPortSizeReq 8
86
87typedef struct {
88 BYTE type;
89 BOOL pad1;
90 CARD16 sequenceNumber B16;
91 CARD32 length B32;
92 CARD32 width B32;
93 CARD32 height B32;
94 CARD32 pad2 B32;
95 CARD32 pad3 B32;
96 CARD32 pad4 B32;
97 CARD32 pad5 B32;
98} xXF86DGAGetViewPortSizeReply;
99#define sz_xXF86DGAGetViewPortSizeReply 32
100
101typedef struct _XF86DGASetViewPort {
102 CARD8 reqType; /* always DGAReqCode */
103 CARD8 dgaReqType; /* always X_XF86DGASetViewPort */
104 CARD16 length B16;
105 CARD16 screen B16;
106 CARD16 pad B16;
107 CARD32 x B32;
108 CARD32 y B32;
109} xXF86DGASetViewPortReq;
110#define sz_xXF86DGASetViewPortReq 16
111
112typedef struct _XF86DGAGetVidPage {
113 CARD8 reqType; /* always DGAReqCode */
114 CARD8 dgaReqType; /* always X_XF86DGAGetVidPage */
115 CARD16 length B16;
116 CARD16 screen B16;
117 CARD16 pad B16;
118} xXF86DGAGetVidPageReq;
119#define sz_xXF86DGAGetVidPageReq 8
120
121typedef struct {
122 BYTE type;
123 BOOL pad1;
124 CARD16 sequenceNumber B16;
125 CARD32 length B32;
126 CARD32 vpage B32;
127 CARD32 pad B32;
128 CARD32 pad2 B32;
129 CARD32 pad3 B32;
130 CARD32 pad4 B32;
131 CARD32 pad5 B32;
132} xXF86DGAGetVidPageReply;
133#define sz_xXF86DGAGetVidPageReply 32
134
135
136typedef struct _XF86DGASetVidPage {
137 CARD8 reqType; /* always DGAReqCode */
138 CARD8 dgaReqType; /* always X_XF86DGASetVidPage */
139 CARD16 length B16;
140 CARD16 screen B16;
141 CARD16 vpage B16;
142} xXF86DGASetVidPageReq;
143#define sz_xXF86DGASetVidPageReq 8
144
145
146typedef struct _XF86DGAQueryDirectVideo {
147 CARD8 reqType; /* always DGAReqCode */
148 CARD8 dgaReqType; /* always X_DGAQueryVersion */
149 CARD16 length B16;
150 CARD16 screen B16;
151 CARD16 pad B16;
152} xXF86DGAQueryDirectVideoReq;
153#define sz_xXF86DGAQueryDirectVideoReq 8
154
155typedef struct {
156 BYTE type;
157 BOOL pad1;
158 CARD16 sequenceNumber B16;
159 CARD32 length B32;
160 CARD32 flags B32;
161 CARD32 pad B32;
162 CARD32 pad2 B32;
163 CARD32 pad3 B32;
164 CARD32 pad4 B32;
165 CARD32 pad5 B32;
166} xXF86DGAQueryDirectVideoReply;
167#define sz_xXF86DGAQueryDirectVideoReply 32
168
169
170typedef struct _XF86DGAViewPortChanged {
171 CARD8 reqType; /* always DGAReqCode */
172 CARD8 dgaReqType; /* always X_DGAQueryVersion */
173 CARD16 length B16;
174 CARD16 screen B16;
175 CARD16 n B16;
176} xXF86DGAViewPortChangedReq;
177#define sz_xXF86DGAViewPortChangedReq 8
178
179typedef struct {
180 BYTE type;
181 BOOL pad1;
182 CARD16 sequenceNumber B16;
183 CARD32 length B32;
184 CARD32 result B32;
185 CARD32 pad B32;
186 CARD32 pad2 B32;
187 CARD32 pad3 B32;
188 CARD32 pad4 B32;
189 CARD32 pad5 B32;
190} xXF86DGAViewPortChangedReply;
191#define sz_xXF86DGAViewPortChangedReply 32
192
193#endif /* _XF86DGASTR1_H_ */
194
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/xf86dgastr.h b/apps/plugins/sdl/src/video/Xext/extensions/xf86dgastr.h
deleted file mode 100644
index b249feb3c6..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/xf86dgastr.h
+++ /dev/null
@@ -1,344 +0,0 @@
1/* $XFree86: xc/include/extensions/xf86dgastr.h,v 3.14 2001/08/01 00:44:36 tsi Exp $ */
2/*
3
4Copyright (c) 1995 Jon Tombs
5Copyright (c) 1995 XFree86 Inc.
6
7*/
8
9#ifndef _XF86DGASTR_H_
10#define _XF86DGASTR_H_
11
12#include "xf86dga1str.h"
13
14#define XF86DGANAME "XFree86-DGA"
15
16#define XDGA_MAJOR_VERSION 2 /* current version numbers */
17#define XDGA_MINOR_VERSION 0
18
19
20typedef struct _XDGAQueryVersion {
21 CARD8 reqType; /* always DGAReqCode */
22 CARD8 dgaReqType; /* always X_DGAQueryVersion */
23 CARD16 length B16;
24} xXDGAQueryVersionReq;
25#define sz_xXDGAQueryVersionReq 4
26
27typedef struct {
28 BYTE type; /* X_Reply */
29 BOOL pad1;
30 CARD16 sequenceNumber B16;
31 CARD32 length B32;
32 CARD16 majorVersion B16; /* major version of DGA protocol */
33 CARD16 minorVersion B16; /* minor version of DGA protocol */
34 CARD32 pad2 B32;
35 CARD32 pad3 B32;
36 CARD32 pad4 B32;
37 CARD32 pad5 B32;
38 CARD32 pad6 B32;
39} xXDGAQueryVersionReply;
40#define sz_xXDGAQueryVersionReply 32
41
42typedef struct _XDGAQueryModes {
43 CARD8 reqType;
44 CARD8 dgaReqType;
45 CARD16 length B16;
46 CARD32 screen B32;
47} xXDGAQueryModesReq;
48#define sz_xXDGAQueryModesReq 8
49
50typedef struct {
51 BYTE type; /* X_Reply */
52 BOOL pad1;
53 CARD16 sequenceNumber B16;
54 CARD32 length B32;
55 CARD32 number B32; /* number of modes available */
56 CARD32 pad2 B32;
57 CARD32 pad3 B32;
58 CARD32 pad4 B32;
59 CARD32 pad5 B32;
60 CARD32 pad6 B32;
61} xXDGAQueryModesReply;
62#define sz_xXDGAQueryModesReply 32
63
64
65typedef struct _XDGASetMode {
66 CARD8 reqType;
67 CARD8 dgaReqType;
68 CARD16 length B16;
69 CARD32 screen B32;
70 CARD32 mode B32; /* mode number to init */
71 CARD32 pid B32; /* Pixmap descriptor */
72} xXDGASetModeReq;
73#define sz_xXDGASetModeReq 16
74
75typedef struct {
76 BYTE type; /* X_Reply */
77 BOOL pad1;
78 CARD16 sequenceNumber B16;
79 CARD32 length B32;
80 CARD32 offset B32; /* offset into framebuffer map */
81 CARD32 flags B32;
82 CARD32 pad2 B32;
83 CARD32 pad3 B32;
84 CARD32 pad4 B32;
85 CARD32 pad5 B32;
86} xXDGASetModeReply;
87#define sz_xXDGASetModeReply 32
88
89typedef struct {
90 CARD8 byte_order;
91 CARD8 depth;
92 CARD16 num B16;
93 CARD16 bpp B16;
94 CARD16 name_size B16;
95 CARD32 vsync_num B32;
96 CARD32 vsync_den B32;
97 CARD32 flags B32;
98 CARD16 image_width B16;
99 CARD16 image_height B16;
100 CARD16 pixmap_width B16;
101 CARD16 pixmap_height B16;
102 CARD32 bytes_per_scanline B32;
103 CARD32 red_mask B32;
104 CARD32 green_mask B32;
105 CARD32 blue_mask B32;
106 CARD16 visual_class B16;
107 CARD16 pad1 B16;
108 CARD16 viewport_width B16;
109 CARD16 viewport_height B16;
110 CARD16 viewport_xstep B16;
111 CARD16 viewport_ystep B16;
112 CARD16 viewport_xmax B16;
113 CARD16 viewport_ymax B16;
114 CARD32 viewport_flags B32;
115 CARD32 reserved1 B32;
116 CARD32 reserved2 B32;
117} xXDGAModeInfo;
118#define sz_xXDGAModeInfo 72
119
120typedef struct _XDGAOpenFramebuffer {
121 CARD8 reqType;
122 CARD8 dgaReqType;
123 CARD16 length B16;
124 CARD32 screen B32;
125} xXDGAOpenFramebufferReq;
126#define sz_xXDGAOpenFramebufferReq 8
127
128typedef struct {
129 BYTE type; /* X_Reply */
130 BOOL pad1;
131 CARD16 sequenceNumber B16;
132 CARD32 length B32; /* device name size if there is one */
133 CARD32 mem1 B32; /* physical memory */
134 CARD32 mem2 B32; /* spillover for _alpha_ */
135 CARD32 size B32; /* size of map in bytes */
136 CARD32 offset B32; /* optional offset into device */
137 CARD32 extra B32; /* extra info associated with the map */
138 CARD32 pad2 B32;
139} xXDGAOpenFramebufferReply;
140#define sz_xXDGAOpenFramebufferReply 32
141
142
143typedef struct _XDGACloseFramebuffer {
144 CARD8 reqType;
145 CARD8 dgaReqType;
146 CARD16 length B16;
147 CARD32 screen B32;
148} xXDGACloseFramebufferReq;
149#define sz_xXDGACloseFramebufferReq 8
150
151
152typedef struct _XDGASetViewport {
153 CARD8 reqType;
154 CARD8 dgaReqType;
155 CARD16 length B16;
156 CARD32 screen B32;
157 CARD16 x B16;
158 CARD16 y B16;
159 CARD32 flags B32;
160} xXDGASetViewportReq;
161#define sz_xXDGASetViewportReq 16
162
163
164typedef struct _XDGAInstallColormap {
165 CARD8 reqType;
166 CARD8 dgaReqType;
167 CARD16 length B16;
168 CARD32 screen B32;
169 CARD32 cmap B32;
170} xXDGAInstallColormapReq;
171#define sz_xXDGAInstallColormapReq 12
172
173typedef struct _XDGASelectInput {
174 CARD8 reqType;
175 CARD8 dgaReqType;
176 CARD16 length B16;
177 CARD32 screen B32;
178 CARD32 mask B32;
179} xXDGASelectInputReq;
180#define sz_xXDGASelectInputReq 12
181
182typedef struct _XDGAFillRectangle {
183 CARD8 reqType;
184 CARD8 dgaReqType;
185 CARD16 length B16;
186 CARD32 screen B32;
187 CARD16 x B16;
188 CARD16 y B16;
189 CARD16 width B16;
190 CARD16 height B16;
191 CARD32 color B32;
192} xXDGAFillRectangleReq;
193#define sz_xXDGAFillRectangleReq 20
194
195
196typedef struct _XDGACopyArea {
197 CARD8 reqType;
198 CARD8 dgaReqType;
199 CARD16 length B16;
200 CARD32 screen B32;
201 CARD16 srcx B16;
202 CARD16 srcy B16;
203 CARD16 width B16;
204 CARD16 height B16;
205 CARD16 dstx B16;
206 CARD16 dsty B16;
207} xXDGACopyAreaReq;
208#define sz_xXDGACopyAreaReq 20
209
210typedef struct _XDGACopyTransparentArea {
211 CARD8 reqType;
212 CARD8 dgaReqType;
213 CARD16 length B16;
214 CARD32 screen B32;
215 CARD16 srcx B16;
216 CARD16 srcy B16;
217 CARD16 width B16;
218 CARD16 height B16;
219 CARD16 dstx B16;
220 CARD16 dsty B16;
221 CARD32 key B32;
222} xXDGACopyTransparentAreaReq;
223#define sz_xXDGACopyTransparentAreaReq 24
224
225
226typedef struct _XDGAGetViewportStatus {
227 CARD8 reqType;
228 CARD8 dgaReqType;
229 CARD16 length B16;
230 CARD32 screen B32;
231} xXDGAGetViewportStatusReq;
232#define sz_xXDGAGetViewportStatusReq 8
233
234typedef struct {
235 BYTE type;
236 BOOL pad1;
237 CARD16 sequenceNumber B16;
238 CARD32 length B32;
239 CARD32 status B32;
240 CARD32 pad2 B32;
241 CARD32 pad3 B32;
242 CARD32 pad4 B32;
243 CARD32 pad5 B32;
244 CARD32 pad6 B32;
245} xXDGAGetViewportStatusReply;
246#define sz_xXDGAGetViewportStatusReply 32
247
248typedef struct _XDGASync {
249 CARD8 reqType;
250 CARD8 dgaReqType;
251 CARD16 length B16;
252 CARD32 screen B32;
253} xXDGASyncReq;
254#define sz_xXDGASyncReq 8
255
256typedef struct {
257 BYTE type;
258 BOOL pad1;
259 CARD16 sequenceNumber B16;
260 CARD32 length B32;
261 CARD32 pad2 B32;
262 CARD32 pad3 B32;
263 CARD32 pad4 B32;
264 CARD32 pad5 B32;
265 CARD32 pad6 B32;
266 CARD32 pad7 B32;
267} xXDGASyncReply;
268#define sz_xXDGASyncReply 32
269
270typedef struct _XDGASetClientVersion {
271 CARD8 reqType;
272 CARD8 dgaReqType;
273 CARD16 length B16;
274 CARD16 major B16;
275 CARD16 minor B16;
276} xXDGASetClientVersionReq;
277#define sz_xXDGASetClientVersionReq 8
278
279
280typedef struct {
281 CARD8 reqType;
282 CARD8 dgaReqType;
283 CARD16 length B16;
284 CARD32 screen B32;
285 CARD16 x B16;
286 CARD16 y B16;
287 CARD32 flags B32;
288} xXDGAChangePixmapModeReq;
289#define sz_xXDGAChangePixmapModeReq 16
290
291typedef struct {
292 BYTE type;
293 BOOL pad1;
294 CARD16 sequenceNumber B16;
295 CARD32 length B32;
296 CARD16 x B16;
297 CARD16 y B16;
298 CARD32 pad3 B32;
299 CARD32 pad4 B32;
300 CARD32 pad5 B32;
301 CARD32 pad6 B32;
302 CARD32 pad7 B32;
303} xXDGAChangePixmapModeReply;
304#define sz_xXDGAChangePixmapModeReply 32
305
306typedef struct _XDGACreateColormap {
307 CARD8 reqType;
308 CARD8 dgaReqType;
309 CARD16 length B16;
310 CARD32 screen B32;
311 CARD32 id B32;
312 CARD32 mode B32;
313 CARD8 alloc;
314 CARD8 pad1;
315 CARD16 pad2;
316} xXDGACreateColormapReq;
317#define sz_xXDGACreateColormapReq 20
318
319
320typedef struct {
321 union {
322 struct {
323 BYTE type;
324 BYTE detail;
325 CARD16 sequenceNumber B16;
326 } u;
327 struct {
328 CARD32 pad0 B32;
329 CARD32 time B32;
330 INT16 dx B16;
331 INT16 dy B16;
332 INT16 screen B16;
333 CARD16 state B16;
334 CARD32 pad1 B32;
335 CARD32 pad2 B32;
336 CARD32 pad3 B32;
337 CARD32 pad4 B32;
338 } event;
339 } u;
340} dgaEvent;
341
342
343#endif /* _XF86DGASTR_H_ */
344
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/xf86vmode.h b/apps/plugins/sdl/src/video/Xext/extensions/xf86vmode.h
deleted file mode 100644
index eb56c0e8da..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/xf86vmode.h
+++ /dev/null
@@ -1,314 +0,0 @@
1/* $XFree86: xc/include/extensions/xf86vmode.h,v 3.30 2001/05/07 20:09:50 mvojkovi Exp $ */
2/*
3
4Copyright 1995 Kaleb S. KEITHLEY
5
6Permission is hereby granted, free of charge, to any person obtaining
7a copy of this software and associated documentation files (the
8"Software"), to deal in the Software without restriction, including
9without limitation the rights to use, copy, modify, merge, publish,
10distribute, sublicense, and/or sell copies of the Software, and to
11permit persons to whom the Software is furnished to do so, subject to
12the following conditions:
13
14The above copyright notice and this permission notice shall be
15included in all copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20IN NO EVENT SHALL Kaleb S. KEITHLEY BE LIABLE FOR ANY CLAIM, DAMAGES
21OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23OTHER DEALINGS IN THE SOFTWARE.
24
25Except as contained in this notice, the name of Kaleb S. KEITHLEY
26shall not be used in advertising or otherwise to promote the sale, use
27or other dealings in this Software without prior written authorization
28from Kaleb S. KEITHLEY
29
30*/
31/* $Xorg: xf86vmode.h,v 1.3 2000/08/18 04:05:46 coskrey Exp $ */
32
33/* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */
34
35#ifndef _XF86VIDMODE_H_
36#define _XF86VIDMODE_H_
37
38#include <X11/Xfuncproto.h>
39#include <X11/Xmd.h>
40#include "SDL_name.h"
41
42#define X_XF86VidModeQueryVersion 0
43#define X_XF86VidModeGetModeLine 1
44#define X_XF86VidModeModModeLine 2
45#define X_XF86VidModeSwitchMode 3
46#define X_XF86VidModeGetMonitor 4
47#define X_XF86VidModeLockModeSwitch 5
48#define X_XF86VidModeGetAllModeLines 6
49#define X_XF86VidModeAddModeLine 7
50#define X_XF86VidModeDeleteModeLine 8
51#define X_XF86VidModeValidateModeLine 9
52#define X_XF86VidModeSwitchToMode 10
53#define X_XF86VidModeGetViewPort 11
54#define X_XF86VidModeSetViewPort 12
55/* new for version 2.x of this extension */
56#define X_XF86VidModeGetDotClocks 13
57#define X_XF86VidModeSetClientVersion 14
58#define X_XF86VidModeSetGamma 15
59#define X_XF86VidModeGetGamma 16
60#define X_XF86VidModeGetGammaRamp 17
61#define X_XF86VidModeSetGammaRamp 18
62#define X_XF86VidModeGetGammaRampSize 19
63
64#define CLKFLAG_PROGRAMABLE 1
65
66#ifdef XF86VIDMODE_EVENTS
67#define XF86VidModeNotify 0
68#define XF86VidModeNumberEvents (XF86VidModeNotify + 1)
69
70#define XF86VidModeNotifyMask 0x00000001
71
72#define XF86VidModeNonEvent 0
73#define XF86VidModeModeChange 1
74#else
75#define XF86VidModeNumberEvents 0
76#endif
77
78#define XF86VidModeBadClock 0
79#define XF86VidModeBadHTimings 1
80#define XF86VidModeBadVTimings 2
81#define XF86VidModeModeUnsuitable 3
82#define XF86VidModeExtensionDisabled 4
83#define XF86VidModeClientNotLocal 5
84#define XF86VidModeZoomLocked 6
85#define XF86VidModeNumberErrors (XF86VidModeZoomLocked + 1)
86
87#ifndef _XF86VIDMODE_SERVER_
88
89typedef struct {
90 unsigned short hdisplay;
91 unsigned short hsyncstart;
92 unsigned short hsyncend;
93 unsigned short htotal;
94 unsigned short hskew;
95 unsigned short vdisplay;
96 unsigned short vsyncstart;
97 unsigned short vsyncend;
98 unsigned short vtotal;
99 unsigned int flags;
100 int privsize;
101#if defined(__cplusplus) || defined(c_plusplus)
102 /* private is a C++ reserved word */
103 INT32 *c_private;
104#else
105 INT32 *private;
106#endif
107} SDL_NAME(XF86VidModeModeLine);
108
109typedef struct {
110 unsigned int dotclock;
111 unsigned short hdisplay;
112 unsigned short hsyncstart;
113 unsigned short hsyncend;
114 unsigned short htotal;
115 unsigned short hskew;
116 unsigned short vdisplay;
117 unsigned short vsyncstart;
118 unsigned short vsyncend;
119 unsigned short vtotal;
120 unsigned int flags;
121 int privsize;
122#if defined(__cplusplus) || defined(c_plusplus)
123 /* private is a C++ reserved word */
124 INT32 *c_private;
125#else
126 INT32 *private;
127#endif
128} SDL_NAME(XF86VidModeModeInfo);
129
130typedef struct {
131 float hi;
132 float lo;
133} SDL_NAME(XF86VidModeSyncRange);
134
135typedef struct {
136 char* vendor;
137 char* model;
138 float EMPTY;
139 unsigned char nhsync;
140 SDL_NAME(XF86VidModeSyncRange)* hsync;
141 unsigned char nvsync;
142 SDL_NAME(XF86VidModeSyncRange)* vsync;
143} SDL_NAME(XF86VidModeMonitor);
144
145typedef struct {
146 int type; /* of event */
147 unsigned long serial; /* # of last request processed by server */
148 Bool send_event; /* true if this came from a SendEvent req */
149 Display *display; /* Display the event was read from */
150 Window root; /* root window of event screen */
151 int state; /* What happened */
152 int kind; /* What happened */
153 Bool forced; /* extents of new region */
154 Time time; /* event timestamp */
155} SDL_NAME(XF86VidModeNotifyEvent);
156
157typedef struct {
158 float red; /* Red Gamma value */
159 float green; /* Green Gamma value */
160 float blue; /* Blue Gamma value */
161} SDL_NAME(XF86VidModeGamma);
162
163
164#define SDL_XF86VidModeSelectNextMode(disp, scr) \
165 SDL_NAME(XF86VidModeSwitchMode)(disp, scr, 1)
166#define SDL_XF86VidModeSelectPrevMode(disp, scr) \
167 SDL_NAME(XF86VidModeSwitchMode)(disp, scr, -1)
168
169_XFUNCPROTOBEGIN
170
171Bool SDL_NAME(XF86VidModeQueryVersion)(
172 Display* /* dpy */,
173 int* /* majorVersion */,
174 int* /* minorVersion */
175);
176
177Bool SDL_NAME(XF86VidModeQueryExtension)(
178 Display* /* dpy */,
179 int* /* event_base */,
180 int* /* error_base */
181);
182
183Bool SDL_NAME(XF86VidModeSetClientVersion)(
184 Display* /* dpy */
185);
186
187Bool SDL_NAME(XF86VidModeGetModeLine)(
188 Display* /* dpy */,
189 int /* screen */,
190 int* /* dotclock */,
191 SDL_NAME(XF86VidModeModeLine)* /* modeline */
192);
193
194Bool SDL_NAME(XF86VidModeGetAllModeLines)(
195 Display* /* dpy */,
196 int /* screen */,
197 int* /* modecount */,
198 SDL_NAME(XF86VidModeModeInfo)*** /* modelinesPtr */
199);
200
201Bool SDL_NAME(XF86VidModeAddModeLine)(
202 Display* /* dpy */,
203 int /* screen */,
204 SDL_NAME(XF86VidModeModeInfo)* /* new modeline */,
205 SDL_NAME(XF86VidModeModeInfo)* /* after modeline */
206);
207
208Bool SDL_NAME(XF86VidModeDeleteModeLine)(
209 Display* /* dpy */,
210 int /* screen */,
211 SDL_NAME(XF86VidModeModeInfo)* /* modeline */
212);
213
214Bool SDL_NAME(XF86VidModeModModeLine)(
215 Display* /* dpy */,
216 int /* screen */,
217 SDL_NAME(XF86VidModeModeLine)* /* modeline */
218);
219
220Status SDL_NAME(XF86VidModeValidateModeLine)(
221 Display* /* dpy */,
222 int /* screen */,
223 SDL_NAME(XF86VidModeModeInfo)* /* modeline */
224);
225
226Bool SDL_NAME(XF86VidModeSwitchMode)(
227 Display* /* dpy */,
228 int /* screen */,
229 int /* zoom */
230);
231
232Bool SDL_NAME(XF86VidModeSwitchToMode)(
233 Display* /* dpy */,
234 int /* screen */,
235 SDL_NAME(XF86VidModeModeInfo)* /* modeline */
236);
237
238Bool SDL_NAME(XF86VidModeLockModeSwitch)(
239 Display* /* dpy */,
240 int /* screen */,
241 int /* lock */
242);
243
244Bool SDL_NAME(XF86VidModeGetMonitor)(
245 Display* /* dpy */,
246 int /* screen */,
247 SDL_NAME(XF86VidModeMonitor)* /* monitor */
248);
249
250Bool SDL_NAME(XF86VidModeGetViewPort)(
251 Display* /* dpy */,
252 int /* screen */,
253 int* /* x return */,
254 int* /* y return */
255);
256
257Bool SDL_NAME(XF86VidModeSetViewPort)(
258 Display* /* dpy */,
259 int /* screen */,
260 int /* x */,
261 int /* y */
262);
263
264Bool SDL_NAME(XF86VidModeGetDotClocks)(
265 Display* /* dpy */,
266 int /* screen */,
267 int* /* flags return */,
268 int* /* number of clocks return */,
269 int* /* max dot clock return */,
270 int** /* clocks return */
271);
272
273Bool SDL_NAME(XF86VidModeGetGamma)(
274 Display* /* dpy */,
275 int /* screen */,
276 SDL_NAME(XF86VidModeGamma)* /* Gamma */
277);
278
279Bool SDL_NAME(XF86VidModeSetGamma)(
280 Display* /* dpy */,
281 int /* screen */,
282 SDL_NAME(XF86VidModeGamma)* /* Gamma */
283);
284
285Bool SDL_NAME(XF86VidModeSetGammaRamp)(
286 Display* /* dpy */,
287 int /* screen */,
288 int /* size */,
289 unsigned short* /* red array */,
290 unsigned short* /* green array */,
291 unsigned short* /* blue array */
292);
293
294Bool SDL_NAME(XF86VidModeGetGammaRamp)(
295 Display* /* dpy */,
296 int /* screen */,
297 int /* size */,
298 unsigned short* /* red array */,
299 unsigned short* /* green array */,
300 unsigned short* /* blue array */
301);
302
303Bool SDL_NAME(XF86VidModeGetGammaRampSize)(
304 Display* /* dpy */,
305 int /* screen */,
306 int* /* size */
307);
308
309
310_XFUNCPROTOEND
311
312#endif
313
314#endif
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/xf86vmstr.h b/apps/plugins/sdl/src/video/Xext/extensions/xf86vmstr.h
deleted file mode 100644
index 0c3078d5aa..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/xf86vmstr.h
+++ /dev/null
@@ -1,546 +0,0 @@
1/* $XFree86: xc/include/extensions/xf86vmstr.h,v 3.27 2001/08/01 00:44:36 tsi Exp $ */
2/*
3
4Copyright 1995 Kaleb S. KEITHLEY
5
6Permission is hereby granted, free of charge, to any person obtaining
7a copy of this software and associated documentation files (the
8"Software"), to deal in the Software without restriction, including
9without limitation the rights to use, copy, modify, merge, publish,
10distribute, sublicense, and/or sell copies of the Software, and to
11permit persons to whom the Software is furnished to do so, subject to
12the following conditions:
13
14The above copyright notice and this permission notice shall be
15included in all copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20IN NO EVENT SHALL Kaleb S. KEITHLEY BE LIABLE FOR ANY CLAIM, DAMAGES
21OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23OTHER DEALINGS IN THE SOFTWARE.
24
25Except as contained in this notice, the name of Kaleb S. KEITHLEY
26shall not be used in advertising or otherwise to promote the sale, use
27or other dealings in this Software without prior written authorization
28from Kaleb S. KEITHLEY
29
30*/
31/* $Xorg: xf86vmstr.h,v 1.3 2000/08/18 04:05:46 coskrey Exp $ */
32
33/* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */
34
35#ifndef _XF86VIDMODESTR_H_
36#define _XF86VIDMODESTR_H_
37
38#include "xf86vmode.h"
39
40#define XF86VIDMODENAME "XFree86-VidModeExtension"
41
42#define XF86VIDMODE_MAJOR_VERSION 2 /* current version numbers */
43#define XF86VIDMODE_MINOR_VERSION 1
44/*
45 * major version 0 == uses parameter-to-wire functions in XFree86 libXxf86vm.
46 * major version 1 == uses parameter-to-wire functions hard-coded in xvidtune
47 * client.
48 * major version 2 == uses new protocol version in XFree86 4.0.
49 */
50
51typedef struct _XF86VidModeQueryVersion {
52 CARD8 reqType; /* always XF86VidModeReqCode */
53 CARD8 xf86vidmodeReqType; /* always X_XF86VidModeQueryVersion */
54 CARD16 length B16;
55} xXF86VidModeQueryVersionReq;
56#define sz_xXF86VidModeQueryVersionReq 4
57
58typedef struct {
59 BYTE type; /* X_Reply */
60 BOOL pad1;
61 CARD16 sequenceNumber B16;
62 CARD32 length B32;
63 CARD16 majorVersion B16; /* major version of XF86VidMode */
64 CARD16 minorVersion B16; /* minor version of XF86VidMode */
65 CARD32 pad2 B32;
66 CARD32 pad3 B32;
67 CARD32 pad4 B32;
68 CARD32 pad5 B32;
69 CARD32 pad6 B32;
70} xXF86VidModeQueryVersionReply;
71#define sz_xXF86VidModeQueryVersionReply 32
72
73typedef struct _XF86VidModeGetModeLine {
74 CARD8 reqType; /* always XF86VidModeReqCode */
75 CARD8 xf86vidmodeReqType;
76 CARD16 length B16;
77 CARD16 screen B16;
78 CARD16 pad B16;
79} xXF86VidModeGetModeLineReq,
80 xXF86VidModeGetAllModeLinesReq,
81 xXF86VidModeGetMonitorReq,
82 xXF86VidModeGetViewPortReq,
83 xXF86VidModeGetDotClocksReq;
84#define sz_xXF86VidModeGetModeLineReq 8
85#define sz_xXF86VidModeGetAllModeLinesReq 8
86#define sz_xXF86VidModeGetMonitorReq 8
87#define sz_xXF86VidModeGetViewPortReq 8
88#define sz_xXF86VidModeGetDotClocksReq 8
89
90typedef struct {
91 BYTE type; /* X_Reply */
92 BOOL pad1;
93 CARD16 sequenceNumber B16;
94 CARD32 length B32;
95 CARD32 dotclock B32;
96 CARD16 hdisplay B16;
97 CARD16 hsyncstart B16;
98 CARD16 hsyncend B16;
99 CARD16 htotal B16;
100 CARD16 hskew B16;
101 CARD16 vdisplay B16;
102 CARD16 vsyncstart B16;
103 CARD16 vsyncend B16;
104 CARD16 vtotal B16;
105 CARD16 pad2 B16;
106 CARD32 flags B32;
107 CARD32 reserved1 B32;
108 CARD32 reserved2 B32;
109 CARD32 reserved3 B32;
110 CARD32 privsize B32;
111} xXF86VidModeGetModeLineReply;
112#define sz_xXF86VidModeGetModeLineReply 52
113
114/* 0.x version */
115typedef struct {
116 BYTE type; /* X_Reply */
117 BOOL pad1;
118 CARD16 sequenceNumber B16;
119 CARD32 length B32;
120 CARD32 dotclock B32;
121 CARD16 hdisplay B16;
122 CARD16 hsyncstart B16;
123 CARD16 hsyncend B16;
124 CARD16 htotal B16;
125 CARD16 vdisplay B16;
126 CARD16 vsyncstart B16;
127 CARD16 vsyncend B16;
128 CARD16 vtotal B16;
129 CARD32 flags B32;
130 CARD32 privsize B32;
131} xXF86OldVidModeGetModeLineReply;
132#define sz_xXF86OldVidModeGetModeLineReply 36
133
134typedef struct {
135 CARD32 dotclock B32;
136 CARD16 hdisplay B16;
137 CARD16 hsyncstart B16;
138 CARD16 hsyncend B16;
139 CARD16 htotal B16;
140 CARD32 hskew B16;
141 CARD16 vdisplay B16;
142 CARD16 vsyncstart B16;
143 CARD16 vsyncend B16;
144 CARD16 vtotal B16;
145 CARD16 pad1 B16;
146 CARD32 flags B32;
147 CARD32 reserved1 B32;
148 CARD32 reserved2 B32;
149 CARD32 reserved3 B32;
150 CARD32 privsize B32;
151} xXF86VidModeModeInfo;
152
153/* 0.x version */
154typedef struct {
155 CARD32 dotclock B32;
156 CARD16 hdisplay B16;
157 CARD16 hsyncstart B16;
158 CARD16 hsyncend B16;
159 CARD16 htotal B16;
160 CARD16 vdisplay B16;
161 CARD16 vsyncstart B16;
162 CARD16 vsyncend B16;
163 CARD16 vtotal B16;
164 CARD32 flags B32;
165 CARD32 privsize B32;
166} xXF86OldVidModeModeInfo;
167
168typedef struct {
169 BYTE type; /* X_Reply */
170 BOOL pad1;
171 CARD16 sequenceNumber B16;
172 CARD32 length B32;
173 CARD32 modecount B32;
174 CARD32 pad2 B32;
175 CARD32 pad3 B32;
176 CARD32 pad4 B32;
177 CARD32 pad5 B32;
178 CARD32 pad6 B32;
179} xXF86VidModeGetAllModeLinesReply;
180#define sz_xXF86VidModeGetAllModeLinesReply 32
181
182typedef struct _XF86VidModeAddModeLine {
183 CARD8 reqType; /* always XF86VidModeReqCode */
184 CARD8 xf86vidmodeReqType; /* always X_XF86VidModeAddMode */
185 CARD16 length B16;
186 CARD32 screen B32; /* could be CARD16 but need the pad */
187 CARD32 dotclock B32;
188 CARD16 hdisplay B16;
189 CARD16 hsyncstart B16;
190 CARD16 hsyncend B16;
191 CARD16 htotal B16;
192 CARD16 hskew B16;
193 CARD16 vdisplay B16;
194 CARD16 vsyncstart B16;
195 CARD16 vsyncend B16;
196 CARD16 vtotal B16;
197 CARD16 pad1 B16;
198 CARD32 flags B32;
199 CARD32 reserved1 B32;
200 CARD32 reserved2 B32;
201 CARD32 reserved3 B32;
202 CARD32 privsize B32;
203 CARD32 after_dotclock B32;
204 CARD16 after_hdisplay B16;
205 CARD16 after_hsyncstart B16;
206 CARD16 after_hsyncend B16;
207 CARD16 after_htotal B16;
208 CARD16 after_hskew B16;
209 CARD16 after_vdisplay B16;
210 CARD16 after_vsyncstart B16;
211 CARD16 after_vsyncend B16;
212 CARD16 after_vtotal B16;
213 CARD16 pad2 B16;
214 CARD32 after_flags B32;
215 CARD32 reserved4 B32;
216 CARD32 reserved5 B32;
217 CARD32 reserved6 B32;
218} xXF86VidModeAddModeLineReq;
219#define sz_xXF86VidModeAddModeLineReq 92
220
221/* 0.x version */
222typedef struct _XF86OldVidModeAddModeLine {
223 CARD8 reqType; /* always XF86VidModeReqCode */
224 CARD8 xf86vidmodeReqType; /* always X_XF86VidModeAddMode */
225 CARD16 length B16;
226 CARD32 screen B32; /* could be CARD16 but need the pad */
227 CARD32 dotclock B32;
228 CARD16 hdisplay B16;
229 CARD16 hsyncstart B16;
230 CARD16 hsyncend B16;
231 CARD16 htotal B16;
232 CARD16 vdisplay B16;
233 CARD16 vsyncstart B16;
234 CARD16 vsyncend B16;
235 CARD16 vtotal B16;
236 CARD32 flags B32;
237 CARD32 privsize B32;
238 CARD32 after_dotclock B32;
239 CARD16 after_hdisplay B16;
240 CARD16 after_hsyncstart B16;
241 CARD16 after_hsyncend B16;
242 CARD16 after_htotal B16;
243 CARD16 after_vdisplay B16;
244 CARD16 after_vsyncstart B16;
245 CARD16 after_vsyncend B16;
246 CARD16 after_vtotal B16;
247 CARD32 after_flags B32;
248} xXF86OldVidModeAddModeLineReq;
249#define sz_xXF86OldVidModeAddModeLineReq 60
250
251typedef struct _XF86VidModeModModeLine {
252 CARD8 reqType; /* always XF86VidModeReqCode */
253 CARD8 xf86vidmodeReqType; /* always X_XF86VidModeModModeLine */
254 CARD16 length B16;
255 CARD32 screen B32; /* could be CARD16 but need the pad */
256 CARD16 hdisplay B16;
257 CARD16 hsyncstart B16;
258 CARD16 hsyncend B16;
259 CARD16 htotal B16;
260 CARD16 hskew B16;
261 CARD16 vdisplay B16;
262 CARD16 vsyncstart B16;
263 CARD16 vsyncend B16;
264 CARD16 vtotal B16;
265 CARD16 pad1 B16;
266 CARD32 flags B32;
267 CARD32 reserved1 B32;
268 CARD32 reserved2 B32;
269 CARD32 reserved3 B32;
270 CARD32 privsize B32;
271} xXF86VidModeModModeLineReq;
272#define sz_xXF86VidModeModModeLineReq 48
273
274/* 0.x version */
275typedef struct _XF86OldVidModeModModeLine {
276 CARD8 reqType; /* always XF86OldVidModeReqCode */
277 CARD8 xf86vidmodeReqType; /* always X_XF86OldVidModeModModeLine */
278 CARD16 length B16;
279 CARD32 screen B32; /* could be CARD16 but need the pad */
280 CARD16 hdisplay B16;
281 CARD16 hsyncstart B16;
282 CARD16 hsyncend B16;
283 CARD16 htotal B16;
284 CARD16 vdisplay B16;
285 CARD16 vsyncstart B16;
286 CARD16 vsyncend B16;
287 CARD16 vtotal B16;
288 CARD32 flags B32;
289 CARD32 privsize B32;
290} xXF86OldVidModeModModeLineReq;
291#define sz_xXF86OldVidModeModModeLineReq 32
292
293typedef struct _XF86VidModeValidateModeLine {
294 CARD8 reqType; /* always XF86VidModeReqCode */
295 CARD8 xf86vidmodeReqType;
296 CARD16 length B16;
297 CARD32 screen B32; /* could be CARD16 but need the pad */
298 CARD32 dotclock B32;
299 CARD16 hdisplay B16;
300 CARD16 hsyncstart B16;
301 CARD16 hsyncend B16;
302 CARD16 htotal B16;
303 CARD16 hskew B16;
304 CARD16 vdisplay B16;
305 CARD16 vsyncstart B16;
306 CARD16 vsyncend B16;
307 CARD16 vtotal B16;
308 CARD16 pad1 B16;
309 CARD32 flags B32;
310 CARD32 reserved1 B32;
311 CARD32 reserved2 B32;
312 CARD32 reserved3 B32;
313 CARD32 privsize B32;
314} xXF86VidModeDeleteModeLineReq,
315 xXF86VidModeValidateModeLineReq,
316 xXF86VidModeSwitchToModeReq;
317#define sz_xXF86VidModeDeleteModeLineReq 52
318#define sz_xXF86VidModeValidateModeLineReq 52
319#define sz_xXF86VidModeSwitchToModeReq 52
320
321/* 0.x version */
322typedef struct _XF86OldVidModeValidateModeLine {
323 CARD8 reqType; /* always XF86OldVidModeReqCode */
324 CARD8 xf86vidmodeReqType;
325 CARD16 length B16;
326 CARD32 screen B32; /* could be CARD16 but need the pad */
327 CARD32 dotclock B32;
328 CARD16 hdisplay B16;
329 CARD16 hsyncstart B16;
330 CARD16 hsyncend B16;
331 CARD16 htotal B16;
332 CARD16 vdisplay B16;
333 CARD16 vsyncstart B16;
334 CARD16 vsyncend B16;
335 CARD16 vtotal B16;
336 CARD32 flags B32;
337 CARD32 privsize B32;
338} xXF86OldVidModeDeleteModeLineReq,
339 xXF86OldVidModeValidateModeLineReq,
340 xXF86OldVidModeSwitchToModeReq;
341#define sz_xXF86OldVidModeDeleteModeLineReq 36
342#define sz_xXF86OldVidModeValidateModeLineReq 36
343#define sz_xXF86OldVidModeSwitchToModeReq 36
344
345typedef struct _XF86VidModeSwitchMode {
346 CARD8 reqType; /* always XF86VidModeReqCode */
347 CARD8 xf86vidmodeReqType; /* always X_XF86VidModeSwitchMode */
348 CARD16 length B16;
349 CARD16 screen B16;
350 CARD16 zoom B16;
351} xXF86VidModeSwitchModeReq;
352#define sz_xXF86VidModeSwitchModeReq 8
353
354typedef struct _XF86VidModeLockModeSwitch {
355 CARD8 reqType; /* always XF86VidModeReqCode */
356 CARD8 xf86vidmodeReqType; /* always X_XF86VidModeLockModeSwitch */
357 CARD16 length B16;
358 CARD16 screen B16;
359 CARD16 lock B16;
360} xXF86VidModeLockModeSwitchReq;
361#define sz_xXF86VidModeLockModeSwitchReq 8
362
363typedef struct {
364 BYTE type; /* X_Reply */
365 BOOL pad1;
366 CARD16 sequenceNumber B16;
367 CARD32 length B32;
368 CARD32 status B32;
369 CARD32 pad2 B32;
370 CARD32 pad3 B32;
371 CARD32 pad4 B32;
372 CARD32 pad5 B32;
373 CARD32 pad6 B32;
374} xXF86VidModeValidateModeLineReply;
375#define sz_xXF86VidModeValidateModeLineReply 32
376
377typedef struct {
378 BYTE type; /* X_Reply */
379 BOOL pad1;
380 CARD16 sequenceNumber B16;
381 CARD32 length B32;
382 CARD8 vendorLength;
383 CARD8 modelLength;
384 CARD8 nhsync;
385 CARD8 nvsync;
386 CARD32 pad2 B32;
387 CARD32 pad3 B32;
388 CARD32 pad4 B32;
389 CARD32 pad5 B32;
390 CARD32 pad6 B32;
391} xXF86VidModeGetMonitorReply;
392#define sz_xXF86VidModeGetMonitorReply 32
393
394typedef struct {
395 BYTE type;
396 BOOL pad1;
397 CARD16 sequenceNumber B16;
398 CARD32 length B32;
399 CARD32 x B32;
400 CARD32 y B32;
401 CARD32 pad2 B32;
402 CARD32 pad3 B32;
403 CARD32 pad4 B32;
404 CARD32 pad5 B32;
405} xXF86VidModeGetViewPortReply;
406#define sz_xXF86VidModeGetViewPortReply 32
407
408typedef struct _XF86VidModeSetViewPort {
409 CARD8 reqType; /* always VidModeReqCode */
410 CARD8 xf86vidmodeReqType; /* always X_XF86VidModeSetViewPort */
411 CARD16 length B16;
412 CARD16 screen B16;
413 CARD16 pad B16;
414 CARD32 x B32;
415 CARD32 y B32;
416} xXF86VidModeSetViewPortReq;
417#define sz_xXF86VidModeSetViewPortReq 16
418
419typedef struct {
420 BYTE type;
421 BOOL pad1;
422 CARD16 sequenceNumber B16;
423 CARD32 length B32;
424 CARD32 flags B32;
425 CARD32 clocks B32;
426 CARD32 maxclocks B32;
427 CARD32 pad2 B32;
428 CARD32 pad3 B32;
429 CARD32 pad4 B32;
430} xXF86VidModeGetDotClocksReply;
431#define sz_xXF86VidModeGetDotClocksReply 32
432
433typedef struct _XF86VidModeSetClientVersion {
434 CARD8 reqType; /* always XF86VidModeReqCode */
435 CARD8 xf86vidmodeReqType;
436 CARD16 length B16;
437 CARD16 major B16;
438 CARD16 minor B16;
439} xXF86VidModeSetClientVersionReq;
440#define sz_xXF86VidModeSetClientVersionReq 8
441
442typedef struct _XF86VidModeGetGamma {
443 CARD8 reqType; /* always XF86VidModeReqCode */
444 CARD8 xf86vidmodeReqType;
445 CARD16 length B16;
446 CARD16 screen B16;
447 CARD16 pad B16;
448 CARD32 pad1 B32;
449 CARD32 pad2 B32;
450 CARD32 pad3 B32;
451 CARD32 pad4 B32;
452 CARD32 pad5 B32;
453 CARD32 pad6 B32;
454} xXF86VidModeGetGammaReq;
455#define sz_xXF86VidModeGetGammaReq 32
456
457typedef struct {
458 BYTE type;
459 BOOL pad;
460 CARD16 sequenceNumber B16;
461 CARD32 length B32;
462 CARD32 red B32;
463 CARD32 green B32;
464 CARD32 blue B32;
465 CARD32 pad1 B32;
466 CARD32 pad2 B32;
467 CARD32 pad3 B32;
468} xXF86VidModeGetGammaReply;
469#define sz_xXF86VidModeGetGammaReply 32
470
471typedef struct _XF86VidModeSetGamma {
472 CARD8 reqType; /* always XF86VidModeReqCode */
473 CARD8 xf86vidmodeReqType;
474 CARD16 length B16;
475 CARD16 screen B16;
476 CARD16 pad B16;
477 CARD32 red B32;
478 CARD32 green B32;
479 CARD32 blue B32;
480 CARD32 pad1 B32;
481 CARD32 pad2 B32;
482 CARD32 pad3 B32;
483} xXF86VidModeSetGammaReq;
484#define sz_xXF86VidModeSetGammaReq 32
485
486
487typedef struct _XF86VidModeSetGammaRamp {
488 CARD8 reqType; /* always XF86VidModeReqCode */
489 CARD8 xf86vidmodeReqType;
490 CARD16 length B16;
491 CARD16 screen B16;
492 CARD16 size B16;
493} xXF86VidModeSetGammaRampReq;
494#define sz_xXF86VidModeSetGammaRampReq 8
495
496typedef struct _XF86VidModeGetGammaRamp {
497 CARD8 reqType; /* always XF86VidModeReqCode */
498 CARD8 xf86vidmodeReqType;
499 CARD16 length B16;
500 CARD16 screen B16;
501 CARD16 size B16;
502} xXF86VidModeGetGammaRampReq;
503#define sz_xXF86VidModeGetGammaRampReq 8
504
505typedef struct {
506 BYTE type;
507 BOOL pad;
508 CARD16 sequenceNumber B16;
509 CARD32 length B32;
510 CARD16 size B16;
511 CARD16 pad0 B16;
512 CARD32 pad1 B32;
513 CARD32 pad2 B32;
514 CARD32 pad3 B32;
515 CARD32 pad4 B32;
516 CARD32 pad5 B32;
517} xXF86VidModeGetGammaRampReply;
518#define sz_xXF86VidModeGetGammaRampReply 32
519
520typedef struct _XF86VidModeGetGammaRampSize {
521 CARD8 reqType; /* always XF86VidModeReqCode */
522 CARD8 xf86vidmodeReqType;
523 CARD16 length B16;
524 CARD16 screen B16;
525 CARD16 pad B16;
526} xXF86VidModeGetGammaRampSizeReq;
527#define sz_xXF86VidModeGetGammaRampSizeReq 8
528
529typedef struct {
530 BYTE type;
531 BOOL pad;
532 CARD16 sequenceNumber B16;
533 CARD32 length B32;
534 CARD16 size B16;
535 CARD16 pad0 B16;
536 CARD32 pad1 B32;
537 CARD32 pad2 B32;
538 CARD32 pad3 B32;
539 CARD32 pad4 B32;
540 CARD32 pad5 B32;
541} xXF86VidModeGetGammaRampSizeReply;
542#define sz_xXF86VidModeGetGammaRampSizeReply 32
543
544
545#endif /* _XF86VIDMODESTR_H_ */
546
diff --git a/apps/plugins/sdl/src/video/Xext/extensions/xme.h b/apps/plugins/sdl/src/video/Xext/extensions/xme.h
deleted file mode 100644
index f550623c9f..0000000000
--- a/apps/plugins/sdl/src/video/Xext/extensions/xme.h
+++ /dev/null
@@ -1,45 +0,0 @@
1/*
2 * Copyright 1993-2001 by Xi Graphics, Inc.
3 * All Rights Reserved.
4 *
5 * Please see the LICENSE file accompanying this distribution for licensing
6 * information.
7 *
8 * Please send any bug fixes and modifications to src@xig.com.
9 *
10 * $XiGId: xme.h,v 1.1.1.1 2001/11/19 19:01:10 jon Exp $
11 *
12 */
13
14
15#ifndef _XME_H_INCLUDED
16#define _XME_H_INCLUDED
17
18typedef struct {
19 short x;
20 short y;
21 unsigned short w;
22 unsigned short h;
23} XiGMiscViewInfo;
24
25typedef struct {
26 unsigned short width;
27 unsigned short height;
28 int refresh;
29} XiGMiscResolutionInfo;
30
31extern Bool XiGMiscQueryVersion(Display *dpy, int *major, int *minor);
32extern int XiGMiscQueryViews(Display *dpy, int screen,
33 XiGMiscViewInfo **pviews);
34extern int XiGMiscQueryResolutions(Display *dpy, int screen, int view,
35 int *pactive,
36 XiGMiscResolutionInfo **presolutions);
37extern void XiGMiscChangeResolution(Display *dpy, int screen, int view,
38 int width, int height, int refresh);
39
40/* SDL addition from Ryan: free memory used by xme. */
41extern void XiGMiscDestroy(void);
42
43#endif /* _XME_H_INCLUDED */
44
45
diff --git a/apps/plugins/sdl/src/video/aalib/SDL_aaevents.c b/apps/plugins/sdl/src/video/aalib/SDL_aaevents.c
deleted file mode 100644
index a26ab2d0e1..0000000000
--- a/apps/plugins/sdl/src/video/aalib/SDL_aaevents.c
+++ /dev/null
@@ -1,202 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting AA events into SDL events */
25
26#include <stdio.h>
27
28#include <aalib.h>
29
30#include "SDL.h"
31#include "../../events/SDL_sysevents.h"
32#include "../../events/SDL_events_c.h"
33#include "SDL_aavideo.h"
34#include "SDL_aaevents_c.h"
35
36/* The translation tables from a console scancode to a SDL keysym */
37static SDLKey keymap[401];
38
39static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym);
40
41
42void AA_PumpEvents(_THIS)
43{
44 int posted = 0;
45 int mouse_button, mouse_x, mouse_y;
46 int evt;
47 SDL_keysym keysym;
48
49 static int prev_button = -1, prev_x = -1, prev_y = -1;
50
51 if( ! this->screen ) /* Wait till we got the screen initialized */
52 return;
53
54 do {
55 posted = 0;
56 /* Gather events */
57
58 /* Get mouse status */
59 SDL_mutexP(AA_mutex);
60 aa_getmouse (AA_context, &mouse_x, &mouse_y, &mouse_button);
61 SDL_mutexV(AA_mutex);
62 mouse_x = mouse_x * this->screen->w / aa_scrwidth (AA_context);
63 mouse_y = mouse_y * this->screen->h / aa_scrheight (AA_context);
64
65 /* Compare against previous state and generate events */
66 if( prev_button != mouse_button ) {
67 if( mouse_button & AA_BUTTON1 ) {
68 if ( ! (prev_button & AA_BUTTON1) ) {
69 posted += SDL_PrivateMouseButton(SDL_PRESSED, 1, 0, 0);
70 }
71 } else {
72 if ( prev_button & AA_BUTTON1 ) {
73 posted += SDL_PrivateMouseButton(SDL_RELEASED, 1, 0, 0);
74 }
75 }
76 if( mouse_button & AA_BUTTON2 ) {
77 if ( ! (prev_button & AA_BUTTON2) ) {
78 posted += SDL_PrivateMouseButton(SDL_PRESSED, 2, 0, 0);
79 }
80 } else {
81 if ( prev_button & AA_BUTTON2 ) {
82 posted += SDL_PrivateMouseButton(SDL_RELEASED, 2, 0, 0);
83 }
84 }
85 if( mouse_button & AA_BUTTON3 ) {
86 if ( ! (prev_button & AA_BUTTON3) ) {
87 posted += SDL_PrivateMouseButton(SDL_PRESSED, 3, 0, 0);
88 }
89 } else {
90 if ( prev_button & AA_BUTTON3 ) {
91 posted += SDL_PrivateMouseButton(SDL_RELEASED, 3, 0, 0);
92 }
93 }
94 }
95 if ( prev_x != mouse_x || prev_y != mouse_y ) {
96 posted += SDL_PrivateMouseMotion(0, 0, mouse_x, mouse_y);
97 }
98
99 prev_button = mouse_button;
100 prev_x = mouse_x; prev_y = mouse_y;
101
102 /* Get keyboard event */
103 SDL_mutexP(AA_mutex);
104 evt = aa_getevent(AA_context, 0);
105 SDL_mutexV(AA_mutex);
106 if ( (evt > AA_NONE) && (evt < AA_RELEASE) && (evt != AA_MOUSE) && (evt != AA_RESIZE) ) {
107 /* Key pressed */
108/* printf("Key pressed: %d (%c)\n", evt, evt); */
109 posted += SDL_PrivateKeyboard(SDL_PRESSED, TranslateKey(evt, &keysym));
110 } else if ( evt >= AA_RELEASE ) {
111 /* Key released */
112 evt &= ~AA_RELEASE;
113/* printf("Key released: %d (%c)\n", evt, evt); */
114 posted += SDL_PrivateKeyboard(SDL_RELEASED, TranslateKey(evt, &keysym));
115 }
116 } while ( posted );
117}
118
119void AA_InitOSKeymap(_THIS)
120{
121 int i;
122 static const char *std_keys = " 01234567890&#'()_-|$*+-=/\\:;.,!?<>{}[]@~%^\x9";
123 const char *std;
124
125 /* Initialize the AAlib key translation table */
126 for ( i=0; i<SDL_arraysize(keymap); ++i )
127 keymap[i] = SDLK_UNKNOWN;
128
129 /* Alphabet keys */
130 for ( i = 0; i<26; ++i ){
131 keymap['a' + i] = SDLK_a+i;
132 keymap['A' + i] = SDLK_a+i;
133 }
134 /* Function keys */
135 for ( i = 0; i<12; ++i ){
136 keymap[334 + i] = SDLK_F1+i;
137 }
138 /* Keys that have the same symbols and don't have to be translated */
139 for( std = std_keys; *std; std ++ ) {
140 keymap[*std] = *std;
141 }
142
143 keymap[13] = SDLK_RETURN;
144 keymap[AA_BACKSPACE] = SDLK_BACKSPACE;
145
146 keymap[369] = SDLK_LSHIFT;
147 keymap[370] = SDLK_RSHIFT;
148 keymap[371] = SDLK_LCTRL;
149 keymap[372] = SDLK_RCTRL;
150 keymap[377] = SDLK_LALT;
151 keymap[270] = SDLK_RALT;
152 keymap[271] = SDLK_NUMLOCK;
153 keymap[373] = SDLK_CAPSLOCK;
154 keymap[164] = SDLK_SCROLLOCK;
155
156 keymap[243] = SDLK_INSERT;
157 keymap[304] = SDLK_DELETE;
158 keymap[224] = SDLK_HOME;
159 keymap[231] = SDLK_END;
160 keymap[229] = SDLK_PAGEUP;
161 keymap[230] = SDLK_PAGEDOWN;
162
163 keymap[241] = SDLK_PRINT;
164 keymap[163] = SDLK_BREAK;
165
166 keymap[302] = SDLK_KP0;
167 keymap[300] = SDLK_KP1;
168 keymap[297] = SDLK_KP2;
169 keymap[299] = SDLK_KP3;
170 keymap[294] = SDLK_KP4;
171 keymap[301] = SDLK_KP5;
172 keymap[296] = SDLK_KP6;
173 keymap[293] = SDLK_KP7;
174 keymap[295] = SDLK_KP8;
175 keymap[298] = SDLK_KP9;
176
177 keymap[AA_ESC] = SDLK_ESCAPE;
178 keymap[AA_UP] = SDLK_UP;
179 keymap[AA_DOWN] = SDLK_DOWN;
180 keymap[AA_LEFT] = SDLK_LEFT;
181 keymap[AA_RIGHT] = SDLK_RIGHT;
182}
183
184static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym)
185{
186 /* Sanity check */
187 if ( scancode >= SDL_arraysize(keymap) )
188 scancode = AA_UNKNOWN;
189
190 /* Set the keysym information */
191 keysym->scancode = scancode;
192 keysym->sym = keymap[scancode];
193 keysym->mod = KMOD_NONE;
194
195 /* If UNICODE is on, get the UNICODE value for the key */
196 keysym->unicode = 0;
197 if ( SDL_TranslateUNICODE ) {
198 /* Populate the unicode field with the ASCII value */
199 keysym->unicode = scancode;
200 }
201 return(keysym);
202}
diff --git a/apps/plugins/sdl/src/video/aalib/SDL_aaevents_c.h b/apps/plugins/sdl/src/video/aalib/SDL_aaevents_c.h
deleted file mode 100644
index 6dbc9f691f..0000000000
--- a/apps/plugins/sdl/src/video/aalib/SDL_aaevents_c.h
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_aavideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29extern void AA_initkeymaps(int fd);
30extern void AA_mousecallback(int button, int dx, int dy,
31 int u1,int u2,int u3, int u4);
32extern void AA_keyboardcallback(int scancode, int pressed);
33
34extern void AA_InitOSKeymap(_THIS);
35extern void AA_PumpEvents(_THIS);
diff --git a/apps/plugins/sdl/src/video/aalib/SDL_aamouse.c b/apps/plugins/sdl/src/video/aalib/SDL_aamouse.c
deleted file mode 100644
index dc784a56f9..0000000000
--- a/apps/plugins/sdl/src/video/aalib/SDL_aamouse.c
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <stdio.h>
25
26#include "SDL_mouse.h"
27#include "../../events/SDL_events_c.h"
28
29#include "SDL_aamouse_c.h"
30
31
32/* The implementation dependent data for the window manager cursor */
33struct WMcursor {
34 int unused;
35};
diff --git a/apps/plugins/sdl/src/video/aalib/SDL_aamouse_c.h b/apps/plugins/sdl/src/video/aalib/SDL_aamouse_c.h
deleted file mode 100644
index 6ce3d9863b..0000000000
--- a/apps/plugins/sdl/src/video/aalib/SDL_aamouse_c.h
+++ /dev/null
@@ -1,26 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_aavideo.h"
25
26/* Functions to be exported */
diff --git a/apps/plugins/sdl/src/video/aalib/SDL_aavideo.c b/apps/plugins/sdl/src/video/aalib/SDL_aavideo.c
deleted file mode 100644
index e6d5d3e4ce..0000000000
--- a/apps/plugins/sdl/src/video/aalib/SDL_aavideo.c
+++ /dev/null
@@ -1,388 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* AAlib based SDL video driver implementation.
25*/
26
27#include <unistd.h>
28#include <sys/stat.h>
29
30
31#include "SDL_video.h"
32#include "SDL_mouse.h"
33#include "../SDL_sysvideo.h"
34#include "../SDL_pixels_c.h"
35#include "../../events/SDL_events_c.h"
36
37#include "SDL_aavideo.h"
38#include "SDL_aaevents_c.h"
39#include "SDL_aamouse_c.h"
40
41#include <aalib.h>
42
43/* Initialization/Query functions */
44static int AA_VideoInit(_THIS, SDL_PixelFormat *vformat);
45static SDL_Rect **AA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
46static SDL_Surface *AA_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
47static int AA_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
48static void AA_VideoQuit(_THIS);
49
50/* Hardware surface functions */
51static int AA_AllocHWSurface(_THIS, SDL_Surface *surface);
52static int AA_LockHWSurface(_THIS, SDL_Surface *surface);
53static int AA_FlipHWSurface(_THIS, SDL_Surface *surface);
54static void AA_UnlockHWSurface(_THIS, SDL_Surface *surface);
55static void AA_FreeHWSurface(_THIS, SDL_Surface *surface);
56
57/* Cache the VideoDevice struct */
58static struct SDL_VideoDevice *local_this;
59
60/* AAlib driver bootstrap functions */
61
62static int AA_Available(void)
63{
64 return 1; /* Always available ! */
65}
66
67static void AA_DeleteDevice(SDL_VideoDevice *device)
68{
69 SDL_free(device->hidden);
70 SDL_free(device);
71}
72
73static SDL_VideoDevice *AA_CreateDevice(int devindex)
74{
75 SDL_VideoDevice *device;
76
77 /* Initialize all variables that we clean on shutdown */
78 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
79 if ( device ) {
80 SDL_memset(device, 0, (sizeof *device));
81 device->hidden = (struct SDL_PrivateVideoData *)
82 SDL_malloc((sizeof *device->hidden));
83 }
84 if ( (device == NULL) || (device->hidden == NULL) ) {
85 SDL_OutOfMemory();
86 if ( device ) {
87 SDL_free(device);
88 }
89 return(0);
90 }
91 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
92
93 /* Set the function pointers */
94 device->VideoInit = AA_VideoInit;
95 device->ListModes = AA_ListModes;
96 device->SetVideoMode = AA_SetVideoMode;
97 device->CreateYUVOverlay = NULL;
98 device->SetColors = AA_SetColors;
99 device->UpdateRects = NULL;
100 device->VideoQuit = AA_VideoQuit;
101 device->AllocHWSurface = AA_AllocHWSurface;
102 device->CheckHWBlit = NULL;
103 device->FillHWRect = NULL;
104 device->SetHWColorKey = NULL;
105 device->SetHWAlpha = NULL;
106 device->LockHWSurface = AA_LockHWSurface;
107 device->UnlockHWSurface = AA_UnlockHWSurface;
108 device->FlipHWSurface = NULL;
109 device->FreeHWSurface = AA_FreeHWSurface;
110 device->SetCaption = NULL;
111 device->SetIcon = NULL;
112 device->IconifyWindow = NULL;
113 device->GrabInput = NULL;
114 device->GetWMInfo = NULL;
115 device->InitOSKeymap = AA_InitOSKeymap;
116 device->PumpEvents = AA_PumpEvents;
117
118 device->free = AA_DeleteDevice;
119
120 return device;
121}
122
123VideoBootStrap AALIB_bootstrap = {
124 "aalib", "ASCII Art Library",
125 AA_Available, AA_CreateDevice
126};
127
128static void AA_ResizeHandler(aa_context *);
129
130int AA_VideoInit(_THIS, SDL_PixelFormat *vformat)
131{
132 int keyboard;
133 int i;
134
135 /* Initialize all variables that we clean on shutdown */
136 for ( i=0; i<SDL_NUMMODES; ++i ) {
137 SDL_modelist[i] = SDL_malloc(sizeof(SDL_Rect));
138 SDL_modelist[i]->x = SDL_modelist[i]->y = 0;
139 }
140 /* Modes sorted largest to smallest */
141 SDL_modelist[0]->w = 1024; SDL_modelist[0]->h = 768;
142 SDL_modelist[1]->w = 800; SDL_modelist[1]->h = 600;
143 SDL_modelist[2]->w = 640; SDL_modelist[2]->h = 480;
144 SDL_modelist[3]->w = 320; SDL_modelist[3]->h = 400;
145 SDL_modelist[4]->w = 320; SDL_modelist[4]->h = 240;
146 SDL_modelist[5]->w = 320; SDL_modelist[5]->h = 200;
147 SDL_modelist[6] = NULL;
148
149 /* Initialize the library */
150
151 AA_mutex = SDL_CreateMutex();
152
153 aa_parseoptions (NULL, NULL, NULL, NULL);
154
155 AA_context = aa_autoinit(&aa_defparams);
156 if ( ! AA_context ) {
157 SDL_SetError("Unable to initialize AAlib");
158 return(-1);
159 }
160
161 /* Enable mouse and keyboard support */
162
163 if ( ! aa_autoinitkbd (AA_context, AA_SENDRELEASE) ) {
164 SDL_SetError("Unable to initialize AAlib keyboard");
165 return(-1);
166 }
167 if ( ! aa_autoinitmouse (AA_context, AA_SENDRELEASE) ) {
168 fprintf(stderr,"Warning: Unable to initialize AAlib mouse");
169 }
170 AA_rparams = aa_getrenderparams();
171
172 local_this = this;
173
174 aa_resizehandler(AA_context, AA_ResizeHandler);
175
176 fprintf(stderr,"Using AAlib driver: %s (%s)\n", AA_context->driver->name, AA_context->driver->shortname);
177
178 AA_in_x11 = (SDL_strcmp(AA_context->driver->shortname,"X11") == 0);
179 /* Determine the screen depth (use default 8-bit depth) */
180 vformat->BitsPerPixel = 8;
181 vformat->BytesPerPixel = 1;
182
183 /* We're done! */
184 return(0);
185}
186
187SDL_Rect **AA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
188{
189 if(format->BitsPerPixel != 8)
190 return NULL;
191
192 if ( flags & SDL_FULLSCREEN ) {
193 return SDL_modelist;
194 } else {
195 return (SDL_Rect **) -1;
196 }
197}
198
199/* From aavga.c
200 AAlib does not give us the choice of the actual resolution, thus we have to simulate additional
201 resolution by scaling down manually each frame
202*/
203static void fastscale (register char *b1, register char *b2, int x1, int x2, int y1, int y2)
204{
205 register int ex, spx = 0, ddx, ddx1;
206 int ddy1, ddy, spy = 0, ey;
207 int x;
208 char *bb1 = b1;
209 if (!x1 || !x2 || !y1 || !y2)
210 return;
211 ddx = x1 + x1;
212 ddx1 = x2 + x2;
213 if (ddx1 < ddx)
214 spx = ddx / ddx1, ddx %= ddx1;
215 ddy = y1 + y1;
216 ddy1 = y2 + y2;
217 if (ddy1 < ddy)
218 spy = (ddy / ddy1) * x1, ddy %= ddy1;
219 ey = -ddy1;
220 for (; y2; y2--) {
221 ex = -ddx1;
222 for (x = x2; x; x--) {
223 *b2 = *b1;
224 b2++;
225 b1 += spx;
226 ex += ddx;
227 if (ex > 0) {
228 b1++;
229 ex -= ddx1;
230 }
231 }
232 bb1 += spy;
233 ey += ddy;
234 if (ey > 0) {
235 bb1 += x1;
236 ey -= ddy1;
237 }
238 b1 = bb1;
239 }
240}
241
242/* Various screen update functions available */
243static void AA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
244
245SDL_Surface *AA_SetVideoMode(_THIS, SDL_Surface *current,
246 int width, int height, int bpp, Uint32 flags)
247{
248 int mode;
249
250 if ( AA_buffer ) {
251 SDL_free( AA_buffer );
252 }
253
254 AA_buffer = SDL_malloc(width * height);
255 if ( ! AA_buffer ) {
256 SDL_SetError("Couldn't allocate buffer for requested mode");
257 return(NULL);
258 }
259
260/* printf("Setting mode %dx%d\n", width, height); */
261
262 SDL_memset(aa_image(AA_context), 0, aa_imgwidth(AA_context) * aa_imgheight(AA_context));
263 SDL_memset(AA_buffer, 0, width * height);
264
265 /* Allocate the new pixel format for the screen */
266 if ( ! SDL_ReallocFormat(current, 8, 0, 0, 0, 0) ) {
267 return(NULL);
268 }
269
270 /* Set up the new mode framebuffer */
271 current->flags = SDL_FULLSCREEN;
272 AA_w = current->w = width;
273 AA_h = current->h = height;
274 current->pitch = current->w;
275 current->pixels = AA_buffer;
276
277 AA_x_ratio = ((double)aa_imgwidth(AA_context)) / ((double)width);
278 AA_y_ratio = ((double)aa_imgheight(AA_context)) / ((double)height);
279
280 /* Set the blit function */
281 this->UpdateRects = AA_DirectUpdate;
282
283 /* We're done */
284 return(current);
285}
286
287static void AA_ResizeHandler(aa_context *context)
288{
289 aa_resize(context);
290 local_this->hidden->x_ratio = ((double)aa_imgwidth(context)) / ((double)local_this->screen->w);
291 local_this->hidden->y_ratio = ((double)aa_imgheight(context)) / ((double)local_this->screen->h);
292
293 fastscale (local_this->hidden->buffer, aa_image(context), local_this->hidden->w, aa_imgwidth (context), local_this->hidden->h, aa_imgheight (context));
294 aa_renderpalette(context, local_this->hidden->palette, local_this->hidden->rparams, 0, 0, aa_scrwidth(context), aa_scrheight(context));
295 aa_flush(context);
296}
297
298/* We don't actually allow hardware surfaces other than the main one */
299static int AA_AllocHWSurface(_THIS, SDL_Surface *surface)
300{
301 return(-1);
302}
303static void AA_FreeHWSurface(_THIS, SDL_Surface *surface)
304{
305 return;
306}
307
308/* We need to wait for vertical retrace on page flipped displays */
309static int AA_LockHWSurface(_THIS, SDL_Surface *surface)
310{
311 /* TODO ? */
312 return(0);
313}
314static void AA_UnlockHWSurface(_THIS, SDL_Surface *surface)
315{
316 return;
317}
318
319/* FIXME: How is this done with AAlib? */
320static int AA_FlipHWSurface(_THIS, SDL_Surface *surface)
321{
322 SDL_mutexP(AA_mutex);
323 aa_flush(AA_context);
324 SDL_mutexV(AA_mutex);
325 return(0);
326}
327
328static void AA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
329{
330 int i;
331 SDL_Rect *rect;
332
333 fastscale (AA_buffer, aa_image(AA_context), AA_w, aa_imgwidth (AA_context), AA_h, aa_imgheight (AA_context));
334#if 1
335 aa_renderpalette(AA_context, AA_palette, AA_rparams, 0, 0, aa_scrwidth(AA_context), aa_scrheight(AA_context));
336#else
337 /* Render only the rectangles in the list */
338 printf("Update rects : ");
339 for ( i=0; i < numrects; ++i ) {
340 rect = &rects[i];
341 printf("(%d,%d-%d,%d)", rect->x, rect->y, rect->w, rect->h);
342 aa_renderpalette(AA_context, AA_palette, AA_rparams, rect->x * AA_x_ratio, rect->y * AA_y_ratio, rect->w * AA_x_ratio, rect->h * AA_y_ratio);
343 }
344 printf("\n");
345#endif
346 SDL_mutexP(AA_mutex);
347 aa_flush(AA_context);
348 SDL_mutexV(AA_mutex);
349 return;
350}
351
352int AA_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
353{
354 int i;
355
356 for ( i=0; i < ncolors; i++ ) {
357 aa_setpalette(AA_palette, firstcolor + i,
358 colors[i].r>>2,
359 colors[i].g>>2,
360 colors[i].b>>2);
361 }
362 return(1);
363}
364
365/* Note: If we are terminated, this could be called in the middle of
366 another SDL video routine -- notably UpdateRects.
367*/
368void AA_VideoQuit(_THIS)
369{
370 int i;
371
372 aa_uninitkbd(AA_context);
373 aa_uninitmouse(AA_context);
374
375 /* Free video mode lists */
376 for ( i=0; i<SDL_NUMMODES; ++i ) {
377 if ( SDL_modelist[i] != NULL ) {
378 SDL_free(SDL_modelist[i]);
379 SDL_modelist[i] = NULL;
380 }
381 }
382
383 aa_close(AA_context);
384
385 SDL_DestroyMutex(AA_mutex);
386
387 this->screen->pixels = NULL;
388}
diff --git a/apps/plugins/sdl/src/video/aalib/SDL_aavideo.h b/apps/plugins/sdl/src/video/aalib/SDL_aavideo.h
deleted file mode 100644
index 987edc9768..0000000000
--- a/apps/plugins/sdl/src/video/aalib/SDL_aavideo.h
+++ /dev/null
@@ -1,66 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_aavideo_h
25#define _SDL_aavideo_h
26
27#include "SDL_mouse.h"
28#include "SDL_mutex.h"
29#include "../SDL_sysvideo.h"
30
31#include <aalib.h>
32
33/* Hidden "this" pointer for the video functions */
34#define _THIS SDL_VideoDevice *this
35
36#define SDL_NUMMODES 6
37
38/* Private display data */
39struct SDL_PrivateVideoData {
40 SDL_Rect *SDL_modelist[SDL_NUMMODES+1];
41 aa_context *context;
42 aa_palette palette;
43 aa_renderparams *rparams;
44 double x_ratio, y_ratio;
45 int w, h;
46 SDL_mutex *mutex;
47 int in_x11;
48 void *buffer;
49};
50
51/* Old variable names */
52#define SDL_modelist (this->hidden->SDL_modelist)
53#define AA_context (this->hidden->context)
54#define AA_palette (this->hidden->palette)
55#define AA_rparams (this->hidden->rparams)
56#define AA_buffer (this->hidden->buffer)
57
58#define AA_x_ratio (this->hidden->x_ratio)
59#define AA_y_ratio (this->hidden->y_ratio)
60
61#define AA_mutex (this->hidden->mutex)
62#define AA_in_x11 (this->hidden->in_x11)
63#define AA_w (this->hidden->w)
64#define AA_h (this->hidden->h)
65
66#endif /* _SDL_aavideo_h */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_ataric2p.S b/apps/plugins/sdl/src/video/ataricommon/SDL_ataric2p.S
deleted file mode 100644
index 3cd1961b85..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_ataric2p.S
+++ /dev/null
@@ -1,452 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/*
24 Chunky to planar conversion routine
25 1 byte/pixel -> 4 or 8 bit planes
26
27 Patrice Mandin
28 Xavier Joubert
29 Mikael Kalms
30*/
31
32 .globl _SDL_Atari_C2pConvert
33 .globl _SDL_Atari_C2pConvert8
34 .globl _SDL_Atari_C2pConvert4
35 .globl _SDL_Atari_C2pConvert4_pal
36
37/* ------------ Conversion C2P, 8 bits ------------ */
38
39 .text
40_SDL_Atari_C2pConvert8:
41#if !defined(__mcoldfire__)
42 movel sp@(4),c2p_source
43 movel sp@(8),c2p_dest
44 movel sp@(12),c2p_width
45 movel sp@(16),c2p_height
46 movel sp@(20),c2p_dblligne
47 movel sp@(24),c2p_srcpitch
48 movel sp@(28),c2p_dstpitch
49
50 moveml d2-d7/a2-a6,sp@-
51
52 movel c2p_source,c2p_cursrc
53 movel c2p_dest,c2p_curdst
54 movel #0x0f0f0f0f,d4
55 movel #0x00ff00ff,d5
56 movel #0x55555555,d6
57 movew c2p_height+2,c2p_row
58 movew c2p_width+2,d0
59 andw #-8,d0
60 movew d0,c2p_rowlen
61
62SDL_Atari_C2p8_rowloop:
63
64 movel c2p_cursrc,a0
65 movel c2p_curdst,a1
66
67 movel a0,a2
68 addw c2p_rowlen,a2
69
70 movel a0@+,d0
71 movel a0@+,d1
72 movel a0@+,d2
73 movel a0@+,d3
74/*
75 d0 = a7a6a5a4a3a2a1a0 b7b6b5b4b3b2b1b0 c7c6c5c4c3c2c1c0 d7d6d5d4d3d2d1d0
76 d1 = e7e6e5e4e3e2e1e0 f7f6f5f4f3f2f1f0 g7g6g5g4g3g2g1g0 h7h6h5h4h3h2h1h0
77 d2 = i7i6i5i4i3i2i1i0 j7j6j5j4j3j2j1j0 k7k6k5k4k3k2k1k0 l7l6l5l4l3l2l1l0
78 d3 = m7m6m5m4m3m2m1m0 n7n6n5n4n3n2n1n0 o7o6o5o4o3o2o1o0 p7p6p5p4p3p2p1p0
79*/
80 movel d1,d7
81 lsrl #4,d7
82 eorl d0,d7
83 andl d4,d7
84 eorl d7,d0
85 lsll #4,d7
86 eorl d7,d1
87
88 movel d3,d7
89 lsrl #4,d7
90 eorl d2,d7
91 andl d4,d7
92 eorl d7,d2
93 lsll #4,d7
94 eorl d7,d3
95
96 movel d2,d7
97 lsrl #8,d7
98 eorl d0,d7
99 andl d5,d7
100 eorl d7,d0
101 lsll #8,d7
102 eorl d7,d2
103
104 movel d3,d7
105 lsrl #8,d7
106 eorl d1,d7
107 andl d5,d7
108 eorl d7,d1
109 lsll #8,d7
110 eorl d7,d3
111/*
112 d0 = a7a6a5a4e7e6e5e4 i7i6i5i4m7m6m5m4 c7c6c5c4g7g6g5g4 k7k6k5k4o7o6o5o4
113 d1 = a3a2a1a0e3e2e1e0 i3i2i1i0m3m2m1m0 c3c2c1c0g3g2g1g0 k3k2k1k0o3o2o1o0
114 d2 = b7b6b5b4f7f6f5f4 j7j6j5j4n7n6n5n4 d7d6d5d4h7h6h5h4 l7l6l5l4p7p6p5p4
115 d3 = b3b2b1b0f3f2f1f0 j3j2j1j0n3n2n1n0 d3d2d1d0h3h2h1h0 l3l2l1l0p3p2p1p0
116*/
117 bras SDL_Atari_C2p8_start
118
119SDL_Atari_C2p8_pix16:
120
121 movel a0@+,d0
122 movel a0@+,d1
123 movel a0@+,d2
124 movel a0@+,d3
125/*
126 d0 = a7a6a5a4a3a2a1a0 b7b6b5b4b3b2b1b0 c7c6c5c4c3c2c1c0 d7d6d5d4d3d2d1d0
127 d1 = e7e6e5e4e3e2e1e0 f7f6f5f4f3f2f1f0 g7g6g5g4g3g2g1g0 h7h6h5h4h3h2h1h0
128 d2 = i7i6i5i4i3i2i1i0 j7j6j5j4j3j2j1j0 k7k6k5k4k3k2k1k0 l7l6l5l4l3l2l1l0
129 d3 = m7m6m5m4m3m2m1m0 n7n6n5n4n3n2n1n0 o7o6o5o4o3o2o1o0 p7p6p5p4p3p2p1p0
130*/
131 movel d1,d7
132 lsrl #4,d7
133 movel a3,a1@+
134 eorl d0,d7
135 andl d4,d7
136 eorl d7,d0
137 lsll #4,d7
138 eorl d7,d1
139
140 movel d3,d7
141 lsrl #4,d7
142 eorl d2,d7
143 andl d4,d7
144 eorl d7,d2
145 movel a4,a1@+
146 lsll #4,d7
147 eorl d7,d3
148
149 movel d2,d7
150 lsrl #8,d7
151 eorl d0,d7
152 andl d5,d7
153 eorl d7,d0
154 movel a5,a1@+
155 lsll #8,d7
156 eorl d7,d2
157
158 movel d3,d7
159 lsrl #8,d7
160 eorl d1,d7
161 andl d5,d7
162 eorl d7,d1
163 movel a6,a1@+
164 lsll #8,d7
165 eorl d7,d3
166/*
167 d0 = a7a6a5a4e7e6e5e4 i7i6i5i4m7m6m5m4 c7c6c5c4g7g6g5g4 k7k6k5k4o7o6o5o4
168 d1 = a3a2a1a0e3e2e1e0 i3i2i1i0m3m2m1m0 c3c2c1c0g3g2g1g0 k3k2k1k0o3o2o1o0
169 d2 = b7b6b5b4f7f6f5f4 j7j6j5j4n7n6n5n4 d7d6d5d4h7h6h5h4 l7l6l5l4p7p6p5p4
170 d3 = b3b2b1b0f3f2f1f0 j3j2j1j0n3n2n1n0 d3d2d1d0h3h2h1h0 l3l2l1l0p3p2p1p0
171*/
172
173SDL_Atari_C2p8_start:
174
175 movel d2,d7
176 lsrl #1,d7
177 eorl d0,d7
178 andl d6,d7
179 eorl d7,d0
180 addl d7,d7
181 eorl d7,d2
182
183 movel d3,d7
184 lsrl #1,d7
185 eorl d1,d7
186 andl d6,d7
187 eorl d7,d1
188 addl d7,d7
189 eorl d7,d3
190/*
191 d0 = a7b7a5b5e7f7e5f5 i7j7i5j5m7n7m5n5 c7d7c5d5g7h7g5h5 k7l7k5l5o7p7o5p5
192 d1 = a3b3a1b1e3f3e1f1 i3j3i1j1m3n3m1n1 c3d3c1d1g3h3g1h1 k3l3k1l1o3p3o1p1
193 d2 = a6b6a4b4e6f6e4f4 i6j6i4j4m6n6m4n4 c6d6c4d4g6h6g4h4 k6l6k4l4o6p6o4p4
194 d3 = a2b2a0b0e2f2e0f0 i2j2i0j0m2n2m0n0 c2d2c0d0g2h2g0h0 k2l2k0l0o2p2o0p0
195*/
196 movew d2,d7
197 movew d0,d2
198 swap d2
199 movew d2,d0
200 movew d7,d2
201
202 movew d3,d7
203 movew d1,d3
204 swap d3
205 movew d3,d1
206 movew d7,d3
207/*
208 d0 = a7b7a5b5e7f7e5f5 i7j7i5j5m7n7m5n5 a6b6a4b4e6f6e4f4 i6j6i4j4m6n6m4n4
209 d1 = a3b3a1b1e3f3e1f1 i3j3i1j1m3n3m1n1 a2b2a0b0e2f2e0f0 i2j2i0j0m2n2m0n0
210 d2 = c7d7c5d5g7h7g5h5 k7l7k5l5o7p7o5p5 c6d6c4d4g6h6g4h4 k6l6k4l4o6p6o4p4
211 d3 = c3d3c1d1g3h3g1h1 k3l3k1l1o3p3o1p1 c2d2c0d0g2h2g0h0 k2l2k0l0o2p2o0p0
212*/
213 movel d2,d7
214 lsrl #2,d7
215 eorl d0,d7
216 andl #0x33333333,d7
217 eorl d7,d0
218 lsll #2,d7
219 eorl d7,d2
220
221 movel d3,d7
222 lsrl #2,d7
223 eorl d1,d7
224 andl #0x33333333,d7
225 eorl d7,d1
226 lsll #2,d7
227 eorl d7,d3
228/*
229 d0 = a7b7c7d7e7f7g7h7 i7j7k7l7m7n7o7p7 a6b6c6d6e6f6g6h6 i6j6k6l6m6n6o6p6
230 d1 = a3b3c3d3e3f3g3h3 i3j3k3l3m3n3o3p3 a2b2c2d2e2f2g2h2 i2j2k2l2m2n2o2p2
231 d2 = a5b5c5d5e5f5g5h5 i5j5k5l5m5n5o5p5 a4b4c4d4e4f4g4h4 i4j4k4l4m4n4o4p4
232 d3 = a1b1c1d1e1f1g1h1 i1j1k1l1m1n1o1p1 a0b0c0d0e0f0g0h0 i0j0k0l0m0n0o0p0
233*/
234 swap d0
235 swap d1
236 swap d2
237 swap d3
238
239 movel d0,a6
240 movel d2,a5
241 movel d1,a4
242 movel d3,a3
243
244 cmpl a0,a2
245 bgt SDL_Atari_C2p8_pix16
246
247 movel a3,a1@+
248 movel a4,a1@+
249 movel a5,a1@+
250 movel a6,a1@+
251
252 /* Double the line ? */
253
254 movel c2p_srcpitch,d0
255 movel c2p_dstpitch,d1
256
257 tstl c2p_dblligne
258 beqs SDL_Atari_C2p8_nodblline
259
260 movel c2p_curdst,a0
261 movel a0,a1
262 addl d1,a1
263
264 movew c2p_width+2,d7
265 lsrw #4,d7
266 subql #1,d7
267SDL_Atari_C2p8_dblloop:
268 movel a0@+,a1@+
269 movel a0@+,a1@+
270 movel a0@+,a1@+
271 movel a0@+,a1@+
272 dbra d7,SDL_Atari_C2p8_dblloop
273
274 addl d1,c2p_curdst
275
276SDL_Atari_C2p8_nodblline:
277
278 /* Next line */
279
280 addl d0,c2p_cursrc
281 addl d1,c2p_curdst
282
283 subqw #1,c2p_row
284 bne SDL_Atari_C2p8_rowloop
285
286 moveml sp@+,d2-d7/a2-a6
287#endif
288 rts
289
290/* ------------ Conversion C2P, 4 bits ------------ */
291
292_SDL_Atari_C2pConvert4:
293#if !defined(__mcoldfire__)
294 movel sp@(4),c2p_source
295 movel sp@(8),c2p_dest
296 movel sp@(12),c2p_width
297 movel sp@(16),c2p_height
298 movel sp@(20),c2p_dblligne
299 movel sp@(24),c2p_srcpitch
300 movel sp@(28),c2p_dstpitch
301
302 moveml d2-d7/a2-a6,sp@-
303
304 movel c2p_source,a0
305 movel c2p_dest,a1
306 lea _SDL_Atari_table_c2p,a2
307 movel #0x00070001,d3
308#if defined(__mc68020__)
309 moveq #0,d0
310#endif
311
312 movel c2p_height,d7
313 subql #1,d7
314c2p4_bcly:
315 movel a0,a4 | Save start address of source
316 movel a1,a5 | Save start address of dest
317
318 | Conversion
319
320 movel c2p_width,d6
321 lsrw #4,d6
322 subql #1,d6
323c2p4_bclx:
324 | Octets 0-7
325
326 moveq #0,d1
327 moveq #7,d5
328c2p4_bcl07:
329#if defined(__mc68020__)
330 moveb a0@+,d0
331 lea a2@(0,d0:w:4),a3
332#else
333 moveq #0,d0
334 moveb a0@+,d0
335 lslw #2,d0
336 lea a2@(0,d0:w),a3
337#endif
338 lsll #1,d1
339 orl a3@,d1
340 dbra d5,c2p4_bcl07
341
342 movepl d1,a1@(0)
343 addw d3,a1
344 swap d3
345
346 | Octets 8-15
347
348 moveq #0,d1
349 moveq #7,d5
350c2p4_bcl815:
351#if defined(__mc68020__)
352 moveb a0@+,d0
353 lea a2@(0,d0:w:4),a3
354#else
355 moveq #0,d0
356 moveb a0@+,d0
357 lslw #2,d0
358 lea a2@(0,d0:w),a3
359#endif
360 lsll #1,d1
361 orl a3@,d1
362 dbra d5,c2p4_bcl815
363
364 movepl d1,a1@(0)
365 addw d3,a1
366 swap d3
367
368 dbra d6,c2p4_bclx
369
370 | Double line ?
371
372 tstl c2p_dblligne
373 beqs c2p4_nodblligne
374
375 movel a5,a6 | src line
376 movel a5,a1 | dest line
377 addl c2p_dstpitch,a1
378
379 movel c2p_width,d6
380 lsrw #3,d6
381 subql #1,d6
382c2p4_copydbl:
383 movel a6@+,a1@+
384 dbra d6,c2p4_copydbl
385
386 addl c2p_dstpitch,a5
387c2p4_nodblligne:
388
389 | Next line
390
391 movel a4,a0
392 addl c2p_srcpitch,a0
393 movel a5,a1
394 addl c2p_dstpitch,a1
395
396 dbra d7,c2p4_bcly
397
398 moveml sp@+,d2-d7/a2-a6
399#endif
400 rts
401
402/* ------------ Conversion of a light palette in 4 bits ------------ */
403
404_SDL_Atari_C2pConvert4_pal:
405#if !defined(__mcoldfire__)
406 /* a0 is a 256-word light palette */
407 movel sp@(4),a0
408
409 moveml d2-d3,sp@-
410
411 lea _SDL_Atari_table_c2p,a1
412 movew #255,d3
413c2p_pal_initbcl:
414 movew a0@+,d0
415 lsrw #4,d0
416 andw #15,d0
417
418 moveq #3,d1
419c2p_pal_initbyte:
420 btst d1,d0
421 sne d2
422 negw d2
423 moveb d2,a1@(0,d1:w)
424
425 dbra d1,c2p_pal_initbyte
426
427 addql #4,a1
428 dbra d3,c2p_pal_initbcl
429
430 moveml sp@+,d2-d3
431#endif
432 rts
433
434/* ------------ Buffers ------------ */
435
436 .bss
437
438 .even
439 .comm _SDL_Atari_C2pConvert,4
440 .comm _SDL_Atari_table_c2p,1024
441
442 .comm c2p_source,4 /* Source framebuffer */
443 .comm c2p_dest,4 /* Destination framebuffer */
444 .comm c2p_width,4 /* Width of zone to convert */
445 .comm c2p_height,4 /* Height of zone to convert */
446 .comm c2p_dblligne,4 /* Double the lines while converting ? */
447 .comm c2p_srcpitch,4 /* Source pitch */
448 .comm c2p_dstpitch,4 /* Destination pitch */
449 .comm c2p_cursrc,4 /* Current source line */
450 .comm c2p_curdst,4 /* Current destination line */
451 .comm c2p_rowlen,2 /* Line length in bytes */
452 .comm c2p_row,2 /* Current line number */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_ataric2p_s.h b/apps/plugins/sdl/src/video/ataricommon/SDL_ataric2p_s.h
deleted file mode 100644
index 48bdae7242..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_ataric2p_s.h
+++ /dev/null
@@ -1,75 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _ATARI_C2P_h
25#define _ATARI_C2P_h
26
27#include "SDL_stdinc.h"
28
29/*--- Functions pointers ---*/
30
31/* Convert a chunky screen to bitplane screen */
32
33extern void (*SDL_Atari_C2pConvert)(
34 Uint8 *src, /* Source screen (one byte=one pixel) */
35 Uint8 *dest, /* Destination (4/8 bits planes) */
36 Uint32 width, /* Dimensions of screen to convert */
37 Uint32 height,
38 Uint32 dblligne, /* Double the lines when converting ? */
39 Uint32 srcpitch, /* Length of one source line in bytes */
40 Uint32 dstpitch /* Length of one destination line in bytes */
41);
42
43/*--- 8 bits functions ---*/
44
45/* Convert a chunky screen to bitplane screen */
46
47void SDL_Atari_C2pConvert8(
48 Uint8 *src, /* Source screen (one byte=one pixel) */
49 Uint8 *dest, /* Destination (8 bits planes) */
50 Uint32 width, /* Dimensions of screen to convert */
51 Uint32 height,
52 Uint32 dblligne, /* Double the lines when converting ? */
53 Uint32 srcpitch, /* Length of one source line in bytes */
54 Uint32 dstpitch /* Length of one destination line in bytes */
55);
56
57/*--- 4 bits functions ---*/
58
59/* Convert a chunky screen to bitplane screen */
60
61void SDL_Atari_C2pConvert4(
62 Uint8 *src, /* Source screen (one byte=one pixel) */
63 Uint8 *dest, /* Destination (4 bits planes) */
64 Uint32 width, /* Dimensions of screen to convert */
65 Uint32 height,
66 Uint32 dblligne, /* Double the lines when converting ? */
67 Uint32 srcpitch, /* Length of one source line in bytes */
68 Uint32 dstpitch /* Length of one destination line in bytes */
69);
70
71/* Conversion palette */
72
73void SDL_Atari_C2pConvert4_pal(Uint16 *lightpalette);
74
75#endif /* _ATARI_C2P_h */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_ataridevmouse.c b/apps/plugins/sdl/src/video/ataricommon/SDL_ataridevmouse.c
deleted file mode 100644
index 0527380bad..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_ataridevmouse.c
+++ /dev/null
@@ -1,159 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 MiNT /dev/mouse driver
26
27 Patrice Mandin
28*/
29
30#include <fcntl.h>
31#include <unistd.h>
32
33#include "../../events/SDL_events_c.h"
34#include "SDL_ataridevmouse_c.h"
35
36/* Defines */
37
38#define DEVICE_NAME "/dev/mouse"
39
40/* Local variables */
41
42static int handle = -1;
43static int mouseb, prev_mouseb;
44
45/* Functions */
46
47int SDL_AtariDevMouse_Open(void)
48{
49 int r;
50 const char *mousedev;
51
52 /*
53 TODO: Fix the MiNT device driver, that locks mouse for other
54 applications, so this is disabled till fixed
55 */
56 return 0;
57
58 /* First, try SDL_MOUSEDEV device */
59 mousedev = SDL_getenv("SDL_MOUSEDEV");
60 if (!mousedev) {
61 handle = open(mousedev, 0);
62 }
63
64 /* Failed, try default device */
65 if (handle<0) {
66 handle = open(DEVICE_NAME, 0);
67 }
68
69 if (handle<0) {
70 handle = -1;
71 return 0;
72 }
73
74 /* Set non blocking mode */
75 r = fcntl(handle, F_GETFL, 0);
76 if (r<0) {
77 close(handle);
78 handle = -1;
79 return 0;
80 }
81
82 r |= O_NDELAY;
83
84 r = fcntl(handle, F_SETFL, r);
85 if (r<0) {
86 close(handle);
87 handle = -1;
88 return 0;
89 }
90
91 prev_mouseb = 7;
92 return 1;
93}
94
95void SDL_AtariDevMouse_Close(void)
96{
97 if (handle>0) {
98 close(handle);
99 handle = -1;
100 }
101}
102
103static int atari_GetButton(int button)
104{
105 switch(button)
106 {
107 case 0:
108 return SDL_BUTTON_RIGHT;
109 case 1:
110 return SDL_BUTTON_MIDDLE;
111 default:
112 break;
113 }
114
115 return SDL_BUTTON_LEFT;
116}
117
118void SDL_AtariDevMouse_PostMouseEvents(_THIS, SDL_bool buttonEvents)
119{
120 unsigned char buffer[3];
121 int mousex, mousey;
122
123 if (handle<0) {
124 return;
125 }
126
127 mousex = mousey = 0;
128 while (read(handle, buffer, sizeof(buffer))==sizeof(buffer)) {
129 mouseb = buffer[0] & 7;
130 mousex += (char) buffer[1];
131 mousey += (char) buffer[2];
132
133 /* Mouse button events */
134 if (buttonEvents && (mouseb != prev_mouseb)) {
135 int i;
136
137 for (i=0;i<3;i++) {
138 int curbutton, prevbutton;
139
140 curbutton = mouseb & (1<<i);
141 prevbutton = prev_mouseb & (1<<i);
142
143 if (curbutton && !prevbutton) {
144 SDL_PrivateMouseButton(SDL_RELEASED, atari_GetButton(i), 0, 0);
145 }
146 if (!curbutton && prevbutton) {
147 SDL_PrivateMouseButton(SDL_PRESSED, atari_GetButton(i), 0, 0);
148 }
149 }
150
151 prev_mouseb = mouseb;
152 }
153 }
154
155 /* Mouse motion event */
156 if (mousex || mousey) {
157 SDL_PrivateMouseMotion(0, 1, mousex, -mousey);
158 }
159}
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_ataridevmouse_c.h b/apps/plugins/sdl/src/video/ataricommon/SDL_ataridevmouse_c.h
deleted file mode 100644
index 7cae0222e0..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_ataridevmouse_c.h
+++ /dev/null
@@ -1,42 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 MiNT /dev/mouse driver
26
27 Patrice Mandin
28*/
29
30#ifndef _SDL_ATARI_DEVMOUSE_H_
31#define _SDL_ATARI_DEVMOUSE_H_
32
33#include "../SDL_sysvideo.h"
34
35/* Hidden "this" pointer for the video functions */
36#define _THIS SDL_VideoDevice *this
37
38extern int SDL_AtariDevMouse_Open(void);
39extern void SDL_AtariDevMouse_Close(void);
40extern void SDL_AtariDevMouse_PostMouseEvents(_THIS, SDL_bool buttonEvents);
41
42#endif /* _SDL_ATARI_DEVMOUSE_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarieddi.S b/apps/plugins/sdl/src/video/ataricommon/SDL_atarieddi.S
deleted file mode 100644
index d8cbf48f2b..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarieddi.S
+++ /dev/null
@@ -1,42 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/*
24 * Read EdDI version
25 *
26 * Patrice Mandin
27 */
28
29 .text
30
31 .globl _Atari_get_EdDI_version
32
33/*--- Vector installer ---*/
34
35_Atari_get_EdDI_version:
36 movel sp@(4),a0 /* Value of EdDI cookie */
37
38 /* Call EdDI function #0 */
39 clrw d0
40 jsr (a0)
41
42 rts
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarieddi_s.h b/apps/plugins/sdl/src/video/ataricommon/SDL_atarieddi_s.h
deleted file mode 100644
index cd3e524663..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarieddi_s.h
+++ /dev/null
@@ -1,54 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_Atari_eddi_s_h
25#define _SDL_Atari_eddi_s_h
26
27/*--- Defines ---*/
28
29/* EdDI versions */
30
31#define EDDI_10 (0x0100)
32#define EDDI_11 (0x0110)
33
34/* Screen format */
35
36enum {
37 VDI_FORMAT_UNKNOWN=-1,
38 VDI_FORMAT_INTER=0, /* Interleaved bitplanes */
39 VDI_FORMAT_VDI=1, /* VDI independent */
40 VDI_FORMAT_PACK=2 /* Packed pixels */
41};
42
43/* CLUT types */
44enum {
45 VDI_CLUT_NONE=0, /* Monochrome mode */
46 VDI_CLUT_HARDWARE, /* <256 colours mode */
47 VDI_CLUT_SOFTWARE /* True colour mode */
48};
49
50/*--- Functions ---*/
51
52unsigned long Atari_get_EdDI_version(void *function_pointer);
53
54#endif /* _SDL_Atari_eddi_s_h */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarievents.c b/apps/plugins/sdl/src/video/ataricommon/SDL_atarievents.c
deleted file mode 100644
index 8831275306..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarievents.c
+++ /dev/null
@@ -1,234 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Atari keyboard events manager
26 *
27 * Patrice Mandin
28 *
29 * This routines choose what the final event manager will be
30 */
31
32#include <mint/cookie.h>
33#include <mint/osbind.h>
34
35#include "../../events/SDL_sysevents.h"
36#include "../../events/SDL_events_c.h"
37
38#include "SDL_atarikeys.h"
39#include "SDL_atarievents_c.h"
40#include "SDL_biosevents_c.h"
41#include "SDL_gemdosevents_c.h"
42#include "SDL_ikbdevents_c.h"
43
44enum {
45 MCH_ST=0,
46 MCH_STE,
47 MCH_TT,
48 MCH_F30,
49 MCH_CLONE,
50 MCH_ARANYM
51};
52
53/* The translation tables from a console scancode to a SDL keysym */
54static SDLKey keymap[ATARIBIOS_MAXKEYS];
55static char *keytab_normal;
56
57void (*Atari_ShutdownEvents)(void);
58
59static void Atari_InitializeEvents(_THIS)
60{
61 const char *envr;
62 long cookie_mch;
63
64 /* Test if we are on an Atari machine or not */
65 if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) {
66 cookie_mch = 0;
67 }
68 cookie_mch >>= 16;
69
70 /* Default is Ikbd, the faster except for clones */
71 switch(cookie_mch) {
72 case MCH_ST:
73 case MCH_STE:
74 case MCH_TT:
75 case MCH_F30:
76 case MCH_ARANYM:
77 this->InitOSKeymap=AtariIkbd_InitOSKeymap;
78 this->PumpEvents=AtariIkbd_PumpEvents;
79 Atari_ShutdownEvents=AtariIkbd_ShutdownEvents;
80 break;
81 default:
82 this->InitOSKeymap=AtariGemdos_InitOSKeymap;
83 this->PumpEvents=AtariGemdos_PumpEvents;
84 Atari_ShutdownEvents=AtariGemdos_ShutdownEvents;
85 break;
86 }
87
88 envr = SDL_getenv("SDL_ATARI_EVENTSDRIVER");
89
90 if (!envr) {
91 return;
92 }
93
94 if (SDL_strcmp(envr, "ikbd") == 0) {
95 this->InitOSKeymap=AtariIkbd_InitOSKeymap;
96 this->PumpEvents=AtariIkbd_PumpEvents;
97 Atari_ShutdownEvents=AtariIkbd_ShutdownEvents;
98 }
99
100 if (SDL_strcmp(envr, "gemdos") == 0) {
101 this->InitOSKeymap=AtariGemdos_InitOSKeymap;
102 this->PumpEvents=AtariGemdos_PumpEvents;
103 Atari_ShutdownEvents=AtariGemdos_ShutdownEvents;
104 }
105
106 if (SDL_strcmp(envr, "bios") == 0) {
107 this->InitOSKeymap=AtariBios_InitOSKeymap;
108 this->PumpEvents=AtariBios_PumpEvents;
109 Atari_ShutdownEvents=AtariBios_ShutdownEvents;
110 }
111}
112
113void Atari_InitOSKeymap(_THIS)
114{
115 Atari_InitializeEvents(this);
116
117 SDL_Atari_InitInternalKeymap(this);
118
119 /* Call choosen routine */
120 this->InitOSKeymap(this);
121}
122
123void SDL_Atari_InitInternalKeymap(_THIS)
124{
125 int i;
126 _KEYTAB *key_tables;
127
128 /* Read system tables for scancode -> ascii translation */
129 key_tables = (_KEYTAB *) Keytbl(KT_NOCHANGE, KT_NOCHANGE, KT_NOCHANGE);
130 keytab_normal = key_tables->unshift;
131
132 /* Initialize keymap */
133 for ( i=0; i<ATARIBIOS_MAXKEYS; i++ )
134 keymap[i] = SDLK_UNKNOWN;
135
136 /* Functions keys */
137 for ( i = 0; i<10; i++ )
138 keymap[SCANCODE_F1 + i] = SDLK_F1+i;
139
140 /* Cursor keypad */
141 keymap[SCANCODE_HELP] = SDLK_HELP;
142 keymap[SCANCODE_UNDO] = SDLK_UNDO;
143 keymap[SCANCODE_INSERT] = SDLK_INSERT;
144 keymap[SCANCODE_CLRHOME] = SDLK_HOME;
145 keymap[SCANCODE_UP] = SDLK_UP;
146 keymap[SCANCODE_DOWN] = SDLK_DOWN;
147 keymap[SCANCODE_RIGHT] = SDLK_RIGHT;
148 keymap[SCANCODE_LEFT] = SDLK_LEFT;
149
150 /* Special keys */
151 keymap[SCANCODE_ESCAPE] = SDLK_ESCAPE;
152 keymap[SCANCODE_BACKSPACE] = SDLK_BACKSPACE;
153 keymap[SCANCODE_TAB] = SDLK_TAB;
154 keymap[SCANCODE_ENTER] = SDLK_RETURN;
155 keymap[SCANCODE_DELETE] = SDLK_DELETE;
156 keymap[SCANCODE_LEFTCONTROL] = SDLK_LCTRL;
157 keymap[SCANCODE_LEFTSHIFT] = SDLK_LSHIFT;
158 keymap[SCANCODE_RIGHTSHIFT] = SDLK_RSHIFT;
159 keymap[SCANCODE_LEFTALT] = SDLK_LALT;
160 keymap[SCANCODE_CAPSLOCK] = SDLK_CAPSLOCK;
161}
162
163void Atari_PumpEvents(_THIS)
164{
165 Atari_InitializeEvents(this);
166
167 /* Call choosen routine */
168 this->PumpEvents(this);
169}
170
171/* Atari to Unicode charset translation table */
172
173Uint16 SDL_AtariToUnicodeTable[256]={
174 /* Standard ASCII characters from 0x00 to 0x7e */
175 /* Unicode stuff from 0x7f to 0xff */
176
177 0x0000,0x0001,0x0002,0x0003,0x0004,0x0005,0x0006,0x0007,
178 0x0008,0x0009,0x000A,0x000B,0x000C,0x000D,0x000E,0x000F,
179 0x0010,0x0011,0x0012,0x0013,0x0014,0x0015,0x0016,0x0017,
180 0x0018,0x0019,0x001A,0x001B,0x001C,0x001D,0x001E,0x001F,
181 0x0020,0x0021,0x0022,0x0023,0x0024,0x0025,0x0026,0x0027,
182 0x0028,0x0029,0x002A,0x002B,0x002C,0x002D,0x002E,0x002F,
183 0x0030,0x0031,0x0032,0x0033,0x0034,0x0035,0x0036,0x0037,
184 0x0038,0x0039,0x003A,0x003B,0x003C,0x003D,0x003E,0x003F,
185
186 0x0040,0x0041,0x0042,0x0043,0x0044,0x0045,0x0046,0x0047,
187 0x0048,0x0049,0x004A,0x004B,0x004C,0x004D,0x004E,0x004F,
188 0x0050,0x0051,0x0052,0x0053,0x0054,0x0055,0x0056,0x0057,
189 0x0058,0x0059,0x005A,0x005B,0x005C,0x005D,0x005E,0x005F,
190 0x0060,0x0061,0x0062,0x0063,0x0064,0x0065,0x0066,0x0067,
191 0x0068,0x0069,0x006A,0x006B,0x006C,0x006D,0x006E,0x006F,
192 0x0070,0x0071,0x0072,0x0073,0x0074,0x0075,0x0076,0x0077,
193 0x0078,0x0079,0x007A,0x007B,0x007C,0x007D,0x007E,0x0394,
194
195 0x00C7,0x00FC,0x00E9,0x00E2,0x00E4,0x00E0,0x00E5,0x00E7,
196 0x00EA,0x00EB,0x00E8,0x00EF,0x00EE,0x00EC,0x00C4,0x00C5,
197 0x00C9,0x00E6,0x00C6,0x00F4,0x00F6,0x00F2,0x00FB,0x00F9,
198 0x00FF,0x00D6,0x00DC,0x00A2,0x00A3,0x00A5,0x00DF,0x0192,
199 0x00E1,0x00ED,0x00F3,0x00FA,0x00F1,0x00D1,0x00AA,0x00BA,
200 0x00BF,0x2310,0x00AC,0x00BD,0x00BC,0x00A1,0x00AB,0x00BB,
201 0x00C3,0x00F5,0x00D8,0x00F8,0x0153,0x0152,0x00C0,0x00C3,
202 0x00D5,0x00A8,0x00B4,0x2020,0x00B6,0x00A9,0x00AE,0x2122,
203
204 0x0133,0x0132,0x05D0,0x05D1,0x05D2,0x05D3,0x05D4,0x05D5,
205 0x05D6,0x05D7,0x05D8,0x05D9,0x05DB,0x05DC,0x05DE,0x05E0,
206 0x05E1,0x05E2,0x05E4,0x05E6,0x05E7,0x05E8,0x05E9,0x05EA,
207 0x05DF,0x05DA,0x05DD,0x05E3,0x05E5,0x00A7,0x2038,0x221E,
208 0x03B1,0x03B2,0x0393,0x03C0,0x03A3,0x03C3,0x00B5,0x03C4,
209 0x03A6,0x0398,0x03A9,0x03B4,0x222E,0x03C6,0x2208,0x2229,
210 0x2261,0x00B1,0x2265,0x2264,0x2320,0x2321,0x00F7,0x2248,
211 0x00B0,0x2022,0x00B7,0x221A,0x207F,0x00B2,0x00B3,0x00AF
212};
213
214SDL_keysym *SDL_Atari_TranslateKey(int scancode, SDL_keysym *keysym,
215 SDL_bool pressed)
216{
217 int asciicode = 0;
218
219 /* Set the keysym information */
220 keysym->scancode = scancode;
221 keysym->mod = KMOD_NONE;
222 keysym->sym = keymap[scancode];
223 keysym->unicode = 0;
224
225 if (keysym->sym == SDLK_UNKNOWN) {
226 keysym->sym = asciicode = keytab_normal[scancode];
227 }
228
229 if (SDL_TranslateUNICODE && pressed) {
230 keysym->unicode = SDL_AtariToUnicodeTable[asciicode];
231 }
232
233 return(keysym);
234}
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarievents_c.h b/apps/plugins/sdl/src/video/ataricommon/SDL_atarievents_c.h
deleted file mode 100644
index a7dd882454..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarievents_c.h
+++ /dev/null
@@ -1,52 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Atari keyboard events manager
26 *
27 * Patrice Mandin
28 */
29
30#ifndef _SDL_ATARI_EVENTS_H_
31#define _SDL_ATARI_EVENTS_H_
32
33#include "../SDL_sysvideo.h"
34
35/* Hidden "this" pointer for the video functions */
36#define _THIS SDL_VideoDevice *this
37
38#define ATARIBIOS_MAXKEYS 128
39
40extern void (*Atari_ShutdownEvents)(void);
41
42extern void Atari_InitOSKeymap(_THIS);
43extern void Atari_PumpEvents(_THIS);
44
45extern void SDL_Atari_InitInternalKeymap(_THIS);
46
47/* Atari to Unicode charset translation table */
48extern Uint16 SDL_AtariToUnicodeTable[256];
49SDL_keysym *SDL_Atari_TranslateKey(int scancode, SDL_keysym *keysym,
50 SDL_bool pressed);
51
52#endif /* _SDL_ATARI_EVENTS_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarigl.c b/apps/plugins/sdl/src/video/ataricommon/SDL_atarigl.c
deleted file mode 100644
index 1cf2689c95..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarigl.c
+++ /dev/null
@@ -1,1086 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Atari OSMesa.ldg implementation of SDL OpenGL support */
25
26/*--- Includes ---*/
27
28#if SDL_VIDEO_OPENGL
29#include <GL/osmesa.h>
30#endif
31
32#include <mint/osbind.h>
33
34#include "SDL_endian.h"
35#include "SDL_video.h"
36#include "SDL_atarigl_c.h"
37#if SDL_VIDEO_OPENGL_OSMESA_DYNAMIC
38#include "SDL_loadso.h"
39#endif
40
41/*--- Defines ---*/
42
43#define PATH_OSMESA_LDG "osmesa.ldg"
44#define PATH_MESAGL_LDG "mesa_gl.ldg"
45#define PATH_TINYGL_LDG "tiny_gl.ldg"
46
47#define VDI_RGB 0xf
48
49/*--- Functions prototypes ---*/
50
51#if SDL_VIDEO_OPENGL
52static void SDL_AtariGL_UnloadLibrary(_THIS);
53
54static void CopyShadowNull(_THIS, SDL_Surface *surface);
55static void CopyShadowDirect(_THIS, SDL_Surface *surface);
56static void CopyShadowRGBTo555(_THIS, SDL_Surface *surface);
57static void CopyShadowRGBTo565(_THIS, SDL_Surface *surface);
58static void CopyShadowRGBSwap(_THIS, SDL_Surface *surface);
59static void CopyShadowRGBToARGB(_THIS, SDL_Surface *surface);
60static void CopyShadowRGBToABGR(_THIS, SDL_Surface *surface);
61static void CopyShadowRGBToBGRA(_THIS, SDL_Surface *surface);
62static void CopyShadowRGBToRGBA(_THIS, SDL_Surface *surface);
63static void CopyShadow8888To555(_THIS, SDL_Surface *surface);
64static void CopyShadow8888To565(_THIS, SDL_Surface *surface);
65
66static void ConvertNull(_THIS, SDL_Surface *surface);
67static void Convert565To555be(_THIS, SDL_Surface *surface);
68static void Convert565To555le(_THIS, SDL_Surface *surface);
69static void Convert565le(_THIS, SDL_Surface *surface);
70static void ConvertBGRAToABGR(_THIS, SDL_Surface *surface);
71
72static int InitNew(_THIS, SDL_Surface *current);
73static int InitOld(_THIS, SDL_Surface *current);
74#endif
75
76/*--- Public functions ---*/
77
78int SDL_AtariGL_Init(_THIS, SDL_Surface *current)
79{
80#if SDL_VIDEO_OPENGL
81 if (gl_oldmesa) {
82 gl_active = InitOld(this, current);
83 } else {
84 gl_active = InitNew(this, current);
85 }
86#endif
87
88 return (gl_active);
89}
90
91void SDL_AtariGL_Quit(_THIS, SDL_bool unload)
92{
93#if SDL_VIDEO_OPENGL
94 if (gl_oldmesa) {
95 /* Old mesa implementations */
96 if (this->gl_data->OSMesaDestroyLDG) {
97 this->gl_data->OSMesaDestroyLDG();
98 }
99 if (gl_shadow) {
100 Mfree(gl_shadow);
101 gl_shadow = NULL;
102 }
103 } else {
104 /* New mesa implementation */
105 if (gl_ctx) {
106 if (this->gl_data->OSMesaDestroyContext) {
107 this->gl_data->OSMesaDestroyContext(gl_ctx);
108 }
109 gl_ctx = NULL;
110 }
111 }
112
113 if (unload) {
114 SDL_AtariGL_UnloadLibrary(this);
115 }
116
117#endif /* SDL_VIDEO_OPENGL */
118 gl_active = 0;
119}
120
121int SDL_AtariGL_LoadLibrary(_THIS, const char *path)
122{
123#if SDL_VIDEO_OPENGL
124
125#if SDL_VIDEO_OPENGL_OSMESA_DYNAMIC
126 void *handle;
127 SDL_bool cancel_load;
128
129 if (gl_active) {
130 SDL_SetError("OpenGL context already created");
131 return -1;
132 }
133
134 /* Unload previous driver */
135 SDL_AtariGL_UnloadLibrary(this);
136
137 /* Load library given by path */
138 handle = SDL_LoadObject(path);
139 if (handle == NULL) {
140 /* Try to load another one */
141 path = SDL_getenv("SDL_VIDEO_GL_DRIVER");
142 if ( path != NULL ) {
143 handle = SDL_LoadObject(path);
144 }
145
146 /* If it does not work, try some other */
147 if (handle == NULL) {
148 path = PATH_OSMESA_LDG;
149 handle = SDL_LoadObject(path);
150 }
151
152 if (handle == NULL) {
153 path = PATH_MESAGL_LDG;
154 handle = SDL_LoadObject(path);
155 }
156
157 if (handle == NULL) {
158 path = PATH_TINYGL_LDG;
159 handle = SDL_LoadObject(path);
160 }
161 }
162
163 if (handle == NULL) {
164 SDL_SetError("Could not load OpenGL library");
165 return -1;
166 }
167
168 this->gl_data->glGetIntegerv = SDL_LoadFunction(handle, "glGetIntegerv");
169 this->gl_data->glFinish = SDL_LoadFunction(handle, "glFinish");
170 this->gl_data->glFlush = SDL_LoadFunction(handle, "glFlush");
171
172 cancel_load = SDL_FALSE;
173 if (this->gl_data->glGetIntegerv == NULL) {
174 cancel_load = SDL_TRUE;
175 } else {
176 /* We need either glFinish (OSMesa) or glFlush (TinyGL) */
177 if ((this->gl_data->glFinish == NULL) &&
178 (this->gl_data->glFlush == NULL)) {
179 cancel_load = SDL_TRUE;
180 }
181 }
182 if (cancel_load) {
183 SDL_SetError("Could not retrieve OpenGL functions");
184 SDL_UnloadObject(handle);
185 /* Restore pointers to static library */
186 SDL_AtariGL_InitPointers(this);
187 return -1;
188 }
189
190 /* Load functions pointers (osmesa.ldg) */
191 this->gl_data->OSMesaCreateContextExt = SDL_LoadFunction(handle, "OSMesaCreateContextExt");
192 this->gl_data->OSMesaDestroyContext = SDL_LoadFunction(handle, "OSMesaDestroyContext");
193 this->gl_data->OSMesaMakeCurrent = SDL_LoadFunction(handle, "OSMesaMakeCurrent");
194 this->gl_data->OSMesaPixelStore = SDL_LoadFunction(handle, "OSMesaPixelStore");
195 this->gl_data->OSMesaGetProcAddress = SDL_LoadFunction(handle, "OSMesaGetProcAddress");
196
197 /* Load old functions pointers (mesa_gl.ldg, tiny_gl.ldg) */
198 this->gl_data->OSMesaCreateLDG = SDL_LoadFunction(handle, "OSMesaCreateLDG");
199 this->gl_data->OSMesaDestroyLDG = SDL_LoadFunction(handle, "OSMesaDestroyLDG");
200
201 gl_oldmesa = 0;
202
203 if ( (this->gl_data->OSMesaCreateContextExt == NULL) ||
204 (this->gl_data->OSMesaDestroyContext == NULL) ||
205 (this->gl_data->OSMesaMakeCurrent == NULL) ||
206 (this->gl_data->OSMesaPixelStore == NULL) ||
207 (this->gl_data->OSMesaGetProcAddress == NULL)) {
208 /* Hum, maybe old library ? */
209 if ( (this->gl_data->OSMesaCreateLDG == NULL) ||
210 (this->gl_data->OSMesaDestroyLDG == NULL)) {
211 SDL_SetError("Could not retrieve OSMesa functions");
212 SDL_UnloadObject(handle);
213 /* Restore pointers to static library */
214 SDL_AtariGL_InitPointers(this);
215 return -1;
216 } else {
217 gl_oldmesa = 1;
218 }
219 }
220
221 this->gl_config.dll_handle = handle;
222 if ( path ) {
223 SDL_strlcpy(this->gl_config.driver_path, path,
224 SDL_arraysize(this->gl_config.driver_path));
225 } else {
226 *this->gl_config.driver_path = '\0';
227 }
228
229#endif
230 this->gl_config.driver_loaded = 1;
231
232 return 0;
233#else
234 return -1;
235#endif
236}
237
238void *SDL_AtariGL_GetProcAddress(_THIS, const char *proc)
239{
240 void *func = NULL;
241#if SDL_VIDEO_OPENGL
242
243 if (this->gl_config.dll_handle) {
244 func = SDL_LoadFunction(this->gl_config.dll_handle, (void *)proc);
245 } else if (this->gl_data->OSMesaGetProcAddress) {
246 func = this->gl_data->OSMesaGetProcAddress(proc);
247 }
248
249#endif
250 return func;
251}
252
253int SDL_AtariGL_GetAttribute(_THIS, SDL_GLattr attrib, int* value)
254{
255#if SDL_VIDEO_OPENGL
256 GLenum mesa_attrib;
257 SDL_Surface *surface;
258
259 if (!gl_active) {
260 return -1;
261 }
262
263 switch(attrib) {
264 case SDL_GL_RED_SIZE:
265 mesa_attrib = GL_RED_BITS;
266 break;
267 case SDL_GL_GREEN_SIZE:
268 mesa_attrib = GL_GREEN_BITS;
269 break;
270 case SDL_GL_BLUE_SIZE:
271 mesa_attrib = GL_BLUE_BITS;
272 break;
273 case SDL_GL_ALPHA_SIZE:
274 mesa_attrib = GL_ALPHA_BITS;
275 break;
276 case SDL_GL_DOUBLEBUFFER:
277 surface = this->screen;
278 *value = ((surface->flags & SDL_DOUBLEBUF)==SDL_DOUBLEBUF);
279 return 0;
280 case SDL_GL_DEPTH_SIZE:
281 mesa_attrib = GL_DEPTH_BITS;
282 break;
283 case SDL_GL_STENCIL_SIZE:
284 mesa_attrib = GL_STENCIL_BITS;
285 break;
286 case SDL_GL_ACCUM_RED_SIZE:
287 mesa_attrib = GL_ACCUM_RED_BITS;
288 break;
289 case SDL_GL_ACCUM_GREEN_SIZE:
290 mesa_attrib = GL_ACCUM_GREEN_BITS;
291 break;
292 case SDL_GL_ACCUM_BLUE_SIZE:
293 mesa_attrib = GL_ACCUM_BLUE_BITS;
294 break;
295 case SDL_GL_ACCUM_ALPHA_SIZE:
296 mesa_attrib = GL_ACCUM_ALPHA_BITS;
297 break;
298 default :
299 return -1;
300 }
301
302 this->gl_data->glGetIntegerv(mesa_attrib, value);
303 return 0;
304#else
305 return -1;
306#endif
307}
308
309int SDL_AtariGL_MakeCurrent(_THIS)
310{
311#if SDL_VIDEO_OPENGL
312 SDL_Surface *surface;
313 GLenum type;
314
315 if (gl_oldmesa && gl_active) {
316 return 0;
317 }
318
319 if (this->gl_config.dll_handle) {
320 if ((this->gl_data->OSMesaMakeCurrent == NULL) ||
321 (this->gl_data->OSMesaPixelStore == NULL)) {
322 return -1;
323 }
324 }
325
326 if (!gl_active) {
327 SDL_SetError("Invalid OpenGL context");
328 return -1;
329 }
330
331 surface = this->screen;
332
333 if ((surface->format->BitsPerPixel == 15) || (surface->format->BitsPerPixel == 16)) {
334 type = GL_UNSIGNED_SHORT_5_6_5;
335 } else {
336 type = GL_UNSIGNED_BYTE;
337 }
338
339 if (!(this->gl_data->OSMesaMakeCurrent(gl_ctx, surface->pixels, type, surface->w, surface->h))) {
340 SDL_SetError("Can not make OpenGL context current");
341 return -1;
342 }
343
344 /* OSMesa draws upside down */
345 this->gl_data->OSMesaPixelStore(OSMESA_Y_UP, 0);
346
347 return 0;
348#else
349 return -1;
350#endif
351}
352
353void SDL_AtariGL_SwapBuffers(_THIS)
354{
355#if SDL_VIDEO_OPENGL
356 if (gl_active) {
357 if (this->gl_config.dll_handle) {
358 if (this->gl_data->glFinish) {
359 this->gl_data->glFinish();
360 } else if (this->gl_data->glFlush) {
361 this->gl_data->glFlush();
362 }
363 } else {
364 this->gl_data->glFinish();
365 }
366 gl_copyshadow(this, this->screen);
367 gl_convert(this, this->screen);
368 }
369#endif
370}
371
372void SDL_AtariGL_InitPointers(_THIS)
373{
374#if SDL_VIDEO_OPENGL
375 this->gl_data->OSMesaCreateContextExt = OSMesaCreateContextExt;
376 this->gl_data->OSMesaDestroyContext = OSMesaDestroyContext;
377 this->gl_data->OSMesaMakeCurrent = OSMesaMakeCurrent;
378 this->gl_data->OSMesaPixelStore = OSMesaPixelStore;
379 this->gl_data->OSMesaGetProcAddress = OSMesaGetProcAddress;
380
381 this->gl_data->glGetIntegerv = glGetIntegerv;
382 this->gl_data->glFinish = glFinish;
383 this->gl_data->glFlush = glFlush;
384
385 this->gl_data->OSMesaCreateLDG = NULL;
386 this->gl_data->OSMesaDestroyLDG = NULL;
387#endif
388}
389
390/*--- Private functions ---*/
391
392#if SDL_VIDEO_OPENGL
393static void SDL_AtariGL_UnloadLibrary(_THIS)
394{
395 if (this->gl_config.dll_handle) {
396 SDL_UnloadObject(this->gl_config.dll_handle);
397 this->gl_config.dll_handle = NULL;
398
399 /* Restore pointers to static library */
400 SDL_AtariGL_InitPointers(this);
401 }
402}
403
404/*--- Creation of an OpenGL context using new/old functions ---*/
405
406static int InitNew(_THIS, SDL_Surface *current)
407{
408 GLenum osmesa_format;
409 SDL_PixelFormat *pixel_format;
410 Uint32 redmask;
411 int recreatecontext;
412 GLint newaccumsize;
413
414 if (this->gl_config.dll_handle) {
415 if (this->gl_data->OSMesaCreateContextExt == NULL) {
416 return 0;
417 }
418 }
419
420 /* Init OpenGL context using OSMesa */
421 gl_convert = ConvertNull;
422 gl_copyshadow = CopyShadowNull;
423 gl_upsidedown = SDL_FALSE;
424
425 pixel_format = current->format;
426 redmask = pixel_format->Rmask;
427 switch (pixel_format->BitsPerPixel) {
428 case 15:
429 /* 1555, big and little endian, unsupported */
430 gl_pixelsize = 2;
431 osmesa_format = OSMESA_RGB_565;
432 if (redmask == 31<<10) {
433 gl_convert = Convert565To555be;
434 } else {
435 gl_convert = Convert565To555le;
436 }
437 break;
438 case 16:
439 gl_pixelsize = 2;
440 if (redmask == 31<<11) {
441 osmesa_format = OSMESA_RGB_565;
442 } else {
443 /* 565, little endian, unsupported */
444 osmesa_format = OSMESA_RGB_565;
445 gl_convert = Convert565le;
446 }
447 break;
448 case 24:
449 gl_pixelsize = 3;
450 if (redmask == 255<<16) {
451 osmesa_format = OSMESA_RGB;
452 } else {
453 osmesa_format = OSMESA_BGR;
454 }
455 break;
456 case 32:
457 gl_pixelsize = 4;
458 if (redmask == 255<<16) {
459 osmesa_format = OSMESA_ARGB;
460 } else if (redmask == 255<<8) {
461 osmesa_format = OSMESA_BGRA;
462 } else if (redmask == 255<<24) {
463 osmesa_format = OSMESA_RGBA;
464 } else {
465 /* ABGR format unsupported */
466 osmesa_format = OSMESA_BGRA;
467 gl_convert = ConvertBGRAToABGR;
468 }
469 break;
470 default:
471 gl_pixelsize = 1;
472 osmesa_format = OSMESA_COLOR_INDEX;
473 break;
474 }
475
476 /* Try to keep current context if possible */
477 newaccumsize =
478 this->gl_config.accum_red_size +
479 this->gl_config.accum_green_size +
480 this->gl_config.accum_blue_size +
481 this->gl_config.accum_alpha_size;
482 recreatecontext=1;
483 if (gl_ctx &&
484 (gl_curformat == osmesa_format) &&
485 (gl_curdepth == this->gl_config.depth_size) &&
486 (gl_curstencil == this->gl_config.stencil_size) &&
487 (gl_curaccum == newaccumsize)) {
488 recreatecontext = 0;
489 }
490 if (recreatecontext) {
491 SDL_AtariGL_Quit(this, SDL_FALSE);
492
493 gl_ctx = this->gl_data->OSMesaCreateContextExt(
494 osmesa_format, this->gl_config.depth_size,
495 this->gl_config.stencil_size, newaccumsize, NULL );
496
497 if (gl_ctx) {
498 gl_curformat = osmesa_format;
499 gl_curdepth = this->gl_config.depth_size;
500 gl_curstencil = this->gl_config.stencil_size;
501 gl_curaccum = newaccumsize;
502 } else {
503 gl_curformat = 0;
504 gl_curdepth = 0;
505 gl_curstencil = 0;
506 gl_curaccum = 0;
507 }
508 }
509
510 return (gl_ctx != NULL);
511}
512
513
514static int InitOld(_THIS, SDL_Surface *current)
515{
516 GLenum osmesa_format;
517 SDL_PixelFormat *pixel_format;
518 Uint32 redmask;
519 int recreatecontext, tinygl_present;
520
521 if (this->gl_config.dll_handle) {
522 if (this->gl_data->OSMesaCreateLDG == NULL) {
523 return 0;
524 }
525 }
526
527 /* TinyGL only supports VDI_RGB (OSMESA_RGB) */
528 tinygl_present=0;
529 if (this->gl_config.dll_handle) {
530 if (this->gl_data->glFinish == NULL) {
531 tinygl_present=1;
532 }
533 }
534
535 /* Init OpenGL context using OSMesa */
536 gl_convert = ConvertNull;
537 gl_copyshadow = CopyShadowNull;
538 gl_upsidedown = SDL_FALSE;
539
540 pixel_format = current->format;
541 redmask = pixel_format->Rmask;
542 switch (pixel_format->BitsPerPixel) {
543 case 15:
544 /* 15 bits unsupported */
545 if (tinygl_present) {
546 gl_pixelsize = 3;
547 osmesa_format = VDI_RGB;
548 if (redmask == 31<<10) {
549 gl_copyshadow = CopyShadowRGBTo555;
550 } else {
551 gl_copyshadow = CopyShadowRGBTo565;
552 gl_convert = Convert565To555le;
553 }
554 } else {
555 gl_pixelsize = 4;
556 gl_upsidedown = SDL_TRUE;
557 osmesa_format = OSMESA_ARGB;
558 if (redmask == 31<<10) {
559 gl_copyshadow = CopyShadow8888To555;
560 } else {
561 gl_copyshadow = CopyShadow8888To565;
562 gl_convert = Convert565To555le;
563 }
564 }
565 break;
566 case 16:
567 /* 16 bits unsupported */
568 if (tinygl_present) {
569 gl_pixelsize = 3;
570 osmesa_format = VDI_RGB;
571 gl_copyshadow = CopyShadowRGBTo565;
572 if (redmask != 31<<11) {
573 /* 565, little endian, unsupported */
574 gl_convert = Convert565le;
575 }
576 } else {
577 gl_pixelsize = 4;
578 gl_upsidedown = SDL_TRUE;
579 osmesa_format = OSMESA_ARGB;
580 gl_copyshadow = CopyShadow8888To565;
581 if (redmask != 31<<11) {
582 /* 565, little endian, unsupported */
583 gl_convert = Convert565le;
584 }
585 }
586 break;
587 case 24:
588 gl_pixelsize = 3;
589 if (tinygl_present) {
590 osmesa_format = VDI_RGB;
591 gl_copyshadow = CopyShadowDirect;
592 if (redmask != 255<<16) {
593 gl_copyshadow = CopyShadowRGBSwap;
594 }
595 } else {
596 gl_copyshadow = CopyShadowDirect;
597 gl_upsidedown = SDL_TRUE;
598 if (redmask == 255<<16) {
599 osmesa_format = OSMESA_RGB;
600 } else {
601 osmesa_format = OSMESA_BGR;
602 }
603 }
604 break;
605 case 32:
606 if (tinygl_present) {
607 gl_pixelsize = 3;
608 osmesa_format = VDI_RGB;
609 gl_copyshadow = CopyShadowRGBToARGB;
610 if (redmask == 255) {
611 gl_convert = CopyShadowRGBToABGR;
612 } else if (redmask == 255<<8) {
613 gl_convert = CopyShadowRGBToBGRA;
614 } else if (redmask == 255<<24) {
615 gl_convert = CopyShadowRGBToRGBA;
616 }
617 } else {
618 gl_pixelsize = 4;
619 gl_upsidedown = SDL_TRUE;
620 gl_copyshadow = CopyShadowDirect;
621 if (redmask == 255<<16) {
622 osmesa_format = OSMESA_ARGB;
623 } else if (redmask == 255<<8) {
624 osmesa_format = OSMESA_BGRA;
625 } else if (redmask == 255<<24) {
626 osmesa_format = OSMESA_RGBA;
627 } else {
628 /* ABGR format unsupported */
629 osmesa_format = OSMESA_BGRA;
630 gl_convert = ConvertBGRAToABGR;
631 }
632 }
633 break;
634 default:
635 if (tinygl_present) {
636 SDL_AtariGL_Quit(this, SDL_FALSE);
637 return 0;
638 }
639 gl_pixelsize = 1;
640 gl_copyshadow = CopyShadowDirect;
641 osmesa_format = OSMESA_COLOR_INDEX;
642 break;
643 }
644
645 /* Try to keep current context if possible */
646 recreatecontext=1;
647 if (gl_shadow &&
648 (gl_curformat == osmesa_format) &&
649 (gl_curwidth == current->w) &&
650 (gl_curheight == current->h)) {
651 recreatecontext = 0;
652 }
653 if (recreatecontext) {
654 SDL_AtariGL_Quit(this, SDL_FALSE);
655
656 gl_shadow = this->gl_data->OSMesaCreateLDG(
657 osmesa_format, GL_UNSIGNED_BYTE, current->w, current->h
658 );
659
660 if (gl_shadow) {
661 gl_curformat = osmesa_format;
662 gl_curwidth = current->w;
663 gl_curheight = current->h;
664 } else {
665 gl_curformat = 0;
666 gl_curwidth = 0;
667 gl_curheight = 0;
668 }
669 }
670
671 return (gl_shadow != NULL);
672}
673
674/*--- Conversions routines from shadow buffer to the screen ---*/
675
676static void CopyShadowNull(_THIS, SDL_Surface *surface)
677{
678}
679
680static void CopyShadowDirect(_THIS, SDL_Surface *surface)
681{
682 int y, srcpitch, dstpitch;
683 Uint8 *srcline, *dstline;
684
685 srcline = gl_shadow;
686 srcpitch = surface->w * gl_pixelsize;
687 dstline = surface->pixels;
688 dstpitch = surface->pitch;
689 if (gl_upsidedown) {
690 srcline += (surface->h-1)*srcpitch;
691 srcpitch = -srcpitch;
692 }
693
694 for (y=0; y<surface->h; y++) {
695 SDL_memcpy(dstline, srcline, srcpitch);
696
697 srcline += srcpitch;
698 dstline += dstpitch;
699 }
700}
701
702static void CopyShadowRGBTo555(_THIS, SDL_Surface *surface)
703{
704 int x,y, srcpitch, dstpitch;
705 Uint16 *dstline, *dstcol;
706 Uint8 *srcline, *srccol;
707
708 srcline = (Uint8 *)gl_shadow;
709 srcpitch = surface->w * gl_pixelsize;
710 dstline = surface->pixels;
711 dstpitch = surface->pitch >>1;
712 if (gl_upsidedown) {
713 srcline += (surface->h-1)*srcpitch;
714 srcpitch = -srcpitch;
715 }
716
717 for (y=0; y<surface->h; y++) {
718 srccol = srcline;
719 dstcol = dstline;
720 for (x=0; x<surface->w; x++) {
721 Uint16 dstcolor;
722
723 dstcolor = ((*srccol++)<<7) & (31<<10);
724 dstcolor |= ((*srccol++)<<2) & (31<<5);
725 dstcolor |= ((*srccol++)>>3) & 31;
726 *dstcol++ = dstcolor;
727 }
728
729 srcline += srcpitch;
730 dstline += dstpitch;
731 }
732}
733
734static void CopyShadowRGBTo565(_THIS, SDL_Surface *surface)
735{
736 int x,y, srcpitch, dstpitch;
737 Uint16 *dstline, *dstcol;
738 Uint8 *srcline, *srccol;
739
740 srcline = (Uint8 *)gl_shadow;
741 srcpitch = surface->w * gl_pixelsize;
742 dstline = surface->pixels;
743 dstpitch = surface->pitch >>1;
744 if (gl_upsidedown) {
745 srcline += (surface->h-1)*srcpitch;
746 srcpitch = -srcpitch;
747 }
748
749 for (y=0; y<surface->h; y++) {
750 srccol = srcline;
751 dstcol = dstline;
752
753 for (x=0; x<surface->w; x++) {
754 Uint16 dstcolor;
755
756 dstcolor = ((*srccol++)<<8) & (31<<11);
757 dstcolor |= ((*srccol++)<<3) & (63<<5);
758 dstcolor |= ((*srccol++)>>3) & 31;
759 *dstcol++ = dstcolor;
760 }
761
762 srcline += srcpitch;
763 dstline += dstpitch;
764 }
765}
766
767static void CopyShadowRGBSwap(_THIS, SDL_Surface *surface)
768{
769 int x,y, srcpitch, dstpitch;
770 Uint8 *dstline, *dstcol;
771 Uint8 *srcline, *srccol;
772
773 srcline = (Uint8 *)gl_shadow;
774 srcpitch = surface->w * gl_pixelsize;
775 dstline = surface->pixels;
776 dstpitch = surface->pitch;
777 if (gl_upsidedown) {
778 srcline += (surface->h-1)*srcpitch;
779 srcpitch = -srcpitch;
780 }
781
782 for (y=0; y<surface->h; y++) {
783 srccol = srcline;
784 dstcol = dstline;
785
786 for (x=0; x<surface->w; x++) {
787 *dstcol++ = srccol[2];
788 *dstcol++ = srccol[1];
789 *dstcol++ = srccol[0];
790 srccol += 3;
791 }
792
793 srcline += srcpitch;
794 dstline += dstpitch;
795 }
796}
797
798static void CopyShadowRGBToARGB(_THIS, SDL_Surface *surface)
799{
800 int x,y, srcpitch, dstpitch;
801 Uint32 *dstline, *dstcol;
802 Uint8 *srcline, *srccol;
803
804 srcline = (Uint8 *)gl_shadow;
805 srcpitch = surface->w * gl_pixelsize;
806 dstline = surface->pixels;
807 dstpitch = surface->pitch >>2;
808 if (gl_upsidedown) {
809 srcline += (surface->h-1)*srcpitch;
810 srcpitch = -srcpitch;
811 }
812
813 for (y=0; y<surface->h; y++) {
814 srccol = srcline;
815 dstcol = dstline;
816
817 for (x=0; x<surface->w; x++) {
818 Uint32 dstcolor;
819
820 dstcolor = (*srccol++)<<16;
821 dstcolor |= (*srccol++)<<8;
822 dstcolor |= *srccol++;
823
824 *dstcol++ = dstcolor;
825 }
826
827 srcline += srcpitch;
828 dstline += dstpitch;
829 }
830}
831
832static void CopyShadowRGBToABGR(_THIS, SDL_Surface *surface)
833{
834 int x,y, srcpitch, dstpitch;
835 Uint32 *dstline, *dstcol;
836 Uint8 *srcline, *srccol;
837
838 srcline = (Uint8 *)gl_shadow;
839 srcpitch = surface->w * gl_pixelsize;
840 dstline = surface->pixels;
841 dstpitch = surface->pitch >>2;
842 if (gl_upsidedown) {
843 srcline += (surface->h-1)*srcpitch;
844 srcpitch = -srcpitch;
845 }
846
847 for (y=0; y<surface->h; y++) {
848 srccol = srcline;
849 dstcol = dstline;
850
851 for (x=0; x<surface->w; x++) {
852 Uint32 dstcolor;
853
854 dstcolor = *srccol++;
855 dstcolor |= (*srccol++)<<8;
856 dstcolor |= (*srccol++)<<16;
857
858 *dstcol++ = dstcolor;
859 }
860
861 srcline += srcpitch;
862 dstline += dstpitch;
863 }
864}
865
866static void CopyShadowRGBToBGRA(_THIS, SDL_Surface *surface)
867{
868 int x,y, srcpitch, dstpitch;
869 Uint32 *dstline, *dstcol;
870 Uint8 *srcline, *srccol;
871
872 srcline = (Uint8 *)gl_shadow;
873 srcpitch = surface->w * gl_pixelsize;
874 dstline = surface->pixels;
875 dstpitch = surface->pitch >>2;
876 if (gl_upsidedown) {
877 srcline += (surface->h-1)*srcpitch;
878 srcpitch = -srcpitch;
879 }
880
881 for (y=0; y<surface->h; y++) {
882 srccol = srcline;
883 dstcol = dstline;
884
885 for (x=0; x<surface->w; x++) {
886 Uint32 dstcolor;
887
888 dstcolor = (*srccol++)<<8;
889 dstcolor |= (*srccol++)<<16;
890 dstcolor |= (*srccol++)<<24;
891
892 *dstcol++ = dstcolor;
893 }
894
895 srcline += srcpitch;
896 dstline += dstpitch;
897 }
898}
899
900static void CopyShadowRGBToRGBA(_THIS, SDL_Surface *surface)
901{
902 int x,y, srcpitch, dstpitch;
903 Uint32 *dstline, *dstcol;
904 Uint8 *srcline, *srccol;
905
906 srcline = (Uint8 *)gl_shadow;
907 srcpitch = surface->w * gl_pixelsize;
908 dstline = surface->pixels;
909 dstpitch = surface->pitch >>2;
910 if (gl_upsidedown) {
911 srcline += (surface->h-1)*srcpitch;
912 srcpitch = -srcpitch;
913 }
914
915 for (y=0; y<surface->h; y++) {
916 srccol = srcline;
917 dstcol = dstline;
918
919 for (x=0; x<surface->w; x++) {
920 Uint32 dstcolor;
921
922 dstcolor = (*srccol++)<<24;
923 dstcolor |= (*srccol++)<<16;
924 dstcolor |= (*srccol++)<<8;
925
926 *dstcol++ = dstcolor;
927 }
928
929 srcline += srcpitch;
930 dstline += dstpitch;
931 }
932}
933
934static void CopyShadow8888To555(_THIS, SDL_Surface *surface)
935{
936 int x,y, srcpitch, dstpitch;
937 Uint16 *dstline, *dstcol;
938 Uint32 *srcline, *srccol;
939
940 srcline = (Uint32 *)gl_shadow;
941 srcpitch = (surface->w * gl_pixelsize) >>2;
942 dstline = surface->pixels;
943 dstpitch = surface->pitch >>1;
944 if (gl_upsidedown) {
945 srcline += (surface->h-1)*srcpitch;
946 srcpitch = -srcpitch;
947 }
948
949 for (y=0; y<surface->h; y++) {
950 srccol = srcline;
951 dstcol = dstline;
952 for (x=0; x<surface->w; x++) {
953 Uint32 srccolor;
954 Uint16 dstcolor;
955
956 srccolor = *srccol++;
957 dstcolor = (srccolor>>9) & (31<<10);
958 dstcolor |= (srccolor>>6) & (31<<5);
959 dstcolor |= (srccolor>>3) & 31;
960 *dstcol++ = dstcolor;
961 }
962
963 srcline += srcpitch;
964 dstline += dstpitch;
965 }
966}
967
968static void CopyShadow8888To565(_THIS, SDL_Surface *surface)
969{
970 int x,y, srcpitch, dstpitch;
971 Uint16 *dstline, *dstcol;
972 Uint32 *srcline, *srccol;
973
974 srcline = (Uint32 *)gl_shadow;
975 srcpitch = (surface->w * gl_pixelsize) >> 2;
976 dstline = surface->pixels;
977 dstpitch = surface->pitch >>1;
978 if (gl_upsidedown) {
979 srcline += (surface->h-1)*srcpitch;
980 srcpitch = -srcpitch;
981 }
982
983 for (y=0; y<surface->h; y++) {
984 srccol = srcline;
985 dstcol = dstline;
986
987 for (x=0; x<surface->w; x++) {
988 Uint32 srccolor;
989 Uint16 dstcolor;
990
991 srccolor = *srccol++;
992 dstcolor = (srccolor>>8) & (31<<11);
993 dstcolor |= (srccolor>>5) & (63<<5);
994 dstcolor |= (srccolor>>3) & 31;
995 *dstcol++ = dstcolor;
996 }
997
998 srcline += srcpitch;
999 dstline += dstpitch;
1000 }
1001}
1002
1003/*--- Conversions routines in the screen ---*/
1004
1005static void ConvertNull(_THIS, SDL_Surface *surface)
1006{
1007}
1008
1009static void Convert565To555be(_THIS, SDL_Surface *surface)
1010{
1011 int x,y, pitch;
1012 unsigned short *line, *pixel;
1013
1014 line = surface->pixels;
1015 pitch = surface->pitch >> 1;
1016 for (y=0; y<surface->h; y++) {
1017 pixel = line;
1018 for (x=0; x<surface->w; x++) {
1019 unsigned short color = *pixel;
1020
1021 *pixel++ = (color & 0x1f)|((color>>1) & 0xffe0);
1022 }
1023
1024 line += pitch;
1025 }
1026}
1027
1028static void Convert565To555le(_THIS, SDL_Surface *surface)
1029{
1030 int x,y, pitch;
1031 unsigned short *line, *pixel;
1032
1033 line = surface->pixels;
1034 pitch = surface->pitch >>1;
1035 for (y=0; y<surface->h; y++) {
1036 pixel = line;
1037 for (x=0; x<surface->w; x++) {
1038 unsigned short color = *pixel;
1039
1040 color = (color & 0x1f)|((color>>1) & 0xffe0);
1041 *pixel++ = SDL_Swap16(color);
1042 }
1043
1044 line += pitch;
1045 }
1046}
1047
1048static void Convert565le(_THIS, SDL_Surface *surface)
1049{
1050 int x,y, pitch;
1051 unsigned short *line, *pixel;
1052
1053 line = surface->pixels;
1054 pitch = surface->pitch >>1;
1055 for (y=0; y<surface->h; y++) {
1056 pixel = line;
1057 for (x=0; x<surface->w; x++) {
1058 unsigned short color = *pixel;
1059
1060 *pixel++ = SDL_Swap16(color);
1061 }
1062
1063 line += pitch;
1064 }
1065}
1066
1067static void ConvertBGRAToABGR(_THIS, SDL_Surface *surface)
1068{
1069 int x,y, pitch;
1070 unsigned long *line, *pixel;
1071
1072 line = surface->pixels;
1073 pitch = surface->pitch >>2;
1074 for (y=0; y<surface->h; y++) {
1075 pixel = line;
1076 for (x=0; x<surface->w; x++) {
1077 unsigned long color = *pixel;
1078
1079 *pixel++ = (color<<24)|(color>>8);
1080 }
1081
1082 line += pitch;
1083 }
1084}
1085
1086#endif /* SDL_VIDEO_OPENGL */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarigl_c.h b/apps/plugins/sdl/src/video/ataricommon/SDL_atarigl_c.h
deleted file mode 100644
index 5adcf2a251..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarigl_c.h
+++ /dev/null
@@ -1,109 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Atari OSMesa.ldg implementation of SDL OpenGL support */
25
26#ifndef _SDL_ATARIGL_H_
27#define _SDL_ATARIGL_H_
28
29#if SDL_VIDEO_OPENGL
30#include <GL/osmesa.h>
31#endif
32
33#include "../SDL_sysvideo.h"
34
35/* Hidden "this" pointer for the video functions */
36#define _THIS SDL_VideoDevice *this
37
38struct SDL_PrivateGLData {
39
40 int gl_active; /* to stop switching drivers while we have a valid context */
41
42 int gl_oldmesa; /* Old OpenGL support ? */
43
44 int gl_pixelsize; /* for CopyShadow functions */
45
46 SDL_bool gl_upsidedown; /* Some implementations draw upside down */
47
48 Uint8 *gl_shadow; /* Shadow buffer for old implementations */
49
50 /* for unsupported OSMesa buffer formats */
51 void (*ConvertSurface)(_THIS, SDL_Surface *surface);
52
53 /* to convert the shadow buffer to the screen format */
54 void (*CopyShadow)(_THIS, SDL_Surface *surface);
55
56#if SDL_VIDEO_OPENGL
57 OSMesaContext ctx;
58
59 /* OpenGL functions */
60 void (*glGetIntegerv)( GLenum pname, GLint *value );
61 void (*glFinish)(void);
62 void (*glFlush)(void);
63
64 /* osmesa.ldg */
65 OSMesaContext (*OSMesaCreateContextExt)( GLenum format, GLint depthBits, GLint stencilBits, GLint accumBits, OSMesaContext sharelist);
66 void (*OSMesaDestroyContext)( OSMesaContext ctx );
67 GLboolean (*OSMesaMakeCurrent)( OSMesaContext ctx, void *buffer, GLenum type, GLsizei width, GLsizei height );
68 void (*OSMesaPixelStore)( GLint pname, GLint value );
69 void * (*OSMesaGetProcAddress)( const char *funcName );
70
71 /* mesa_gl.ldg, tiny_gl.ldg */
72 void *(*OSMesaCreateLDG)( long format, long type, long width, long height );
73 void (*OSMesaDestroyLDG)(void);
74
75 /* Info needed to compare existing context with new asked one */
76 int width, height;
77 GLenum format;
78 GLint depth,stencil,accum;
79#endif
80};
81
82/* Variable names */
83#define gl_active (this->gl_data->gl_active)
84#define gl_ctx (this->gl_data->ctx)
85#define gl_oldmesa (this->gl_data->gl_oldmesa)
86#define gl_pixelsize (this->gl_data->gl_pixelsize)
87#define gl_upsidedown (this->gl_data->gl_upsidedown)
88#define gl_shadow (this->gl_data->gl_shadow)
89#define gl_convert (this->gl_data->ConvertSurface)
90#define gl_copyshadow (this->gl_data->CopyShadow)
91#define gl_curformat (this->gl_data->format)
92#define gl_curdepth (this->gl_data->depth)
93#define gl_curstencil (this->gl_data->stencil)
94#define gl_curaccum (this->gl_data->accum)
95#define gl_curwidth (this->gl_data->width)
96#define gl_curheight (this->gl_data->height)
97
98/* OpenGL functions */
99extern int SDL_AtariGL_Init(_THIS, SDL_Surface *current);
100extern void SDL_AtariGL_Quit(_THIS, SDL_bool unload);
101extern void SDL_AtariGL_InitPointers(_THIS);
102
103extern int SDL_AtariGL_LoadLibrary(_THIS, const char *path);
104extern void *SDL_AtariGL_GetProcAddress(_THIS, const char *proc);
105extern int SDL_AtariGL_GetAttribute(_THIS, SDL_GLattr attrib, int* value);
106extern int SDL_AtariGL_MakeCurrent(_THIS);
107extern void SDL_AtariGL_SwapBuffers(_THIS);
108
109#endif /* _SDL_ATARIGL_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarikeys.h b/apps/plugins/sdl/src/video/ataricommon/SDL_atarikeys.h
deleted file mode 100644
index a9f7cfd41b..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarikeys.h
+++ /dev/null
@@ -1,140 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/*
24 * Atari Scancode definitions
25 *
26 * Patrice Mandin
27 */
28
29#ifndef _SDL_ATARIKEYS_H_
30#define _SDL_ATARIKEYS_H_
31
32/* --- Keyboard scancodes --- */
33/* taken from svgalib/vgakeyboard.h */
34
35#define SCANCODE_ESCAPE 0x01
36#define SCANCODE_1 0x02
37#define SCANCODE_2 0x03
38#define SCANCODE_3 0x04
39#define SCANCODE_4 0x05
40#define SCANCODE_5 0x06
41#define SCANCODE_6 0x07
42#define SCANCODE_7 0x08
43#define SCANCODE_8 0x09
44#define SCANCODE_9 0x0a
45#define SCANCODE_0 0x0b
46#define SCANCODE_MINUS 0x0c
47#define SCANCODE_EQUAL 0x0d
48#define SCANCODE_BACKSPACE 0x0e
49
50#define SCANCODE_TAB 0x0f
51#define SCANCODE_Q 0x10
52#define SCANCODE_W 0x11
53#define SCANCODE_E 0x12
54#define SCANCODE_R 0x13
55#define SCANCODE_T 0x14
56#define SCANCODE_Y 0x15
57#define SCANCODE_U 0x16
58#define SCANCODE_I 0x17
59#define SCANCODE_O 0x18
60#define SCANCODE_P 0x19
61#define SCANCODE_BRACKET_LEFT 0x1a
62#define SCANCODE_BRACKET_RIGHT 0x1b
63#define SCANCODE_ENTER 0x1c
64#define SCANCODE_DELETE 0x53
65
66#define SCANCODE_LEFTCONTROL 0x1d
67#define SCANCODE_A 0x1e
68#define SCANCODE_S 0x1f
69#define SCANCODE_D 0x20
70#define SCANCODE_F 0x21
71#define SCANCODE_G 0x22
72#define SCANCODE_H 0x23
73#define SCANCODE_J 0x24
74#define SCANCODE_K 0x25
75#define SCANCODE_L 0x26
76#define SCANCODE_SEMICOLON 0x27
77#define SCANCODE_APOSTROPHE 0x28
78#define SCANCODE_GRAVE 0x29
79
80#define SCANCODE_LEFTSHIFT 0x2a
81#define SCANCODE_BACKSLASH 0x2b
82#define SCANCODE_Z 0x2c
83#define SCANCODE_X 0x2d
84#define SCANCODE_C 0x2e
85#define SCANCODE_V 0x2f
86#define SCANCODE_B 0x30
87#define SCANCODE_N 0x31
88#define SCANCODE_M 0x32
89#define SCANCODE_COMMA 0x33
90#define SCANCODE_PERIOD 0x34
91#define SCANCODE_SLASH 0x35
92#define SCANCODE_RIGHTSHIFT 0x36
93
94#define SCANCODE_LEFTALT 0x38
95#define SCANCODE_SPACE 0x39
96#define SCANCODE_CAPSLOCK 0x3a
97
98/* Functions keys */
99#define SCANCODE_F1 0x3b
100#define SCANCODE_F2 0x3c
101#define SCANCODE_F3 0x3d
102#define SCANCODE_F4 0x3e
103#define SCANCODE_F5 0x3f
104#define SCANCODE_F6 0x40
105#define SCANCODE_F7 0x41
106#define SCANCODE_F8 0x42
107#define SCANCODE_F9 0x43
108#define SCANCODE_F10 0x44
109
110/* Numeric keypad */
111#define SCANCODE_KP0 0x70
112#define SCANCODE_KP1 0x6d
113#define SCANCODE_KP2 0x6e
114#define SCANCODE_KP3 0x6f
115#define SCANCODE_KP4 0x6a
116#define SCANCODE_KP5 0x6b
117#define SCANCODE_KP6 0x6c
118#define SCANCODE_KP7 0x67
119#define SCANCODE_KP8 0x68
120#define SCANCODE_KP9 0x69
121#define SCANCODE_KP_PERIOD 0x71
122#define SCANCODE_KP_DIVIDE 0x65
123#define SCANCODE_KP_MULTIPLY 0x66
124#define SCANCODE_KP_MINUS 0x4a
125#define SCANCODE_KP_PLUS 0x4e
126#define SCANCODE_KP_ENTER 0x72
127#define SCANCODE_KP_LEFTPAREN 0x63
128#define SCANCODE_KP_RIGHTPAREN 0x64
129
130/* Cursor keypad */
131#define SCANCODE_HELP 0x62
132#define SCANCODE_UNDO 0x61
133#define SCANCODE_INSERT 0x52
134#define SCANCODE_CLRHOME 0x47
135#define SCANCODE_UP 0x48
136#define SCANCODE_DOWN 0x50
137#define SCANCODE_RIGHT 0x4d
138#define SCANCODE_LEFT 0x4b
139
140#endif /* _SDL_ATARIKEYS_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarimxalloc.c b/apps/plugins/sdl/src/video/ataricommon/SDL_atarimxalloc.c
deleted file mode 100644
index 224baef308..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarimxalloc.c
+++ /dev/null
@@ -1,52 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Memory allocation
26 *
27 * Patrice Mandin
28 */
29
30#include <mint/osbind.h>
31
32#include "SDL_stdinc.h"
33
34/*--- Variables ---*/
35
36static int atari_mxalloc_avail=-1;
37
38/*--- Functions ---*/
39
40void *Atari_SysMalloc(Uint32 size, Uint16 alloc_type)
41{
42 /* Test if Mxalloc() available */
43 if (atari_mxalloc_avail<0) {
44 atari_mxalloc_avail = ((Sversion()&0xFF)>=0x01) | (Sversion()>=0x1900);
45 }
46
47 if (atari_mxalloc_avail) {
48 return (void *) Mxalloc(size, alloc_type);
49 } else {
50 return (void *) Malloc(size);
51 }
52}
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarimxalloc_c.h b/apps/plugins/sdl/src/video/ataricommon/SDL_atarimxalloc_c.h
deleted file mode 100644
index 937408d0c5..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarimxalloc_c.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Memory allocation
26 *
27 * Patrice Mandin
28 */
29
30#ifndef _SDL_ATARI_MXALLOC_H_
31#define _SDL_ATARI_MXALLOC_H_
32
33/*--- Functions ---*/
34
35extern void *Atari_SysMalloc(Uint32 size, Uint16 alloc_type);
36
37#endif /* _SDL_ATARI_MXALLOC_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_atarisuper.h b/apps/plugins/sdl/src/video/ataricommon/SDL_atarisuper.h
deleted file mode 100644
index 8f25c7e5f4..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_atarisuper.h
+++ /dev/null
@@ -1,61 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _ATARI_SUPER_h
25#define _ATARI_SUPER_h
26
27#include "SDL_stdinc.h"
28
29#ifndef SuperToUser
30
31/*
32 * Safe binding to switch back from supervisor to user mode.
33 * On TOS or EmuTOS, if the stack pointer has changed between Super(0)
34 * and Super(oldssp), the resulting user stack pointer is wrong.
35 * This bug does not occur with FreeMiNT.
36 * So the safe way to return from supervisor to user mode is to backup
37 * the stack pointer then restore it after the trap.
38 * Sometimes, GCC optimizes the stack usage, so this matters.
39 */
40#define SuperToUser(ptr) \
41(void)__extension__ \
42({ \
43 register long retvalue __asm__("d0"); \
44 register long sp_backup; \
45 \
46 __asm__ volatile \
47 ( \
48 "movl sp,%1\n\t" \
49 "movl %2,sp@-\n\t" \
50 "movw #0x20,sp@-\n\t" \
51 "trap #1\n\t" \
52 "movl %1,sp\n\t" \
53 : "=r"(retvalue), "=&r"(sp_backup) /* outputs */ \
54 : "g"((long)(ptr)) /* inputs */ \
55 : "d1", "d2", "a0", "a1", "a2" \
56 ); \
57})
58
59#endif /* SuperToUser */
60
61#endif /* _ATARI_SUPER_h */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_biosevents.c b/apps/plugins/sdl/src/video/ataricommon/SDL_biosevents.c
deleted file mode 100644
index 3d36b2b5d9..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_biosevents.c
+++ /dev/null
@@ -1,131 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Atari keyboard events manager, using BIOS
26 *
27 * Patrice Mandin
28 */
29
30/* Mint includes */
31#include <mint/osbind.h>
32#include <mint/cookie.h>
33
34#include "../../events/SDL_sysevents.h"
35#include "../../events/SDL_events_c.h"
36
37#include "SDL_atarikeys.h"
38#include "SDL_atarievents_c.h"
39#include "SDL_xbiosevents_c.h"
40#include "SDL_ataridevmouse_c.h"
41
42static unsigned char bios_currentkeyboard[ATARIBIOS_MAXKEYS];
43static unsigned char bios_previouskeyboard[ATARIBIOS_MAXKEYS];
44static SDL_bool use_dev_mouse = SDL_FALSE;
45
46static void UpdateSpecialKeys(int special_keys_state);
47
48void AtariBios_InitOSKeymap(_THIS)
49{
50 int vectors_mask;
51/* unsigned long dummy;*/
52
53 SDL_memset(bios_currentkeyboard, 0, sizeof(bios_currentkeyboard));
54 SDL_memset(bios_previouskeyboard, 0, sizeof(bios_previouskeyboard));
55
56 use_dev_mouse = (SDL_AtariDevMouse_Open()!=0) ? SDL_TRUE : SDL_FALSE;
57
58 vectors_mask = ATARI_XBIOS_JOYSTICKEVENTS; /* XBIOS joystick events */
59 if (!use_dev_mouse) {
60 vectors_mask |= ATARI_XBIOS_MOUSEEVENTS; /* XBIOS mouse events */
61 }
62/* if (Getcookie(C_MiNT, &dummy)==C_FOUND) {
63 vectors_mask = 0;
64 }*/
65
66 SDL_AtariXbios_InstallVectors(vectors_mask);
67}
68
69void AtariBios_PumpEvents(_THIS)
70{
71 int i;
72 SDL_keysym keysym;
73
74 /* Update pressed keys */
75 SDL_memset(bios_currentkeyboard, 0, ATARIBIOS_MAXKEYS);
76
77 while (Bconstat(_CON)) {
78 unsigned long key_pressed;
79 key_pressed=Bconin(_CON);
80 bios_currentkeyboard[(key_pressed>>16)&(ATARIBIOS_MAXKEYS-1)]=0xFF;
81 }
82
83 /* Read special keys */
84 UpdateSpecialKeys(Kbshift(-1));
85
86 /* Now generate events */
87 for (i=0; i<ATARIBIOS_MAXKEYS; i++) {
88 /* Key pressed ? */
89 if (bios_currentkeyboard[i] && !bios_previouskeyboard[i])
90 SDL_PrivateKeyboard(SDL_PRESSED,
91 SDL_Atari_TranslateKey(i, &keysym, SDL_TRUE));
92
93 /* Key unpressed ? */
94 if (bios_previouskeyboard[i] && !bios_currentkeyboard[i])
95 SDL_PrivateKeyboard(SDL_RELEASED,
96 SDL_Atari_TranslateKey(i, &keysym, SDL_FALSE));
97 }
98
99 if (use_dev_mouse) {
100 SDL_AtariDevMouse_PostMouseEvents(this, SDL_TRUE);
101 } else {
102 SDL_AtariXbios_PostMouseEvents(this, SDL_TRUE);
103 }
104
105 /* Will be previous table */
106 SDL_memcpy(bios_previouskeyboard, bios_currentkeyboard, sizeof(bios_previouskeyboard));
107}
108
109static void UpdateSpecialKeys(int special_keys_state)
110{
111#define UPDATE_SPECIAL_KEYS(numbit,scancode) \
112 { \
113 if (special_keys_state & (1<<(numbit))) { \
114 bios_currentkeyboard[scancode]=0xFF; \
115 } \
116 }
117
118 UPDATE_SPECIAL_KEYS(K_RSHIFT, SCANCODE_RIGHTSHIFT);
119 UPDATE_SPECIAL_KEYS(K_LSHIFT, SCANCODE_LEFTSHIFT);
120 UPDATE_SPECIAL_KEYS(K_CTRL, SCANCODE_LEFTCONTROL);
121 UPDATE_SPECIAL_KEYS(K_ALT, SCANCODE_LEFTALT);
122 UPDATE_SPECIAL_KEYS(K_CAPSLOCK, SCANCODE_CAPSLOCK);
123}
124
125void AtariBios_ShutdownEvents(void)
126{
127 SDL_AtariXbios_RestoreVectors();
128 if (use_dev_mouse) {
129 SDL_AtariDevMouse_Close();
130 }
131}
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_biosevents_c.h b/apps/plugins/sdl/src/video/ataricommon/SDL_biosevents_c.h
deleted file mode 100644
index f016e6a65b..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_biosevents_c.h
+++ /dev/null
@@ -1,42 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Atari keyboard events manager, using BIOS
26 *
27 * Patrice Mandin
28 */
29
30#ifndef _SDL_ATARI_BIOSEVENTS_H_
31#define _SDL_ATARI_BIOSEVENTS_H_
32
33#include "../SDL_sysvideo.h"
34
35/* Hidden "this" pointer for the video functions */
36#define _THIS SDL_VideoDevice *this
37
38extern void AtariBios_InitOSKeymap(_THIS);
39extern void AtariBios_PumpEvents(_THIS);
40extern void AtariBios_ShutdownEvents(void);
41
42#endif /* _SDL_ATARI_BIOSEVENTS_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_gemdosevents.c b/apps/plugins/sdl/src/video/ataricommon/SDL_gemdosevents.c
deleted file mode 100644
index e1ebaa666c..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_gemdosevents.c
+++ /dev/null
@@ -1,132 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Atari keyboard events manager, using Gemdos
26 *
27 * Patrice Mandin
28 */
29
30/* Mint includes */
31#include <mint/osbind.h>
32#include <mint/cookie.h>
33
34#include "../../events/SDL_sysevents.h"
35#include "../../events/SDL_events_c.h"
36
37#include "SDL_atarikeys.h"
38#include "SDL_atarievents_c.h"
39#include "SDL_xbiosevents_c.h"
40#include "SDL_ataridevmouse_c.h"
41
42/* To save state of keyboard */
43
44static unsigned char gemdos_currentkeyboard[ATARIBIOS_MAXKEYS];
45static unsigned char gemdos_previouskeyboard[ATARIBIOS_MAXKEYS];
46static SDL_bool use_dev_mouse = SDL_FALSE;
47
48static void UpdateSpecialKeys(int special_keys_state);
49
50void AtariGemdos_InitOSKeymap(_THIS)
51{
52 int vectors_mask;
53/* unsigned long dummy;*/
54
55 SDL_memset(gemdos_currentkeyboard, 0, sizeof(gemdos_currentkeyboard));
56 SDL_memset(gemdos_previouskeyboard, 0, sizeof(gemdos_previouskeyboard));
57
58 use_dev_mouse = (SDL_AtariDevMouse_Open()!=0) ? SDL_TRUE : SDL_FALSE;
59
60 vectors_mask = ATARI_XBIOS_JOYSTICKEVENTS; /* XBIOS joystick events */
61 if (!use_dev_mouse) {
62 vectors_mask |= ATARI_XBIOS_MOUSEEVENTS; /* XBIOS mouse events */
63 }
64/* if (Getcookie(C_MiNT, &dummy)==C_FOUND) {
65 vectors_mask = 0;
66 }*/
67 SDL_AtariXbios_InstallVectors(vectors_mask);
68}
69
70void AtariGemdos_PumpEvents(_THIS)
71{
72 int i;
73 SDL_keysym keysym;
74
75 /* Update pressed keys */
76 SDL_memset(gemdos_currentkeyboard, 0, ATARIBIOS_MAXKEYS);
77
78 while (Cconis()!=DEV_BUSY) {
79 unsigned long key_pressed;
80 key_pressed=Cnecin();
81 gemdos_currentkeyboard[(key_pressed>>16)&(ATARIBIOS_MAXKEYS-1)]=0xFF;
82 }
83
84 /* Read special keys */
85 UpdateSpecialKeys(Kbshift(-1));
86
87 /* Now generate events */
88 for (i=0; i<ATARIBIOS_MAXKEYS; i++) {
89 /* Key pressed ? */
90 if (gemdos_currentkeyboard[i] && !gemdos_previouskeyboard[i])
91 SDL_PrivateKeyboard(SDL_PRESSED,
92 SDL_Atari_TranslateKey(i, &keysym, SDL_TRUE));
93
94 /* Key unpressed ? */
95 if (gemdos_previouskeyboard[i] && !gemdos_currentkeyboard[i])
96 SDL_PrivateKeyboard(SDL_RELEASED,
97 SDL_Atari_TranslateKey(i, &keysym, SDL_FALSE));
98 }
99
100 if (use_dev_mouse) {
101 SDL_AtariDevMouse_PostMouseEvents(this, SDL_TRUE);
102 } else {
103 SDL_AtariXbios_PostMouseEvents(this, SDL_TRUE);
104 }
105
106 /* Will be previous table */
107 SDL_memcpy(gemdos_previouskeyboard, gemdos_currentkeyboard, sizeof(gemdos_previouskeyboard));
108}
109
110static void UpdateSpecialKeys(int special_keys_state)
111{
112#define UPDATE_SPECIAL_KEYS(numbit,scancode) \
113 { \
114 if (special_keys_state & (1<<(numbit))) { \
115 gemdos_currentkeyboard[scancode]=0xFF; \
116 } \
117 }
118
119 UPDATE_SPECIAL_KEYS(K_RSHIFT, SCANCODE_RIGHTSHIFT);
120 UPDATE_SPECIAL_KEYS(K_LSHIFT, SCANCODE_LEFTSHIFT);
121 UPDATE_SPECIAL_KEYS(K_CTRL, SCANCODE_LEFTCONTROL);
122 UPDATE_SPECIAL_KEYS(K_ALT, SCANCODE_LEFTALT);
123 UPDATE_SPECIAL_KEYS(K_CAPSLOCK, SCANCODE_CAPSLOCK);
124}
125
126void AtariGemdos_ShutdownEvents(void)
127{
128 SDL_AtariXbios_RestoreVectors();
129 if (use_dev_mouse) {
130 SDL_AtariDevMouse_Close();
131 }
132}
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_gemdosevents_c.h b/apps/plugins/sdl/src/video/ataricommon/SDL_gemdosevents_c.h
deleted file mode 100644
index b9924e63ab..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_gemdosevents_c.h
+++ /dev/null
@@ -1,42 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Atari keyboard events manager, using Gemdos
26 *
27 * Patrice Mandin
28 */
29
30#ifndef _SDL_ATARI_GEMDOSEVENTS_H_
31#define _SDL_ATARI_GEMDOSEVENTS_H_
32
33#include "../SDL_sysvideo.h"
34
35/* Hidden "this" pointer for the video functions */
36#define _THIS SDL_VideoDevice *this
37
38extern void AtariGemdos_InitOSKeymap(_THIS);
39extern void AtariGemdos_PumpEvents(_THIS);
40extern void AtariGemdos_ShutdownEvents(void);
41
42#endif /* _SDL_ATARI_GEMDOSEVENTS_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdevents.c b/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdevents.c
deleted file mode 100644
index 35fc5cb71a..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdevents.c
+++ /dev/null
@@ -1,124 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Atari keyboard events manager, using hardware IKBD
26 *
27 * Patrice Mandin
28 */
29
30/* Mint includes */
31#include <mint/osbind.h>
32
33#include "../../events/SDL_sysevents.h"
34#include "../../events/SDL_events_c.h"
35
36#include "SDL_atarikeys.h"
37#include "SDL_atarievents_c.h"
38#include "SDL_ikbdinterrupt_s.h"
39
40#define KEY_PRESSED 0xff
41#define KEY_UNDEFINED 0x80
42#define KEY_RELEASED 0x00
43
44static Uint16 atari_prevmouseb; /* save state of mouse buttons */
45
46void AtariIkbd_InitOSKeymap(_THIS)
47{
48 SDL_memset((void *) SDL_AtariIkbd_keyboard, KEY_UNDEFINED, sizeof(SDL_AtariIkbd_keyboard));
49
50 /* Now install our handler */
51 SDL_AtariIkbd_mouseb = SDL_AtariIkbd_mousex = SDL_AtariIkbd_mousey = 0;
52 atari_prevmouseb = 0;
53
54 Supexec(SDL_AtariIkbdInstall);
55}
56
57static int atari_GetButton(int button)
58{
59 switch(button)
60 {
61 case 0:
62 return SDL_BUTTON_RIGHT;
63 break;
64 case 1:
65 default:
66 return SDL_BUTTON_LEFT;
67 break;
68 }
69}
70
71void AtariIkbd_PumpEvents(_THIS)
72{
73 int i;
74 SDL_keysym keysym;
75
76 /*--- Send keyboard events ---*/
77
78 for (i=0; i<ATARIBIOS_MAXKEYS; i++) {
79 /* Key pressed ? */
80 if (SDL_AtariIkbd_keyboard[i]==KEY_PRESSED) {
81 SDL_PrivateKeyboard(SDL_PRESSED,
82 SDL_Atari_TranslateKey(i, &keysym, SDL_TRUE));
83 SDL_AtariIkbd_keyboard[i]=KEY_UNDEFINED;
84 }
85
86 /* Key released ? */
87 if (SDL_AtariIkbd_keyboard[i]==KEY_RELEASED) {
88 SDL_PrivateKeyboard(SDL_RELEASED,
89 SDL_Atari_TranslateKey(i, &keysym, SDL_FALSE));
90 SDL_AtariIkbd_keyboard[i]=KEY_UNDEFINED;
91 }
92 }
93
94 /*--- Send mouse events ---*/
95
96 /* Mouse motion ? */
97 if (SDL_AtariIkbd_mousex || SDL_AtariIkbd_mousey) {
98 SDL_PrivateMouseMotion(0, 1, SDL_AtariIkbd_mousex, SDL_AtariIkbd_mousey);
99 SDL_AtariIkbd_mousex = SDL_AtariIkbd_mousey = 0;
100 }
101
102 /* Mouse button ? */
103 if (SDL_AtariIkbd_mouseb != atari_prevmouseb) {
104 for (i=0;i<2;i++) {
105 int curbutton, prevbutton;
106
107 curbutton = SDL_AtariIkbd_mouseb & (1<<i);
108 prevbutton = atari_prevmouseb & (1<<i);
109
110 if (curbutton && !prevbutton) {
111 SDL_PrivateMouseButton(SDL_PRESSED, atari_GetButton(i), 0, 0);
112 }
113 if (!curbutton && prevbutton) {
114 SDL_PrivateMouseButton(SDL_RELEASED, atari_GetButton(i), 0, 0);
115 }
116 }
117 atari_prevmouseb = SDL_AtariIkbd_mouseb;
118 }
119}
120
121void AtariIkbd_ShutdownEvents(void)
122{
123 Supexec(SDL_AtariIkbdUninstall);
124}
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdevents_c.h b/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdevents_c.h
deleted file mode 100644
index 753e777de9..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdevents_c.h
+++ /dev/null
@@ -1,42 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Atari keyboard events manager, using hardware IKBD
26 *
27 * Patrice Mandin
28 */
29
30#ifndef _SDL_ATARI_IKBDEVENTS_H_
31#define _SDL_ATARI_IKBDEVENTS_H_
32
33#include "../SDL_sysvideo.h"
34
35/* Hidden "this" pointer for the video functions */
36#define _THIS SDL_VideoDevice *this
37
38extern void AtariIkbd_InitOSKeymap(_THIS);
39extern void AtariIkbd_PumpEvents(_THIS);
40extern void AtariIkbd_ShutdownEvents(void);
41
42#endif /* _SDL_ATARI_IKBDEVENTS_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdinterrupt.S b/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdinterrupt.S
deleted file mode 100644
index 21facc80a2..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdinterrupt.S
+++ /dev/null
@@ -1,404 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/*
24 * IKBD 6301 interrupt routine
25 *
26 * Patrice Mandin
27 */
28
29 .text
30
31 .globl _SDL_AtariIkbdInstall
32 .globl _SDL_AtariIkbdUninstall
33
34 .globl _SDL_AtariIkbd_keyboard
35 .globl _SDL_AtariIkbd_mouseb
36 .globl _SDL_AtariIkbd_mousex
37 .globl _SDL_AtariIkbd_mousey
38 .globl _SDL_AtariIkbd_joystick
39
40 .globl _SDL_AtariIkbd_enabled
41
42/*--- Install our IKBD vector ---*/
43
44_SDL_AtariIkbdInstall:
45#if defined(__mcoldfire__)
46 lea sp@(-16),sp
47 moveml d0-d1/a0-a1,sp@
48#else
49 moveml d0-d1/a0-a1,sp@-
50#endif
51
52 | Disable interrupts
53
54 movew #0x2700,sr
55
56 | Save MFP registers used for keyboard
57
58 lea 0xfffffa00:w,a0
59 btst #6,a0@(0x09)
60#if defined(__mcoldfire__)
61 sne d0
62 move.b d0,ikbd_ierb
63#else
64 sne ikbd_ierb
65#endif
66 btst #6,a0@(0x15)
67#if defined(__mcoldfire__)
68 sne d0
69 move.b d0,ikbd_imrb
70#else
71 sne ikbd_imrb
72#endif
73
74 | Set our routine
75
76#if defined(__mcoldfire__)
77 movel 0x118:w,d0
78 movel d0,old_ikbd
79 lea ikbd,a0
80 movel a0,0x118:w
81 moveql #6,d0
82 bset d0,0xfffffa09:w | IERB
83 bset d0,0xfffffa15:w | IMRB
84#else
85 movel 0x118:w,old_ikbd
86 movel #ikbd,0x118:w
87 bset #6,0xfffffa09:w | IERB
88 bset #6,0xfffffa15:w | IMRB
89#endif
90
91 | Set mouse relative mode
92
93#if defined(__mcoldfire__)
94 moveql #8,d0
95 moveb d0,0xfffffc02:w
96#else
97 moveb #8,0xfffffc02:w
98#endif
99
100 | Reenable interrupts
101
102 movew #0x2300,sr
103
104 | Interrupts done
105
106#if defined(__mcoldfire__)
107 movel #0xffff,d0
108 movew d0,_SDL_AtariIkbd_enabled
109
110 moveml sp@,d0-d1/a0-a1
111 lea sp@(16),sp
112#else
113 movew #0xffff,_SDL_AtariIkbd_enabled
114
115 moveml sp@+,d0-d1/a0-a1
116#endif
117 rts
118
119/*--- Uninstall our IKBD vector ---*/
120
121_SDL_AtariIkbdUninstall:
122 movel a0,sp@-
123
124 | Disable interrupts
125
126 movew #0x2700,sr
127
128 | Restore previous MFP registers
129
130 lea 0xfffffa00:w,a0
131
132 bclr #6,a0@(0x09)
133 tstb ikbd_ierb
134 beqs ikbd_restoreierb
135 bset #6,a0@(0x09)
136ikbd_restoreierb:
137
138 bclr #6,a0@(0x15)
139 tstb ikbd_imrb
140 beqs ikbd_restoreimrb
141 bset #6,a0@(0x15)
142ikbd_restoreimrb:
143
144#if defined(__mcoldfire__)
145 movel old_ikbd,a0
146 movel a0,0x118:w
147#else
148 movel old_ikbd,0x118:w
149#endif
150
151 | Clear keyboard buffer
152
153 lea 0xfffffc00:w,a0
154ikbd_videbuffer:
155 btst #0,a0@
156 beqs ikbd_finbuffer
157 tstb a0@(0x02)
158 bras ikbd_videbuffer
159ikbd_finbuffer:
160
161 | Reenable interrupts
162
163 movew #0x2300,sr
164
165 movel sp@+,a0
166 rts
167
168 .bss
169
170 .even
171 .comm ikbd_ierb,1
172 .comm ikbd_imrb,1
173
174/*--- Our custom IKBD vector ---*/
175
176 .text
177 .even
178 .ascii "XBRA"
179 .ascii "LSDL"
180 .comm old_ikbd,4*1
181ikbd:
182#if defined(__mcoldfire__)
183 lea sp@(-12),sp
184 moveml d0-d1/a0,sp@
185#else
186 moveml d0-d1/a0,sp@-
187#endif
188
189 | Check if source is IKBD or MIDI
190#if defined(__mcoldfire__)
191 moveql #0,d0
192 btst d0,0xfffffc00.w
193#else
194 btst #0,0xfffffc00.w
195#endif
196 beqs ikbd_oldmidi
197
198 moveb 0xfffffc02:w,d0
199
200 | Joystick packet ?
201
202 cmpb #0xff,d0
203 beqs ikbd_yes_joystick
204
205 | Mouse packet ?
206
207 cmpb #0xf8,d0
208 bmis ikbd_no_mouse
209 cmpb #0xfc,d0
210 bpls ikbd_no_mouse
211
212 | Mouse packet, byte #1
213
214ikbd_yes_mouse:
215#if defined(__mcoldfire__)
216 andl #3,d0
217#else
218 andw #3,d0
219#endif
220 movew d0,_SDL_AtariIkbd_mouseb
221
222#if defined(__mcoldfire__)
223 movel #ikbd_mousex,d0
224 movel d0,0x118:w
225#else
226 movel #ikbd_mousex,0x118:w
227#endif
228 bras ikbd_endit_stack
229
230 | Joystick packet, byte #1
231
232ikbd_yes_joystick:
233#if defined(__mcoldfire__)
234 movel #ikbd_joystick,d0
235 movel d0,0x118:w
236#else
237 movel #ikbd_joystick,0x118:w
238#endif
239 bras ikbd_endit_stack
240
241 | Keyboard press/release
242
243ikbd_no_mouse:
244 moveb d0,d1
245 lea _SDL_AtariIkbd_keyboard,a0
246#if defined(__mcoldfire__)
247 andl #0x7f,d1
248 btst #7,d0
249 spl d0
250 moveb d0,a0@(0,d1:l)
251#else
252 andw #0x7f,d1
253 tas d0
254 spl a0@(0,d1:w)
255#endif
256
257 | End of interrupt
258
259ikbd_endit_stack:
260#if defined(__mcoldfire__)
261 moveql #6,d0
262 bclr d0,0xfffffa11:w
263
264 moveml sp@,d0-d1/a0
265 lea sp@(12),sp
266#else
267 moveml sp@+,d0-d1/a0
268
269 bclr #6,0xfffffa11:w
270#endif
271 rte
272
273 | Call old MIDI interrupt
274
275ikbd_oldmidi:
276#if defined(__mcoldfire__)
277 moveml sp@,d0-d1/a0
278 lea sp@(12),sp
279#else
280 moveml sp@+,d0-d1/a0
281#endif
282
283 movel old_ikbd,sp@-
284 rts
285
286 | Mouse packet, byte #2
287
288ikbd_mousex:
289#if defined(__mcoldfire__)
290 lea sp@(-12),sp
291 moveml d0-d1/a0,sp@
292#else
293 moveml d0-d1/a0,sp@-
294#endif
295
296 | Check if source is IKBD or MIDI
297#if defined(__mcoldfire__)
298 moveql #0,d0
299 btst d0,0xfffffc00.w
300#else
301 btst #0,0xfffffc00.w
302#endif
303 beqs ikbd_oldmidi
304
305 moveb 0xfffffc02:w,d0
306 extw d0
307#if defined(__mcoldfire__)
308 movew _SDL_AtariIkbd_mousex,d1
309 addl d1,d0
310 movew d0,_SDL_AtariIkbd_mousex
311
312 movel #ikbd_mousey,d0
313 movel d0,0x118:w
314#else
315 addw d0,_SDL_AtariIkbd_mousex
316
317 movel #ikbd_mousey,0x118:w
318#endif
319 bras ikbd_endit_stack
320
321 | Mouse packet, byte #3
322
323ikbd_mousey:
324#if defined(__mcoldfire__)
325 lea sp@(-12),sp
326 moveml d0-d1/a0,sp@
327#else
328 moveml d0-d1/a0,sp@-
329#endif
330
331 | Check if source is IKBD or MIDI
332#if defined(__mcoldfire__)
333 moveql #0,d0
334 btst d0,0xfffffc00.w
335#else
336 btst #0,0xfffffc00.w
337#endif
338 beqs ikbd_oldmidi
339
340 moveb 0xfffffc02:w,d0
341 extw d0
342#if defined(__mcoldfire__)
343 movew _SDL_AtariIkbd_mousey,d1
344 addl d1,d0
345 movew d0,_SDL_AtariIkbd_mousey
346
347 movel #ikbd,d0
348 movel d0,0x118:w
349#else
350 addw d0,_SDL_AtariIkbd_mousey
351
352 movel #ikbd,0x118:w
353#endif
354 bras ikbd_endit_stack
355
356 | Joystick packet, byte #2
357
358ikbd_joystick:
359#if defined(__mcoldfire__)
360 lea sp@(-12),sp
361 moveml d0-d1/a0,sp@
362#else
363 moveml d0-d1/a0,sp@-
364#endif
365
366 | Check if source is IKBD or MIDI
367#if defined(__mcoldfire__)
368 moveql #0,d0
369 btst d0,0xfffffc00.w
370#else
371 btst #0,0xfffffc00.w
372#endif
373 beqs ikbd_oldmidi
374
375#if defined(__mcoldfire__)
376 moveb 0xfffffc02:w,d0
377 moveb d0,_SDL_AtariIkbd_joystick+1
378
379 movel #ikbd,d0
380 movel d0,0x118:w
381
382 bra ikbd_endit_stack
383#else
384 moveb 0xfffffc02:w,_SDL_AtariIkbd_joystick+1
385
386 movel #ikbd,0x118:w
387
388 bras ikbd_endit_stack
389#endif
390
391 .data
392
393 .even
394_SDL_AtariIkbd_enabled:
395 .word 0
396
397 .bss
398
399 .even
400 .comm _SDL_AtariIkbd_keyboard,128
401 .comm _SDL_AtariIkbd_mousex,2
402 .comm _SDL_AtariIkbd_mousey,2
403 .comm _SDL_AtariIkbd_mouseb,2
404 .comm _SDL_AtariIkbd_joystick,2
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdinterrupt_s.h b/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdinterrupt_s.h
deleted file mode 100644
index ea544bcfcd..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_ikbdinterrupt_s.h
+++ /dev/null
@@ -1,61 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Mouse vector
26 *
27 * Patrice Mandin
28 */
29
30#ifndef _SDL_IKBDINTERRUPT_S_H_
31#define _SDL_IKBDINTERRUPT_S_H_
32
33#include <mint/osbind.h>
34
35#include "SDL_stdinc.h"
36
37/* Const */
38
39#define IKBD_JOY_UP (1<<0)
40#define IKBD_JOY_DOWN (1<<1)
41#define IKBD_JOY_LEFT (1<<2)
42#define IKBD_JOY_RIGHT (1<<3)
43#define IKBD_JOY_FIRE (1<<7)
44
45/* Variables */
46
47extern volatile Uint8 SDL_AtariIkbd_keyboard[128]; /* Keyboard table */
48extern volatile Uint16 SDL_AtariIkbd_mouseb; /* Mouse on port 0, buttons */
49extern volatile Sint16 SDL_AtariIkbd_mousex; /* Mouse X relative motion */
50extern volatile Sint16 SDL_AtariIkbd_mousey; /* Mouse Y relative motion */
51extern volatile Uint16 SDL_AtariIkbd_joystick; /* Joystick on port 1 */
52
53/* For joystick driver to know if this is usable */
54extern Uint16 SDL_AtariIkbd_enabled;
55
56/* Functions */
57
58extern void SDL_AtariIkbdInstall(void);
59extern void SDL_AtariIkbdUninstall(void);
60
61#endif /* _SDL_IKBDINTERRUPT_S_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosevents.c b/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosevents.c
deleted file mode 100644
index 232500f7ae..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosevents.c
+++ /dev/null
@@ -1,155 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * XBIOS mouse & joystick vectors
26 *
27 * Patrice Mandin
28 */
29
30#include <mint/osbind.h>
31
32#include "../../events/SDL_events_c.h"
33#include "SDL_atarisuper.h"
34#include "SDL_xbiosevents_c.h"
35#include "SDL_xbiosinterrupt_s.h"
36
37/* Variables */
38
39int SDL_AtariXbios_enabled=0;
40
41/* Local variables */
42
43static _KBDVECS *kbdvecs; /* Pointer to access system vectors */
44static Uint16 atari_prevmouseb; /* buttons */
45
46/* Functions */
47
48void SDL_AtariXbios_InstallVectors(int vectors_mask)
49{
50 void *oldpile;
51
52 /* Clear variables */
53 SDL_AtariXbios_mouselock =
54 SDL_AtariXbios_mouseb =
55 SDL_AtariXbios_mousex =
56 SDL_AtariXbios_mousey =
57 SDL_AtariXbios_joystick =
58 atari_prevmouseb = 0;
59
60 if (vectors_mask==0) {
61 SDL_AtariXbios_enabled=0;
62 return;
63 }
64
65 /* Read IKBD vectors base */
66 kbdvecs=Kbdvbase();
67
68 /* Go to supervisor mode */
69 oldpile=(void *)Super(0);
70
71 /* Install our vectors */
72 SDL_AtariXbios_Install(
73 kbdvecs,
74 (vectors_mask & ATARI_XBIOS_MOUSEEVENTS) ? SDL_AtariXbios_MouseVector : NULL,
75 (vectors_mask & ATARI_XBIOS_JOYSTICKEVENTS) ? SDL_AtariXbios_JoystickVector : NULL
76 );
77
78 /* Back to user mode */
79 SuperToUser(oldpile);
80
81 SDL_AtariXbios_enabled=1;
82}
83
84void SDL_AtariXbios_RestoreVectors(void)
85{
86 void *oldpile;
87
88 if (SDL_AtariXbios_enabled==0) {
89 return;
90 }
91
92 /* Read IKBD vectors base */
93 kbdvecs=Kbdvbase();
94
95 /* Go to supervisor mode */
96 oldpile=(void *)Super(NULL);
97
98 /* Reinstall system vector */
99 SDL_AtariXbios_Restore(kbdvecs);
100
101 /* Back to user mode */
102 SuperToUser(oldpile);
103}
104
105static int atari_GetButton(int button)
106{
107 switch(button)
108 {
109 case 0:
110 return SDL_BUTTON_RIGHT;
111 break;
112 case 1:
113 default:
114 return SDL_BUTTON_LEFT;
115 break;
116 }
117}
118
119void SDL_AtariXbios_PostMouseEvents(_THIS, SDL_bool buttonEvents)
120{
121 if (SDL_AtariXbios_enabled==0) {
122 return;
123 }
124
125 /* Mouse motion ? */
126 if (SDL_AtariXbios_mousex || SDL_AtariXbios_mousey) {
127 SDL_PrivateMouseMotion(0, 1, SDL_AtariXbios_mousex, SDL_AtariXbios_mousey);
128 SDL_AtariXbios_mousex = SDL_AtariXbios_mousey = 0;
129 }
130
131 /* Mouse button ? */
132 if (buttonEvents && (SDL_AtariXbios_mouseb != atari_prevmouseb)) {
133 int i;
134
135 for (i=0;i<2;i++) {
136 int curbutton, prevbutton;
137
138 curbutton = SDL_AtariXbios_mouseb & (1<<i);
139 prevbutton = atari_prevmouseb & (1<<i);
140
141 if (curbutton && !prevbutton) {
142 SDL_PrivateMouseButton(SDL_PRESSED, atari_GetButton(i), 0, 0);
143 }
144 if (!curbutton && prevbutton) {
145 SDL_PrivateMouseButton(SDL_RELEASED, atari_GetButton(i), 0, 0);
146 }
147 }
148 atari_prevmouseb = SDL_AtariXbios_mouseb;
149 }
150}
151
152void SDL_AtariXbios_LockMousePosition(SDL_bool lockPosition)
153{
154 SDL_AtariXbios_mouselock = lockPosition;
155}
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosevents_c.h b/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosevents_c.h
deleted file mode 100644
index 374b06280b..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosevents_c.h
+++ /dev/null
@@ -1,48 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Xbios mouse & joystick vectors
26 *
27 * Patrice Mandin
28 */
29
30#ifndef _SDL_ATARI_XBIOSEVENTS_H_
31#define _SDL_ATARI_XBIOSEVENTS_H_
32
33#include "../SDL_sysvideo.h"
34
35/* Hidden "this" pointer for the video functions */
36#define _THIS SDL_VideoDevice *this
37
38#define ATARI_XBIOS_MOUSEEVENTS (1<<0)
39#define ATARI_XBIOS_JOYSTICKEVENTS (1<<1)
40
41extern int SDL_AtariXbios_enabled;
42
43extern void SDL_AtariXbios_InstallVectors(int vectors_mask);
44extern void SDL_AtariXbios_RestoreVectors(void);
45extern void SDL_AtariXbios_PostMouseEvents(_THIS, SDL_bool buttonEvents);
46extern void SDL_AtariXbios_LockMousePosition(SDL_bool lockPosition);
47
48#endif /* _SDL_XBIOSEVENTS_H_ */
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosinterrupt.S b/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosinterrupt.S
deleted file mode 100644
index 3fc1a60ada..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosinterrupt.S
+++ /dev/null
@@ -1,212 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/*
24 * XBIOS mouse & joystick vectors
25 *
26 * Patrice Mandin
27 */
28
29 .text
30
31 .globl _SDL_AtariXbios_Install
32 .globl _SDL_AtariXbios_Restore
33 .globl _SDL_AtariXbios_MouseVector
34 .globl _SDL_AtariXbios_JoystickVector
35
36 .globl _SDL_AtariXbios_mouselock
37 .globl _SDL_AtariXbios_mouseb
38 .globl _SDL_AtariXbios_mousex
39 .globl _SDL_AtariXbios_mousey
40 .globl _SDL_AtariXbios_joystick
41
42/*--- Vector installer ---*/
43
44_SDL_AtariXbios_Install:
45 movel sp@(4),a0
46
47 /* Stop interrupts */
48
49 movew #0x2700,sr
50
51 /* Save old mouse vector, set our routine */
52
53 clrl oldmousevector
54 movel sp@(8),d0
55 beqs no_new_mouse_vector
56#if defined(__mcoldfire__)
57 movel a0@(16),d1
58 movel d1,oldmousevector
59#else
60 movel a0@(16),oldmousevector
61#endif
62 movel d0,a0@(16)
63no_new_mouse_vector:
64
65 /* Save old joystick vector, set our routine */
66
67 clrl oldjoystickvector
68 movel sp@(12),d0
69 beqs no_new_joystick_vector
70#if defined(__mcoldfire__)
71 movel a0@(24),d1
72 movel d1,oldjoystickvector
73#else
74 movel a0@(24),oldjoystickvector
75#endif
76 movel d0,a0@(24)
77no_new_joystick_vector:
78
79 /* Restart interrupts */
80
81 movew #0x2300,sr
82
83 rts
84
85/*--- Vector restorer ---*/
86
87_SDL_AtariXbios_Restore:
88 movel sp@(4),a0
89
90 /* Stop interrupts */
91
92 movew #0x2700,sr
93
94 /* Restore mouse vector */
95
96 movel oldmousevector,d0
97 beqs no_restore_mouse
98 movel d0,a0@(16)
99no_restore_mouse:
100
101 /* Restore joystick vector */
102
103 movel oldjoystickvector,d0
104 beqs no_restore_joystick
105 movel d0,a0@(24)
106no_restore_joystick:
107
108 /* Restart interrupts */
109
110 movew #0x2300,sr
111
112 rts
113
114/*--- Our mouse vector ---*/
115
116 .text
117 .even
118 .ascii "XBRA"
119 .ascii "LSDL"
120 .comm oldmousevector,4*1
121_SDL_AtariXbios_MouseVector:
122#if defined(__mcoldfire__)
123 lea sp@(-8),sp
124 moveml d0-d1,sp@
125#else
126 movel d0,sp@-
127#endif
128
129 /* Mouse buttons */
130 moveb (a0),d0
131#if defined(__mcoldfire__)
132 andl #3,d0
133#else
134 andw #3,d0
135#endif
136 movew d0,_SDL_AtariXbios_mouseb
137
138 /* X movement */
139 moveb a0@(1),d0
140 extw d0
141#if defined(__mcoldfire__)
142 movew _SDL_AtariXbios_mousex,d1
143 addl d1,d0
144 movew d0,_SDL_AtariXbios_mousex
145#else
146 addw d0,_SDL_AtariXbios_mousex
147#endif
148
149 /* Y movement */
150 moveb a0@(2),d0
151 extw d0
152#if defined(__mcoldfire__)
153 movew _SDL_AtariXbios_mousey,d1
154 addl d1,d0
155 movew d0,_SDL_AtariXbios_mousey
156#else
157 addw d0,_SDL_AtariXbios_mousey
158#endif
159
160 /* Lock mouse position ? */
161 tstw _SDL_AtariXbios_mouselock
162 beq.s no_mouse_lock
163 clrb a0@(1)
164 clrb a0@(2)
165no_mouse_lock:
166
167 /* Jump through old vector */
168#if defined(__mcoldfire__)
169 moveml sp@,d0-d1
170 lea sp@(8),sp
171#else
172 movel sp@+,d0
173#endif
174
175 movel oldmousevector,sp@-
176 rts
177
178 .data
179 .even
180 .comm _SDL_AtariXbios_mouselock,2*1
181 .comm _SDL_AtariXbios_mousex,2*1
182 .comm _SDL_AtariXbios_mousey,2*1
183 .comm _SDL_AtariXbios_mouseb,2*1
184
185/*--- Our joystick vector ---*/
186
187 .text
188 .even
189 .ascii "XBRA"
190 .ascii "LSDL"
191 .comm oldjoystickvector,4*1
192_SDL_AtariXbios_JoystickVector:
193 movel d0,sp@-
194
195 /* New joystick state */
196 moveb a0@(2),d0
197#if defined(__mcoldfire__)
198 andl #0x8f,d0
199#else
200 andw #0x8f,d0
201#endif
202 movew d0,_SDL_AtariXbios_joystick
203
204 /* Jump through old vector */
205 movel sp@+,d0
206
207 movel oldjoystickvector,sp@-
208 rts
209
210 .data
211 .even
212 .comm _SDL_AtariXbios_joystick,2*1
diff --git a/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosinterrupt_s.h b/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosinterrupt_s.h
deleted file mode 100644
index dfb31c218a..0000000000
--- a/apps/plugins/sdl/src/video/ataricommon/SDL_xbiosinterrupt_s.h
+++ /dev/null
@@ -1,52 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Mouse vector
26 *
27 * Patrice Mandin
28 */
29
30#ifndef _SDL_XBIOSINTERRUPT_S_H_
31#define _SDL_XBIOSINTERRUPT_S_H_
32
33#include <mint/osbind.h>
34
35#include "SDL_stdinc.h"
36
37/* Variables */
38
39extern volatile Uint16 SDL_AtariXbios_mouselock; /* mouse lock position */
40extern volatile Uint16 SDL_AtariXbios_mouseb; /* buttons */
41extern volatile Sint16 SDL_AtariXbios_mousex; /* X relative motion */
42extern volatile Sint16 SDL_AtariXbios_mousey; /* Y relative motion */
43extern volatile Uint16 SDL_AtariXbios_joystick; /* Joystick */
44
45/* Functions */
46
47extern void SDL_AtariXbios_Install(_KBDVECS *kbdvecs,void *newmousevector,void *newjoystickvector);
48extern void SDL_AtariXbios_Restore(_KBDVECS *kbdvecs);
49extern void SDL_AtariXbios_MouseVector(void *buf);
50extern void SDL_AtariXbios_JoystickVector(void *buf);
51
52#endif /* _SDL_XBIOSINTERRUPT_S_H_ */
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_BView.h b/apps/plugins/sdl/src/video/bwindow/SDL_BView.h
deleted file mode 100644
index bfa2c89588..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_BView.h
+++ /dev/null
@@ -1,116 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_BView_h
25#define _SDL_BView_h
26
27/* This is the event handling and graphics update portion of SDL_BWin */
28
29extern "C" {
30#include "../../events/SDL_events_c.h"
31};
32
33class SDL_BView : public BView
34{
35public:
36 SDL_BView(BRect frame) :
37 BView(frame, "SDL View", B_FOLLOW_ALL_SIDES,
38 (B_WILL_DRAW|B_FRAME_EVENTS)) {
39 image = NULL;
40 xoff = yoff = 0;
41 SetViewColor(0,0,0,0);
42 SetHighColor(0,0,0,0);
43 }
44 virtual ~SDL_BView() {
45 SetBitmap(NULL);
46 }
47 /* Set drawing offsets for fullscreen mode */
48 virtual void SetXYOffset(int x, int y) {
49 xoff = x;
50 yoff = y;
51 }
52 virtual void GetXYOffset(int &x, int &y) {
53 x = xoff;
54 y = yoff;
55 }
56 virtual void GetXYOffset(float &x, float &y) {
57 x = (float)xoff;
58 y = (float)yoff;
59 }
60 /* The view changed size. If it means we're in fullscreen, we
61 * draw a nice black box in the entire view to get black borders.
62 */
63 virtual void FrameResized(float width, float height) {
64 BRect bounds;
65 bounds.top = bounds.left = 0;
66 bounds.right = width;
67 bounds.bottom = height;
68 /* Fill the entire view with black */
69 FillRect(bounds, B_SOLID_HIGH);
70 /* And if there's an image, redraw it. */
71 if( image ) {
72 bounds = image->Bounds();
73 Draw(bounds);
74 }
75 }
76
77 /* Drawing portion of this complete breakfast. :) */
78 virtual void SetBitmap(BBitmap *bitmap) {
79 if ( image ) {
80 delete image;
81 }
82 image = bitmap;
83 }
84 virtual void Draw(BRect updateRect) {
85 if ( image ) {
86 if(xoff || yoff) {
87 BRect dest;
88 dest.top = updateRect.top + yoff;
89 dest.left = updateRect.left + xoff;
90 dest.bottom = updateRect.bottom + yoff;
91 dest.right = updateRect.right + xoff;
92 DrawBitmap(image, updateRect, dest);
93 } else {
94 DrawBitmap(image, updateRect, updateRect);
95 }
96 }
97 }
98 virtual void DrawAsync(BRect updateRect) {
99 if(xoff || yoff) {
100 BRect dest;
101 dest.top = updateRect.top + yoff;
102 dest.left = updateRect.left + xoff;
103 dest.bottom = updateRect.bottom + yoff;
104 dest.right = updateRect.right + xoff;;
105 DrawBitmapAsync(image, updateRect, dest);
106 } else {
107 DrawBitmapAsync(image, updateRect, updateRect);
108 }
109 }
110
111private:
112 BBitmap *image;
113 int xoff, yoff;
114};
115
116#endif /* _SDL_BView_h */
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_BWin.h b/apps/plugins/sdl/src/video/bwindow/SDL_BWin.h
deleted file mode 100644
index f2b19a29e2..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_BWin.h
+++ /dev/null
@@ -1,290 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23#ifndef _SDL_BWin_h
24#define _SDL_BWin_h
25
26#include "SDL_config.h"
27
28#include <stdio.h>
29#include <AppKit.h>
30#include <InterfaceKit.h>
31#include <be/game/DirectWindow.h>
32#if SDL_VIDEO_OPENGL
33#include "SDL_opengl.h"
34#include <be/opengl/GLView.h>
35#endif
36#include <support/UTF8.h>
37
38#include "../../main/beos/SDL_BeApp.h"
39#include "SDL_events.h"
40#include "SDL_BView.h"
41
42extern "C" {
43#include "../../events/SDL_events_c.h"
44
45extern int mouse_relative;
46};
47
48class SDL_BWin : public BDirectWindow
49{
50public:
51 SDL_BWin(BRect bounds) :
52 BDirectWindow(bounds, "Untitled", B_TITLED_WINDOW, 0) {
53 last_buttons = 0;
54 the_view = NULL;
55#if SDL_VIDEO_OPENGL
56 SDL_GLView = NULL;
57#endif
58 SDL_View = NULL;
59 Unlock();
60 shown = false;
61 inhibit_resize = false;
62 }
63
64 virtual ~SDL_BWin() {
65 Lock();
66 if ( the_view ) {
67#if SDL_VIDEO_OPENGL
68 if ( the_view == SDL_GLView ) {
69 SDL_GLView->UnlockGL();
70 }
71#endif
72 RemoveChild(the_view);
73 the_view = NULL;
74 }
75 Unlock();
76#if SDL_VIDEO_OPENGL
77 if ( SDL_GLView ) {
78 delete SDL_GLView;
79 }
80#endif
81 if ( SDL_View ) {
82 delete SDL_View;
83 }
84 }
85
86
87 /* Override the Show() method so we can tell when we've been shown */
88 virtual void Show(void) {
89 BWindow::Show();
90 shown = true;
91 }
92 virtual bool Shown(void) {
93 return (shown);
94 }
95 /* If called, the next resize event will not be forwarded to SDL. */
96 virtual void InhibitResize(void) {
97 inhibit_resize=true;
98 }
99 /* Handle resizing of the window */
100 virtual void FrameResized(float width, float height) {
101 if(inhibit_resize)
102 inhibit_resize = false;
103 else
104 SDL_PrivateResize((int)width, (int)height);
105 }
106 virtual int CreateView(Uint32 flags, Uint32 gl_flags) {
107 int retval;
108
109 retval = 0;
110 Lock();
111 if ( flags & SDL_OPENGL ) {
112#if SDL_VIDEO_OPENGL
113 if ( SDL_GLView == NULL ) {
114 SDL_GLView = new BGLView(Bounds(), "SDL GLView",
115 B_FOLLOW_ALL_SIDES, (B_WILL_DRAW|B_FRAME_EVENTS),
116 gl_flags|BGL_DOUBLE);
117 SDL_GLView->EnableDirectMode(true);
118 }
119 if ( the_view != SDL_GLView ) {
120 if ( the_view ) {
121 RemoveChild(the_view);
122 }
123 AddChild(SDL_GLView);
124 SDL_GLView->LockGL();
125 the_view = SDL_GLView;
126 }
127#else
128 SDL_SetError("OpenGL support not enabled");
129 retval = -1;
130#endif
131 } else {
132 if ( SDL_View == NULL ) {
133 SDL_View = new SDL_BView(Bounds());
134 }
135 if ( the_view != SDL_View ) {
136 if ( the_view ) {
137 RemoveChild(the_view);
138 }
139 AddChild(SDL_View);
140 the_view = SDL_View;
141 }
142 }
143#if SDL_VIDEO_OPENGL
144 if ( the_view == SDL_GLView ) {
145 SDL_GLView->UnlockGL();
146 }
147#endif
148 Unlock();
149 return(retval);
150 }
151 virtual void SetBitmap(BBitmap *bitmap) {
152 SDL_View->SetBitmap(bitmap);
153 }
154 virtual void SetXYOffset(int x, int y) {
155#if SDL_VIDEO_OPENGL
156 if ( the_view == SDL_GLView ) {
157 return;
158 }
159#endif
160 SDL_View->SetXYOffset(x, y);
161 }
162 virtual void GetXYOffset(int &x, int &y) {
163#if SDL_VIDEO_OPENGL
164 if ( the_view == SDL_GLView ) {
165 x = 0;
166 y = 0;
167 return;
168 }
169#endif
170 SDL_View->GetXYOffset(x, y);
171 }
172 virtual void GetXYOffset(float &x, float &y) {
173#if SDL_VIDEO_OPENGL
174 if ( the_view == SDL_GLView ) {
175 x = 0.0f;
176 y = 0.0f;
177 return;
178 }
179#endif
180 SDL_View->GetXYOffset(x, y);
181 }
182 virtual bool BeginDraw(void) {
183 return(Lock());
184 }
185 virtual void DrawAsync(BRect updateRect) {
186 SDL_View->DrawAsync(updateRect);
187 }
188 virtual void EndDraw(void) {
189 SDL_View->Sync();
190 Unlock();
191 }
192#if SDL_VIDEO_OPENGL
193 virtual void SwapBuffers(void) {
194 SDL_GLView->UnlockGL();
195 SDL_GLView->SwapBuffers();
196 SDL_GLView->LockGL();
197 }
198#endif
199 virtual BView *View(void) {
200 return(the_view);
201 }
202
203 /* Hook functions -- overridden */
204 virtual void Minimize(bool minimize) {
205 /* This is only called when mimimized, not when restored */
206 //SDL_PrivateAppActive(minimize, SDL_APPACTIVE);
207 BWindow::Minimize(minimize);
208 }
209 virtual void WindowActivated(bool active) {
210 SDL_PrivateAppActive(active, SDL_APPINPUTFOCUS);
211 }
212 virtual bool QuitRequested(void) {
213 if ( SDL_BeAppActive > 0 ) {
214 SDL_PrivateQuit();
215 /* We don't ever actually close the window here because
216 the application should respond to the quit request,
217 or ignore it as desired.
218 */
219#if SDL_VIDEO_OPENGL
220 if ( SDL_GLView != NULL ) {
221 SDL_GLView->EnableDirectMode(false);
222 }
223#endif
224 return(false);
225 }
226 return(true); /* Close the app window */
227 }
228 virtual void Quit() {
229 if (!IsLocked())
230 Lock();
231 BDirectWindow::Quit();
232 }
233
234 virtual int16 Translate2Unicode(const char *buf) {
235 int32 state, srclen, dstlen;
236 unsigned char destbuf[2];
237 Uint16 unicode = 0;
238
239 if ((uchar)buf[0] > 127) {
240 state = 0;
241 srclen = SDL_strlen(buf);
242 dstlen = sizeof(destbuf);
243 convert_from_utf8(B_UNICODE_CONVERSION, buf, &srclen, (char *)destbuf, &dstlen, &state);
244 unicode = destbuf[0];
245 unicode <<= 8;
246 unicode |= destbuf[1];
247 } else
248 unicode = buf[0];
249
250 /* For some reason function keys map to control characters */
251# define CTRL(X) ((X)-'@')
252 switch (unicode) {
253 case CTRL('A'):
254 case CTRL('B'):
255 case CTRL('C'):
256 case CTRL('D'):
257 case CTRL('E'):
258 case CTRL('K'):
259 case CTRL('L'):
260 case CTRL('P'):
261 if ( ! (SDL_GetModState() & KMOD_CTRL) )
262 unicode = 0;
263 break;
264 /* Keyboard input maps newline to carriage return */
265 case '\n':
266 unicode = '\r';
267 break;
268 default:
269 break;
270 }
271
272 return unicode;
273 }
274
275 virtual void DispatchMessage(BMessage *msg, BHandler *target);
276
277 virtual void DirectConnected(direct_buffer_info *info);
278
279private:
280#if SDL_VIDEO_OPENGL
281 BGLView *SDL_GLView;
282#endif
283 SDL_BView *SDL_View;
284 BView *the_view;
285 bool shown;
286 bool inhibit_resize;
287 int32 last_buttons;
288};
289
290#endif /* _SDL_BWin_h */
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_lowvideo.h b/apps/plugins/sdl/src/video/bwindow/SDL_lowvideo.h
deleted file mode 100644
index 0513b2db26..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_lowvideo.h
+++ /dev/null
@@ -1,58 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowvideo_h
25#define _SDL_lowvideo_h
26
27#include "SDL_BWin.h"
28#include "SDL_mouse.h"
29#include "../SDL_sysvideo.h"
30
31/* Hidden "this" pointer for the video functions */
32#define _THIS SDL_VideoDevice *_this
33
34/* Private display data */
35struct SDL_PrivateVideoData {
36 /* The main window */
37 SDL_BWin *SDL_Win;
38
39 /* The fullscreen mode list */
40 display_mode saved_mode;
41#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
42 int SDL_nummodes[NUM_MODELISTS];
43 SDL_Rect **SDL_modelist[NUM_MODELISTS];
44
45 /* A completely clear cursor */
46 WMcursor *BlankCursor;
47
48 SDL_Overlay *overlay;
49};
50/* Old variable names */
51#define SDL_Win (_this->hidden->SDL_Win)
52#define saved_mode (_this->hidden->saved_mode)
53#define SDL_nummodes (_this->hidden->SDL_nummodes)
54#define SDL_modelist (_this->hidden->SDL_modelist)
55#define SDL_BlankCursor (_this->hidden->BlankCursor)
56#define current_overlay (_this->hidden->overlay)
57
58#endif /* _SDL_lowvideo_h */
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_sysevents.cc b/apps/plugins/sdl/src/video/bwindow/SDL_sysevents.cc
deleted file mode 100644
index 9e127506de..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_sysevents.cc
+++ /dev/null
@@ -1,415 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <support/UTF8.h>
25#include <stdio.h>
26#include <string.h>
27#include "SDL_error.h"
28#include "SDL_events.h"
29#include "SDL_BWin.h"
30#include "SDL_lowvideo.h"
31
32static SDLKey keymap[128];
33int mouse_relative = 0;
34extern "C" {
35
36#include "../../events/SDL_sysevents.h"
37#include "../../events/SDL_events_c.h"
38#include "SDL_sysevents_c.h"
39#include "../SDL_cursor_c.h"
40
41void BE_PumpEvents(_THIS)
42{
43}
44
45void BE_InitOSKeymap(_THIS)
46{
47 for ( uint i=0; i<SDL_TABLESIZE(keymap); ++i )
48 keymap[i] = SDLK_UNKNOWN;
49
50 keymap[0x01] = SDLK_ESCAPE;
51 keymap[B_F1_KEY] = SDLK_F1;
52 keymap[B_F2_KEY] = SDLK_F2;
53 keymap[B_F3_KEY] = SDLK_F3;
54 keymap[B_F4_KEY] = SDLK_F4;
55 keymap[B_F5_KEY] = SDLK_F5;
56 keymap[B_F6_KEY] = SDLK_F6;
57 keymap[B_F7_KEY] = SDLK_F7;
58 keymap[B_F8_KEY] = SDLK_F8;
59 keymap[B_F9_KEY] = SDLK_F9;
60 keymap[B_F10_KEY] = SDLK_F10;
61 keymap[B_F11_KEY] = SDLK_F11;
62 keymap[B_F12_KEY] = SDLK_F12;
63 keymap[B_PRINT_KEY] = SDLK_PRINT;
64 keymap[B_SCROLL_KEY] = SDLK_SCROLLOCK;
65 keymap[B_PAUSE_KEY] = SDLK_PAUSE;
66 keymap[0x11] = SDLK_BACKQUOTE;
67 keymap[0x12] = SDLK_1;
68 keymap[0x13] = SDLK_2;
69 keymap[0x14] = SDLK_3;
70 keymap[0x15] = SDLK_4;
71 keymap[0x16] = SDLK_5;
72 keymap[0x17] = SDLK_6;
73 keymap[0x18] = SDLK_7;
74 keymap[0x19] = SDLK_8;
75 keymap[0x1a] = SDLK_9;
76 keymap[0x1b] = SDLK_0;
77 keymap[0x1c] = SDLK_MINUS;
78 keymap[0x1d] = SDLK_EQUALS;
79 keymap[0x1e] = SDLK_BACKSPACE;
80 keymap[0x1f] = SDLK_INSERT;
81 keymap[0x20] = SDLK_HOME;
82 keymap[0x21] = SDLK_PAGEUP;
83 keymap[0x22] = SDLK_NUMLOCK;
84 keymap[0x23] = SDLK_KP_DIVIDE;
85 keymap[0x24] = SDLK_KP_MULTIPLY;
86 keymap[0x25] = SDLK_KP_MINUS;
87 keymap[0x26] = SDLK_TAB;
88 keymap[0x27] = SDLK_q;
89 keymap[0x28] = SDLK_w;
90 keymap[0x29] = SDLK_e;
91 keymap[0x2a] = SDLK_r;
92 keymap[0x2b] = SDLK_t;
93 keymap[0x2c] = SDLK_y;
94 keymap[0x2d] = SDLK_u;
95 keymap[0x2e] = SDLK_i;
96 keymap[0x2f] = SDLK_o;
97 keymap[0x30] = SDLK_p;
98 keymap[0x31] = SDLK_LEFTBRACKET;
99 keymap[0x32] = SDLK_RIGHTBRACKET;
100 keymap[0x33] = SDLK_BACKSLASH;
101 keymap[0x34] = SDLK_DELETE;
102 keymap[0x35] = SDLK_END;
103 keymap[0x36] = SDLK_PAGEDOWN;
104 keymap[0x37] = SDLK_KP7;
105 keymap[0x38] = SDLK_KP8;
106 keymap[0x39] = SDLK_KP9;
107 keymap[0x3a] = SDLK_KP_PLUS;
108 keymap[0x3b] = SDLK_CAPSLOCK;
109 keymap[0x3c] = SDLK_a;
110 keymap[0x3d] = SDLK_s;
111 keymap[0x3e] = SDLK_d;
112 keymap[0x3f] = SDLK_f;
113 keymap[0x40] = SDLK_g;
114 keymap[0x41] = SDLK_h;
115 keymap[0x42] = SDLK_j;
116 keymap[0x43] = SDLK_k;
117 keymap[0x44] = SDLK_l;
118 keymap[0x45] = SDLK_SEMICOLON;
119 keymap[0x46] = SDLK_QUOTE;
120 keymap[0x47] = SDLK_RETURN;
121 keymap[0x48] = SDLK_KP4;
122 keymap[0x49] = SDLK_KP5;
123 keymap[0x4a] = SDLK_KP6;
124 keymap[0x4b] = SDLK_LSHIFT;
125 keymap[0x4c] = SDLK_z;
126 keymap[0x4d] = SDLK_x;
127 keymap[0x4e] = SDLK_c;
128 keymap[0x4f] = SDLK_v;
129 keymap[0x50] = SDLK_b;
130 keymap[0x51] = SDLK_n;
131 keymap[0x52] = SDLK_m;
132 keymap[0x53] = SDLK_COMMA;
133 keymap[0x54] = SDLK_PERIOD;
134 keymap[0x55] = SDLK_SLASH;
135 keymap[0x56] = SDLK_RSHIFT;
136 keymap[0x57] = SDLK_UP;
137 keymap[0x58] = SDLK_KP1;
138 keymap[0x59] = SDLK_KP2;
139 keymap[0x5a] = SDLK_KP3;
140 keymap[0x5b] = SDLK_KP_ENTER;
141 keymap[0x5c] = SDLK_LCTRL;
142 keymap[0x5d] = SDLK_LALT;
143 keymap[0x5e] = SDLK_SPACE;
144 keymap[0x5f] = SDLK_RALT;
145 keymap[0x60] = SDLK_RCTRL;
146 keymap[0x61] = SDLK_LEFT;
147 keymap[0x62] = SDLK_DOWN;
148 keymap[0x63] = SDLK_RIGHT;
149 keymap[0x64] = SDLK_KP0;
150 keymap[0x65] = SDLK_KP_PERIOD;
151 keymap[0x66] = SDLK_LMETA;
152 keymap[0x67] = SDLK_RMETA;
153 keymap[0x68] = SDLK_MENU;
154 keymap[0x69] = SDLK_EURO;
155 keymap[0x6a] = SDLK_KP_EQUALS;
156 keymap[0x6b] = SDLK_POWER;
157}
158
159}; /* Extern C */
160
161void SDL_BWin::DispatchMessage(BMessage *msg, BHandler *target)
162{
163 switch (msg->what) {
164 case B_MOUSE_MOVED:
165 {
166 SDL_VideoDevice *view = current_video;
167 BPoint where;
168 int32 transit;
169 if (msg->FindPoint("where", &where) == B_OK && msg->FindInt32("be:transit", &transit) == B_OK) {
170 int x, y;
171
172 GetXYOffset(x, y);
173 x = (int)where.x - x;
174 y = (int)where.y - y;
175
176 //BeSman: I need another method for cursor catching !!!
177 if (view->input_grab != SDL_GRAB_OFF)
178 {
179 bool clipped = false;
180 if ( x < 0 ) {
181 x = 0;
182 clipped = true;
183 } else if ( x >= SDL_VideoSurface->w ) {
184 x = (SDL_VideoSurface->w-1);
185 clipped = true;
186 }
187 if ( y < 0 ) {
188 y = 0;
189 clipped = true;
190 } else if ( y >= SDL_VideoSurface->h ) {
191 y = (SDL_VideoSurface->h-1);
192 clipped = true;
193 }
194 if ( clipped ) {
195 BPoint edge;
196 GetXYOffset(edge.x, edge.y);
197 edge.x += x;
198 edge.y += y;
199 ConvertToScreen(&edge);
200 set_mouse_position((int)edge.x, (int)edge.y);
201 }
202 transit = B_INSIDE_VIEW;
203 }
204 if (transit == B_EXITED_VIEW) {
205 if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) {
206 SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
207#if SDL_VIDEO_OPENGL
208 // for some reason, SDL_EraseCursor fails for OpenGL
209 if (this->the_view != this->SDL_GLView)
210#endif
211 SDL_EraseCursor(SDL_VideoSurface);
212 be_app->SetCursor(B_HAND_CURSOR);
213 }
214 } else {
215 if ( !(SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) {
216 SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
217#if SDL_VIDEO_OPENGL
218 // for some reason, SDL_EraseCursor fails for OpenGL
219 if (this->the_view != this->SDL_GLView)
220#endif
221 SDL_EraseCursor(SDL_VideoSurface);
222 SDL_SetCursor(NULL);
223 }
224
225 if ( mouse_relative ) {
226 int half_w = (SDL_VideoSurface->w/2);
227 int half_h = (SDL_VideoSurface->h/2);
228 x -= half_w;
229 y -= half_h;
230 if ( x || y ) {
231 BPoint center;
232 GetXYOffset(center.x, center.y);
233 center.x += half_w;
234 center.y += half_h;
235 ConvertToScreen(&center);
236 set_mouse_position((int)center.x, (int)center.y);
237 SDL_PrivateMouseMotion(0, 1, x, y);
238 }
239 } else {
240 SDL_PrivateMouseMotion(0, 0, x, y);
241 }
242 }
243 }
244 break;
245 }
246
247 case B_MOUSE_DOWN:
248 {
249 /* it looks like mouse down is send only for first clicked
250 button, each next is not send while last one is holded */
251 int32 buttons;
252 int sdl_buttons = 0;
253 if (msg->FindInt32("buttons", &buttons) == B_OK) {
254 /* Add any mouse button events */
255 if (buttons & B_PRIMARY_MOUSE_BUTTON) {
256 sdl_buttons |= SDL_BUTTON_LEFT;
257 }
258 if (buttons & B_SECONDARY_MOUSE_BUTTON) {
259 sdl_buttons |= SDL_BUTTON_RIGHT;
260 }
261 if (buttons & B_TERTIARY_MOUSE_BUTTON) {
262 sdl_buttons |= SDL_BUTTON_MIDDLE;
263 }
264 SDL_PrivateMouseButton(SDL_PRESSED, sdl_buttons, 0, 0);
265
266 last_buttons = buttons;
267 }
268 break;
269 }
270
271 case B_MOUSE_UP:
272 {
273 /* mouse up doesn't give which button was released,
274 only state of buttons (after release, so it's always = 0),
275 which is not what we need ;]
276 So we need to store button in mouse down, and restore
277 in mouse up :(
278 mouse up is (similarly to mouse down) send only for
279 first button down (ie. it's no send if we click another button
280 without releasing previous one first) - but that's probably
281 because of how drivers are written?, not BeOS itself. */
282 int32 buttons;
283 int sdl_buttons = 0;
284 if (msg->FindInt32("buttons", &buttons) == B_OK) {
285 /* Add any mouse button events */
286 if ((buttons ^ B_PRIMARY_MOUSE_BUTTON) & last_buttons) {
287 sdl_buttons |= SDL_BUTTON_LEFT;
288 }
289 if ((buttons ^ B_SECONDARY_MOUSE_BUTTON) & last_buttons) {
290 sdl_buttons |= SDL_BUTTON_RIGHT;
291 }
292 if ((buttons ^ B_TERTIARY_MOUSE_BUTTON) & last_buttons) {
293 sdl_buttons |= SDL_BUTTON_MIDDLE;
294 }
295 SDL_PrivateMouseButton(SDL_RELEASED, sdl_buttons, 0, 0);
296
297 last_buttons = buttons;
298 }
299 break;
300 }
301
302 case B_MOUSE_WHEEL_CHANGED:
303 {
304 float x, y;
305 x = y = 0;
306 if (msg->FindFloat("be:wheel_delta_x", &x) == B_OK && msg->FindFloat("be:wheel_delta_y", &y) == B_OK) {
307 if (x < 0 || y < 0) {
308 SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELDOWN, 0, 0);
309 SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELDOWN, 0, 0);
310 } else if (x > 0 || y > 0) {
311 SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELUP, 0, 0);
312 SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELUP, 0, 0);
313 }
314 }
315 break;
316 }
317
318 case B_KEY_DOWN:
319 case B_UNMAPPED_KEY_DOWN: /* modifier keys are unmapped */
320 {
321 int32 key;
322 int32 modifiers;
323 int32 key_repeat;
324 /* Workaround for SDL message queue being filled too fast because of BeOS own key-repeat mechanism */
325 if (msg->FindInt32("be:key_repeat", &key_repeat) == B_OK && key_repeat > 0)
326 break;
327
328 if (msg->FindInt32("key", &key) == B_OK && msg->FindInt32("modifiers", &modifiers) == B_OK) {
329 SDL_keysym keysym;
330 keysym.scancode = key;
331 if (key < 128) {
332 keysym.sym = keymap[key];
333 } else {
334 keysym.sym = SDLK_UNKNOWN;
335 }
336 /* FIX THIS?
337 it seems SDL_PrivateKeyboard() changes mod value
338 anyway, and doesn't care about what we setup here */
339 keysym.mod = KMOD_NONE;
340 keysym.unicode = 0;
341 if (SDL_TranslateUNICODE) {
342 const char *bytes;
343 if (msg->FindString("bytes", &bytes) == B_OK) {
344 /* FIX THIS?
345 this cares only about first "letter",
346 so if someone maps some key to print
347 "BeOS rulez!" only "B" will be used. */
348 keysym.unicode = Translate2Unicode(bytes);
349 }
350 }
351 SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
352 }
353 break;
354 }
355
356 case B_KEY_UP:
357 case B_UNMAPPED_KEY_UP: /* modifier keys are unmapped */
358 {
359 int32 key;
360 int32 modifiers;
361 if (msg->FindInt32("key", &key) == B_OK && msg->FindInt32("modifiers", &modifiers) == B_OK) {
362 SDL_keysym keysym;
363 keysym.scancode = key;
364 if (key < 128) {
365 keysym.sym = keymap[key];
366 } else {
367 keysym.sym = SDLK_UNKNOWN;
368 }
369 keysym.mod = KMOD_NONE; /* FIX THIS? */
370 keysym.unicode = 0;
371 if (SDL_TranslateUNICODE) {
372 const char *bytes;
373 if (msg->FindString("bytes", &bytes) == B_OK) {
374 keysym.unicode = Translate2Unicode(bytes);
375 }
376 }
377 SDL_PrivateKeyboard(SDL_RELEASED, &keysym);
378 }
379 break;
380 }
381
382 default:
383 /* move it after switch{} so it's always handled
384 that way we keep BeOS feautures like:
385 - CTRL+Q to close window (and other shortcuts)
386 - PrintScreen to make screenshot into /boot/home
387 - etc.. */
388 //BDirectWindow::DispatchMessage(msg, target);
389 break;
390 }
391 BDirectWindow::DispatchMessage(msg, target);
392}
393
394void SDL_BWin::DirectConnected(direct_buffer_info *info) {
395 switch (info->buffer_state & B_DIRECT_MODE_MASK) {
396 case B_DIRECT_START:
397 case B_DIRECT_MODIFY:
398 {
399 int32 width = info->window_bounds.right -
400 info->window_bounds.left;
401 int32 height = info->window_bounds.bottom -
402 info->window_bounds.top;
403 SDL_PrivateResize(width, height);
404 break;
405 }
406 default:
407 break;
408 }
409#if SDL_VIDEO_OPENGL
410 // If it is a BGLView, it is apparently required to
411 // call DirectConnected() on it as well
412 if (this->the_view == this->SDL_GLView)
413 this->SDL_GLView->DirectConnected(info);
414#endif
415}
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_sysevents_c.h b/apps/plugins/sdl/src/video/bwindow/SDL_sysevents_c.h
deleted file mode 100644
index 70c55358c9..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_sysevents_c.h
+++ /dev/null
@@ -1,31 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_lowvideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29
30extern void BE_InitOSKeymap(_THIS);
31extern void BE_PumpEvents(_THIS);
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_sysmouse.cc b/apps/plugins/sdl/src/video/bwindow/SDL_sysmouse.cc
deleted file mode 100644
index 9a557d6286..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_sysmouse.cc
+++ /dev/null
@@ -1,153 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <AppKit.h>
25#include <GameKit.h>
26
27#include "SDL_BWin.h"
28
29extern "C" {
30#include "../SDL_cursor_c.h"
31#include "SDL_sysmouse_c.h"
32
33/* Convert bits to padded bytes */
34#define PADDED_BITS(bits) ((bits+7)/8)
35
36/* The implementation dependent data for the window manager cursor */
37struct WMcursor {
38 char *bits;
39};
40
41/* Can this be done in the BeOS? */
42WMcursor *BE_CreateWMCursor(_THIS,
43 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
44{
45 WMcursor *cursor;
46 int allowed_x;
47 int allowed_y;
48 int run, pad, i;
49 char *cptr;
50
51 allowed_x = 16; /* BeOS limitation */
52 allowed_y = 16; /* BeOS limitation */
53 if ( (w > allowed_x) || (h > allowed_y) ) {
54 SDL_SetError("Only cursors of dimension (%dx%d) are allowed",
55 allowed_x, allowed_y);
56 return(NULL);
57 }
58
59 /* Allocate the cursor */
60 cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor));
61 if ( cursor == NULL ) {
62 SDL_OutOfMemory();
63 return(NULL);
64 }
65 cursor->bits = (char *)SDL_malloc(4+2*((allowed_x/8)*allowed_y));
66 if ( cursor->bits == NULL ) {
67 SDL_free(cursor);
68 SDL_OutOfMemory();
69 return(NULL);
70 }
71 cursor->bits[0] = allowed_y; /* Size of the cursor */
72 cursor->bits[1] = 1; /* Bit depth of cursor */
73 cursor->bits[2] = hot_y;
74 cursor->bits[3] = hot_x;
75 cptr = &cursor->bits[4];
76
77 /* Pad out to the normal cursor size */
78 run = PADDED_BITS(w);
79 pad = PADDED_BITS(allowed_x)-run;
80 for ( i=0; i<h; ++i ) {
81 SDL_memcpy(cptr, data, run);
82 SDL_memset(cptr+run, 0, pad);
83 data += run;
84 cptr += (run+pad);
85 }
86 for ( ; i<allowed_y; ++i ) {
87 SDL_memset(cptr, 0, run+pad);
88 cptr += (run+pad);
89 }
90 for ( i=0; i<h; ++i ) {
91 /* FIXME: The mask should be OR'd with the data to turn
92 inverted color pixels black, since inverted color pixels
93 aren't supported under BeOS.
94 */
95 SDL_memcpy(cptr, mask, run);
96 SDL_memset(cptr+run, 0, pad);
97 mask += run;
98 cptr += (run+pad);
99 }
100 for ( ; i<allowed_y; ++i ) {
101 SDL_memset(cptr, 0, run+pad);
102 cptr += (run+pad);
103 }
104 return(cursor);
105}
106
107int BE_ShowWMCursor(_THIS, WMcursor *cursor)
108{
109 if ( be_app->Lock() ) {
110 if ( cursor == NULL ) {
111 if ( SDL_BlankCursor != NULL ) {
112 be_app->SetCursor(SDL_BlankCursor->bits);
113 }
114 } else {
115 be_app->SetCursor(cursor->bits);
116 }
117 be_app->Unlock();
118 }
119 return(1);
120}
121
122void BE_FreeWMCursor(_THIS, WMcursor *cursor)
123{
124 SDL_free(cursor->bits);
125 SDL_free(cursor);
126}
127
128/* Implementation by Christian Bauer <cbauer@student.physik.uni-mainz.de> */
129void BE_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
130{
131 BPoint pt;
132 SDL_Win->GetXYOffset(pt.x, pt.y);
133 pt.x += x;
134 pt.y += y;
135 SDL_Win->Lock();
136 SDL_Win->ConvertToScreen(&pt);
137 SDL_Win->Unlock();
138 set_mouse_position((int32)pt.x, (int32)pt.y);
139}
140
141/* Check to see if we need to enter or leave mouse relative mode */
142void BE_CheckMouseMode(_THIS)
143{
144 /* If the mouse is hidden and input is grabbed, we use relative mode */
145 if ( !(SDL_cursorstate & CURSOR_VISIBLE) &&
146 (_this->input_grab != SDL_GRAB_OFF) ) {
147 mouse_relative = 1;
148 } else {
149 mouse_relative = 0;
150 }
151}
152
153}; /* Extern C */
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_sysmouse_c.h b/apps/plugins/sdl/src/video/bwindow/SDL_sysmouse_c.h
deleted file mode 100644
index 70b3b2a5f9..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_sysmouse_c.h
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_lowvideo.h"
25
26/* Functions to be exported */
27extern void BE_FreeWMCursor(_THIS, WMcursor *cursor);
28extern WMcursor *BE_CreateWMCursor(_THIS,
29 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
30extern int BE_ShowWMCursor(_THIS, WMcursor *cursor);
31extern void BE_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
32extern void BE_CheckMouseMode(_THIS);
33
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_sysvideo.cc b/apps/plugins/sdl/src/video/bwindow/SDL_sysvideo.cc
deleted file mode 100644
index c32b661d24..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_sysvideo.cc
+++ /dev/null
@@ -1,841 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* BWindow based framebuffer implementation */
25
26#include <unistd.h>
27
28#include "SDL_BWin.h"
29#include "SDL_timer.h"
30
31extern "C" {
32
33#include "../SDL_sysvideo.h"
34#include "../../events/SDL_events_c.h"
35#include "SDL_sysevents_c.h"
36#include "SDL_sysmouse_c.h"
37#include "SDL_syswm_c.h"
38#include "SDL_lowvideo.h"
39#include "../SDL_yuvfuncs.h"
40#include "SDL_sysyuv.h"
41#include "../blank_cursor.h"
42
43#define BEOS_HIDDEN_SIZE 32 /* starting hidden window size */
44
45/* Initialization/Query functions */
46static int BE_VideoInit(_THIS, SDL_PixelFormat *vformat);
47static SDL_Rect **BE_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
48static SDL_Surface *BE_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
49static void BE_UpdateMouse(_THIS);
50static int BE_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
51static void BE_VideoQuit(_THIS);
52
53/* Hardware surface functions */
54static int BE_AllocHWSurface(_THIS, SDL_Surface *surface);
55static int BE_LockHWSurface(_THIS, SDL_Surface *surface);
56static void BE_UnlockHWSurface(_THIS, SDL_Surface *surface);
57static void BE_FreeHWSurface(_THIS, SDL_Surface *surface);
58
59static int BE_ToggleFullScreen(_THIS, int fullscreen);
60
61/* OpenGL functions */
62#if SDL_VIDEO_OPENGL
63static int BE_GL_LoadLibrary(_THIS, const char *path);
64static void* BE_GL_GetProcAddress(_THIS, const char *proc);
65static int BE_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value);
66static int BE_GL_MakeCurrent(_THIS);
67static void BE_GL_SwapBuffers(_THIS);
68#endif
69
70/* FB driver bootstrap functions */
71
72static int BE_Available(void)
73{
74 return(1);
75}
76
77static void BE_DeleteDevice(SDL_VideoDevice *device)
78{
79 SDL_free(device->hidden);
80 SDL_free(device);
81}
82
83static SDL_VideoDevice *BE_CreateDevice(int devindex)
84{
85 SDL_VideoDevice *device;
86
87 /* Initialize all variables that we clean on shutdown */
88 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
89 if ( device ) {
90 SDL_memset(device, 0, (sizeof *device));
91 device->hidden = (struct SDL_PrivateVideoData *)
92 SDL_malloc((sizeof *device->hidden));
93 }
94 if ( (device == NULL) || (device->hidden == NULL) ) {
95 SDL_OutOfMemory();
96 if ( device ) {
97 SDL_free(device);
98 }
99 return(0);
100 }
101 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
102
103 /* Set the function pointers */
104 /* Initialization/Query functions */
105 device->VideoInit = BE_VideoInit;
106 device->ListModes = BE_ListModes;
107 device->SetVideoMode = BE_SetVideoMode;
108 device->ToggleFullScreen = BE_ToggleFullScreen;
109 device->UpdateMouse = BE_UpdateMouse;
110 device->CreateYUVOverlay = BE_CreateYUVOverlay;
111 device->SetColors = BE_SetColors;
112 device->UpdateRects = NULL;
113 device->VideoQuit = BE_VideoQuit;
114 /* Hardware acceleration functions */
115 device->AllocHWSurface = BE_AllocHWSurface;
116 device->CheckHWBlit = NULL;
117 device->FillHWRect = NULL;
118 device->SetHWColorKey = NULL;
119 device->SetHWAlpha = NULL;
120 device->LockHWSurface = BE_LockHWSurface;
121 device->UnlockHWSurface = BE_UnlockHWSurface;
122 device->FlipHWSurface = NULL;
123 device->FreeHWSurface = BE_FreeHWSurface;
124 /* Gamma support */
125#if SDL_VIDEO_OPENGL
126 /* OpenGL support */
127 device->GL_LoadLibrary = BE_GL_LoadLibrary;
128 device->GL_GetProcAddress = BE_GL_GetProcAddress;
129 device->GL_GetAttribute = BE_GL_GetAttribute;
130 device->GL_MakeCurrent = BE_GL_MakeCurrent;
131 device->GL_SwapBuffers = BE_GL_SwapBuffers;
132#endif
133 /* Window manager functions */
134 device->SetCaption = BE_SetWMCaption;
135 device->SetIcon = NULL;
136 device->IconifyWindow = BE_IconifyWindow;
137 device->GrabInput = BE_GrabInput;
138 device->GetWMInfo = BE_GetWMInfo;
139 /* Cursor manager functions */
140 device->FreeWMCursor = BE_FreeWMCursor;
141 device->CreateWMCursor = BE_CreateWMCursor;
142 device->ShowWMCursor = BE_ShowWMCursor;
143 device->WarpWMCursor = BE_WarpWMCursor;
144 device->MoveWMCursor = NULL;
145 device->CheckMouseMode = BE_CheckMouseMode;
146 /* Event manager functions */
147 device->InitOSKeymap = BE_InitOSKeymap;
148 device->PumpEvents = BE_PumpEvents;
149
150 device->free = BE_DeleteDevice;
151
152 /* Set the driver flags */
153 device->handles_any_size = 1;
154
155 return device;
156}
157
158VideoBootStrap BWINDOW_bootstrap = {
159 "bwindow", "BDirectWindow graphics",
160 BE_Available, BE_CreateDevice
161};
162
163static inline int ColorSpaceToBitsPerPixel(uint32 colorspace)
164{
165 int bitsperpixel;
166
167 bitsperpixel = 0;
168 switch (colorspace) {
169 case B_CMAP8:
170 bitsperpixel = 8;
171 break;
172 case B_RGB15:
173 case B_RGBA15:
174 case B_RGB15_BIG:
175 case B_RGBA15_BIG:
176 bitsperpixel = 15;
177 break;
178 case B_RGB16:
179 case B_RGB16_BIG:
180 bitsperpixel = 16;
181 break;
182 case B_RGB32:
183 case B_RGBA32:
184 case B_RGB32_BIG:
185 case B_RGBA32_BIG:
186 bitsperpixel = 32;
187 break;
188 default:
189 break;
190 }
191 return(bitsperpixel);
192}
193
194/* Function to sort the display_list in bscreen */
195static int CompareModes(const void *A, const void *B)
196{
197 const display_mode *a = (display_mode *)A;
198 const display_mode *b = (display_mode *)B;
199
200 if ( a->space == b->space ) {
201 return((b->virtual_width*b->virtual_height)-
202 (a->virtual_width*a->virtual_height));
203 } else {
204 return(ColorSpaceToBitsPerPixel(b->space)-
205 ColorSpaceToBitsPerPixel(a->space));
206 }
207}
208
209/* Yes, this isn't the fastest it could be, but it works nicely */
210static int BE_AddMode(_THIS, int index, unsigned int w, unsigned int h)
211{
212 SDL_Rect *mode;
213 int i;
214 int next_mode;
215
216 /* Check to see if we already have this mode */
217 if ( SDL_nummodes[index] > 0 ) {
218 for ( i=SDL_nummodes[index]-1; i >= 0; --i ) {
219 mode = SDL_modelist[index][i];
220 if ( (mode->w == w) && (mode->h == h) ) {
221#ifdef BWINDOW_DEBUG
222 fprintf(stderr, "We already have mode %dx%d at %d bytes per pixel\n", w, h, index+1);
223#endif
224 return(0);
225 }
226 }
227 }
228
229 /* Set up the new video mode rectangle */
230 mode = (SDL_Rect *)SDL_malloc(sizeof *mode);
231 if ( mode == NULL ) {
232 SDL_OutOfMemory();
233 return(-1);
234 }
235 mode->x = 0;
236 mode->y = 0;
237 mode->w = w;
238 mode->h = h;
239#ifdef BWINDOW_DEBUG
240 fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h, index+1);
241#endif
242
243 /* Allocate the new list of modes, and fill in the new mode */
244 next_mode = SDL_nummodes[index];
245 SDL_modelist[index] = (SDL_Rect **)
246 SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *));
247 if ( SDL_modelist[index] == NULL ) {
248 SDL_OutOfMemory();
249 SDL_nummodes[index] = 0;
250 SDL_free(mode);
251 return(-1);
252 }
253 SDL_modelist[index][next_mode] = mode;
254 SDL_modelist[index][next_mode+1] = NULL;
255 SDL_nummodes[index]++;
256
257 return(0);
258}
259
260int BE_VideoInit(_THIS, SDL_PixelFormat *vformat)
261{
262 display_mode *modes;
263 uint32 i, nmodes;
264 int bpp;
265 BRect bounds;
266
267 /* Initialize the Be Application for appserver interaction */
268 if ( SDL_InitBeApp() < 0 ) {
269 return(-1);
270 }
271
272 /* It is important that this be created after SDL_InitBeApp() */
273 BScreen bscreen;
274
275 /* Save the current display mode */
276 bscreen.GetMode(&saved_mode);
277 _this->info.current_w = saved_mode.virtual_width;
278 _this->info.current_h = saved_mode.virtual_height;
279
280 /* Determine the screen depth */
281 vformat->BitsPerPixel = ColorSpaceToBitsPerPixel(bscreen.ColorSpace());
282 if ( vformat->BitsPerPixel == 0 ) {
283 SDL_SetError("Unknown BScreen colorspace: 0x%x",
284 bscreen.ColorSpace());
285 return(-1);
286 }
287
288 /* Get the video modes we can switch to in fullscreen mode */
289 bscreen.GetModeList(&modes, &nmodes);
290 SDL_qsort(modes, nmodes, sizeof *modes, CompareModes);
291 for ( i=0; i<nmodes; ++i ) {
292 bpp = ColorSpaceToBitsPerPixel(modes[i].space);
293 //if ( bpp != 0 ) { // There are bugs in changing colorspace
294 if ( modes[i].space == saved_mode.space ) {
295 BE_AddMode(_this, ((bpp+7)/8)-1,
296 modes[i].virtual_width,
297 modes[i].virtual_height);
298 }
299 }
300
301 /* Create the window and view */
302 bounds.top = 0; bounds.left = 0;
303 bounds.right = BEOS_HIDDEN_SIZE;
304 bounds.bottom = BEOS_HIDDEN_SIZE;
305 SDL_Win = new SDL_BWin(bounds);
306
307#if SDL_VIDEO_OPENGL
308 /* testgl application doesn't load library, just tries to load symbols */
309 /* is it correct? if so we have to load library here */
310 BE_GL_LoadLibrary(_this, NULL);
311#endif
312
313 /* Create the clear cursor */
314 SDL_BlankCursor = BE_CreateWMCursor(_this, blank_cdata, blank_cmask,
315 BLANK_CWIDTH, BLANK_CHEIGHT, BLANK_CHOTX, BLANK_CHOTY);
316
317 /* Fill in some window manager capabilities */
318 _this->info.wm_available = 1;
319
320 /* We're done! */
321 return(0);
322}
323
324/* We support any dimension at our bit-depth */
325SDL_Rect **BE_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
326{
327 SDL_Rect **modes;
328
329 modes = ((SDL_Rect **)0);
330 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
331 modes = SDL_modelist[((format->BitsPerPixel+7)/8)-1];
332 } else {
333 if ( format->BitsPerPixel ==
334 _this->screen->format->BitsPerPixel ) {
335 modes = ((SDL_Rect **)-1);
336 }
337 }
338 return(modes);
339}
340
341/* Various screen update functions available */
342static void BE_NormalUpdate(_THIS, int numrects, SDL_Rect *rects);
343
344
345/* Find the closest display mode for fullscreen */
346static bool BE_FindClosestFSMode(_THIS, int width, int height, int bpp,
347 display_mode *mode)
348{
349 BScreen bscreen;
350 uint32 i, nmodes;
351 SDL_Rect **modes;
352 display_mode *dmodes;
353 display_mode current;
354 float current_refresh;
355 bscreen.GetMode(&current);
356 current_refresh = (1000 * current.timing.pixel_clock) /
357 (current.timing.h_total * current.timing.v_total);
358
359 modes = SDL_modelist[((bpp+7)/8)-1];
360
361 // find end of list (lowest-resolution mode; modes are ordered
362 // highest-to-lowest).
363 i = 0; while(modes[i]) i++;
364 if (!i) return false; // what? no modes at all?
365
366 // find first mode with resolution >= requested in both dimensions
367 for (--i; i >= 0; --i)
368 {
369 if (modes[i]->w >= width && modes[i]->h >= height)
370 break;
371 }
372
373 // unable to find any mode with that high a resolution!
374 if (i < 0)
375 return false;
376
377 width = modes[i]->w;
378 height = modes[i]->h;
379
380 bscreen.GetModeList(&dmodes, &nmodes);
381 for ( i = 0; i < nmodes; ++i ) {
382 if ( (bpp == ColorSpaceToBitsPerPixel(dmodes[i].space)) &&
383 (width == dmodes[i].virtual_width) &&
384 (height == dmodes[i].virtual_height) ) {
385 break;
386 }
387 }
388 if ( i != nmodes ) {
389 *mode = dmodes[i];
390 if ((mode->virtual_width <= current.virtual_width) &&
391 (mode->virtual_height <= current.virtual_height)) {
392 float new_refresh = (1000 * mode->timing.pixel_clock) /
393 (mode->timing.h_total * mode->timing.v_total);
394 if (new_refresh < current_refresh) {
395 mode->timing.pixel_clock = (uint32)((mode->timing.h_total * mode->timing.v_total)
396 * current_refresh / 1000);
397 }
398 }
399 return true;
400 } else {
401 return false;
402 }
403}
404
405static int BE_SetFullScreen(_THIS, SDL_Surface *screen, int fullscreen)
406{
407 // printf("SetFullScreen(%d)\n", fullscreen);
408 BScreen bscreen;
409
410 // SetFullSscreen() does not work as expected if called in a window
411 // that was never shown. This is probably a bug in the Haiku Game Kit that needs
412 // to be investigated.
413 if (SDL_Win->Lock()) {
414 // Show our window.
415 SDL_Win->Show();
416 }
417
418 if (SDL_Win->IsLocked()) {
419 // Unlock the window if it was locked. This is needed as only the
420 // first call to Show() unlocks the looper. All other calls to it
421 // will not.
422 SDL_Win->Unlock();
423 }
424
425 int width = screen->w;
426 int height = screen->h;
427
428 if (fullscreen) {
429 // Set resolution to the closest available one that matches the
430 // current SDL resolution.
431 display_mode mode;
432 bscreen.GetMode(&mode);
433
434 int bpp = screen->format->BitsPerPixel;
435 if (bpp != ColorSpaceToBitsPerPixel(mode.space) ||
436 width != mode.virtual_width || height != mode.virtual_height) {
437 if(BE_FindClosestFSMode(_this, width, height, bpp, &mode)) {
438 bscreen.SetMode(&mode);
439 } else {
440 // printf("Could not set new mode.\n");
441 return(0);
442 }
443 }
444 } else {
445 // Reset to the previous known resolution as we are now in window
446 // mode.
447 bscreen.SetMode(&saved_mode);
448 }
449
450 // Effectivelly set/reset full screen mode. If we are already in
451 // full screen mode, we reset back to windowed mode first so the
452 // window can resize when going fullscreen.
453 // if (fullscreen)
454 // printf("Going fullscreen\n");
455 // else
456 // printf("Going windowed\n");
457 SDL_Win->SetFullScreen(fullscreen);
458
459 // Calculate offsets for centering the window (in window mode) and for
460 // dentering the bitmap (in full screen mode).
461 BRect bounds = bscreen.Frame();
462 bounds.PrintToStream();
463 int32 cx = (bounds.IntegerWidth() - width)/2;
464 int32 cy = (bounds.IntegerHeight() - height)/2;
465
466 // printf ("cx = %d, cy = %d\n", cx, cy);
467 if (!SDL_Win->IsFullScreen()) {
468 // printf("Doing not fullscreen stuff.\n");
469 // We are not in full screen mode, so we want to change the window
470 // size to match the resolution in SDL.
471 SDL_Win->ResizeTo(width, height);
472
473 // And also center the window and reset the drawing offset.
474 SDL_Win->MoveTo(cx, cy);
475 SDL_Win->SetXYOffset(0, 0);
476 } else {
477 // printf("Doing fullscreen stuff.");
478 // Center the bitmap whenever we are in full screen mode.
479 SDL_Win->SetXYOffset(cx, cy);
480 }
481
482 // Set relevant internal SDL screen flags.
483 if (SDL_Win->IsFullScreen()) {
484 screen->flags |= SDL_FULLSCREEN;
485 } else {
486 screen->flags &= ~SDL_FULLSCREEN;
487 }
488
489 return(1);
490}
491
492static int BE_ToggleFullScreen(_THIS, int fullscreen)
493{
494 return BE_SetFullScreen(_this, _this->screen, fullscreen);
495}
496
497/* FIXME: check return values and cleanup here */
498SDL_Surface *BE_SetVideoMode(_THIS, SDL_Surface *current,
499 int width, int height, int bpp, Uint32 flags)
500{
501 BScreen bscreen;
502 BBitmap *bbitmap;
503 BRect bounds;
504 Uint32 gl_flags = 0;
505
506 /* Only RGB works on r5 currently */
507 gl_flags = BGL_RGB;
508 if (_this->gl_config.double_buffer)
509 gl_flags |= BGL_DOUBLE;
510 else
511 gl_flags |= BGL_SINGLE;
512 if (_this->gl_config.alpha_size > 0 || bpp == 32)
513 gl_flags |= BGL_ALPHA;
514 if (_this->gl_config.depth_size > 0)
515 gl_flags |= BGL_DEPTH;
516 if (_this->gl_config.stencil_size > 0)
517 gl_flags |= BGL_STENCIL;
518 if (_this->gl_config.accum_red_size > 0
519 || _this->gl_config.accum_green_size > 0
520 || _this->gl_config.accum_blue_size > 0
521 || _this->gl_config.accum_alpha_size > 0)
522 gl_flags |= BGL_ACCUM;
523
524 /* Create the view for this window, using found flags */
525 if ( SDL_Win->CreateView(flags, gl_flags) < 0 ) {
526 return(NULL);
527 }
528
529 current->flags = 0; /* Clear flags */
530 current->w = width;
531 current->h = height;
532 SDL_Win->SetType(B_TITLED_WINDOW);
533 if ( flags & SDL_NOFRAME ) {
534 current->flags |= SDL_NOFRAME;
535 SDL_Win->SetLook(B_NO_BORDER_WINDOW_LOOK);
536 } else {
537 if ( (flags & SDL_RESIZABLE) && !(flags & SDL_OPENGL) ) {
538 current->flags |= SDL_RESIZABLE;
539 /* We don't want opaque resizing (TM). :-) */
540 SDL_Win->SetFlags(B_OUTLINE_RESIZE);
541 } else {
542 SDL_Win->SetFlags(B_NOT_RESIZABLE|B_NOT_ZOOMABLE);
543 }
544 }
545
546 if ( flags & SDL_OPENGL ) {
547 current->flags |= SDL_OPENGL;
548 current->pitch = 0;
549 current->pixels = NULL;
550 _this->UpdateRects = NULL;
551 } else {
552 /* Create the BBitmap framebuffer */
553 bounds.top = 0; bounds.left = 0;
554 bounds.right = width-1;
555 bounds.bottom = height-1;
556 bbitmap = new BBitmap(bounds, bscreen.ColorSpace());
557 if ( ! bbitmap->IsValid() ) {
558 SDL_SetError("Couldn't create screen bitmap");
559 delete bbitmap;
560 return(NULL);
561 }
562 current->pitch = bbitmap->BytesPerRow();
563 current->pixels = (void *)bbitmap->Bits();
564 SDL_Win->SetBitmap(bbitmap);
565 _this->UpdateRects = BE_NormalUpdate;
566 }
567
568 /* Set the correct fullscreen mode */
569 BE_SetFullScreen(_this, current, flags & SDL_FULLSCREEN ? 1 : 0);
570
571 /* We're done */
572 return(current);
573}
574
575/* Update the current mouse state and position */
576void BE_UpdateMouse(_THIS)
577{
578 BPoint point;
579 uint32 buttons;
580
581 if ( SDL_Win->Lock() ) {
582 /* Get new input state, if still active */
583 if ( SDL_Win->IsActive() ) {
584 (SDL_Win->View())->GetMouse(&point, &buttons, true);
585 } else {
586 point.x = -1;
587 point.y = -1;
588 }
589 SDL_Win->Unlock();
590
591 if ( (point.x >= 0) && (point.x < SDL_VideoSurface->w) &&
592 (point.y >= 0) && (point.y < SDL_VideoSurface->h) ) {
593 SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
594 SDL_PrivateMouseMotion(0, 0,
595 (Sint16)point.x, (Sint16)point.y);
596 } else {
597 SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
598 }
599 }
600}
601
602/* We don't actually allow hardware surfaces other than the main one */
603static int BE_AllocHWSurface(_THIS, SDL_Surface *surface)
604{
605 return(-1);
606}
607static void BE_FreeHWSurface(_THIS, SDL_Surface *surface)
608{
609 return;
610}
611static int BE_LockHWSurface(_THIS, SDL_Surface *surface)
612{
613 return(0);
614}
615static void BE_UnlockHWSurface(_THIS, SDL_Surface *surface)
616{
617 return;
618}
619
620static void BE_NormalUpdate(_THIS, int numrects, SDL_Rect *rects)
621{
622 if ( SDL_Win->BeginDraw() ) {
623 int i;
624
625 for ( i=0; i<numrects; ++i ) {
626 BRect rect;
627
628 rect.top = rects[i].y;
629 rect.left = rects[i].x;
630 rect.bottom = rect.top+rects[i].h-1;
631 rect.right = rect.left+rects[i].w-1;
632 SDL_Win->DrawAsync(rect);
633 }
634 SDL_Win->EndDraw();
635 }
636}
637
638#if SDL_VIDEO_OPENGL
639/* Passing a NULL path means load pointers from the application */
640int BE_GL_LoadLibrary(_THIS, const char *path)
641{
642 if (path == NULL) {
643 if (_this->gl_config.dll_handle == NULL) {
644 image_info info;
645 int32 cookie = 0;
646 while (get_next_image_info(0,&cookie,&info) == B_OK) {
647 void *location = NULL;
648#ifdef __HAIKU__
649 if (get_image_symbol(info.id,"glBegin",B_SYMBOL_TYPE_ANY,&location) == B_OK) { // This is how it actually works in Haiku
650#else
651 if (get_image_symbol((image_id)cookie,"glBegin",B_SYMBOL_TYPE_ANY,&location) == B_OK) { // I don't know if that *did* work in BeOS
652#endif
653 _this->gl_config.dll_handle = (void*)info.id;
654 _this->gl_config.driver_loaded = 1;
655 SDL_strlcpy(_this->gl_config.driver_path, "libGL.so", SDL_arraysize(_this->gl_config.driver_path));
656 }
657 }
658 }
659 } else {
660 /*
661 FIXME None of BeOS libGL.so implementations have exported functions
662 to load BGLView, which should be reloaded from new lib.
663 So for now just "load" linked libGL.so :(
664 */
665 if (_this->gl_config.dll_handle == NULL) {
666 return BE_GL_LoadLibrary(_this, NULL);
667 }
668
669 /* Unload old first */
670 /*if (_this->gl_config.dll_handle != NULL) {*/
671 /* Do not try to unload application itself (if LoadLibrary was called before with NULL ;) */
672 /* image_info info;
673 if (get_image_info((image_id)_this->gl_config.dll_handle, &info) == B_OK) {
674 if (info.type != B_APP_IMAGE) {
675 unload_add_on((image_id)_this->gl_config.dll_handle);
676 }
677 }
678
679 }
680
681 if ((_this->gl_config.dll_handle = (void*)load_add_on(path)) != (void*)B_ERROR) {
682 _this->gl_config.driver_loaded = 1;
683 SDL_strlcpy(_this->gl_config.driver_path, path, SDL_arraysize(_this->gl_config.driver_path));
684 }*/
685 }
686
687 if (_this->gl_config.dll_handle != NULL) {
688 return 0;
689 } else {
690 _this->gl_config.dll_handle = NULL;
691 _this->gl_config.driver_loaded = 0;
692 *_this->gl_config.driver_path = '\0';
693 return -1;
694 }
695}
696
697void* BE_GL_GetProcAddress(_THIS, const char *proc)
698{
699 if (_this->gl_config.dll_handle != NULL) {
700 void *location = NULL;
701 status_t err;
702 if ((err = get_image_symbol((image_id)_this->gl_config.dll_handle, proc, B_SYMBOL_TYPE_ANY, &location)) == B_OK) {
703 return location;
704 } else {
705 SDL_SetError("Couldn't find OpenGL symbol");
706 return NULL;
707 }
708 } else {
709 SDL_SetError("OpenGL library not loaded");
710 return NULL;
711 }
712}
713
714int BE_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value)
715{
716 /*
717 FIXME? Right now BE_GL_GetAttribute shouldn't be called between glBegin() and glEnd() - it doesn't use "cached" values
718 */
719 switch (attrib)
720 {
721 case SDL_GL_RED_SIZE:
722 glGetIntegerv(GL_RED_BITS, (GLint*)value);
723 break;
724 case SDL_GL_GREEN_SIZE:
725 glGetIntegerv(GL_GREEN_BITS, (GLint*)value);
726 break;
727 case SDL_GL_BLUE_SIZE:
728 glGetIntegerv(GL_BLUE_BITS, (GLint*)value);
729 break;
730 case SDL_GL_ALPHA_SIZE:
731 glGetIntegerv(GL_ALPHA_BITS, (GLint*)value);
732 break;
733 case SDL_GL_DOUBLEBUFFER:
734 glGetBooleanv(GL_DOUBLEBUFFER, (GLboolean*)value);
735 break;
736 case SDL_GL_BUFFER_SIZE:
737 int v;
738 glGetIntegerv(GL_RED_BITS, (GLint*)&v);
739 *value = v;
740 glGetIntegerv(GL_GREEN_BITS, (GLint*)&v);
741 *value += v;
742 glGetIntegerv(GL_BLUE_BITS, (GLint*)&v);
743 *value += v;
744 glGetIntegerv(GL_ALPHA_BITS, (GLint*)&v);
745 *value += v;
746 break;
747 case SDL_GL_DEPTH_SIZE:
748 glGetIntegerv(GL_DEPTH_BITS, (GLint*)value); /* Mesa creates 16 only? r5 always 32 */
749 break;
750 case SDL_GL_STENCIL_SIZE:
751 glGetIntegerv(GL_STENCIL_BITS, (GLint*)value);
752 break;
753 case SDL_GL_ACCUM_RED_SIZE:
754 glGetIntegerv(GL_ACCUM_RED_BITS, (GLint*)value);
755 break;
756 case SDL_GL_ACCUM_GREEN_SIZE:
757 glGetIntegerv(GL_ACCUM_GREEN_BITS, (GLint*)value);
758 break;
759 case SDL_GL_ACCUM_BLUE_SIZE:
760 glGetIntegerv(GL_ACCUM_BLUE_BITS, (GLint*)value);
761 break;
762 case SDL_GL_ACCUM_ALPHA_SIZE:
763 glGetIntegerv(GL_ACCUM_ALPHA_BITS, (GLint*)value);
764 break;
765 case SDL_GL_STEREO:
766 case SDL_GL_MULTISAMPLEBUFFERS:
767 case SDL_GL_MULTISAMPLESAMPLES:
768 default:
769 *value=0;
770 return(-1);
771 }
772 return 0;
773}
774
775int BE_GL_MakeCurrent(_THIS)
776{
777 /* FIXME: should we glview->unlock and then glview->lock()? */
778 return 0;
779}
780
781void BE_GL_SwapBuffers(_THIS)
782{
783 SDL_Win->SwapBuffers();
784}
785#endif
786
787/* Is the system palette settable? */
788int BE_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
789{
790 int i;
791 SDL_Palette *palette;
792 const color_map *cmap = BScreen().ColorMap();
793
794 /* Get the screen colormap */
795 palette = _this->screen->format->palette;
796 for ( i=0; i<256; ++i ) {
797 palette->colors[i].r = cmap->color_list[i].red;
798 palette->colors[i].g = cmap->color_list[i].green;
799 palette->colors[i].b = cmap->color_list[i].blue;
800 }
801 return(0);
802}
803
804void BE_VideoQuit(_THIS)
805{
806 int i, j;
807
808 SDL_Win->Quit();
809 SDL_Win = NULL;
810
811 if ( SDL_BlankCursor != NULL ) {
812 BE_FreeWMCursor(_this, SDL_BlankCursor);
813 SDL_BlankCursor = NULL;
814 }
815 for ( i=0; i<NUM_MODELISTS; ++i ) {
816 if ( SDL_modelist[i] ) {
817 for ( j=0; SDL_modelist[i][j]; ++j ) {
818 SDL_free(SDL_modelist[i][j]);
819 }
820 SDL_free(SDL_modelist[i]);
821 SDL_modelist[i] = NULL;
822 }
823 }
824 /* Restore the original video mode */
825 if ( _this->screen ) {
826 if ( (_this->screen->flags&SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
827 BScreen bscreen;
828 bscreen.SetMode(&saved_mode);
829 }
830 _this->screen->pixels = NULL;
831 }
832
833#if SDL_VIDEO_OPENGL
834 if (_this->gl_config.dll_handle != NULL)
835 unload_add_on((image_id)_this->gl_config.dll_handle);
836#endif
837
838 SDL_QuitBeApp();
839}
840
841}; /* Extern C */
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_syswm.cc b/apps/plugins/sdl/src/video/bwindow/SDL_syswm.cc
deleted file mode 100644
index df801005d4..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_syswm.cc
+++ /dev/null
@@ -1,92 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_BWin.h"
25
26extern "C" {
27#include "SDL_syswm_c.h"
28#include "SDL_error.h"
29#include "../SDL_cursor_c.h"
30
31void BE_SetWMCaption(_THIS, const char *title, const char *icon)
32{
33 SDL_Win->SetTitle(title);
34}
35
36int BE_IconifyWindow(_THIS)
37{
38 SDL_Win->Minimize(true);
39 return 1;
40}
41
42SDL_GrabMode BE_GrabInput(_THIS, SDL_GrabMode mode)
43{
44 if ( mode == SDL_GRAB_OFF ) {
45// be_app->ShowCursor();
46 if ( !(SDL_cursorstate & CURSOR_VISIBLE) ) {
47 /* BeSman: Jan 2, 2006
48 must be leaving relative mode, move mouse from
49 center of window to where it belongs ... */
50 BPoint pt;
51 int x, y;
52 SDL_GetMouseState(&x,&y);
53 pt.x = x;
54 pt.y = y;
55 SDL_Win->Lock();
56 SDL_Win->ConvertToScreen(&pt);
57 SDL_Win->Unlock();
58 set_mouse_position((int)pt.x, (int)pt.y);
59 }
60 } else {
61// be_app->HideCursor();
62 if ( !(SDL_cursorstate & CURSOR_VISIBLE) ) {
63 /* BeSman: Jan 2, 2006
64 must be entering relative mode, get ready by
65 moving mouse to center of window ... */
66 BPoint pt;
67 pt.x = (SDL_VideoSurface->w/2);
68 pt.y = (SDL_VideoSurface->h/2);
69 SDL_Win->Lock();
70 SDL_Win->ConvertToScreen(&pt);
71 SDL_Win->Unlock();
72 set_mouse_position((int)pt.x, (int)pt.y);
73 }
74 }
75 return(mode);
76}
77
78int BE_GetWMInfo(_THIS, SDL_SysWMinfo *info)
79{
80 if (info->version.major <= SDL_MAJOR_VERSION)
81 {
82 return 1;
83 }
84 else
85 {
86 SDL_SetError("Application not compiled with SDL %d.%d\n",
87 SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
88 return -1;
89 }
90}
91
92}; /* Extern C */
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_syswm_c.h b/apps/plugins/sdl/src/video/bwindow/SDL_syswm_c.h
deleted file mode 100644
index c1285c8ec2..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_syswm_c.h
+++ /dev/null
@@ -1,32 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_syswm.h"
25#include "SDL_lowvideo.h"
26
27
28/* Functions to be exported */
29extern void BE_SetWMCaption(_THIS, const char *title, const char *icon);
30extern int BE_IconifyWindow(_THIS);
31extern int BE_GetWMInfo(_THIS, SDL_SysWMinfo *info);
32extern SDL_GrabMode BE_GrabInput(_THIS, SDL_GrabMode mode);
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_sysyuv.cc b/apps/plugins/sdl/src/video/bwindow/SDL_sysyuv.cc
deleted file mode 100644
index 7c71b006e4..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_sysyuv.cc
+++ /dev/null
@@ -1,314 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the BeOS version of SDL YUV video overlays */
25
26#include "SDL_video.h"
27#include "SDL_sysyuv.h"
28#include "../SDL_yuvfuncs.h"
29
30extern "C" {
31
32/* The functions used to manipulate software video overlays */
33static struct private_yuvhwfuncs be_yuvfuncs =
34{
35 BE_LockYUVOverlay,
36 BE_UnlockYUVOverlay,
37 BE_DisplayYUVOverlay,
38 BE_FreeYUVOverlay
39};
40
41BBitmap * BE_GetOverlayBitmap(BRect bounds, color_space cs) {
42 BBitmap *bbitmap;
43 bbitmap = new BBitmap(bounds,B_BITMAP_WILL_OVERLAY,cs);
44 if (!bbitmap || bbitmap->InitCheck() != B_OK) {
45 delete bbitmap;
46 return 0;
47 }
48 overlay_restrictions r;
49 bbitmap->GetOverlayRestrictions(&r);
50 uint32 width = bounds.IntegerWidth() + 1;
51 uint32 height = bounds.IntegerHeight() + 1;
52 uint32 width_padding = 0;
53 uint32 height_padding = 0;
54 if ((r.source.horizontal_alignment != 0) ||
55 (r.source.vertical_alignment != 0)) {
56 delete bbitmap;
57 return 0;
58 }
59 if (r.source.width_alignment != 0) {
60 uint32 aligned_width = r.source.width_alignment + 1;
61 if (width % aligned_width > 0) {
62 width_padding = aligned_width - width % aligned_width;
63 }
64 }
65 if (r.source.height_alignment != 0) {
66 uint32 aligned_height = r.source.height_alignment + 1;
67 if (height % aligned_height > 0) {
68 fprintf(stderr,"GetOverlayBitmap failed height alignment\n");
69 fprintf(stderr,"- height = %lu, aligned_height = %lu\n",height,aligned_height);
70 delete bbitmap;
71 return 0;
72 }
73 }
74 if ((r.source.min_width > width) ||
75 (r.source.min_height > height) ||
76 (r.source.max_width < width) ||
77 (r.source.max_height < height)) {
78 fprintf(stderr,"GetOverlayBitmap failed bounds tests\n");
79 delete bbitmap;
80 return 0;
81 }
82 if ((width_padding != 0) || (height_padding != 0)) {
83 delete bbitmap;
84 bounds.Set(bounds.left,bounds.top,bounds.right+width_padding,bounds.bottom+height_padding);
85 bbitmap = new BBitmap(bounds,B_BITMAP_WILL_OVERLAY,cs);
86 if (!bbitmap || bbitmap->InitCheck() != B_OK) {
87 fprintf(stderr,"GetOverlayBitmap failed late\n");
88 delete bbitmap;
89 return 0;
90 }
91 }
92 return bbitmap;
93}
94
95// See <GraphicsDefs.h> [btw: Cb=U, Cr=V]
96// See also http://www.fourcc.org/indexyuv.htm
97color_space convert_color_space(Uint32 format) {
98 switch (format) {
99 case SDL_YV12_OVERLAY:
100 return B_YUV9;
101 case SDL_IYUV_OVERLAY:
102 return B_YUV12;
103 case SDL_YUY2_OVERLAY:
104 return B_YCbCr422;
105 case SDL_UYVY_OVERLAY:
106 return B_YUV422;
107 case SDL_YVYU_OVERLAY: // not supported on beos?
108 return B_NO_COLOR_SPACE;
109 default:
110 return B_NO_COLOR_SPACE;
111 }
112}
113
114// See SDL_video.h
115int count_planes(Uint32 format) {
116 switch (format) {
117 case SDL_YV12_OVERLAY:
118 case SDL_IYUV_OVERLAY:
119 return 3;
120 case SDL_YUY2_OVERLAY:
121 case SDL_UYVY_OVERLAY:
122 case SDL_YVYU_OVERLAY:
123 return 1;
124 default:
125 return 0;
126 }
127}
128
129SDL_Overlay *BE_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display) {
130 SDL_Overlay* overlay;
131 struct private_yuvhwdata* hwdata;
132 BBitmap *bbitmap;
133 int planes;
134 BRect bounds;
135 color_space cs;
136
137 /* find the appropriate BeOS colorspace descriptor */
138 cs = convert_color_space(format);
139 if (cs == B_NO_COLOR_SPACE)
140 {
141 return NULL;
142 }
143
144 /* count planes */
145 planes = count_planes(format);
146 if (planes == 0)
147 {
148 return NULL;
149 }
150 /* TODO: figure out planar modes, if anyone cares */
151 if (planes == 3)
152 {
153 return NULL;
154 }
155
156 /* Create the overlay structure */
157 overlay = (SDL_Overlay*)SDL_calloc(1, sizeof(SDL_Overlay));
158
159 if (overlay == NULL)
160 {
161 SDL_OutOfMemory();
162 return NULL;
163 }
164
165 /* Fill in the basic members */
166 overlay->format = format;
167 overlay->w = width;
168 overlay->h = height;
169 overlay->hwdata = NULL;
170
171 /* Set up the YUV surface function structure */
172 overlay->hwfuncs = &be_yuvfuncs;
173
174 /* Create the pixel data and lookup tables */
175 hwdata = (struct private_yuvhwdata*)SDL_calloc(1, sizeof(struct private_yuvhwdata));
176
177 if (hwdata == NULL)
178 {
179 SDL_OutOfMemory();
180 SDL_FreeYUVOverlay(overlay);
181 return NULL;
182 }
183
184 overlay->hwdata = hwdata;
185 overlay->hwdata->display = display;
186 overlay->hwdata->bview = NULL;
187 overlay->hwdata->bbitmap = NULL;
188 overlay->hwdata->locked = 0;
189
190 /* Create the BBitmap framebuffer */
191 bounds.top = 0; bounds.left = 0;
192 bounds.right = width-1;
193 bounds.bottom = height-1;
194
195 BView * bview = new BView(bounds,"overlay",B_FOLLOW_NONE,B_WILL_DRAW);
196 if (!bview) {
197 SDL_OutOfMemory();
198 SDL_FreeYUVOverlay(overlay);
199 return NULL;
200 }
201 overlay->hwdata->bview = bview;
202 overlay->hwdata->first_display = true;
203 bview->Hide();
204
205 bbitmap = BE_GetOverlayBitmap(bounds,cs);
206 if (!bbitmap) {
207 overlay->hwdata->bbitmap = NULL;
208 SDL_FreeYUVOverlay(overlay);
209 return NULL;
210 }
211 overlay->hwdata->bbitmap = bbitmap;
212
213 overlay->planes = planes;
214 overlay->pitches = (Uint16*)SDL_calloc(overlay->planes, sizeof(Uint16));
215 overlay->pixels = (Uint8**)SDL_calloc(overlay->planes, sizeof(Uint8*));
216 if (!overlay->pitches || !overlay->pixels)
217 {
218 SDL_OutOfMemory();
219 SDL_FreeYUVOverlay(overlay);
220 return(NULL);
221 }
222
223 overlay->pitches[0] = bbitmap->BytesPerRow();
224 overlay->pixels[0] = (Uint8 *)bbitmap->Bits();
225 overlay->hw_overlay = 1;
226
227 if (SDL_Win->LockWithTimeout(1000000) != B_OK) {
228 SDL_FreeYUVOverlay(overlay);
229 return(NULL);
230 }
231 BView * view = SDL_Win->View();
232 view->AddChild(bview);
233 rgb_color key;
234 bview->SetViewOverlay(bbitmap,bounds,bview->Bounds(),&key,B_FOLLOW_ALL,
235 B_OVERLAY_FILTER_HORIZONTAL|B_OVERLAY_FILTER_VERTICAL);
236 bview->SetViewColor(key);
237 bview->Flush();
238 SDL_Win->Unlock();
239
240 current_overlay=overlay;
241
242 return overlay;
243}
244
245int BE_LockYUVOverlay(_THIS, SDL_Overlay* overlay)
246{
247 if (overlay == NULL)
248 {
249 return 0;
250 }
251
252 overlay->hwdata->locked = 1;
253 return 0;
254}
255
256void BE_UnlockYUVOverlay(_THIS, SDL_Overlay* overlay)
257{
258 if (overlay == NULL)
259 {
260 return;
261 }
262
263 overlay->hwdata->locked = 0;
264}
265
266int BE_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect *dst)
267{
268 if ((overlay == NULL) || (overlay->hwdata==NULL)
269 || (overlay->hwdata->bview==NULL) || (SDL_Win->View() == NULL))
270 {
271 return -1;
272 }
273 if (SDL_Win->LockWithTimeout(50000) != B_OK) {
274 return 0;
275 }
276 BView * bview = overlay->hwdata->bview;
277 if (SDL_Win->IsFullScreen()) {
278 int left,top;
279 SDL_Win->GetXYOffset(left,top);
280 bview->MoveTo(left+dst->x,top+dst->y);
281 } else {
282 bview->MoveTo(dst->x,dst->y);
283 }
284 bview->ResizeTo(dst->w,dst->h);
285 bview->Flush();
286 if (overlay->hwdata->first_display) {
287 bview->Show();
288 overlay->hwdata->first_display = false;
289 }
290 SDL_Win->Unlock();
291
292 return 0;
293}
294
295void BE_FreeYUVOverlay(_THIS, SDL_Overlay *overlay)
296{
297 if (overlay == NULL)
298 {
299 return;
300 }
301
302 if (overlay->hwdata == NULL)
303 {
304 return;
305 }
306
307 current_overlay=NULL;
308
309 delete overlay->hwdata->bbitmap;
310
311 SDL_free(overlay->hwdata);
312}
313
314}; // extern "C"
diff --git a/apps/plugins/sdl/src/video/bwindow/SDL_sysyuv.h b/apps/plugins/sdl/src/video/bwindow/SDL_sysyuv.h
deleted file mode 100644
index fb5961c9d8..0000000000
--- a/apps/plugins/sdl/src/video/bwindow/SDL_sysyuv.h
+++ /dev/null
@@ -1,73 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24
25#ifndef __SDL_SYS_YUV_H__
26#define __SDL_SYS_YUV_H__
27
28/* This is the BeOS implementation of YUV video overlays */
29
30#include "SDL_video.h"
31#include "SDL_lowvideo.h"
32
33extern "C" {
34
35struct private_yuvhwdata
36{
37/* FRAMEDATA* CurrentFrameData;
38 FRAMEDATA* FrameData0;
39 FRAMEDATA* FrameData1;
40 PgScalerProps_t props;
41 PgScalerCaps_t caps;
42 PgVideoChannel_t* channel;
43 PhArea_t CurrentViewPort;
44 PhPoint_t CurrentWindowPos;
45 long format;
46 int scaler_on;
47 int current;
48 long YStride;
49 long VStride;
50 long UStride;
51 int ischromakey;
52 long chromakey;
53 int forcedredraw;
54 unsigned long State;
55 long flags;
56*/
57 SDL_Surface *display;
58 BView *bview;
59 bool first_display;
60 BBitmap *bbitmap;
61 int locked;
62};
63
64extern BBitmap * BE_GetOverlayBitmap(BRect bounds, color_space cs);
65extern SDL_Overlay* BE_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface* display);
66extern int BE_LockYUVOverlay(_THIS, SDL_Overlay* overlay);
67extern void BE_UnlockYUVOverlay(_THIS, SDL_Overlay* overlay);
68extern int BE_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect* dst);
69extern void BE_FreeYUVOverlay(_THIS, SDL_Overlay* overlay);
70
71};
72
73#endif /* __SDL_PH_YUV_H__ */
diff --git a/apps/plugins/sdl/src/video/caca/SDL_cacaevents.c b/apps/plugins/sdl/src/video/caca/SDL_cacaevents.c
deleted file mode 100644
index 723b1ddef9..0000000000
--- a/apps/plugins/sdl/src/video/caca/SDL_cacaevents.c
+++ /dev/null
@@ -1,101 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23#ifdef SAVE_RCSID
24static char rcsid =
25 "@(#) $Id: libsdl-1.2.11-libcaca.patch,v 1.1 2006/09/18 16:06:06 mr_bones_ Exp $";
26#endif
27
28#include <stdio.h>
29
30#include <caca.h>
31#ifdef CACA_API_VERSION_1
32#include <caca0.h>
33#endif
34
35#include "SDL.h"
36#include "../../events/SDL_sysevents.h"
37#include "../../events/SDL_events_c.h"
38#include "SDL_cacavideo.h"
39#include "SDL_cacaevents_c.h"
40
41void Caca_PumpEvents(_THIS)
42{
43 int posted = 0;
44 int event;
45 SDL_keysym keysym;
46
47 if( ! this->screen ) /* Wait till we got the screen initialised */
48 return;
49
50 do {
51 posted = 0;
52
53 /* Get libcaca event */
54 SDL_mutexP(Caca_mutex);
55 event = caca_get_event(CACA_EVENT_ANY);
56 SDL_mutexV(Caca_mutex);
57
58 if ( event & (CACA_EVENT_KEY_PRESS | CACA_EVENT_KEY_RELEASE)) {
59 int key;
60 switch ( event & 0xffffff )
61 {
62 case CACA_KEY_LEFT: key = SDLK_LEFT; break;
63 case CACA_KEY_RIGHT: key = SDLK_RIGHT; break;
64 case CACA_KEY_UP: key = SDLK_UP; break;
65 case CACA_KEY_DOWN: key = SDLK_DOWN; break;
66 default: key = event & 0xff; break;
67 }
68 /* Key pressed */
69/* printf("Key pressed: %d (%c)\n", key, key); */
70 keysym.scancode = key;
71 keysym.sym = key;
72 keysym.mod = KMOD_NONE;
73 keysym.unicode = 0;
74 if ( SDL_TranslateUNICODE ) {
75 keysym.unicode = key;
76 }
77 posted += SDL_PrivateKeyboard((event & CACA_EVENT_KEY_PRESS) ? SDL_PRESSED : SDL_RELEASED, &keysym);
78 }
79 else if ( event & (CACA_EVENT_MOUSE_PRESS | CACA_EVENT_MOUSE_RELEASE) ) {
80 /* FIXME: we currently ignore the button type! */
81 int button = event & 0x00ffffff;
82 if ( button > 3 ) {
83 button = 1;
84 }
85 posted += SDL_PrivateMouseButton((event & CACA_EVENT_MOUSE_PRESS) ? SDL_PRESSED : SDL_RELEASED, button, 0, 0);
86 }
87 else if ( event & CACA_EVENT_MOUSE_MOTION ) {
88 int new_x = 0, new_y = 0;
89 new_x = ((event & 0x00fff000) >> 12) * Caca_w / caca_get_width();
90 new_y = ((event & 0x00000fff) >> 0) * Caca_h / caca_get_height();
91 posted += SDL_PrivateMouseMotion(0, 0, new_x, new_y);
92 }
93 } while ( posted );
94}
95
96void Caca_InitOSKeymap(_THIS)
97{
98 return;
99}
100
101
diff --git a/apps/plugins/sdl/src/video/caca/SDL_cacaevents_c.h b/apps/plugins/sdl/src/video/caca/SDL_cacaevents_c.h
deleted file mode 100644
index 988c3b7cdf..0000000000
--- a/apps/plugins/sdl/src/video/caca/SDL_cacaevents_c.h
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23#ifdef SAVE_RCSID
24static char rcsid =
25 "@(#) $Id: libsdl-1.2.11-libcaca.patch,v 1.1 2006/09/18 16:06:06 mr_bones_ Exp $";
26#endif
27
28#include "SDL_cacavideo.h"
29
30/* Variables and functions exported by SDL_sysevents.c to other parts.
31 of the native video subsystem (SDL_sysvideo.c)
32*/
33extern void Caca_PumpEvents(_THIS);
34extern void Caca_InitOSKeymap(_THIS);
35
diff --git a/apps/plugins/sdl/src/video/caca/SDL_cacavideo.c b/apps/plugins/sdl/src/video/caca/SDL_cacavideo.c
deleted file mode 100644
index 59a070ce7a..0000000000
--- a/apps/plugins/sdl/src/video/caca/SDL_cacavideo.c
+++ /dev/null
@@ -1,304 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 2003 Sam Hocevar
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Hocevar
20 sam@zoy.org
21*/
22
23#ifdef SAVE_RCSID
24static char rcsid =
25 "@(#) $Id: libsdl-1.2.11-libcaca.patch,v 1.1 2006/09/18 16:06:06 mr_bones_ Exp $";
26#endif
27
28/* libcaca based SDL video driver implementation.
29*/
30
31#include <stdlib.h>
32#include <stdio.h>
33#include <string.h>
34#include <unistd.h>
35#include <sys/stat.h>
36
37
38#include "SDL.h"
39#include "SDL_error.h"
40#include "SDL_video.h"
41#include "SDL_mouse.h"
42#include "../SDL_sysvideo.h"
43#include "../SDL_pixels_c.h"
44#include "../../events/SDL_events_c.h"
45
46#include "SDL_cacavideo.h"
47#include "SDL_cacaevents_c.h"
48
49#include <caca.h>
50#ifdef CACA_API_VERSION_1
51#include <caca0.h>
52#endif
53
54/* Initialization/Query functions */
55static int Caca_VideoInit(_THIS, SDL_PixelFormat *vformat);
56static SDL_Rect **Caca_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
57static SDL_Surface *Caca_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
58static void Caca_VideoQuit(_THIS);
59
60/* Hardware surface functions */
61static int Caca_AllocHWSurface(_THIS, SDL_Surface *surface);
62static int Caca_LockHWSurface(_THIS, SDL_Surface *surface);
63static int Caca_FlipHWSurface(_THIS, SDL_Surface *surface);
64static void Caca_UnlockHWSurface(_THIS, SDL_Surface *surface);
65static void Caca_FreeHWSurface(_THIS, SDL_Surface *surface);
66
67/* Cache the VideoDevice struct */
68static struct SDL_VideoDevice *local_this;
69
70/* libcaca driver bootstrap functions */
71
72static int Caca_Available(void)
73{
74 return 1; /* Always available ! */
75}
76
77static void Caca_DeleteDevice(SDL_VideoDevice *device)
78{
79 free(device->hidden);
80 free(device);
81}
82static SDL_VideoDevice *Caca_CreateDevice(int devindex)
83{
84 SDL_VideoDevice *device;
85
86 /* Initialize all variables that we clean on shutdown */
87 device = (SDL_VideoDevice *)malloc(sizeof(SDL_VideoDevice));
88 if ( device ) {
89 memset(device, 0, (sizeof *device));
90 device->hidden = (struct SDL_PrivateVideoData *)
91 malloc((sizeof *device->hidden));
92 }
93 if ( (device == NULL) || (device->hidden == NULL) ) {
94 SDL_OutOfMemory();
95 if ( device ) {
96 free(device);
97 }
98 return(0);
99 }
100 memset(device->hidden, 0, (sizeof *device->hidden));
101
102 /* Set the function pointers */
103 device->VideoInit = Caca_VideoInit;
104 device->ListModes = Caca_ListModes;
105 device->SetVideoMode = Caca_SetVideoMode;
106 device->CreateYUVOverlay = NULL;
107 device->SetColors = NULL;
108 device->UpdateRects = NULL;
109 device->VideoQuit = Caca_VideoQuit;
110 device->AllocHWSurface = Caca_AllocHWSurface;
111 device->CheckHWBlit = NULL;
112 device->FillHWRect = NULL;
113 device->SetHWColorKey = NULL;
114 device->SetHWAlpha = NULL;
115 device->LockHWSurface = Caca_LockHWSurface;
116 device->UnlockHWSurface = Caca_UnlockHWSurface;
117 device->FlipHWSurface = NULL;
118 device->FreeHWSurface = Caca_FreeHWSurface;
119 device->SetCaption = NULL;
120 device->SetIcon = NULL;
121 device->IconifyWindow = NULL;
122 device->GrabInput = NULL;
123 device->GetWMInfo = NULL;
124 device->InitOSKeymap = Caca_InitOSKeymap;
125 device->PumpEvents = Caca_PumpEvents;
126
127 device->free = Caca_DeleteDevice;
128
129 return device;
130}
131
132VideoBootStrap CACA_bootstrap = {
133 "caca", "Color ASCII Art Library",
134 Caca_Available, Caca_CreateDevice
135};
136
137int Caca_VideoInit(_THIS, SDL_PixelFormat *vformat)
138{
139 int i;
140
141 /* Initialize all variables that we clean on shutdown */
142 for ( i=0; i<SDL_NUMMODES; ++i ) {
143 SDL_modelist[i] = malloc(sizeof(SDL_Rect));
144 SDL_modelist[i]->x = SDL_modelist[i]->y = 0;
145 }
146 /* Modes sorted largest to smallest */
147 SDL_modelist[0]->w = 1024; SDL_modelist[0]->h = 768;
148 SDL_modelist[1]->w = 800; SDL_modelist[1]->h = 600;
149 SDL_modelist[2]->w = 640; SDL_modelist[2]->h = 480;
150 SDL_modelist[3]->w = 320; SDL_modelist[3]->h = 400;
151 SDL_modelist[4]->w = 320; SDL_modelist[4]->h = 240;
152 SDL_modelist[5]->w = 320; SDL_modelist[5]->h = 200;
153 SDL_modelist[6] = NULL;
154
155 Caca_mutex = SDL_CreateMutex();
156
157 /* Initialize the library */
158 if ( caca_init() != 0 ) {
159 SDL_SetError("Unable to initialize libcaca");
160 return(-1);
161 }
162
163 /* Initialize private variables */
164 Caca_lastkey = 0;
165 Caca_bitmap = NULL;
166 Caca_buffer = NULL;
167
168 local_this = this;
169
170 /* Determine the screen depth (use default 8-bit depth) */
171 vformat->BitsPerPixel = 8;
172 vformat->BytesPerPixel = 1;
173
174 /* We're done! */
175 return(0);
176}
177
178SDL_Rect **Caca_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
179{
180 if(format->BitsPerPixel != 8)
181 return NULL;
182
183 if ( flags & SDL_FULLSCREEN ) {
184 return SDL_modelist;
185 } else {
186 return (SDL_Rect **) -1;
187 }
188}
189
190/* Various screen update functions available */
191static void Caca_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
192
193SDL_Surface *Caca_SetVideoMode(_THIS, SDL_Surface *current,
194 int width, int height, int bpp, Uint32 flags)
195{
196 if ( Caca_buffer ) {
197 free( Caca_buffer );
198 Caca_buffer = NULL;
199 }
200
201 if ( Caca_bitmap ) {
202 caca_free_bitmap( Caca_bitmap );
203 Caca_bitmap = NULL;
204 }
205
206 Caca_buffer = malloc(2 * ((width + 15) & ~15) * height);
207 if ( ! Caca_buffer ) {
208 SDL_SetError("Couldn't allocate buffer for requested mode");
209 return(NULL);
210 }
211
212 memset(Caca_buffer, 0, 2 * ((width + 15) & ~15) * height);
213
214 /* Allocate the new pixel format for the screen */
215 if ( ! SDL_ReallocFormat(current, 16, 0xf800, 0x07e0, 0x001f, 0) ) {
216 return(NULL);
217 }
218
219 /* Set up the new mode framebuffer */
220 current->flags = SDL_FULLSCREEN;
221 Caca_w = current->w = width;
222 Caca_h = current->h = height;
223 current->pitch = 2 * ((width + 15) & ~15);
224 current->pixels = Caca_buffer;
225
226 /* Create the libcaca bitmap */
227 Caca_bitmap = caca_create_bitmap( 16, width, height, current->pitch, 0xf800, 0x07e0, 0x001f, 0x0000 );
228 if ( ! Caca_bitmap ) {
229 SDL_SetError("Couldn't allocate libcaca bitmap");
230 return(NULL);
231 }
232
233 /* Set the blit function */
234 this->UpdateRects = Caca_DirectUpdate;
235
236 /* We're done */
237 return(current);
238}
239
240/* We don't actually allow hardware surfaces other than the main one */
241static int Caca_AllocHWSurface(_THIS, SDL_Surface *surface)
242{
243 return(-1);
244}
245static void Caca_FreeHWSurface(_THIS, SDL_Surface *surface)
246{
247 return;
248}
249
250/* We need to wait for vertical retrace on page flipped displays */
251static int Caca_LockHWSurface(_THIS, SDL_Surface *surface)
252{
253 /* TODO ? */
254 return(0);
255}
256static void Caca_UnlockHWSurface(_THIS, SDL_Surface *surface)
257{
258 return;
259}
260
261/* FIXME: How is this done with libcaca? */
262static int Caca_FlipHWSurface(_THIS, SDL_Surface *surface)
263{
264 SDL_mutexP(Caca_mutex);
265 caca_refresh();
266 SDL_mutexV(Caca_mutex);
267 return(0);
268}
269
270static void Caca_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
271{
272 SDL_mutexP(Caca_mutex);
273 caca_draw_bitmap( 0, 0, caca_get_width() - 1, caca_get_height() - 1,
274 Caca_bitmap, Caca_buffer );
275 caca_refresh();
276 SDL_mutexV(Caca_mutex);
277 return;
278}
279
280/* Note: If we are terminated, this could be called in the middle of
281 another SDL video routine -- notably UpdateRects.
282*/
283void Caca_VideoQuit(_THIS)
284{
285 int i;
286
287 /* Free video mode lists */
288 for ( i=0; i<SDL_NUMMODES; ++i ) {
289 if ( SDL_modelist[i] != NULL ) {
290 free(SDL_modelist[i]);
291 SDL_modelist[i] = NULL;
292 }
293 }
294
295 if ( Caca_bitmap ) {
296 caca_free_bitmap( Caca_bitmap );
297 Caca_bitmap = NULL;
298 }
299
300 caca_end();
301
302 SDL_DestroyMutex(Caca_mutex);
303}
304
diff --git a/apps/plugins/sdl/src/video/caca/SDL_cacavideo.h b/apps/plugins/sdl/src/video/caca/SDL_cacavideo.h
deleted file mode 100644
index 91fcc817af..0000000000
--- a/apps/plugins/sdl/src/video/caca/SDL_cacavideo.h
+++ /dev/null
@@ -1,76 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 2003 Sam Hocevar
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Hocevar
20 sam@zoy.org
21*/
22
23#ifdef SAVE_RCSID
24static char rcsid =
25 "@(#) $Id: libsdl-1.2.11-libcaca.patch,v 1.1 2006/09/18 16:06:06 mr_bones_ Exp $";
26#endif
27
28#ifndef _SDL_cacavideo_h
29#define _SDL_cacavideo_h
30
31#include "SDL_mouse.h"
32#include "../SDL_sysvideo.h"
33#include "SDL_mutex.h"
34
35#include <sys/time.h>
36#include <time.h>
37
38#include <caca.h>
39#ifdef CACA_API_VERSION_1
40#include <caca0.h>
41#endif
42
43/* Hidden "this" pointer for the video functions */
44#define _THIS SDL_VideoDevice *this
45
46#define SDL_NUMMODES 6
47
48/* Private display data */
49struct SDL_PrivateVideoData {
50 SDL_Rect *SDL_modelist[SDL_NUMMODES+1];
51 SDL_mutex *mutex;
52
53 struct caca_bitmap *bitmap;
54 void *buffer;
55 int w, h;
56
57 int lastkey;
58 struct timeval lasttime;
59};
60
61/* Old variable names */
62#define SDL_modelist (this->hidden->SDL_modelist)
63#define Caca_palette (this->hidden->palette)
64#define Caca_bitmap (this->hidden->bitmap)
65#define Caca_buffer (this->hidden->buffer)
66
67#define Caca_w (this->hidden->w)
68#define Caca_h (this->hidden->h)
69
70#define Caca_lastkey (this->hidden->lastkey)
71#define Caca_lasttime (this->hidden->lasttime)
72
73#define Caca_mutex (this->hidden->mutex)
74
75#endif /* _SDL_cacavideo_h */
76
diff --git a/apps/plugins/sdl/src/video/dc/SDL_dcevents.c b/apps/plugins/sdl/src/video/dc/SDL_dcevents.c
deleted file mode 100644
index 38dcca4e5b..0000000000
--- a/apps/plugins/sdl/src/video/dc/SDL_dcevents.c
+++ /dev/null
@@ -1,152 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL.h"
25#include "../../events/SDL_sysevents.h"
26#include "../../events/SDL_events_c.h"
27#include "SDL_dcvideo.h"
28#include "SDL_dcevents_c.h"
29
30#include <dc/maple.h>
31#include <dc/maple/mouse.h>
32#include <dc/maple/keyboard.h>
33
34const static unsigned short sdl_key[]= {
35 /*0*/ 0, 0, 0, 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
36 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
37 'u', 'v', 'w', 'x', 'y', 'z',
38 /*1e*/ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
39 /*28*/ SDLK_RETURN, SDLK_ESCAPE, SDLK_BACKSPACE, SDLK_TAB, SDLK_SPACE, SDLK_MINUS, SDLK_PLUS, SDLK_LEFTBRACKET,
40 SDLK_RIGHTBRACKET, SDLK_BACKSLASH , 0, SDLK_SEMICOLON, SDLK_QUOTE,
41 /*35*/ '~', SDLK_COMMA, SDLK_PERIOD, SDLK_SLASH, SDLK_CAPSLOCK,
42 SDLK_F1, SDLK_F2, SDLK_F3, SDLK_F4, SDLK_F5, SDLK_F6, SDLK_F7, SDLK_F8, SDLK_F9, SDLK_F10, SDLK_F11, SDLK_F12,
43 /*46*/ SDLK_PRINT, SDLK_SCROLLOCK, SDLK_PAUSE, SDLK_INSERT, SDLK_HOME, SDLK_PAGEUP, SDLK_DELETE, SDLK_END, SDLK_PAGEDOWN, SDLK_RIGHT, SDLK_LEFT, SDLK_DOWN, SDLK_UP,
44 /*53*/ SDLK_NUMLOCK, SDLK_KP_DIVIDE, SDLK_KP_MULTIPLY, SDLK_KP_MINUS, SDLK_KP_PLUS, SDLK_KP_ENTER,
45 SDLK_KP1, SDLK_KP2, SDLK_KP3, SDLK_KP4, SDLK_KP5, SDLK_KP6,
46 /*5f*/ SDLK_KP7, SDLK_KP8, SDLK_KP9, SDLK_KP0, SDLK_KP_PERIOD, 0 /* S3 */
47};
48
49const static unsigned short sdl_shift[] = {
50 SDLK_LCTRL,SDLK_LSHIFT,SDLK_LALT,0 /* S1 */,
51 SDLK_RCTRL,SDLK_RSHIFT,SDLK_RALT,0 /* S2 */,
52};
53
54#define MOUSE_WHEELUP (1<<4)
55#define MOUSE_WHEELDOWN (1<<5)
56
57static void mouse_update(void)
58{
59const static char sdl_mousebtn[] = {
60 MOUSE_LEFTBUTTON,
61 MOUSE_RIGHTBUTTON,
62 MOUSE_SIDEBUTTON,
63 MOUSE_WHEELUP,
64 MOUSE_WHEELDOWN
65};
66
67 uint8 addr;
68 mouse_cond_t cond;
69
70 static int prev_buttons;
71 int buttons,changed;
72 int i;
73
74 if ((addr = maple_first_mouse())==0 || mouse_get_cond(addr, &cond)<0) return;
75
76 buttons = cond.buttons^0xff;
77 if (cond.dz<0) buttons|=MOUSE_WHEELUP;
78 if (cond.dz>0) buttons|=MOUSE_WHEELDOWN;
79
80 if (cond.dx||cond.dy) SDL_PrivateMouseMotion(0,1,cond.dx,cond.dy);
81
82 changed = buttons^prev_buttons;
83 for(i=0;i<sizeof(sdl_mousebtn);i++) {
84 if (changed & sdl_mousebtn[i]) {
85 SDL_PrivateMouseButton((buttons & sdl_mousebtn[i])?SDL_PRESSED:SDL_RELEASED,i,0,0);
86 }
87 }
88 prev_buttons = buttons;
89}
90
91static void keyboard_update(void)
92{
93 static kbd_state_t old_state;
94 static uint8 old_addr;
95
96 kbd_state_t *state;
97 uint8 addr;
98 int port,unit;
99
100 int shiftkeys;
101 SDL_keysym keysym;
102
103 int i;
104
105 addr = maple_first_kb();
106
107 if (addr==0) return;
108
109 if (addr!=old_addr) {
110 old_addr = addr;
111 SDL_memset(&old_state,0,sizeof(old_state));
112 }
113
114 maple_raddr(addr,&port,&unit);
115
116 state = maple_dev_state(port,unit);
117 if (!state) return;
118
119 shiftkeys = state->shift_keys ^ old_state.shift_keys;
120 for(i=0;i<sizeof(sdl_shift);i++) {
121 if ((shiftkeys>>i)&1) {
122 keysym.sym = sdl_shift[i];
123 SDL_PrivateKeyboard(((state->shift_keys>>i)&1)?SDL_PRESSED:SDL_RELEASED,&keysym);
124 }
125 }
126
127 for(i=0;i<sizeof(sdl_key);i++) {
128 if (state->matrix[i]!=old_state.matrix[i]) {
129 int key = sdl_key[i];
130 if (key) {
131 keysym.sym = key;
132 SDL_PrivateKeyboard(state->matrix[i]?SDL_PRESSED:SDL_RELEASED,&keysym);
133 }
134 }
135 }
136
137 old_state = *state;
138}
139
140void DC_PumpEvents(_THIS)
141{
142 keyboard_update();
143 mouse_update();
144}
145
146void DC_InitOSKeymap(_THIS)
147{
148 /* do nothing. */
149}
150
151/* end of SDL_dcevents.c ... */
152
diff --git a/apps/plugins/sdl/src/video/dc/SDL_dcevents_c.h b/apps/plugins/sdl/src/video/dc/SDL_dcevents_c.h
deleted file mode 100644
index 3196eae47d..0000000000
--- a/apps/plugins/sdl/src/video/dc/SDL_dcevents_c.h
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_dcvideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29extern void DC_InitOSKeymap(_THIS);
30extern void DC_PumpEvents(_THIS);
31
32/* end of SDL_dcevents_c.h ... */
33
diff --git a/apps/plugins/sdl/src/video/dc/SDL_dcmouse.c b/apps/plugins/sdl/src/video/dc/SDL_dcmouse.c
deleted file mode 100644
index 61a0ba028c..0000000000
--- a/apps/plugins/sdl/src/video/dc/SDL_dcmouse.c
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <stdio.h>
25
26#include "SDL_mouse.h"
27#include "../../events/SDL_events_c.h"
28
29#include "SDL_dcmouse_c.h"
30
31
32/* The implementation dependent data for the window manager cursor */
33struct WMcursor {
34 int unused;
35};
diff --git a/apps/plugins/sdl/src/video/dc/SDL_dcmouse_c.h b/apps/plugins/sdl/src/video/dc/SDL_dcmouse_c.h
deleted file mode 100644
index dc018bb164..0000000000
--- a/apps/plugins/sdl/src/video/dc/SDL_dcmouse_c.h
+++ /dev/null
@@ -1,26 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_dcvideo.h"
25
26/* Functions to be exported */
diff --git a/apps/plugins/sdl/src/video/dc/SDL_dcvideo.c b/apps/plugins/sdl/src/video/dc/SDL_dcvideo.c
deleted file mode 100644
index 5838a49a32..0000000000
--- a/apps/plugins/sdl/src/video/dc/SDL_dcvideo.c
+++ /dev/null
@@ -1,445 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_video.h"
25#include "SDL_mouse.h"
26#include "../SDL_sysvideo.h"
27#include "../SDL_pixels_c.h"
28#include "../../events/SDL_events_c.h"
29
30#include "SDL_dcvideo.h"
31#include "SDL_dcevents_c.h"
32#include "SDL_dcmouse_c.h"
33
34#include <dc/video.h>
35#include <dc/pvr.h>
36
37
38/* Initialization/Query functions */
39static int DC_VideoInit(_THIS, SDL_PixelFormat *vformat);
40static SDL_Rect **DC_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
41static SDL_Surface *DC_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
42static int DC_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
43static void DC_VideoQuit(_THIS);
44
45/* Hardware surface functions */
46static int DC_AllocHWSurface(_THIS, SDL_Surface *surface);
47static int DC_LockHWSurface(_THIS, SDL_Surface *surface);
48static void DC_UnlockHWSurface(_THIS, SDL_Surface *surface);
49static void DC_FreeHWSurface(_THIS, SDL_Surface *surface);
50static int DC_FlipHWSurface(_THIS, SDL_Surface *surface);
51
52/* etc. */
53static void DC_UpdateRects(_THIS, int numrects, SDL_Rect *rects);
54
55/* OpenGL */
56#if SDL_VIDEO_OPENGL
57static void *DC_GL_GetProcAddress(_THIS, const char *proc);
58static int DC_GL_LoadLibrary(_THIS, const char *path);
59static int DC_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value);
60static void DC_GL_SwapBuffers(_THIS);
61#endif
62
63/* DC driver bootstrap functions */
64
65static int DC_Available(void)
66{
67 return 1;
68}
69
70static void DC_DeleteDevice(SDL_VideoDevice *device)
71{
72 SDL_free(device->hidden);
73 SDL_free(device);
74}
75
76static SDL_VideoDevice *DC_CreateDevice(int devindex)
77{
78 SDL_VideoDevice *device;
79
80 /* Initialize all variables that we clean on shutdown */
81 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
82 if ( device ) {
83 SDL_memset(device, 0, (sizeof *device));
84 device->hidden = (struct SDL_PrivateVideoData *)
85 SDL_malloc((sizeof *device->hidden));
86 }
87 if ( (device == NULL) || (device->hidden == NULL) ) {
88 SDL_OutOfMemory();
89 if ( device ) {
90 SDL_free(device);
91 }
92 return(0);
93 }
94 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
95
96 /* Set the function pointers */
97 device->VideoInit = DC_VideoInit;
98 device->ListModes = DC_ListModes;
99 device->SetVideoMode = DC_SetVideoMode;
100 device->CreateYUVOverlay = NULL;
101 device->SetColors = DC_SetColors;
102 device->UpdateRects = DC_UpdateRects;
103 device->VideoQuit = DC_VideoQuit;
104 device->AllocHWSurface = DC_AllocHWSurface;
105 device->CheckHWBlit = NULL;
106 device->FillHWRect = NULL;
107 device->SetHWColorKey = NULL;
108 device->SetHWAlpha = NULL;
109 device->LockHWSurface = DC_LockHWSurface;
110 device->UnlockHWSurface = DC_UnlockHWSurface;
111 device->FlipHWSurface = DC_FlipHWSurface;
112 device->FreeHWSurface = DC_FreeHWSurface;
113#if SDL_VIDEO_OPENGL
114 device->GL_LoadLibrary = DC_GL_LoadLibrary;
115 device->GL_GetProcAddress = DC_GL_GetProcAddress;
116 device->GL_GetAttribute = DC_GL_GetAttribute;
117 device->GL_MakeCurrent = NULL;
118 device->GL_SwapBuffers = DC_GL_SwapBuffers;
119#endif
120 device->SetCaption = NULL;
121 device->SetIcon = NULL;
122 device->IconifyWindow = NULL;
123 device->GrabInput = NULL;
124 device->GetWMInfo = NULL;
125 device->InitOSKeymap = DC_InitOSKeymap;
126 device->PumpEvents = DC_PumpEvents;
127
128 device->free = DC_DeleteDevice;
129
130 return device;
131}
132
133VideoBootStrap DC_bootstrap = {
134 "dcvideo", "Dreamcast Video",
135 DC_Available, DC_CreateDevice
136};
137
138
139int DC_VideoInit(_THIS, SDL_PixelFormat *vformat)
140{
141 /* Determine the screen depth (use default 16-bit depth) */
142 /* we change this during the SDL_SetVideoMode implementation... */
143 vformat->BitsPerPixel = 16;
144 vformat->Rmask = 0x0000f800;
145 vformat->Gmask = 0x000007e0;
146 vformat->Bmask = 0x0000001f;
147
148 /* We're done! */
149 return(0);
150}
151
152const static SDL_Rect
153 RECT_800x600 = {0,0,800,600},
154 RECT_640x480 = {0,0,640,480},
155 RECT_320x240 = {0,0,320,240};
156const static SDL_Rect *vid_modes[] = {
157 &RECT_800x600,
158 &RECT_640x480,
159 &RECT_320x240,
160 NULL
161};
162
163SDL_Rect **DC_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
164{
165 switch(format->BitsPerPixel) {
166 case 15:
167 case 16:
168 return &vid_modes;
169 case 32:
170 if (!(flags & SDL_OPENGL))
171 return &vid_modes;
172 default:
173 return NULL;
174 }
175// return (SDL_Rect **) -1;
176}
177
178pvr_init_params_t params = {
179 /* Enable opaque and translucent polygons with size 16 */
180 { PVR_BINSIZE_16, PVR_BINSIZE_0, PVR_BINSIZE_16, PVR_BINSIZE_0, PVR_BINSIZE_16 },
181
182 /* Vertex buffer size */
183 512*1024
184};
185
186#if SDL_VIDEO_OPENGL
187static int pvr_inited;
188#endif
189
190SDL_Surface *DC_SetVideoMode(_THIS, SDL_Surface *current,
191 int width, int height, int bpp, Uint32 flags)
192{
193 int disp_mode,pixel_mode,pitch;
194 Uint32 Rmask, Gmask, Bmask;
195
196 if (width==320 && height==240) disp_mode=DM_320x240;
197 else if (width==640 && height==480) disp_mode=DM_640x480;
198 else if (width==800 && height==600) disp_mode=DM_800x608;
199 else {
200 SDL_SetError("Couldn't find requested mode in list");
201 return(NULL);
202 }
203
204 switch(bpp) {
205 case 15: pixel_mode = PM_RGB555; pitch = width*2;
206 /* 5-5-5 */
207 Rmask = 0x00007c00;
208 Gmask = 0x000003e0;
209 Bmask = 0x0000001f;
210 break;
211 case 16: pixel_mode = PM_RGB565; pitch = width*2;
212 /* 5-6-5 */
213 Rmask = 0x0000f800;
214 Gmask = 0x000007e0;
215 Bmask = 0x0000001f;
216 break;
217 case 24: bpp = 32;
218 case 32: pixel_mode = PM_RGB888; pitch = width*4;
219 Rmask = 0x00ff0000;
220 Gmask = 0x0000ff00;
221 Bmask = 0x000000ff;
222#if SDL_VIDEO_OPENGL
223 if (!(flags & SDL_OPENGL))
224#endif
225 break;
226 default:
227 SDL_SetError("Couldn't find requested mode in list");
228 return(NULL);
229 }
230
231// if ( bpp != current->format->BitsPerPixel ) {
232 if ( ! SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, 0) ) {
233 return(NULL);
234 }
235// }
236
237 /* Set up the new mode framebuffer */
238 current->flags = (SDL_FULLSCREEN|SDL_HWSURFACE);
239 current->w = width;
240 current->h = height;
241 current->pitch = pitch;
242
243#if SDL_VIDEO_OPENGL
244 if (pvr_inited) {
245 pvr_inited = 0;
246 pvr_shutdown();
247 }
248#endif
249
250 vid_set_mode(disp_mode,pixel_mode);
251
252 current->pixels = vram_s;
253
254#if SDL_VIDEO_OPENGL
255 if (flags & SDL_OPENGL) {
256 this->gl_config.driver_loaded = 1;
257 current->flags = SDL_FULLSCREEN | SDL_OPENGL;
258 current->pixels = NULL;
259 pvr_inited = 1;
260 pvr_init(&params);
261 glKosInit();
262 glKosBeginFrame();
263 } else
264#endif
265 if (flags | SDL_DOUBLEBUF) {
266 current->flags |= SDL_DOUBLEBUF;
267 current->pixels = (void*)((int)current->pixels | 0x400000);
268 }
269
270 /* We're done */
271 return(current);
272}
273
274/* We don't actually allow hardware surfaces other than the main one */
275static int DC_AllocHWSurface(_THIS, SDL_Surface *surface)
276{
277 return(-1);
278}
279static void DC_FreeHWSurface(_THIS, SDL_Surface *surface)
280{
281 return;
282}
283
284/* We need to wait for vertical retrace on page flipped displays */
285static int DC_LockHWSurface(_THIS, SDL_Surface *surface)
286{
287 return(0);
288}
289
290static void DC_UnlockHWSurface(_THIS, SDL_Surface *surface)
291{
292 return;
293}
294
295static int DC_FlipHWSurface(_THIS, SDL_Surface *surface)
296{
297 if (surface->flags & SDL_DOUBLEBUF) {
298 vid_set_start((int)surface->pixels & 0xffffff);
299 surface->pixels = (void*)((int)surface->pixels ^ 0x400000);
300 }
301 return(0);
302}
303
304static void DC_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
305{
306 /* do nothing. */
307}
308
309static int DC_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
310{
311 /* do nothing of note. */
312 return(1);
313}
314
315/* Note: If we are terminated, this could be called in the middle of
316 another SDL video routine -- notably UpdateRects.
317*/
318static void DC_VideoQuit(_THIS)
319{
320#if SDL_VIDEO_OPENGL
321 if (pvr_inited) {
322 pvr_inited = 0;
323 pvr_shutdown();
324 }
325#endif
326}
327
328#if SDL_VIDEO_OPENGL
329
330void dmyfunc(void) {}
331
332typedef void (*funcptr)();
333const static struct {
334 char *name;
335 funcptr addr;
336} glfuncs[] = {
337#define DEF(func) {#func,&func}
338 DEF(glBegin),
339 DEF(glBindTexture),
340 DEF(glBlendFunc),
341 DEF(glColor4f),
342// DEF(glCopyImageID),
343 DEF(glDisable),
344 DEF(glEnable),
345 DEF(glEnd),
346 DEF(glFlush),
347 DEF(glGenTextures),
348 DEF(glGetString),
349 DEF(glLoadIdentity),
350 DEF(glMatrixMode),
351 DEF(glOrtho),
352 DEF(glPixelStorei),
353// DEF(glPopAttrib),
354// DEF(glPopClientAttrib),
355 {"glPopAttrib",&dmyfunc},
356 {"glPopClientAttrib",&dmyfunc},
357 DEF(glPopMatrix),
358// DEF(glPushAttrib),
359// DEF(glPushClientAttrib),
360 {"glPushAttrib",&dmyfunc},
361 {"glPushClientAttrib",&dmyfunc},
362 DEF(glPushMatrix),
363 DEF(glTexCoord2f),
364 DEF(glTexEnvf),
365 DEF(glTexImage2D),
366 DEF(glTexParameteri),
367 DEF(glTexSubImage2D),
368 DEF(glVertex2i),
369 DEF(glViewport),
370#undef DEF
371};
372
373static void *DC_GL_GetProcAddress(_THIS, const char *proc)
374{
375 void *ret;
376 int i;
377
378 ret = glKosGetProcAddress(proc);
379 if (ret) return ret;
380
381 for(i=0;i<sizeof(glfuncs)/sizeof(glfuncs[0]);i++) {
382 if (SDL_strcmp(proc,glfuncs[i].name)==0) return glfuncs[i].addr;
383 }
384
385 return NULL;
386}
387
388static int DC_GL_LoadLibrary(_THIS, const char *path)
389{
390 this->gl_config.driver_loaded = 1;
391
392 return 0;
393}
394
395static int DC_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value)
396{
397 GLenum mesa_attrib;
398 int val;
399
400 switch(attrib) {
401 case SDL_GL_RED_SIZE:
402 val = 5;
403 break;
404 case SDL_GL_GREEN_SIZE:
405 val = 6;
406 break;
407 case SDL_GL_BLUE_SIZE:
408 val = 5;
409 break;
410 case SDL_GL_ALPHA_SIZE:
411 val = 0;
412 break;
413 case SDL_GL_DOUBLEBUFFER:
414 val = 1;
415 break;
416 case SDL_GL_DEPTH_SIZE:
417 val = 16; /* or 32? */
418 break;
419 case SDL_GL_STENCIL_SIZE:
420 val = 0;
421 break;
422 case SDL_GL_ACCUM_RED_SIZE:
423 val = 0;
424 break;
425 case SDL_GL_ACCUM_GREEN_SIZE:
426 val = 0;
427 case SDL_GL_ACCUM_BLUE_SIZE:
428 val = 0;
429 break;
430 case SDL_GL_ACCUM_ALPHA_SIZE:
431 val = 0;
432 break;
433 default :
434 return -1;
435 }
436 *value = val;
437 return 0;
438}
439
440static void DC_GL_SwapBuffers(_THIS)
441{
442 glKosFinishFrame();
443 glKosBeginFrame();
444}
445#endif
diff --git a/apps/plugins/sdl/src/video/dc/SDL_dcvideo.h b/apps/plugins/sdl/src/video/dc/SDL_dcvideo.h
deleted file mode 100644
index 837f028dbb..0000000000
--- a/apps/plugins/sdl/src/video/dc/SDL_dcvideo.h
+++ /dev/null
@@ -1,42 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_dcvideo_h
25#define _SDL_dcvideo_h
26
27#include "SDL_mouse.h"
28#include "SDL_mutex.h"
29#include "../SDL_sysvideo.h"
30
31/* Hidden "this" pointer for the video functions */
32#define _THIS SDL_VideoDevice *this
33
34
35/* Private display data */
36
37struct SDL_PrivateVideoData {
38 int w, h;
39 void *buffer;
40};
41
42#endif /* _SDL_dcvideo_h */
diff --git a/apps/plugins/sdl/src/video/dga/SDL_dgaevents.c b/apps/plugins/sdl/src/video/dga/SDL_dgaevents.c
deleted file mode 100644
index 4e6d5f054f..0000000000
--- a/apps/plugins/sdl/src/video/dga/SDL_dgaevents.c
+++ /dev/null
@@ -1,163 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting DGA events into SDL events */
25
26#include <stdio.h>
27#include <X11/Xlib.h>
28#include "../Xext/extensions/xf86dga.h"
29
30#include "SDL_timer.h"
31#include "../SDL_sysvideo.h"
32#include "../../events/SDL_events_c.h"
33#include "SDL_dgavideo.h"
34#include "SDL_dgaevents_c.h"
35
36/* get function pointers... */
37#include "../x11/SDL_x11dyn.h"
38
39/* Heheh we're using X11 event code */
40extern int X11_Pending(Display *display);
41extern void X11_InitKeymap(void);
42extern SDLKey X11_TranslateKeycode(Display *display, KeyCode kc);
43
44static int DGA_DispatchEvent(_THIS)
45{
46 int posted;
47 SDL_NAME(XDGAEvent) xevent;
48
49 XNextEvent(DGA_Display, (XEvent *)&xevent);
50
51 posted = 0;
52 xevent.type -= DGA_event_base;
53 switch (xevent.type) {
54
55 /* Mouse motion? */
56 case MotionNotify: {
57 if ( SDL_VideoSurface ) {
58 posted = SDL_PrivateMouseMotion(0, 1,
59 xevent.xmotion.dx, xevent.xmotion.dy);
60 }
61 }
62 break;
63
64 /* Mouse button press? */
65 case ButtonPress: {
66 posted = SDL_PrivateMouseButton(SDL_PRESSED,
67 xevent.xbutton.button, 0, 0);
68 }
69 break;
70
71 /* Mouse button release? */
72 case ButtonRelease: {
73 posted = SDL_PrivateMouseButton(SDL_RELEASED,
74 xevent.xbutton.button, 0, 0);
75 }
76 break;
77
78 /* Key press? */
79 case KeyPress: {
80 SDL_keysym keysym;
81 KeyCode keycode;
82 XKeyEvent xkey;
83
84 SDL_NAME(XDGAKeyEventToXKeyEvent)(&xevent.xkey, &xkey);
85 keycode = xkey.keycode;
86#ifdef DEBUG_XEVENTS
87printf("KeyPress (X11 keycode = 0x%X)\n", xkey.keycode);
88#endif
89 /* Get the translated SDL virtual keysym */
90 keysym.scancode = keycode;
91 keysym.sym = X11_TranslateKeycode(DGA_Display, keycode);
92 keysym.mod = KMOD_NONE;
93 keysym.unicode = 0;
94
95 /* Look up the translated value for the key event */
96 if ( SDL_TranslateUNICODE ) {
97 static XComposeStatus state;
98 char keybuf[32];
99
100 if ( XLookupString(&xkey, keybuf, sizeof(keybuf), NULL, &state) ) {
101 /*
102 * FIXME: XLookupString() may yield more than one
103 * character, so we need a mechanism to allow for
104 * this (perhaps null keypress events with a
105 * unicode value)
106 */
107 keysym.unicode = (Uint8)keybuf[0];
108 }
109 }
110 posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
111 }
112 break;
113
114 /* Key release? */
115 case KeyRelease: {
116 SDL_keysym keysym;
117 KeyCode keycode;
118 XKeyEvent xkey;
119
120 SDL_NAME(XDGAKeyEventToXKeyEvent)(&xevent.xkey, &xkey);
121 keycode = xkey.keycode;
122#ifdef DEBUG_XEVENTS
123printf("KeyRelease (X11 keycode = 0x%X)\n", xkey.keycode);
124#endif
125 /* Get the translated SDL virtual keysym */
126 keysym.scancode = keycode;
127 keysym.sym = X11_TranslateKeycode(DGA_Display, keycode);
128 keysym.mod = KMOD_NONE;
129 keysym.unicode = 0;
130 posted = SDL_PrivateKeyboard(SDL_RELEASED, &keysym);
131 }
132 break;
133 }
134 return(posted);
135}
136
137void DGA_PumpEvents(_THIS)
138{
139 /* Keep processing pending events */
140 LOCK_DISPLAY();
141
142 /* Update activity every five seconds to prevent screensaver. --ryan. */
143 if (!allow_screensaver) {
144 static Uint32 screensaverTicks;
145 Uint32 nowTicks = SDL_GetTicks();
146 if ((nowTicks - screensaverTicks) > 5000) {
147 XResetScreenSaver(DGA_Display);
148 screensaverTicks = nowTicks;
149 }
150 }
151
152 while ( X11_Pending(DGA_Display) ) {
153 DGA_DispatchEvent(this);
154 }
155
156 UNLOCK_DISPLAY();
157}
158
159void DGA_InitOSKeymap(_THIS)
160{
161 X11_InitKeymap();
162}
163
diff --git a/apps/plugins/sdl/src/video/dga/SDL_dgaevents_c.h b/apps/plugins/sdl/src/video/dga/SDL_dgaevents_c.h
deleted file mode 100644
index 45f8cc59ea..0000000000
--- a/apps/plugins/sdl/src/video/dga/SDL_dgaevents_c.h
+++ /dev/null
@@ -1,28 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_dgavideo.h"
25
26/* Functions to be exported */
27extern void DGA_PumpEvents(_THIS);
28extern void DGA_InitOSKeymap(_THIS);
diff --git a/apps/plugins/sdl/src/video/dga/SDL_dgamouse.c b/apps/plugins/sdl/src/video/dga/SDL_dgamouse.c
deleted file mode 100644
index 43bc5d6ea8..0000000000
--- a/apps/plugins/sdl/src/video/dga/SDL_dgamouse.c
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <stdio.h>
25
26#include "SDL_mouse.h"
27#include "../../events/SDL_events_c.h"
28#include "SDL_dgavideo.h"
29#include "SDL_dgamouse_c.h"
30
31
32/* The implementation dependent data for the window manager cursor */
33struct WMcursor {
34 int unused;
35};
diff --git a/apps/plugins/sdl/src/video/dga/SDL_dgamouse_c.h b/apps/plugins/sdl/src/video/dga/SDL_dgamouse_c.h
deleted file mode 100644
index 4ea8b21417..0000000000
--- a/apps/plugins/sdl/src/video/dga/SDL_dgamouse_c.h
+++ /dev/null
@@ -1,26 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_dgavideo.h"
25
26/* Functions to be exported */
diff --git a/apps/plugins/sdl/src/video/dga/SDL_dgavideo.c b/apps/plugins/sdl/src/video/dga/SDL_dgavideo.c
deleted file mode 100644
index 267d5cc335..0000000000
--- a/apps/plugins/sdl/src/video/dga/SDL_dgavideo.c
+++ /dev/null
@@ -1,1101 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* DGA 2.0 based SDL video driver implementation.
25*/
26
27#include <stdio.h>
28
29#include <X11/Xlib.h>
30#include "../Xext/extensions/xf86dga.h"
31
32#include "SDL_video.h"
33#include "SDL_mouse.h"
34#include "../SDL_sysvideo.h"
35#include "../SDL_pixels_c.h"
36#include "../../events/SDL_events_c.h"
37#include "SDL_dgavideo.h"
38#include "SDL_dgamouse_c.h"
39#include "SDL_dgaevents_c.h"
40
41/* get function pointers... */
42#include "../x11/SDL_x11dyn.h"
43
44/*#define DGA_DEBUG*/
45
46/* Initialization/Query functions */
47static int DGA_VideoInit(_THIS, SDL_PixelFormat *vformat);
48static SDL_Rect **DGA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
49static SDL_Surface *DGA_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
50static int DGA_SetColors(_THIS, int firstcolor, int ncolors,
51 SDL_Color *colors);
52static int DGA_SetGammaRamp(_THIS, Uint16 *ramp);
53static void DGA_VideoQuit(_THIS);
54
55/* Hardware surface functions */
56static int DGA_InitHWSurfaces(_THIS, SDL_Surface *screen, Uint8 *base, int size);
57static void DGA_FreeHWSurfaces(_THIS);
58static int DGA_AllocHWSurface(_THIS, SDL_Surface *surface);
59static int DGA_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color);
60static int DGA_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst);
61static int DGA_LockHWSurface(_THIS, SDL_Surface *surface);
62static void DGA_UnlockHWSurface(_THIS, SDL_Surface *surface);
63static void DGA_FreeHWSurface(_THIS, SDL_Surface *surface);
64static int DGA_FlipHWSurface(_THIS, SDL_Surface *surface);
65
66/* DGA driver bootstrap functions */
67
68static int DGA_Available(void)
69{
70 const char *display = NULL;
71 Display *dpy = NULL;
72 int available = 0;
73
74 /* The driver is available is available if the display is local
75 and the DGA 2.0+ extension is available, and we can map mem.
76 */
77 if ( SDL_X11_LoadSymbols() ) {
78 if ( (SDL_strncmp(XDisplayName(display), ":", 1) == 0) ||
79 (SDL_strncmp(XDisplayName(display), "unix:", 5) == 0) ) {
80 dpy = XOpenDisplay(display);
81 if ( dpy ) {
82 int events, errors, major, minor;
83
84 if ( SDL_NAME(XDGAQueryExtension)(dpy, &events, &errors) &&
85 SDL_NAME(XDGAQueryVersion)(dpy, &major, &minor) ) {
86 int screen;
87
88 screen = DefaultScreen(dpy);
89 if ( (major >= 2) &&
90 SDL_NAME(XDGAOpenFramebuffer)(dpy, screen) ) {
91 available = 1;
92 SDL_NAME(XDGACloseFramebuffer)(dpy, screen);
93 }
94 }
95 XCloseDisplay(dpy);
96 }
97 }
98 SDL_X11_UnloadSymbols();
99 }
100 return(available);
101}
102
103static void DGA_DeleteDevice(SDL_VideoDevice *device)
104{
105 if (device != NULL) {
106 SDL_free(device->hidden);
107 SDL_free(device);
108 SDL_X11_UnloadSymbols();
109 }
110}
111
112static SDL_VideoDevice *DGA_CreateDevice(int devindex)
113{
114 SDL_VideoDevice *device = NULL;
115
116 /* Initialize all variables that we clean on shutdown */
117 if (SDL_X11_LoadSymbols()) {
118 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
119 if ( device ) {
120 SDL_memset(device, 0, (sizeof *device));
121 device->hidden = (struct SDL_PrivateVideoData *)
122 SDL_malloc((sizeof *device->hidden));
123 }
124 if ( (device == NULL) || (device->hidden == NULL) ) {
125 SDL_OutOfMemory();
126 if ( device ) {
127 SDL_free(device);
128 }
129 SDL_X11_UnloadSymbols();
130 return(0);
131 }
132 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
133
134 /* Set the function pointers */
135 device->VideoInit = DGA_VideoInit;
136 device->ListModes = DGA_ListModes;
137 device->SetVideoMode = DGA_SetVideoMode;
138 device->SetColors = DGA_SetColors;
139 device->UpdateRects = NULL;
140 device->VideoQuit = DGA_VideoQuit;
141 device->AllocHWSurface = DGA_AllocHWSurface;
142 device->CheckHWBlit = DGA_CheckHWBlit;
143 device->FillHWRect = DGA_FillHWRect;
144 device->SetHWColorKey = NULL;
145 device->SetHWAlpha = NULL;
146 device->LockHWSurface = DGA_LockHWSurface;
147 device->UnlockHWSurface = DGA_UnlockHWSurface;
148 device->FlipHWSurface = DGA_FlipHWSurface;
149 device->FreeHWSurface = DGA_FreeHWSurface;
150 device->SetGammaRamp = DGA_SetGammaRamp;
151 device->GetGammaRamp = NULL;
152 device->SetCaption = NULL;
153 device->SetIcon = NULL;
154 device->IconifyWindow = NULL;
155 device->GrabInput = NULL;
156 device->GetWMInfo = NULL;
157 device->InitOSKeymap = DGA_InitOSKeymap;
158 device->PumpEvents = DGA_PumpEvents;
159
160 device->free = DGA_DeleteDevice;
161 }
162
163 return device;
164}
165
166VideoBootStrap DGA_bootstrap = {
167 "dga", "XFree86 DGA 2.0",
168 DGA_Available, DGA_CreateDevice
169};
170
171static int DGA_AddMode(_THIS, int bpp, int w, int h)
172{
173 SDL_Rect *mode;
174 int index;
175 int next_mode;
176
177 /* Check to see if we already have this mode */
178 if ( bpp < 8 ) { /* Not supported */
179 return(0);
180 }
181 index = ((bpp+7)/8)-1;
182 if ( SDL_nummodes[index] > 0 ) {
183 mode = SDL_modelist[index][SDL_nummodes[index]-1];
184 if ( (mode->w == w) && (mode->h == h) ) {
185 return(0);
186 }
187 }
188
189 /* Set up the new video mode rectangle */
190 mode = (SDL_Rect *)SDL_malloc(sizeof *mode);
191 if ( mode == NULL ) {
192 SDL_OutOfMemory();
193 return(-1);
194 }
195 mode->x = 0;
196 mode->y = 0;
197 mode->w = w;
198 mode->h = h;
199
200 /* Allocate the new list of modes, and fill in the new mode */
201 next_mode = SDL_nummodes[index];
202 SDL_modelist[index] = (SDL_Rect **)
203 SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *));
204 if ( SDL_modelist[index] == NULL ) {
205 SDL_OutOfMemory();
206 SDL_nummodes[index] = 0;
207 SDL_free(mode);
208 return(-1);
209 }
210 SDL_modelist[index][next_mode] = mode;
211 SDL_modelist[index][next_mode+1] = NULL;
212 SDL_nummodes[index]++;
213
214 return(0);
215}
216
217/* This whole function is a hack. :) */
218static Uint32 get_video_size(_THIS)
219{
220 /* This is a non-exported function from libXxf86dga.a */
221 extern unsigned char *SDL_NAME(XDGAGetMappedMemory)(int screen);
222 FILE *proc;
223 unsigned long mem;
224 unsigned start, stop;
225 char line[BUFSIZ];
226 Uint32 size;
227
228 mem = (unsigned long)SDL_NAME(XDGAGetMappedMemory)(DGA_Screen);
229 size = 0;
230 proc = fopen("/proc/self/maps", "r");
231 if ( proc ) {
232 while ( fgets(line, sizeof(line)-1, proc) ) {
233 SDL_sscanf(line, "%x-%x", &start, &stop);
234 if ( start == mem ) {
235 size = (Uint32)((stop-start)/1024);
236 break;
237 }
238 }
239 fclose(proc);
240 }
241 return(size);
242}
243
244#ifdef DGA_DEBUG
245static void PrintMode(SDL_NAME(XDGAMode) *mode)
246{
247 printf("Mode: %s (%dx%d) at %d bpp (%f refresh, %d pitch) num: %d\n",
248 mode->name,
249 mode->viewportWidth, mode->viewportHeight,
250 mode->depth == 24 ? mode->bitsPerPixel : mode->depth,
251 mode->verticalRefresh, mode->bytesPerScanline, mode->num);
252 printf("\tRGB: 0x%8.8x 0x%8.8x 0x%8.8x (%d - %s)\n",
253 mode->redMask, mode->greenMask, mode->blueMask,
254 mode->visualClass,
255 mode->visualClass == TrueColor ? "truecolor" :
256 mode->visualClass == DirectColor ? "directcolor" :
257 mode->visualClass == PseudoColor ? "pseudocolor" : "unknown");
258 printf("\tFlags: ");
259 if ( mode->flags & XDGAConcurrentAccess )
260 printf(" XDGAConcurrentAccess");
261 if ( mode->flags & XDGASolidFillRect )
262 printf(" XDGASolidFillRect");
263 if ( mode->flags & XDGABlitRect )
264 printf(" XDGABlitRect");
265 if ( mode->flags & XDGABlitTransRect )
266 printf(" XDGABlitTransRect");
267 if ( mode->flags & XDGAPixmap )
268 printf(" XDGAPixmap");
269 if ( mode->flags & XDGAInterlaced )
270 printf(" XDGAInterlaced");
271 if ( mode->flags & XDGADoublescan )
272 printf(" XDGADoublescan");
273 if ( mode->viewportFlags & XDGAFlipRetrace )
274 printf(" XDGAFlipRetrace");
275 if ( mode->viewportFlags & XDGAFlipImmediate )
276 printf(" XDGAFlipImmediate");
277 printf("\n");
278}
279#endif /* DGA_DEBUG */
280
281static int cmpmodes(const void *va, const void *vb)
282{
283 const SDL_NAME(XDGAMode) *a = (const SDL_NAME(XDGAMode) *)va;
284 const SDL_NAME(XDGAMode) *b = (const SDL_NAME(XDGAMode) *)vb;
285
286 if ( (a->viewportWidth == b->viewportWidth) &&
287 (b->viewportHeight == a->viewportHeight) ) {
288 /* Prefer 32 bpp over 24 bpp, 16 bpp over 15 bpp */
289 int a_bpp = a->depth == 24 ? a->bitsPerPixel : a->depth;
290 int b_bpp = b->depth == 24 ? b->bitsPerPixel : b->depth;
291 if ( a_bpp != b_bpp ) {
292 return b_bpp - a_bpp;
293 }
294 /* Prefer DirectColor visuals, for gamma support */
295 if ( a->visualClass == DirectColor && b->visualClass != DirectColor )
296 return -1;
297 if ( b->visualClass == DirectColor && a->visualClass != DirectColor )
298 return 1;
299 /* Maintain server refresh rate sorting */
300 return a->num - b->num;
301 } else if ( a->viewportWidth == b->viewportWidth ) {
302 return b->viewportHeight - a->viewportHeight;
303 } else {
304 return b->viewportWidth - a->viewportWidth;
305 }
306}
307static void UpdateHWInfo(_THIS, SDL_NAME(XDGAMode) *mode)
308{
309 this->info.wm_available = 0;
310 this->info.hw_available = 1;
311 if ( mode->flags & XDGABlitRect ) {
312 this->info.blit_hw = 1;
313 } else {
314 this->info.blit_hw = 0;
315 }
316 if ( mode->flags & XDGABlitTransRect ) {
317 this->info.blit_hw_CC = 1;
318 } else {
319 this->info.blit_hw_CC = 0;
320 }
321 if ( mode->flags & XDGASolidFillRect ) {
322 this->info.blit_fill = 1;
323 } else {
324 this->info.blit_fill = 0;
325 }
326 this->info.video_mem = get_video_size(this);
327}
328
329static int DGA_VideoInit(_THIS, SDL_PixelFormat *vformat)
330{
331 const char *env;
332 const char *display;
333 int event_base, error_base;
334 int major_version, minor_version;
335 Visual *visual;
336 SDL_NAME(XDGAMode) *modes;
337 int i, num_modes;
338
339 /* Open the X11 display */
340 display = NULL; /* Get it from DISPLAY environment variable */
341
342 DGA_Display = XOpenDisplay(display);
343 if ( DGA_Display == NULL ) {
344 SDL_SetError("Couldn't open X11 display");
345 return(-1);
346 }
347
348 /* Check for the DGA extension */
349 if ( ! SDL_NAME(XDGAQueryExtension)(DGA_Display, &event_base, &error_base) ||
350 ! SDL_NAME(XDGAQueryVersion)(DGA_Display, &major_version, &minor_version) ) {
351 SDL_SetError("DGA extension not available");
352 XCloseDisplay(DGA_Display);
353 return(-1);
354 }
355 if ( major_version < 2 ) {
356 SDL_SetError("DGA driver requires DGA 2.0 or newer");
357 XCloseDisplay(DGA_Display);
358 return(-1);
359 }
360 DGA_event_base = event_base;
361
362 /* Determine the current screen size */
363 this->info.current_w = DisplayWidth(DGA_Display, DGA_Screen);
364 this->info.current_h = DisplayHeight(DGA_Display, DGA_Screen);
365
366 /* Determine the current screen depth */
367 visual = DefaultVisual(DGA_Display, DGA_Screen);
368 {
369 XPixmapFormatValues *pix_format;
370 int i, num_formats;
371
372 vformat->BitsPerPixel = DefaultDepth(DGA_Display, DGA_Screen);
373 pix_format = XListPixmapFormats(DGA_Display, &num_formats);
374 if ( pix_format == NULL ) {
375 SDL_SetError("Couldn't determine screen formats");
376 XCloseDisplay(DGA_Display);
377 return(-1);
378 }
379 for ( i=0; i<num_formats; ++i ) {
380 if ( vformat->BitsPerPixel == pix_format[i].depth )
381 break;
382 }
383 if ( i != num_formats )
384 vformat->BitsPerPixel = pix_format[i].bits_per_pixel;
385 XFree((char *)pix_format);
386 }
387 if ( vformat->BitsPerPixel > 8 ) {
388 vformat->Rmask = visual->red_mask;
389 vformat->Gmask = visual->green_mask;
390 vformat->Bmask = visual->blue_mask;
391 }
392
393 /* Open access to the framebuffer */
394 if ( ! SDL_NAME(XDGAOpenFramebuffer)(DGA_Display, DGA_Screen) ) {
395 SDL_SetError("Unable to map the video memory");
396 XCloseDisplay(DGA_Display);
397 return(-1);
398 }
399
400 /* Allow environment override of screensaver disable. */
401 env = SDL_getenv("SDL_VIDEO_ALLOW_SCREENSAVER");
402 if ( env ) {
403 allow_screensaver = SDL_atoi(env);
404 } else {
405#ifdef SDL_VIDEO_DISABLE_SCREENSAVER
406 allow_screensaver = 0;
407#else
408 allow_screensaver = 1;
409#endif
410 }
411
412 /* Query for the list of available video modes */
413 modes = SDL_NAME(XDGAQueryModes)(DGA_Display, DGA_Screen, &num_modes);
414 SDL_qsort(modes, num_modes, sizeof *modes, cmpmodes);
415 for ( i=0; i<num_modes; ++i ) {
416 if ( ((modes[i].visualClass == PseudoColor) ||
417 (modes[i].visualClass == DirectColor) ||
418 (modes[i].visualClass == TrueColor)) &&
419 !(modes[i].flags & (XDGAInterlaced|XDGADoublescan)) ) {
420#ifdef DGA_DEBUG
421 PrintMode(&modes[i]);
422#endif
423 DGA_AddMode(this, modes[i].bitsPerPixel,
424 modes[i].viewportWidth,
425 modes[i].viewportHeight);
426 }
427 }
428 UpdateHWInfo(this, modes);
429 XFree(modes);
430
431 /* Create the hardware surface lock mutex */
432 hw_lock = SDL_CreateMutex();
433 if ( hw_lock == NULL ) {
434 SDL_SetError("Unable to create lock mutex");
435 DGA_VideoQuit(this);
436 return(-1);
437 }
438
439#ifdef LOCK_DGA_DISPLAY
440 /* Create the event lock so we're thread-safe.. :-/ */
441 event_lock = SDL_CreateMutex();
442#endif /* LOCK_DGA_DISPLAY */
443
444 /* We're done! */
445 return(0);
446}
447
448SDL_Rect **DGA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
449{
450 return(SDL_modelist[((format->BitsPerPixel+7)/8)-1]);
451}
452
453/* Various screen update functions available */
454static void DGA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
455
456SDL_Surface *DGA_SetVideoMode(_THIS, SDL_Surface *current,
457 int width, int height, int bpp, Uint32 flags)
458{
459 SDL_NAME(XDGAMode) *modes;
460 int i, num_modes;
461 SDL_NAME(XDGADevice) *mode;
462 int screen_len;
463 Uint8 *surfaces_mem;
464 int surfaces_len;
465
466 /* Free any previous colormap */
467 if ( DGA_colormap ) {
468 XFreeColormap(DGA_Display, DGA_colormap);
469 DGA_colormap = 0;
470 }
471
472 /* Search for a matching video mode */
473 modes = SDL_NAME(XDGAQueryModes)(DGA_Display, DGA_Screen, &num_modes);
474 SDL_qsort(modes, num_modes, sizeof *modes, cmpmodes);
475 for ( i=0; i<num_modes; ++i ) {
476 int depth;
477
478 depth = modes[i].depth;
479 if ( depth == 24 ) { /* Distinguish between 24 and 32 bpp */
480 depth = modes[i].bitsPerPixel;
481 }
482 if ( (depth == bpp) &&
483 (modes[i].viewportWidth == width) &&
484 (modes[i].viewportHeight == height) &&
485 ((modes[i].visualClass == PseudoColor) ||
486 (modes[i].visualClass == DirectColor) ||
487 (modes[i].visualClass == TrueColor)) &&
488 !(modes[i].flags & (XDGAInterlaced|XDGADoublescan)) ) {
489 break;
490 }
491 }
492 if ( i == num_modes ) {
493 SDL_SetError("No matching video mode found");
494 return(NULL);
495 }
496#ifdef DGA_DEBUG
497 PrintMode(&modes[i]);
498#endif
499
500 /* Set the video mode */
501 mode = SDL_NAME(XDGASetMode)(DGA_Display, DGA_Screen, modes[i].num);
502 XFree(modes);
503 if ( mode == NULL ) {
504 SDL_SetError("Unable to switch to requested mode");
505 return(NULL);
506 }
507 DGA_visualClass = mode->mode.visualClass;
508 memory_base = (Uint8 *)mode->data;
509 memory_pitch = mode->mode.bytesPerScanline;
510
511 /* Set up the new mode framebuffer */
512 current->flags = (SDL_FULLSCREEN|SDL_HWSURFACE);
513 current->w = mode->mode.viewportWidth;
514 current->h = mode->mode.viewportHeight;
515 current->pitch = memory_pitch;
516 current->pixels = memory_base;
517 if ( ! SDL_ReallocFormat(current, mode->mode.bitsPerPixel,
518 mode->mode.redMask,
519 mode->mode.greenMask,
520 mode->mode.blueMask, 0) ) {
521 return(NULL);
522 }
523 screen_len = current->h*current->pitch;
524
525 /* Create a colormap if necessary */
526 if ( (DGA_visualClass == PseudoColor) ||
527 (DGA_visualClass == DirectColor) ) {
528 DGA_colormap = SDL_NAME(XDGACreateColormap)(DGA_Display, DGA_Screen,
529 mode, AllocAll);
530 if ( DGA_visualClass == PseudoColor ) {
531 current->flags |= SDL_HWPALETTE;
532 } else {
533 /* Initialize the colormap to the identity mapping */
534 SDL_GetGammaRamp(0, 0, 0);
535 this->screen = current;
536 DGA_SetGammaRamp(this, this->gamma);
537 this->screen = NULL;
538 }
539 } else {
540 DGA_colormap = SDL_NAME(XDGACreateColormap)(DGA_Display, DGA_Screen,
541 mode, AllocNone);
542 }
543 SDL_NAME(XDGAInstallColormap)(DGA_Display, DGA_Screen, DGA_colormap);
544
545 /* Update the hardware capabilities */
546 UpdateHWInfo(this, &mode->mode);
547
548 /* Set up the information for hardware surfaces */
549 surfaces_mem = (Uint8 *)current->pixels + screen_len;
550 surfaces_len = (mode->mode.imageHeight*current->pitch - screen_len);
551
552 /* Update for double-buffering, if we can */
553 SDL_NAME(XDGASetViewport)(DGA_Display, DGA_Screen, 0, 0, XDGAFlipRetrace);
554 if ( flags & SDL_DOUBLEBUF ) {
555 if ( mode->mode.imageHeight >= (current->h*2) ) {
556 current->flags |= SDL_DOUBLEBUF;
557 flip_page = 0;
558 flip_yoffset[0] = 0;
559 flip_yoffset[1] = current->h;
560 flip_address[0] = memory_base;
561 flip_address[1] = memory_base+screen_len;
562 surfaces_mem += screen_len;
563 surfaces_len -= screen_len;
564 }
565 }
566
567 /* Allocate memory tracking for hardware surfaces */
568 DGA_FreeHWSurfaces(this);
569 if ( surfaces_len < 0 ) {
570 surfaces_len = 0;
571 }
572 DGA_InitHWSurfaces(this, current, surfaces_mem, surfaces_len);
573
574 /* Expose the back buffer as surface memory */
575 if ( current->flags & SDL_DOUBLEBUF ) {
576 this->screen = current;
577 DGA_FlipHWSurface(this, current);
578 this->screen = NULL;
579 }
580
581 /* Set the update rectangle function */
582 this->UpdateRects = DGA_DirectUpdate;
583
584 /* Enable mouse and keyboard support */
585 { long input_mask;
586 input_mask = (KeyPressMask | KeyReleaseMask);
587 input_mask |= (ButtonPressMask | ButtonReleaseMask);
588 input_mask |= PointerMotionMask;
589 SDL_NAME(XDGASelectInput)(DGA_Display, DGA_Screen, input_mask);
590 }
591
592 /* We're done */
593 return(current);
594}
595
596#ifdef DGA_DEBUG
597static void DGA_DumpHWSurfaces(_THIS)
598{
599 vidmem_bucket *bucket;
600
601 printf("Memory left: %d (%d total)\n", surfaces_memleft, surfaces_memtotal);
602 printf("\n");
603 printf(" Base Size\n");
604 for ( bucket=&surfaces; bucket; bucket=bucket->next ) {
605 printf("Bucket: %p, %d (%s)\n", bucket->base, bucket->size, bucket->used ? "used" : "free");
606 if ( bucket->prev ) {
607 if ( bucket->base != bucket->prev->base+bucket->prev->size ) {
608 printf("Warning, corrupt bucket list! (prev)\n");
609 }
610 } else {
611 if ( bucket != &surfaces ) {
612 printf("Warning, corrupt bucket list! (!prev)\n");
613 }
614 }
615 if ( bucket->next ) {
616 if ( bucket->next->base != bucket->base+bucket->size ) {
617 printf("Warning, corrupt bucket list! (next)\n");
618 }
619 }
620 }
621 printf("\n");
622}
623#endif
624
625static int DGA_InitHWSurfaces(_THIS, SDL_Surface *screen, Uint8 *base, int size)
626{
627 vidmem_bucket *bucket;
628
629 surfaces_memtotal = size;
630 surfaces_memleft = size;
631
632 if ( surfaces_memleft > 0 ) {
633 bucket = (vidmem_bucket *)SDL_malloc(sizeof(*bucket));
634 if ( bucket == NULL ) {
635 SDL_OutOfMemory();
636 return(-1);
637 }
638 bucket->prev = &surfaces;
639 bucket->used = 0;
640 bucket->dirty = 0;
641 bucket->base = base;
642 bucket->size = size;
643 bucket->next = NULL;
644 } else {
645 bucket = NULL;
646 }
647
648 surfaces.prev = NULL;
649 surfaces.used = 1;
650 surfaces.dirty = 0;
651 surfaces.base = screen->pixels;
652 surfaces.size = (unsigned int)((long)base - (long)surfaces.base);
653 surfaces.next = bucket;
654 screen->hwdata = (struct private_hwdata *)((char*)&surfaces);
655 return(0);
656}
657static void DGA_FreeHWSurfaces(_THIS)
658{
659 vidmem_bucket *bucket, *freeable;
660
661 bucket = surfaces.next;
662 while ( bucket ) {
663 freeable = bucket;
664 bucket = bucket->next;
665 SDL_free(freeable);
666 }
667 surfaces.next = NULL;
668}
669
670static __inline__ void DGA_AddBusySurface(SDL_Surface *surface)
671{
672 ((vidmem_bucket *)surface->hwdata)->dirty = 1;
673}
674
675static __inline__ int DGA_IsSurfaceBusy(SDL_Surface *surface)
676{
677 return ((vidmem_bucket *)surface->hwdata)->dirty;
678}
679
680static __inline__ void DGA_WaitBusySurfaces(_THIS)
681{
682 vidmem_bucket *bucket;
683
684 /* Wait for graphic operations to complete */
685 SDL_NAME(XDGASync)(DGA_Display, DGA_Screen);
686
687 /* Clear all surface dirty bits */
688 for ( bucket=&surfaces; bucket; bucket=bucket->next ) {
689 bucket->dirty = 0;
690 }
691}
692
693static int DGA_AllocHWSurface(_THIS, SDL_Surface *surface)
694{
695 vidmem_bucket *bucket;
696 int size;
697 int extra;
698 int retval = 0;
699
700/* Temporarily, we only allow surfaces the same width as display.
701 Some blitters require the pitch between two hardware surfaces
702 to be the same. Others have interesting alignment restrictions.
703*/
704if ( surface->pitch > SDL_VideoSurface->pitch ) {
705 SDL_SetError("Surface requested wider than screen");
706 return(-1);
707}
708surface->pitch = SDL_VideoSurface->pitch;
709 size = surface->h * surface->pitch;
710#ifdef DGA_DEBUG
711 fprintf(stderr, "Allocating bucket of %d bytes\n", size);
712#endif
713 LOCK_DISPLAY();
714
715 /* Quick check for available mem */
716 if ( size > surfaces_memleft ) {
717 SDL_SetError("Not enough video memory");
718 retval = -1;
719 goto done;
720 }
721
722 /* Search for an empty bucket big enough */
723 for ( bucket=&surfaces; bucket; bucket=bucket->next ) {
724 if ( ! bucket->used && (size <= bucket->size) ) {
725 break;
726 }
727 }
728 if ( bucket == NULL ) {
729 SDL_SetError("Video memory too fragmented");
730 retval = -1;
731 goto done;
732 }
733
734 /* Create a new bucket for left-over memory */
735 extra = (bucket->size - size);
736 if ( extra ) {
737 vidmem_bucket *newbucket;
738
739#ifdef DGA_DEBUG
740 fprintf(stderr, "Adding new free bucket of %d bytes\n", extra);
741#endif
742 newbucket = (vidmem_bucket *)SDL_malloc(sizeof(*newbucket));
743 if ( newbucket == NULL ) {
744 SDL_OutOfMemory();
745 retval = -1;
746 goto done;
747 }
748 newbucket->prev = bucket;
749 newbucket->used = 0;
750 newbucket->base = bucket->base+size;
751 newbucket->size = extra;
752 newbucket->next = bucket->next;
753 if ( bucket->next ) {
754 bucket->next->prev = newbucket;
755 }
756 bucket->next = newbucket;
757 }
758
759 /* Set the current bucket values and return it! */
760 bucket->used = 1;
761 bucket->size = size;
762 bucket->dirty = 0;
763#ifdef DGA_DEBUG
764 fprintf(stderr, "Allocated %d bytes at %p\n", bucket->size, bucket->base);
765#endif
766 surfaces_memleft -= size;
767 surface->flags |= SDL_HWSURFACE;
768 surface->pixels = bucket->base;
769 surface->hwdata = (struct private_hwdata *)bucket;
770done:
771 UNLOCK_DISPLAY();
772 return(retval);
773}
774static void DGA_FreeHWSurface(_THIS, SDL_Surface *surface)
775{
776 vidmem_bucket *bucket, *freeable;
777
778 /* Wait for any pending operations involving this surface */
779 if ( DGA_IsSurfaceBusy(surface) ) {
780 LOCK_DISPLAY();
781 DGA_WaitBusySurfaces(this);
782 UNLOCK_DISPLAY();
783 }
784
785 /* Look for the bucket in the current list */
786 for ( bucket=&surfaces; bucket; bucket=bucket->next ) {
787 if ( bucket == (vidmem_bucket *)surface->hwdata ) {
788 break;
789 }
790 }
791 if ( bucket && bucket->used ) {
792 /* Add the memory back to the total */
793#ifdef DGA_DEBUG
794 printf("Freeing bucket of %d bytes\n", bucket->size);
795#endif
796 surfaces_memleft += bucket->size;
797
798 /* Can we merge the space with surrounding buckets? */
799 bucket->used = 0;
800 if ( bucket->next && ! bucket->next->used ) {
801#ifdef DGA_DEBUG
802 printf("Merging with next bucket, for %d total bytes\n", bucket->size+bucket->next->size);
803#endif
804 freeable = bucket->next;
805 bucket->size += bucket->next->size;
806 bucket->next = bucket->next->next;
807 if ( bucket->next ) {
808 bucket->next->prev = bucket;
809 }
810 SDL_free(freeable);
811 }
812 if ( bucket->prev && ! bucket->prev->used ) {
813#ifdef DGA_DEBUG
814 printf("Merging with previous bucket, for %d total bytes\n", bucket->prev->size+bucket->size);
815#endif
816 freeable = bucket;
817 bucket->prev->size += bucket->size;
818 bucket->prev->next = bucket->next;
819 if ( bucket->next ) {
820 bucket->next->prev = bucket->prev;
821 }
822 SDL_free(freeable);
823 }
824 }
825 surface->pixels = NULL;
826 surface->hwdata = NULL;
827}
828
829static __inline__ void DGA_dst_to_xy(_THIS, SDL_Surface *dst, int *x, int *y)
830{
831 *x = (long)((Uint8 *)dst->pixels - memory_base)%memory_pitch;
832 *y = (long)((Uint8 *)dst->pixels - memory_base)/memory_pitch;
833}
834
835static int DGA_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color)
836{
837 int x, y;
838 unsigned int w, h;
839
840 /* Don't fill the visible part of the screen, wait until flipped */
841 LOCK_DISPLAY();
842 if ( was_flipped && (dst == this->screen) ) {
843 while ( SDL_NAME(XDGAGetViewportStatus)(DGA_Display, DGA_Screen) )
844 /* Keep waiting for the hardware ... */ ;
845 was_flipped = 0;
846 }
847 DGA_dst_to_xy(this, dst, &x, &y);
848 x += rect->x;
849 y += rect->y;
850 w = rect->w;
851 h = rect->h;
852#if 0
853 printf("Hardware accelerated rectangle fill: %dx%d at %d,%d\n", w, h, x, y);
854#endif
855 SDL_NAME(XDGAFillRectangle)(DGA_Display, DGA_Screen, x, y, w, h, color);
856 if ( !(this->screen->flags & SDL_DOUBLEBUF) ) {
857 XFlush(DGA_Display);
858 }
859 DGA_AddBusySurface(dst);
860 UNLOCK_DISPLAY();
861 return(0);
862}
863
864static int HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
865 SDL_Surface *dst, SDL_Rect *dstrect)
866{
867 SDL_VideoDevice *this;
868 int srcx, srcy;
869 int dstx, dsty;
870 unsigned int w, h;
871
872 this = current_video;
873 /* Don't blit to the visible part of the screen, wait until flipped */
874 LOCK_DISPLAY();
875 if ( was_flipped && (dst == this->screen) ) {
876 while ( SDL_NAME(XDGAGetViewportStatus)(DGA_Display, DGA_Screen) )
877 /* Keep waiting for the hardware ... */ ;
878 was_flipped = 0;
879 }
880 DGA_dst_to_xy(this, src, &srcx, &srcy);
881 srcx += srcrect->x;
882 srcy += srcrect->y;
883 DGA_dst_to_xy(this, dst, &dstx, &dsty);
884 dstx += dstrect->x;
885 dsty += dstrect->y;
886 w = srcrect->w;
887 h = srcrect->h;
888#if 0
889 printf("Blitting %dx%d from %d,%d to %d,%d\n", w, h, srcx, srcy, dstx, dsty);
890#endif
891 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
892 SDL_NAME(XDGACopyTransparentArea)(DGA_Display, DGA_Screen,
893 srcx, srcy, w, h, dstx, dsty, src->format->colorkey);
894 } else {
895 SDL_NAME(XDGACopyArea)(DGA_Display, DGA_Screen,
896 srcx, srcy, w, h, dstx, dsty);
897 }
898 if ( !(this->screen->flags & SDL_DOUBLEBUF) ) {
899 XFlush(DGA_Display);
900 }
901 DGA_AddBusySurface(src);
902 DGA_AddBusySurface(dst);
903 UNLOCK_DISPLAY();
904 return(0);
905}
906
907static int DGA_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst)
908{
909 int accelerated;
910
911 /* Set initial acceleration on */
912 src->flags |= SDL_HWACCEL;
913
914 /* Set the surface attributes */
915 if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
916 if ( ! this->info.blit_hw_A ) {
917 src->flags &= ~SDL_HWACCEL;
918 }
919 }
920 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
921 if ( ! this->info.blit_hw_CC ) {
922 src->flags &= ~SDL_HWACCEL;
923 }
924 }
925
926 /* Check to see if final surface blit is accelerated */
927 accelerated = !!(src->flags & SDL_HWACCEL);
928 if ( accelerated ) {
929 src->map->hw_blit = HWAccelBlit;
930 }
931 return(accelerated);
932}
933
934static __inline__ void DGA_WaitFlip(_THIS)
935{
936 if ( was_flipped ) {
937 while ( SDL_NAME(XDGAGetViewportStatus)(DGA_Display, DGA_Screen) )
938 /* Keep waiting for the hardware ... */ ;
939 was_flipped = 0;
940 }
941}
942
943static int DGA_LockHWSurface(_THIS, SDL_Surface *surface)
944{
945 if ( surface == this->screen ) {
946 SDL_mutexP(hw_lock);
947 LOCK_DISPLAY();
948 if ( DGA_IsSurfaceBusy(surface) ) {
949 DGA_WaitBusySurfaces(this);
950 }
951 DGA_WaitFlip(this);
952 UNLOCK_DISPLAY();
953 } else {
954 if ( DGA_IsSurfaceBusy(surface) ) {
955 LOCK_DISPLAY();
956 DGA_WaitBusySurfaces(this);
957 UNLOCK_DISPLAY();
958 }
959 }
960 return(0);
961}
962static void DGA_UnlockHWSurface(_THIS, SDL_Surface *surface)
963{
964 if ( surface == this->screen ) {
965 SDL_mutexV(hw_lock);
966 }
967}
968
969static int DGA_FlipHWSurface(_THIS, SDL_Surface *surface)
970{
971 /* Wait for vertical retrace and then flip display */
972 LOCK_DISPLAY();
973 if ( DGA_IsSurfaceBusy(this->screen) ) {
974 DGA_WaitBusySurfaces(this);
975 }
976 DGA_WaitFlip(this);
977 SDL_NAME(XDGASetViewport)(DGA_Display, DGA_Screen,
978 0, flip_yoffset[flip_page], XDGAFlipRetrace);
979 XFlush(DGA_Display);
980 UNLOCK_DISPLAY();
981 was_flipped = 1;
982 flip_page = !flip_page;
983
984 surface->pixels = flip_address[flip_page];
985 return(0);
986}
987
988static void DGA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
989{
990 /* The application is already updating the visible video memory */
991 return;
992}
993
994static int DGA_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
995{
996 int i;
997 XColor *xcmap;
998
999 /* This happens on initialization */
1000 if ( ! DGA_colormap ) {
1001 return(0);
1002 }
1003 xcmap = SDL_stack_alloc(XColor, ncolors);
1004 for ( i=0; i<ncolors; ++i ) {
1005 xcmap[i].pixel = firstcolor + i;
1006 xcmap[i].red = (colors[i].r<<8)|colors[i].r;
1007 xcmap[i].green = (colors[i].g<<8)|colors[i].g;
1008 xcmap[i].blue = (colors[i].b<<8)|colors[i].b;
1009 xcmap[i].flags = (DoRed|DoGreen|DoBlue);
1010 }
1011 LOCK_DISPLAY();
1012 XStoreColors(DGA_Display, DGA_colormap, xcmap, ncolors);
1013 XSync(DGA_Display, False);
1014 UNLOCK_DISPLAY();
1015 SDL_stack_free(xcmap);
1016
1017 /* That was easy. :) */
1018 return(1);
1019}
1020
1021int DGA_SetGammaRamp(_THIS, Uint16 *ramp)
1022{
1023 int i, ncolors;
1024 XColor xcmap[256];
1025
1026 /* See if actually setting the gamma is supported */
1027 if ( DGA_visualClass != DirectColor ) {
1028 SDL_SetError("Gamma correction not supported on this visual");
1029 return(-1);
1030 }
1031
1032 /* Calculate the appropriate palette for the given gamma ramp */
1033 if ( this->screen->format->BitsPerPixel <= 16 ) {
1034 ncolors = 64; /* Is this right? */
1035 } else {
1036 ncolors = 256;
1037 }
1038 for ( i=0; i<ncolors; ++i ) {
1039 Uint8 c = (256 * i / ncolors);
1040 xcmap[i].pixel = SDL_MapRGB(this->screen->format, c, c, c);
1041 xcmap[i].red = ramp[0*256+c];
1042 xcmap[i].green = ramp[1*256+c];
1043 xcmap[i].blue = ramp[2*256+c];
1044 xcmap[i].flags = (DoRed|DoGreen|DoBlue);
1045 }
1046 LOCK_DISPLAY();
1047 XStoreColors(DGA_Display, DGA_colormap, xcmap, ncolors);
1048 XSync(DGA_Display, False);
1049 UNLOCK_DISPLAY();
1050 return(0);
1051}
1052
1053void DGA_VideoQuit(_THIS)
1054{
1055 int i, j;
1056
1057 if ( DGA_Display ) {
1058 /* Free colormap, if necessary */
1059 if ( DGA_colormap ) {
1060 XFreeColormap(DGA_Display, DGA_colormap);
1061 DGA_colormap = 0;
1062 }
1063
1064 /* Unmap memory and reset video mode */
1065 SDL_NAME(XDGACloseFramebuffer)(DGA_Display, DGA_Screen);
1066 if ( this->screen ) {
1067 /* Tell SDL not to free the pixels */
1068 DGA_FreeHWSurface(this, this->screen);
1069 }
1070 SDL_NAME(XDGASetMode)(DGA_Display, DGA_Screen, 0);
1071
1072 /* Clear the lock mutex */
1073 if ( hw_lock != NULL ) {
1074 SDL_DestroyMutex(hw_lock);
1075 hw_lock = NULL;
1076 }
1077#ifdef LOCK_DGA_DISPLAY
1078 if ( event_lock != NULL ) {
1079 SDL_DestroyMutex(event_lock);
1080 event_lock = NULL;
1081 }
1082#endif /* LOCK_DGA_DISPLAY */
1083
1084 /* Clean up defined video modes */
1085 for ( i=0; i<NUM_MODELISTS; ++i ) {
1086 if ( SDL_modelist[i] != NULL ) {
1087 for ( j=0; SDL_modelist[i][j]; ++j ) {
1088 SDL_free(SDL_modelist[i][j]);
1089 }
1090 SDL_free(SDL_modelist[i]);
1091 SDL_modelist[i] = NULL;
1092 }
1093 }
1094
1095 /* Clean up the memory bucket list */
1096 DGA_FreeHWSurfaces(this);
1097
1098 /* Close up the display */
1099 XCloseDisplay(DGA_Display);
1100 }
1101}
diff --git a/apps/plugins/sdl/src/video/dga/SDL_dgavideo.h b/apps/plugins/sdl/src/video/dga/SDL_dgavideo.h
deleted file mode 100644
index bd2ecb8d59..0000000000
--- a/apps/plugins/sdl/src/video/dga/SDL_dgavideo.h
+++ /dev/null
@@ -1,124 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_dgavideo_h
25#define _SDL_dgavideo_h
26
27#include <X11/Xlib.h>
28
29/* Apparently some X11 systems can't include this multiple times... */
30#ifndef SDL_INCLUDED_XLIBINT_H
31#define SDL_INCLUDED_XLIBINT_H 1
32#include <X11/Xlibint.h>
33#endif
34
35#include <X11/Xproto.h>
36
37#include "SDL_mouse.h"
38#include "SDL_mutex.h"
39#include "../SDL_sysvideo.h"
40
41/* Hidden "this" pointer for the video functions */
42#define _THIS SDL_VideoDevice *this
43
44/* Define this if you need the DGA driver to be thread-safe */
45#define LOCK_DGA_DISPLAY
46#ifdef LOCK_DGA_DISPLAY
47#define LOCK_DISPLAY() SDL_mutexP(event_lock)
48#define UNLOCK_DISPLAY() SDL_mutexV(event_lock)
49#else
50#define LOCK_DISPLAY()
51#define UNLOCK_DISPLAY()
52#endif
53
54
55/* This is the structure we use to keep track of video memory */
56typedef struct vidmem_bucket {
57 struct vidmem_bucket *prev;
58 int used;
59 int dirty;
60 Uint8 *base;
61 unsigned int size;
62 struct vidmem_bucket *next;
63} vidmem_bucket;
64
65/* Private display data */
66struct SDL_PrivateVideoData {
67 Display *DGA_Display;
68 Colormap DGA_colormap;
69 int visualClass;
70
71#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
72 int SDL_nummodes[NUM_MODELISTS];
73 SDL_Rect **SDL_modelist[NUM_MODELISTS];
74
75 /* Information for the video surface */
76 Uint8 *memory_base;
77 int memory_pitch;
78 SDL_mutex *hw_lock;
79 int sync_needed;
80 int was_flipped;
81
82 /* Information for hardware surfaces */
83 vidmem_bucket surfaces;
84 int surfaces_memtotal;
85 int surfaces_memleft;
86
87 /* Information for double-buffering */
88 int flip_page;
89 int flip_yoffset[2];
90 Uint8 *flip_address[2];
91
92 /* Used to handle DGA events */
93 int event_base;
94#ifdef LOCK_DGA_DISPLAY
95 SDL_mutex *event_lock;
96#endif
97
98 /* Screensaver settings */
99 int allow_screensaver;
100};
101
102/* Old variable names */
103#define DGA_Display (this->hidden->DGA_Display)
104#define DGA_Screen DefaultScreen(DGA_Display)
105#define DGA_colormap (this->hidden->DGA_colormap)
106#define DGA_visualClass (this->hidden->visualClass)
107#define memory_base (this->hidden->memory_base)
108#define memory_pitch (this->hidden->memory_pitch)
109#define flip_page (this->hidden->flip_page)
110#define flip_yoffset (this->hidden->flip_yoffset)
111#define flip_address (this->hidden->flip_address)
112#define sync_needed (this->hidden->sync_needed)
113#define was_flipped (this->hidden->was_flipped)
114#define SDL_nummodes (this->hidden->SDL_nummodes)
115#define SDL_modelist (this->hidden->SDL_modelist)
116#define surfaces (this->hidden->surfaces)
117#define surfaces_memtotal (this->hidden->surfaces_memtotal)
118#define surfaces_memleft (this->hidden->surfaces_memleft)
119#define hw_lock (this->hidden->hw_lock)
120#define DGA_event_base (this->hidden->event_base)
121#define event_lock (this->hidden->event_lock)
122#define allow_screensaver (this->hidden->allow_screensaver)
123
124#endif /* _SDL_dgavideo_h */
diff --git a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_events.c b/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_events.c
deleted file mode 100644
index 246b75b176..0000000000
--- a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_events.c
+++ /dev/null
@@ -1,219 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting DirectFB input events into SDL events */
25
26#include <sys/types.h>
27#include <sys/time.h>
28#include <unistd.h>
29#include <fcntl.h>
30#include <termios.h>
31
32#include <directfb.h>
33
34#include "SDL.h"
35#include "../SDL_sysvideo.h"
36#include "../../events/SDL_sysevents.h"
37#include "../../events/SDL_events_c.h"
38#include "SDL_DirectFB_video.h"
39#include "SDL_DirectFB_events.h"
40
41/* The translation tables from a DirectFB keycode to a SDL keysym */
42static SDLKey keymap[256];
43static SDL_keysym *DirectFB_TranslateKey (DFBInputEvent *ev, SDL_keysym *keysym);
44static int DirectFB_TranslateButton (DFBInputEvent *ev);
45
46static int posted = 0;
47
48
49void DirectFB_PumpEvents (_THIS)
50{
51 DFBInputEvent evt;
52
53 while (HIDDEN->eventbuffer->GetEvent (HIDDEN->eventbuffer,
54 DFB_EVENT (&evt)) == DFB_OK)
55 {
56 SDL_keysym keysym;
57
58 switch (evt.type)
59 {
60 case DIET_BUTTONPRESS:
61 posted += SDL_PrivateMouseButton(SDL_PRESSED,
62 DirectFB_TranslateButton (&evt), 0, 0);
63 break;
64 case DIET_BUTTONRELEASE:
65 posted += SDL_PrivateMouseButton(SDL_RELEASED,
66 DirectFB_TranslateButton (&evt), 0, 0);
67 break;
68 case DIET_KEYPRESS:
69 posted += SDL_PrivateKeyboard(SDL_PRESSED, DirectFB_TranslateKey(&evt, &keysym));
70 break;
71 case DIET_KEYRELEASE:
72 posted += SDL_PrivateKeyboard(SDL_RELEASED, DirectFB_TranslateKey(&evt, &keysym));
73 break;
74 case DIET_AXISMOTION:
75 if (evt.flags & DIEF_AXISREL)
76 {
77 if (evt.axis == DIAI_X)
78 posted += SDL_PrivateMouseMotion(0, 1, evt.axisrel, 0);
79 else if (evt.axis == DIAI_Y)
80 posted += SDL_PrivateMouseMotion(0, 1, 0, evt.axisrel);
81 }
82 else if (evt.flags & DIEF_AXISABS)
83 {
84 static int last_x, last_y;
85 if (evt.axis == DIAI_X)
86 last_x = evt.axisabs;
87 else if (evt.axis == DIAI_Y)
88 last_y = evt.axisabs;
89 posted += SDL_PrivateMouseMotion(0, 0, last_x, last_y);
90 }
91 break;
92 default:
93 ;
94 }
95 }
96}
97
98void DirectFB_InitOSKeymap (_THIS)
99{
100 int i;
101
102 /* Initialize the DirectFB key translation table */
103 for (i=0; i<SDL_arraysize(keymap); ++i)
104 keymap[i] = SDLK_UNKNOWN;
105
106 keymap[DIKI_A - DIKI_UNKNOWN] = SDLK_a;
107 keymap[DIKI_B - DIKI_UNKNOWN] = SDLK_b;
108 keymap[DIKI_C - DIKI_UNKNOWN] = SDLK_c;
109 keymap[DIKI_D - DIKI_UNKNOWN] = SDLK_d;
110 keymap[DIKI_E - DIKI_UNKNOWN] = SDLK_e;
111 keymap[DIKI_F - DIKI_UNKNOWN] = SDLK_f;
112 keymap[DIKI_G - DIKI_UNKNOWN] = SDLK_g;
113 keymap[DIKI_H - DIKI_UNKNOWN] = SDLK_h;
114 keymap[DIKI_I - DIKI_UNKNOWN] = SDLK_i;
115 keymap[DIKI_J - DIKI_UNKNOWN] = SDLK_j;
116 keymap[DIKI_K - DIKI_UNKNOWN] = SDLK_k;
117 keymap[DIKI_L - DIKI_UNKNOWN] = SDLK_l;
118 keymap[DIKI_M - DIKI_UNKNOWN] = SDLK_m;
119 keymap[DIKI_N - DIKI_UNKNOWN] = SDLK_n;
120 keymap[DIKI_O - DIKI_UNKNOWN] = SDLK_o;
121 keymap[DIKI_P - DIKI_UNKNOWN] = SDLK_p;
122 keymap[DIKI_Q - DIKI_UNKNOWN] = SDLK_q;
123 keymap[DIKI_R - DIKI_UNKNOWN] = SDLK_r;
124 keymap[DIKI_S - DIKI_UNKNOWN] = SDLK_s;
125 keymap[DIKI_T - DIKI_UNKNOWN] = SDLK_t;
126 keymap[DIKI_U - DIKI_UNKNOWN] = SDLK_u;
127 keymap[DIKI_V - DIKI_UNKNOWN] = SDLK_v;
128 keymap[DIKI_W - DIKI_UNKNOWN] = SDLK_w;
129 keymap[DIKI_X - DIKI_UNKNOWN] = SDLK_x;
130 keymap[DIKI_Y - DIKI_UNKNOWN] = SDLK_y;
131 keymap[DIKI_Z - DIKI_UNKNOWN] = SDLK_z;
132
133 keymap[DIKI_0 - DIKI_UNKNOWN] = SDLK_0;
134 keymap[DIKI_1 - DIKI_UNKNOWN] = SDLK_1;
135 keymap[DIKI_2 - DIKI_UNKNOWN] = SDLK_2;
136 keymap[DIKI_3 - DIKI_UNKNOWN] = SDLK_3;
137 keymap[DIKI_4 - DIKI_UNKNOWN] = SDLK_4;
138 keymap[DIKI_5 - DIKI_UNKNOWN] = SDLK_5;
139 keymap[DIKI_6 - DIKI_UNKNOWN] = SDLK_6;
140 keymap[DIKI_7 - DIKI_UNKNOWN] = SDLK_7;
141 keymap[DIKI_8 - DIKI_UNKNOWN] = SDLK_8;
142 keymap[DIKI_9 - DIKI_UNKNOWN] = SDLK_9;
143
144 keymap[DIKI_F1 - DIKI_UNKNOWN] = SDLK_F1;
145 keymap[DIKI_F2 - DIKI_UNKNOWN] = SDLK_F2;
146 keymap[DIKI_F3 - DIKI_UNKNOWN] = SDLK_F3;
147 keymap[DIKI_F4 - DIKI_UNKNOWN] = SDLK_F4;
148 keymap[DIKI_F5 - DIKI_UNKNOWN] = SDLK_F5;
149 keymap[DIKI_F6 - DIKI_UNKNOWN] = SDLK_F6;
150 keymap[DIKI_F7 - DIKI_UNKNOWN] = SDLK_F7;
151 keymap[DIKI_F8 - DIKI_UNKNOWN] = SDLK_F8;
152 keymap[DIKI_F9 - DIKI_UNKNOWN] = SDLK_F9;
153 keymap[DIKI_F10 - DIKI_UNKNOWN] = SDLK_F10;
154 keymap[DIKI_F11 - DIKI_UNKNOWN] = SDLK_F11;
155 keymap[DIKI_F12 - DIKI_UNKNOWN] = SDLK_F12;
156
157 keymap[DIKI_ESCAPE - DIKI_UNKNOWN] = SDLK_ESCAPE;
158 keymap[DIKI_LEFT - DIKI_UNKNOWN] = SDLK_LEFT;
159 keymap[DIKI_RIGHT - DIKI_UNKNOWN] = SDLK_RIGHT;
160 keymap[DIKI_UP - DIKI_UNKNOWN] = SDLK_UP;
161 keymap[DIKI_DOWN - DIKI_UNKNOWN] = SDLK_DOWN;
162 keymap[DIKI_CONTROL_L - DIKI_UNKNOWN] = SDLK_LCTRL;
163 keymap[DIKI_CONTROL_R - DIKI_UNKNOWN] = SDLK_RCTRL;
164 keymap[DIKI_SHIFT_L - DIKI_UNKNOWN] = SDLK_LSHIFT;
165 keymap[DIKI_SHIFT_R - DIKI_UNKNOWN] = SDLK_RSHIFT;
166 keymap[DIKI_ALT_L - DIKI_UNKNOWN] = SDLK_LALT;
167 keymap[DIKI_ALT_R - DIKI_UNKNOWN] = SDLK_RALT;
168 keymap[DIKI_TAB - DIKI_UNKNOWN] = SDLK_TAB;
169 keymap[DIKI_ENTER - DIKI_UNKNOWN] = SDLK_RETURN;
170 keymap[DIKI_SPACE - DIKI_UNKNOWN] = SDLK_SPACE;
171 keymap[DIKI_BACKSPACE - DIKI_UNKNOWN] = SDLK_BACKSPACE;
172 keymap[DIKI_INSERT - DIKI_UNKNOWN] = SDLK_INSERT;
173 keymap[DIKI_DELETE - DIKI_UNKNOWN] = SDLK_DELETE;
174 keymap[DIKI_HOME - DIKI_UNKNOWN] = SDLK_HOME;
175 keymap[DIKI_END - DIKI_UNKNOWN] = SDLK_END;
176 keymap[DIKI_PAGE_UP - DIKI_UNKNOWN] = SDLK_PAGEUP;
177 keymap[DIKI_PAGE_DOWN - DIKI_UNKNOWN] = SDLK_PAGEDOWN;
178 keymap[DIKI_CAPS_LOCK - DIKI_UNKNOWN] = SDLK_CAPSLOCK;
179 keymap[DIKI_NUM_LOCK - DIKI_UNKNOWN] = SDLK_NUMLOCK;
180 keymap[DIKI_SCROLL_LOCK - DIKI_UNKNOWN] = SDLK_SCROLLOCK;
181 keymap[DIKI_PRINT - DIKI_UNKNOWN] = SDLK_PRINT;
182 keymap[DIKI_PAUSE - DIKI_UNKNOWN] = SDLK_PAUSE;
183 keymap[DIKI_KP_DIV - DIKI_UNKNOWN] = SDLK_KP_DIVIDE;
184 keymap[DIKI_KP_MULT - DIKI_UNKNOWN] = SDLK_KP_MULTIPLY;
185 keymap[DIKI_KP_MINUS - DIKI_UNKNOWN] = SDLK_KP_MINUS;
186 keymap[DIKI_KP_PLUS - DIKI_UNKNOWN] = SDLK_KP_PLUS;
187 keymap[DIKI_KP_ENTER - DIKI_UNKNOWN] = SDLK_KP_ENTER;
188}
189
190
191static SDL_keysym *DirectFB_TranslateKey (DFBInputEvent *ev, SDL_keysym *keysym)
192{
193 /* Set the keysym information */
194 keysym->scancode = ev->key_id;
195 keysym->mod = KMOD_NONE; /* FIXME */
196 keysym->unicode = (DFB_KEY_TYPE (ev->key_symbol) == DIKT_UNICODE) ? ev->key_symbol : 0;
197
198 if (ev->key_symbol > 0 && ev->key_symbol < 128)
199 keysym->sym = ev->key_symbol;
200 else
201 keysym->sym = keymap[ev->key_id - DIKI_UNKNOWN];
202
203 return keysym;
204}
205
206static int DirectFB_TranslateButton (DFBInputEvent *ev)
207{
208 switch (ev->button)
209 {
210 case DIBI_LEFT:
211 return 1;
212 case DIBI_MIDDLE:
213 return 2;
214 case DIBI_RIGHT:
215 return 3;
216 default:
217 return 0;
218 }
219}
diff --git a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_events.h b/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_events.h
deleted file mode 100644
index 20f3967271..0000000000
--- a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_events.h
+++ /dev/null
@@ -1,29 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_DirectFB_video.h"
25
26/* Functions to be exported */
27extern void DirectFB_InitOSKeymap(_THIS);
28extern void DirectFB_PumpEvents(_THIS);
29
diff --git a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_keys.h b/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_keys.h
deleted file mode 100644
index 2868ee6ffa..0000000000
--- a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_keys.h
+++ /dev/null
@@ -1,135 +0,0 @@
1
2#define SCANCODE_ESCAPE 1
3
4#define SCANCODE_1 2
5#define SCANCODE_2 3
6#define SCANCODE_3 4
7#define SCANCODE_4 5
8#define SCANCODE_5 6
9#define SCANCODE_6 7
10#define SCANCODE_7 8
11#define SCANCODE_8 9
12#define SCANCODE_9 10
13#define SCANCODE_0 11
14
15#define SCANCODE_MINUS 12
16#define SCANCODE_EQUAL 13
17
18#define SCANCODE_BACKSPACE 14
19#define SCANCODE_TAB 15
20
21#define SCANCODE_Q 16
22#define SCANCODE_W 17
23#define SCANCODE_E 18
24#define SCANCODE_R 19
25#define SCANCODE_T 20
26#define SCANCODE_Y 21
27#define SCANCODE_U 22
28#define SCANCODE_I 23
29#define SCANCODE_O 24
30#define SCANCODE_P 25
31#define SCANCODE_BRACKET_LEFT 26
32#define SCANCODE_BRACKET_RIGHT 27
33
34#define SCANCODE_ENTER 28
35
36#define SCANCODE_LEFTCONTROL 29
37
38#define SCANCODE_A 30
39#define SCANCODE_S 31
40#define SCANCODE_D 32
41#define SCANCODE_F 33
42#define SCANCODE_G 34
43#define SCANCODE_H 35
44#define SCANCODE_J 36
45#define SCANCODE_K 37
46#define SCANCODE_L 38
47#define SCANCODE_SEMICOLON 39
48#define SCANCODE_APOSTROPHE 40
49#define SCANCODE_GRAVE 41
50
51#define SCANCODE_LEFTSHIFT 42
52#define SCANCODE_BACKSLASH 43
53
54#define SCANCODE_Z 44
55#define SCANCODE_X 45
56#define SCANCODE_C 46
57#define SCANCODE_V 47
58#define SCANCODE_B 48
59#define SCANCODE_N 49
60#define SCANCODE_M 50
61#define SCANCODE_COMMA 51
62#define SCANCODE_PERIOD 52
63#define SCANCODE_SLASH 53
64
65#define SCANCODE_RIGHTSHIFT 54
66#define SCANCODE_KEYPADMULTIPLY 55
67
68#define SCANCODE_LEFTALT 56
69#define SCANCODE_SPACE 57
70#define SCANCODE_CAPSLOCK 58
71
72#define SCANCODE_F1 59
73#define SCANCODE_F2 60
74#define SCANCODE_F3 61
75#define SCANCODE_F4 62
76#define SCANCODE_F5 63
77#define SCANCODE_F6 64
78#define SCANCODE_F7 65
79#define SCANCODE_F8 66
80#define SCANCODE_F9 67
81#define SCANCODE_F10 68
82
83#define SCANCODE_NUMLOCK 69
84#define SCANCODE_SCROLLLOCK 70
85
86#define SCANCODE_KEYPAD7 71
87#define SCANCODE_CURSORUPLEFT 71
88#define SCANCODE_KEYPAD8 72
89#define SCANCODE_CURSORUP 72
90#define SCANCODE_KEYPAD9 73
91#define SCANCODE_CURSORUPRIGHT 73
92#define SCANCODE_KEYPADMINUS 74
93#define SCANCODE_KEYPAD4 75
94#define SCANCODE_CURSORLEFT 75
95#define SCANCODE_KEYPAD5 76
96#define SCANCODE_KEYPAD6 77
97#define SCANCODE_CURSORRIGHT 77
98#define SCANCODE_KEYPADPLUS 78
99#define SCANCODE_KEYPAD1 79
100#define SCANCODE_CURSORDOWNLEFT 79
101#define SCANCODE_KEYPAD2 80
102#define SCANCODE_CURSORDOWN 80
103#define SCANCODE_KEYPAD3 81
104#define SCANCODE_CURSORDOWNRIGHT 81
105#define SCANCODE_KEYPAD0 82
106#define SCANCODE_KEYPADPERIOD 83
107
108#define SCANCODE_LESS 86
109
110#define SCANCODE_F11 87
111#define SCANCODE_F12 88
112
113#define SCANCODE_KEYPADENTER 96
114#define SCANCODE_RIGHTCONTROL 97
115#define SCANCODE_CONTROL 97
116#define SCANCODE_KEYPADDIVIDE 98
117#define SCANCODE_PRINTSCREEN 99
118#define SCANCODE_RIGHTALT 100
119#define SCANCODE_BREAK 101 /* Beware: is 119 */
120#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */
121
122#define SCANCODE_HOME 102
123#define SCANCODE_CURSORBLOCKUP 90 /* Cursor key block */
124#define SCANCODE_PAGEUP 104
125#define SCANCODE_CURSORBLOCKLEFT 92 /* Cursor key block */
126#define SCANCODE_CURSORBLOCKRIGHT 94 /* Cursor key block */
127#define SCANCODE_END 107
128#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */
129#define SCANCODE_PAGEDOWN 109
130#define SCANCODE_INSERT 110
131#define SCANCODE_REMOVE 111
132
133#define SCANCODE_RIGHTWIN 126
134#define SCANCODE_LEFTWIN 125
135
diff --git a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_video.c b/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_video.c
deleted file mode 100644
index f665ec6825..0000000000
--- a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_video.c
+++ /dev/null
@@ -1,1171 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 MGA CRTC2 support by Thomas Jarosch - tomj@simonv.com
23 CRTC2 support is inspired by mplayer's dfbmga driver
24 written by Ville Syrj��<syrjala@sci.fi>
25*/
26#include "SDL_config.h"
27
28/* DirectFB video driver implementation.
29*/
30
31#include <fcntl.h>
32#include <unistd.h>
33#include <sys/mman.h>
34
35#include <directfb.h>
36#include <directfb_version.h>
37
38#include "SDL_video.h"
39#include "SDL_mouse.h"
40#include "../SDL_sysvideo.h"
41#include "../SDL_pixels_c.h"
42#include "../../events/SDL_events_c.h"
43#include "SDL_DirectFB_video.h"
44#include "SDL_DirectFB_events.h"
45#include "SDL_DirectFB_yuv.h"
46
47/* The implementation dependent data for the window manager cursor */
48struct WMcursor {
49 int unused;
50};
51
52
53/* Initialization/Query functions */
54static int DirectFB_VideoInit(_THIS, SDL_PixelFormat *vformat);
55static SDL_Rect **DirectFB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
56static SDL_Surface *DirectFB_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
57static int DirectFB_SetColors(_THIS, int firstcolor, int ncolors,
58 SDL_Color *colors);
59static void DirectFB_VideoQuit(_THIS);
60
61/* Hardware surface functions */
62static int DirectFB_AllocHWSurface(_THIS, SDL_Surface *surface);
63static int DirectFB_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color);
64static int DirectFB_LockHWSurface(_THIS, SDL_Surface *surface);
65static void DirectFB_UnlockHWSurface(_THIS, SDL_Surface *surface);
66static void DirectFB_FreeHWSurface(_THIS, SDL_Surface *surface);
67static int DirectFB_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst);
68static int DirectFB_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
69 SDL_Surface *dst, SDL_Rect *dstrect);
70static int DirectFB_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key);
71static int DirectFB_SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 alpha);
72static int DirectFB_FlipHWSurface(_THIS, SDL_Surface *surface);
73static int DirectFB_ShowWMCursor(_THIS, WMcursor *cursor);
74
75/* Various screen update functions available */
76static void DirectFB_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
77static void DirectFB_WindowedUpdate(_THIS, int numrects, SDL_Rect *rects);
78
79/* This is the rect EnumModes2 uses */
80struct DirectFBEnumRect {
81 SDL_Rect r;
82 struct DirectFBEnumRect* next;
83};
84
85static struct DirectFBEnumRect *enumlist = NULL;
86
87
88/* DirectFB driver bootstrap functions */
89
90static int DirectFB_Available(void)
91{
92 return 1;
93}
94
95static void DirectFB_DeleteDevice(SDL_VideoDevice *device)
96{
97 SDL_free(device->hidden);
98 SDL_free(device);
99}
100
101static SDL_VideoDevice *DirectFB_CreateDevice(int devindex)
102{
103 SDL_VideoDevice *device;
104
105 /* Initialize all variables that we clean on shutdown */
106 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
107 if (device)
108 {
109 SDL_memset (device, 0, (sizeof *device));
110 device->hidden = (struct SDL_PrivateVideoData *) malloc (sizeof (*device->hidden));
111 }
112 if (device == NULL || device->hidden == NULL)
113 {
114 SDL_OutOfMemory();
115 if (device)
116 {
117 free (device);
118 }
119 return(0);
120 }
121 SDL_memset (device->hidden, 0, sizeof (*device->hidden));
122
123 /* Set the function pointers */
124 device->VideoInit = DirectFB_VideoInit;
125 device->ListModes = DirectFB_ListModes;
126 device->SetVideoMode = DirectFB_SetVideoMode;
127 device->SetColors = DirectFB_SetColors;
128 device->UpdateRects = NULL;
129 device->CreateYUVOverlay = DirectFB_CreateYUVOverlay;
130 device->VideoQuit = DirectFB_VideoQuit;
131 device->AllocHWSurface = DirectFB_AllocHWSurface;
132 device->CheckHWBlit = DirectFB_CheckHWBlit;
133 device->FillHWRect = DirectFB_FillHWRect;
134 device->SetHWColorKey = DirectFB_SetHWColorKey;
135 device->SetHWAlpha = DirectFB_SetHWAlpha;
136 device->LockHWSurface = DirectFB_LockHWSurface;
137 device->UnlockHWSurface = DirectFB_UnlockHWSurface;
138 device->FlipHWSurface = DirectFB_FlipHWSurface;
139 device->FreeHWSurface = DirectFB_FreeHWSurface;
140 device->ShowWMCursor = DirectFB_ShowWMCursor;
141 device->SetCaption = NULL;
142 device->SetIcon = NULL;
143 device->IconifyWindow = NULL;
144 device->GrabInput = NULL;
145 device->GetWMInfo = NULL;
146 device->InitOSKeymap = DirectFB_InitOSKeymap;
147 device->PumpEvents = DirectFB_PumpEvents;
148
149 device->free = DirectFB_DeleteDevice;
150
151 return device;
152}
153
154VideoBootStrap DirectFB_bootstrap = {
155 "directfb", "DirectFB",
156 DirectFB_Available, DirectFB_CreateDevice
157};
158
159static DFBSurfacePixelFormat GetFormatForBpp (int bpp, IDirectFBDisplayLayer *layer)
160{
161 DFBDisplayLayerConfig dlc;
162 int bytes = (bpp + 7) / 8;
163
164 layer->GetConfiguration (layer, &dlc);
165
166 if (bytes == DFB_BYTES_PER_PIXEL(dlc.pixelformat) && bytes > 1)
167 return dlc.pixelformat;
168
169 switch (bytes)
170 {
171 case 1:
172 return DSPF_LUT8;
173 case 2:
174 return DSPF_RGB16;
175 case 3:
176 return DSPF_RGB24;
177 case 4:
178 return DSPF_RGB32;
179 }
180
181 return DSPF_UNKNOWN;
182}
183
184static DFBEnumerationResult EnumModesCallback (int width,
185 int height,
186 int bpp,
187 void *data)
188{
189 SDL_VideoDevice *this = (SDL_VideoDevice *)data;
190 struct DirectFBEnumRect *enumrect;
191
192 HIDDEN->nummodes++;
193
194 if (enumlist && enumlist->r.w == width && enumlist->r.h == height)
195 return DFENUM_OK;
196
197 enumrect = SDL_calloc(1, sizeof(struct DirectFBEnumRect));
198 if (!enumrect)
199 {
200 SDL_OutOfMemory();
201 return DFENUM_CANCEL;
202 }
203
204 enumrect->r.w = (Uint16)width;
205 enumrect->r.h = (Uint16)height;
206 enumrect->next = enumlist;
207
208 enumlist = enumrect;
209
210 return DFENUM_OK;
211}
212
213struct private_hwdata {
214 IDirectFBSurface *surface;
215 IDirectFBPalette *palette;
216};
217
218void SetDirectFBerror (const char *function, DFBResult code)
219{
220 const char *error = DirectFBErrorString (code);
221
222 if (error)
223 SDL_SetError("%s: %s", function, error);
224 else
225 SDL_SetError("Unknown error code from %s", function);
226}
227
228static DFBSurfacePixelFormat SDLToDFBPixelFormat (SDL_PixelFormat *format)
229{
230 if (format->Rmask && format->Gmask && format->Bmask)
231 {
232 switch (format->BitsPerPixel)
233 {
234 case 8:
235 return DSPF_LUT8;
236
237 case 16:
238 if (format->Rmask == 0xF800 &&
239 format->Gmask == 0x07E0 &&
240 format->Bmask == 0x001F)
241 return DSPF_RGB16;
242 /* fall through */
243
244 case 15:
245 if (format->Rmask == 0x7C00 &&
246 format->Gmask == 0x03E0 &&
247 format->Bmask == 0x001F)
248 return DSPF_ARGB1555;
249 break;
250
251 case 24:
252 if (format->Rmask == 0xFF0000 &&
253 format->Gmask == 0x00FF00 &&
254 format->Bmask == 0x0000FF)
255 return DSPF_RGB24;
256 break;
257
258 case 32:
259 if (format->Rmask == 0xFF0000 &&
260 format->Gmask == 0x00FF00 &&
261 format->Bmask == 0x0000FF)
262 {
263 if (format->Amask == 0xFF000000)
264 return DSPF_ARGB;
265 else
266 return DSPF_RGB32;
267 }
268 break;
269 }
270 }
271 else
272 {
273 switch (format->BitsPerPixel)
274 {
275 case 8:
276 return DSPF_LUT8;
277 case 15:
278 return DSPF_ARGB1555;
279 case 16:
280 return DSPF_RGB16;
281 case 24:
282 return DSPF_RGB24;
283 case 32:
284 return DSPF_RGB32;
285 }
286 }
287
288 return DSPF_UNKNOWN;
289}
290
291static SDL_Palette *AllocatePalette(int size)
292{
293 SDL_Palette *palette;
294 SDL_Color *colors;
295
296 palette = SDL_calloc (1, sizeof(SDL_Palette));
297 if (!palette)
298 {
299 SDL_OutOfMemory();
300 return NULL;
301 }
302
303 colors = SDL_calloc (size, sizeof(SDL_Color));
304 if (!colors)
305 {
306 SDL_OutOfMemory();
307 return NULL;
308 }
309
310 palette->ncolors = size;
311 palette->colors = colors;
312
313 return palette;
314}
315
316static int DFBToSDLPixelFormat (DFBSurfacePixelFormat pixelformat, SDL_PixelFormat *format)
317{
318 format->Amask = format->Rmask = format->Gmask = format->Bmask = 0;
319 format->BitsPerPixel = format->BytesPerPixel = 0;
320
321 switch (pixelformat)
322 {
323 case DSPF_A8:
324 format->Amask = 0x000000FF;
325 break;
326
327 case DSPF_ARGB1555:
328 format->Rmask = 0x00007C00;
329 format->Gmask = 0x000003E0;
330 format->Bmask = 0x0000001F;
331 break;
332
333 case DSPF_RGB16:
334 format->Rmask = 0x0000F800;
335 format->Gmask = 0x000007E0;
336 format->Bmask = 0x0000001F;
337 break;
338
339 case DSPF_ARGB:
340 format->Amask = 0; /* apps don't seem to like that: 0xFF000000; */
341 /* fall through */
342 case DSPF_RGB24:
343 case DSPF_RGB32:
344 format->Rmask = 0x00FF0000;
345 format->Gmask = 0x0000FF00;
346 format->Bmask = 0x000000FF;
347 break;
348
349 case DSPF_LUT8:
350 format->Rmask = 0x000000FF;
351 format->Gmask = 0x000000FF;
352 format->Bmask = 0x000000FF;
353
354 if (!format->palette)
355 format->palette = AllocatePalette(256);
356 break;
357
358 default:
359 fprintf (stderr, "SDL_DirectFB: Unsupported pixelformat (0x%08x)!\n", pixelformat);
360 return -1;
361 }
362
363 format->BitsPerPixel = DFB_BYTES_PER_PIXEL(pixelformat) * 8;
364 format->BytesPerPixel = DFB_BYTES_PER_PIXEL(pixelformat);
365
366 return 0;
367}
368
369
370int DirectFB_VideoInit(_THIS, SDL_PixelFormat *vformat)
371{
372 int i;
373 DFBResult ret;
374#if (DIRECTFB_MAJOR_VERSION == 0) && (DIRECTFB_MINOR_VERSION == 9) && (DIRECTFB_MICRO_VERSION < 23)
375 DFBCardCapabilities caps;
376#else
377 DFBGraphicsDeviceDescription caps;
378#endif
379 DFBDisplayLayerConfig dlc;
380 struct DirectFBEnumRect *rect;
381 IDirectFB *dfb = NULL;
382 IDirectFBDisplayLayer *layer = NULL;
383 IDirectFBEventBuffer *events = NULL;
384
385 HIDDEN->c2layer = NULL, HIDDEN->c2frame = NULL;
386 HIDDEN->enable_mga_crtc2 = 0;
387 HIDDEN->mga_crtc2_stretch_overscan = 1;
388
389 ret = DirectFBInit (NULL, NULL);
390 if (ret)
391 {
392 SetDirectFBerror ("DirectFBInit", ret);
393 goto error;
394 }
395
396 ret = DirectFBCreate (&dfb);
397 if (ret)
398 {
399 SetDirectFBerror ("DirectFBCreate", ret);
400 goto error;
401 }
402
403 ret = dfb->GetDisplayLayer (dfb, DLID_PRIMARY, &layer);
404 if (ret)
405 {
406 SetDirectFBerror ("dfb->GetDisplayLayer", ret);
407 goto error;
408 }
409
410 ret = dfb->CreateInputEventBuffer (dfb, DICAPS_ALL, DFB_FALSE, &events);
411 if (ret)
412 {
413 SetDirectFBerror ("dfb->CreateEventBuffer", ret);
414 goto error;
415 }
416
417 layer->EnableCursor (layer, 1);
418
419 /* Query layer configuration to determine the current mode and pixelformat */
420 layer->GetConfiguration (layer, &dlc);
421
422 /* If current format is not supported use LUT8 as the default */
423 if (DFBToSDLPixelFormat (dlc.pixelformat, vformat))
424 DFBToSDLPixelFormat (DSPF_LUT8, vformat);
425
426 /* Enumerate the available fullscreen modes */
427 ret = dfb->EnumVideoModes (dfb, EnumModesCallback, this);
428 if (ret)
429 {
430 SetDirectFBerror ("dfb->EnumVideoModes", ret);
431 goto error;
432 }
433
434 HIDDEN->modelist = SDL_calloc (HIDDEN->nummodes + 1, sizeof(SDL_Rect *));
435 if (!HIDDEN->modelist)
436 {
437 SDL_OutOfMemory();
438 goto error;
439 }
440
441 for (i = 0, rect = enumlist; rect; ++i, rect = rect->next )
442 {
443 HIDDEN->modelist[i] = &rect->r;
444 }
445
446 HIDDEN->modelist[i] = NULL;
447
448
449 /* Query card capabilities to get the video memory size */
450#if (DIRECTFB_MAJOR_VERSION == 0) && (DIRECTFB_MINOR_VERSION == 9) && (DIRECTFB_MICRO_VERSION < 23)
451 dfb->GetCardCapabilities (dfb, &caps);
452#else
453 dfb->GetDeviceDescription (dfb, &caps);
454#endif
455
456 this->info.wm_available = 1;
457 this->info.hw_available = 1;
458 this->info.blit_hw = 1;
459 this->info.blit_hw_CC = 1;
460 this->info.blit_hw_A = 1;
461 this->info.blit_fill = 1;
462 this->info.video_mem = caps.video_memory / 1024;
463 this->info.current_w = dlc.width;
464 this->info.current_h = dlc.height;
465
466 HIDDEN->initialized = 1;
467 HIDDEN->dfb = dfb;
468 HIDDEN->layer = layer;
469 HIDDEN->eventbuffer = events;
470
471 if (SDL_getenv("SDL_DIRECTFB_MGA_CRTC2") != NULL)
472 HIDDEN->enable_mga_crtc2 = 1;
473
474 if (HIDDEN->enable_mga_crtc2)
475 {
476 DFBDisplayLayerConfig dlc;
477 DFBDisplayLayerConfigFlags failed;
478
479 ret = dfb->GetDisplayLayer (dfb, 2, &HIDDEN->c2layer);
480 if (ret)
481 {
482 SetDirectFBerror ("dfb->GetDisplayLayer(CRTC2)", ret);
483 goto error;
484 }
485
486 ret = HIDDEN->layer->SetCooperativeLevel(HIDDEN->layer, DLSCL_EXCLUSIVE);
487 if (ret)
488 {
489 SetDirectFBerror ("layer->SetCooperativeLevel(CRTC2, EXCLUSIVE)", ret);
490 goto error;
491 }
492
493 ret = HIDDEN->c2layer->SetCooperativeLevel(HIDDEN->c2layer, DLSCL_EXCLUSIVE);
494 if (ret)
495 {
496 SetDirectFBerror ("c2layer->SetCooperativeLevel(CRTC2, EXCLUSIVE)", ret);
497 goto error;
498 }
499
500 HIDDEN->c2layer->SetOpacity(HIDDEN->c2layer, 0x0);
501
502 /* Init the surface here as it got a fixed size */
503 dlc.flags = DLCONF_PIXELFORMAT | DLCONF_BUFFERMODE;
504 dlc.buffermode = DLBM_BACKVIDEO;
505 dlc.pixelformat = DSPF_RGB32;
506
507 ret = HIDDEN->c2layer->TestConfiguration( HIDDEN->c2layer, &dlc, &failed );
508 if (ret)
509 {
510 SetDirectFBerror ("c2layer->TestConfiguration", ret);
511 goto error;
512 }
513
514 ret = HIDDEN->c2layer->SetConfiguration( HIDDEN->c2layer, &dlc );
515 if (ret)
516 {
517 SetDirectFBerror ("c2layer->SetConfiguration", ret);
518 goto error;
519 }
520
521 ret = HIDDEN->c2layer->GetSurface( HIDDEN->c2layer, &HIDDEN->c2frame );
522 if (ret)
523 {
524 SetDirectFBerror ("c2layer->GetSurface", ret);
525 goto error;
526 }
527
528 HIDDEN->c2framesize.x = 0;
529 HIDDEN->c2framesize.y = 0;
530 HIDDEN->c2frame->GetSize( HIDDEN->c2frame, &HIDDEN->c2framesize.w, &HIDDEN->c2framesize.h);
531
532 HIDDEN->c2frame->SetBlittingFlags( HIDDEN->c2frame, DSBLIT_NOFX );
533 HIDDEN->c2frame->SetColor( HIDDEN->c2frame, 0, 0, 0, 0xff );
534
535 /* Clear CRTC2 */
536 HIDDEN->c2frame->Clear(HIDDEN->c2frame, 0, 0, 0, 0xff );
537 HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, 0 );
538 HIDDEN->c2frame->Clear(HIDDEN->c2frame, 0, 0, 0, 0xff );
539 HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, 0 );
540 HIDDEN->c2frame->Clear(HIDDEN->c2frame, 0, 0, 0, 0xff );
541
542 HIDDEN->c2layer->SetOpacity(HIDDEN->c2layer, 0xFF );
543
544 /* Check if overscan is possibly set */
545 if (SDL_getenv("SDL_DIRECTFB_MGA_OVERSCAN") != NULL)
546 {
547 float overscan = 0;
548 if (SDL_sscanf(SDL_getenv("SDL_DIRECTFB_MGA_OVERSCAN"), "%f", &overscan) == 1)
549 if (overscan > 0 && overscan < 2)
550 HIDDEN->mga_crtc2_stretch_overscan = overscan;
551 }
552
553 #ifdef DIRECTFB_CRTC2_DEBUG
554 printf("CRTC2 overscan: %f\n", HIDDEN->mga_crtc2_stretch_overscan);
555 #endif
556 }
557
558 return 0;
559
560 error:
561 if (events)
562 events->Release (events);
563
564 if (HIDDEN->c2frame)
565 HIDDEN->c2frame->Release (HIDDEN->c2frame);
566
567 if (HIDDEN->c2layer)
568 HIDDEN->c2layer->Release (HIDDEN->c2layer);
569
570 if (layer)
571 layer->Release (layer);
572
573 if (dfb)
574 dfb->Release (dfb);
575
576 return -1;
577}
578
579static SDL_Rect **DirectFB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
580{
581 if (flags & SDL_FULLSCREEN)
582 return HIDDEN->modelist;
583 else
584 if (SDLToDFBPixelFormat (format) != DSPF_UNKNOWN)
585 return (SDL_Rect**) -1;
586
587 return NULL;
588}
589
590static SDL_Surface *DirectFB_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags)
591{
592 DFBResult ret;
593 DFBSurfaceDescription dsc;
594 DFBSurfacePixelFormat pixelformat;
595 IDirectFBSurface *surface;
596
597 fprintf (stderr, "SDL DirectFB_SetVideoMode: %dx%d@%d, flags: 0x%08x\n",
598 width, height, bpp, flags);
599
600 flags |= SDL_FULLSCREEN;
601
602 /* Release previous primary surface */
603 if (current->hwdata && current->hwdata->surface)
604 {
605 current->hwdata->surface->Release (current->hwdata->surface);
606 current->hwdata->surface = NULL;
607
608 /* And its palette if present */
609 if (current->hwdata->palette)
610 {
611 current->hwdata->palette->Release (current->hwdata->palette);
612 current->hwdata->palette = NULL;
613 }
614 }
615 else if (!current->hwdata)
616 {
617 /* Allocate the hardware acceleration data */
618 current->hwdata = (struct private_hwdata *) SDL_calloc (1, sizeof(*current->hwdata));
619 if (!current->hwdata)
620 {
621 SDL_OutOfMemory();
622 return NULL;
623 }
624 }
625
626 /* Set cooperative level depending on flag SDL_FULLSCREEN */
627 if (flags & SDL_FULLSCREEN)
628 {
629 ret = HIDDEN->dfb->SetCooperativeLevel (HIDDEN->dfb, DFSCL_FULLSCREEN);
630 if (ret && !HIDDEN->enable_mga_crtc2)
631 {
632 DirectFBError ("dfb->SetCooperativeLevel", ret);
633 flags &= ~SDL_FULLSCREEN;
634 }
635 }
636 else
637 HIDDEN->dfb->SetCooperativeLevel (HIDDEN->dfb, DFSCL_NORMAL);
638
639 /* Set video mode */
640 ret = HIDDEN->dfb->SetVideoMode (HIDDEN->dfb, width, height, bpp);
641 if (ret)
642 {
643 if (flags & SDL_FULLSCREEN)
644 {
645 flags &= ~SDL_FULLSCREEN;
646 HIDDEN->dfb->SetCooperativeLevel (HIDDEN->dfb, DFSCL_NORMAL);
647 ret = HIDDEN->dfb->SetVideoMode (HIDDEN->dfb, width, height, bpp);
648 }
649
650 if (ret)
651 {
652 SetDirectFBerror ("dfb->SetVideoMode", ret);
653 return NULL;
654 }
655 }
656
657 /* Create primary surface */
658 dsc.flags = DSDESC_CAPS | DSDESC_PIXELFORMAT;
659 dsc.caps = DSCAPS_PRIMARY | ((flags & SDL_DOUBLEBUF) ? DSCAPS_FLIPPING : 0);
660 dsc.pixelformat = GetFormatForBpp (bpp, HIDDEN->layer);
661
662 ret = HIDDEN->dfb->CreateSurface (HIDDEN->dfb, &dsc, &surface);
663 if (ret && (flags & SDL_DOUBLEBUF))
664 {
665 /* Try without double buffering */
666 dsc.caps &= ~DSCAPS_FLIPPING;
667 ret = HIDDEN->dfb->CreateSurface (HIDDEN->dfb, &dsc, &surface);
668 }
669 if (ret)
670 {
671 SetDirectFBerror ("dfb->CreateSurface", ret);
672 return NULL;
673 }
674
675 current->w = width;
676 current->h = height;
677 current->flags = SDL_HWSURFACE | SDL_PREALLOC;
678
679 if (flags & SDL_FULLSCREEN)
680 {
681 current->flags |= SDL_FULLSCREEN;
682 this->UpdateRects = DirectFB_DirectUpdate;
683 }
684 else
685 this->UpdateRects = DirectFB_WindowedUpdate;
686
687 if (dsc.caps & DSCAPS_FLIPPING)
688 current->flags |= SDL_DOUBLEBUF;
689
690 surface->GetPixelFormat (surface, &pixelformat);
691
692 DFBToSDLPixelFormat (pixelformat, current->format);
693
694 /* Get the surface palette (if supported) */
695 if (DFB_PIXELFORMAT_IS_INDEXED( pixelformat ))
696 {
697 surface->GetPalette (surface, &current->hwdata->palette);
698
699 current->flags |= SDL_HWPALETTE;
700 }
701
702 current->hwdata->surface = surface;
703
704 /* MGA CRTC2 stuff */
705 if (HIDDEN->enable_mga_crtc2)
706 {
707 /* no stretching if c2ssize == c2framesize */
708 HIDDEN->c2ssize.x = 0, HIDDEN->c2ssize.y = 0;
709 HIDDEN->c2ssize.w = width;
710 HIDDEN->c2ssize.h = height;
711
712 HIDDEN->c2dsize.x = 0, HIDDEN->c2dsize.y = 0;
713 HIDDEN->c2dsize.w = width;
714 HIDDEN->c2dsize.h = height;
715
716 HIDDEN->mga_crtc2_stretch = 0;
717
718 if (SDL_getenv("SDL_DIRECTFB_MGA_STRETCH") != NULL)
719 {
720 /* Normally assume a picture aspect ratio of 4:3 */
721 int zoom_aspect_x = 4, zoom_aspect_y = 3, i, j;
722
723 for (i = 1; i < 20; i++)
724 {
725 for (j = 1; j < 10; j++)
726 {
727 if ((float)width/(float)i*(float)j == height)
728 {
729 zoom_aspect_x = i;
730 zoom_aspect_y = j;
731
732 /* break the loop */
733 i = 21;
734 break;
735 }
736 }
737 }
738
739 #ifdef DIRECTFB_CRTC2_DEBUG
740 printf("Source resolution: X: %d, Y: %d, Aspect ratio: %d:%d\n", width, height, zoom_aspect_x, zoom_aspect_y);
741 printf("CRTC2 resolution: X: %d, Y: %d\n", HIDDEN->c2framesize.w, HIDDEN->c2framesize.h);
742 #endif
743
744 /* don't stretch only slightly smaller/larger images */
745 if ((float)width < (float)HIDDEN->c2framesize.w*0.95 || (float)height < (float)HIDDEN->c2framesize.h*0.95)
746 {
747 while ((float)HIDDEN->c2dsize.w < (float)HIDDEN->c2framesize.w*HIDDEN->mga_crtc2_stretch_overscan && (float)HIDDEN->c2dsize.h < (float)HIDDEN->c2framesize.h*HIDDEN->mga_crtc2_stretch_overscan)
748 {
749 HIDDEN->c2dsize.w+=zoom_aspect_x;
750 HIDDEN->c2dsize.h+=zoom_aspect_y;
751 }
752
753 /* one step down */
754 HIDDEN->c2dsize.w-=zoom_aspect_x;
755 HIDDEN->c2dsize.h-=zoom_aspect_y;
756
757 #ifdef DIRECTFB_CRTC2_DEBUG
758 printf("Stretched resolution: X: %d, Y: %d\n", HIDDEN->c2dsize.w, HIDDEN->c2dsize.h);
759 #endif
760
761 HIDDEN->mga_crtc2_stretch = 1;
762 }
763 else if ((float)width > (float)HIDDEN->c2framesize.w*0.95 || (float)height > (float)HIDDEN->c2framesize.h*0.95)
764 {
765 while ((float)HIDDEN->c2dsize.w > (float)HIDDEN->c2framesize.w*HIDDEN->mga_crtc2_stretch_overscan || (float)HIDDEN->c2dsize.h > (float)HIDDEN->c2framesize.h*HIDDEN->mga_crtc2_stretch_overscan)
766 {
767 HIDDEN->c2dsize.w-=zoom_aspect_x;
768 HIDDEN->c2dsize.h-=zoom_aspect_y;
769 }
770
771 #ifdef DIRECTFB_CRTC2_DEBUG
772 printf("Down-Stretched resolution: X: %d, Y: %d\n", HIDDEN->c2dsize.w, HIDDEN->c2dsize.h);
773 #endif
774
775 HIDDEN->mga_crtc2_stretch = 1;
776 } else {
777 #ifdef DIRECTFB_CRTC2_DEBUG
778 printf("Not stretching image\n");
779 #endif
780 }
781
782 /* Panning */
783 if (HIDDEN->c2framesize.w > HIDDEN->c2dsize.w)
784 HIDDEN->c2dsize.x = (HIDDEN->c2framesize.w - HIDDEN->c2dsize.w) / 2;
785 else
786 HIDDEN->c2dsize.x = (HIDDEN->c2dsize.w - HIDDEN->c2framesize.w) / 2;
787
788 if (HIDDEN->c2framesize.h > HIDDEN->c2dsize.h)
789 HIDDEN->c2dsize.y = (HIDDEN->c2framesize.h - HIDDEN->c2dsize.h) / 2;
790 else
791 HIDDEN->c2dsize.y = (HIDDEN->c2dsize.h - HIDDEN->c2framesize.h) / 2;
792
793 #ifdef DIRECTFB_CRTC2_DEBUG
794 printf("CRTC2 position X: %d, Y: %d\n", HIDDEN->c2dsize.x, HIDDEN->c2dsize.y);
795 #endif
796 }
797 }
798
799 return current;
800}
801
802static int DirectFB_AllocHWSurface(_THIS, SDL_Surface *surface)
803{
804 DFBResult ret;
805 DFBSurfaceDescription dsc;
806
807 /* fprintf(stderr, "SDL: DirectFB_AllocHWSurface (%dx%d@%d, flags: 0x%08x)\n",
808 surface->w, surface->h, surface->format->BitsPerPixel, surface->flags);*/
809
810 if (surface->w < 8 || surface->h < 8)
811 return -1;
812
813 /* fill surface description */
814 dsc.flags = DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS;
815 dsc.width = surface->w;
816 dsc.height = surface->h;
817 dsc.caps = (surface->flags & SDL_DOUBLEBUF) ? DSCAPS_FLIPPING : 0;
818
819 /* find the right pixelformat */
820 dsc.pixelformat = SDLToDFBPixelFormat (surface->format);
821 if (dsc.pixelformat == DSPF_UNKNOWN)
822 return -1;
823
824 /* Allocate the hardware acceleration data */
825 surface->hwdata = (struct private_hwdata *) SDL_calloc (1, sizeof(*surface->hwdata));
826 if (surface->hwdata == NULL)
827 {
828 SDL_OutOfMemory();
829 return -1;
830 }
831
832 /* Create the surface */
833 ret = HIDDEN->dfb->CreateSurface (HIDDEN->dfb, &dsc, &surface->hwdata->surface);
834 if (ret)
835 {
836 SetDirectFBerror ("dfb->CreateSurface", ret);
837 free (surface->hwdata);
838 surface->hwdata = NULL;
839 return -1;
840 }
841
842 surface->flags |= SDL_HWSURFACE | SDL_PREALLOC;
843
844 return 0;
845}
846
847static void DirectFB_FreeHWSurface(_THIS, SDL_Surface *surface)
848{
849 if (surface->hwdata && HIDDEN->initialized)
850 {
851 surface->hwdata->surface->Release (surface->hwdata->surface);
852 free (surface->hwdata);
853 surface->hwdata = NULL;
854 }
855}
856
857static int DirectFB_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst)
858{
859 /* fprintf(stderr, "SDL: DirectFB_CheckHWBlit (src->hwdata: %p, dst->hwdata: %p)\n",
860 src->hwdata, dst->hwdata);*/
861
862 if (!src->hwdata || !dst->hwdata)
863 return 0;
864
865 src->flags |= SDL_HWACCEL;
866 src->map->hw_blit = DirectFB_HWAccelBlit;
867
868 return 1;
869}
870
871static int DirectFB_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
872 SDL_Surface *dst, SDL_Rect *dstrect)
873{
874 DFBSurfaceBlittingFlags flags = DSBLIT_NOFX;
875
876 DFBRectangle sr = { srcrect->x, srcrect->y, srcrect->w, srcrect->h };
877 DFBRectangle dr = { dstrect->x, dstrect->y, dstrect->w, dstrect->h };
878
879 IDirectFBSurface *surface = dst->hwdata->surface;
880
881 if (src->flags & SDL_SRCCOLORKEY)
882 {
883 flags |= DSBLIT_SRC_COLORKEY;
884 DirectFB_SetHWColorKey (NULL, src, src->format->colorkey);
885 }
886
887 if (src->flags & SDL_SRCALPHA)
888 {
889 flags |= DSBLIT_BLEND_COLORALPHA;
890 surface->SetColor (surface, 0xff, 0xff, 0xff, src->format->alpha);
891 }
892
893 surface->SetBlittingFlags (surface, flags);
894
895 if (sr.w == dr.w && sr.h == dr.h)
896 surface->Blit (surface, src->hwdata->surface, &sr, dr.x, dr.y);
897 else
898 surface->StretchBlit (surface, src->hwdata->surface, &sr, &dr);
899
900 return 0;
901}
902
903static int DirectFB_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color)
904{
905 SDL_PixelFormat *fmt = dst->format;
906 IDirectFBSurface *surface = dst->hwdata->surface;
907
908 /* ugly */
909 surface->SetColor (surface,
910 (color & fmt->Rmask) >> (fmt->Rshift - fmt->Rloss),
911 (color & fmt->Gmask) >> (fmt->Gshift - fmt->Gloss),
912 (color & fmt->Bmask) << (fmt->Bloss - fmt->Bshift), 0xFF);
913 surface->FillRectangle (surface, dstrect->x, dstrect->y, dstrect->w, dstrect->h);
914
915 return 0;
916}
917
918static int DirectFB_SetHWColorKey(_THIS, SDL_Surface *src, Uint32 key)
919{
920 SDL_PixelFormat *fmt = src->format;
921 IDirectFBSurface *surface = src->hwdata->surface;
922
923 if (fmt->BitsPerPixel == 8)
924 surface->SetSrcColorKeyIndex (surface, key);
925 else
926 /* ugly */
927 surface->SetSrcColorKey (surface,
928 (key & fmt->Rmask) >> (fmt->Rshift - fmt->Rloss),
929 (key & fmt->Gmask) >> (fmt->Gshift - fmt->Gloss),
930 (key & fmt->Bmask) << (fmt->Bloss - fmt->Bshift));
931
932 return 0;
933}
934
935static int DirectFB_SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 alpha)
936{
937 return 0;
938}
939
940static int DirectFB_FlipHWSurface(_THIS, SDL_Surface *surface)
941{
942 if (HIDDEN->enable_mga_crtc2)
943 {
944 int rtn = surface->hwdata->surface->Flip (surface->hwdata->surface, NULL, 0);
945 if (HIDDEN->mga_crtc2_stretch)
946 HIDDEN->c2frame->StretchBlit(HIDDEN->c2frame, surface->hwdata->surface, &HIDDEN->c2ssize, &HIDDEN->c2dsize);
947 else
948 HIDDEN->c2frame->Blit(HIDDEN->c2frame, surface->hwdata->surface, NULL, HIDDEN->c2dsize.x, HIDDEN->c2dsize.y);
949
950 HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, DSFLIP_WAITFORSYNC);
951 return rtn;
952 }
953 else
954 return surface->hwdata->surface->Flip (surface->hwdata->surface, NULL, DSFLIP_WAITFORSYNC);
955}
956
957static int DirectFB_LockHWSurface(_THIS, SDL_Surface *surface)
958{
959 DFBResult ret;
960 void *data;
961 int pitch;
962
963 ret = surface->hwdata->surface->Lock (surface->hwdata->surface,
964 DSLF_WRITE, &data, &pitch);
965 if (ret)
966 {
967 SetDirectFBerror ("surface->Lock", ret);
968 return -1;
969 }
970
971 surface->pixels = data;
972 surface->pitch = pitch;
973
974 return 0;
975}
976
977static void DirectFB_UnlockHWSurface(_THIS, SDL_Surface *surface)
978{
979 surface->hwdata->surface->Unlock (surface->hwdata->surface);
980 surface->pixels = NULL;
981}
982
983static void DirectFB_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
984{
985 if (HIDDEN->enable_mga_crtc2)
986 {
987 if (HIDDEN->mga_crtc2_stretch)
988 HIDDEN->c2frame->StretchBlit(HIDDEN->c2frame, this->screen->hwdata->surface, &HIDDEN->c2ssize, &HIDDEN->c2dsize);
989 else
990 HIDDEN->c2frame->Blit(HIDDEN->c2frame, this->screen->hwdata->surface, NULL, HIDDEN->c2dsize.x, HIDDEN->c2dsize.y);
991
992 HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, DSFLIP_WAITFORSYNC);
993 }
994}
995
996static void DirectFB_WindowedUpdate(_THIS, int numrects, SDL_Rect *rects)
997{
998 DFBRegion region;
999 int i;
1000 int region_valid = 0;
1001 IDirectFBSurface *surface = this->screen->hwdata->surface;
1002
1003 for (i=0; i<numrects; ++i)
1004 {
1005 int x2, y2;
1006
1007 if ( ! rects[i].w ) /* Clipped? */
1008 continue;
1009
1010 x2 = rects[i].x + rects[i].w - 1;
1011 y2 = rects[i].y + rects[i].h - 1;
1012
1013 if (region_valid)
1014 {
1015 if (rects[i].x < region.x1)
1016 region.x1 = rects[i].x;
1017
1018 if (rects[i].y < region.y1)
1019 region.y1 = rects[i].y;
1020
1021 if (x2 > region.x2)
1022 region.x2 = x2;
1023
1024 if (y2 > region.y2)
1025 region.y2 = y2;
1026 }
1027 else
1028 {
1029 region.x1 = rects[i].x;
1030 region.y1 = rects[i].y;
1031 region.x2 = x2;
1032 region.y2 = y2;
1033
1034 region_valid = 1;
1035 }
1036 }
1037
1038 if (region_valid)
1039 {
1040 if (HIDDEN->enable_mga_crtc2)
1041 {
1042 if (HIDDEN->mga_crtc2_stretch)
1043 HIDDEN->c2frame->StretchBlit(HIDDEN->c2frame, surface, &HIDDEN->c2ssize, &HIDDEN->c2dsize);
1044 else
1045 HIDDEN->c2frame->Blit(HIDDEN->c2frame, surface, NULL, HIDDEN->c2dsize.x, HIDDEN->c2dsize.y);
1046
1047 HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, DSFLIP_WAITFORSYNC);
1048 }
1049 else
1050 surface->Flip (surface, &region, DSFLIP_WAITFORSYNC);
1051 }
1052}
1053
1054int DirectFB_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
1055{
1056 IDirectFBPalette *palette = this->screen->hwdata->palette;
1057
1058 if (!palette)
1059 return 0;
1060
1061 if (firstcolor > 255)
1062 return 0;
1063
1064 if (firstcolor + ncolors > 256)
1065 ncolors = 256 - firstcolor;
1066
1067 if (ncolors > 0)
1068 {
1069 int i;
1070 DFBColor entries[ncolors];
1071
1072 for (i=0; i<ncolors; i++)
1073 {
1074 entries[i].a = 0xff;
1075 entries[i].r = colors[i].r;
1076 entries[i].g = colors[i].g;
1077 entries[i].b = colors[i].b;
1078 }
1079
1080 palette->SetEntries (palette, entries, ncolors, firstcolor);
1081 }
1082
1083 return 1;
1084}
1085
1086void DirectFB_VideoQuit(_THIS)
1087{
1088 struct DirectFBEnumRect *rect = enumlist;
1089
1090 if (this->screen && this->screen->hwdata)
1091 {
1092 IDirectFBSurface *surface = this->screen->hwdata->surface;
1093 IDirectFBPalette *palette = this->screen->hwdata->palette;
1094
1095 if (palette)
1096 palette->Release (palette);
1097
1098 if (surface)
1099 surface->Release (surface);
1100
1101 this->screen->hwdata->surface = NULL;
1102 this->screen->hwdata->palette = NULL;
1103 }
1104
1105 if (HIDDEN->c2frame)
1106 {
1107 HIDDEN->c2frame->Release (HIDDEN->c2frame);
1108 HIDDEN->c2frame = NULL;
1109 }
1110
1111 if (HIDDEN->eventbuffer)
1112 {
1113 HIDDEN->eventbuffer->Release (HIDDEN->eventbuffer);
1114 HIDDEN->eventbuffer = NULL;
1115 }
1116
1117 if (HIDDEN->c2layer)
1118 {
1119 HIDDEN->c2layer->Release (HIDDEN->c2layer);
1120 HIDDEN->c2layer = NULL;
1121 }
1122
1123 if (HIDDEN->layer)
1124 {
1125 HIDDEN->layer->Release (HIDDEN->layer);
1126 HIDDEN->layer = NULL;
1127 }
1128
1129 if (HIDDEN->dfb)
1130 {
1131 HIDDEN->dfb->Release (HIDDEN->dfb);
1132 HIDDEN->dfb = NULL;
1133 }
1134
1135 /* Free video mode list */
1136 if (HIDDEN->modelist)
1137 {
1138 free (HIDDEN->modelist);
1139 HIDDEN->modelist = NULL;
1140 }
1141
1142 /* Free mode enumeration list */
1143 while (rect)
1144 {
1145 struct DirectFBEnumRect *next = rect->next;
1146 free (rect);
1147 rect = next;
1148 }
1149 enumlist = NULL;
1150
1151 HIDDEN->initialized = 0;
1152}
1153
1154
1155int DirectFB_ShowWMCursor(_THIS, WMcursor *cursor)
1156{
1157 /* We can only hide or show the default cursor */
1158 if ( cursor == NULL )
1159 {
1160 HIDDEN->layer->SetCursorOpacity(HIDDEN->layer, 0x00);
1161 }
1162 else
1163 {
1164 HIDDEN->layer->SetCursorOpacity(HIDDEN->layer, 0xFF);
1165 }
1166 return 1;
1167}
1168
1169void DirectFB_FinalQuit(void)
1170{
1171}
diff --git a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_video.h b/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_video.h
deleted file mode 100644
index e1fa12c268..0000000000
--- a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_video.h
+++ /dev/null
@@ -1,62 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_DirectFB_video_h
25#define _SDL_DirectFB_video_h
26
27#include <directfb.h>
28
29#include "SDL_mouse.h"
30#include "../SDL_sysvideo.h"
31
32#define _THIS SDL_VideoDevice *this
33
34/* Private display data */
35
36struct SDL_PrivateVideoData
37{
38 int initialized;
39
40 IDirectFB *dfb;
41 IDirectFBDisplayLayer *layer;
42 IDirectFBEventBuffer *eventbuffer;
43
44 int nummodes;
45 SDL_Rect **modelist;
46
47 /* MGA CRTC2 support */
48 int enable_mga_crtc2;
49 int mga_crtc2_stretch;
50 float mga_crtc2_stretch_overscan;
51 IDirectFBDisplayLayer *c2layer;
52 IDirectFBSurface *c2frame;
53 DFBRectangle c2ssize; /* Real screen size */
54 DFBRectangle c2dsize; /* Stretched screen size */
55 DFBRectangle c2framesize; /* CRTC2 screen size */
56};
57
58#define HIDDEN (this->hidden)
59
60void SetDirectFBerror (const char *function, DFBResult code);
61
62#endif /* _SDL_DirectFB_video_h */
diff --git a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_yuv.c b/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_yuv.c
deleted file mode 100644
index fd0cef1180..0000000000
--- a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_yuv.c
+++ /dev/null
@@ -1,290 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the DirectFB implementation of YUV video overlays */
25
26#include "SDL_video.h"
27#include "SDL_DirectFB_yuv.h"
28#include "../SDL_yuvfuncs.h"
29
30
31/* The functions used to manipulate software video overlays */
32static struct private_yuvhwfuncs directfb_yuvfuncs = {
33 DirectFB_LockYUVOverlay,
34 DirectFB_UnlockYUVOverlay,
35 DirectFB_DisplayYUVOverlay,
36 DirectFB_FreeYUVOverlay
37};
38
39struct private_yuvhwdata {
40 DFBDisplayLayerID layer_id;
41
42 IDirectFBDisplayLayer *layer;
43 IDirectFBSurface *surface;
44
45 /* These are just so we don't have to allocate them separately */
46 Uint16 pitches[3];
47 Uint8 *planes[3];
48};
49
50static DFBEnumerationResult
51enum_layers_callback( DFBDisplayLayerID id,
52 DFBDisplayLayerDescription desc,
53 void *data )
54{
55 struct private_yuvhwdata *hwdata = (struct private_yuvhwdata *) data;
56
57 /* we don't want the primary */
58 if (id == DLID_PRIMARY)
59 return DFENUM_OK;
60
61 /* take the one with a surface for video */
62 if ((desc.caps & DLCAPS_SURFACE) && (desc.type & DLTF_VIDEO))
63 {
64 hwdata->layer_id = id;
65
66 return DFENUM_CANCEL;
67 }
68
69 return DFENUM_OK;
70}
71
72
73static DFBResult CreateYUVSurface(_THIS, struct private_yuvhwdata *hwdata,
74 int width, int height, Uint32 format)
75{
76 DFBResult ret;
77 IDirectFB *dfb = HIDDEN->dfb;
78 IDirectFBDisplayLayer *layer;
79 DFBDisplayLayerConfig conf;
80
81 ret = dfb->EnumDisplayLayers (dfb, enum_layers_callback, hwdata);
82 if (ret)
83 {
84 SetDirectFBerror("IDirectFB::EnumDisplayLayers", ret);
85 return ret;
86 }
87
88 if (!hwdata->layer_id)
89 return DFB_UNSUPPORTED;
90
91 ret = dfb->GetDisplayLayer (dfb, hwdata->layer_id, &layer);
92 if (ret)
93 {
94 SetDirectFBerror("IDirectFB::GetDisplayLayer", ret);
95 return ret;
96 }
97
98 conf.flags = DLCONF_WIDTH | DLCONF_HEIGHT | DLCONF_PIXELFORMAT;
99 conf.width = width;
100 conf.height = height;
101
102 switch (format)
103 {
104 case SDL_YV12_OVERLAY:
105 conf.pixelformat = DSPF_YV12;
106 break;
107 case SDL_IYUV_OVERLAY:
108 conf.pixelformat = DSPF_I420;
109 break;
110 case SDL_YUY2_OVERLAY:
111 conf.pixelformat = DSPF_YUY2;
112 break;
113 case SDL_UYVY_OVERLAY:
114 conf.pixelformat = DSPF_UYVY;
115 break;
116 default:
117 fprintf (stderr, "SDL_DirectFB: Unsupported YUV format (0x%08x)!\n", format);
118 break;
119 }
120
121 /* Need to set coop level or newer DirectFB versions will fail here. */
122 ret = layer->SetCooperativeLevel (layer, DLSCL_ADMINISTRATIVE);
123 if (ret)
124 {
125 SetDirectFBerror("IDirectFBDisplayLayer::SetCooperativeLevel() failed", ret);
126 layer->Release (layer);
127 return ret;
128 }
129
130 ret = layer->SetConfiguration (layer, &conf);
131 if (ret)
132 {
133 SetDirectFBerror("IDirectFBDisplayLayer::SetConfiguration", ret);
134 layer->Release (layer);
135 return ret;
136 }
137
138 ret = layer->GetSurface (layer, &hwdata->surface);
139 if (ret)
140 {
141 SetDirectFBerror("IDirectFBDisplayLayer::GetSurface", ret);
142 layer->Release (layer);
143 return ret;
144 }
145
146 hwdata->layer = layer;
147
148 return DFB_OK;
149}
150
151SDL_Overlay *DirectFB_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display)
152{
153 SDL_Overlay *overlay;
154 struct private_yuvhwdata *hwdata;
155
156 /* Create the overlay structure */
157 overlay = SDL_calloc (1, sizeof(SDL_Overlay));
158 if (!overlay)
159 {
160 SDL_OutOfMemory();
161 return NULL;
162 }
163
164 /* Fill in the basic members */
165 overlay->format = format;
166 overlay->w = width;
167 overlay->h = height;
168
169 /* Set up the YUV surface function structure */
170 overlay->hwfuncs = &directfb_yuvfuncs;
171
172 /* Create the pixel data and lookup tables */
173 hwdata = SDL_calloc(1, sizeof(struct private_yuvhwdata));
174 overlay->hwdata = hwdata;
175 if (!hwdata)
176 {
177 SDL_OutOfMemory();
178 SDL_FreeYUVOverlay (overlay);
179 return NULL;
180 }
181
182 if (CreateYUVSurface (this, hwdata, width, height, format))
183 {
184 SDL_FreeYUVOverlay (overlay);
185 return NULL;
186 }
187
188 overlay->hw_overlay = 1;
189
190 /* Set up the plane pointers */
191 overlay->pitches = hwdata->pitches;
192 overlay->pixels = hwdata->planes;
193 switch (format)
194 {
195 case SDL_YV12_OVERLAY:
196 case SDL_IYUV_OVERLAY:
197 overlay->planes = 3;
198 break;
199 default:
200 overlay->planes = 1;
201 break;
202 }
203
204 /* We're all done.. */
205 return overlay;
206}
207
208int DirectFB_LockYUVOverlay(_THIS, SDL_Overlay *overlay)
209{
210 DFBResult ret;
211 void *data;
212 int pitch;
213 IDirectFBSurface *surface = overlay->hwdata->surface;
214
215 ret = surface->Lock (surface, DSLF_READ | DSLF_WRITE, &data, &pitch);
216 if (ret)
217 {
218 SetDirectFBerror("IDirectFBSurface::Lock", ret);
219 return -1;
220 }
221
222 /* Find the pitch and offset values for the overlay */
223 overlay->pitches[0] = (Uint16) pitch;
224 overlay->pixels[0] = (Uint8*) data;
225
226 switch (overlay->format)
227 {
228 case SDL_YV12_OVERLAY:
229 case SDL_IYUV_OVERLAY:
230 /* Add the two extra planes */
231 overlay->pitches[1] = overlay->pitches[0] / 2;
232 overlay->pitches[2] = overlay->pitches[0] / 2;
233 overlay->pixels[1] = overlay->pixels[0] + overlay->pitches[0] * overlay->h;
234 overlay->pixels[2] = overlay->pixels[1] + overlay->pitches[1] * overlay->h / 2;
235 break;
236 default:
237 /* Only one plane, no worries */
238 break;
239 }
240
241 return 0;
242}
243
244void DirectFB_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay)
245{
246 IDirectFBSurface *surface = overlay->hwdata->surface;
247
248 overlay->pixels[0] = overlay->pixels[1] = overlay->pixels[2] = NULL;
249
250 surface->Unlock (surface);
251}
252
253int DirectFB_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst)
254{
255 DFBResult ret;
256 DFBDisplayLayerConfig conf;
257 IDirectFBDisplayLayer *primary = HIDDEN->layer;
258 IDirectFBDisplayLayer *layer = overlay->hwdata->layer;
259
260 primary->GetConfiguration (primary, &conf);
261
262 ret = layer->SetScreenLocation (layer,
263 dst->x / (float) conf.width, dst->y / (float) conf.height,
264 dst->w / (float) conf.width, dst->h / (float) conf.height );
265 if (ret)
266 {
267 SetDirectFBerror("IDirectFBDisplayLayer::SetScreenLocation", ret);
268 return -1;
269 }
270
271 return 0;
272}
273
274void DirectFB_FreeYUVOverlay(_THIS, SDL_Overlay *overlay)
275{
276 struct private_yuvhwdata *hwdata;
277
278 hwdata = overlay->hwdata;
279 if (hwdata)
280 {
281 if (hwdata->surface)
282 hwdata->surface->Release (hwdata->surface);
283
284 if (hwdata->layer)
285 hwdata->layer->Release (hwdata->layer);
286
287 free (hwdata);
288 }
289}
290
diff --git a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_yuv.h b/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_yuv.h
deleted file mode 100644
index 64bc86fa02..0000000000
--- a/apps/plugins/sdl/src/video/directfb/SDL_DirectFB_yuv.h
+++ /dev/null
@@ -1,38 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the DirectFB implementation of YUV video overlays */
25
26#include "SDL_video.h"
27#include "SDL_DirectFB_video.h"
28
29extern SDL_Overlay *DirectFB_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display);
30
31extern int DirectFB_LockYUVOverlay(_THIS, SDL_Overlay *overlay);
32
33extern void DirectFB_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay);
34
35extern int DirectFB_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst);
36
37extern void DirectFB_FreeYUVOverlay(_THIS, SDL_Overlay *overlay);
38
diff --git a/apps/plugins/sdl/src/video/fbcon/3dfx_mmio.h b/apps/plugins/sdl/src/video/fbcon/3dfx_mmio.h
deleted file mode 100644
index b641454809..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/3dfx_mmio.h
+++ /dev/null
@@ -1,56 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* 3Dfx register definitions */
25
26#include "3dfx_regs.h"
27
28/* 3Dfx control macros */
29
30#define tdfx_in8(reg) *(volatile Uint8 *)(mapped_io + (reg))
31#define tdfx_in32(reg) *(volatile Uint32 *)(mapped_io + (reg))
32
33#define tdfx_out8(reg,v) *(volatile Uint8 *)(mapped_io + (reg)) = v;
34#define tdfx_out32(reg,v) *(volatile Uint32 *)(mapped_io + (reg)) = v;
35
36
37/* Wait for fifo space */
38#define tdfx_wait(space) \
39{ \
40 while ( (tdfx_in8(TDFX_STATUS) & 0x1F) < space ) \
41 ; \
42}
43
44
45/* Wait for idle accelerator */
46#define tdfx_waitidle() \
47{ \
48 int i = 0; \
49 \
50 tdfx_wait(1); \
51 tdfx_out32(COMMAND_3D, COMMAND_3D_NOP); \
52 do { \
53 i = (tdfx_in32(TDFX_STATUS) & STATUS_BUSY) ? 0 : i + 1; \
54 } while ( i != 3 ); \
55}
56
diff --git a/apps/plugins/sdl/src/video/fbcon/3dfx_regs.h b/apps/plugins/sdl/src/video/fbcon/3dfx_regs.h
deleted file mode 100644
index e86f727b30..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/3dfx_regs.h
+++ /dev/null
@@ -1,83 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _3DFX_REGS_H
25#define _3DFX_REGS_H
26
27/* This information comes from the public 3Dfx specs for the Voodoo 3000 */
28
29/* mapped_io register offsets */
30#define TDFX_STATUS 0x00
31
32#define INTCTRL (0x00100000 + 0x04)
33#define CLIP0MIN (0x00100000 + 0x08)
34#define CLIP0MAX (0x00100000 + 0x0c)
35#define DSTBASE (0x00100000 + 0x10)
36#define DSTFORMAT (0x00100000 + 0x14)
37#define SRCCOLORKEYMIN (0x00100000 + 0x18)
38#define SRCCOLORKEYMAX (0x00100000 + 0x1c)
39#define DSTCOLORKEYMIN (0x00100000 + 0x20)
40#define DSTCOLORKEYMAX (0x00100000 + 0x24)
41#define BRESERROR0 (0x00100000 + 0x28)
42#define BRESERROR1 (0x00100000 + 0x2c)
43#define ROP_2D (0x00100000 + 0x30)
44#define SRCBASE (0x00100000 + 0x34)
45#define COMMANDEXTRA_2D (0x00100000 + 0x38)
46#define PATTERN0 (0x00100000 + 0x44)
47#define PATTERN1 (0x00100000 + 0x48)
48#define CLIP1MIN (0x00100000 + 0x4c)
49#define CLIP1MAX (0x00100000 + 0x50)
50#define SRCFORMAT (0x00100000 + 0x54)
51#define SRCSIZE (0x00100000 + 0x58)
52#define SRCXY (0x00100000 + 0x5c)
53#define COLORBACK (0x00100000 + 0x60)
54#define COLORFORE (0x00100000 + 0x64)
55#define DSTSIZE (0x00100000 + 0x68)
56#define DSTXY (0x00100000 + 0x6c)
57#define COMMAND_2D (0x00100000 + 0x70)
58#define LAUNCH_2D (0x00100000 + 0x80)
59#define PATTERNBASE (0x00100000 + 0x100)
60
61#define COMMAND_3D (0x00200000 + 0x120)
62
63/* register bitfields (not all, only as needed) */
64
65#define BIT(x) (1UL << (x))
66
67#define COMMAND_2D_BITBLT 0x01
68#define COMMAND_2D_FILLRECT 0x05
69#define COMMAND_2D_LINE 0x06
70#define COMMAND_2D_POLYGON_FILL 0x08
71#define COMMAND_2D_INITIATE BIT(8)
72#define COMMAND_2D_REVERSELINE BIT(9)
73#define COMMAND_2D_STIPPLELINE BIT(12)
74#define COMMAND_2D_MONOCHROME_PATT BIT(13)
75#define COMMAND_2D_MONOCHROME_TRANSP BIT(16)
76
77#define COMMAND_3D_NOP 0x00
78
79#define STATUS_RETRACE BIT(6)
80#define STATUS_BUSY BIT(9)
81
82#endif /* _3DFX_REGS_H */
83
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fb3dfx.c b/apps/plugins/sdl/src/video/fbcon/SDL_fb3dfx.c
deleted file mode 100644
index eb083b85ab..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fb3dfx.c
+++ /dev/null
@@ -1,215 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_video.h"
25#include "../SDL_blit.h"
26#include "SDL_fb3dfx.h"
27#include "3dfx_mmio.h"
28
29
30/* Wait for vertical retrace */
31static void WaitVBL(_THIS)
32{
33 /* find start of retrace */
34 tdfx_waitidle();
35 while( (tdfx_in32(TDFX_STATUS) & STATUS_RETRACE) == STATUS_RETRACE )
36 ;
37 /* wait until we're past the start */
38 while( (tdfx_in32(TDFX_STATUS) & STATUS_RETRACE) == 0 )
39 ;
40}
41static void WaitIdle(_THIS)
42{
43 tdfx_waitidle();
44}
45
46/* Sets video mem colorkey and accelerated blit function */
47static int SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key)
48{
49 return(0);
50}
51
52static int FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color)
53{
54 int bpp;
55 Uint32 dst_base;
56 Uint32 format;
57 int dstX, dstY;
58
59 /* Don't blit to the display surface when switched away */
60 if ( switched_away ) {
61 return -2; /* no hardware access */
62 }
63 if ( dst == this->screen ) {
64 SDL_mutexP(hw_lock);
65 }
66
67 /* Set the destination pixel format */
68 dst_base = ((char *)dst->pixels - mapped_mem);
69 bpp = dst->format->BitsPerPixel;
70 format = dst->pitch | ((bpp+((bpp==8) ? 0 : 8)) << 13);
71
72 /* Calculate source and destination base coordinates */
73 dstX = rect->x;
74 dstY = rect->y;
75
76 /* Execute the fill command */
77 tdfx_wait(6);
78 tdfx_out32(DSTBASE, dst_base);
79 tdfx_out32(DSTFORMAT, format);
80 tdfx_out32(COLORFORE, color);
81 tdfx_out32(COMMAND_2D, COMMAND_2D_FILLRECT);
82 tdfx_out32(DSTSIZE, rect->w | (rect->h << 16));
83 tdfx_out32(LAUNCH_2D, dstX | (dstY << 16));
84
85 FB_AddBusySurface(dst);
86
87 if ( dst == this->screen ) {
88 SDL_mutexV(hw_lock);
89 }
90 return(0);
91}
92
93static int HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
94 SDL_Surface *dst, SDL_Rect *dstrect)
95{
96 SDL_VideoDevice *this = current_video;
97 int bpp;
98 Uint32 src_format;
99 Uint32 src_base;
100 Uint32 dst_base;
101 int srcX, srcY;
102 int dstX, dstY;
103 Uint32 blitop;
104 Uint32 use_colorkey;
105
106 /* Don't blit to the display surface when switched away */
107 if ( switched_away ) {
108 return -2; /* no hardware access */
109 }
110 if ( dst == this->screen ) {
111 SDL_mutexP(hw_lock);
112 }
113
114 /* Set the source and destination pixel format */
115 src_base = ((char *)src->pixels - mapped_mem);
116 bpp = src->format->BitsPerPixel;
117 src_format = src->pitch | ((bpp+((bpp==8) ? 0 : 8)) << 13);
118 dst_base = ((char *)dst->pixels - mapped_mem);
119 bpp = dst->format->BitsPerPixel;
120
121 srcX = srcrect->x;
122 srcY = srcrect->y;
123 dstX = dstrect->x;
124 dstY = dstrect->y;
125
126 /* Assemble the blit operation */
127 blitop = COMMAND_2D_BITBLT | (0xCC << 24);
128 if ( srcX <= dstX ) {
129 blitop |= BIT(14);
130 srcX += (dstrect->w - 1);
131 dstX += (dstrect->w - 1);
132 }
133 if ( srcY <= dstY ) {
134 blitop |= BIT(15);
135 srcY += (dstrect->h - 1);
136 dstY += (dstrect->h - 1);
137 }
138
139 /* Perform the blit! */
140 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
141 tdfx_wait(3);
142 tdfx_out32(SRCCOLORKEYMIN, src->format->colorkey);
143 tdfx_out32(SRCCOLORKEYMAX, src->format->colorkey);
144 tdfx_out32(ROP_2D, 0xAA00);
145 use_colorkey = 1;
146 } else {
147 use_colorkey = 0;
148 }
149 tdfx_wait(9);
150 tdfx_out32(SRCBASE, (Uint32)src_base);
151 tdfx_out32(SRCFORMAT, src_format);
152 tdfx_out32(DSTBASE, (Uint32)dst_base);
153 tdfx_out32(DSTFORMAT, src_format);
154 tdfx_out32(COMMAND_2D, blitop);
155 tdfx_out32(COMMANDEXTRA_2D, use_colorkey);
156 tdfx_out32(DSTSIZE, dstrect->w | (dstrect->h << 16));
157 tdfx_out32(DSTXY, dstX | (dstY << 16));
158 tdfx_out32(LAUNCH_2D, srcX | (srcY << 16));
159
160 FB_AddBusySurface(src);
161 FB_AddBusySurface(dst);
162
163 if ( dst == this->screen ) {
164 SDL_mutexV(hw_lock);
165 }
166 return(0);
167}
168
169static int CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst)
170{
171 int accelerated;
172
173 /* Set initial acceleration on */
174 src->flags |= SDL_HWACCEL;
175
176 /* Set the surface attributes */
177 if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
178 if ( ! this->info.blit_hw_A ) {
179 src->flags &= ~SDL_HWACCEL;
180 }
181 }
182 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
183 if ( ! this->info.blit_hw_CC ) {
184 src->flags &= ~SDL_HWACCEL;
185 }
186 }
187
188 /* Check to see if final surface blit is accelerated */
189 accelerated = !!(src->flags & SDL_HWACCEL);
190 if ( accelerated ) {
191 src->map->hw_blit = HWAccelBlit;
192 }
193 return(accelerated);
194}
195
196void FB_3DfxAccel(_THIS, __u32 card)
197{
198 /* We have hardware accelerated surface functions */
199 this->CheckHWBlit = CheckHWBlit;
200 wait_vbl = WaitVBL;
201 wait_idle = WaitIdle;
202
203 /* Reset the 3Dfx controller */
204 tdfx_out32(BRESERROR0, 0);
205 tdfx_out32(BRESERROR1, 0);
206
207 /* The 3Dfx has an accelerated color fill */
208 this->info.blit_fill = 1;
209 this->FillHWRect = FillHWRect;
210
211 /* The 3Dfx has accelerated normal and colorkey blits */
212 this->info.blit_hw = 1;
213 this->info.blit_hw_CC = 1;
214 this->SetHWColorKey = SetHWColorKey;
215}
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fb3dfx.h b/apps/plugins/sdl/src/video/fbcon/SDL_fb3dfx.h
deleted file mode 100644
index 4a59de9d80..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fb3dfx.h
+++ /dev/null
@@ -1,29 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* 3Dfx hardware acceleration for the SDL framebuffer console driver */
25
26#include "SDL_fbvideo.h"
27
28/* Set up the driver for 3Dfx acceleration */
29extern void FB_3DfxAccel(_THIS, __u32 card);
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbelo.c b/apps/plugins/sdl/src/video/fbcon/SDL_fbelo.c
deleted file mode 100644
index 63dff87ce6..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbelo.c
+++ /dev/null
@@ -1,442 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <unistd.h>
25#include <sys/time.h>
26#include <ctype.h>
27
28#include "SDL_stdinc.h"
29#include "SDL_fbvideo.h"
30#include "SDL_fbelo.h"
31
32/*
33 calibration default values
34 values are read from the following environment variables:
35
36 SDL_ELO_MIN_X
37 SDL_ELO_MAX_X
38 SDL_ELO_MIN_Y
39 SDL_ELO_MAX_Y
40*/
41
42static int ELO_MIN_X = 400;
43static int ELO_MAX_X = 3670;
44static int ELO_MIN_Y = 500;
45static int ELO_MAX_Y = 3540;
46
47#define ELO_SNAP_SIZE 6
48#define ELO_TOUCH_BYTE 'T'
49#define ELO_ID 'I'
50#define ELO_MODE 'M'
51#define ELO_PARAMETER 'P'
52#define ELO_REPORT 'B'
53#define ELO_ACK 'A'
54
55#define ELO_INIT_CHECKSUM 0xAA
56
57#define ELO_BTN_PRESS 0x01
58#define ELO_STREAM 0x02
59#define ELO_BTN_RELEASE 0x04
60
61#define ELO_TOUCH_MODE 0x01
62#define ELO_STREAM_MODE 0x02
63#define ELO_UNTOUCH_MODE 0x04
64#define ELO_RANGE_CHECK_MODE 0x40
65#define ELO_TRIM_MODE 0x02
66#define ELO_CALIB_MODE 0x04
67#define ELO_SCALING_MODE 0x08
68#define ELO_TRACKING_MODE 0x40
69
70#define ELO_SERIAL_MASK 0xF8
71
72#define ELO_SERIAL_IO '0'
73
74#define ELO_MAX_TRIALS 3
75#define ELO_MAX_WAIT 100000
76#define ELO_UNTOUCH_DELAY 5
77#define ELO_REPORT_DELAY 1
78
79/* eloParsePacket
80*/
81int eloParsePacket(unsigned char* mousebuf, int* dx, int* dy, int* button_state) {
82 static int elo_button = 0;
83 static int last_x = 0;
84 static int last_y = 0;
85 int x,y;
86
87 /* Check if we have a touch packet */
88 if (mousebuf[1] != ELO_TOUCH_BYTE) {
89 return 0;
90 }
91
92 x = ((mousebuf[4] << 8) | mousebuf[3]);
93 y = ((mousebuf[6] << 8) | mousebuf[5]);
94
95 if((SDL_abs(x - last_x) > ELO_SNAP_SIZE) || (SDL_abs(y - last_y) > ELO_SNAP_SIZE)) {
96 *dx = ((mousebuf[4] << 8) | mousebuf[3]);
97 *dy = ((mousebuf[6] << 8) | mousebuf[5]);
98 }
99 else {
100 *dx = last_x;
101 *dy = last_y;
102 }
103
104 last_x = *dx;
105 last_y = *dy;
106
107 if ( (mousebuf[2] & 0x07) == ELO_BTN_PRESS ) {
108 elo_button = 1;
109 }
110 if ( (mousebuf[2] & 0x07) == ELO_BTN_RELEASE ) {
111 elo_button = 0;
112 }
113
114 *button_state = elo_button;
115 return 1;
116}
117
118/* Convert the raw coordinates from the ELO controller
119 to a screen position.
120*/
121void eloConvertXY(_THIS, int *dx, int *dy) {
122 int input_x = *dx;
123 int input_y = *dy;
124 int width = ELO_MAX_X - ELO_MIN_X;
125 int height = ELO_MAX_Y - ELO_MIN_Y;
126
127 *dx = ((int)cache_vinfo.xres - ((int)cache_vinfo.xres * (input_x - ELO_MIN_X)) / width);
128 *dy = (cache_vinfo.yres * (input_y - ELO_MIN_Y)) / height;
129}
130
131
132/* eloGetPacket
133*/
134int eloGetPacket(unsigned char* buffer, int* buffer_p, int* checksum, int fd) {
135 int num_bytes;
136 int ok;
137
138 if(fd == 0) {
139 num_bytes = ELO_PACKET_SIZE;
140 }
141 else {
142 num_bytes = read(fd,
143 (char *) (buffer + *buffer_p),
144 ELO_PACKET_SIZE - *buffer_p);
145 }
146
147 if (num_bytes < 0) {
148#ifdef DEBUG_MOUSE
149 fprintf(stderr, "System error while reading from Elographics touchscreen.\n");
150#endif
151 return 0;
152 }
153
154 while (num_bytes) {
155 if ((*buffer_p == 0) && (buffer[0] != ELO_START_BYTE)) {
156 SDL_memcpy(&buffer[0], &buffer[1], num_bytes-1);
157 }
158 else {
159 if (*buffer_p < ELO_PACKET_SIZE-1) {
160 *checksum = *checksum + buffer[*buffer_p];
161 *checksum = *checksum % 256;
162 }
163 (*buffer_p)++;
164 }
165 num_bytes--;
166 }
167
168 if (*buffer_p == ELO_PACKET_SIZE) {
169 ok = (*checksum == buffer[ELO_PACKET_SIZE-1]);
170 *checksum = ELO_INIT_CHECKSUM;
171 *buffer_p = 0;
172
173 if (!ok) {
174 return 0;
175 }
176
177 return 1;
178 }
179 else {
180 return 0;
181 }
182}
183
184/* eloSendPacket
185*/
186
187int eloSendPacket(unsigned char* packet, int fd)
188{
189 int i, result;
190 int sum = ELO_INIT_CHECKSUM;
191
192 packet[0] = ELO_START_BYTE;
193 for (i = 0; i < ELO_PACKET_SIZE-1; i++) {
194 sum += packet[i];
195 sum &= 0xFF;
196 }
197 packet[ELO_PACKET_SIZE-1] = sum;
198
199 result = write(fd, packet, ELO_PACKET_SIZE);
200
201 if (result != ELO_PACKET_SIZE) {
202#ifdef DEBUG_MOUSE
203 printf("System error while sending to Elographics touchscreen.\n");
204#endif
205 return 0;
206 }
207 else {
208 return 1;
209 }
210}
211
212
213/* eloWaitForInput
214 */
215int eloWaitForInput(int fd, int timeout)
216{
217 fd_set readfds;
218 struct timeval to;
219 int r;
220
221 FD_ZERO(&readfds);
222 FD_SET(fd, &readfds);
223 to.tv_sec = 0;
224 to.tv_usec = timeout;
225
226 r = select(FD_SETSIZE, &readfds, NULL, NULL, &to);
227 return r;
228}
229
230/* eloWaitReply
231 */
232int eloWaitReply(unsigned char type, unsigned char *reply, int fd) {
233 int ok;
234 int i, result;
235 int reply_p = 0;
236 int sum = ELO_INIT_CHECKSUM;
237
238 i = ELO_MAX_TRIALS;
239 do {
240 ok = 0;
241
242 result = eloWaitForInput(fd, ELO_MAX_WAIT);
243
244 if (result > 0) {
245 ok = eloGetPacket(reply, &reply_p, &sum, fd);
246
247 if (ok && reply[1] != type && type != ELO_PARAMETER) {
248#ifdef DEBUG_MOUSE
249 fprintf(stderr, "Wrong reply received\n");
250#endif
251 ok = 0;
252 }
253 }
254 else {
255#ifdef DEBUG_MOUSE
256 fprintf(stderr, "No input!\n");
257#endif
258 }
259
260 if (result == 0) {
261 i--;
262 }
263 } while(!ok && (i>0));
264
265 return ok;
266}
267
268
269/* eloWaitAck
270 */
271
272int eloWaitAck(int fd) {
273 unsigned char packet[ELO_PACKET_SIZE];
274 int i, nb_errors;
275
276 if (eloWaitReply(ELO_ACK, packet, fd)) {
277 for (i = 0, nb_errors = 0; i < 4; i++) {
278 if (packet[2 + i] != '0') {
279 nb_errors++;
280 }
281 }
282
283 if (nb_errors != 0) {
284#ifdef DEBUG_MOUSE
285 fprintf(stderr, "Elographics acknowledge packet reports %d errors\n", nb_errors);
286#endif
287 }
288 return 1;
289 }
290 else {
291 return 0;
292 }
293}
294
295
296/* eloSendQuery --
297*/
298int eloSendQuery(unsigned char *request, unsigned char* reply, int fd) {
299 int ok;
300
301 if (eloSendPacket(request, fd)) {
302 ok = eloWaitReply(toupper(request[1]), reply, fd);
303 if (ok) {
304 ok = eloWaitAck(fd);
305 }
306 return ok;
307 }
308 else {
309 return 0;
310 }
311}
312
313
314/* eloSendControl
315*/
316int eloSendControl(unsigned char* control, int fd) {
317 if (eloSendPacket(control, fd)) {
318 return eloWaitAck(fd);
319 }
320 else {
321 return 0;
322 }
323}
324
325/* eloInitController
326*/
327int eloInitController(int fd) {
328 unsigned char req[ELO_PACKET_SIZE];
329 unsigned char reply[ELO_PACKET_SIZE];
330 const char *buffer = NULL;
331 int result = 0;
332
333 struct termios mouse_termios;
334
335 /* try to read the calibration values */
336 buffer = SDL_getenv("SDL_ELO_MIN_X");
337 if(buffer) {
338 ELO_MIN_X = SDL_atoi(buffer);
339 }
340 buffer = SDL_getenv("SDL_ELO_MAX_X");
341 if(buffer) {
342 ELO_MAX_X = SDL_atoi(buffer);
343 }
344 buffer = SDL_getenv("SDL_ELO_MIN_Y");
345 if(buffer) {
346 ELO_MIN_Y = SDL_atoi(buffer);
347 }
348 buffer = SDL_getenv("SDL_ELO_MAX_Y");
349 if(buffer) {
350 ELO_MAX_Y = SDL_atoi(buffer);
351 }
352
353#ifdef DEBUG_MOUSE
354 fprintf( stderr, "ELO calibration values:\nmin_x: %i\nmax_x: %i\nmin_y: %i\nmax_y: %i\n",
355 ELO_MIN_X,
356 ELO_MAX_X,
357 ELO_MIN_Y,
358 ELO_MAX_Y);
359#endif
360
361 /* set comm params */
362 SDL_memset(&mouse_termios, 0, sizeof(mouse_termios));
363 mouse_termios.c_cflag = B9600 | CS8 | CREAD | CLOCAL;
364 mouse_termios.c_cc[VMIN] = 1;
365 result = tcsetattr(fd, TCSANOW, &mouse_termios);
366
367 if (result < 0) {
368#ifdef DEBUG_MOUSE
369 fprintf( stderr, "Unable to configure Elographics touchscreen port\n");
370#endif
371 return 0;
372 }
373
374 SDL_memset(req, 0, ELO_PACKET_SIZE);
375 req[1] = tolower(ELO_PARAMETER);
376 if (!eloSendQuery(req, reply, fd)) {
377#ifdef DEBUG_MOUSE
378 fprintf( stderr, "Not at the specified rate or model 2310, will continue\n");
379#endif
380 }
381
382 SDL_memset(req, 0, ELO_PACKET_SIZE);
383 req[1] = tolower(ELO_ID);
384 if (eloSendQuery(req, reply, fd)) {
385#ifdef DEBUG_MOUSE
386 fprintf(stderr, "Ok, controller configured!\n");
387#endif
388 }
389 else {
390#ifdef DEBUG_MOUSE
391 fprintf( stderr, "Unable to ask Elographics touchscreen identification\n");
392#endif
393 return 0;
394 }
395
396 SDL_memset(req, 0, ELO_PACKET_SIZE);
397 req[1] = ELO_MODE;
398 req[3] = ELO_TOUCH_MODE | ELO_STREAM_MODE | ELO_UNTOUCH_MODE;
399 req[4] = ELO_TRACKING_MODE;
400 if (!eloSendControl(req, fd)) {
401#ifdef DEBUG_MOUSE
402 fprintf( stderr, "Unable to change Elographics touchscreen operating mode\n");
403#endif
404 return 0;
405 }
406
407 SDL_memset(req, 0, ELO_PACKET_SIZE);
408 req[1] = ELO_REPORT;
409 req[2] = ELO_UNTOUCH_DELAY;
410 req[3] = ELO_REPORT_DELAY;
411 if (!eloSendControl(req, fd)) {
412#ifdef DEBUG_MOUSE
413 fprintf( stderr, "Unable to change Elographics touchscreen reports timings\n");
414#endif
415 return 0;
416 }
417
418 return 1;
419}
420
421int eloReadPosition(_THIS, int fd, int* x, int* y, int* button_state, int* realx, int* realy) {
422 unsigned char buffer[ELO_PACKET_SIZE];
423 int pointer = 0;
424 int checksum = ELO_INIT_CHECKSUM;
425
426 while(pointer < ELO_PACKET_SIZE) {
427 if(eloGetPacket(buffer, &pointer, &checksum, fd)) {
428 break;
429 }
430 }
431
432 if(!eloParsePacket(buffer, realx, realy, button_state)) {
433 return 0;
434 }
435
436 *x = *realx;
437 *y = *realy;
438
439 eloConvertXY(this, x, y);
440
441 return 1;
442}
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbelo.h b/apps/plugins/sdl/src/video/fbcon/SDL_fbelo.h
deleted file mode 100644
index e7fde4ff2f..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbelo.h
+++ /dev/null
@@ -1,55 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef SDL_fbelo_h
25#define SDL_fbelo_h
26
27#include "SDL_fbvideo.h"
28
29/* ELO */
30#define ELO_PACKET_SIZE 10
31#define ELO_START_BYTE 'U'
32
33/* eloConvertXY
34 Convert the raw coordinates from the ELO controller
35 to a screen position.
36*/
37void eloConvertXY(_THIS, int *dx, int *dy);
38
39/* eloInitController(int fd)
40 Initialize the ELO serial touchscreen controller
41*/
42int eloInitController(int fd);
43
44/* eloParsePacket
45 extract position and button state from a packet
46*/
47int eloParsePacket(unsigned char* mousebuf, int* dx, int* dy, int* button_state);
48
49/* eloReadPosition
50 read a packet and get the cursor position
51*/
52
53int eloReadPosition(_THIS, int fd, int* x, int* y, int* button_state, int* realx, int* realy);
54
55#endif /* SDL_fbelo_h */
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbevents.c b/apps/plugins/sdl/src/video/fbcon/SDL_fbevents.c
deleted file mode 100644
index 5e369a4a89..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbevents.c
+++ /dev/null
@@ -1,1254 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting console events into SDL events */
25
26#include <stdio.h>
27#include <sys/types.h>
28#include <sys/time.h>
29#include <sys/ioctl.h>
30#include <unistd.h>
31#include <fcntl.h>
32#include <errno.h>
33#include <limits.h>
34
35/* For parsing /proc */
36#include <dirent.h>
37#include <ctype.h>
38
39#include <linux/vt.h>
40#include <linux/kd.h>
41#include <linux/keyboard.h>
42
43#include "SDL_timer.h"
44#include "SDL_mutex.h"
45#include "../SDL_sysvideo.h"
46#include "../../events/SDL_sysevents.h"
47#include "../../events/SDL_events_c.h"
48#include "SDL_fbvideo.h"
49#include "SDL_fbevents_c.h"
50#include "SDL_fbkeys.h"
51
52#include "SDL_fbelo.h"
53
54#ifndef GPM_NODE_FIFO
55#define GPM_NODE_FIFO "/dev/gpmdata"
56#endif
57
58/*#define DEBUG_KEYBOARD*/
59/*#define DEBUG_MOUSE*/
60
61/* The translation tables from a console scancode to a SDL keysym */
62#define NUM_VGAKEYMAPS (1<<KG_CAPSSHIFT)
63static Uint16 vga_keymap[NUM_VGAKEYMAPS][NR_KEYS];
64static SDLKey keymap[128];
65static Uint16 keymap_temp[128]; /* only used at startup */
66static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym);
67
68/* Ugh, we have to duplicate the kernel's keysym mapping code...
69 Oh, it's not so bad. :-)
70
71 FIXME: Add keyboard LED handling code
72 */
73static void FB_vgainitkeymaps(int fd)
74{
75 struct kbentry entry;
76 int map, i;
77
78 /* Don't do anything if we are passed a closed keyboard */
79 if ( fd < 0 ) {
80 return;
81 }
82
83 /* Load all the keysym mappings */
84 for ( map=0; map<NUM_VGAKEYMAPS; ++map ) {
85 SDL_memset(vga_keymap[map], 0, NR_KEYS*sizeof(Uint16));
86 for ( i=0; i<NR_KEYS; ++i ) {
87 entry.kb_table = map;
88 entry.kb_index = i;
89 if ( ioctl(fd, KDGKBENT, &entry) == 0 ) {
90 /* fill keytemp. This replaces SDL_fbkeys.h */
91 if ( (map == 0) && (i<128) ) {
92 keymap_temp[i] = entry.kb_value;
93 }
94 /* The "Enter" key is a special case */
95 if ( entry.kb_value == K_ENTER ) {
96 entry.kb_value = K(KT_ASCII,13);
97 }
98 /* Handle numpad specially as well */
99 if ( KTYP(entry.kb_value) == KT_PAD ) {
100 switch ( entry.kb_value ) {
101 case K_P0:
102 case K_P1:
103 case K_P2:
104 case K_P3:
105 case K_P4:
106 case K_P5:
107 case K_P6:
108 case K_P7:
109 case K_P8:
110 case K_P9:
111 vga_keymap[map][i]=entry.kb_value;
112 vga_keymap[map][i]+= '0';
113 break;
114 case K_PPLUS:
115 vga_keymap[map][i]=K(KT_ASCII,'+');
116 break;
117 case K_PMINUS:
118 vga_keymap[map][i]=K(KT_ASCII,'-');
119 break;
120 case K_PSTAR:
121 vga_keymap[map][i]=K(KT_ASCII,'*');
122 break;
123 case K_PSLASH:
124 vga_keymap[map][i]=K(KT_ASCII,'/');
125 break;
126 case K_PENTER:
127 vga_keymap[map][i]=K(KT_ASCII,'\r');
128 break;
129 case K_PCOMMA:
130 vga_keymap[map][i]=K(KT_ASCII,',');
131 break;
132 case K_PDOT:
133 vga_keymap[map][i]=K(KT_ASCII,'.');
134 break;
135 default:
136 break;
137 }
138 }
139 /* Do the normal key translation */
140 if ( (KTYP(entry.kb_value) == KT_LATIN) ||
141 (KTYP(entry.kb_value) == KT_ASCII) ||
142 (KTYP(entry.kb_value) == KT_LETTER) ) {
143 vga_keymap[map][i] = entry.kb_value;
144 }
145 }
146 }
147 }
148}
149
150int FB_InGraphicsMode(_THIS)
151{
152 return((keyboard_fd >= 0) && (saved_kbd_mode >= 0));
153}
154
155int FB_EnterGraphicsMode(_THIS)
156{
157 struct termios keyboard_termios;
158
159 /* Set medium-raw keyboard mode */
160 if ( (keyboard_fd >= 0) && !FB_InGraphicsMode(this) ) {
161
162 /* Switch to the correct virtual terminal */
163 if ( current_vt > 0 ) {
164 struct vt_stat vtstate;
165
166 if ( ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0 ) {
167 saved_vt = vtstate.v_active;
168 }
169 if ( ioctl(keyboard_fd, VT_ACTIVATE, current_vt) == 0 ) {
170 ioctl(keyboard_fd, VT_WAITACTIVE, current_vt);
171 }
172 }
173
174 /* Set the terminal input mode */
175 if ( tcgetattr(keyboard_fd, &saved_kbd_termios) < 0 ) {
176 SDL_SetError("Unable to get terminal attributes");
177 if ( keyboard_fd > 0 ) {
178 close(keyboard_fd);
179 }
180 keyboard_fd = -1;
181 return(-1);
182 }
183 if ( ioctl(keyboard_fd, KDGKBMODE, &saved_kbd_mode) < 0 ) {
184 SDL_SetError("Unable to get current keyboard mode");
185 if ( keyboard_fd > 0 ) {
186 close(keyboard_fd);
187 }
188 keyboard_fd = -1;
189 return(-1);
190 }
191 keyboard_termios = saved_kbd_termios;
192 keyboard_termios.c_lflag &= ~(ICANON | ECHO | ISIG);
193 keyboard_termios.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON);
194 keyboard_termios.c_cc[VMIN] = 0;
195 keyboard_termios.c_cc[VTIME] = 0;
196 if (tcsetattr(keyboard_fd, TCSAFLUSH, &keyboard_termios) < 0) {
197 FB_CloseKeyboard(this);
198 SDL_SetError("Unable to set terminal attributes");
199 return(-1);
200 }
201 /* This will fail if we aren't root or this isn't our tty */
202 if ( ioctl(keyboard_fd, KDSKBMODE, K_MEDIUMRAW) < 0 ) {
203 FB_CloseKeyboard(this);
204 SDL_SetError("Unable to set keyboard in raw mode");
205 return(-1);
206 }
207 if ( ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS) < 0 ) {
208 FB_CloseKeyboard(this);
209 SDL_SetError("Unable to set keyboard in graphics mode");
210 return(-1);
211 }
212 /* Prevent switching the virtual terminal */
213 ioctl(keyboard_fd, VT_LOCKSWITCH, 1);
214 }
215 return(keyboard_fd);
216}
217
218void FB_LeaveGraphicsMode(_THIS)
219{
220 if ( FB_InGraphicsMode(this) ) {
221 ioctl(keyboard_fd, KDSETMODE, KD_TEXT);
222 ioctl(keyboard_fd, KDSKBMODE, saved_kbd_mode);
223 tcsetattr(keyboard_fd, TCSAFLUSH, &saved_kbd_termios);
224 saved_kbd_mode = -1;
225
226 /* Head back over to the original virtual terminal */
227 ioctl(keyboard_fd, VT_UNLOCKSWITCH, 1);
228 if ( saved_vt > 0 ) {
229 ioctl(keyboard_fd, VT_ACTIVATE, saved_vt);
230 }
231 }
232}
233
234void FB_CloseKeyboard(_THIS)
235{
236 if ( keyboard_fd >= 0 ) {
237 FB_LeaveGraphicsMode(this);
238 if ( keyboard_fd > 0 ) {
239 close(keyboard_fd);
240 }
241 }
242 keyboard_fd = -1;
243}
244
245int FB_OpenKeyboard(_THIS)
246{
247 /* Open only if not already opened */
248 if ( keyboard_fd < 0 ) {
249 static const char * const tty0[] = { "/dev/tty0", "/dev/vc/0", NULL };
250 static const char * const vcs[] = { "/dev/vc/%d", "/dev/tty%d", NULL };
251 int i, tty0_fd;
252
253 /* Try to query for a free virtual terminal */
254 tty0_fd = -1;
255 for ( i=0; tty0[i] && (tty0_fd < 0); ++i ) {
256 tty0_fd = open(tty0[i], O_WRONLY, 0);
257 }
258 if ( tty0_fd < 0 ) {
259 tty0_fd = dup(0); /* Maybe stdin is a VT? */
260 }
261 ioctl(tty0_fd, VT_OPENQRY, &current_vt);
262 close(tty0_fd);
263 if ( (geteuid() == 0) && (current_vt > 0) ) {
264 for ( i=0; vcs[i] && (keyboard_fd < 0); ++i ) {
265 char vtpath[12];
266
267 SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], current_vt);
268 keyboard_fd = open(vtpath, O_RDWR, 0);
269#ifdef DEBUG_KEYBOARD
270 fprintf(stderr, "vtpath = %s, fd = %d\n",
271 vtpath, keyboard_fd);
272#endif /* DEBUG_KEYBOARD */
273
274 /* This needs to be our controlling tty
275 so that the kernel ioctl() calls work
276 */
277 if ( keyboard_fd >= 0 ) {
278 tty0_fd = open("/dev/tty", O_RDWR, 0);
279 if ( tty0_fd >= 0 ) {
280 ioctl(tty0_fd, TIOCNOTTY, 0);
281 close(tty0_fd);
282 }
283 }
284 }
285 }
286 if ( keyboard_fd < 0 ) {
287 /* Last resort, maybe our tty is a usable VT */
288 struct vt_stat vtstate;
289
290 keyboard_fd = open("/dev/tty", O_RDWR);
291
292 if ( ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0 ) {
293 current_vt = vtstate.v_active;
294 } else {
295 current_vt = 0;
296 }
297 }
298#ifdef DEBUG_KEYBOARD
299 fprintf(stderr, "Current VT: %d\n", current_vt);
300#endif
301 saved_kbd_mode = -1;
302
303 /* Make sure that our input is a console terminal */
304 { int dummy;
305 if ( ioctl(keyboard_fd, KDGKBMODE, &dummy) < 0 ) {
306 close(keyboard_fd);
307 keyboard_fd = -1;
308 SDL_SetError("Unable to open a console terminal");
309 }
310 }
311
312 /* Set up keymap */
313 FB_vgainitkeymaps(keyboard_fd);
314 }
315 return(keyboard_fd);
316}
317
318static enum {
319 MOUSE_NONE = -1,
320 MOUSE_MSC, /* Note: GPM uses the MSC protocol */
321 MOUSE_PS2,
322 MOUSE_IMPS2,
323 MOUSE_MS,
324 MOUSE_BM,
325 MOUSE_ELO,
326 MOUSE_TSLIB,
327 NUM_MOUSE_DRVS
328} mouse_drv = MOUSE_NONE;
329
330void FB_CloseMouse(_THIS)
331{
332#if SDL_INPUT_TSLIB
333 if (ts_dev != NULL) {
334 ts_close(ts_dev);
335 ts_dev = NULL;
336 mouse_fd = -1;
337 }
338#endif /* SDL_INPUT_TSLIB */
339 if ( mouse_fd > 0 ) {
340 close(mouse_fd);
341 }
342 mouse_fd = -1;
343}
344
345/* Returns processes listed in /proc with the desired name */
346static int find_pid(DIR *proc, const char *wanted_name)
347{
348 struct dirent *entry;
349 int pid;
350
351 /* First scan proc for the gpm process */
352 pid = 0;
353 while ( (pid == 0) && ((entry=readdir(proc)) != NULL) ) {
354 if ( isdigit(entry->d_name[0]) ) {
355 FILE *status;
356 char path[PATH_MAX];
357 char name[PATH_MAX];
358
359 SDL_snprintf(path, SDL_arraysize(path), "/proc/%s/status", entry->d_name);
360 status=fopen(path, "r");
361 if ( status ) {
362 int matches = 0;
363 name[0] = '\0';
364 matches = fscanf(status, "Name: %s", name);
365 if ( (matches == 1) && (SDL_strcmp(name, wanted_name) == 0) ) {
366 pid = SDL_atoi(entry->d_name);
367 }
368 fclose(status);
369 }
370 }
371 }
372 return pid;
373}
374
375/* Returns true if /dev/gpmdata is being written to by gpm */
376static int gpm_available(char *proto, size_t protolen)
377{
378 int available;
379 DIR *proc;
380 int pid;
381 int cmdline, len, arglen;
382 char path[PATH_MAX];
383 char args[PATH_MAX], *arg;
384
385 /* Don't bother looking if the fifo isn't there */
386#ifdef DEBUG_MOUSE
387 fprintf(stderr,"testing gpm\n");
388#endif
389 if ( access(GPM_NODE_FIFO, F_OK) < 0 ) {
390 return(0);
391 }
392
393 available = 0;
394 proc = opendir("/proc");
395 if ( proc ) {
396 char raw_proto[10] = { '\0' };
397 char repeat_proto[10] = { '\0' };
398 while ( !available && (pid=find_pid(proc, "gpm")) > 0 ) {
399 SDL_snprintf(path, SDL_arraysize(path), "/proc/%d/cmdline", pid);
400 cmdline = open(path, O_RDONLY, 0);
401 if ( cmdline >= 0 ) {
402 len = read(cmdline, args, sizeof(args));
403 arg = args;
404 while ( len > 0 ) {
405 arglen = SDL_strlen(arg)+1;
406#ifdef DEBUG_MOUSE
407 fprintf(stderr,"gpm arg %s len %d\n",arg,arglen);
408#endif
409 if ( SDL_strcmp(arg, "-t") == 0) {
410 /* protocol string, keep it for later */
411 char *t, *s;
412 t = arg + arglen;
413 s = SDL_strchr(t, ' ');
414 if (s) *s = 0;
415 SDL_strlcpy(raw_proto, t, SDL_arraysize(raw_proto));
416 if (s) *s = ' ';
417 }
418 if ( SDL_strncmp(arg, "-R", 2) == 0 ) {
419 char *t, *s;
420 available = 1;
421 t = arg + 2;
422 s = SDL_strchr(t, ' ');
423 if (s) *s = 0;
424 SDL_strlcpy(repeat_proto, t, SDL_arraysize(repeat_proto));
425 if (s) *s = ' ';
426 }
427 len -= arglen;
428 arg += arglen;
429 }
430 close(cmdline);
431 }
432 }
433 closedir(proc);
434
435 if ( available ) {
436 if ( SDL_strcmp(repeat_proto, "raw") == 0 ) {
437 SDL_strlcpy(proto, raw_proto, protolen);
438 } else if ( *repeat_proto ) {
439 SDL_strlcpy(proto, repeat_proto, protolen);
440 } else {
441 SDL_strlcpy(proto, "msc", protolen);
442 }
443 }
444 }
445 return available;
446}
447
448
449/* rcg06112001 Set up IMPS/2 mode, if possible. This gives
450 * us access to the mousewheel, etc. Returns zero if
451 * writes to device failed, but you still need to query the
452 * device to see which mode it's actually in.
453 */
454static int set_imps2_mode(int fd)
455{
456 /* If you wanted to control the mouse mode (and we do :) ) ...
457 Set IMPS/2 protocol:
458 {0xf3,200,0xf3,100,0xf3,80}
459 Reset mouse device:
460 {0xFF}
461 */
462 Uint8 set_imps2[] = {0xf3, 200, 0xf3, 100, 0xf3, 80};
463 /*Uint8 reset = 0xff;*/
464 fd_set fdset;
465 struct timeval tv;
466 int retval = 0;
467
468 if ( write(fd, &set_imps2, sizeof(set_imps2)) == sizeof(set_imps2) ) {
469 /* Don't reset it, that'll clear IMPS/2 mode on some mice
470 if (write(fd, &reset, sizeof (reset)) == sizeof (reset) ) {
471 retval = 1;
472 }
473 */
474 }
475
476 /* Get rid of any chatter from the above */
477 FD_ZERO(&fdset);
478 FD_SET(fd, &fdset);
479 tv.tv_sec = 0;
480 tv.tv_usec = 0;
481 while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) {
482 char temp[32];
483 if (read(fd, temp, sizeof(temp)) <= 0) {
484 break;
485 }
486 }
487
488 return retval;
489}
490
491
492/* Returns true if the mouse uses the IMPS/2 protocol */
493static int detect_imps2(int fd)
494{
495 int imps2;
496
497 imps2 = 0;
498
499 if ( SDL_getenv("SDL_MOUSEDEV_IMPS2") ) {
500 imps2 = 1;
501 }
502 if ( ! imps2 ) {
503 Uint8 query_ps2 = 0xF2;
504 fd_set fdset;
505 struct timeval tv;
506
507 /* Get rid of any mouse motion noise */
508 FD_ZERO(&fdset);
509 FD_SET(fd, &fdset);
510 tv.tv_sec = 0;
511 tv.tv_usec = 0;
512 while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) {
513 char temp[32];
514 if (read(fd, temp, sizeof(temp)) <= 0) {
515 break;
516 }
517 }
518
519 /* Query for the type of mouse protocol */
520 if ( write(fd, &query_ps2, sizeof (query_ps2)) == sizeof (query_ps2)) {
521 Uint8 ch = 0;
522
523 /* Get the mouse protocol response */
524 do {
525 FD_ZERO(&fdset);
526 FD_SET(fd, &fdset);
527 tv.tv_sec = 1;
528 tv.tv_usec = 0;
529 if ( select(fd+1, &fdset, 0, 0, &tv) < 1 ) {
530 break;
531 }
532 } while ( (read(fd, &ch, sizeof (ch)) == sizeof (ch)) &&
533 ((ch == 0xFA) || (ch == 0xAA)) );
534
535 /* Experimental values (Logitech wheelmouse) */
536#ifdef DEBUG_MOUSE
537fprintf(stderr, "Last mouse mode: 0x%x\n", ch);
538#endif
539 if ( (ch == 3) || (ch == 4) ) {
540 imps2 = 1;
541 }
542 }
543 }
544 return imps2;
545}
546
547int FB_OpenMouse(_THIS)
548{
549 int i;
550 const char *mousedev;
551 const char *mousedrv;
552
553 mousedrv = SDL_getenv("SDL_MOUSEDRV");
554 mousedev = SDL_getenv("SDL_MOUSEDEV");
555 mouse_fd = -1;
556
557#if SDL_INPUT_TSLIB
558 if ( mousedrv && (SDL_strcmp(mousedrv, "TSLIB") == 0) ) {
559 if (mousedev == NULL) mousedev = SDL_getenv("TSLIB_TSDEVICE");
560 if (mousedev != NULL) {
561 ts_dev = ts_open(mousedev, 1);
562 if ((ts_dev != NULL) && (ts_config(ts_dev) >= 0)) {
563#ifdef DEBUG_MOUSE
564 fprintf(stderr, "Using tslib touchscreen\n");
565#endif
566 mouse_drv = MOUSE_TSLIB;
567 mouse_fd = ts_fd(ts_dev);
568 return mouse_fd;
569 }
570 }
571 mouse_drv = MOUSE_NONE;
572 return mouse_fd;
573 }
574#endif /* SDL_INPUT_TSLIB */
575
576 /* ELO TOUCHSCREEN SUPPORT */
577
578 if ( mousedrv && (SDL_strcmp(mousedrv, "ELO") == 0) ) {
579 mouse_fd = open(mousedev, O_RDWR);
580 if ( mouse_fd >= 0 ) {
581 if(eloInitController(mouse_fd)) {
582#ifdef DEBUG_MOUSE
583fprintf(stderr, "Using ELO touchscreen\n");
584#endif
585 mouse_drv = MOUSE_ELO;
586 }
587
588 }
589 else if ( mouse_fd < 0 ) {
590 mouse_drv = MOUSE_NONE;
591 }
592
593 return(mouse_fd);
594 }
595
596 /* STD MICE */
597
598 if ( mousedev == NULL ) {
599 /* FIXME someday... allow multiple mice in this driver */
600 static const char *ps2mice[] = {
601 "/dev/input/mice", "/dev/usbmouse", "/dev/psaux", NULL
602 };
603 /* First try to use GPM in repeater mode */
604 if ( mouse_fd < 0 ) {
605 char proto[10];
606 if ( gpm_available(proto, SDL_arraysize(proto)) ) {
607 mouse_fd = open(GPM_NODE_FIFO, O_RDONLY, 0);
608 if ( mouse_fd >= 0 ) {
609 if ( SDL_strcmp(proto, "msc") == 0 ) {
610 mouse_drv = MOUSE_MSC;
611 } else if ( SDL_strcmp(proto, "ps2") == 0 ) {
612 mouse_drv = MOUSE_PS2;
613 } else if ( SDL_strcmp(proto, "imps2") == 0 ) {
614 mouse_drv = MOUSE_IMPS2;
615 } else if ( SDL_strcmp(proto, "ms") == 0 ||
616 SDL_strcmp(proto, "bare") == 0 ) {
617 mouse_drv = MOUSE_MS;
618 } else if ( SDL_strcmp(proto, "bm") == 0 ) {
619 mouse_drv = MOUSE_BM;
620 } else {
621 /* Unknown protocol... */
622#ifdef DEBUG_MOUSE
623 fprintf(stderr, "GPM mouse using unknown protocol = %s\n", proto);
624#endif
625 close(mouse_fd);
626 mouse_fd = -1;
627 }
628 }
629#ifdef DEBUG_MOUSE
630 if ( mouse_fd >= 0 ) {
631 fprintf(stderr, "Using GPM mouse, protocol = %s\n", proto);
632 }
633#endif /* DEBUG_MOUSE */
634 }
635 }
636 /* Now try to use a modern PS/2 mouse */
637 for ( i=0; (mouse_fd < 0) && ps2mice[i]; ++i ) {
638 mouse_fd = open(ps2mice[i], O_RDWR, 0);
639 if (mouse_fd < 0) {
640 mouse_fd = open(ps2mice[i], O_RDONLY, 0);
641 }
642 if (mouse_fd >= 0) {
643 /* rcg06112001 Attempt to set IMPS/2 mode */
644 set_imps2_mode(mouse_fd);
645 if (detect_imps2(mouse_fd)) {
646#ifdef DEBUG_MOUSE
647fprintf(stderr, "Using IMPS2 mouse\n");
648#endif
649 mouse_drv = MOUSE_IMPS2;
650 } else {
651#ifdef DEBUG_MOUSE
652fprintf(stderr, "Using PS2 mouse\n");
653#endif
654 mouse_drv = MOUSE_PS2;
655 }
656 }
657 }
658 /* Next try to use a PPC ADB port mouse */
659 if ( mouse_fd < 0 ) {
660 mouse_fd = open("/dev/adbmouse", O_RDONLY, 0);
661 if ( mouse_fd >= 0 ) {
662#ifdef DEBUG_MOUSE
663fprintf(stderr, "Using ADB mouse\n");
664#endif
665 mouse_drv = MOUSE_BM;
666 }
667 }
668 }
669 /* Default to a serial Microsoft mouse */
670 if ( mouse_fd < 0 ) {
671 if ( mousedev == NULL ) {
672 mousedev = "/dev/mouse";
673 }
674 mouse_fd = open(mousedev, O_RDONLY, 0);
675 if ( mouse_fd >= 0 ) {
676 struct termios mouse_termios;
677
678 /* Set the sampling speed to 1200 baud */
679 tcgetattr(mouse_fd, &mouse_termios);
680 mouse_termios.c_iflag = IGNBRK | IGNPAR;
681 mouse_termios.c_oflag = 0;
682 mouse_termios.c_lflag = 0;
683 mouse_termios.c_line = 0;
684 mouse_termios.c_cc[VTIME] = 0;
685 mouse_termios.c_cc[VMIN] = 1;
686 mouse_termios.c_cflag = CREAD | CLOCAL | HUPCL;
687 mouse_termios.c_cflag |= CS8;
688 mouse_termios.c_cflag |= B1200;
689 tcsetattr(mouse_fd, TCSAFLUSH, &mouse_termios);
690 if ( mousedrv && (SDL_strcmp(mousedrv, "PS2") == 0) ) {
691#ifdef DEBUG_MOUSE
692fprintf(stderr, "Using (user specified) PS2 mouse on %s\n", mousedev);
693#endif
694 mouse_drv = MOUSE_PS2;
695 } else {
696#ifdef DEBUG_MOUSE
697fprintf(stderr, "Using (default) MS mouse on %s\n", mousedev);
698#endif
699 mouse_drv = MOUSE_MS;
700 }
701 }
702 }
703 if ( mouse_fd < 0 ) {
704 mouse_drv = MOUSE_NONE;
705 }
706 return(mouse_fd);
707}
708
709static int posted = 0;
710
711void FB_vgamousecallback(int button, int relative, int dx, int dy)
712{
713 int button_1, button_3;
714 int button_state;
715 int state_changed;
716 int i;
717 Uint8 state;
718
719 if ( dx || dy ) {
720 posted += SDL_PrivateMouseMotion(0, relative, dx, dy);
721 }
722
723 /* Swap button 1 and 3 */
724 button_1 = (button & 0x04) >> 2;
725 button_3 = (button & 0x01) << 2;
726 button &= ~0x05;
727 button |= (button_1|button_3);
728
729 /* See what changed */
730 button_state = SDL_GetMouseState(NULL, NULL);
731 state_changed = button_state ^ button;
732 for ( i=0; i<8; ++i ) {
733 if ( state_changed & (1<<i) ) {
734 if ( button & (1<<i) ) {
735 state = SDL_PRESSED;
736 } else {
737 state = SDL_RELEASED;
738 }
739 posted += SDL_PrivateMouseButton(state, i+1, 0, 0);
740 }
741 }
742}
743
744/* Handle input from tslib */
745#if SDL_INPUT_TSLIB
746static void handle_tslib(_THIS)
747{
748 struct ts_sample sample;
749 int button;
750
751 while (ts_read(ts_dev, &sample, 1) > 0) {
752 button = (sample.pressure > 0) ? 1 : 0;
753 button <<= 2; /* must report it as button 3 */
754 FB_vgamousecallback(button, 0, sample.x, sample.y);
755 }
756 return;
757}
758#endif /* SDL_INPUT_TSLIB */
759
760/* For now, use MSC, PS/2, and MS protocols
761 Driver adapted from the SVGAlib mouse driver code (taken from gpm, etc.)
762 */
763static void handle_mouse(_THIS)
764{
765 static int start = 0;
766 static unsigned char mousebuf[BUFSIZ];
767 static int relative = 1;
768
769 int i, nread;
770 int button = 0;
771 int dx = 0, dy = 0;
772 int packetsize = 0;
773 int realx, realy;
774
775 /* Figure out the mouse packet size */
776 switch (mouse_drv) {
777 case MOUSE_NONE:
778 break; /* carry on to read from device and discard it. */
779 case MOUSE_MSC:
780 packetsize = 5;
781 break;
782 case MOUSE_IMPS2:
783 packetsize = 4;
784 break;
785 case MOUSE_PS2:
786 case MOUSE_MS:
787 case MOUSE_BM:
788 packetsize = 3;
789 break;
790 case MOUSE_ELO:
791 /* try to read the next packet */
792 if(eloReadPosition(this, mouse_fd, &dx, &dy, &button, &realx, &realy)) {
793 button = (button & 0x01) << 2;
794 FB_vgamousecallback(button, 0, dx, dy);
795 }
796 return; /* nothing left to do */
797 case MOUSE_TSLIB:
798#if SDL_INPUT_TSLIB
799 handle_tslib(this);
800#endif
801 return; /* nothing left to do */
802 default:
803 /* Uh oh.. */
804 packetsize = 0;
805 break;
806 }
807
808 /* Special handling for the quite sensitive ELO controller */
809 if (mouse_drv == MOUSE_ELO) {
810
811 }
812
813 /* Read as many packets as possible */
814 nread = read(mouse_fd, &mousebuf[start], BUFSIZ-start);
815 if ( nread < 0 ) {
816 return;
817 }
818
819 if (mouse_drv == MOUSE_NONE) {
820 return; /* we're done; just draining the input queue. */
821 }
822
823 nread += start;
824#ifdef DEBUG_MOUSE
825 fprintf(stderr, "Read %d bytes from mouse, start = %d\n", nread, start);
826#endif
827
828 for ( i=0; i<(nread-(packetsize-1)); i += packetsize ) {
829 switch (mouse_drv) {
830 case MOUSE_NONE: /* shouldn't actually hit this. */
831 break; /* just throw everything away. */
832 case MOUSE_MSC:
833 /* MSC protocol has 0x80 in high byte */
834 if ( (mousebuf[i] & 0xF8) != 0x80 ) {
835 /* Go to next byte */
836 i -= (packetsize-1);
837 continue;
838 }
839 /* Get current mouse state */
840 button = (~mousebuf[i]) & 0x07;
841 dx = (signed char)(mousebuf[i+1]) +
842 (signed char)(mousebuf[i+3]);
843 dy = -((signed char)(mousebuf[i+2]) +
844 (signed char)(mousebuf[i+4]));
845 break;
846 case MOUSE_PS2:
847 /* PS/2 protocol has nothing in high byte */
848 if ( (mousebuf[i] & 0xC0) != 0 ) {
849 /* Go to next byte */
850 i -= (packetsize-1);
851 continue;
852 }
853 /* Get current mouse state */
854 button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/
855 (mousebuf[i] & 0x02) >> 1 | /*Right*/
856 (mousebuf[i] & 0x01) << 2; /*Left*/
857 dx = (mousebuf[i] & 0x10) ?
858 mousebuf[i+1] - 256 : mousebuf[i+1];
859 dy = (mousebuf[i] & 0x20) ?
860 -(mousebuf[i+2] - 256) : -mousebuf[i+2];
861 break;
862 case MOUSE_IMPS2:
863 /* Get current mouse state */
864 button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/
865 (mousebuf[i] & 0x02) >> 1 | /*Right*/
866 (mousebuf[i] & 0x01) << 2 | /*Left*/
867 (mousebuf[i] & 0x40) >> 3 | /* 4 */
868 (mousebuf[i] & 0x80) >> 3; /* 5 */
869 dx = (mousebuf[i] & 0x10) ?
870 mousebuf[i+1] - 256 : mousebuf[i+1];
871 dy = (mousebuf[i] & 0x20) ?
872 -(mousebuf[i+2] - 256) : -mousebuf[i+2];
873 switch (mousebuf[i+3]&0x0F) {
874 case 0x0E: /* DX = +1 */
875 case 0x02: /* DX = -1 */
876 break;
877 case 0x0F: /* DY = +1 (map button 4) */
878 FB_vgamousecallback(button | (1<<3),
879 1, 0, 0);
880 break;
881 case 0x01: /* DY = -1 (map button 5) */
882 FB_vgamousecallback(button | (1<<4),
883 1, 0, 0);
884 break;
885 }
886 break;
887 case MOUSE_MS:
888 /* Microsoft protocol has 0x40 in high byte */
889 if ( (mousebuf[i] & 0x40) != 0x40 ) {
890 /* Go to next byte */
891 i -= (packetsize-1);
892 continue;
893 }
894 /* Get current mouse state */
895 button = ((mousebuf[i] & 0x20) >> 3) |
896 ((mousebuf[i] & 0x10) >> 4);
897 dx = (signed char)(((mousebuf[i] & 0x03) << 6) |
898 (mousebuf[i + 1] & 0x3F));
899 dy = (signed char)(((mousebuf[i] & 0x0C) << 4) |
900 (mousebuf[i + 2] & 0x3F));
901 break;
902 case MOUSE_BM:
903 /* BusMouse protocol has 0xF8 in high byte */
904 if ( (mousebuf[i] & 0xF8) != 0x80 ) {
905 /* Go to next byte */
906 i -= (packetsize-1);
907 continue;
908 }
909 /* Get current mouse state */
910 button = (~mousebuf[i]) & 0x07;
911 dx = (signed char)mousebuf[i+1];
912 dy = -(signed char)mousebuf[i+2];
913 break;
914 default:
915 /* Uh oh.. */
916 dx = 0;
917 dy = 0;
918 break;
919 }
920 FB_vgamousecallback(button, relative, dx, dy);
921 }
922 if ( i < nread ) {
923 SDL_memcpy(mousebuf, &mousebuf[i], (nread-i));
924 start = (nread-i);
925 } else {
926 start = 0;
927 }
928 return;
929}
930
931/* Handle switching to another VC, returns when our VC is back */
932static void switch_vt_prep(_THIS)
933{
934 SDL_Surface *screen = SDL_VideoSurface;
935
936 SDL_PrivateAppActive(0, (SDL_APPACTIVE|SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS));
937
938 /* Save the contents of the screen, and go to text mode */
939 wait_idle(this);
940 screen_arealen = ((screen->h + (2*this->offset_y)) * screen->pitch);
941 screen_contents = (Uint8 *)SDL_malloc(screen_arealen);
942 if ( screen_contents ) {
943 SDL_memcpy(screen_contents, screen->pixels, screen_arealen);
944 }
945 FB_SavePaletteTo(this, 256, screen_palette);
946 ioctl(console_fd, FBIOGET_VSCREENINFO, &screen_vinfo);
947 ioctl(keyboard_fd, KDSETMODE, KD_TEXT);
948 ioctl(keyboard_fd, VT_UNLOCKSWITCH, 1);
949}
950static void switch_vt_done(_THIS)
951{
952 SDL_Surface *screen = SDL_VideoSurface;
953
954 /* Restore graphics mode and the contents of the screen */
955 ioctl(keyboard_fd, VT_LOCKSWITCH, 1);
956 ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS);
957 ioctl(console_fd, FBIOPUT_VSCREENINFO, &screen_vinfo);
958 FB_RestorePaletteFrom(this, 256, screen_palette);
959 if ( screen_contents ) {
960 SDL_memcpy(screen->pixels, screen_contents, screen_arealen);
961 SDL_free(screen_contents);
962 screen_contents = NULL;
963 }
964
965 /* Get updates to the shadow surface while switched away */
966 if ( SDL_ShadowSurface ) {
967 SDL_UpdateRect(SDL_ShadowSurface, 0, 0, 0, 0);
968 }
969
970 SDL_PrivateAppActive(1, (SDL_APPACTIVE|SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS));
971}
972static void switch_vt(_THIS, unsigned short which)
973{
974 struct vt_stat vtstate;
975
976 /* Figure out whether or not we're switching to a new console */
977 if ( (ioctl(keyboard_fd, VT_GETSTATE, &vtstate) < 0) ||
978 (which == vtstate.v_active) ) {
979 return;
980 }
981
982 /* New console, switch to it */
983 SDL_mutexP(hw_lock);
984 switch_vt_prep(this);
985 if ( ioctl(keyboard_fd, VT_ACTIVATE, which) == 0 ) {
986 ioctl(keyboard_fd, VT_WAITACTIVE, which);
987 switched_away = 1;
988 } else {
989 switch_vt_done(this);
990 }
991 SDL_mutexV(hw_lock);
992}
993
994static void handle_keyboard(_THIS)
995{
996 unsigned char keybuf[BUFSIZ];
997 int i, nread;
998 int pressed;
999 int scancode;
1000 SDL_keysym keysym;
1001
1002 nread = read(keyboard_fd, keybuf, BUFSIZ);
1003 for ( i=0; i<nread; ++i ) {
1004 scancode = keybuf[i] & 0x7F;
1005 if ( keybuf[i] & 0x80 ) {
1006 pressed = SDL_RELEASED;
1007 } else {
1008 pressed = SDL_PRESSED;
1009 }
1010 TranslateKey(scancode, &keysym);
1011 /* Handle Ctrl-Alt-FN for vt switch */
1012 switch (keysym.sym) {
1013 case SDLK_F1:
1014 case SDLK_F2:
1015 case SDLK_F3:
1016 case SDLK_F4:
1017 case SDLK_F5:
1018 case SDLK_F6:
1019 case SDLK_F7:
1020 case SDLK_F8:
1021 case SDLK_F9:
1022 case SDLK_F10:
1023 case SDLK_F11:
1024 case SDLK_F12:
1025 if ( (SDL_GetModState() & KMOD_CTRL) &&
1026 (SDL_GetModState() & KMOD_ALT) ) {
1027 if ( pressed ) {
1028 switch_vt(this, (keysym.sym-SDLK_F1)+1);
1029 }
1030 break;
1031 }
1032 /* Fall through to normal processing */
1033 default:
1034 posted += SDL_PrivateKeyboard(pressed, &keysym);
1035 break;
1036 }
1037 }
1038}
1039
1040void FB_PumpEvents(_THIS)
1041{
1042 fd_set fdset;
1043 int max_fd;
1044 static struct timeval zero;
1045
1046 do {
1047 if ( switched_away ) {
1048 struct vt_stat vtstate;
1049
1050 SDL_mutexP(hw_lock);
1051 if ( (ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0) &&
1052 vtstate.v_active == current_vt ) {
1053 switched_away = 0;
1054 switch_vt_done(this);
1055 }
1056 SDL_mutexV(hw_lock);
1057 }
1058
1059 posted = 0;
1060
1061 FD_ZERO(&fdset);
1062 max_fd = 0;
1063 if ( keyboard_fd >= 0 ) {
1064 FD_SET(keyboard_fd, &fdset);
1065 if ( max_fd < keyboard_fd ) {
1066 max_fd = keyboard_fd;
1067 }
1068 }
1069 if ( mouse_fd >= 0 ) {
1070 FD_SET(mouse_fd, &fdset);
1071 if ( max_fd < mouse_fd ) {
1072 max_fd = mouse_fd;
1073 }
1074 }
1075 if ( select(max_fd+1, &fdset, NULL, NULL, &zero) > 0 ) {
1076 if ( keyboard_fd >= 0 ) {
1077 if ( FD_ISSET(keyboard_fd, &fdset) ) {
1078 handle_keyboard(this);
1079 }
1080 }
1081 if ( mouse_fd >= 0 ) {
1082 if ( FD_ISSET(mouse_fd, &fdset) ) {
1083 handle_mouse(this);
1084 }
1085 }
1086 }
1087 } while ( posted );
1088}
1089
1090void FB_InitOSKeymap(_THIS)
1091{
1092 int i;
1093
1094 /* Initialize the Linux key translation table */
1095
1096 /* First get the ascii keys and others not well handled */
1097 for (i=0; i<SDL_arraysize(keymap); ++i) {
1098 switch(i) {
1099 /* These aren't handled by the x86 kernel keymapping (?) */
1100 case SCANCODE_PRINTSCREEN:
1101 keymap[i] = SDLK_PRINT;
1102 break;
1103 case SCANCODE_BREAK:
1104 keymap[i] = SDLK_BREAK;
1105 break;
1106 case SCANCODE_BREAK_ALTERNATIVE:
1107 keymap[i] = SDLK_PAUSE;
1108 break;
1109 case SCANCODE_LEFTSHIFT:
1110 keymap[i] = SDLK_LSHIFT;
1111 break;
1112 case SCANCODE_RIGHTSHIFT:
1113 keymap[i] = SDLK_RSHIFT;
1114 break;
1115 case SCANCODE_LEFTCONTROL:
1116 keymap[i] = SDLK_LCTRL;
1117 break;
1118 case SCANCODE_RIGHTCONTROL:
1119 keymap[i] = SDLK_RCTRL;
1120 break;
1121 case SCANCODE_RIGHTWIN:
1122 keymap[i] = SDLK_RSUPER;
1123 break;
1124 case SCANCODE_LEFTWIN:
1125 keymap[i] = SDLK_LSUPER;
1126 break;
1127 case SCANCODE_LEFTALT:
1128 keymap[i] = SDLK_LALT;
1129 break;
1130 case SCANCODE_RIGHTALT:
1131 keymap[i] = SDLK_RALT;
1132 break;
1133 case 127:
1134 keymap[i] = SDLK_MENU;
1135 break;
1136 /* this should take care of all standard ascii keys */
1137 default:
1138 keymap[i] = KVAL(vga_keymap[0][i]);
1139 break;
1140 }
1141 }
1142 for (i=0; i<SDL_arraysize(keymap); ++i) {
1143 switch(keymap_temp[i]) {
1144 case K_F1: keymap[i] = SDLK_F1; break;
1145 case K_F2: keymap[i] = SDLK_F2; break;
1146 case K_F3: keymap[i] = SDLK_F3; break;
1147 case K_F4: keymap[i] = SDLK_F4; break;
1148 case K_F5: keymap[i] = SDLK_F5; break;
1149 case K_F6: keymap[i] = SDLK_F6; break;
1150 case K_F7: keymap[i] = SDLK_F7; break;
1151 case K_F8: keymap[i] = SDLK_F8; break;
1152 case K_F9: keymap[i] = SDLK_F9; break;
1153 case K_F10: keymap[i] = SDLK_F10; break;
1154 case K_F11: keymap[i] = SDLK_F11; break;
1155 case K_F12: keymap[i] = SDLK_F12; break;
1156
1157 case K_DOWN: keymap[i] = SDLK_DOWN; break;
1158 case K_LEFT: keymap[i] = SDLK_LEFT; break;
1159 case K_RIGHT: keymap[i] = SDLK_RIGHT; break;
1160 case K_UP: keymap[i] = SDLK_UP; break;
1161
1162 case K_P0: keymap[i] = SDLK_KP0; break;
1163 case K_P1: keymap[i] = SDLK_KP1; break;
1164 case K_P2: keymap[i] = SDLK_KP2; break;
1165 case K_P3: keymap[i] = SDLK_KP3; break;
1166 case K_P4: keymap[i] = SDLK_KP4; break;
1167 case K_P5: keymap[i] = SDLK_KP5; break;
1168 case K_P6: keymap[i] = SDLK_KP6; break;
1169 case K_P7: keymap[i] = SDLK_KP7; break;
1170 case K_P8: keymap[i] = SDLK_KP8; break;
1171 case K_P9: keymap[i] = SDLK_KP9; break;
1172 case K_PPLUS: keymap[i] = SDLK_KP_PLUS; break;
1173 case K_PMINUS: keymap[i] = SDLK_KP_MINUS; break;
1174 case K_PSTAR: keymap[i] = SDLK_KP_MULTIPLY; break;
1175 case K_PSLASH: keymap[i] = SDLK_KP_DIVIDE; break;
1176 case K_PENTER: keymap[i] = SDLK_KP_ENTER; break;
1177 case K_PDOT: keymap[i] = SDLK_KP_PERIOD; break;
1178
1179 case K_SHIFT: if ( keymap[i] != SDLK_RSHIFT )
1180 keymap[i] = SDLK_LSHIFT;
1181 break;
1182 case K_SHIFTL: keymap[i] = SDLK_LSHIFT; break;
1183 case K_SHIFTR: keymap[i] = SDLK_RSHIFT; break;
1184 case K_CTRL: if ( keymap[i] != SDLK_RCTRL )
1185 keymap[i] = SDLK_LCTRL;
1186 break;
1187 case K_CTRLL: keymap[i] = SDLK_LCTRL; break;
1188 case K_CTRLR: keymap[i] = SDLK_RCTRL; break;
1189 case K_ALT: keymap[i] = SDLK_LALT; break;
1190 case K_ALTGR: keymap[i] = SDLK_RALT; break;
1191
1192 case K_INSERT: keymap[i] = SDLK_INSERT; break;
1193 case K_REMOVE: keymap[i] = SDLK_DELETE; break;
1194 case K_PGUP: keymap[i] = SDLK_PAGEUP; break;
1195 case K_PGDN: keymap[i] = SDLK_PAGEDOWN; break;
1196 case K_FIND: keymap[i] = SDLK_HOME; break;
1197 case K_SELECT: keymap[i] = SDLK_END; break;
1198
1199 case K_NUM: keymap[i] = SDLK_NUMLOCK; break;
1200 case K_CAPS: keymap[i] = SDLK_CAPSLOCK; break;
1201
1202 case K_F13: keymap[i] = SDLK_PRINT; break;
1203 case K_HOLD: keymap[i] = SDLK_SCROLLOCK; break;
1204 case K_PAUSE: keymap[i] = SDLK_PAUSE; break;
1205
1206 case 127: keymap[i] = SDLK_BACKSPACE; break;
1207
1208 default: break;
1209 }
1210 }
1211}
1212
1213static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym)
1214{
1215 /* Set the keysym information */
1216 keysym->scancode = scancode;
1217 keysym->sym = keymap[scancode];
1218 keysym->mod = KMOD_NONE;
1219
1220 /* If UNICODE is on, get the UNICODE value for the key */
1221 keysym->unicode = 0;
1222 if ( SDL_TranslateUNICODE ) {
1223 int map;
1224 SDLMod modstate;
1225
1226 modstate = SDL_GetModState();
1227 map = 0;
1228 if ( modstate & KMOD_SHIFT ) {
1229 map |= (1<<KG_SHIFT);
1230 }
1231 if ( modstate & KMOD_CTRL ) {
1232 map |= (1<<KG_CTRL);
1233 }
1234 if ( modstate & KMOD_LALT ) {
1235 map |= (1<<KG_ALT);
1236 }
1237 if ( modstate & KMOD_RALT ) {
1238 map |= (1<<KG_ALTGR);
1239 }
1240 if ( KTYP(vga_keymap[map][scancode]) == KT_LETTER ) {
1241 if ( modstate & KMOD_CAPS ) {
1242 map ^= (1<<KG_SHIFT);
1243 }
1244 }
1245 if ( KTYP(vga_keymap[map][scancode]) == KT_PAD ) {
1246 if ( modstate & KMOD_NUM ) {
1247 keysym->unicode=KVAL(vga_keymap[map][scancode]);
1248 }
1249 } else {
1250 keysym->unicode = KVAL(vga_keymap[map][scancode]);
1251 }
1252 }
1253 return(keysym);
1254}
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbevents_c.h b/apps/plugins/sdl/src/video/fbcon/SDL_fbevents_c.h
deleted file mode 100644
index fe8b09cab3..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbevents_c.h
+++ /dev/null
@@ -1,38 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_fbvideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29extern int FB_OpenKeyboard(_THIS);
30extern void FB_CloseKeyboard(_THIS);
31extern int FB_OpenMouse(_THIS);
32extern void FB_CloseMouse(_THIS);
33extern int FB_EnterGraphicsMode(_THIS);
34extern int FB_InGraphicsMode(_THIS);
35extern void FB_LeaveGraphicsMode(_THIS);
36
37extern void FB_InitOSKeymap(_THIS);
38extern void FB_PumpEvents(_THIS);
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbkeys.h b/apps/plugins/sdl/src/video/fbcon/SDL_fbkeys.h
deleted file mode 100644
index 2b01b6b2e3..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbkeys.h
+++ /dev/null
@@ -1,139 +0,0 @@
1
2/* Scancodes for the Linux framebuffer console
3 - Taken with thanks from SVGAlib 1.4.0
4*/
5
6#define SCANCODE_ESCAPE 1
7
8#define SCANCODE_1 2
9#define SCANCODE_2 3
10#define SCANCODE_3 4
11#define SCANCODE_4 5
12#define SCANCODE_5 6
13#define SCANCODE_6 7
14#define SCANCODE_7 8
15#define SCANCODE_8 9
16#define SCANCODE_9 10
17#define SCANCODE_0 11
18
19#define SCANCODE_MINUS 12
20#define SCANCODE_EQUAL 13
21
22#define SCANCODE_BACKSPACE 14
23#define SCANCODE_TAB 15
24
25#define SCANCODE_Q 16
26#define SCANCODE_W 17
27#define SCANCODE_E 18
28#define SCANCODE_R 19
29#define SCANCODE_T 20
30#define SCANCODE_Y 21
31#define SCANCODE_U 22
32#define SCANCODE_I 23
33#define SCANCODE_O 24
34#define SCANCODE_P 25
35#define SCANCODE_BRACKET_LEFT 26
36#define SCANCODE_BRACKET_RIGHT 27
37
38#define SCANCODE_ENTER 28
39
40#define SCANCODE_LEFTCONTROL 29
41
42#define SCANCODE_A 30
43#define SCANCODE_S 31
44#define SCANCODE_D 32
45#define SCANCODE_F 33
46#define SCANCODE_G 34
47#define SCANCODE_H 35
48#define SCANCODE_J 36
49#define SCANCODE_K 37
50#define SCANCODE_L 38
51#define SCANCODE_SEMICOLON 39
52#define SCANCODE_APOSTROPHE 40
53#define SCANCODE_GRAVE 41
54
55#define SCANCODE_LEFTSHIFT 42
56#define SCANCODE_BACKSLASH 43
57
58#define SCANCODE_Z 44
59#define SCANCODE_X 45
60#define SCANCODE_C 46
61#define SCANCODE_V 47
62#define SCANCODE_B 48
63#define SCANCODE_N 49
64#define SCANCODE_M 50
65#define SCANCODE_COMMA 51
66#define SCANCODE_PERIOD 52
67#define SCANCODE_SLASH 53
68
69#define SCANCODE_RIGHTSHIFT 54
70#define SCANCODE_KEYPADMULTIPLY 55
71
72#define SCANCODE_LEFTALT 56
73#define SCANCODE_SPACE 57
74#define SCANCODE_CAPSLOCK 58
75
76#define SCANCODE_F1 59
77#define SCANCODE_F2 60
78#define SCANCODE_F3 61
79#define SCANCODE_F4 62
80#define SCANCODE_F5 63
81#define SCANCODE_F6 64
82#define SCANCODE_F7 65
83#define SCANCODE_F8 66
84#define SCANCODE_F9 67
85#define SCANCODE_F10 68
86
87#define SCANCODE_NUMLOCK 69
88#define SCANCODE_SCROLLLOCK 70
89
90#define SCANCODE_KEYPAD7 71
91#define SCANCODE_CURSORUPLEFT 71
92#define SCANCODE_KEYPAD8 72
93#define SCANCODE_CURSORUP 72
94#define SCANCODE_KEYPAD9 73
95#define SCANCODE_CURSORUPRIGHT 73
96#define SCANCODE_KEYPADMINUS 74
97#define SCANCODE_KEYPAD4 75
98#define SCANCODE_CURSORLEFT 75
99#define SCANCODE_KEYPAD5 76
100#define SCANCODE_KEYPAD6 77
101#define SCANCODE_CURSORRIGHT 77
102#define SCANCODE_KEYPADPLUS 78
103#define SCANCODE_KEYPAD1 79
104#define SCANCODE_CURSORDOWNLEFT 79
105#define SCANCODE_KEYPAD2 80
106#define SCANCODE_CURSORDOWN 80
107#define SCANCODE_KEYPAD3 81
108#define SCANCODE_CURSORDOWNRIGHT 81
109#define SCANCODE_KEYPAD0 82
110#define SCANCODE_KEYPADPERIOD 83
111
112#define SCANCODE_LESS 86
113
114#define SCANCODE_F11 87
115#define SCANCODE_F12 88
116
117#define SCANCODE_KEYPADENTER 96
118#define SCANCODE_RIGHTCONTROL 97
119#define SCANCODE_CONTROL 97
120#define SCANCODE_KEYPADDIVIDE 98
121#define SCANCODE_PRINTSCREEN 99
122#define SCANCODE_RIGHTALT 100
123#define SCANCODE_BREAK 101 /* Beware: is 119 */
124#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */
125
126#define SCANCODE_HOME 102
127#define SCANCODE_CURSORBLOCKUP 103 /* Cursor key block */
128#define SCANCODE_PAGEUP 104
129#define SCANCODE_CURSORBLOCKLEFT 105 /* Cursor key block */
130#define SCANCODE_CURSORBLOCKRIGHT 106 /* Cursor key block */
131#define SCANCODE_END 107
132#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */
133#define SCANCODE_PAGEDOWN 109
134#define SCANCODE_INSERT 110
135#define SCANCODE_REMOVE 111
136
137#define SCANCODE_RIGHTWIN 126
138#define SCANCODE_LEFTWIN 125
139
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbmatrox.c b/apps/plugins/sdl/src/video/fbcon/SDL_fbmatrox.c
deleted file mode 100644
index 04b90b05da..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbmatrox.c
+++ /dev/null
@@ -1,280 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_video.h"
25#include "../SDL_blit.h"
26#include "SDL_fbmatrox.h"
27#include "matrox_mmio.h"
28
29
30/* Wait for vertical retrace - taken from the XFree86 Matrox driver */
31static void WaitVBL(_THIS)
32{
33 int count;
34
35 /* find start of retrace */
36 mga_waitidle();
37 while ( (mga_in8(0x1FDA) & 0x08) )
38 ;
39 while ( !(mga_in8(0x1FDA) & 0x08) )
40 ;
41 /* wait until we're past the start */
42 count = mga_in32(0x1E20) + 2;
43 while ( mga_in32(0x1E20) < count )
44 ;
45}
46static void WaitIdle(_THIS)
47{
48 mga_waitidle();
49}
50
51/* Sets video mem colorkey and accelerated blit function */
52static int SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key)
53{
54 return(0);
55}
56
57/* Sets per surface hardware alpha value */
58#if 0
59static int SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 value)
60{
61 return(0);
62}
63#endif
64
65static int FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color)
66{
67 int dstX, dstY;
68 Uint32 fxbndry;
69 Uint32 ydstlen;
70 Uint32 fillop;
71
72 /* Don't blit to the display surface when switched away */
73 if ( switched_away ) {
74 return -2; /* no hardware access */
75 }
76 if ( dst == this->screen ) {
77 SDL_mutexP(hw_lock);
78 }
79
80 switch (dst->format->BytesPerPixel) {
81 case 1:
82 color |= (color<<8);
83 case 2:
84 color |= (color<<16);
85 break;
86 }
87
88 /* Set up the X/Y base coordinates */
89 FB_dst_to_xy(this, dst, &dstX, &dstY);
90
91 /* Adjust for the current rectangle */
92 dstX += rect->x;
93 dstY += rect->y;
94
95 /* Set up the X boundaries */
96 fxbndry = (dstX | ((dstX+rect->w) << 16));
97
98 /* Set up the Y boundaries */
99 ydstlen = (rect->h | (dstY << 16));
100
101 /* Set up for color fill operation */
102 fillop = MGADWG_TRAP | MGADWG_SOLID |
103 MGADWG_ARZERO | MGADWG_SGNZERO | MGADWG_SHIFTZERO;
104
105 /* Execute the operations! */
106 mga_wait(5);
107 mga_out32(MGAREG_DWGCTL, fillop | MGADWG_REPLACE);
108 mga_out32(MGAREG_FCOL, color);
109 mga_out32(MGAREG_FXBNDRY, fxbndry);
110 mga_out32(MGAREG_YDSTLEN + MGAREG_EXEC, ydstlen);
111
112 FB_AddBusySurface(dst);
113
114 if ( dst == this->screen ) {
115 SDL_mutexV(hw_lock);
116 }
117 return(0);
118}
119
120static int HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
121 SDL_Surface *dst, SDL_Rect *dstrect)
122{
123 SDL_VideoDevice *this = current_video;
124 int pitch, w, h;
125 int srcX, srcY;
126 int dstX, dstY;
127 Uint32 sign;
128 Uint32 start, stop;
129 int skip;
130 Uint32 blitop;
131
132 /* FIXME: For now, only blit to display surface */
133 if ( dst->pitch != SDL_VideoSurface->pitch ) {
134 return(src->map->sw_blit(src, srcrect, dst, dstrect));
135 }
136
137 /* Don't blit to the display surface when switched away */
138 if ( switched_away ) {
139 return -2; /* no hardware access */
140 }
141 if ( dst == this->screen ) {
142 SDL_mutexP(hw_lock);
143 }
144
145 /* Calculate source and destination base coordinates (in pixels) */
146 w = dstrect->w;
147 h = dstrect->h;
148 FB_dst_to_xy(this, src, &srcX, &srcY);
149 FB_dst_to_xy(this, dst, &dstX, &dstY);
150
151 /* Adjust for the current blit rectangles */
152 srcX += srcrect->x;
153 srcY += srcrect->y;
154 dstX += dstrect->x;
155 dstY += dstrect->y;
156 pitch = dst->pitch/dst->format->BytesPerPixel;
157
158 /* Set up the blit direction (sign) flags */
159 sign = 0;
160 if ( srcX < dstX ) {
161 sign |= 1;
162 }
163 if ( srcY < dstY ) {
164 sign |= 4;
165 srcY += (h - 1);
166 dstY += (h - 1);
167 }
168
169 /* Set up the blit source row start, end, and skip (in pixels) */
170 stop = start = (srcY * pitch) + srcX;
171 if ( srcX < dstX ) {
172 start += (w - 1);
173 } else {
174 stop += (w - 1);
175 }
176 if ( srcY < dstY ) {
177 skip = -pitch;
178 } else {
179 skip = pitch;
180 }
181
182 /* Set up the blit operation */
183 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
184 Uint32 colorkey;
185
186 blitop = MGADWG_BFCOL | MGADWG_BITBLT |
187 MGADWG_SHIFTZERO | MGADWG_RSTR | (0x0C << 16) |
188 MGADWG_TRANSC;
189
190 colorkey = src->format->colorkey;
191 switch (dst->format->BytesPerPixel) {
192 case 1:
193 colorkey |= (colorkey<<8);
194 case 2:
195 colorkey |= (colorkey<<16);
196 break;
197 }
198 mga_wait(2);
199 mga_out32(MGAREG_FCOL, colorkey);
200 mga_out32(MGAREG_BCOL, 0xFFFFFFFF);
201 } else {
202 blitop = MGADWG_BFCOL | MGADWG_BITBLT |
203 MGADWG_SHIFTZERO | MGADWG_RSTR | (0x0C << 16);
204 }
205 mga_wait(7);
206 mga_out32(MGAREG_SGN, sign);
207 mga_out32(MGAREG_AR3, start);
208 mga_out32(MGAREG_AR0, stop);
209 mga_out32(MGAREG_AR5, skip);
210 mga_out32(MGAREG_FXBNDRY, (dstX | ((dstX + w-1) << 16)));
211 mga_out32(MGAREG_YDSTLEN, (dstY << 16) | h);
212 mga_out32(MGAREG_DWGCTL + MGAREG_EXEC, blitop);
213
214 FB_AddBusySurface(src);
215 FB_AddBusySurface(dst);
216
217 if ( dst == this->screen ) {
218 SDL_mutexV(hw_lock);
219 }
220 return(0);
221}
222
223static int CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst)
224{
225 int accelerated;
226
227 /* Set initial acceleration on */
228 src->flags |= SDL_HWACCEL;
229
230 /* Set the surface attributes */
231 if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
232 if ( ! this->info.blit_hw_A ) {
233 src->flags &= ~SDL_HWACCEL;
234 }
235 }
236 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
237 if ( ! this->info.blit_hw_CC ) {
238 src->flags &= ~SDL_HWACCEL;
239 }
240 }
241
242 /* Check to see if final surface blit is accelerated */
243 accelerated = !!(src->flags & SDL_HWACCEL);
244 if ( accelerated ) {
245 src->map->hw_blit = HWAccelBlit;
246 }
247 return(accelerated);
248}
249
250void FB_MatroxAccel(_THIS, __u32 card)
251{
252 /* We have hardware accelerated surface functions */
253 this->CheckHWBlit = CheckHWBlit;
254 wait_vbl = WaitVBL;
255 wait_idle = WaitIdle;
256
257 /* The Matrox has an accelerated color fill */
258 this->info.blit_fill = 1;
259 this->FillHWRect = FillHWRect;
260
261 /* The Matrox has accelerated normal and colorkey blits. */
262 this->info.blit_hw = 1;
263 /* The Millenium I appears to do the colorkey test a word
264 at a time, and the transparency is intverted. (?)
265 */
266 if ( card != FB_ACCEL_MATROX_MGA2064W ) {
267 this->info.blit_hw_CC = 1;
268 this->SetHWColorKey = SetHWColorKey;
269 }
270
271#if 0 /* Not yet implemented? */
272 /* The Matrox G200/G400 has an accelerated alpha blit */
273 if ( (card == FB_ACCEL_MATROX_MGAG200)
274 || (card == FB_ACCEL_MATROX_MGAG400)
275 ) {
276 this->info.blit_hw_A = 1;
277 this->SetHWAlpha = SetHWAlpha;
278 }
279#endif
280}
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbmatrox.h b/apps/plugins/sdl/src/video/fbcon/SDL_fbmatrox.h
deleted file mode 100644
index f7d41b0240..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbmatrox.h
+++ /dev/null
@@ -1,29 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Matrox hardware acceleration for the SDL framebuffer console driver */
25
26#include "SDL_fbvideo.h"
27
28/* Set up the driver for Matrox acceleration */
29extern void FB_MatroxAccel(_THIS, __u32 card);
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbmouse.c b/apps/plugins/sdl/src/video/fbcon/SDL_fbmouse.c
deleted file mode 100644
index d65f27ece5..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbmouse.c
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_mouse.h"
25#include "../../events/SDL_events_c.h"
26#include "SDL_fbvideo.h"
27#include "SDL_fbmouse_c.h"
28
29
30/* The implementation dependent data for the window manager cursor */
31struct WMcursor {
32 int unused;
33};
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbmouse_c.h b/apps/plugins/sdl/src/video/fbcon/SDL_fbmouse_c.h
deleted file mode 100644
index fbb031d1f7..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbmouse_c.h
+++ /dev/null
@@ -1,26 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_fbvideo.h"
25
26/* Functions to be exported */
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbriva.c b/apps/plugins/sdl/src/video/fbcon/SDL_fbriva.c
deleted file mode 100644
index eb4b71f1bb..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbriva.c
+++ /dev/null
@@ -1,222 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_video.h"
25#include "../SDL_blit.h"
26#include "SDL_fbriva.h"
27#include "riva_mmio.h"
28#include "riva_regs.h"
29
30
31static int FifoEmptyCount = 0;
32static int FifoFreeCount = 0;
33
34/* Wait for vertical retrace */
35static void WaitVBL(_THIS)
36{
37 volatile Uint8 *port = (Uint8 *)(mapped_io + PCIO_OFFSET + 0x3DA);
38
39 while ( (*port & 0x08) )
40 ;
41 while ( !(*port & 0x08) )
42 ;
43}
44static void NV3WaitIdle(_THIS)
45{
46 RivaRop *Rop = (RivaRop *)(mapped_io + ROP_OFFSET);
47 while ( (Rop->FifoFree < FifoEmptyCount) ||
48 (*(mapped_io + PGRAPH_OFFSET + 0x000006B0) & 0x01) )
49 ;
50}
51static void NV4WaitIdle(_THIS)
52{
53 RivaRop *Rop = (RivaRop *)(mapped_io + ROP_OFFSET);
54 while ( (Rop->FifoFree < FifoEmptyCount) ||
55 (*(mapped_io + PGRAPH_OFFSET + 0x00000700) & 0x01) )
56 ;
57}
58
59#if 0 /* Not yet implemented? */
60/* Sets video mem colorkey and accelerated blit function */
61static int SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key)
62{
63 return(0);
64}
65
66/* Sets per surface hardware alpha value */
67static int SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 value)
68{
69 return(0);
70}
71#endif /* Not yet implemented */
72
73static int FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color)
74{
75 int dstX, dstY;
76 int dstW, dstH;
77 RivaBitmap *Bitmap = (RivaBitmap *)(mapped_io + BITMAP_OFFSET);
78
79 /* Don't blit to the display surface when switched away */
80 if ( switched_away ) {
81 return -2; /* no hardware access */
82 }
83 if ( dst == this->screen ) {
84 SDL_mutexP(hw_lock);
85 }
86
87 /* Set up the X/Y base coordinates */
88 dstW = rect->w;
89 dstH = rect->h;
90 FB_dst_to_xy(this, dst, &dstX, &dstY);
91
92 /* Adjust for the current rectangle */
93 dstX += rect->x;
94 dstY += rect->y;
95
96 RIVA_FIFO_FREE(Bitmap, 1);
97 Bitmap->Color1A = color;
98
99 RIVA_FIFO_FREE(Bitmap, 2);
100 Bitmap->UnclippedRectangle[0].TopLeft = (dstX << 16) | dstY;
101 Bitmap->UnclippedRectangle[0].WidthHeight = (dstW << 16) | dstH;
102
103 FB_AddBusySurface(dst);
104
105 if ( dst == this->screen ) {
106 SDL_mutexV(hw_lock);
107 }
108 return(0);
109}
110
111static int HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
112 SDL_Surface *dst, SDL_Rect *dstrect)
113{
114 SDL_VideoDevice *this = current_video;
115 int srcX, srcY;
116 int dstX, dstY;
117 int dstW, dstH;
118 RivaScreenBlt *Blt = (RivaScreenBlt *)(mapped_io + BLT_OFFSET);
119
120 /* FIXME: For now, only blit to display surface */
121 if ( dst->pitch != SDL_VideoSurface->pitch ) {
122 return(src->map->sw_blit(src, srcrect, dst, dstrect));
123 }
124
125 /* Don't blit to the display surface when switched away */
126 if ( switched_away ) {
127 return -2; /* no hardware access */
128 }
129 if ( dst == this->screen ) {
130 SDL_mutexP(hw_lock);
131 }
132
133 /* Calculate source and destination base coordinates (in pixels) */
134 dstW = dstrect->w;
135 dstH = dstrect->h;
136 FB_dst_to_xy(this, src, &srcX, &srcY);
137 FB_dst_to_xy(this, dst, &dstX, &dstY);
138
139 /* Adjust for the current blit rectangles */
140 srcX += srcrect->x;
141 srcY += srcrect->y;
142 dstX += dstrect->x;
143 dstY += dstrect->y;
144
145 RIVA_FIFO_FREE(Blt, 3);
146 Blt->TopLeftSrc = (srcY << 16) | srcX;
147 Blt->TopLeftDst = (dstY << 16) | dstX;
148 Blt->WidthHeight = (dstH << 16) | dstW;
149
150 FB_AddBusySurface(src);
151 FB_AddBusySurface(dst);
152
153 if ( dst == this->screen ) {
154 SDL_mutexV(hw_lock);
155 }
156 return(0);
157}
158
159static int CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst)
160{
161 int accelerated;
162
163 /* Set initial acceleration on */
164 src->flags |= SDL_HWACCEL;
165
166 /* Set the surface attributes */
167 if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
168 if ( ! this->info.blit_hw_A ) {
169 src->flags &= ~SDL_HWACCEL;
170 }
171 }
172 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
173 if ( ! this->info.blit_hw_CC ) {
174 src->flags &= ~SDL_HWACCEL;
175 }
176 }
177
178 /* Check to see if final surface blit is accelerated */
179 accelerated = !!(src->flags & SDL_HWACCEL);
180 if ( accelerated ) {
181 src->map->hw_blit = HWAccelBlit;
182 }
183 return(accelerated);
184}
185
186void FB_RivaAccel(_THIS, __u32 card)
187{
188 RivaRop *Rop = (RivaRop *)(mapped_io + ROP_OFFSET);
189
190 /* We have hardware accelerated surface functions */
191 this->CheckHWBlit = CheckHWBlit;
192 wait_vbl = WaitVBL;
193 switch (card) {
194 case FB_ACCEL_NV3:
195 wait_idle = NV3WaitIdle;
196 break;
197 case FB_ACCEL_NV4:
198 wait_idle = NV4WaitIdle;
199 break;
200 default:
201 /* Hmm... FIXME */
202 break;
203 }
204 FifoEmptyCount = Rop->FifoFree;
205
206 /* The Riva has an accelerated color fill */
207 this->info.blit_fill = 1;
208 this->FillHWRect = FillHWRect;
209
210 /* The Riva has accelerated normal and colorkey blits. */
211 this->info.blit_hw = 1;
212#if 0 /* Not yet implemented? */
213 this->info.blit_hw_CC = 1;
214 this->SetHWColorKey = SetHWColorKey;
215#endif
216
217#if 0 /* Not yet implemented? */
218 /* The Riva has an accelerated alpha blit */
219 this->info.blit_hw_A = 1;
220 this->SetHWAlpha = SetHWAlpha;
221#endif
222}
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbriva.h b/apps/plugins/sdl/src/video/fbcon/SDL_fbriva.h
deleted file mode 100644
index c78682e8a5..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbriva.h
+++ /dev/null
@@ -1,36 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Riva hardware acceleration for the SDL framebuffer console driver */
25
26#include "SDL_fbvideo.h"
27
28#ifndef FB_ACCEL_NV3
29#define FB_ACCEL_NV3 27
30#endif
31#ifndef FB_ACCEL_NV4
32#define FB_ACCEL_NV4 28
33#endif
34
35/* Set up the driver for Riva acceleration */
36extern void FB_RivaAccel(_THIS, __u32 card);
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbvideo.c b/apps/plugins/sdl/src/video/fbcon/SDL_fbvideo.c
deleted file mode 100644
index 5e5880908d..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbvideo.c
+++ /dev/null
@@ -1,1982 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Framebuffer console based SDL video driver implementation.
25*/
26
27#include <stdio.h>
28#include <fcntl.h>
29#include <unistd.h>
30#include <sys/ioctl.h>
31#include <sys/mman.h>
32
33#ifndef HAVE_GETPAGESIZE
34#include <asm/page.h> /* For definition of PAGE_SIZE */
35#endif
36
37#include <linux/vt.h>
38
39#include "SDL_video.h"
40#include "SDL_mouse.h"
41#include "../SDL_sysvideo.h"
42#include "../SDL_pixels_c.h"
43#include "../../events/SDL_events_c.h"
44#include "SDL_fbvideo.h"
45#include "SDL_fbmouse_c.h"
46#include "SDL_fbevents_c.h"
47#include "SDL_fb3dfx.h"
48#include "SDL_fbmatrox.h"
49#include "SDL_fbriva.h"
50
51/*#define FBCON_DEBUG*/
52
53#if defined(i386) && defined(FB_TYPE_VGA_PLANES)
54#define VGA16_FBCON_SUPPORT
55#include <sys/io.h> /* For ioperm() */
56#ifndef FB_AUX_VGA_PLANES_VGA4
57#define FB_AUX_VGA_PLANES_VGA4 0
58#endif
59/*
60static inline void outb (unsigned char value, unsigned short port)
61{
62 __asm__ __volatile__ ("outb %b0,%w1"::"a" (value), "Nd" (port));
63}
64*/
65#endif /* FB_TYPE_VGA_PLANES */
66
67/* A list of video resolutions that we query for (sorted largest to smallest) */
68static const SDL_Rect checkres[] = {
69 { 0, 0, 1600, 1200 }, /* 16 bpp: 0x11E, or 286 */
70 { 0, 0, 1408, 1056 }, /* 16 bpp: 0x19A, or 410 */
71 { 0, 0, 1280, 1024 }, /* 16 bpp: 0x11A, or 282 */
72 { 0, 0, 1152, 864 }, /* 16 bpp: 0x192, or 402 */
73 { 0, 0, 1024, 768 }, /* 16 bpp: 0x117, or 279 */
74 { 0, 0, 960, 720 }, /* 16 bpp: 0x18A, or 394 */
75 { 0, 0, 800, 600 }, /* 16 bpp: 0x114, or 276 */
76 { 0, 0, 768, 576 }, /* 16 bpp: 0x182, or 386 */
77 { 0, 0, 720, 576 }, /* PAL */
78 { 0, 0, 720, 480 }, /* NTSC */
79 { 0, 0, 640, 480 }, /* 16 bpp: 0x111, or 273 */
80 { 0, 0, 640, 400 }, /* 8 bpp: 0x100, or 256 */
81 { 0, 0, 512, 384 },
82 { 0, 0, 320, 240 },
83 { 0, 0, 320, 200 }
84};
85static const struct {
86 int xres;
87 int yres;
88 int pixclock;
89 int left;
90 int right;
91 int upper;
92 int lower;
93 int hslen;
94 int vslen;
95 int sync;
96 int vmode;
97} vesa_timings[] = {
98#ifdef USE_VESA_TIMINGS /* Only tested on Matrox Millenium I */
99 { 640, 400, 39771, 48, 16, 39, 8, 96, 2, 2, 0 }, /* 70 Hz */
100 { 640, 480, 39683, 48, 16, 33, 10, 96, 2, 0, 0 }, /* 60 Hz */
101 { 768, 576, 26101, 144, 16, 28, 6, 112, 4, 0, 0 }, /* 60 Hz */
102 { 800, 600, 24038, 144, 24, 28, 8, 112, 6, 0, 0 }, /* 60 Hz */
103 { 960, 720, 17686, 144, 24, 28, 8, 112, 4, 0, 0 }, /* 60 Hz */
104 { 1024, 768, 15386, 160, 32, 30, 4, 128, 4, 0, 0 }, /* 60 Hz */
105 { 1152, 864, 12286, 192, 32, 30, 4, 128, 4, 0, 0 }, /* 60 Hz */
106 { 1280, 1024, 9369, 224, 32, 32, 4, 136, 4, 0, 0 }, /* 60 Hz */
107 { 1408, 1056, 8214, 256, 40, 32, 5, 144, 5, 0, 0 }, /* 60 Hz */
108 { 1600, 1200,/*?*/0, 272, 48, 32, 5, 152, 5, 0, 0 }, /* 60 Hz */
109#else
110 /* You can generate these timings from your XF86Config file using
111 the 'modeline2fb' perl script included with the fbset package.
112 These timings were generated for Matrox Millenium I, 15" monitor.
113 */
114 { 320, 200, 79440, 16, 16, 20, 4, 48, 1, 0, 2 }, /* 70 Hz */
115 { 320, 240, 63492, 16, 16, 16, 4, 48, 2, 0, 2 }, /* 72 Hz */
116 { 512, 384, 49603, 48, 16, 16, 1, 64, 3, 0, 0 }, /* 78 Hz */
117 { 640, 400, 31746, 96, 32, 41, 1, 64, 3, 2, 0 }, /* 85 Hz */
118 { 640, 480, 31746, 120, 16, 16, 1, 64, 3, 0, 0 }, /* 75 Hz */
119 { 768, 576, 26101, 144, 16, 28, 6, 112, 4, 0, 0 }, /* 60 Hz */
120 { 800, 600, 20000, 64, 56, 23, 37, 120, 6, 3, 0 }, /* 72 Hz */
121 { 960, 720, 17686, 144, 24, 28, 8, 112, 4, 0, 0 }, /* 60 Hz */
122 { 1024, 768, 13333, 144, 24, 29, 3, 136, 6, 0, 0 }, /* 70 Hz */
123 { 1152, 864, 12286, 192, 32, 30, 4, 128, 4, 0, 0 }, /* 60 Hz */
124 { 1280, 1024, 9369, 224, 32, 32, 4, 136, 4, 0, 0 }, /* 60 Hz */
125 { 1408, 1056, 8214, 256, 40, 32, 5, 144, 5, 0, 0 }, /* 60 Hz */
126 { 1600, 1200,/*?*/0, 272, 48, 32, 5, 152, 5, 0, 0 }, /* 60 Hz */
127#endif
128};
129enum {
130 FBCON_ROTATE_NONE = 0,
131 FBCON_ROTATE_CCW = 90,
132 FBCON_ROTATE_UD = 180,
133 FBCON_ROTATE_CW = 270
134};
135
136#define min(a,b) ((a)<(b)?(a):(b))
137
138/* Initialization/Query functions */
139static int FB_VideoInit(_THIS, SDL_PixelFormat *vformat);
140static SDL_Rect **FB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
141static SDL_Surface *FB_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
142#ifdef VGA16_FBCON_SUPPORT
143static SDL_Surface *FB_SetVGA16Mode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
144#endif
145static int FB_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
146static void FB_VideoQuit(_THIS);
147
148/* Hardware surface functions */
149static int FB_InitHWSurfaces(_THIS, SDL_Surface *screen, char *base, int size);
150static void FB_FreeHWSurfaces(_THIS);
151static int FB_AllocHWSurface(_THIS, SDL_Surface *surface);
152static int FB_LockHWSurface(_THIS, SDL_Surface *surface);
153static void FB_UnlockHWSurface(_THIS, SDL_Surface *surface);
154static void FB_FreeHWSurface(_THIS, SDL_Surface *surface);
155static void FB_WaitVBL(_THIS);
156static void FB_WaitIdle(_THIS);
157static int FB_FlipHWSurface(_THIS, SDL_Surface *surface);
158
159/* Internal palette functions */
160static void FB_SavePalette(_THIS, struct fb_fix_screeninfo *finfo,
161 struct fb_var_screeninfo *vinfo);
162static void FB_RestorePalette(_THIS);
163
164/* Shadow buffer functions */
165static FB_bitBlit FB_blit16;
166static FB_bitBlit FB_blit16blocked;
167
168static int SDL_getpagesize(void)
169{
170#ifdef HAVE_GETPAGESIZE
171 return getpagesize();
172#elif defined(PAGE_SIZE)
173 return PAGE_SIZE;
174#else
175#error Can not determine system page size.
176 return 4096; /* this is what it USED to be in Linux... */
177#endif
178}
179
180
181/* Small wrapper for mmap() so we can play nicely with no-mmu hosts
182 * (non-mmu hosts disallow the MAP_SHARED flag) */
183
184static void *do_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset)
185{
186 void *ret;
187 ret = mmap(start, length, prot, flags, fd, offset);
188 if ( ret == (char *)-1 && (flags & MAP_SHARED) ) {
189 ret = mmap(start, length, prot,
190 (flags & ~MAP_SHARED) | MAP_PRIVATE, fd, offset);
191 }
192 return ret;
193}
194
195/* FB driver bootstrap functions */
196
197static int FB_Available(void)
198{
199 int console = -1;
200 /* Added check for /fb/0 (devfs) */
201 /* but - use environment variable first... if it fails, still check defaults */
202 int idx = 0;
203 const char *SDL_fbdevs[4] = { NULL, "/dev/fb0", "/dev/fb/0", NULL };
204
205 SDL_fbdevs[0] = SDL_getenv("SDL_FBDEV");
206 if( !SDL_fbdevs[0] )
207 idx++;
208 for( ; SDL_fbdevs[idx]; idx++ )
209 {
210 console = open(SDL_fbdevs[idx], O_RDWR, 0);
211 if ( console >= 0 ) {
212 close(console);
213 break;
214 }
215 }
216 return(console >= 0);
217}
218
219static void FB_DeleteDevice(SDL_VideoDevice *device)
220{
221 SDL_free(device->hidden);
222 SDL_free(device);
223}
224
225static SDL_VideoDevice *FB_CreateDevice(int devindex)
226{
227 SDL_VideoDevice *this;
228
229 /* Initialize all variables that we clean on shutdown */
230 this = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
231 if ( this ) {
232 SDL_memset(this, 0, (sizeof *this));
233 this->hidden = (struct SDL_PrivateVideoData *)
234 SDL_malloc((sizeof *this->hidden));
235 }
236 if ( (this == NULL) || (this->hidden == NULL) ) {
237 SDL_OutOfMemory();
238 if ( this ) {
239 SDL_free(this);
240 }
241 return(0);
242 }
243 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
244 wait_vbl = FB_WaitVBL;
245 wait_idle = FB_WaitIdle;
246 mouse_fd = -1;
247 keyboard_fd = -1;
248
249 /* Set the function pointers */
250 this->VideoInit = FB_VideoInit;
251 this->ListModes = FB_ListModes;
252 this->SetVideoMode = FB_SetVideoMode;
253 this->SetColors = FB_SetColors;
254 this->UpdateRects = NULL;
255 this->VideoQuit = FB_VideoQuit;
256 this->AllocHWSurface = FB_AllocHWSurface;
257 this->CheckHWBlit = NULL;
258 this->FillHWRect = NULL;
259 this->SetHWColorKey = NULL;
260 this->SetHWAlpha = NULL;
261 this->LockHWSurface = FB_LockHWSurface;
262 this->UnlockHWSurface = FB_UnlockHWSurface;
263 this->FlipHWSurface = FB_FlipHWSurface;
264 this->FreeHWSurface = FB_FreeHWSurface;
265 this->SetCaption = NULL;
266 this->SetIcon = NULL;
267 this->IconifyWindow = NULL;
268 this->GrabInput = NULL;
269 this->GetWMInfo = NULL;
270 this->InitOSKeymap = FB_InitOSKeymap;
271 this->PumpEvents = FB_PumpEvents;
272
273 this->free = FB_DeleteDevice;
274
275 return this;
276}
277
278VideoBootStrap FBCON_bootstrap = {
279 "fbcon", "Linux Framebuffer Console",
280 FB_Available, FB_CreateDevice
281};
282
283#define FB_MODES_DB "/etc/fb.modes"
284
285static int read_fbmodes_line(FILE*f, char* line, int length)
286{
287 int blank;
288 char* c;
289 int i;
290
291 blank=0;
292 /* find a relevant line */
293 do
294 {
295 if (!fgets(line,length,f))
296 return 0;
297 c=line;
298 while(((*c=='\t')||(*c==' '))&&(*c!=0))
299 c++;
300
301 if ((*c=='\n')||(*c=='#')||(*c==0))
302 blank=1;
303 else
304 blank=0;
305 }
306 while(blank);
307 /* remove whitespace at the begining of the string */
308 i=0;
309 do
310 {
311 line[i]=c[i];
312 i++;
313 }
314 while(c[i]!=0);
315 return 1;
316}
317
318static int read_fbmodes_mode(FILE *f, struct fb_var_screeninfo *vinfo)
319{
320 char line[1024];
321 char option[256];
322
323 /* Find a "geometry" */
324 do {
325 if (read_fbmodes_line(f, line, sizeof(line))==0)
326 return 0;
327 if (SDL_strncmp(line,"geometry",8)==0)
328 break;
329 }
330 while(1);
331
332 SDL_sscanf(line, "geometry %d %d %d %d %d", &vinfo->xres, &vinfo->yres,
333 &vinfo->xres_virtual, &vinfo->yres_virtual, &vinfo->bits_per_pixel);
334 if (read_fbmodes_line(f, line, sizeof(line))==0)
335 return 0;
336
337 SDL_sscanf(line, "timings %d %d %d %d %d %d %d", &vinfo->pixclock,
338 &vinfo->left_margin, &vinfo->right_margin, &vinfo->upper_margin,
339 &vinfo->lower_margin, &vinfo->hsync_len, &vinfo->vsync_len);
340
341 vinfo->sync=0;
342 vinfo->vmode=FB_VMODE_NONINTERLACED;
343
344 /* Parse misc options */
345 do {
346 if (read_fbmodes_line(f, line, sizeof(line))==0)
347 return 0;
348
349 if (SDL_strncmp(line,"hsync",5)==0) {
350 SDL_sscanf(line,"hsync %s",option);
351 if (SDL_strncmp(option,"high",4)==0)
352 vinfo->sync |= FB_SYNC_HOR_HIGH_ACT;
353 }
354 else if (SDL_strncmp(line,"vsync",5)==0) {
355 SDL_sscanf(line,"vsync %s",option);
356 if (SDL_strncmp(option,"high",4)==0)
357 vinfo->sync |= FB_SYNC_VERT_HIGH_ACT;
358 }
359 else if (SDL_strncmp(line,"csync",5)==0) {
360 SDL_sscanf(line,"csync %s",option);
361 if (SDL_strncmp(option,"high",4)==0)
362 vinfo->sync |= FB_SYNC_COMP_HIGH_ACT;
363 }
364 else if (SDL_strncmp(line,"extsync",5)==0) {
365 SDL_sscanf(line,"extsync %s",option);
366 if (SDL_strncmp(option,"true",4)==0)
367 vinfo->sync |= FB_SYNC_EXT;
368 }
369 else if (SDL_strncmp(line,"laced",5)==0) {
370 SDL_sscanf(line,"laced %s",option);
371 if (SDL_strncmp(option,"true",4)==0)
372 vinfo->vmode |= FB_VMODE_INTERLACED;
373 }
374 else if (SDL_strncmp(line,"double",6)==0) {
375 SDL_sscanf(line,"double %s",option);
376 if (SDL_strncmp(option,"true",4)==0)
377 vinfo->vmode |= FB_VMODE_DOUBLE;
378 }
379 }
380 while(SDL_strncmp(line,"endmode",7)!=0);
381
382 return 1;
383}
384
385static int FB_CheckMode(_THIS, struct fb_var_screeninfo *vinfo,
386 int index, unsigned int *w, unsigned int *h)
387{
388 int mode_okay;
389
390 mode_okay = 0;
391 vinfo->bits_per_pixel = (index+1)*8;
392 vinfo->xres = *w;
393 vinfo->xres_virtual = *w;
394 vinfo->yres = *h;
395 vinfo->yres_virtual = *h;
396 vinfo->activate = FB_ACTIVATE_TEST;
397 if ( ioctl(console_fd, FBIOPUT_VSCREENINFO, vinfo) == 0 ) {
398#ifdef FBCON_DEBUG
399 fprintf(stderr, "Checked mode %dx%d at %d bpp, got mode %dx%d at %d bpp\n", *w, *h, (index+1)*8, vinfo->xres, vinfo->yres, vinfo->bits_per_pixel);
400#endif
401 if ( (((vinfo->bits_per_pixel+7)/8)-1) == index ) {
402 *w = vinfo->xres;
403 *h = vinfo->yres;
404 mode_okay = 1;
405 }
406 }
407 return mode_okay;
408}
409
410static int FB_AddMode(_THIS, int index, unsigned int w, unsigned int h, int check_timings)
411{
412 SDL_Rect *mode;
413 int i;
414 int next_mode;
415
416 /* Check to see if we already have this mode */
417 if ( SDL_nummodes[index] > 0 ) {
418 mode = SDL_modelist[index][SDL_nummodes[index]-1];
419 if ( (mode->w == w) && (mode->h == h) ) {
420#ifdef FBCON_DEBUG
421 fprintf(stderr, "We already have mode %dx%d at %d bytes per pixel\n", w, h, index+1);
422#endif
423 return(0);
424 }
425 }
426
427 /* Only allow a mode if we have a valid timing for it */
428 if ( check_timings ) {
429 int found_timing = 0;
430 for ( i=0; i<(sizeof(vesa_timings)/sizeof(vesa_timings[0])); ++i ) {
431 if ( (w == vesa_timings[i].xres) &&
432 (h == vesa_timings[i].yres) && vesa_timings[i].pixclock ) {
433 found_timing = 1;
434 break;
435 }
436 }
437 if ( !found_timing ) {
438#ifdef FBCON_DEBUG
439 fprintf(stderr, "No valid timing line for mode %dx%d\n", w, h);
440#endif
441 return(0);
442 }
443 }
444
445 /* Set up the new video mode rectangle */
446 mode = (SDL_Rect *)SDL_malloc(sizeof *mode);
447 if ( mode == NULL ) {
448 SDL_OutOfMemory();
449 return(-1);
450 }
451 mode->x = 0;
452 mode->y = 0;
453 mode->w = w;
454 mode->h = h;
455#ifdef FBCON_DEBUG
456 fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h, index+1);
457#endif
458
459 /* Allocate the new list of modes, and fill in the new mode */
460 next_mode = SDL_nummodes[index];
461 SDL_modelist[index] = (SDL_Rect **)
462 SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *));
463 if ( SDL_modelist[index] == NULL ) {
464 SDL_OutOfMemory();
465 SDL_nummodes[index] = 0;
466 SDL_free(mode);
467 return(-1);
468 }
469 SDL_modelist[index][next_mode] = mode;
470 SDL_modelist[index][next_mode+1] = NULL;
471 SDL_nummodes[index]++;
472
473 return(0);
474}
475
476static int cmpmodes(const void *va, const void *vb)
477{
478 const SDL_Rect *a = *(const SDL_Rect**)va;
479 const SDL_Rect *b = *(const SDL_Rect**)vb;
480 if ( a->h == b->h )
481 return b->w - a->w;
482 else
483 return b->h - a->h;
484}
485
486static void FB_SortModes(_THIS)
487{
488 int i;
489 for ( i=0; i<NUM_MODELISTS; ++i ) {
490 if ( SDL_nummodes[i] > 0 ) {
491 SDL_qsort(SDL_modelist[i], SDL_nummodes[i], sizeof *SDL_modelist[i], cmpmodes);
492 }
493 }
494}
495
496static int FB_VideoInit(_THIS, SDL_PixelFormat *vformat)
497{
498 const int pagesize = SDL_getpagesize();
499 struct fb_fix_screeninfo finfo;
500 struct fb_var_screeninfo vinfo;
501 int i, j;
502 int current_index;
503 unsigned int current_w;
504 unsigned int current_h;
505 const char *SDL_fbdev;
506 const char *rotation;
507 FILE *modesdb;
508
509 /* Initialize the library */
510 SDL_fbdev = SDL_getenv("SDL_FBDEV");
511 if ( SDL_fbdev == NULL ) {
512 SDL_fbdev = "/dev/fb0";
513 }
514 console_fd = open(SDL_fbdev, O_RDWR, 0);
515 if ( console_fd < 0 ) {
516 SDL_SetError("Unable to open %s", SDL_fbdev);
517 return(-1);
518 }
519
520#if !SDL_THREADS_DISABLED
521 /* Create the hardware surface lock mutex */
522 hw_lock = SDL_CreateMutex();
523 if ( hw_lock == NULL ) {
524 SDL_SetError("Unable to create lock mutex");
525 FB_VideoQuit(this);
526 return(-1);
527 }
528#endif
529
530 /* Get the type of video hardware */
531 if ( ioctl(console_fd, FBIOGET_FSCREENINFO, &finfo) < 0 ) {
532 SDL_SetError("Couldn't get console hardware info");
533 FB_VideoQuit(this);
534 return(-1);
535 }
536 switch (finfo.type) {
537 case FB_TYPE_PACKED_PIXELS:
538 /* Supported, no worries.. */
539 break;
540#ifdef VGA16_FBCON_SUPPORT
541 case FB_TYPE_VGA_PLANES:
542 /* VGA16 is supported, but that's it */
543 if ( finfo.type_aux == FB_AUX_VGA_PLANES_VGA4 ) {
544 if ( ioperm(0x3b4, 0x3df - 0x3b4 + 1, 1) < 0 ) {
545 SDL_SetError("No I/O port permissions");
546 FB_VideoQuit(this);
547 return(-1);
548 }
549 this->SetVideoMode = FB_SetVGA16Mode;
550 break;
551 }
552 /* Fall through to unsupported case */
553#endif /* VGA16_FBCON_SUPPORT */
554 default:
555 SDL_SetError("Unsupported console hardware");
556 FB_VideoQuit(this);
557 return(-1);
558 }
559 switch (finfo.visual) {
560 case FB_VISUAL_TRUECOLOR:
561 case FB_VISUAL_PSEUDOCOLOR:
562 case FB_VISUAL_STATIC_PSEUDOCOLOR:
563 case FB_VISUAL_DIRECTCOLOR:
564 break;
565 default:
566 SDL_SetError("Unsupported console hardware");
567 FB_VideoQuit(this);
568 return(-1);
569 }
570
571 /* Check if the user wants to disable hardware acceleration */
572 { const char *fb_accel;
573 fb_accel = SDL_getenv("SDL_FBACCEL");
574 if ( fb_accel ) {
575 finfo.accel = SDL_atoi(fb_accel);
576 }
577 }
578
579 /* Memory map the device, compensating for buggy PPC mmap() */
580 mapped_offset = (((long)finfo.smem_start) -
581 (((long)finfo.smem_start)&~(pagesize-1)));
582 mapped_memlen = finfo.smem_len+mapped_offset;
583 mapped_mem = do_mmap(NULL, mapped_memlen,
584 PROT_READ|PROT_WRITE, MAP_SHARED, console_fd, 0);
585 if ( mapped_mem == (char *)-1 ) {
586 SDL_SetError("Unable to memory map the video hardware");
587 mapped_mem = NULL;
588 FB_VideoQuit(this);
589 return(-1);
590 }
591
592 /* Determine the current screen depth */
593 if ( ioctl(console_fd, FBIOGET_VSCREENINFO, &vinfo) < 0 ) {
594 SDL_SetError("Couldn't get console pixel format");
595 FB_VideoQuit(this);
596 return(-1);
597 }
598 vformat->BitsPerPixel = vinfo.bits_per_pixel;
599 if ( vformat->BitsPerPixel < 8 ) {
600 /* Assuming VGA16, we handle this via a shadow framebuffer */
601 vformat->BitsPerPixel = 8;
602 }
603 for ( i=0; i<vinfo.red.length; ++i ) {
604 vformat->Rmask <<= 1;
605 vformat->Rmask |= (0x00000001<<vinfo.red.offset);
606 }
607 for ( i=0; i<vinfo.green.length; ++i ) {
608 vformat->Gmask <<= 1;
609 vformat->Gmask |= (0x00000001<<vinfo.green.offset);
610 }
611 for ( i=0; i<vinfo.blue.length; ++i ) {
612 vformat->Bmask <<= 1;
613 vformat->Bmask |= (0x00000001<<vinfo.blue.offset);
614 }
615 saved_vinfo = vinfo;
616
617 /* Save hardware palette, if needed */
618 FB_SavePalette(this, &finfo, &vinfo);
619
620 /* If the I/O registers are available, memory map them so we
621 can take advantage of any supported hardware acceleration.
622 */
623 vinfo.accel_flags = 0; /* Temporarily reserve registers */
624 ioctl(console_fd, FBIOPUT_VSCREENINFO, &vinfo);
625 if ( finfo.accel && finfo.mmio_len ) {
626 mapped_iolen = finfo.mmio_len;
627 mapped_io = do_mmap(NULL, mapped_iolen, PROT_READ|PROT_WRITE,
628 MAP_SHARED, console_fd, mapped_memlen);
629 if ( mapped_io == (char *)-1 ) {
630 /* Hmm, failed to memory map I/O registers */
631 mapped_io = NULL;
632 }
633 }
634
635 rotate = FBCON_ROTATE_NONE;
636 rotation = SDL_getenv("SDL_VIDEO_FBCON_ROTATION");
637 if (rotation != NULL) {
638 if (SDL_strlen(rotation) == 0) {
639 shadow_fb = 0;
640 rotate = FBCON_ROTATE_NONE;
641#ifdef FBCON_DEBUG
642 printf("Not rotating, no shadow\n");
643#endif
644 } else if (!SDL_strcmp(rotation, "NONE")) {
645 shadow_fb = 1;
646 rotate = FBCON_ROTATE_NONE;
647#ifdef FBCON_DEBUG
648 printf("Not rotating, but still using shadow\n");
649#endif
650 } else if (!SDL_strcmp(rotation, "CW")) {
651 shadow_fb = 1;
652 rotate = FBCON_ROTATE_CW;
653#ifdef FBCON_DEBUG
654 printf("Rotating screen clockwise\n");
655#endif
656 } else if (!SDL_strcmp(rotation, "CCW")) {
657 shadow_fb = 1;
658 rotate = FBCON_ROTATE_CCW;
659#ifdef FBCON_DEBUG
660 printf("Rotating screen counter clockwise\n");
661#endif
662 } else if (!SDL_strcmp(rotation, "UD")) {
663 shadow_fb = 1;
664 rotate = FBCON_ROTATE_UD;
665#ifdef FBCON_DEBUG
666 printf("Rotating screen upside down\n");
667#endif
668 } else {
669 SDL_SetError("\"%s\" is not a valid value for "
670 "SDL_VIDEO_FBCON_ROTATION", rotation);
671 return(-1);
672 }
673 }
674
675 if (rotate == FBCON_ROTATE_CW || rotate == FBCON_ROTATE_CCW) {
676 current_w = vinfo.yres;
677 current_h = vinfo.xres;
678 } else {
679 current_w = vinfo.xres;
680 current_h = vinfo.yres;
681 }
682
683 /* Query for the list of available video modes */
684 current_index = ((vinfo.bits_per_pixel+7)/8)-1;
685 modesdb = fopen(FB_MODES_DB, "r");
686 for ( i=0; i<NUM_MODELISTS; ++i ) {
687 SDL_nummodes[i] = 0;
688 SDL_modelist[i] = NULL;
689 }
690 if ( SDL_getenv("SDL_FB_BROKEN_MODES") != NULL ) {
691 FB_AddMode(this, current_index, current_w, current_h, 0);
692 } else if(modesdb) {
693 while ( read_fbmodes_mode(modesdb, &vinfo) ) {
694 for ( i=0; i<NUM_MODELISTS; ++i ) {
695 unsigned int w, h;
696
697 if (rotate == FBCON_ROTATE_CW || rotate == FBCON_ROTATE_CCW) {
698 w = vinfo.yres;
699 h = vinfo.xres;
700 } else {
701 w = vinfo.xres;
702 h = vinfo.yres;
703 }
704 /* See if we are querying for the current mode */
705 if ( i == current_index ) {
706 if ( (current_w > w) || (current_h > h) ) {
707 /* Only check once */
708 FB_AddMode(this, i, current_w, current_h, 0);
709 current_index = -1;
710 }
711 }
712 if ( FB_CheckMode(this, &vinfo, i, &w, &h) ) {
713 FB_AddMode(this, i, w, h, 0);
714 }
715 }
716 }
717 fclose(modesdb);
718 FB_SortModes(this);
719 } else {
720 for ( i=0; i<NUM_MODELISTS; ++i ) {
721 for ( j=0; j<(sizeof(checkres)/sizeof(checkres[0])); ++j ) {
722 unsigned int w, h;
723
724 if (rotate == FBCON_ROTATE_CW || rotate == FBCON_ROTATE_CCW) {
725 w = checkres[j].h;
726 h = checkres[j].w;
727 } else {
728 w = checkres[j].w;
729 h = checkres[j].h;
730 }
731 /* See if we are querying for the current mode */
732 if ( i == current_index ) {
733 if ( (current_w > w) || (current_h > h) ) {
734 /* Only check once */
735 FB_AddMode(this, i, current_w, current_h, 0);
736 current_index = -1;
737 }
738 }
739 if ( FB_CheckMode(this, &vinfo, i, &w, &h) ) {
740 FB_AddMode(this, i, w, h, 1);
741 }
742 }
743 }
744 }
745
746 this->info.current_w = current_w;
747 this->info.current_h = current_h;
748 this->info.wm_available = 0;
749 this->info.hw_available = !shadow_fb;
750 this->info.video_mem = shadow_fb ? 0 : finfo.smem_len/1024;
751 /* Fill in our hardware acceleration capabilities */
752 if ( mapped_io ) {
753 switch (finfo.accel) {
754 case FB_ACCEL_MATROX_MGA2064W:
755 case FB_ACCEL_MATROX_MGA1064SG:
756 case FB_ACCEL_MATROX_MGA2164W:
757 case FB_ACCEL_MATROX_MGA2164W_AGP:
758 case FB_ACCEL_MATROX_MGAG100:
759 /*case FB_ACCEL_MATROX_MGAG200: G200 acceleration broken! */
760 case FB_ACCEL_MATROX_MGAG400:
761#ifdef FBACCEL_DEBUG
762 printf("Matrox hardware accelerator!\n");
763#endif
764 FB_MatroxAccel(this, finfo.accel);
765 break;
766 case FB_ACCEL_3DFX_BANSHEE:
767#ifdef FBACCEL_DEBUG
768 printf("3DFX hardware accelerator!\n");
769#endif
770 FB_3DfxAccel(this, finfo.accel);
771 break;
772 case FB_ACCEL_NV3:
773 case FB_ACCEL_NV4:
774#ifdef FBACCEL_DEBUG
775 printf("NVidia hardware accelerator!\n");
776#endif
777 FB_RivaAccel(this, finfo.accel);
778 break;
779 default:
780#ifdef FBACCEL_DEBUG
781 printf("Unknown hardware accelerator.\n");
782#endif
783 break;
784 }
785 }
786
787 if (shadow_fb) {
788 shadow_mem = (char *)SDL_malloc(mapped_memlen);
789 if (shadow_mem == NULL) {
790 SDL_SetError("No memory for shadow");
791 return (-1);
792 }
793 }
794
795 /* Enable mouse and keyboard support */
796 if ( FB_OpenKeyboard(this) < 0 ) {
797 FB_VideoQuit(this);
798 return(-1);
799 }
800 if ( FB_OpenMouse(this) < 0 ) {
801 const char *sdl_nomouse;
802
803 sdl_nomouse = SDL_getenv("SDL_NOMOUSE");
804 if ( ! sdl_nomouse ) {
805 SDL_SetError("Unable to open mouse");
806 FB_VideoQuit(this);
807 return(-1);
808 }
809 }
810
811 /* We're done! */
812 return(0);
813}
814
815static SDL_Rect **FB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
816{
817 return(SDL_modelist[((format->BitsPerPixel+7)/8)-1]);
818}
819
820/* Various screen update functions available */
821static void FB_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
822#ifdef VGA16_FBCON_SUPPORT
823static void FB_VGA16Update(_THIS, int numrects, SDL_Rect *rects);
824#endif
825
826#ifdef FBCON_DEBUG
827static void print_vinfo(struct fb_var_screeninfo *vinfo)
828{
829 fprintf(stderr, "Printing vinfo:\n");
830 fprintf(stderr, "\txres: %d\n", vinfo->xres);
831 fprintf(stderr, "\tyres: %d\n", vinfo->yres);
832 fprintf(stderr, "\txres_virtual: %d\n", vinfo->xres_virtual);
833 fprintf(stderr, "\tyres_virtual: %d\n", vinfo->yres_virtual);
834 fprintf(stderr, "\txoffset: %d\n", vinfo->xoffset);
835 fprintf(stderr, "\tyoffset: %d\n", vinfo->yoffset);
836 fprintf(stderr, "\tbits_per_pixel: %d\n", vinfo->bits_per_pixel);
837 fprintf(stderr, "\tgrayscale: %d\n", vinfo->grayscale);
838 fprintf(stderr, "\tnonstd: %d\n", vinfo->nonstd);
839 fprintf(stderr, "\tactivate: %d\n", vinfo->activate);
840 fprintf(stderr, "\theight: %d\n", vinfo->height);
841 fprintf(stderr, "\twidth: %d\n", vinfo->width);
842 fprintf(stderr, "\taccel_flags: %d\n", vinfo->accel_flags);
843 fprintf(stderr, "\tpixclock: %d\n", vinfo->pixclock);
844 fprintf(stderr, "\tleft_margin: %d\n", vinfo->left_margin);
845 fprintf(stderr, "\tright_margin: %d\n", vinfo->right_margin);
846 fprintf(stderr, "\tupper_margin: %d\n", vinfo->upper_margin);
847 fprintf(stderr, "\tlower_margin: %d\n", vinfo->lower_margin);
848 fprintf(stderr, "\thsync_len: %d\n", vinfo->hsync_len);
849 fprintf(stderr, "\tvsync_len: %d\n", vinfo->vsync_len);
850 fprintf(stderr, "\tsync: %d\n", vinfo->sync);
851 fprintf(stderr, "\tvmode: %d\n", vinfo->vmode);
852 fprintf(stderr, "\tred: %d/%d\n", vinfo->red.length, vinfo->red.offset);
853 fprintf(stderr, "\tgreen: %d/%d\n", vinfo->green.length, vinfo->green.offset);
854 fprintf(stderr, "\tblue: %d/%d\n", vinfo->blue.length, vinfo->blue.offset);
855 fprintf(stderr, "\talpha: %d/%d\n", vinfo->transp.length, vinfo->transp.offset);
856}
857static void print_finfo(struct fb_fix_screeninfo *finfo)
858{
859 fprintf(stderr, "Printing finfo:\n");
860 fprintf(stderr, "\tsmem_start = %p\n", (char *)finfo->smem_start);
861 fprintf(stderr, "\tsmem_len = %d\n", finfo->smem_len);
862 fprintf(stderr, "\ttype = %d\n", finfo->type);
863 fprintf(stderr, "\ttype_aux = %d\n", finfo->type_aux);
864 fprintf(stderr, "\tvisual = %d\n", finfo->visual);
865 fprintf(stderr, "\txpanstep = %d\n", finfo->xpanstep);
866 fprintf(stderr, "\typanstep = %d\n", finfo->ypanstep);
867 fprintf(stderr, "\tywrapstep = %d\n", finfo->ywrapstep);
868 fprintf(stderr, "\tline_length = %d\n", finfo->line_length);
869 fprintf(stderr, "\tmmio_start = %p\n", (char *)finfo->mmio_start);
870 fprintf(stderr, "\tmmio_len = %d\n", finfo->mmio_len);
871 fprintf(stderr, "\taccel = %d\n", finfo->accel);
872}
873#endif
874
875static int choose_fbmodes_mode(struct fb_var_screeninfo *vinfo)
876{
877 int matched;
878 FILE *modesdb;
879 struct fb_var_screeninfo cinfo;
880
881 matched = 0;
882 modesdb = fopen(FB_MODES_DB, "r");
883 if ( modesdb ) {
884 /* Parse the mode definition file */
885 while ( read_fbmodes_mode(modesdb, &cinfo) ) {
886 if ( (vinfo->xres == cinfo.xres && vinfo->yres == cinfo.yres) &&
887 (!matched || (vinfo->bits_per_pixel == cinfo.bits_per_pixel)) ) {
888 vinfo->pixclock = cinfo.pixclock;
889 vinfo->left_margin = cinfo.left_margin;
890 vinfo->right_margin = cinfo.right_margin;
891 vinfo->upper_margin = cinfo.upper_margin;
892 vinfo->lower_margin = cinfo.lower_margin;
893 vinfo->hsync_len = cinfo.hsync_len;
894 vinfo->vsync_len = cinfo.vsync_len;
895 if ( matched ) {
896 break;
897 }
898 matched = 1;
899 }
900 }
901 fclose(modesdb);
902 }
903 return(matched);
904}
905
906static int choose_vesa_mode(struct fb_var_screeninfo *vinfo)
907{
908 int matched;
909 int i;
910
911 /* Check for VESA timings */
912 matched = 0;
913 for ( i=0; i<(sizeof(vesa_timings)/sizeof(vesa_timings[0])); ++i ) {
914 if ( (vinfo->xres == vesa_timings[i].xres) &&
915 (vinfo->yres == vesa_timings[i].yres) ) {
916#ifdef FBCON_DEBUG
917 fprintf(stderr, "Using VESA timings for %dx%d\n",
918 vinfo->xres, vinfo->yres);
919#endif
920 if ( vesa_timings[i].pixclock ) {
921 vinfo->pixclock = vesa_timings[i].pixclock;
922 }
923 vinfo->left_margin = vesa_timings[i].left;
924 vinfo->right_margin = vesa_timings[i].right;
925 vinfo->upper_margin = vesa_timings[i].upper;
926 vinfo->lower_margin = vesa_timings[i].lower;
927 vinfo->hsync_len = vesa_timings[i].hslen;
928 vinfo->vsync_len = vesa_timings[i].vslen;
929 vinfo->sync = vesa_timings[i].sync;
930 vinfo->vmode = vesa_timings[i].vmode;
931 matched = 1;
932 break;
933 }
934 }
935 return(matched);
936}
937
938#ifdef VGA16_FBCON_SUPPORT
939static SDL_Surface *FB_SetVGA16Mode(_THIS, SDL_Surface *current,
940 int width, int height, int bpp, Uint32 flags)
941{
942 struct fb_fix_screeninfo finfo;
943 struct fb_var_screeninfo vinfo;
944
945 /* Set the terminal into graphics mode */
946 if ( FB_EnterGraphicsMode(this) < 0 ) {
947 return(NULL);
948 }
949
950 /* Restore the original palette */
951 FB_RestorePalette(this);
952
953 /* Set the video mode and get the final screen format */
954 if ( ioctl(console_fd, FBIOGET_VSCREENINFO, &vinfo) < 0 ) {
955 SDL_SetError("Couldn't get console screen info");
956 return(NULL);
957 }
958 cache_vinfo = vinfo;
959#ifdef FBCON_DEBUG
960 fprintf(stderr, "Printing actual vinfo:\n");
961 print_vinfo(&vinfo);
962#endif
963 if ( ! SDL_ReallocFormat(current, bpp, 0, 0, 0, 0) ) {
964 return(NULL);
965 }
966 current->format->palette->ncolors = 16;
967
968 /* Get the fixed information about the console hardware.
969 This is necessary since finfo.line_length changes.
970 */
971 if ( ioctl(console_fd, FBIOGET_FSCREENINFO, &finfo) < 0 ) {
972 SDL_SetError("Couldn't get console hardware info");
973 return(NULL);
974 }
975#ifdef FBCON_DEBUG
976 fprintf(stderr, "Printing actual finfo:\n");
977 print_finfo(&finfo);
978#endif
979
980 /* Save hardware palette, if needed */
981 FB_SavePalette(this, &finfo, &vinfo);
982
983 /* Set up the new mode framebuffer */
984 current->flags = SDL_FULLSCREEN;
985 current->w = vinfo.xres;
986 current->h = vinfo.yres;
987 current->pitch = current->w;
988 current->pixels = SDL_malloc(current->h*current->pitch);
989
990 /* Set the update rectangle function */
991 this->UpdateRects = FB_VGA16Update;
992
993 /* We're done */
994 return(current);
995}
996#endif /* VGA16_FBCON_SUPPORT */
997
998static SDL_Surface *FB_SetVideoMode(_THIS, SDL_Surface *current,
999 int width, int height, int bpp, Uint32 flags)
1000{
1001 struct fb_fix_screeninfo finfo;
1002 struct fb_var_screeninfo vinfo;
1003 int i;
1004 Uint32 Rmask;
1005 Uint32 Gmask;
1006 Uint32 Bmask;
1007 char *surfaces_mem;
1008 int surfaces_len;
1009
1010 /* Set the terminal into graphics mode */
1011 if ( FB_EnterGraphicsMode(this) < 0 ) {
1012 return(NULL);
1013 }
1014
1015 /* Restore the original palette */
1016 FB_RestorePalette(this);
1017
1018 /* Set the video mode and get the final screen format */
1019 if ( ioctl(console_fd, FBIOGET_VSCREENINFO, &vinfo) < 0 ) {
1020 SDL_SetError("Couldn't get console screen info");
1021 return(NULL);
1022 }
1023#ifdef FBCON_DEBUG
1024 fprintf(stderr, "Printing original vinfo:\n");
1025 print_vinfo(&vinfo);
1026#endif
1027 /* Do not use double buffering with shadow buffer */
1028 if (shadow_fb) {
1029 flags &= ~SDL_DOUBLEBUF;
1030 }
1031
1032 if ( (vinfo.xres != width) || (vinfo.yres != height) ||
1033 (vinfo.bits_per_pixel != bpp) || (flags & SDL_DOUBLEBUF) ) {
1034 vinfo.activate = FB_ACTIVATE_NOW;
1035 vinfo.accel_flags = 0;
1036 vinfo.bits_per_pixel = bpp;
1037 vinfo.xres = width;
1038 vinfo.xres_virtual = width;
1039 vinfo.yres = height;
1040 if ( flags & SDL_DOUBLEBUF ) {
1041 vinfo.yres_virtual = height*2;
1042 } else {
1043 vinfo.yres_virtual = height;
1044 }
1045 vinfo.xoffset = 0;
1046 vinfo.yoffset = 0;
1047 vinfo.red.length = vinfo.red.offset = 0;
1048 vinfo.green.length = vinfo.green.offset = 0;
1049 vinfo.blue.length = vinfo.blue.offset = 0;
1050 vinfo.transp.length = vinfo.transp.offset = 0;
1051 if ( ! choose_fbmodes_mode(&vinfo) ) {
1052 choose_vesa_mode(&vinfo);
1053 }
1054#ifdef FBCON_DEBUG
1055 fprintf(stderr, "Printing wanted vinfo:\n");
1056 print_vinfo(&vinfo);
1057#endif
1058 if ( !shadow_fb &&
1059 ioctl(console_fd, FBIOPUT_VSCREENINFO, &vinfo) < 0 ) {
1060 vinfo.yres_virtual = height;
1061 if ( ioctl(console_fd, FBIOPUT_VSCREENINFO, &vinfo) < 0 ) {
1062 SDL_SetError("Couldn't set console screen info");
1063 return(NULL);
1064 }
1065 }
1066 } else {
1067 int maxheight;
1068
1069 /* Figure out how much video memory is available */
1070 if ( flags & SDL_DOUBLEBUF ) {
1071 maxheight = height*2;
1072 } else {
1073 maxheight = height;
1074 }
1075 if ( vinfo.yres_virtual > maxheight ) {
1076 vinfo.yres_virtual = maxheight;
1077 }
1078 }
1079 cache_vinfo = vinfo;
1080#ifdef FBCON_DEBUG
1081 fprintf(stderr, "Printing actual vinfo:\n");
1082 print_vinfo(&vinfo);
1083#endif
1084 Rmask = 0;
1085 for ( i=0; i<vinfo.red.length; ++i ) {
1086 Rmask <<= 1;
1087 Rmask |= (0x00000001<<vinfo.red.offset);
1088 }
1089 Gmask = 0;
1090 for ( i=0; i<vinfo.green.length; ++i ) {
1091 Gmask <<= 1;
1092 Gmask |= (0x00000001<<vinfo.green.offset);
1093 }
1094 Bmask = 0;
1095 for ( i=0; i<vinfo.blue.length; ++i ) {
1096 Bmask <<= 1;
1097 Bmask |= (0x00000001<<vinfo.blue.offset);
1098 }
1099 if ( ! SDL_ReallocFormat(current, vinfo.bits_per_pixel,
1100 Rmask, Gmask, Bmask, 0) ) {
1101 return(NULL);
1102 }
1103
1104 /* Get the fixed information about the console hardware.
1105 This is necessary since finfo.line_length changes.
1106 */
1107 if ( ioctl(console_fd, FBIOGET_FSCREENINFO, &finfo) < 0 ) {
1108 SDL_SetError("Couldn't get console hardware info");
1109 return(NULL);
1110 }
1111
1112 /* Save hardware palette, if needed */
1113 FB_SavePalette(this, &finfo, &vinfo);
1114
1115 if (shadow_fb) {
1116 if (vinfo.bits_per_pixel == 16) {
1117 blitFunc = (rotate == FBCON_ROTATE_NONE ||
1118 rotate == FBCON_ROTATE_UD) ?
1119 FB_blit16 : FB_blit16blocked;
1120 } else {
1121#ifdef FBCON_DEBUG
1122 fprintf(stderr, "Init vinfo:\n");
1123 print_vinfo(&vinfo);
1124#endif
1125 SDL_SetError("Using software buffer, but no blitter "
1126 "function is available for %d bpp.",
1127 vinfo.bits_per_pixel);
1128 return(NULL);
1129 }
1130 }
1131
1132 /* Set up the new mode framebuffer */
1133 current->flags &= SDL_FULLSCREEN;
1134 if (shadow_fb) {
1135 current->flags |= SDL_SWSURFACE;
1136 } else {
1137 current->flags |= SDL_HWSURFACE;
1138 }
1139 current->w = vinfo.xres;
1140 current->h = vinfo.yres;
1141 if (shadow_fb) {
1142 current->pitch = current->w * ((vinfo.bits_per_pixel + 7) / 8);
1143 current->pixels = shadow_mem;
1144 physlinebytes = finfo.line_length;
1145 } else {
1146 current->pitch = finfo.line_length;
1147 current->pixels = mapped_mem+mapped_offset;
1148 }
1149
1150 /* Set up the information for hardware surfaces */
1151 surfaces_mem = (char *)current->pixels +
1152 vinfo.yres_virtual*current->pitch;
1153 surfaces_len = (shadow_fb) ?
1154 0 : (mapped_memlen-(surfaces_mem-mapped_mem));
1155
1156 FB_FreeHWSurfaces(this);
1157 FB_InitHWSurfaces(this, current, surfaces_mem, surfaces_len);
1158
1159 /* Let the application know we have a hardware palette */
1160 switch (finfo.visual) {
1161 case FB_VISUAL_PSEUDOCOLOR:
1162 current->flags |= SDL_HWPALETTE;
1163 break;
1164 default:
1165 break;
1166 }
1167
1168 /* Update for double-buffering, if we can */
1169 if ( flags & SDL_DOUBLEBUF ) {
1170 if ( vinfo.yres_virtual == (height*2) ) {
1171 current->flags |= SDL_DOUBLEBUF;
1172 flip_page = 0;
1173 flip_address[0] = (char *)current->pixels;
1174 flip_address[1] = (char *)current->pixels+
1175 current->h*current->pitch;
1176 this->screen = current;
1177 FB_FlipHWSurface(this, current);
1178 this->screen = NULL;
1179 }
1180 }
1181
1182 /* Set the update rectangle function */
1183 this->UpdateRects = FB_DirectUpdate;
1184
1185 /* We're done */
1186 return(current);
1187}
1188
1189#ifdef FBCON_DEBUG
1190void FB_DumpHWSurfaces(_THIS)
1191{
1192 vidmem_bucket *bucket;
1193
1194 printf("Memory left: %d (%d total)\n", surfaces_memleft, surfaces_memtotal);
1195 printf("\n");
1196 printf(" Base Size\n");
1197 for ( bucket=&surfaces; bucket; bucket=bucket->next ) {
1198 printf("Bucket: %p, %d (%s)\n", bucket->base, bucket->size, bucket->used ? "used" : "free");
1199 if ( bucket->prev ) {
1200 if ( bucket->base != bucket->prev->base+bucket->prev->size ) {
1201 printf("Warning, corrupt bucket list! (prev)\n");
1202 }
1203 } else {
1204 if ( bucket != &surfaces ) {
1205 printf("Warning, corrupt bucket list! (!prev)\n");
1206 }
1207 }
1208 if ( bucket->next ) {
1209 if ( bucket->next->base != bucket->base+bucket->size ) {
1210 printf("Warning, corrupt bucket list! (next)\n");
1211 }
1212 }
1213 }
1214 printf("\n");
1215}
1216#endif
1217
1218static int FB_InitHWSurfaces(_THIS, SDL_Surface *screen, char *base, int size)
1219{
1220 vidmem_bucket *bucket;
1221
1222 surfaces_memtotal = size;
1223 surfaces_memleft = size;
1224
1225 if ( surfaces_memleft > 0 ) {
1226 bucket = (vidmem_bucket *)SDL_malloc(sizeof(*bucket));
1227 if ( bucket == NULL ) {
1228 SDL_OutOfMemory();
1229 return(-1);
1230 }
1231 bucket->prev = &surfaces;
1232 bucket->used = 0;
1233 bucket->dirty = 0;
1234 bucket->base = base;
1235 bucket->size = size;
1236 bucket->next = NULL;
1237 } else {
1238 bucket = NULL;
1239 }
1240
1241 surfaces.prev = NULL;
1242 surfaces.used = 1;
1243 surfaces.dirty = 0;
1244 surfaces.base = screen->pixels;
1245 surfaces.size = (unsigned int)((long)base - (long)surfaces.base);
1246 surfaces.next = bucket;
1247 screen->hwdata = (struct private_hwdata *)&surfaces;
1248 return(0);
1249}
1250static void FB_FreeHWSurfaces(_THIS)
1251{
1252 vidmem_bucket *bucket, *freeable;
1253
1254 bucket = surfaces.next;
1255 while ( bucket ) {
1256 freeable = bucket;
1257 bucket = bucket->next;
1258 SDL_free(freeable);
1259 }
1260 surfaces.next = NULL;
1261}
1262
1263static int FB_AllocHWSurface(_THIS, SDL_Surface *surface)
1264{
1265 vidmem_bucket *bucket;
1266 int size;
1267 int extra;
1268
1269/* Temporarily, we only allow surfaces the same width as display.
1270 Some blitters require the pitch between two hardware surfaces
1271 to be the same. Others have interesting alignment restrictions.
1272 Until someone who knows these details looks at the code...
1273*/
1274if ( surface->pitch > SDL_VideoSurface->pitch ) {
1275 SDL_SetError("Surface requested wider than screen");
1276 return(-1);
1277}
1278surface->pitch = SDL_VideoSurface->pitch;
1279 size = surface->h * surface->pitch;
1280#ifdef FBCON_DEBUG
1281 fprintf(stderr, "Allocating bucket of %d bytes\n", size);
1282#endif
1283
1284 /* Quick check for available mem */
1285 if ( size > surfaces_memleft ) {
1286 SDL_SetError("Not enough video memory");
1287 return(-1);
1288 }
1289
1290 /* Search for an empty bucket big enough */
1291 for ( bucket=&surfaces; bucket; bucket=bucket->next ) {
1292 if ( ! bucket->used && (size <= bucket->size) ) {
1293 break;
1294 }
1295 }
1296 if ( bucket == NULL ) {
1297 SDL_SetError("Video memory too fragmented");
1298 return(-1);
1299 }
1300
1301 /* Create a new bucket for left-over memory */
1302 extra = (bucket->size - size);
1303 if ( extra ) {
1304 vidmem_bucket *newbucket;
1305
1306#ifdef FBCON_DEBUG
1307 fprintf(stderr, "Adding new free bucket of %d bytes\n", extra);
1308#endif
1309 newbucket = (vidmem_bucket *)SDL_malloc(sizeof(*newbucket));
1310 if ( newbucket == NULL ) {
1311 SDL_OutOfMemory();
1312 return(-1);
1313 }
1314 newbucket->prev = bucket;
1315 newbucket->used = 0;
1316 newbucket->base = bucket->base+size;
1317 newbucket->size = extra;
1318 newbucket->next = bucket->next;
1319 if ( bucket->next ) {
1320 bucket->next->prev = newbucket;
1321 }
1322 bucket->next = newbucket;
1323 }
1324
1325 /* Set the current bucket values and return it! */
1326 bucket->used = 1;
1327 bucket->size = size;
1328 bucket->dirty = 0;
1329#ifdef FBCON_DEBUG
1330 fprintf(stderr, "Allocated %d bytes at %p\n", bucket->size, bucket->base);
1331#endif
1332 surfaces_memleft -= size;
1333 surface->flags |= SDL_HWSURFACE;
1334 surface->pixels = bucket->base;
1335 surface->hwdata = (struct private_hwdata *)bucket;
1336 return(0);
1337}
1338static void FB_FreeHWSurface(_THIS, SDL_Surface *surface)
1339{
1340 vidmem_bucket *bucket, *freeable;
1341
1342 /* Look for the bucket in the current list */
1343 for ( bucket=&surfaces; bucket; bucket=bucket->next ) {
1344 if ( bucket == (vidmem_bucket *)surface->hwdata ) {
1345 break;
1346 }
1347 }
1348 if ( bucket && bucket->used ) {
1349 /* Add the memory back to the total */
1350#ifdef DGA_DEBUG
1351 printf("Freeing bucket of %d bytes\n", bucket->size);
1352#endif
1353 surfaces_memleft += bucket->size;
1354
1355 /* Can we merge the space with surrounding buckets? */
1356 bucket->used = 0;
1357 if ( bucket->next && ! bucket->next->used ) {
1358#ifdef DGA_DEBUG
1359 printf("Merging with next bucket, for %d total bytes\n", bucket->size+bucket->next->size);
1360#endif
1361 freeable = bucket->next;
1362 bucket->size += bucket->next->size;
1363 bucket->next = bucket->next->next;
1364 if ( bucket->next ) {
1365 bucket->next->prev = bucket;
1366 }
1367 SDL_free(freeable);
1368 }
1369 if ( bucket->prev && ! bucket->prev->used ) {
1370#ifdef DGA_DEBUG
1371 printf("Merging with previous bucket, for %d total bytes\n", bucket->prev->size+bucket->size);
1372#endif
1373 freeable = bucket;
1374 bucket->prev->size += bucket->size;
1375 bucket->prev->next = bucket->next;
1376 if ( bucket->next ) {
1377 bucket->next->prev = bucket->prev;
1378 }
1379 SDL_free(freeable);
1380 }
1381 }
1382 surface->pixels = NULL;
1383 surface->hwdata = NULL;
1384}
1385
1386static int FB_LockHWSurface(_THIS, SDL_Surface *surface)
1387{
1388 if ( switched_away ) {
1389 return -2; /* no hardware access */
1390 }
1391 if ( surface == this->screen ) {
1392 SDL_mutexP(hw_lock);
1393 if ( FB_IsSurfaceBusy(surface) ) {
1394 FB_WaitBusySurfaces(this);
1395 }
1396 } else {
1397 if ( FB_IsSurfaceBusy(surface) ) {
1398 FB_WaitBusySurfaces(this);
1399 }
1400 }
1401 return(0);
1402}
1403static void FB_UnlockHWSurface(_THIS, SDL_Surface *surface)
1404{
1405 if ( surface == this->screen ) {
1406 SDL_mutexV(hw_lock);
1407 }
1408}
1409
1410static void FB_WaitVBL(_THIS)
1411{
1412#ifdef FBIOWAITRETRACE /* Heheh, this didn't make it into the main kernel */
1413 ioctl(console_fd, FBIOWAITRETRACE, 0);
1414#endif
1415 return;
1416}
1417
1418static void FB_WaitIdle(_THIS)
1419{
1420 return;
1421}
1422
1423static int FB_FlipHWSurface(_THIS, SDL_Surface *surface)
1424{
1425 if ( switched_away ) {
1426 return -2; /* no hardware access */
1427 }
1428
1429 /* Wait for vertical retrace and then flip display */
1430 cache_vinfo.yoffset = flip_page*surface->h;
1431 if ( FB_IsSurfaceBusy(this->screen) ) {
1432 FB_WaitBusySurfaces(this);
1433 }
1434 wait_vbl(this);
1435 if ( ioctl(console_fd, FBIOPAN_DISPLAY, &cache_vinfo) < 0 ) {
1436 SDL_SetError("ioctl(FBIOPAN_DISPLAY) failed");
1437 return(-1);
1438 }
1439 flip_page = !flip_page;
1440
1441 surface->pixels = flip_address[flip_page];
1442 return(0);
1443}
1444
1445static void FB_blit16(Uint8 *byte_src_pos, int src_right_delta, int src_down_delta,
1446 Uint8 *byte_dst_pos, int dst_linebytes, int width, int height)
1447{
1448 int w;
1449 Uint16 *src_pos = (Uint16 *)byte_src_pos;
1450 Uint16 *dst_pos = (Uint16 *)byte_dst_pos;
1451
1452 while (height) {
1453 Uint16 *src = src_pos;
1454 Uint16 *dst = dst_pos;
1455 for (w = width; w != 0; w--) {
1456 *dst = *src;
1457 src += src_right_delta;
1458 dst++;
1459 }
1460 dst_pos = (Uint16 *)((Uint8 *)dst_pos + dst_linebytes);
1461 src_pos += src_down_delta;
1462 height--;
1463 }
1464}
1465
1466#define BLOCKSIZE_W 32
1467#define BLOCKSIZE_H 32
1468
1469static void FB_blit16blocked(Uint8 *byte_src_pos, int src_right_delta, int src_down_delta,
1470 Uint8 *byte_dst_pos, int dst_linebytes, int width, int height)
1471{
1472 int w;
1473 Uint16 *src_pos = (Uint16 *)byte_src_pos;
1474 Uint16 *dst_pos = (Uint16 *)byte_dst_pos;
1475
1476 while (height > 0) {
1477 Uint16 *src = src_pos;
1478 Uint16 *dst = dst_pos;
1479 for (w = width; w > 0; w -= BLOCKSIZE_W) {
1480 FB_blit16((Uint8 *)src,
1481 src_right_delta,
1482 src_down_delta,
1483 (Uint8 *)dst,
1484 dst_linebytes,
1485 min(w, BLOCKSIZE_W),
1486 min(height, BLOCKSIZE_H));
1487 src += src_right_delta * BLOCKSIZE_W;
1488 dst += BLOCKSIZE_W;
1489 }
1490 dst_pos = (Uint16 *)((Uint8 *)dst_pos + dst_linebytes * BLOCKSIZE_H);
1491 src_pos += src_down_delta * BLOCKSIZE_H;
1492 height -= BLOCKSIZE_H;
1493 }
1494}
1495
1496static void FB_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
1497{
1498 int width = cache_vinfo.xres;
1499 int height = cache_vinfo.yres;
1500 int bytes_per_pixel = (cache_vinfo.bits_per_pixel + 7) / 8;
1501 int i;
1502
1503 if (!shadow_fb) {
1504 /* The application is already updating the visible video memory */
1505 return;
1506 }
1507
1508 if (cache_vinfo.bits_per_pixel != 16) {
1509 SDL_SetError("Shadow copy only implemented for 16 bpp");
1510 return;
1511 }
1512
1513 for (i = 0; i < numrects; i++) {
1514 int x1, y1, x2, y2;
1515 int scr_x1, scr_y1, scr_x2, scr_y2;
1516 int sha_x1, sha_y1;
1517 int shadow_right_delta; /* Address change when moving right in dest */
1518 int shadow_down_delta; /* Address change when moving down in dest */
1519 char *src_start;
1520 char *dst_start;
1521
1522 x1 = rects[i].x;
1523 y1 = rects[i].y;
1524 x2 = x1 + rects[i].w;
1525 y2 = y1 + rects[i].h;
1526
1527 if (x1 < 0) {
1528 x1 = 0;
1529 } else if (x1 > width) {
1530 x1 = width;
1531 }
1532 if (x2 < 0) {
1533 x2 = 0;
1534 } else if (x2 > width) {
1535 x2 = width;
1536 }
1537 if (y1 < 0) {
1538 y1 = 0;
1539 } else if (y1 > height) {
1540 y1 = height;
1541 }
1542 if (y2 < 0) {
1543 y2 = 0;
1544 } else if (y2 > height) {
1545 y2 = height;
1546 }
1547 if (x2 <= x1 || y2 <= y1) {
1548 continue;
1549 }
1550
1551 switch (rotate) {
1552 case FBCON_ROTATE_NONE:
1553 sha_x1 = scr_x1 = x1;
1554 sha_y1 = scr_y1 = y1;
1555 scr_x2 = x2;
1556 scr_y2 = y2;
1557 shadow_right_delta = 1;
1558 shadow_down_delta = width;
1559 break;
1560 case FBCON_ROTATE_CCW:
1561 scr_x1 = y1;
1562 scr_y1 = width - x2;
1563 scr_x2 = y2;
1564 scr_y2 = width - x1;
1565 sha_x1 = x2 - 1;
1566 sha_y1 = y1;
1567 shadow_right_delta = width;
1568 shadow_down_delta = -1;
1569 break;
1570 case FBCON_ROTATE_UD:
1571 scr_x1 = width - x2;
1572 scr_y1 = height - y2;
1573 scr_x2 = width - x1;
1574 scr_y2 = height - y1;
1575 sha_x1 = x2 - 1;
1576 sha_y1 = y2 - 1;
1577 shadow_right_delta = -1;
1578 shadow_down_delta = -width;
1579 break;
1580 case FBCON_ROTATE_CW:
1581 scr_x1 = height - y2;
1582 scr_y1 = x1;
1583 scr_x2 = height - y1;
1584 scr_y2 = x2;
1585 sha_x1 = x1;
1586 sha_y1 = y2 - 1;
1587 shadow_right_delta = -width;
1588 shadow_down_delta = 1;
1589 break;
1590 default:
1591 SDL_SetError("Unknown rotation");
1592 return;
1593 }
1594
1595 src_start = shadow_mem +
1596 (sha_y1 * width + sha_x1) * bytes_per_pixel;
1597 dst_start = mapped_mem + mapped_offset + scr_y1 * physlinebytes +
1598 scr_x1 * bytes_per_pixel;
1599
1600 blitFunc((Uint8 *) src_start,
1601 shadow_right_delta,
1602 shadow_down_delta,
1603 (Uint8 *) dst_start,
1604 physlinebytes,
1605 scr_x2 - scr_x1,
1606 scr_y2 - scr_y1);
1607 }
1608}
1609
1610#ifdef VGA16_FBCON_SUPPORT
1611/* Code adapted with thanks from the XFree86 VGA16 driver! :) */
1612#define writeGr(index, value) \
1613outb(index, 0x3CE); \
1614outb(value, 0x3CF);
1615#define writeSeq(index, value) \
1616outb(index, 0x3C4); \
1617outb(value, 0x3C5);
1618
1619static void FB_VGA16Update(_THIS, int numrects, SDL_Rect *rects)
1620{
1621 SDL_Surface *screen;
1622 int width, height, FBPitch, left, i, j, SRCPitch, phase;
1623 register Uint32 m;
1624 Uint8 s1, s2, s3, s4;
1625 Uint32 *src, *srcPtr;
1626 Uint8 *dst, *dstPtr;
1627
1628 if ( switched_away ) {
1629 return; /* no hardware access */
1630 }
1631
1632 screen = this->screen;
1633 FBPitch = screen->w >> 3;
1634 SRCPitch = screen->pitch >> 2;
1635
1636 writeGr(0x03, 0x00);
1637 writeGr(0x05, 0x00);
1638 writeGr(0x01, 0x00);
1639 writeGr(0x08, 0xFF);
1640
1641 while(numrects--) {
1642 left = rects->x & ~7;
1643 width = (rects->w + 7) >> 3;
1644 height = rects->h;
1645 src = (Uint32*)screen->pixels + (rects->y * SRCPitch) + (left >> 2);
1646 dst = (Uint8*)mapped_mem + (rects->y * FBPitch) + (left >> 3);
1647
1648 if((phase = (long)dst & 3L)) {
1649 phase = 4 - phase;
1650 if(phase > width) phase = width;
1651 width -= phase;
1652 }
1653
1654 while(height--) {
1655 writeSeq(0x02, 1 << 0);
1656 dstPtr = dst;
1657 srcPtr = src;
1658 i = width;
1659 j = phase;
1660 while(j--) {
1661 m = (srcPtr[1] & 0x01010101) | ((srcPtr[0] & 0x01010101) << 4);
1662 *dstPtr++ = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3);
1663 srcPtr += 2;
1664 }
1665 while(i >= 4) {
1666 m = (srcPtr[1] & 0x01010101) | ((srcPtr[0] & 0x01010101) << 4);
1667 s1 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3);
1668 m = (srcPtr[3] & 0x01010101) | ((srcPtr[2] & 0x01010101) << 4);
1669 s2 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3);
1670 m = (srcPtr[5] & 0x01010101) | ((srcPtr[4] & 0x01010101) << 4);
1671 s3 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3);
1672 m = (srcPtr[7] & 0x01010101) | ((srcPtr[6] & 0x01010101) << 4);
1673 s4 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3);
1674 *((Uint32*)dstPtr) = s1 | (s2 << 8) | (s3 << 16) | (s4 << 24);
1675 srcPtr += 8;
1676 dstPtr += 4;
1677 i -= 4;
1678 }
1679 while(i--) {
1680 m = (srcPtr[1] & 0x01010101) | ((srcPtr[0] & 0x01010101) << 4);
1681 *dstPtr++ = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3);
1682 srcPtr += 2;
1683 }
1684
1685 writeSeq(0x02, 1 << 1);
1686 dstPtr = dst;
1687 srcPtr = src;
1688 i = width;
1689 j = phase;
1690 while(j--) {
1691 m = (srcPtr[1] & 0x02020202) | ((srcPtr[0] & 0x02020202) << 4);
1692 *dstPtr++ = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2);
1693 srcPtr += 2;
1694 }
1695 while(i >= 4) {
1696 m = (srcPtr[1] & 0x02020202) | ((srcPtr[0] & 0x02020202) << 4);
1697 s1 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2);
1698 m = (srcPtr[3] & 0x02020202) | ((srcPtr[2] & 0x02020202) << 4);
1699 s2 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2);
1700 m = (srcPtr[5] & 0x02020202) | ((srcPtr[4] & 0x02020202) << 4);
1701 s3 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2);
1702 m = (srcPtr[7] & 0x02020202) | ((srcPtr[6] & 0x02020202) << 4);
1703 s4 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2);
1704 *((Uint32*)dstPtr) = s1 | (s2 << 8) | (s3 << 16) | (s4 << 24);
1705 srcPtr += 8;
1706 dstPtr += 4;
1707 i -= 4;
1708 }
1709 while(i--) {
1710 m = (srcPtr[1] & 0x02020202) | ((srcPtr[0] & 0x02020202) << 4);
1711 *dstPtr++ = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2);
1712 srcPtr += 2;
1713 }
1714
1715 writeSeq(0x02, 1 << 2);
1716 dstPtr = dst;
1717 srcPtr = src;
1718 i = width;
1719 j = phase;
1720 while(j--) {
1721 m = (srcPtr[1] & 0x04040404) | ((srcPtr[0] & 0x04040404) << 4);
1722 *dstPtr++ = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1);
1723 srcPtr += 2;
1724 }
1725 while(i >= 4) {
1726 m = (srcPtr[1] & 0x04040404) | ((srcPtr[0] & 0x04040404) << 4);
1727 s1 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1);
1728 m = (srcPtr[3] & 0x04040404) | ((srcPtr[2] & 0x04040404) << 4);
1729 s2 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1);
1730 m = (srcPtr[5] & 0x04040404) | ((srcPtr[4] & 0x04040404) << 4);
1731 s3 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1);
1732 m = (srcPtr[7] & 0x04040404) | ((srcPtr[6] & 0x04040404) << 4);
1733 s4 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1);
1734 *((Uint32*)dstPtr) = s1 | (s2 << 8) | (s3 << 16) | (s4 << 24);
1735 srcPtr += 8;
1736 dstPtr += 4;
1737 i -= 4;
1738 }
1739 while(i--) {
1740 m = (srcPtr[1] & 0x04040404) | ((srcPtr[0] & 0x04040404) << 4);
1741 *dstPtr++ = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1);
1742 srcPtr += 2;
1743 }
1744
1745 writeSeq(0x02, 1 << 3);
1746 dstPtr = dst;
1747 srcPtr = src;
1748 i = width;
1749 j = phase;
1750 while(j--) {
1751 m = (srcPtr[1] & 0x08080808) | ((srcPtr[0] & 0x08080808) << 4);
1752 *dstPtr++ = (m >> 27) | (m >> 18) | (m >> 9) | m;
1753 srcPtr += 2;
1754 }
1755 while(i >= 4) {
1756 m = (srcPtr[1] & 0x08080808) | ((srcPtr[0] & 0x08080808) << 4);
1757 s1 = (m >> 27) | (m >> 18) | (m >> 9) | m;
1758 m = (srcPtr[3] & 0x08080808) | ((srcPtr[2] & 0x08080808) << 4);
1759 s2 = (m >> 27) | (m >> 18) | (m >> 9) | m;
1760 m = (srcPtr[5] & 0x08080808) | ((srcPtr[4] & 0x08080808) << 4);
1761 s3 = (m >> 27) | (m >> 18) | (m >> 9) | m;
1762 m = (srcPtr[7] & 0x08080808) | ((srcPtr[6] & 0x08080808) << 4);
1763 s4 = (m >> 27) | (m >> 18) | (m >> 9) | m;
1764 *((Uint32*)dstPtr) = s1 | (s2 << 8) | (s3 << 16) | (s4 << 24);
1765 srcPtr += 8;
1766 dstPtr += 4;
1767 i -= 4;
1768 }
1769 while(i--) {
1770 m = (srcPtr[1] & 0x08080808) | ((srcPtr[0] & 0x08080808) << 4);
1771 *dstPtr++ = (m >> 27) | (m >> 18) | (m >> 9) | m;
1772 srcPtr += 2;
1773 }
1774
1775 dst += FBPitch;
1776 src += SRCPitch;
1777 }
1778 rects++;
1779 }
1780}
1781#endif /* VGA16_FBCON_SUPPORT */
1782
1783void FB_SavePaletteTo(_THIS, int palette_len, __u16 *area)
1784{
1785 struct fb_cmap cmap;
1786
1787 cmap.start = 0;
1788 cmap.len = palette_len;
1789 cmap.red = &area[0*palette_len];
1790 cmap.green = &area[1*palette_len];
1791 cmap.blue = &area[2*palette_len];
1792 cmap.transp = NULL;
1793 ioctl(console_fd, FBIOGETCMAP, &cmap);
1794}
1795
1796void FB_RestorePaletteFrom(_THIS, int palette_len, __u16 *area)
1797{
1798 struct fb_cmap cmap;
1799
1800 cmap.start = 0;
1801 cmap.len = palette_len;
1802 cmap.red = &area[0*palette_len];
1803 cmap.green = &area[1*palette_len];
1804 cmap.blue = &area[2*palette_len];
1805 cmap.transp = NULL;
1806 ioctl(console_fd, FBIOPUTCMAP, &cmap);
1807}
1808
1809static void FB_SavePalette(_THIS, struct fb_fix_screeninfo *finfo,
1810 struct fb_var_screeninfo *vinfo)
1811{
1812 int i;
1813
1814 /* Save hardware palette, if needed */
1815 if ( finfo->visual == FB_VISUAL_PSEUDOCOLOR ) {
1816 saved_cmaplen = 1<<vinfo->bits_per_pixel;
1817 saved_cmap=(__u16 *)SDL_malloc(3*saved_cmaplen*sizeof(*saved_cmap));
1818 if ( saved_cmap != NULL ) {
1819 FB_SavePaletteTo(this, saved_cmaplen, saved_cmap);
1820 }
1821 }
1822
1823 /* Added support for FB_VISUAL_DIRECTCOLOR.
1824 With this mode pixel information is passed through the palette...
1825 Neat fading and gamma correction effects can be had by simply
1826 fooling around with the palette instead of changing the pixel
1827 values themselves... Very neat!
1828
1829 Adam Meyerowitz 1/19/2000
1830 ameyerow@optonline.com
1831 */
1832 if ( finfo->visual == FB_VISUAL_DIRECTCOLOR ) {
1833 __u16 new_entries[3*256];
1834
1835 /* Save the colormap */
1836 saved_cmaplen = 256;
1837 saved_cmap=(__u16 *)SDL_malloc(3*saved_cmaplen*sizeof(*saved_cmap));
1838 if ( saved_cmap != NULL ) {
1839 FB_SavePaletteTo(this, saved_cmaplen, saved_cmap);
1840 }
1841
1842 /* Allocate new identity colormap */
1843 for ( i=0; i<256; ++i ) {
1844 new_entries[(0*256)+i] =
1845 new_entries[(1*256)+i] =
1846 new_entries[(2*256)+i] = (i<<8)|i;
1847 }
1848 FB_RestorePaletteFrom(this, 256, new_entries);
1849 }
1850}
1851
1852static void FB_RestorePalette(_THIS)
1853{
1854 /* Restore the original palette */
1855 if ( saved_cmap ) {
1856 FB_RestorePaletteFrom(this, saved_cmaplen, saved_cmap);
1857 SDL_free(saved_cmap);
1858 saved_cmap = NULL;
1859 }
1860}
1861
1862static int FB_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
1863{
1864 int i;
1865 __u16 r[256];
1866 __u16 g[256];
1867 __u16 b[256];
1868 struct fb_cmap cmap;
1869
1870 /* Set up the colormap */
1871 for (i = 0; i < ncolors; i++) {
1872 r[i] = colors[i].r << 8;
1873 g[i] = colors[i].g << 8;
1874 b[i] = colors[i].b << 8;
1875 }
1876 cmap.start = firstcolor;
1877 cmap.len = ncolors;
1878 cmap.red = r;
1879 cmap.green = g;
1880 cmap.blue = b;
1881 cmap.transp = NULL;
1882
1883 if( (ioctl(console_fd, FBIOPUTCMAP, &cmap) < 0) ||
1884 !(this->screen->flags & SDL_HWPALETTE) ) {
1885 colors = this->screen->format->palette->colors;
1886 ncolors = this->screen->format->palette->ncolors;
1887 cmap.start = 0;
1888 cmap.len = ncolors;
1889 SDL_memset(r, 0, sizeof(r));
1890 SDL_memset(g, 0, sizeof(g));
1891 SDL_memset(b, 0, sizeof(b));
1892 if ( ioctl(console_fd, FBIOGETCMAP, &cmap) == 0 ) {
1893 for ( i=ncolors-1; i>=0; --i ) {
1894 colors[i].r = (r[i]>>8);
1895 colors[i].g = (g[i]>>8);
1896 colors[i].b = (b[i]>>8);
1897 }
1898 }
1899 return(0);
1900 }
1901 return(1);
1902}
1903
1904/* Note: If we are terminated, this could be called in the middle of
1905 another SDL video routine -- notably UpdateRects.
1906*/
1907static void FB_VideoQuit(_THIS)
1908{
1909 int i, j;
1910
1911 if ( this->screen ) {
1912 /* Clear screen and tell SDL not to free the pixels */
1913
1914 const char *dontClearPixels = SDL_getenv("SDL_FBCON_DONT_CLEAR");
1915
1916 /* If the framebuffer is not to be cleared, make sure that we won't
1917 * display the previous frame when disabling double buffering. */
1918 if ( dontClearPixels && flip_page == 0 ) {
1919 SDL_memcpy(flip_address[0], flip_address[1], this->screen->pitch * this->screen->h);
1920 }
1921
1922 if ( !dontClearPixels && this->screen->pixels && FB_InGraphicsMode(this) ) {
1923#if defined(__powerpc__) || defined(__ia64__) /* SIGBUS when using SDL_memset() ?? */
1924 Uint8 *rowp = (Uint8 *)this->screen->pixels;
1925 int left = this->screen->pitch*this->screen->h;
1926 while ( left-- ) { *rowp++ = 0; }
1927#else
1928 SDL_memset(this->screen->pixels,0,this->screen->h*this->screen->pitch);
1929#endif
1930 }
1931 /* This test fails when using the VGA16 shadow memory */
1932 if ( ((char *)this->screen->pixels >= mapped_mem) &&
1933 ((char *)this->screen->pixels < (mapped_mem+mapped_memlen)) ) {
1934 this->screen->pixels = NULL;
1935 }
1936 }
1937
1938 /* Clear the lock mutex */
1939 if ( hw_lock ) {
1940 SDL_DestroyMutex(hw_lock);
1941 hw_lock = NULL;
1942 }
1943
1944 /* Clean up defined video modes */
1945 for ( i=0; i<NUM_MODELISTS; ++i ) {
1946 if ( SDL_modelist[i] != NULL ) {
1947 for ( j=0; SDL_modelist[i][j]; ++j ) {
1948 SDL_free(SDL_modelist[i][j]);
1949 }
1950 SDL_free(SDL_modelist[i]);
1951 SDL_modelist[i] = NULL;
1952 }
1953 }
1954
1955 /* Clean up the memory bucket list */
1956 FB_FreeHWSurfaces(this);
1957
1958 /* Close console and input file descriptors */
1959 if ( console_fd > 0 ) {
1960 /* Unmap the video framebuffer and I/O registers */
1961 if ( mapped_mem ) {
1962 munmap(mapped_mem, mapped_memlen);
1963 mapped_mem = NULL;
1964 }
1965 if ( mapped_io ) {
1966 munmap(mapped_io, mapped_iolen);
1967 mapped_io = NULL;
1968 }
1969
1970 /* Restore the original video mode and palette */
1971 if ( FB_InGraphicsMode(this) ) {
1972 FB_RestorePalette(this);
1973 ioctl(console_fd, FBIOPUT_VSCREENINFO, &saved_vinfo);
1974 }
1975
1976 /* We're all done with the framebuffer */
1977 close(console_fd);
1978 console_fd = -1;
1979 }
1980 FB_CloseMouse(this);
1981 FB_CloseKeyboard(this);
1982}
diff --git a/apps/plugins/sdl/src/video/fbcon/SDL_fbvideo.h b/apps/plugins/sdl/src/video/fbcon/SDL_fbvideo.h
deleted file mode 100644
index 1443d2b251..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/SDL_fbvideo.h
+++ /dev/null
@@ -1,200 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_fbvideo_h
25#define _SDL_fbvideo_h
26
27#include <sys/types.h>
28#include <termios.h>
29#include <linux/fb.h>
30
31#include "SDL_mouse.h"
32#include "SDL_mutex.h"
33#include "../SDL_sysvideo.h"
34#if SDL_INPUT_TSLIB
35#include "tslib.h"
36#endif
37
38/* Hidden "this" pointer for the video functions */
39#define _THIS SDL_VideoDevice *this
40
41typedef void FB_bitBlit(
42 Uint8 *src_pos,
43 int src_right_delta, /* pixels, not bytes */
44 int src_down_delta, /* pixels, not bytes */
45 Uint8 *dst_pos,
46 int dst_linebytes,
47 int width,
48 int height);
49
50/* This is the structure we use to keep track of video memory */
51typedef struct vidmem_bucket {
52 struct vidmem_bucket *prev;
53 int used;
54 int dirty;
55 char *base;
56 unsigned int size;
57 struct vidmem_bucket *next;
58} vidmem_bucket;
59
60/* Private display data */
61struct SDL_PrivateVideoData {
62 int console_fd;
63 struct fb_var_screeninfo cache_vinfo;
64 struct fb_var_screeninfo saved_vinfo;
65 int saved_cmaplen;
66 __u16 *saved_cmap;
67
68 int current_vt;
69 int saved_vt;
70 int keyboard_fd;
71 int saved_kbd_mode;
72 struct termios saved_kbd_termios;
73
74 int mouse_fd;
75#if SDL_INPUT_TSLIB
76 struct tsdev *ts_dev;
77#endif
78
79 char *mapped_mem;
80 char *shadow_mem;
81 int mapped_memlen;
82 int mapped_offset;
83 char *mapped_io;
84 long mapped_iolen;
85 int flip_page;
86 char *flip_address[2];
87 int rotate;
88 int shadow_fb; /* Tells whether a shadow is being used. */
89 FB_bitBlit *blitFunc;
90 int physlinebytes; /* Length of a line in bytes in physical fb */
91
92#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
93 int SDL_nummodes[NUM_MODELISTS];
94 SDL_Rect **SDL_modelist[NUM_MODELISTS];
95
96 vidmem_bucket surfaces;
97 int surfaces_memtotal;
98 int surfaces_memleft;
99
100 SDL_mutex *hw_lock;
101 int switched_away;
102 struct fb_var_screeninfo screen_vinfo;
103 Uint32 screen_arealen;
104 Uint8 *screen_contents;
105 __u16 screen_palette[3*256];
106
107 void (*wait_vbl)(_THIS);
108 void (*wait_idle)(_THIS);
109};
110/* Old variable names */
111#define console_fd (this->hidden->console_fd)
112#define current_vt (this->hidden->current_vt)
113#define saved_vt (this->hidden->saved_vt)
114#define keyboard_fd (this->hidden->keyboard_fd)
115#define saved_kbd_mode (this->hidden->saved_kbd_mode)
116#define saved_kbd_termios (this->hidden->saved_kbd_termios)
117#define mouse_fd (this->hidden->mouse_fd)
118#if SDL_INPUT_TSLIB
119#define ts_dev (this->hidden->ts_dev)
120#endif
121#define cache_vinfo (this->hidden->cache_vinfo)
122#define saved_vinfo (this->hidden->saved_vinfo)
123#define saved_cmaplen (this->hidden->saved_cmaplen)
124#define saved_cmap (this->hidden->saved_cmap)
125#define mapped_mem (this->hidden->mapped_mem)
126#define shadow_mem (this->hidden->shadow_mem)
127#define mapped_memlen (this->hidden->mapped_memlen)
128#define mapped_offset (this->hidden->mapped_offset)
129#define mapped_io (this->hidden->mapped_io)
130#define mapped_iolen (this->hidden->mapped_iolen)
131#define flip_page (this->hidden->flip_page)
132#define flip_address (this->hidden->flip_address)
133#define rotate (this->hidden->rotate)
134#define shadow_fb (this->hidden->shadow_fb)
135#define blitFunc (this->hidden->blitFunc)
136#define physlinebytes (this->hidden->physlinebytes)
137#define SDL_nummodes (this->hidden->SDL_nummodes)
138#define SDL_modelist (this->hidden->SDL_modelist)
139#define surfaces (this->hidden->surfaces)
140#define surfaces_memtotal (this->hidden->surfaces_memtotal)
141#define surfaces_memleft (this->hidden->surfaces_memleft)
142#define hw_lock (this->hidden->hw_lock)
143#define switched_away (this->hidden->switched_away)
144#define screen_vinfo (this->hidden->screen_vinfo)
145#define screen_arealen (this->hidden->screen_arealen)
146#define screen_contents (this->hidden->screen_contents)
147#define screen_palette (this->hidden->screen_palette)
148#define wait_vbl (this->hidden->wait_vbl)
149#define wait_idle (this->hidden->wait_idle)
150
151/* Accelerator types that are supported by the driver, but are not
152 necessarily in the kernel headers on the system we compile on.
153*/
154#ifndef FB_ACCEL_MATROX_MGAG400
155#define FB_ACCEL_MATROX_MGAG400 26 /* Matrox G400 */
156#endif
157#ifndef FB_ACCEL_3DFX_BANSHEE
158#define FB_ACCEL_3DFX_BANSHEE 31 /* 3Dfx Banshee */
159#endif
160
161/* These functions are defined in SDL_fbvideo.c */
162extern void FB_SavePaletteTo(_THIS, int palette_len, __u16 *area);
163extern void FB_RestorePaletteFrom(_THIS, int palette_len, __u16 *area);
164
165/* These are utility functions for working with video surfaces */
166
167static __inline__ void FB_AddBusySurface(SDL_Surface *surface)
168{
169 ((vidmem_bucket *)surface->hwdata)->dirty = 1;
170}
171
172static __inline__ int FB_IsSurfaceBusy(SDL_Surface *surface)
173{
174 return ((vidmem_bucket *)surface->hwdata)->dirty;
175}
176
177static __inline__ void FB_WaitBusySurfaces(_THIS)
178{
179 vidmem_bucket *bucket;
180
181 /* Wait for graphic operations to complete */
182 wait_idle(this);
183
184 /* Clear all surface dirty bits */
185 for ( bucket=&surfaces; bucket; bucket=bucket->next ) {
186 bucket->dirty = 0;
187 }
188}
189
190static __inline__ void FB_dst_to_xy(_THIS, SDL_Surface *dst, int *x, int *y)
191{
192 *x = (long)((char *)dst->pixels - mapped_mem)%this->screen->pitch;
193 *y = (long)((char *)dst->pixels - mapped_mem)/this->screen->pitch;
194 if ( dst == this->screen ) {
195 *x += this->offset_x;
196 *y += this->offset_y;
197 }
198}
199
200#endif /* _SDL_fbvideo_h */
diff --git a/apps/plugins/sdl/src/video/fbcon/matrox_mmio.h b/apps/plugins/sdl/src/video/fbcon/matrox_mmio.h
deleted file mode 100644
index a1cf203ea5..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/matrox_mmio.h
+++ /dev/null
@@ -1,51 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* MGA register definitions */
25
26#include "matrox_regs.h"
27
28/* MGA control macros */
29
30#define mga_in8(reg) *(volatile Uint8 *)(mapped_io + (reg))
31#define mga_in32(reg) *(volatile Uint32 *)(mapped_io + (reg))
32
33#define mga_out8(reg,v) *(volatile Uint8 *)(mapped_io + (reg)) = v;
34#define mga_out32(reg,v) *(volatile Uint32 *)(mapped_io + (reg)) = v;
35
36
37/* Wait for fifo space */
38#define mga_wait(space) \
39{ \
40 while ( mga_in8(MGAREG_FIFOSTATUS) < space ) \
41 ; \
42}
43
44
45/* Wait for idle accelerator */
46#define mga_waitidle() \
47{ \
48 while ( mga_in32(MGAREG_STATUS) & 0x10000 ) \
49 ; \
50}
51
diff --git a/apps/plugins/sdl/src/video/fbcon/matrox_regs.h b/apps/plugins/sdl/src/video/fbcon/matrox_regs.h
deleted file mode 100644
index d570b0c9b0..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/matrox_regs.h
+++ /dev/null
@@ -1,376 +0,0 @@
1
2/*
3 * MGA Millennium (MGA2064W) functions
4 * MGA Mystique (MGA1064SG) functions
5 *
6 * Copyright 1996 The XFree86 Project, Inc.
7 *
8 * Authors
9 * Dirk Hohndel
10 * hohndel@XFree86.Org
11 * David Dawes
12 * dawes@XFree86.Org
13 * Contributors:
14 * Guy DESBIEF, Aix-en-provence, France
15 * g.desbief@aix.pacwan.net
16 * MGA1064SG Mystique register file
17 */
18
19
20#ifndef _MGA_REG_H_
21#define _MGA_REG_H_
22
23#define MGAREG_DWGCTL 0x1c00
24#define MGAREG_MACCESS 0x1c04
25/* the following is a mystique only register */
26#define MGAREG_MCTLWTST 0x1c08
27#define MGAREG_ZORG 0x1c0c
28
29#define MGAREG_PAT0 0x1c10
30#define MGAREG_PAT1 0x1c14
31#define MGAREG_PLNWT 0x1c1c
32
33#define MGAREG_BCOL 0x1c20
34#define MGAREG_FCOL 0x1c24
35
36#define MGAREG_SRC0 0x1c30
37#define MGAREG_SRC1 0x1c34
38#define MGAREG_SRC2 0x1c38
39#define MGAREG_SRC3 0x1c3c
40
41#define MGAREG_XYSTRT 0x1c40
42#define MGAREG_XYEND 0x1c44
43
44#define MGAREG_SHIFT 0x1c50
45/* the following is a mystique only register */
46#define MGAREG_DMAPAD 0x1c54
47#define MGAREG_SGN 0x1c58
48#define MGAREG_LEN 0x1c5c
49
50#define MGAREG_AR0 0x1c60
51#define MGAREG_AR1 0x1c64
52#define MGAREG_AR2 0x1c68
53#define MGAREG_AR3 0x1c6c
54#define MGAREG_AR4 0x1c70
55#define MGAREG_AR5 0x1c74
56#define MGAREG_AR6 0x1c78
57
58#define MGAREG_CXBNDRY 0x1c80
59#define MGAREG_FXBNDRY 0x1c84
60#define MGAREG_YDSTLEN 0x1c88
61#define MGAREG_PITCH 0x1c8c
62
63#define MGAREG_YDST 0x1c90
64#define MGAREG_YDSTORG 0x1c94
65#define MGAREG_YTOP 0x1c98
66#define MGAREG_YBOT 0x1c9c
67
68#define MGAREG_CXLEFT 0x1ca0
69#define MGAREG_CXRIGHT 0x1ca4
70#define MGAREG_FXLEFT 0x1ca8
71#define MGAREG_FXRIGHT 0x1cac
72
73#define MGAREG_XDST 0x1cb0
74
75#define MGAREG_DR0 0x1cc0
76#define MGAREG_DR1 0x1cc4
77#define MGAREG_DR2 0x1cc8
78#define MGAREG_DR3 0x1ccc
79
80#define MGAREG_DR4 0x1cd0
81#define MGAREG_DR5 0x1cd4
82#define MGAREG_DR6 0x1cd8
83#define MGAREG_DR7 0x1cdc
84
85#define MGAREG_DR8 0x1ce0
86#define MGAREG_DR9 0x1ce4
87#define MGAREG_DR10 0x1ce8
88#define MGAREG_DR11 0x1cec
89
90#define MGAREG_DR12 0x1cf0
91#define MGAREG_DR13 0x1cf4
92#define MGAREG_DR14 0x1cf8
93#define MGAREG_DR15 0x1cfc
94
95#define MGAREG_SRCORG 0x2cb4
96#define MGAREG_DSTORG 0x2cb8
97
98/* add or or this to one of the previous "power registers" to start
99 the drawing engine */
100
101#define MGAREG_EXEC 0x0100
102
103#define MGAREG_FIFOSTATUS 0x1e10
104#define MGAREG_STATUS 0x1e14
105#define MGAREG_ICLEAR 0x1e18
106#define MGAREG_IEN 0x1e1c
107
108#define MGAREG_VCOUNT 0x1e20
109
110#define MGAREG_Reset 0x1e40
111
112#define MGAREG_OPMODE 0x1e54
113
114/* OPMODE register additives */
115
116#define MGAOPM_DMA_GENERAL (0x00 << 2)
117#define MGAOPM_DMA_BLIT (0x01 << 2)
118#define MGAOPM_DMA_VECTOR (0x10 << 2)
119
120/* DWGCTL register additives */
121
122/* Lines */
123
124#define MGADWG_LINE_OPEN 0x00
125#define MGADWG_AUTOLINE_OPEN 0x01
126#define MGADWG_LINE_CLOSE 0x02
127#define MGADWG_AUTOLINE_CLOSE 0x03
128
129/* Trapezoids */
130#define MGADWG_TRAP 0x04
131#define MGADWG_TEXTURE_TRAP 0x05
132
133/* BitBlts */
134
135#define MGADWG_BITBLT 0x08
136#define MGADWG_FBITBLT 0x0c
137#define MGADWG_ILOAD 0x09
138#define MGADWG_ILOAD_SCALE 0x0d
139#define MGADWG_ILOAD_FILTER 0x0f
140#define MGADWG_IDUMP 0x0a
141
142/* atype access to WRAM */
143
144#define MGADWG_RPL ( 0x00 << 4 )
145#define MGADWG_RSTR ( 0x01 << 4 )
146#define MGADWG_ZI ( 0x03 << 4 )
147#define MGADWG_BLK ( 0x04 << 4 )
148#define MGADWG_I ( 0x07 << 4 )
149
150/* specifies whether bit blits are linear or xy */
151#define MGADWG_LINEAR ( 0x01 << 7 )
152
153/* z drawing mode. use MGADWG_NOZCMP for always */
154
155#define MGADWG_NOZCMP ( 0x00 << 8 )
156#define MGADWG_ZE ( 0x02 << 8 )
157#define MGADWG_ZNE ( 0x03 << 8 )
158#define MGADWG_ZLT ( 0x04 << 8 )
159#define MGADWG_ZLTE ( 0x05 << 8 )
160#define MGADWG_GT ( 0x06 << 8 )
161#define MGADWG_GTE ( 0x07 << 8 )
162
163/* use this to force colour expansion circuitry to do its stuff */
164
165#define MGADWG_SOLID ( 0x01 << 11 )
166
167/* ar register at zero */
168
169#define MGADWG_ARZERO ( 0x01 << 12 )
170
171#define MGADWG_SGNZERO ( 0x01 << 13 )
172
173#define MGADWG_SHIFTZERO ( 0x01 << 14 )
174
175/* See table on 4-43 for bop ALU operations */
176
177/* See table on 4-44 for translucidity masks */
178
179#define MGADWG_BMONOLEF ( 0x00 << 25 )
180#define MGADWG_BMONOWF ( 0x04 << 25 )
181#define MGADWG_BPLAN ( 0x01 << 25 )
182
183/* note that if bfcol is specified and you're doing a bitblt, it causes
184 a fbitblt to be performed, so check that you obey the fbitblt rules */
185
186#define MGADWG_BFCOL ( 0x02 << 25 )
187#define MGADWG_BUYUV ( 0x0e << 25 )
188#define MGADWG_BU32BGR ( 0x03 << 25 )
189#define MGADWG_BU32RGB ( 0x07 << 25 )
190#define MGADWG_BU24BGR ( 0x0b << 25 )
191#define MGADWG_BU24RGB ( 0x0f << 25 )
192
193#define MGADWG_REPLACE 0x000C0000 /* From Linux kernel sources */
194#define MGADWG_PATTERN ( 0x01 << 29 )
195#define MGADWG_TRANSC ( 0x01 << 30 )
196#define MGADWG_NOCLIP ( 0x01 << 31 )
197#define MGAREG_MISC_WRITE 0x3c2
198#define MGAREG_MISC_READ 0x3cc
199#define MGAREG_MISC_IOADSEL (0x1 << 0)
200#define MGAREG_MISC_RAMMAPEN (0x1 << 1)
201#define MGAREG_MISC_CLK_SEL_VGA25 (0x0 << 2)
202#define MGAREG_MISC_CLK_SEL_VGA28 (0x1 << 2)
203#define MGAREG_MISC_CLK_SEL_MGA_PIX (0x2 << 2)
204#define MGAREG_MISC_CLK_SEL_MGA_MSK (0x3 << 2)
205#define MGAREG_MISC_VIDEO_DIS (0x1 << 4)
206#define MGAREG_MISC_HIGH_PG_SEL (0x1 << 5)
207
208/* MMIO VGA registers */
209#define MGAREG_CRTC_INDEX 0x1fd4
210#define MGAREG_CRTC_DATA 0x1fd5
211#define MGAREG_CRTCEXT_INDEX 0x1fde
212#define MGAREG_CRTCEXT_DATA 0x1fdf
213
214
215/* MGA bits for registers PCI_OPTION_REG */
216#define MGA1064_OPT_SYS_CLK_PCI ( 0x00 << 0 )
217#define MGA1064_OPT_SYS_CLK_PLL ( 0x01 << 0 )
218#define MGA1064_OPT_SYS_CLK_EXT ( 0x02 << 0 )
219#define MGA1064_OPT_SYS_CLK_MSK ( 0x03 << 0 )
220
221#define MGA1064_OPT_SYS_CLK_DIS ( 0x01 << 2 )
222#define MGA1064_OPT_G_CLK_DIV_1 ( 0x01 << 3 )
223#define MGA1064_OPT_M_CLK_DIV_1 ( 0x01 << 4 )
224
225#define MGA1064_OPT_SYS_PLL_PDN ( 0x01 << 5 )
226#define MGA1064_OPT_VGA_ION ( 0x01 << 8 )
227
228/* MGA registers in PCI config space */
229#define PCI_MGA_INDEX 0x44
230#define PCI_MGA_DATA 0x48
231#define PCI_MGA_OPTION2 0x50
232#define PCI_MGA_OPTION3 0x54
233
234#define RAMDAC_OFFSET 0x3c00
235
236/* TVP3026 direct registers */
237
238#define TVP3026_INDEX 0x00
239#define TVP3026_WADR_PAL 0x00
240#define TVP3026_COL_PAL 0x01
241#define TVP3026_PIX_RD_MSK 0x02
242#define TVP3026_RADR_PAL 0x03
243#define TVP3026_CUR_COL_ADDR 0x04
244#define TVP3026_CUR_COL_DATA 0x05
245#define TVP3026_DATA 0x0a
246#define TVP3026_CUR_RAM 0x0b
247#define TVP3026_CUR_XLOW 0x0c
248#define TVP3026_CUR_XHI 0x0d
249#define TVP3026_CUR_YLOW 0x0e
250#define TVP3026_CUR_YHI 0x0f
251
252/* TVP3026 indirect registers */
253
254#define TVP3026_SILICON_REV 0x01
255#define TVP3026_CURSOR_CTL 0x06
256#define TVP3026_LATCH_CTL 0x0f
257#define TVP3026_TRUE_COLOR_CTL 0x18
258#define TVP3026_MUX_CTL 0x19
259#define TVP3026_CLK_SEL 0x1a
260#define TVP3026_PAL_PAGE 0x1c
261#define TVP3026_GEN_CTL 0x1d
262#define TVP3026_MISC_CTL 0x1e
263#define TVP3026_GEN_IO_CTL 0x2a
264#define TVP3026_GEN_IO_DATA 0x2b
265#define TVP3026_PLL_ADDR 0x2c
266#define TVP3026_PIX_CLK_DATA 0x2d
267#define TVP3026_MEM_CLK_DATA 0x2e
268#define TVP3026_LOAD_CLK_DATA 0x2f
269#define TVP3026_KEY_RED_LOW 0x32
270#define TVP3026_KEY_RED_HI 0x33
271#define TVP3026_KEY_GREEN_LOW 0x34
272#define TVP3026_KEY_GREEN_HI 0x35
273#define TVP3026_KEY_BLUE_LOW 0x36
274#define TVP3026_KEY_BLUE_HI 0x37
275#define TVP3026_KEY_CTL 0x38
276#define TVP3026_MCLK_CTL 0x39
277#define TVP3026_SENSE_TEST 0x3a
278#define TVP3026_TEST_DATA 0x3b
279#define TVP3026_CRC_LSB 0x3c
280#define TVP3026_CRC_MSB 0x3d
281#define TVP3026_CRC_CTL 0x3e
282#define TVP3026_ID 0x3f
283#define TVP3026_RESET 0xff
284
285
286/* MGA1064 DAC Register file */
287/* MGA1064 direct registers */
288
289#define MGA1064_INDEX 0x00
290#define MGA1064_WADR_PAL 0x00
291#define MGA1064_COL_PAL 0x01
292#define MGA1064_PIX_RD_MSK 0x02
293#define MGA1064_RADR_PAL 0x03
294#define MGA1064_DATA 0x0a
295
296#define MGA1064_CUR_XLOW 0x0c
297#define MGA1064_CUR_XHI 0x0d
298#define MGA1064_CUR_YLOW 0x0e
299#define MGA1064_CUR_YHI 0x0f
300
301/* MGA1064 indirect registers */
302#define MGA1064_CURSOR_BASE_ADR_LOW 0x04
303#define MGA1064_CURSOR_BASE_ADR_HI 0x05
304#define MGA1064_CURSOR_CTL 0x06
305#define MGA1064_CURSOR_COL0_RED 0x08
306#define MGA1064_CURSOR_COL0_GREEN 0x09
307#define MGA1064_CURSOR_COL0_BLUE 0x0a
308
309#define MGA1064_CURSOR_COL1_RED 0x0c
310#define MGA1064_CURSOR_COL1_GREEN 0x0d
311#define MGA1064_CURSOR_COL1_BLUE 0x0e
312
313#define MGA1064_CURSOR_COL2_RED 0x010
314#define MGA1064_CURSOR_COL2_GREEN 0x011
315#define MGA1064_CURSOR_COL2_BLUE 0x012
316
317#define MGA1064_VREF_CTL 0x018
318
319#define MGA1064_MUL_CTL 0x19
320#define MGA1064_MUL_CTL_8bits 0x0
321#define MGA1064_MUL_CTL_15bits 0x01
322#define MGA1064_MUL_CTL_16bits 0x02
323#define MGA1064_MUL_CTL_24bits 0x03
324#define MGA1064_MUL_CTL_32bits 0x04
325#define MGA1064_MUL_CTL_2G8V16bits 0x05
326#define MGA1064_MUL_CTL_G16V16bits 0x06
327#define MGA1064_MUL_CTL_32_24bits 0x07
328
329#define MGAGDAC_XVREFCTRL 0x18
330#define MGA1064_PIX_CLK_CTL 0x1a
331#define MGA1064_PIX_CLK_CTL_CLK_DIS ( 0x01 << 2 )
332#define MGA1064_PIX_CLK_CTL_CLK_POW_DOWN ( 0x01 << 3 )
333#define MGA1064_PIX_CLK_CTL_SEL_PCI ( 0x00 << 0 )
334#define MGA1064_PIX_CLK_CTL_SEL_PLL ( 0x01 << 0 )
335#define MGA1064_PIX_CLK_CTL_SEL_EXT ( 0x02 << 0 )
336#define MGA1064_PIX_CLK_CTL_SEL_MSK ( 0x03 << 0 )
337
338#define MGA1064_GEN_CTL 0x1d
339#define MGA1064_MISC_CTL 0x1e
340#define MGA1064_MISC_CTL_DAC_POW_DN ( 0x01 << 0 )
341#define MGA1064_MISC_CTL_VGA ( 0x01 << 1 )
342#define MGA1064_MISC_CTL_DIS_CON ( 0x03 << 1 )
343#define MGA1064_MISC_CTL_MAFC ( 0x02 << 1 )
344#define MGA1064_MISC_CTL_VGA8 ( 0x01 << 3 )
345#define MGA1064_MISC_CTL_DAC_RAM_CS ( 0x01 << 4 )
346
347#define MGA1064_GEN_IO_CTL 0x2a
348#define MGA1064_GEN_IO_DATA 0x2b
349#define MGA1064_SYS_PLL_M 0x2c
350#define MGA1064_SYS_PLL_N 0x2d
351#define MGA1064_SYS_PLL_P 0x2e
352#define MGA1064_SYS_PLL_STAT 0x2f
353#define MGA1064_ZOOM_CTL 0x38
354#define MGA1064_SENSE_TST 0x3a
355
356#define MGA1064_CRC_LSB 0x3c
357#define MGA1064_CRC_MSB 0x3d
358#define MGA1064_CRC_CTL 0x3e
359#define MGA1064_COL_KEY_MSK_LSB 0x40
360#define MGA1064_COL_KEY_MSK_MSB 0x41
361#define MGA1064_COL_KEY_LSB 0x42
362#define MGA1064_COL_KEY_MSB 0x43
363#define MGA1064_PIX_PLLA_M 0x44
364#define MGA1064_PIX_PLLA_N 0x45
365#define MGA1064_PIX_PLLA_P 0x46
366#define MGA1064_PIX_PLLB_M 0x48
367#define MGA1064_PIX_PLLB_N 0x49
368#define MGA1064_PIX_PLLB_P 0x4a
369#define MGA1064_PIX_PLLC_M 0x4c
370#define MGA1064_PIX_PLLC_N 0x4d
371#define MGA1064_PIX_PLLC_P 0x4e
372
373#define MGA1064_PIX_PLL_STAT 0x4f
374
375#endif
376
diff --git a/apps/plugins/sdl/src/video/fbcon/riva_mmio.h b/apps/plugins/sdl/src/video/fbcon/riva_mmio.h
deleted file mode 100644
index e9261677b1..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/riva_mmio.h
+++ /dev/null
@@ -1,449 +0,0 @@
1/***************************************************************************\
2|* *|
3|* Copyright 1993-1999 NVIDIA, Corporation. All rights reserved. *|
4|* *|
5|* NOTICE TO USER: The source code is copyrighted under U.S. and *|
6|* international laws. Users and possessors of this source code are *|
7|* hereby granted a nonexclusive, royalty-free copyright license to *|
8|* use this code in individual and commercial software. *|
9|* *|
10|* Any use of this source code must include, in the user documenta- *|
11|* tion and internal comments to the code, notices to the end user *|
12|* as follows: *|
13|* *|
14|* Copyright 1993-1999 NVIDIA, Corporation. All rights reserved. *|
15|* *|
16|* NVIDIA, CORPORATION MAKES NO REPRESENTATION ABOUT THE SUITABILITY *|
17|* OF THIS SOURCE CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" *|
18|* WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. NVIDIA, CORPOR- *|
19|* ATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOURCE CODE, *|
20|* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGE- *|
21|* MENT, AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL *|
22|* NVIDIA, CORPORATION BE LIABLE FOR ANY SPECIAL, INDIRECT, INCI- *|
23|* DENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RE- *|
24|* SULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION *|
25|* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF *|
26|* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOURCE CODE. *|
27|* *|
28|* U.S. Government End Users. This source code is a "commercial *|
29|* item," as that term is defined at 48 C.F.R. 2.101 (OCT 1995), *|
30|* consisting of "commercial computer software" and "commercial *|
31|* computer software documentation," as such terms are used in *|
32|* 48 C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Govern- *|
33|* ment only as a commercial end item. Consistent with 48 C.F.R. *|
34|* 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), *|
35|* all U.S. Government End Users acquire the source code with only *|
36|* those rights set forth herein. *|
37|* *|
38\***************************************************************************/
39
40#ifndef __RIVA_HW_H__
41#define __RIVA_HW_H__
42#define RIVA_SW_VERSION 0x00010003
43
44/*
45 * Typedefs to force certain sized values.
46 */
47typedef Uint8 U008;
48typedef Uint16 U016;
49typedef Uint32 U032;
50
51/*
52 * HW access macros.
53 */
54#define NV_WR08(p,i,d) (((U008 *)(p))[i]=(d))
55#define NV_RD08(p,i) (((U008 *)(p))[i])
56#define NV_WR16(p,i,d) (((U016 *)(p))[(i)/2]=(d))
57#define NV_RD16(p,i) (((U016 *)(p))[(i)/2])
58#define NV_WR32(p,i,d) (((U032 *)(p))[(i)/4]=(d))
59#define NV_RD32(p,i) (((U032 *)(p))[(i)/4])
60#define VGA_WR08(p,i,d) NV_WR08(p,i,d)
61#define VGA_RD08(p,i) NV_RD08(p,i)
62
63/*
64 * Define supported architectures.
65 */
66#define NV_ARCH_03 0x03
67#define NV_ARCH_04 0x04
68#define NV_ARCH_10 0x10
69/***************************************************************************\
70* *
71* FIFO registers. *
72* *
73\***************************************************************************/
74
75/*
76 * Raster OPeration. Windows style ROP3.
77 */
78typedef volatile struct
79{
80 U032 reserved00[4];
81 U016 FifoFree;
82 U016 Nop;
83 U032 reserved01[0x0BB];
84 U032 Rop3;
85} RivaRop;
86/*
87 * 8X8 Monochrome pattern.
88 */
89typedef volatile struct
90{
91 U032 reserved00[4];
92 U016 FifoFree;
93 U016 Nop;
94 U032 reserved01[0x0BD];
95 U032 Shape;
96 U032 reserved03[0x001];
97 U032 Color0;
98 U032 Color1;
99 U032 Monochrome[2];
100} RivaPattern;
101/*
102 * Scissor clip rectangle.
103 */
104typedef volatile struct
105{
106 U032 reserved00[4];
107 U016 FifoFree;
108 U016 Nop;
109 U032 reserved01[0x0BB];
110 U032 TopLeft;
111 U032 WidthHeight;
112} RivaClip;
113/*
114 * 2D filled rectangle.
115 */
116typedef volatile struct
117{
118 U032 reserved00[4];
119 U016 FifoFree;
120 U016 Nop[1];
121 U032 reserved01[0x0BC];
122 U032 Color;
123 U032 reserved03[0x03E];
124 U032 TopLeft;
125 U032 WidthHeight;
126} RivaRectangle;
127/*
128 * 2D screen-screen BLT.
129 */
130typedef volatile struct
131{
132 U032 reserved00[4];
133 U016 FifoFree;
134 U016 Nop;
135 U032 reserved01[0x0BB];
136 U032 TopLeftSrc;
137 U032 TopLeftDst;
138 U032 WidthHeight;
139} RivaScreenBlt;
140/*
141 * 2D pixel BLT.
142 */
143typedef volatile struct
144{
145 U032 reserved00[4];
146 U016 FifoFree;
147 U016 Nop[1];
148 U032 reserved01[0x0BC];
149 U032 TopLeft;
150 U032 WidthHeight;
151 U032 WidthHeightIn;
152 U032 reserved02[0x03C];
153 U032 Pixels;
154} RivaPixmap;
155/*
156 * Filled rectangle combined with monochrome expand. Useful for glyphs.
157 */
158typedef volatile struct
159{
160 U032 reserved00[4];
161 U016 FifoFree;
162 U016 Nop;
163 U032 reserved01[0x0BB];
164 U032 reserved03[(0x040)-1];
165 U032 Color1A;
166 struct
167 {
168 U032 TopLeft;
169 U032 WidthHeight;
170 } UnclippedRectangle[64];
171 U032 reserved04[(0x080)-3];
172 struct
173 {
174 U032 TopLeft;
175 U032 BottomRight;
176 } ClipB;
177 U032 Color1B;
178 struct
179 {
180 U032 TopLeft;
181 U032 BottomRight;
182 } ClippedRectangle[64];
183 U032 reserved05[(0x080)-5];
184 struct
185 {
186 U032 TopLeft;
187 U032 BottomRight;
188 } ClipC;
189 U032 Color1C;
190 U032 WidthHeightC;
191 U032 PointC;
192 U032 MonochromeData1C;
193 U032 reserved06[(0x080)+121];
194 struct
195 {
196 U032 TopLeft;
197 U032 BottomRight;
198 } ClipD;
199 U032 Color1D;
200 U032 WidthHeightInD;
201 U032 WidthHeightOutD;
202 U032 PointD;
203 U032 MonochromeData1D;
204 U032 reserved07[(0x080)+120];
205 struct
206 {
207 U032 TopLeft;
208 U032 BottomRight;
209 } ClipE;
210 U032 Color0E;
211 U032 Color1E;
212 U032 WidthHeightInE;
213 U032 WidthHeightOutE;
214 U032 PointE;
215 U032 MonochromeData01E;
216} RivaBitmap;
217/*
218 * 3D textured, Z buffered triangle.
219 */
220typedef volatile struct
221{
222 U032 reserved00[4];
223 U016 FifoFree;
224 U016 Nop;
225 U032 reserved01[0x0BC];
226 U032 TextureOffset;
227 U032 TextureFormat;
228 U032 TextureFilter;
229 U032 FogColor;
230/* This is a problem on LynxOS */
231#ifdef Control
232#undef Control
233#endif
234 U032 Control;
235 U032 AlphaTest;
236 U032 reserved02[0x339];
237 U032 FogAndIndex;
238 U032 Color;
239 float ScreenX;
240 float ScreenY;
241 float ScreenZ;
242 float EyeM;
243 float TextureS;
244 float TextureT;
245} RivaTexturedTriangle03;
246typedef volatile struct
247{
248 U032 reserved00[4];
249 U016 FifoFree;
250 U016 Nop;
251 U032 reserved01[0x0BB];
252 U032 ColorKey;
253 U032 TextureOffset;
254 U032 TextureFormat;
255 U032 TextureFilter;
256 U032 Blend;
257/* This is a problem on LynxOS */
258#ifdef Control
259#undef Control
260#endif
261 U032 Control;
262 U032 FogColor;
263 U032 reserved02[0x39];
264 struct
265 {
266 float ScreenX;
267 float ScreenY;
268 float ScreenZ;
269 float EyeM;
270 U032 Color;
271 U032 Specular;
272 float TextureS;
273 float TextureT;
274 } Vertex[16];
275 U032 DrawTriangle3D;
276} RivaTexturedTriangle05;
277/*
278 * 2D line.
279 */
280typedef volatile struct
281{
282 U032 reserved00[4];
283 U016 FifoFree;
284 U016 Nop[1];
285 U032 reserved01[0x0BC];
286 U032 Color; /* source color 0304-0307*/
287 U032 Reserved02[0x03e];
288 struct { /* start aliased methods in array 0400- */
289 U032 point0; /* y_x S16_S16 in pixels 0- 3*/
290 U032 point1; /* y_x S16_S16 in pixels 4- 7*/
291 } Lin[16]; /* end of aliased methods in array -047f*/
292 struct { /* start aliased methods in array 0480- */
293 U032 point0X; /* in pixels, 0 at left 0- 3*/
294 U032 point0Y; /* in pixels, 0 at top 4- 7*/
295 U032 point1X; /* in pixels, 0 at left 8- b*/
296 U032 point1Y; /* in pixels, 0 at top c- f*/
297 } Lin32[8]; /* end of aliased methods in array -04ff*/
298 U032 PolyLin[32]; /* y_x S16_S16 in pixels 0500-057f*/
299 struct { /* start aliased methods in array 0580- */
300 U032 x; /* in pixels, 0 at left 0- 3*/
301 U032 y; /* in pixels, 0 at top 4- 7*/
302 } PolyLin32[16]; /* end of aliased methods in array -05ff*/
303 struct { /* start aliased methods in array 0600- */
304 U032 color; /* source color 0- 3*/
305 U032 point; /* y_x S16_S16 in pixels 4- 7*/
306 } ColorPolyLin[16]; /* end of aliased methods in array -067f*/
307} RivaLine;
308/*
309 * 2D/3D surfaces
310 */
311typedef volatile struct
312{
313 U032 reserved00[4];
314 U016 FifoFree;
315 U016 Nop;
316 U032 reserved01[0x0BE];
317 U032 Offset;
318} RivaSurface;
319typedef volatile struct
320{
321 U032 reserved00[4];
322 U016 FifoFree;
323 U016 Nop;
324 U032 reserved01[0x0BD];
325 U032 Pitch;
326 U032 RenderBufferOffset;
327 U032 ZBufferOffset;
328} RivaSurface3D;
329
330/***************************************************************************\
331* *
332* Virtualized RIVA H/W interface. *
333* *
334\***************************************************************************/
335
336struct _riva_hw_inst;
337struct _riva_hw_state;
338/*
339 * Virtialized chip interface. Makes RIVA 128 and TNT look alike.
340 */
341typedef struct _riva_hw_inst
342{
343 /*
344 * Chip specific settings.
345 */
346 U032 Architecture;
347 U032 Version;
348 U032 CrystalFreqKHz;
349 U032 RamAmountKBytes;
350 U032 MaxVClockFreqKHz;
351 U032 RamBandwidthKBytesPerSec;
352 U032 EnableIRQ;
353 U032 IO;
354 U032 VBlankBit;
355 U032 FifoFreeCount;
356 U032 FifoEmptyCount;
357 /*
358 * Non-FIFO registers.
359 */
360 volatile U032 *PCRTC;
361 volatile U032 *PRAMDAC;
362 volatile U032 *PFB;
363 volatile U032 *PFIFO;
364 volatile U032 *PGRAPH;
365 volatile U032 *PEXTDEV;
366 volatile U032 *PTIMER;
367 volatile U032 *PMC;
368 volatile U032 *PRAMIN;
369 volatile U032 *FIFO;
370 volatile U032 *CURSOR;
371 volatile U032 *CURSORPOS;
372 volatile U032 *VBLANKENABLE;
373 volatile U032 *VBLANK;
374 volatile U008 *PCIO;
375 volatile U008 *PVIO;
376 volatile U008 *PDIO;
377 /*
378 * Common chip functions.
379 */
380 int (*Busy)(struct _riva_hw_inst *);
381 void (*CalcStateExt)(struct _riva_hw_inst *,struct _riva_hw_state *,int,int,int,int,int,int,int,int,int,int,int,int,int);
382 void (*LoadStateExt)(struct _riva_hw_inst *,struct _riva_hw_state *);
383 void (*UnloadStateExt)(struct _riva_hw_inst *,struct _riva_hw_state *);
384 void (*SetStartAddress)(struct _riva_hw_inst *,U032);
385 void (*SetSurfaces2D)(struct _riva_hw_inst *,U032,U032);
386 void (*SetSurfaces3D)(struct _riva_hw_inst *,U032,U032);
387 int (*ShowHideCursor)(struct _riva_hw_inst *,int);
388 void (*LockUnlock)(struct _riva_hw_inst *, int);
389 /*
390 * Current extended mode settings.
391 */
392 struct _riva_hw_state *CurrentState;
393 /*
394 * FIFO registers.
395 */
396 RivaRop *Rop;
397 RivaPattern *Patt;
398 RivaClip *Clip;
399 RivaPixmap *Pixmap;
400 RivaScreenBlt *Blt;
401 RivaBitmap *Bitmap;
402 RivaLine *Line;
403 RivaTexturedTriangle03 *Tri03;
404 RivaTexturedTriangle05 *Tri05;
405} RIVA_HW_INST;
406/*
407 * Extended mode state information.
408 */
409typedef struct _riva_hw_state
410{
411 U032 bpp;
412 U032 width;
413 U032 height;
414 U032 repaint0;
415 U032 repaint1;
416 U032 screen;
417 U032 pixel;
418 U032 horiz;
419 U032 arbitration0;
420 U032 arbitration1;
421 U032 vpll;
422 U032 pllsel;
423 U032 general;
424 U032 config;
425 U032 cursor0;
426 U032 cursor1;
427 U032 cursor2;
428 U032 offset0;
429 U032 offset1;
430 U032 offset2;
431 U032 offset3;
432 U032 pitch0;
433 U032 pitch1;
434 U032 pitch2;
435 U032 pitch3;
436} RIVA_HW_STATE;
437
438/*
439 * FIFO Free Count. Should attempt to yield processor if RIVA is busy.
440 */
441
442#define RIVA_FIFO_FREE(hwptr,cnt) \
443{ \
444 while (FifoFreeCount < (cnt)) \
445 FifoFreeCount = hwptr->FifoFree >> 2; \
446 FifoFreeCount -= (cnt); \
447}
448#endif /* __RIVA_HW_H__ */
449
diff --git a/apps/plugins/sdl/src/video/fbcon/riva_regs.h b/apps/plugins/sdl/src/video/fbcon/riva_regs.h
deleted file mode 100644
index 5324562ecd..0000000000
--- a/apps/plugins/sdl/src/video/fbcon/riva_regs.h
+++ /dev/null
@@ -1,43 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _RIVA_REGS_H
25#define _RIVA_REGS_H
26
27/* This information comes from the XFree86 NVidia hardware driver */
28
29/* mapped_io register offsets */
30#define PGRAPH_OFFSET 0x00400000
31#define FIFO_OFFSET 0x00800000
32#define ROP_OFFSET FIFO_OFFSET+0x00000000
33#define CLIP_OFFSET FIFO_OFFSET+0x00002000
34#define PATT_OFFSET FIFO_OFFSET+0x00004000
35#define PIXMAP_OFFSET FIFO_OFFSET+0x00006000
36#define BLT_OFFSET FIFO_OFFSET+0x00008000
37#define BITMAP_OFFSET FIFO_OFFSET+0x0000A000
38#define LINE_OFFSET FIFO_OFFSET+0x0000C000
39#define TRI03_OFFSET FIFO_OFFSET+0x0000E000
40#define PCIO_OFFSET 0x00601000
41
42#endif /* _RIVA_REGS_H */
43
diff --git a/apps/plugins/sdl/src/video/gapi/SDL_gapivideo.c b/apps/plugins/sdl/src/video/gapi/SDL_gapivideo.c
deleted file mode 100644
index 86deadc75b..0000000000
--- a/apps/plugins/sdl/src/video/gapi/SDL_gapivideo.c
+++ /dev/null
@@ -1,1287 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Pocket PC GAPI SDL video driver implementation;
25Implemented by Dmitry Yakimov - support@activekitten.com
26Inspired by http://arisme.free.fr/ports/SDL.php
27*/
28
29// TODO: copy surface on window when lost focus
30// TODO: test buttons rotation
31// TODO: test on be300 and HPC ( check WinDib fullscreen keys catching )
32// TODO: test on smartphones
33// TODO: windib on SH3 PPC2000 landscape test
34// TODO: optimize 8bpp landscape mode
35
36// there is some problems in runnings apps from a device landscape mode
37// due to WinCE bugs. Some works and some - does not.
38// TODO: finish Axim Dell X30 and user landscape mode, device landscape mode
39// TODO: finish Axim Dell X30 user portrait, device landscape stylus conversion
40// TODO: fix running GAPI apps from landscape mode -
41// wince goes to portrait mode, but does not update video memory
42
43
44#include "SDL.h"
45#include "SDL_error.h"
46#include "SDL_video.h"
47#include "SDL_mouse.h"
48#include "../SDL_sysvideo.h"
49#include "../SDL_pixels_c.h"
50#include "../../events/SDL_events_c.h"
51#include "../wincommon/SDL_syswm_c.h"
52#include "../wincommon/SDL_sysmouse_c.h"
53#include "../windib/SDL_dibevents_c.h"
54
55#include "../windib/SDL_gapidibvideo.h"
56#include "SDL_gapivideo.h"
57
58#define gapi this->hidden->gapiInfo
59
60#define GAPIVID_DRIVER_NAME "gapi"
61
62#if defined(DEBUG) || defined (_DEBUG) || defined(NDEBUG)
63#define REPORT_VIDEO_INFO 1
64#else
65#define REPORT_VIDEO_INFO 0
66#endif
67
68// for testing with GapiEmu
69#define USE_GAPI_EMU 0
70#define EMULATE_AXIM_X30 0
71#define WITHOUT_GAPI 0
72
73#if USE_GAPI_EMU && !REPORT_VIDEO_INFO
74#pragma message("Warning: Using GapiEmu in release build. I assume you'd like to set USE_GAPI_EMU to zero.")
75#endif
76
77#ifndef _T
78#define _T(x) L##x
79#endif
80
81#ifndef ASSERT
82#define ASSERT(x)
83#endif
84
85// defined and used in SDL_sysevents.c
86extern HINSTANCE aygshell;
87extern void SDL_UnregisterApp();
88extern int DIB_AddMode(_THIS, int bpp, int w, int h);
89
90/* Initialization/Query functions */
91static int GAPI_VideoInit(_THIS, SDL_PixelFormat *vformat);
92static SDL_Rect **GAPI_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
93static SDL_Surface *GAPI_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
94static int GAPI_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
95static void GAPI_VideoQuit(_THIS);
96
97/* Hardware surface functions */
98static int GAPI_AllocHWSurface(_THIS, SDL_Surface *surface);
99static int GAPI_LockHWSurface(_THIS, SDL_Surface *surface);
100static void GAPI_UnlockHWSurface(_THIS, SDL_Surface *surface);
101static void GAPI_FreeHWSurface(_THIS, SDL_Surface *surface);
102
103/* Windows message handling functions, will not be processed */
104static void GAPI_Activate(_THIS, BOOL active, BOOL minimized);
105static void GAPI_RealizePalette(_THIS);
106static void GAPI_PaletteChanged(_THIS, HWND window);
107static void GAPI_WinPAINT(_THIS, HDC hdc);
108
109/* etc. */
110static void GAPI_UpdateRects(_THIS, int numrects, SDL_Rect *rects);
111
112static HMODULE g_hGapiLib = 0;
113#define LINK(type,name,import) \
114 if( g_hGapiLib ) \
115 name = (PFN##type)GetProcAddress( g_hGapiLib, _T(import) );
116
117static char g_bRawBufferAvailable = 0;
118
119/* GAPI driver bootstrap functions */
120
121/* hi res definitions */
122typedef struct _RawFrameBufferInfo
123{
124 WORD wFormat;
125 WORD wBPP;
126 VOID *pFramePointer;
127 int cxStride;
128 int cyStride;
129 int cxPixels;
130 int cyPixels;
131} RawFrameBufferInfo;
132
133static struct _RawFrameBufferInfo g_RawFrameBufferInfo = {0};
134
135#define GETRAWFRAMEBUFFER 0x00020001
136
137#define FORMAT_565 1
138#define FORMAT_555 2
139#define FORMAT_OTHER 3
140
141/* Dell Axim x30 hangs when we use GAPI from landscape,
142 so lets avoid using GxOpenDisplay there via GETGXINFO trick
143 It seems that GAPI subsystem use the same ExtEscape code.
144*/
145#define GETGXINFO 0x00020000
146
147typedef struct GXDeviceInfo
148{
149long Version; //00 (should filled with 100 before calling ExtEscape)
150void * pvFrameBuffer; //04
151unsigned long cbStride; //08
152unsigned long cxWidth; //0c
153unsigned long cyHeight; //10
154unsigned long cBPP; //14
155unsigned long ffFormat; //18
156char Unused[0x84-7*4];
157} GXDeviceInfo;
158
159static int GAPI_Available(void)
160{
161 // try to use VGA display, even on emulator
162 HDC hdc = GetDC(NULL);
163 int result = ExtEscape(hdc, GETRAWFRAMEBUFFER, 0, NULL, sizeof(RawFrameBufferInfo), (char *)&g_RawFrameBufferInfo);
164 ReleaseDC(NULL, hdc);
165 g_bRawBufferAvailable = result > 0;
166
167 //My Asus MyPAL 696 reports the RAWFRAMEBUFFER as available, but with a size of 0 x 0
168 if(g_RawFrameBufferInfo.cxPixels <= 0 || g_RawFrameBufferInfo.cyPixels <= 0){
169 g_bRawBufferAvailable = 0;
170 }
171
172#if WITHOUT_GAPI
173 return g_bRawBufferAvailable;
174#endif
175
176#if USE_GAPI_EMU
177 g_hGapiLib = LoadLibrary(_T("GAPI_Emu.dll"));
178 if( !g_hGapiLib )
179 {
180 SDL_SetError("Gapi Emu not found!");
181 }
182 return g_hGapiLib != 0;
183#endif
184
185 // try to find gx.dll
186 g_hGapiLib = LoadLibrary(_T("\\Windows\\gx.dll"));
187 if( !g_hGapiLib )
188 {
189 g_hGapiLib = LoadLibrary(_T("gx.dll"));
190 if( !g_hGapiLib ) return g_bRawBufferAvailable;
191 }
192
193 return(1);
194}
195
196static int cmpmodes(const void *va, const void *vb)
197{
198 SDL_Rect *a = *(SDL_Rect **)va;
199 SDL_Rect *b = *(SDL_Rect **)vb;
200 if ( a->w == b->w )
201 return b->h - a->h;
202 else
203 return b->w - a->w;
204}
205
206static int GAPI_AddMode(_THIS, int bpp, int w, int h)
207{
208 SDL_Rect *mode;
209 int i, index;
210 int next_mode;
211
212 /* Check to see if we already have this mode */
213 if ( bpp < 8 ) { /* Not supported */
214 return(0);
215 }
216 index = ((bpp+7)/8)-1;
217 for ( i=0; i<gapi->SDL_nummodes[index]; ++i ) {
218 mode = gapi->SDL_modelist[index][i];
219 if ( (mode->w == w) && (mode->h == h) ) {
220 return(0);
221 }
222 }
223
224 /* Set up the new video mode rectangle */
225 mode = (SDL_Rect *)SDL_malloc(sizeof *mode);
226 if ( mode == NULL ) {
227 SDL_OutOfMemory();
228 return(-1);
229 }
230 mode->x = 0;
231 mode->y = 0;
232 mode->w = w;
233 mode->h = h;
234
235 /* Allocate the new list of modes, and fill in the new mode */
236 next_mode = gapi->SDL_nummodes[index];
237 gapi->SDL_modelist[index] = (SDL_Rect **)
238 SDL_realloc(gapi->SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *));
239 if ( gapi->SDL_modelist[index] == NULL ) {
240 SDL_OutOfMemory();
241 gapi->SDL_nummodes[index] = 0;
242 SDL_free(mode);
243 return(-1);
244 }
245 gapi->SDL_modelist[index][next_mode] = mode;
246 gapi->SDL_modelist[index][next_mode+1] = NULL;
247 gapi->SDL_nummodes[index]++;
248
249 return(0);
250}
251
252static void GAPI_DeleteDevice(SDL_VideoDevice *device)
253{
254 if( g_hGapiLib )
255 {
256 FreeLibrary(g_hGapiLib);
257 g_hGapiLib = 0;
258 }
259 SDL_free(device->hidden->gapiInfo);
260 SDL_free(device->hidden);
261 SDL_free(device);
262}
263
264static SDL_VideoDevice *GAPI_CreateDevice(int devindex)
265{
266 SDL_VideoDevice *device;
267
268 if( !g_hGapiLib && !g_bRawBufferAvailable)
269 {
270 if( !GAPI_Available() )
271 {
272 SDL_SetError("GAPI dll is not found and VGA mode is not available!");
273 return 0;
274 }
275 }
276
277 /* Initialize all variables that we clean on shutdown */
278 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
279 if ( device ) {
280 SDL_memset(device, 0, (sizeof *device));
281 device->hidden = (struct SDL_PrivateVideoData *)
282 SDL_malloc((sizeof *device->hidden));
283 if(device->hidden){
284 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
285 device->hidden->gapiInfo = (GapiInfo *)SDL_malloc((sizeof(GapiInfo)));
286 if(device->hidden->gapiInfo == NULL)
287 {
288 SDL_free(device->hidden);
289 device->hidden = NULL;
290 }
291 }
292 }
293 if ( (device == NULL) || (device->hidden == NULL) ) {
294 SDL_OutOfMemory();
295 if ( device ) {
296 SDL_free(device);
297 }
298 return(0);
299 }
300 SDL_memset(device->hidden->gapiInfo, 0, (sizeof *device->hidden->gapiInfo));
301
302 /* Set the function pointers */
303 device->VideoInit = GAPI_VideoInit;
304 device->ListModes = GAPI_ListModes;
305 device->SetVideoMode = GAPI_SetVideoMode;
306 device->UpdateMouse = WIN_UpdateMouse;
307 device->CreateYUVOverlay = NULL;
308 device->SetColors = GAPI_SetColors;
309 device->UpdateRects = GAPI_UpdateRects;
310 device->VideoQuit = GAPI_VideoQuit;
311 device->AllocHWSurface = GAPI_AllocHWSurface;
312 device->CheckHWBlit = NULL;
313 device->FillHWRect = NULL;
314 device->SetHWColorKey = NULL;
315 device->SetHWAlpha = NULL;
316 device->LockHWSurface = GAPI_LockHWSurface;
317 device->UnlockHWSurface = GAPI_UnlockHWSurface;
318 device->FlipHWSurface = NULL;
319 device->FreeHWSurface = GAPI_FreeHWSurface;
320 device->SetCaption = WIN_SetWMCaption;
321 device->SetIcon = WIN_SetWMIcon;
322 device->IconifyWindow = WIN_IconifyWindow;
323 device->GrabInput = WIN_GrabInput;
324 device->GetWMInfo = WIN_GetWMInfo;
325 device->FreeWMCursor = WIN_FreeWMCursor;
326 device->CreateWMCursor = WIN_CreateWMCursor;
327 device->ShowWMCursor = WIN_ShowWMCursor;
328 device->WarpWMCursor = WIN_WarpWMCursor;
329 device->CheckMouseMode = WIN_CheckMouseMode;
330 device->InitOSKeymap = DIB_InitOSKeymap;
331 device->PumpEvents = DIB_PumpEvents;
332
333 /* Set up the windows message handling functions */
334 WIN_Activate = GAPI_Activate;
335 WIN_RealizePalette = GAPI_RealizePalette;
336 WIN_PaletteChanged = GAPI_PaletteChanged;
337 WIN_WinPAINT = GAPI_WinPAINT;
338 HandleMessage = DIB_HandleMessage;
339
340 device->free = GAPI_DeleteDevice;
341
342 /* Load gapi library */
343#define gx device->hidden->gapiInfo->gxFunc
344
345 LINK( GXOpenDisplay, gx.GXOpenDisplay, "?GXOpenDisplay@@YAHPAUHWND__@@K@Z" )
346 LINK( GXCloseDisplay, gx.GXCloseDisplay, "?GXCloseDisplay@@YAHXZ" )
347 LINK( GXBeginDraw, gx.GXBeginDraw, "?GXBeginDraw@@YAPAXXZ" )
348 LINK( GXEndDraw, gx.GXEndDraw, "?GXEndDraw@@YAHXZ" )
349 LINK( GXOpenInput, gx.GXOpenInput, "?GXOpenInput@@YAHXZ" )
350 LINK( GXCloseInput, gx.GXCloseInput, "?GXCloseInput@@YAHXZ" )
351 LINK( GXGetDisplayProperties, gx.GXGetDisplayProperties,"?GXGetDisplayProperties@@YA?AUGXDisplayProperties@@XZ" )
352 LINK( GXGetDefaultKeys, gx.GXGetDefaultKeys, "?GXGetDefaultKeys@@YA?AUGXKeyList@@H@Z" )
353 LINK( GXSuspend, gx.GXSuspend, "?GXSuspend@@YAHXZ" )
354 LINK( GXResume, gx.GXResume, "?GXResume@@YAHXZ" )
355 LINK( GXSetViewport, gx.GXSetViewport, "?GXSetViewport@@YAHKKKK@Z" )
356 LINK( GXIsDisplayDRAMBuffer, gx.GXIsDisplayDRAMBuffer, "?GXIsDisplayDRAMBuffer@@YAHXZ" )
357
358 /* wrong gapi.dll */
359 if( !gx.GXOpenDisplay )
360 {
361 if( g_hGapiLib )
362 {
363 FreeLibrary(g_hGapiLib);
364 g_hGapiLib = 0;
365 }
366 }
367
368 if( !gx.GXOpenDisplay && !g_bRawBufferAvailable)
369 {
370 SDL_SetError("Error: damaged or unknown gapi.dll!\n");
371 GAPI_DeleteDevice(device);
372 return 0;
373 }
374
375 return device;
376}
377
378VideoBootStrap GAPI_bootstrap = {
379 GAPIVID_DRIVER_NAME, "WinCE GAPI video driver",
380 GAPI_Available, GAPI_CreateDevice
381};
382
383static void FillStructs(_THIS, BOOL useVga)
384{
385#ifdef _ARM_
386 WCHAR oemstr[100];
387#endif
388 /* fill a device properties */
389
390 if( !useVga )
391 {
392 gapi->gxProperties = gapi->gxFunc.GXGetDisplayProperties();
393 gapi->needUpdate = 1;
394 gapi->hiresFix = 0;
395 gapi->useVga = 0;
396 gapi->useGXOpenDisplay = 1;
397
398#ifdef _ARM_
399 /* check some devices and extract addition info */
400 SystemParametersInfo( SPI_GETOEMINFO, sizeof( oemstr ), oemstr, 0 );
401
402 // buggy iPaq38xx
403 if ((oemstr[12] == 'H') && (oemstr[13] == '3') && (oemstr[14] == '8') && (gapi->gxProperties.cbxPitch > 0))
404 {
405 gapi->videoMem = (PIXEL*)0xac0755a0;
406 gapi->gxProperties.cbxPitch = -640;
407 gapi->gxProperties.cbyPitch = 2;
408 gapi->needUpdate = 0;
409 }
410#if (EMULATE_AXIM_X30 == 0)
411 // buggy Dell Axim X30
412 if( _tcsncmp(oemstr, L"Dell Axim X30", 13) == 0 )
413#endif
414 {
415 GXDeviceInfo gxInfo = {0};
416 HDC hdc = GetDC(NULL);
417 int result;
418
419 gxInfo.Version = 100;
420 result = ExtEscape(hdc, GETGXINFO, 0, NULL, sizeof(gxInfo), (char *)&gxInfo);
421 if( result > 0 )
422 {
423 gapi->useGXOpenDisplay = 0;
424 gapi->videoMem = gxInfo.pvFrameBuffer;
425 gapi->needUpdate = 0;
426 gapi->gxProperties.cbxPitch = 2;
427 gapi->gxProperties.cbyPitch = 480;
428 gapi->gxProperties.cxWidth = gxInfo.cxWidth;
429 gapi->gxProperties.cyHeight = gxInfo.cyHeight;
430 gapi->gxProperties.ffFormat = gxInfo.ffFormat;
431 }
432 }
433#endif
434 } else
435 {
436 gapi->needUpdate = 0;
437 gapi->hiresFix = 0;
438 gapi->gxProperties.cBPP = g_RawFrameBufferInfo.wBPP;
439 gapi->gxProperties.cbxPitch = g_RawFrameBufferInfo.cxStride;
440 gapi->gxProperties.cbyPitch = g_RawFrameBufferInfo.cyStride;
441 gapi->gxProperties.cxWidth = g_RawFrameBufferInfo.cxPixels;
442 gapi->gxProperties.cyHeight = g_RawFrameBufferInfo.cyPixels;
443 gapi->videoMem = g_RawFrameBufferInfo.pFramePointer;
444 gapi->useVga = 1;
445
446 switch( g_RawFrameBufferInfo.wFormat )
447 {
448 case FORMAT_565:
449 gapi->gxProperties.ffFormat = kfDirect565;
450 break;
451 case FORMAT_555:
452 gapi->gxProperties.ffFormat = kfDirect555;
453 break;
454 default:
455 /* unknown pixel format, try define by BPP! */
456 switch( g_RawFrameBufferInfo.wBPP )
457 {
458 case 4:
459 case 8:
460 gapi->gxProperties.ffFormat = kfDirect;
461 case 16:
462 gapi->gxProperties.ffFormat = kfDirect565;
463 default:
464 gapi->gxProperties.ffFormat = kfDirect;
465 break;
466 }
467 }
468 }
469
470 if( gapi->gxProperties.cBPP != 16 )
471 {
472 gapi->gapiOrientation = SDL_ORIENTATION_UP;
473 } else
474 if( (gapi->gxProperties.cbxPitch > 0) && (gapi->gxProperties.cbyPitch > 0 ))
475 {
476 gapi->gapiOrientation = SDL_ORIENTATION_UP;
477 } else
478 if( (gapi->gxProperties.cbxPitch > 0) && (gapi->gxProperties.cbyPitch < 0 ))
479 {
480 gapi->gapiOrientation = SDL_ORIENTATION_RIGHT; // ipaq 3660
481 } else
482 if( (gapi->gxProperties.cbxPitch < 0) && (gapi->gxProperties.cbyPitch > 0 ))
483 {
484 gapi->gapiOrientation = SDL_ORIENTATION_LEFT; // ipaq 3800
485 }
486}
487
488static void GAPI_CreatePalette(int ncolors, SDL_Color *colors)
489{
490 // Setup a custom color palette
491 BYTE buffer[ sizeof(LOGPALETTE) + 255 * sizeof(PALETTEENTRY) ];
492 int i;
493 LOGPALETTE* pLogical = (LOGPALETTE*)buffer;
494 PALETTEENTRY* entries = pLogical->palPalEntry;
495 HPALETTE hPalette;
496 HDC hdc;
497
498 for (i = 0; i < ncolors; ++i)
499 {
500 // Find intensity by replicating the bit patterns over a byte
501 entries[i].peRed = colors[i].r;
502 entries[i].peGreen = colors[i].g;
503 entries[i].peBlue = colors[i].b;
504 entries[i].peFlags = 0;
505 }
506
507 // Create the GDI palette object
508 pLogical->palVersion = 0x0300;
509 pLogical->palNumEntries = ncolors;
510
511 hPalette = CreatePalette( pLogical );
512 ASSERT(hPalette);
513
514
515 // Realize the palette
516 hdc = GetDC(0);
517
518 SelectPalette( hdc, hPalette, FALSE );
519 RealizePalette( hdc );
520
521 ReleaseDC( 0, hdc );
522 DeleteObject( hPalette );
523}
524
525int GAPI_VideoInit(_THIS, SDL_PixelFormat *vformat)
526{
527 int i,bpp;
528
529 /* Create the window */
530 if ( DIB_CreateWindow(this) < 0 ) {
531 return(-1);
532 }
533
534 if( g_hGapiLib )
535 {
536 FillStructs(this, 0);
537
538 // SDL does not supports 2/4bpp mode, so use 16 bpp
539 bpp = gapi->gxProperties.cBPP < 8 ? 16 : gapi->gxProperties.cBPP;
540
541 /* set up normal and landscape mode */
542 GAPI_AddMode(this, bpp, gapi->gxProperties.cyHeight, gapi->gxProperties.cxWidth);
543 GAPI_AddMode(this, bpp, gapi->gxProperties.cxWidth, gapi->gxProperties.cyHeight);
544 }
545
546 /* add hi-res mode */
547 if( g_bRawBufferAvailable &&
548 !((gapi->gxProperties.cxWidth == (unsigned)g_RawFrameBufferInfo.cxPixels) && (gapi->gxProperties.cyHeight == (unsigned)g_RawFrameBufferInfo.cyPixels)))
549 {
550 FillStructs(this, 1);
551
552 // SDL does not supports 2/4bpp mode, so use 16 bpp
553 bpp = gapi->gxProperties.cBPP < 8 ? 16 : gapi->gxProperties.cBPP;
554
555 /* set up normal and landscape mode */
556 GAPI_AddMode(this, bpp, gapi->gxProperties.cyHeight, gapi->gxProperties.cxWidth);
557 GAPI_AddMode(this, bpp, gapi->gxProperties.cxWidth, gapi->gxProperties.cyHeight);
558 }
559
560 /* Determine the current screen size.
561 * This is NOT necessarily the size of the Framebuffer or GAPI, as they return
562 * the displaysize in ORIENTATION_UP */
563 this->info.current_w = GetSystemMetrics(SM_CXSCREEN);
564 this->info.current_h = GetSystemMetrics(SM_CYSCREEN);
565
566 /* Sort the mode lists */
567 for ( i=0; i<NUM_MODELISTS; ++i ) {
568 if ( gapi->SDL_nummodes[i] > 0 ) {
569 SDL_qsort(gapi->SDL_modelist[i], gapi->SDL_nummodes[i], sizeof *gapi->SDL_modelist[i], cmpmodes);
570 }
571 }
572
573 vformat->BitsPerPixel = gapi->gxProperties.cBPP < 8 ? 16 : (unsigned char)gapi->gxProperties.cBPP;
574
575 // Get color mask
576 if (gapi->gxProperties.ffFormat & kfDirect565) {
577 vformat->BitsPerPixel = 16;
578 vformat->Rmask = 0x0000f800;
579 vformat->Gmask = 0x000007e0;
580 vformat->Bmask = 0x0000001f;
581 gapi->videoMode = GAPI_DIRECT_565;
582 }
583 else
584 if (gapi->gxProperties.ffFormat & kfDirect555) {
585 vformat->BitsPerPixel = 16;
586 vformat->Rmask = 0x00007c00;
587 vformat->Gmask = 0x000003e0;
588 vformat->Bmask = 0x0000001f;
589 gapi->videoMode = GAPI_DIRECT_555;
590 }
591 else
592 if ((gapi->gxProperties.ffFormat & kfDirect) && (gapi->gxProperties.cBPP < 8)) {
593 // We'll perform the conversion
594 vformat->BitsPerPixel = 16;
595 vformat->Rmask = 0x0000f800; // 16 bit 565
596 vformat->Gmask = 0x000007e0;
597 vformat->Bmask = 0x0000001f;
598 if (gapi->gxProperties.ffFormat & kfDirectInverted)
599 gapi->invert = (1 << gapi->gxProperties.cBPP) - 1;
600 gapi->colorscale = gapi->gxProperties.cBPP < 8 ? 8 - gapi->gxProperties.cBPP : 0;
601 gapi->videoMode = GAPI_MONO;
602 }
603 else
604 if (gapi->gxProperties.ffFormat & kfPalette) {
605 gapi->videoMode = GAPI_PALETTE;
606 }
607
608 /* We're done! */
609 return(0);
610}
611
612SDL_Rect **GAPI_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
613{
614 return(gapi->SDL_modelist[((format->BitsPerPixel+7)/8)-1]);
615// return (SDL_Rect **) -1;
616}
617
618SDL_Surface *GAPI_SetVideoMode(_THIS, SDL_Surface *current,
619 int width, int height, int bpp, Uint32 flags)
620{
621 SDL_Surface *video;
622 Uint32 Rmask, Gmask, Bmask;
623 DWORD style;
624 SDL_Rect allScreen;
625
626 if( bpp < 4 )
627 {
628 SDL_SetError("1 bpp and 2 bpp modes is not implemented yet!");
629 return 0;
630 }
631
632 /* Recalculate bitmasks if necessary */
633 if (bpp == current->format->BitsPerPixel) {
634 video = current;
635 }
636 else {
637 switch(bpp) {
638 case 8:
639 Rmask = 0;
640 Gmask = 0;
641 Bmask = 0;
642 break;
643 case 15:
644 case 16:
645 /* Default is 565 unless the display is specifically 555 */
646 if (gapi->gxProperties.ffFormat & kfDirect555) {
647 Rmask = 0x00007c00;
648 Gmask = 0x000003e0;
649 Bmask = 0x0000001f;
650 }
651 else {
652 Rmask = 0x0000f800;
653 Gmask = 0x000007e0;
654 Bmask = 0x0000001f;
655 }
656 break;
657 case 24:
658 case 32:
659 Rmask = 0x00ff0000;
660 Gmask = 0x0000ff00;
661 Bmask = 0x000000ff;
662 break;
663 default:
664 SDL_SetError("Unsupported Bits Per Pixel format requested");
665 return NULL;
666 }
667 video = SDL_CreateRGBSurface(SDL_SWSURFACE,
668 0, 0, bpp, Rmask, Gmask, Bmask, 0);
669 if ( video == NULL ) {
670 SDL_OutOfMemory();
671 return(NULL);
672 }
673 }
674
675 gapi->userOrientation = SDL_ORIENTATION_UP;
676 gapi->systemOrientation = SDL_ORIENTATION_UP;
677 video->flags = SDL_FULLSCREEN; /* Clear flags, GAPI supports fullscreen only */
678
679 /* GAPI or VGA? */
680 if( g_hGapiLib )
681 {
682 FillStructs(this, 0);
683 if( (((unsigned)width != gapi->gxProperties.cxWidth) || ((unsigned)height != gapi->gxProperties.cyHeight))
684 && (((unsigned)width != gapi->gxProperties.cyHeight) || ((unsigned)height != gapi->gxProperties.cxWidth)))
685 FillStructs(this, 1); // gapi is found but we use VGA resolution
686 } else
687 FillStructs(this, 1);
688
689 if ( !gapi->needUpdate && !gapi->videoMem) {
690 SDL_SetError("Couldn't get address of video memory, may be unsupported device or bug");
691 return(NULL);
692 }
693
694 /* detect user landscape mode */
695 if( (width > height) && (gapi->gxProperties.cxWidth < gapi->gxProperties.cyHeight))
696 gapi->userOrientation = SDL_ORIENTATION_RIGHT;
697
698 if(GetSystemMetrics(SM_CYSCREEN) < GetSystemMetrics(SM_CXSCREEN))
699 gapi->systemOrientation = SDL_ORIENTATION_RIGHT;
700
701 gapi->hiresFix = 0;
702
703 /* check hires */
704 if(GetSystemMetrics(SM_CXSCREEN) < width && GetSystemMetrics(SM_CYSCREEN) < height)
705 {
706 gapi->hiresFix = 1;
707 }
708
709 switch( gapi->userOrientation )
710 {
711 case SDL_ORIENTATION_UP:
712 gapi->startOffset = 0;
713 gapi->dstLineStep = gapi->gxProperties.cbyPitch;
714 gapi->dstPixelStep = gapi->gxProperties.cbxPitch;
715 break;
716 case SDL_ORIENTATION_RIGHT:
717 switch( gapi->gapiOrientation )
718 {
719 case SDL_ORIENTATION_UP:
720 case SDL_ORIENTATION_RIGHT:
721 case SDL_ORIENTATION_LEFT:
722 if( (gapi->videoMode == GAPI_MONO) )
723 gapi->startOffset = -gapi->gxProperties.cbxPitch + 1; // monochrome mode
724 else
725 gapi->startOffset = gapi->gxProperties.cbyPitch * (gapi->gxProperties.cyHeight - 1);
726
727 gapi->dstLineStep = gapi->gxProperties.cbxPitch;
728 gapi->dstPixelStep = -gapi->gxProperties.cbyPitch;
729 break;
730 }
731 }
732
733 video->w = gapi->w = width;
734 video->h = gapi->h = height;
735 video->pitch = SDL_CalculatePitch(video);
736
737 /* Small fix for WinCE/Win32 - when activating window
738 SDL_VideoSurface is equal to zero, so activating code
739 is not called properly for fullscreen windows because
740 macros WINDIB_FULLSCREEN uses SDL_VideoSurface
741 */
742 SDL_VideoSurface = video;
743
744 /* GAPI is always fullscreen, title bar is useless */
745 style = 0;
746
747 if (!SDL_windowid)
748 SetWindowLong(SDL_Window, GWL_STYLE, style);
749
750 /* Allocate bitmap */
751 if( gapi->buffer )
752 {
753 SDL_free( gapi->buffer );
754 gapi->buffer = NULL;
755 }
756 gapi->buffer = SDL_malloc(video->h * video->pitch);
757 video->pixels = gapi->buffer;
758
759 if ( ! gapi->buffer ) {
760 SDL_SetError("Couldn't allocate buffer for requested mode");
761 return(NULL);
762 }
763
764 SDL_memset(gapi->buffer, 255, video->h * video->pitch);
765 MoveWindow(SDL_Window, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), FALSE);
766 ShowWindow(SDL_Window, SW_SHOW);
767 SetForegroundWindow(SDL_Window);
768
769 /* JC 14 Mar 2006
770 Flush the message loop or this can cause big problems later
771 Especially if the user decides to use dialog boxes or assert()!
772 */
773 WIN_FlushMessageQueue();
774
775 /* Open GAPI display */
776 if( !gapi->useVga && gapi->useGXOpenDisplay && !gapi->alreadyGXOpened )
777 {
778#if REPORT_VIDEO_INFO
779 printf("system display width (orig): %d\n", GetSystemMetrics(SM_CXSCREEN));
780 printf("system display height (orig): %d\n", GetSystemMetrics(SM_CYSCREEN));
781#endif
782 gapi->alreadyGXOpened = 1;
783 if( !gapi->gxFunc.GXOpenDisplay(SDL_Window, GX_FULLSCREEN) )
784 {
785 SDL_SetError("Couldn't initialize GAPI");
786 return(NULL);
787 }
788 }
789
790 if(gapi->useVga)
791 gapi->coordinateTransform = (4 - gapi->systemOrientation + gapi->userOrientation) % 4;
792 else
793 gapi->coordinateTransform = gapi->userOrientation;
794
795#if REPORT_VIDEO_INFO
796 printf("Video properties:\n");
797 printf("display bpp: %d\n", gapi->gxProperties.cBPP);
798 printf("display width: %d\n", gapi->gxProperties.cxWidth);
799 printf("display height: %d\n", gapi->gxProperties.cyHeight);
800 printf("system display width: %d\n", GetSystemMetrics(SM_CXSCREEN));
801 printf("system display height: %d\n", GetSystemMetrics(SM_CYSCREEN));
802 printf("x pitch: %d\n", gapi->gxProperties.cbxPitch);
803 printf("y pitch: %d\n", gapi->gxProperties.cbyPitch);
804 printf("gapi flags: 0x%x\n", gapi->gxProperties.ffFormat);
805 printf("user orientation: %d\n", gapi->userOrientation);
806 printf("system orientation: %d\n", gapi->systemOrientation);
807 printf("gapi orientation: %d\n", gapi->gapiOrientation);
808
809
810 if( !gapi->useVga && gapi->useGXOpenDisplay && gapi->needUpdate)
811 {
812 gapi->videoMem = gapi->gxFunc.GXBeginDraw();
813 gapi->gxFunc.GXEndDraw();
814 }
815
816 printf("video memory: 0x%x\n", gapi->videoMem);
817 printf("need update: %d\n", gapi->needUpdate);
818 printf("hi-res fix: %d\n", gapi->hiresFix);
819 printf("VGA is available on the device: %d\n", g_bRawBufferAvailable);
820 printf("use raw framebuffer: %d\n", gapi->useVga);
821 printf("video surface bpp: %d\n", video->format->BitsPerPixel);
822 printf("video surface width: %d\n", video->w);
823 printf("video surface height: %d\n", video->h);
824 printf("mouse/arrows transformation angle: %d\n", gapi->coordinateTransform);
825#endif
826
827
828 /* Blank screen */
829 allScreen.x = allScreen.y = 0;
830 allScreen.w = video->w - 1;
831 allScreen.h = video->h - 1;
832 GAPI_UpdateRects(this, 1, &allScreen);
833
834 /* We're done */
835 return(video);
836}
837
838/* We don't actually allow hardware surfaces other than the main one */
839static int GAPI_AllocHWSurface(_THIS, SDL_Surface *surface)
840{
841 return(-1);
842}
843static void GAPI_FreeHWSurface(_THIS, SDL_Surface *surface)
844{
845 return;
846}
847
848/* We need to wait for vertical retrace on page flipped displays */
849static int GAPI_LockHWSurface(_THIS, SDL_Surface *surface)
850{
851 return(0);
852}
853
854static void GAPI_UnlockHWSurface(_THIS, SDL_Surface *surface)
855{
856 return;
857}
858
859static int updateLine8to8(_THIS, unsigned char *srcPointer, unsigned char *destPointer, int width, int height, int lines)
860{
861 if( gapi->dstPixelStep == 1) /* optimized blitting on most devices */
862 {
863 SDL_memcpy(destPointer, srcPointer, width);
864 return 1;
865 } else
866 {
867 // TODO: read 4 pixels, write DWORD
868 int step = gapi->dstPixelStep;
869 while(width--)
870 {
871 *destPointer = *srcPointer++;
872 destPointer += step;
873 }
874 }
875 return 1;
876}
877
878/* Video memory is very slow so lets optimize as much as possible */
879static int updateLine16to16(_THIS, PIXEL *srcPointer, PIXEL *destPointer, int width, int height, int lines)
880{
881 PIXEL *line1, *line2;
882 int step = gapi->dstPixelStep / 2;
883
884 if( step == 1 ) /* optimized blitting on most devices */
885 {
886 SDL_memcpy(destPointer, srcPointer, width * sizeof(PIXEL));
887 return 1;
888 }
889 else
890 {
891 if( (gapi->gapiOrientation != SDL_ORIENTATION_UP) &&
892 (gapi->userOrientation == SDL_ORIENTATION_UP )) // iPaq 3660/3800 and user orientation up
893 {
894 // to prevent data misalignment copy only one line
895 if( ((((unsigned)destPointer & 3) != 0) && (gapi->gapiOrientation == SDL_ORIENTATION_LEFT))
896 || ((((unsigned)destPointer & 3) == 0) && (gapi->gapiOrientation != SDL_ORIENTATION_LEFT))
897 || (lines == 1) )
898 {
899 while(width--)
900 {
901 *destPointer = *srcPointer++;
902 destPointer += step;
903 }
904 return 1;
905 }
906
907 /* read two lines at the same time, write DWORD */
908 line1 = srcPointer;
909 line2 = srcPointer + SDL_VideoSurface->pitch / 2;
910
911 if( gapi->gapiOrientation == SDL_ORIENTATION_LEFT )
912 while(width--) // iPaq 3800
913 {
914 *(DWORD*)destPointer =(*line2++ << 16) | *line1++;
915 destPointer += step;
916 }
917 else
918 {
919 destPointer += gapi->gxProperties.cbyPitch / 2;
920
921 while(width--) // iPaq 3660
922 {
923 *(DWORD*)destPointer =(*line1++ << 16) | *line2++;
924 destPointer += step;
925 }
926 }
927 return 2;
928 } else
929 {
930 // iPaq 3800 and user orientation landscape
931 if( gapi->gapiOrientation == SDL_ORIENTATION_LEFT )
932 {
933 int w1;
934
935 // to prevent data misalignment copy only one pixel
936 if( (((unsigned)destPointer & 3) == 0) && (width > 0))
937 {
938 *destPointer-- = *srcPointer++;
939 width--;
940 }
941
942 destPointer--;
943
944 w1 = width / 2;
945
946 while(w1--)
947 {
948 DWORD p = *(DWORD*)srcPointer;
949 *((DWORD*)destPointer) = (p << 16) | (p >> 16);
950 destPointer -= 2;
951 srcPointer += 2;
952 }
953
954 if( width & 1 ) // copy the last pixel
955 {
956 destPointer++;
957 *destPointer = *srcPointer;
958 }
959
960 return 1;
961 }
962
963 // modern iPaqs and user orientation landscape
964 // read two pixels, write DWORD
965
966 line1 = srcPointer;
967 line2 = srcPointer + SDL_VideoSurface->pitch / 2;
968
969 if( (((unsigned)destPointer & 3) != 0) || (lines == 1) )
970 {
971 while(width--)
972 {
973 *destPointer = *srcPointer++;
974 destPointer += step;
975 }
976 return 1;
977 }
978
979 while(width--)
980 {
981 *(DWORD*)destPointer =(*line2++ << 16) | *line1++;
982 destPointer -= gapi->gxProperties.cbyPitch / 2;
983 }
984 return 2;
985 }
986 }
987}
988
989// Color component masks for 565
990#define REDMASK (31<<11)
991#define GREENMASK (63<<5)
992#define BLUEMASK (31)
993
994
995static int updateLine16to4(_THIS, PIXEL *srcPointer, unsigned char *destPointer, int width, int height, int lines, int yNibble, int xNibble)
996{
997 PIXEL *line1, *line2;
998 int step = gapi->dstPixelStep;
999
1000 if( gapi->userOrientation == SDL_ORIENTATION_UP )
1001 {
1002 if( yNibble ) // copy bottom half of a line
1003 {
1004 while(width--)
1005 {
1006 PIXEL c1 = *srcPointer++;
1007 c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK);
1008 *destPointer = (*destPointer & 0x0F) | ((~(c1 >> 3) << 4));
1009 destPointer += step;
1010 }
1011 return 1;
1012 }
1013
1014 // either 1 pixel picture or tail, anyway this is the last line
1015 if( lines == 1 )
1016 {
1017 while(width--)
1018 {
1019 PIXEL c1 = *srcPointer++;
1020 c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK);
1021 *destPointer = (*destPointer & 0xF0) | ((~(c1 >> 3) & 0xF));
1022 destPointer += step;
1023 }
1024 return 1;
1025 }
1026
1027 line1 = srcPointer;
1028 line2 = srcPointer + SDL_VideoSurface->pitch / 2;
1029
1030 while(width--)
1031 {
1032 PIXEL c1 = *line1++;
1033 PIXEL c2 = *line2++;
1034 c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK);
1035 c2 = ((c2 & REDMASK) >> 11) + ((c2 & GREENMASK) >> 5) + (c2 & BLUEMASK);
1036 *destPointer = ~((c1 >> 3) + ((c2 >> 3) << 4));
1037 destPointer += step;
1038 }
1039 return 2;
1040 } else
1041 {
1042 int w1;
1043 w1 = width / 2;
1044
1045 if( xNibble )
1046 {
1047 // copy one pixel
1048 PIXEL c1 = *srcPointer++;
1049 c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK);
1050 *destPointer = (*destPointer & 0xF0) | ((~(c1 >> 3) & 0xF));
1051 destPointer++;
1052 }
1053
1054 while(w1--)
1055 {
1056 PIXEL c1 = *srcPointer;
1057 PIXEL c2 = *(srcPointer + 1);
1058 c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK);
1059 c2 = ((c2 & REDMASK) >> 11) + ((c2 & GREENMASK) >> 5) + (c2 & BLUEMASK);
1060 *destPointer++ = ~((c2 >> 3) + ((c1 >> 3) << 4));
1061 srcPointer += 2;
1062 }
1063
1064 // copy tail
1065 if( (width & 1) && !xNibble )
1066 {
1067 PIXEL c1 = *srcPointer;
1068 c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK);
1069 *destPointer = (*destPointer & 0x0F) | ((~(c1 >> 3) << 4));
1070 }
1071
1072 return 1;
1073 }
1074}
1075
1076static void GAPI_UpdateRectsMono(_THIS, int numrects, SDL_Rect *rects)
1077{
1078 int i, height;
1079 int linesProcessed;
1080 int xNibble, yNibble;
1081
1082 for (i=0; i<numrects; i++)
1083 {
1084 unsigned char *destPointer;
1085 unsigned char *srcPointer;
1086
1087 if( gapi->userOrientation == SDL_ORIENTATION_UP )
1088 destPointer = (unsigned char*) gapi->videoMem + gapi->startOffset - rects[i].y * gapi->gxProperties.cBPP / 8 + rects[i].x * gapi->dstPixelStep;
1089 else
1090 destPointer = (unsigned char*) gapi->videoMem + gapi->startOffset + rects[i].x * gapi->gxProperties.cBPP / 8 + rects[i].y * gapi->dstLineStep;
1091
1092 srcPointer = ((unsigned char*) SDL_VideoSurface->pixels) + rects[i].y * SDL_VideoSurface->pitch + rects[i].x * 2;
1093 yNibble = rects[i].y & 1; // TODO: only for 4 bpp
1094 xNibble = rects[i].x & 1;
1095 height = rects[i].h;
1096 while (height > 0)
1097 {
1098 switch(gapi->gxProperties.cBPP)
1099 {
1100 case 2: // TODO
1101 case 4:
1102 linesProcessed = updateLine16to4(this, (PIXEL*) srcPointer, destPointer, rects[i].w, rects[i].h, height, yNibble, xNibble);
1103 yNibble = 0;
1104 }
1105 height -= linesProcessed;
1106 if( gapi->userOrientation == SDL_ORIENTATION_UP )
1107 destPointer--; // always fill 1 byte
1108 else destPointer += gapi->dstLineStep;
1109 srcPointer += SDL_VideoSurface->pitch * linesProcessed; // pitch in bytes
1110 }
1111 }
1112}
1113
1114static void GAPI_UpdateRectsColor(_THIS, int numrects, SDL_Rect *rects)
1115{
1116 int i, height;
1117 int bytesPerPixel = (gapi->gxProperties.cBPP + 1) / 8;
1118 int linesProcessed;
1119 for (i=0; i<numrects; i++) {
1120 unsigned char *destPointer = (unsigned char*) gapi->videoMem + gapi->startOffset + rects[i].y * gapi->dstLineStep + rects[i].x * gapi->dstPixelStep;
1121 unsigned char *srcPointer = ((unsigned char*) SDL_VideoSurface->pixels) + rects[i].y * SDL_VideoSurface->pitch + rects[i].x * bytesPerPixel;
1122 height = rects[i].h;
1123
1124// fprintf(stderr, "Starting rect %dx%d, dst=0x%x, w = %d, h = %d\n", rects[i].w, rects[i].h,destPointer,rects[i].w,rects[i].h);
1125// fflush(stderr);
1126 linesProcessed = height;
1127
1128 while (height > 0) {
1129 switch(bytesPerPixel)
1130 {
1131 case 1:
1132 linesProcessed = updateLine8to8(this, srcPointer, (unsigned char *) destPointer, rects[i].w, rects[i].h, height);
1133 break;
1134 case 2:
1135#pragma warning(disable: 4133)
1136 linesProcessed = updateLine16to16(this, (PIXEL*) srcPointer, destPointer, rects[i].w, rects[i].h, height);
1137 break;
1138 }
1139 height -= linesProcessed;
1140 destPointer += gapi->dstLineStep * linesProcessed;
1141 srcPointer += SDL_VideoSurface->pitch * linesProcessed; // pitch in bytes
1142 }
1143// fprintf(stderr, "End of rect\n");
1144// fflush(stderr);
1145 }
1146}
1147
1148
1149static void GAPI_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
1150{
1151 // we do not want to corrupt video memory
1152 if( gapi->suspended ) return;
1153
1154 if( gapi->needUpdate )
1155 gapi->videoMem = gapi->gxFunc.GXBeginDraw();
1156
1157 if( gapi->gxProperties.cBPP < 8 )
1158 GAPI_UpdateRectsMono(this, numrects, rects);
1159 else
1160 GAPI_UpdateRectsColor(this, numrects, rects);
1161
1162 if( gapi->needUpdate )
1163 gapi->gxFunc.GXEndDraw();
1164}
1165
1166/* Note: If we are terminated, this could be called in the middle of
1167 another SDL video routine -- notably UpdateRects.
1168*/
1169void GAPI_VideoQuit(_THIS)
1170{
1171 int i, j;
1172 /* Destroy the window and everything associated with it */
1173 if ( SDL_Window )
1174 {
1175 if ((g_hGapiLib != 0) && this && gapi && gapi->gxFunc.GXCloseDisplay && !gapi->useVga)
1176 gapi->gxFunc.GXCloseDisplay();
1177
1178 if (this->screen->pixels != NULL)
1179 {
1180 SDL_free(this->screen->pixels);
1181 this->screen->pixels = NULL;
1182 }
1183 if ( screen_icn ) {
1184 DestroyIcon(screen_icn);
1185 screen_icn = NULL;
1186 }
1187
1188 DIB_DestroyWindow(this);
1189 SDL_UnregisterApp();
1190
1191 SDL_Window = NULL;
1192#if defined(_WIN32_WCE)
1193
1194// Unload wince aygshell library to prevent leak
1195 if( aygshell )
1196 {
1197 FreeLibrary(aygshell);
1198 aygshell = NULL;
1199 }
1200#endif
1201
1202 /* Free video mode lists */
1203 for ( i=0; i<NUM_MODELISTS; ++i ) {
1204 if ( gapi->SDL_modelist[i] != NULL ) {
1205 for ( j=0; gapi->SDL_modelist[i][j]; ++j )
1206 SDL_free(gapi->SDL_modelist[i][j]);
1207 SDL_free(gapi->SDL_modelist[i]);
1208 gapi->SDL_modelist[i] = NULL;
1209 }
1210 }
1211
1212 }
1213
1214}
1215
1216static void GAPI_Activate(_THIS, BOOL active, BOOL minimized)
1217{
1218 //Nothing to do here (as far as I know)
1219}
1220
1221static void GAPI_RealizePalette(_THIS)
1222{
1223 OutputDebugString(TEXT("GAPI_RealizePalette NOT IMPLEMENTED !\r\n"));
1224}
1225
1226static void GAPI_PaletteChanged(_THIS, HWND window)
1227{
1228 OutputDebugString(TEXT("GAPI_PaletteChanged NOT IMPLEMENTED !\r\n"));
1229}
1230
1231static void GAPI_WinPAINT(_THIS, HDC hdc)
1232{
1233 // draw current offscreen buffer on hdc
1234
1235 int bpp = 16; // we always use either 8 or 16 bpp internally
1236 HGDIOBJ prevObject;
1237 unsigned short *bitmapData;
1238 HBITMAP hb;
1239 HDC srcDC;
1240
1241 // Create a DIB
1242 BYTE buffer[sizeof(BITMAPINFOHEADER) + 3 * sizeof(RGBQUAD)] = {0};
1243 BITMAPINFO* pBMI = (BITMAPINFO*)buffer;
1244 BITMAPINFOHEADER* pHeader = &pBMI->bmiHeader;
1245 DWORD* pColors = (DWORD*)&pBMI->bmiColors;
1246
1247 // CreateDIBSection does not support 332 pixel format on wce
1248 if( gapi->gxProperties.cBPP == 8 ) return;
1249
1250 // DIB Header
1251 pHeader->biSize = sizeof(BITMAPINFOHEADER);
1252 pHeader->biWidth = gapi->w;
1253 pHeader->biHeight = -gapi->h;
1254 pHeader->biPlanes = 1;
1255 pHeader->biBitCount = bpp;
1256 pHeader->biCompression = BI_RGB;
1257 pHeader->biSizeImage = (gapi->w * gapi->h * bpp) / 8;
1258
1259 // Color masks
1260 if( bpp == 16 )
1261 {
1262 pColors[0] = REDMASK;
1263 pColors[1] = GREENMASK;
1264 pColors[2] = BLUEMASK;
1265 pHeader->biCompression = BI_BITFIELDS;
1266 }
1267 // Create the DIB
1268 hb = CreateDIBSection( 0, pBMI, DIB_RGB_COLORS, (void**)&bitmapData, 0, 0 );
1269
1270 // copy data
1271 // FIXME: prevent misalignment, but I've never seen non aligned width of screen
1272 memcpy(bitmapData, gapi->buffer, pHeader->biSizeImage);
1273 srcDC = CreateCompatibleDC(hdc);
1274 prevObject = SelectObject(srcDC, hb);
1275
1276 BitBlt(hdc, 0, 0, gapi->w, gapi->h, srcDC, 0, 0, SRCCOPY);
1277
1278 SelectObject(srcDC, prevObject);
1279 DeleteObject(hb);
1280 DeleteDC(srcDC);
1281}
1282
1283int GAPI_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
1284{
1285 GAPI_CreatePalette(ncolors, colors);
1286 return 1;
1287}
diff --git a/apps/plugins/sdl/src/video/gapi/SDL_gapivideo.h b/apps/plugins/sdl/src/video/gapi/SDL_gapivideo.h
deleted file mode 100644
index 842d098c22..0000000000
--- a/apps/plugins/sdl/src/video/gapi/SDL_gapivideo.h
+++ /dev/null
@@ -1,160 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_gapivideo_h
25#define _SDL_gapivideo_h
26
27#include "SDL_mouse.h"
28#include "SDL_mutex.h"
29#include "../SDL_sysvideo.h"
30#include "../windib/SDL_gapidibvideo.h"
31
32/* From gx.h, since it's not really C compliant */
33
34struct GXDisplayProperties {
35 DWORD cxWidth;
36 DWORD cyHeight; // notice lack of 'th' in the word height.
37 long cbxPitch; // number of bytes to move right one x pixel - can be negative.
38 long cbyPitch; // number of bytes to move down one y pixel - can be negative.
39 long cBPP; // # of bits in each pixel
40 DWORD ffFormat; // format flags.
41};
42
43struct GXKeyList {
44 short vkUp; // key for up
45 POINT ptUp; // x,y position of key/button. Not on screen but in screen coordinates.
46 short vkDown;
47 POINT ptDown;
48 short vkLeft;
49 POINT ptLeft;
50 short vkRight;
51 POINT ptRight;
52 short vkA;
53 POINT ptA;
54 short vkB;
55 POINT ptB;
56 short vkC;
57 POINT ptC;
58 short vkStart;
59 POINT ptStart;
60};
61
62typedef int (*PFNGXOpenDisplay)(HWND hWnd, DWORD dwFlags);
63typedef int (*PFNGXCloseDisplay)();
64typedef void* (*PFNGXBeginDraw)();
65typedef int (*PFNGXEndDraw)();
66typedef int (*PFNGXOpenInput)();
67typedef int (*PFNGXCloseInput)();
68typedef struct GXDisplayProperties (*PFNGXGetDisplayProperties)();
69typedef struct GXKeyList (*PFNGXGetDefaultKeys)(int iOptions);
70typedef int (*PFNGXSuspend)();
71typedef int (*PFNGXResume)();
72typedef int (*PFNGXSetViewport)( DWORD dwTop, DWORD dwHeight, DWORD dwReserved1, DWORD dwReserved2 );
73typedef BOOL (*PFNGXIsDisplayDRAMBuffer)();
74
75struct GapiFunc
76{
77 PFNGXOpenDisplay GXOpenDisplay;
78 PFNGXCloseDisplay GXCloseDisplay;
79 PFNGXBeginDraw GXBeginDraw;
80 PFNGXEndDraw GXEndDraw;
81 PFNGXOpenInput GXOpenInput;
82 PFNGXCloseInput GXCloseInput;
83 PFNGXGetDisplayProperties GXGetDisplayProperties;
84 PFNGXGetDefaultKeys GXGetDefaultKeys;
85 PFNGXSuspend GXSuspend;
86 PFNGXResume GXResume;
87 PFNGXSetViewport GXSetViewport;
88 PFNGXIsDisplayDRAMBuffer GXIsDisplayDRAMBuffer;
89};
90
91#define kfLandscape 0x8 // Screen is rotated 270 degrees
92#define kfPalette 0x10 // Pixel values are indexes into a palette
93#define kfDirect 0x20 // Pixel values contain actual level information
94#define kfDirect555 0x40 // 5 bits each for red, green and blue values in a pixel.
95#define kfDirect565 0x80 // 5 red bits, 6 green bits and 5 blue bits per pixel
96#define kfDirect888 0x100 // 8 bits each for red, green and blue values in a pixel.
97#define kfDirect444 0x200 // 4 red, 4 green, 4 blue
98#define kfDirectInverted 0x400
99
100#define GX_FULLSCREEN 0x01 // for OpenDisplay()
101#define GX_NORMALKEYS 0x02
102#define GX_LANDSCAPEKEYS 0x03
103
104
105/* GAPI video mode */
106typedef enum {
107 GAPI_NONE = 0,
108 GAPI_DIRECT_565,
109 GAPI_DIRECT_555,
110 GAPI_MONO,
111 GAPI_PALETTE
112} GAPIVideoMode;
113
114typedef unsigned short PIXEL;
115
116/* Private display data
117 begin with DIB private structure to allow DIB events code sharing
118*/
119struct GapiInfo {
120 /* Rotation which has to be applied to the key (arrow keys) and mouse events measured in quarters of a circle
121 * counter clockwise */
122 int coordinateTransform;
123 char hiresFix; /* using hires mode without defining hires resource */
124 int invert; //TODO this is only written but never read, so it should be removed
125
126#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
127 int SDL_nummodes[NUM_MODELISTS];
128 SDL_Rect **SDL_modelist[NUM_MODELISTS];
129
130
131 // The orientation of the video mode user wants to get
132 // Probably restricted to UP and RIGHT
133 SDL_ScreenOrientation userOrientation;
134 SDL_ScreenOrientation systemOrientation;
135// --------------
136 int useGXOpenDisplay; /* use GXOpenDispplay */
137 int alreadyGXOpened;
138 int w, h;
139 // The orientation of GAPI framebuffer.
140 // Never changes on the same device.
141 SDL_ScreenOrientation gapiOrientation;
142
143 void *buffer; // may be 8, 16, 24, 32 bpp
144 PIXEL *videoMem;
145 BOOL needUpdate;
146 struct GXKeyList keyList;
147 struct GapiFunc gxFunc;
148 struct GXDisplayProperties gxProperties;
149 GAPIVideoMode videoMode;
150 int colorscale;
151 int dstLineStep; // in bytes
152 int dstPixelStep; // in bytes
153 int startOffset; // in bytes
154 int useVga;
155 int suspended; // do not pu anything into video memory
156};
157
158
159
160#endif /* _SDL_gapivideo_h */
diff --git a/apps/plugins/sdl/src/video/gem/SDL_gemevents.c b/apps/plugins/sdl/src/video/gem/SDL_gemevents.c
deleted file mode 100644
index c5a505de14..0000000000
--- a/apps/plugins/sdl/src/video/gem/SDL_gemevents.c
+++ /dev/null
@@ -1,375 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * GEM SDL video driver implementation
26 * inspired from the Dummy SDL driver
27 *
28 * Patrice Mandin
29 * and work from
30 * Olivier Landemarre, Johan Klockars, Xavier Joubert, Claude Attard
31 */
32
33#include <gem.h>
34
35#include "../../events/SDL_sysevents.h"
36#include "../../events/SDL_events_c.h"
37#include "SDL_gemvideo.h"
38#include "SDL_gemevents_c.h"
39#include "SDL_gemmouse_c.h"
40#include "../ataricommon/SDL_atarikeys.h" /* for keyboard scancodes */
41#include "../ataricommon/SDL_atarievents_c.h"
42#include "../ataricommon/SDL_xbiosevents_c.h"
43#include "../ataricommon/SDL_ataridevmouse_c.h"
44
45/* Variables */
46
47static unsigned char gem_currentkeyboard[ATARIBIOS_MAXKEYS];
48static unsigned char gem_previouskeyboard[ATARIBIOS_MAXKEYS];
49
50/* Functions prototypes */
51
52static int do_messages(_THIS, short *message);
53static void do_keyboard(short kc, short ks);
54static void do_mouse(_THIS, short mx, short my, short mb, short ks);
55
56/* Functions */
57
58void GEM_InitOSKeymap(_THIS)
59{
60 SDL_memset(gem_currentkeyboard, 0, sizeof(gem_currentkeyboard));
61 SDL_memset(gem_previouskeyboard, 0, sizeof(gem_previouskeyboard));
62
63 /* Mouse init */
64 GEM_mouse_relative = SDL_FALSE;
65
66 SDL_Atari_InitInternalKeymap(this);
67}
68
69void GEM_PumpEvents(_THIS)
70{
71 short prevkc, prevks;
72 static short maskmouseb=0;
73 int i;
74 SDL_keysym keysym;
75
76 SDL_memset(gem_currentkeyboard,0,sizeof(gem_currentkeyboard));
77 prevkc = prevks = 0;
78
79 for (;;)
80 {
81 int quit, resultat, event_mask, mouse_event;
82 short buffer[8], kc;
83 short x2,y2,w2,h2;
84 short mousex, mousey, mouseb, dummy;
85 short kstate;
86
87 quit =
88 mouse_event =
89 x2=y2=w2=h2 = 0;
90
91 event_mask = MU_MESAG|MU_TIMER|MU_KEYBD|MU_BUTTON;
92 if (!GEM_fullscreen && (GEM_handle>=0)) {
93 wind_get (GEM_handle, WF_WORKXYWH, &x2, &y2, &w2, &h2);
94 event_mask |= MU_M1;
95 mouse_event = ( (SDL_GetAppState() & SDL_APPMOUSEFOCUS)
96 == SDL_APPMOUSEFOCUS) ? MO_LEAVE : MO_ENTER;
97 }
98
99 resultat = evnt_multi(
100 event_mask,
101 0x101,7,maskmouseb,
102 mouse_event,x2,y2,w2,h2,
103 0,0,0,0,0,
104 buffer,
105 10,
106 &mousex,&mousey,&mouseb,&kstate,&kc,&dummy
107 );
108
109 /* Message event ? */
110 if (resultat & MU_MESAG)
111 quit = do_messages(this, buffer);
112
113 /* Keyboard event ? */
114 if (resultat & MU_KEYBD) {
115 if ((prevkc != kc) || (prevks != kstate)) {
116 do_keyboard(kc,kstate);
117 } else {
118 /* Avoid looping, if repeating same key */
119 break;
120 }
121 }
122
123 /* Mouse entering/leaving window */
124 if (resultat & MU_M1) {
125 if (this->input_grab == SDL_GRAB_OFF) {
126 /* Switch mouse focus state */
127 SDL_PrivateAppActive((mouse_event == MO_ENTER),
128 SDL_APPMOUSEFOCUS);
129 }
130 GEM_CheckMouseMode(this);
131 }
132
133 /* Mouse button event ? */
134 if (resultat & MU_BUTTON) {
135 do_mouse(this, mousex, mousey, mouseb, kstate);
136 maskmouseb = mouseb & 7;
137 }
138
139 /* Timer event ? */
140 if ((resultat & MU_TIMER) || quit)
141 break;
142 }
143
144 /* Now generate keyboard events */
145 for (i=0; i<ATARIBIOS_MAXKEYS; i++) {
146 /* Key pressed ? */
147 if (gem_currentkeyboard[i] && !gem_previouskeyboard[i])
148 SDL_PrivateKeyboard(SDL_PRESSED,
149 SDL_Atari_TranslateKey(i, &keysym, SDL_TRUE));
150
151 /* Key unpressed ? */
152 if (gem_previouskeyboard[i] && !gem_currentkeyboard[i])
153 SDL_PrivateKeyboard(SDL_RELEASED,
154 SDL_Atari_TranslateKey(i, &keysym, SDL_FALSE));
155 }
156
157 SDL_memcpy(gem_previouskeyboard,gem_currentkeyboard,sizeof(gem_previouskeyboard));
158
159 /* Refresh window name ? */
160 if (GEM_refresh_name) {
161 const char *window_name =
162 (SDL_GetAppState() & SDL_APPACTIVE)
163 ? GEM_title_name : GEM_icon_name;
164 if (window_name) {
165 wind_set(GEM_handle,WF_NAME,
166 (short)(((unsigned long)window_name)>>16),
167 (short)(((unsigned long)window_name) & 0xffff),
168 0,0);
169 }
170 GEM_refresh_name = SDL_FALSE;
171 }
172}
173
174static int do_messages(_THIS, short *message)
175{
176 int quit, check_mouse_mode;
177 short x2,y2,w2,h2;
178
179 quit = check_mouse_mode = 0;
180 switch (message[0]) {
181 case WM_CLOSED:
182 case AP_TERM:
183 SDL_PrivateQuit();
184 quit=1;
185 break;
186 case WM_MOVED:
187 wind_set(message[3],WF_CURRXYWH,message[4],message[5],message[6],message[7]);
188 break;
189 case WM_TOPPED:
190 wind_set(message[3],WF_TOP,message[4],0,0,0);
191 /* Continue with TOP event processing */
192 case WM_ONTOP:
193 SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS);
194 if (VDI_setpalette) {
195 VDI_setpalette(this, VDI_curpalette);
196 }
197 check_mouse_mode = 1;
198 break;
199 case WM_REDRAW:
200 if (!GEM_lock_redraw) {
201 GEM_wind_redraw(this, message[3],&message[4]);
202 }
203 break;
204 case WM_ICONIFY:
205 case WM_ALLICONIFY:
206 wind_set(message[3],WF_ICONIFY,message[4],message[5],message[6],message[7]);
207 /* If we're active, make ourselves inactive */
208 if ( SDL_GetAppState() & SDL_APPACTIVE ) {
209 /* Send an internal deactivate event */
210 SDL_PrivateAppActive(0, SDL_APPACTIVE);
211 }
212 /* Update window title */
213 if (GEM_refresh_name && GEM_icon_name) {
214 wind_set(GEM_handle,WF_NAME,(short)(((unsigned long)GEM_icon_name)>>16),(short)(((unsigned long)GEM_icon_name) & 0xffff),0,0);
215 GEM_refresh_name = SDL_FALSE;
216 }
217 check_mouse_mode = 1;
218 break;
219 case WM_UNICONIFY:
220 wind_set(message[3],WF_UNICONIFY,message[4],message[5],message[6],message[7]);
221 /* If we're not active, make ourselves active */
222 if ( !(SDL_GetAppState() & SDL_APPACTIVE) ) {
223 /* Send an internal activate event */
224 SDL_PrivateAppActive(1, SDL_APPACTIVE);
225 }
226 if (GEM_refresh_name && GEM_title_name) {
227 wind_set(GEM_handle,WF_NAME,(short)(((unsigned long)GEM_title_name)>>16),(short)(((unsigned long)GEM_title_name) & 0xffff),0,0);
228 GEM_refresh_name = SDL_FALSE;
229 }
230 check_mouse_mode = 1;
231 break;
232 case WM_SIZED:
233 wind_set (message[3], WF_CURRXYWH, message[4], message[5], message[6], message[7]);
234 wind_get (message[3], WF_WORKXYWH, &x2, &y2, &w2, &h2);
235 GEM_win_fulled = SDL_FALSE; /* Cancel maximized flag */
236 GEM_lock_redraw = SDL_TRUE; /* Prevent redraw till buffers resized */
237 SDL_PrivateResize(w2, h2);
238 break;
239 case WM_FULLED:
240 {
241 short x,y,w,h;
242
243 if (GEM_win_fulled) {
244 wind_get (message[3], WF_PREVXYWH, &x, &y, &w, &h);
245 GEM_win_fulled = SDL_FALSE;
246 } else {
247 x = GEM_desk_x;
248 y = GEM_desk_y;
249 w = GEM_desk_w;
250 h = GEM_desk_h;
251 GEM_win_fulled = SDL_TRUE;
252 }
253 wind_set (message[3], WF_CURRXYWH, x, y, w, h);
254 wind_get (message[3], WF_WORKXYWH, &x2, &y2, &w2, &h2);
255 GEM_lock_redraw = SDL_TRUE; /* Prevent redraw till buffers resized */
256 SDL_PrivateResize(w2, h2);
257 }
258 break;
259 case WM_BOTTOMED:
260 wind_set(message[3],WF_BOTTOM,0,0,0,0);
261 /* Continue with BOTTOM event processing */
262 case WM_UNTOPPED:
263 SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS);
264 if (VDI_setpalette) {
265 VDI_setpalette(this, VDI_oldpalette);
266 }
267 check_mouse_mode = 1;
268 break;
269 }
270
271 if (check_mouse_mode) {
272 GEM_CheckMouseMode(this);
273 }
274
275 return quit;
276}
277
278static void do_keyboard(short kc, short ks)
279{
280 int scancode;
281
282 if (kc) {
283 scancode=(kc>>8) & (ATARIBIOS_MAXKEYS-1);
284 gem_currentkeyboard[scancode]=0xFF;
285 }
286
287 /* Read special keys */
288 if (ks & K_RSHIFT)
289 gem_currentkeyboard[SCANCODE_RIGHTSHIFT]=0xFF;
290 if (ks & K_LSHIFT)
291 gem_currentkeyboard[SCANCODE_LEFTSHIFT]=0xFF;
292 if (ks & K_CTRL)
293 gem_currentkeyboard[SCANCODE_LEFTCONTROL]=0xFF;
294 if (ks & K_ALT)
295 gem_currentkeyboard[SCANCODE_LEFTALT]=0xFF;
296}
297
298static void do_mouse(_THIS, short mx, short my, short mb, short ks)
299{
300 static short prevmousex=0, prevmousey=0, prevmouseb=0;
301 short x2, y2, w2, h2;
302
303 /* Don't return mouse events if out of window */
304 if ((SDL_GetAppState() & SDL_APPMOUSEFOCUS)==0) {
305 return;
306 }
307
308 /* Retrieve window coords, and generate mouse events accordingly */
309 x2 = y2 = 0;
310 w2 = VDI_w;
311 h2 = VDI_h;
312 if ((!GEM_fullscreen) && (GEM_handle>=0)) {
313 wind_get (GEM_handle, WF_WORKXYWH, &x2, &y2, &w2, &h2);
314
315 /* Do not generate mouse button event if out of window working area */
316 if ((mx<x2) || (mx>=x2+w2) || (my<y2) || (my>=y2+h2)) {
317 mb=prevmouseb;
318 }
319 }
320
321 /* Mouse motion ? */
322 if (GEM_mouse_relative) {
323 if (GEM_usedevmouse) {
324 SDL_AtariDevMouse_PostMouseEvents(this, SDL_FALSE);
325 } else {
326 SDL_AtariXbios_PostMouseEvents(this, SDL_FALSE);
327 }
328 } else {
329 if ((prevmousex!=mx) || (prevmousey!=my)) {
330 int posx, posy;
331
332 /* Give mouse position relative to window position */
333 posx = mx - x2;
334 if (posx<0) posx = 0;
335 if (posx>w2) posx = w2-1;
336 posy = my - y2;
337 if (posy<0) posy = 0;
338 if (posy>h2) posy = h2-1;
339
340 SDL_PrivateMouseMotion(0, 0, posx, posy);
341 }
342 prevmousex = mx;
343 prevmousey = my;
344 }
345
346 /* Mouse button ? */
347 if (prevmouseb!=mb) {
348 int i;
349
350 for (i=0;i<3;i++) {
351 int curbutton, prevbutton;
352
353 curbutton = mb & (1<<i);
354 prevbutton = prevmouseb & (1<<i);
355
356 if (curbutton && !prevbutton) {
357 SDL_PrivateMouseButton(SDL_PRESSED, i+1, 0, 0);
358 }
359 if (!curbutton && prevbutton) {
360 SDL_PrivateMouseButton(SDL_RELEASED, i+1, 0, 0);
361 }
362 }
363 prevmouseb = mb;
364 }
365
366 /* Read special keys */
367 if (ks & K_RSHIFT)
368 gem_currentkeyboard[SCANCODE_RIGHTSHIFT]=0xFF;
369 if (ks & K_LSHIFT)
370 gem_currentkeyboard[SCANCODE_LEFTSHIFT]=0xFF;
371 if (ks & K_CTRL)
372 gem_currentkeyboard[SCANCODE_LEFTCONTROL]=0xFF;
373 if (ks & K_ALT)
374 gem_currentkeyboard[SCANCODE_LEFTALT]=0xFF;
375}
diff --git a/apps/plugins/sdl/src/video/gem/SDL_gemevents_c.h b/apps/plugins/sdl/src/video/gem/SDL_gemevents_c.h
deleted file mode 100644
index 7d5d9b3a1d..0000000000
--- a/apps/plugins/sdl/src/video/gem/SDL_gemevents_c.h
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_gemvideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c) */
28
29extern void GEM_InitOSKeymap(_THIS);
30extern void GEM_PumpEvents(_THIS);
31
32/* end of SDL_gemevents_c.h */
33
diff --git a/apps/plugins/sdl/src/video/gem/SDL_gemmouse.c b/apps/plugins/sdl/src/video/gem/SDL_gemmouse.c
deleted file mode 100644
index c876cffe57..0000000000
--- a/apps/plugins/sdl/src/video/gem/SDL_gemmouse.c
+++ /dev/null
@@ -1,205 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * GEM Mouse manager
26 *
27 * Patrice Mandin
28 */
29
30#include <gem.h>
31
32#include "SDL_mouse.h"
33#include "../../events/SDL_events_c.h"
34#include "../SDL_cursor_c.h"
35#include "SDL_gemmouse_c.h"
36#include "SDL_gemvideo.h"
37#include "../ataricommon/SDL_xbiosevents_c.h"
38
39/* Defines */
40
41/*#define DEBUG_VIDEO_GEM 1*/
42
43#define MAXCURWIDTH 16
44#define MAXCURHEIGHT 16
45
46void GEM_FreeWMCursor(_THIS, WMcursor *cursor)
47{
48#ifdef DEBUG_VIDEO_GEM
49 printf("sdl:video:gem: free cursor\n");
50#endif
51
52 if (cursor == NULL)
53 return;
54
55 graf_mouse(ARROW, NULL);
56
57 if (cursor->mform_p != NULL)
58 SDL_free(cursor->mform_p);
59
60 SDL_free(cursor);
61}
62
63WMcursor *GEM_CreateWMCursor(_THIS,
64 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
65{
66 WMcursor *cursor;
67 MFORM *new_mform;
68 int i;
69
70#ifdef DEBUG_VIDEO_GEM
71 Uint16 *data1, *mask1;
72
73 printf("sdl:video:gem: create cursor\n");
74#endif
75
76 /* Check the size */
77 if ( (w > MAXCURWIDTH) || (h > MAXCURHEIGHT) ) {
78 SDL_SetError("Only cursors of dimension (%dx%d) are allowed",
79 MAXCURWIDTH, MAXCURHEIGHT);
80 return(NULL);
81 }
82
83 /* Allocate the cursor memory */
84 cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor));
85 if ( cursor == NULL ) {
86 SDL_OutOfMemory();
87 return(NULL);
88 }
89
90 /* Allocate mform */
91 new_mform = (MFORM *)SDL_malloc(sizeof(MFORM));
92 if (new_mform == NULL) {
93 SDL_free(cursor);
94 SDL_OutOfMemory();
95 return(NULL);
96 }
97
98 cursor->mform_p = new_mform;
99
100 new_mform->mf_xhot = hot_x;
101 new_mform->mf_yhot = hot_y;
102 new_mform->mf_nplanes = 1;
103 new_mform->mf_fg = 0;
104 new_mform->mf_bg = 1;
105
106 for (i=0;i<MAXCURHEIGHT;i++) {
107 new_mform->mf_mask[i]=0;
108 new_mform->mf_data[i]=0;
109#ifdef DEBUG_VIDEO_GEM
110 data1 = (Uint16 *) &data[i<<1];
111 mask1 = (Uint16 *) &mask[i<<1];
112 printf("sdl:video:gem: source: line %d: data=0x%04x, mask=0x%04x\n",
113 i, data1[i], mask1[i]);
114#endif
115 }
116
117 if (w<=8) {
118 for (i=0;i<h;i++) {
119 new_mform->mf_mask[i]= mask[i]<<8;
120 new_mform->mf_data[i]= data[i]<<8;
121 }
122 } else {
123 for (i=0;i<h;i++) {
124 new_mform->mf_mask[i]= (mask[i<<1]<<8) | mask[(i<<1)+1];
125 new_mform->mf_data[i]= (data[i<<1]<<8) | data[(i<<1)+1];
126 }
127 }
128
129#ifdef DEBUG_VIDEO_GEM
130 for (i=0; i<h ;i++) {
131 printf("sdl:video:gem: cursor: line %d: data=0x%04x, mask=0x%04x\n",
132 i, new_mform->mf_data[i], new_mform->mf_mask[i]);
133 }
134
135 printf("sdl:video:gem: CreateWMCursor(): done\n");
136#endif
137
138 return cursor;
139}
140
141int GEM_ShowWMCursor(_THIS, WMcursor *cursor)
142{
143 GEM_cursor = cursor;
144
145 GEM_CheckMouseMode(this);
146
147#ifdef DEBUG_VIDEO_GEM
148 printf("sdl:video:gem: ShowWMCursor(0x%08x)\n", (long) cursor);
149#endif
150
151 return 1;
152}
153
154#if 0
155void GEM_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
156{
157 /* This seems to work only on AES 3.4 (Falcon) */
158
159 EVNTREC warpevent;
160
161 warpevent.ap_event = APPEVNT_MOUSE;
162 warpevent.ap_value = (x << 16) | y;
163
164 appl_tplay(&warpevent, 1, 1000);
165}
166#endif
167
168void GEM_CheckMouseMode(_THIS)
169{
170 const Uint8 full_focus = (SDL_APPACTIVE|SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS);
171 int set_system_cursor = 1, show_system_cursor = 1;
172
173#ifdef DEBUG_VIDEO_GEM
174 printf("sdl:video:gem: check mouse mode\n");
175#endif
176
177 /* If the mouse is hidden and input is grabbed, we use relative mode */
178 GEM_mouse_relative = (!(SDL_cursorstate & CURSOR_VISIBLE))
179 && (this->input_grab != SDL_GRAB_OFF)
180 && (SDL_GetAppState() & SDL_APPACTIVE);
181 SDL_AtariXbios_LockMousePosition(GEM_mouse_relative);
182
183 if (SDL_cursorstate & CURSOR_VISIBLE) {
184 /* Application defined cursor only over the application window */
185 if ((SDL_GetAppState() & full_focus) == full_focus) {
186 if (GEM_cursor) {
187 graf_mouse(USER_DEF, GEM_cursor->mform_p);
188 set_system_cursor = 0;
189 } else {
190 show_system_cursor = 0;
191 }
192 }
193 } else {
194 /* Mouse cursor hidden only over the application window */
195 if ((SDL_GetAppState() & full_focus) == full_focus) {
196 set_system_cursor = 0;
197 show_system_cursor = 0;
198 }
199 }
200
201 graf_mouse(show_system_cursor ? M_ON : M_OFF, NULL);
202 if (set_system_cursor) {
203 graf_mouse(ARROW, NULL);
204 }
205}
diff --git a/apps/plugins/sdl/src/video/gem/SDL_gemmouse_c.h b/apps/plugins/sdl/src/video/gem/SDL_gemmouse_c.h
deleted file mode 100644
index 06f90ba5e5..0000000000
--- a/apps/plugins/sdl/src/video/gem/SDL_gemmouse_c.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_gemvideo.h"
25
26/* Functions to be exported */
27extern void GEM_FreeWMCursor(_THIS, WMcursor *cursor);
28extern WMcursor *GEM_CreateWMCursor(_THIS,
29 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
30extern int GEM_ShowWMCursor(_THIS, WMcursor *cursor);
31#if 0
32extern void GEM_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
33#endif
34extern void GEM_CheckMouseMode(_THIS);
diff --git a/apps/plugins/sdl/src/video/gem/SDL_gemvideo.c b/apps/plugins/sdl/src/video/gem/SDL_gemvideo.c
deleted file mode 100644
index 2ce9151c1d..0000000000
--- a/apps/plugins/sdl/src/video/gem/SDL_gemvideo.c
+++ /dev/null
@@ -1,1337 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 GEM video driver
26
27 Patrice Mandin
28 and work from
29 Olivier Landemarre, Johan Klockars, Xavier Joubert, Claude Attard
30*/
31
32/* Mint includes */
33#include <gem.h>
34#include <gemx.h>
35#include <mint/osbind.h>
36#include <mint/cookie.h>
37
38#include "SDL_endian.h"
39#include "SDL_video.h"
40#include "SDL_mouse.h"
41#include "../SDL_sysvideo.h"
42#include "../SDL_pixels_c.h"
43#include "../../events/SDL_events_c.h"
44#include "../SDL_cursor_c.h"
45
46#include "../ataricommon/SDL_ataric2p_s.h"
47#include "../ataricommon/SDL_atarieddi_s.h"
48#include "../ataricommon/SDL_atarimxalloc_c.h"
49#include "../ataricommon/SDL_atarigl_c.h"
50
51#include "SDL_gemvideo.h"
52#include "SDL_gemevents_c.h"
53#include "SDL_gemmouse_c.h"
54#include "SDL_gemwm_c.h"
55#include "../ataricommon/SDL_xbiosevents_c.h"
56#include "../ataricommon/SDL_ataridevmouse_c.h"
57
58/* Defines */
59
60/*#define DEBUG_VIDEO_GEM 1*/
61
62#define GEM_VID_DRIVER_NAME "gem"
63
64#undef MIN
65#define MIN(a,b) (((a)<(b)) ? (a) : (b))
66#undef MAX
67#define MAX(a,b) (((a)>(b)) ? (a) : (b))
68
69/* Variables */
70
71static unsigned char vdi_index[256] = {
72 0, 2, 3, 6, 4, 7, 5, 8,
73 9, 10, 11, 14, 12, 15, 13, 255
74};
75
76static const char empty_name[]="";
77
78/* Initialization/Query functions */
79static int GEM_VideoInit(_THIS, SDL_PixelFormat *vformat);
80static SDL_Rect **GEM_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
81static SDL_Surface *GEM_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
82static int GEM_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
83static void GEM_VideoQuit(_THIS);
84
85/* Hardware surface functions */
86static int GEM_AllocHWSurface(_THIS, SDL_Surface *surface);
87static int GEM_LockHWSurface(_THIS, SDL_Surface *surface);
88static int GEM_FlipHWSurface(_THIS, SDL_Surface *surface);
89static void GEM_UnlockHWSurface(_THIS, SDL_Surface *surface);
90static void GEM_FreeHWSurface(_THIS, SDL_Surface *surface);
91static void GEM_UpdateRects(_THIS, int numrects, SDL_Rect *rects);
92#if 0
93static int GEM_ToggleFullScreen(_THIS, int on);
94#endif
95
96/* Internal functions */
97static void GEM_FreeBuffers(_THIS);
98static void GEM_ClearScreen(_THIS);
99static void GEM_ClearRect(_THIS, short *rect);
100static void GEM_SetNewPalette(_THIS, Uint16 newpal[256][3]);
101static void GEM_LockScreen(_THIS);
102static void GEM_UnlockScreen(_THIS);
103static void refresh_window(_THIS, int winhandle, short *rect);
104
105#if SDL_VIDEO_OPENGL
106/* OpenGL functions */
107static void GEM_GL_SwapBuffers(_THIS);
108#endif
109
110/* GEM driver bootstrap functions */
111
112static int GEM_Available(void)
113{
114 /* Test if AES available */
115 if (appl_init() == -1)
116 return 0;
117
118 appl_exit();
119 return 1;
120}
121
122static void GEM_DeleteDevice(SDL_VideoDevice *device)
123{
124 SDL_free(device->hidden);
125 SDL_free(device);
126}
127
128static SDL_VideoDevice *GEM_CreateDevice(int devindex)
129{
130 SDL_VideoDevice *device;
131 int vectors_mask;
132/* unsigned long dummy;*/
133
134 /* Initialize all variables that we clean on shutdown */
135 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
136 if ( device ) {
137 SDL_memset(device, 0, (sizeof *device));
138 device->hidden = (struct SDL_PrivateVideoData *)
139 SDL_malloc((sizeof *device->hidden));
140 device->gl_data = (struct SDL_PrivateGLData *)
141 SDL_malloc((sizeof *device->gl_data));
142 }
143 if ( (device == NULL) || (device->hidden == NULL) ) {
144 SDL_OutOfMemory();
145 if ( device ) {
146 SDL_free(device);
147 }
148 return(0);
149 }
150 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
151 SDL_memset(device->gl_data, 0, sizeof(*device->gl_data));
152
153 /* Set the function pointers */
154 device->VideoInit = GEM_VideoInit;
155 device->ListModes = GEM_ListModes;
156 device->SetVideoMode = GEM_SetVideoMode;
157 device->SetColors = GEM_SetColors;
158 device->UpdateRects = NULL /*GEM_UpdateRects*/;
159 device->VideoQuit = GEM_VideoQuit;
160 device->AllocHWSurface = GEM_AllocHWSurface;
161 device->LockHWSurface = GEM_LockHWSurface;
162 device->UnlockHWSurface = GEM_UnlockHWSurface;
163 device->FlipHWSurface = GEM_FlipHWSurface;
164 device->FreeHWSurface = GEM_FreeHWSurface;
165 device->ToggleFullScreen = NULL /*GEM_ToggleFullScreen*/;
166
167 /* Window manager */
168 device->SetCaption = GEM_SetCaption;
169 device->SetIcon = GEM_SetIcon;
170 device->IconifyWindow = GEM_IconifyWindow;
171 device->GrabInput = GEM_GrabInput;
172
173 /* Events */
174 device->InitOSKeymap = GEM_InitOSKeymap;
175 device->PumpEvents = GEM_PumpEvents;
176
177 /* Mouse */
178 device->FreeWMCursor = GEM_FreeWMCursor;
179 device->CreateWMCursor = GEM_CreateWMCursor;
180 device->ShowWMCursor = GEM_ShowWMCursor;
181 device->WarpWMCursor = NULL /*GEM_WarpWMCursor*/;
182 device->CheckMouseMode = GEM_CheckMouseMode;
183
184#if SDL_VIDEO_OPENGL
185 /* OpenGL functions */
186 device->GL_LoadLibrary = SDL_AtariGL_LoadLibrary;
187 device->GL_GetProcAddress = SDL_AtariGL_GetProcAddress;
188 device->GL_GetAttribute = SDL_AtariGL_GetAttribute;
189 device->GL_MakeCurrent = SDL_AtariGL_MakeCurrent;
190 device->GL_SwapBuffers = GEM_GL_SwapBuffers;
191#endif
192
193 device->hidden->use_dev_mouse =
194 (SDL_AtariDevMouse_Open()!=0) ? SDL_TRUE : SDL_FALSE;
195
196 vectors_mask = ATARI_XBIOS_JOYSTICKEVENTS; /* XBIOS joystick events */
197 if (!(device->hidden->use_dev_mouse)) {
198 vectors_mask |= ATARI_XBIOS_MOUSEEVENTS; /* XBIOS mouse events */
199 }
200/* if (Getcookie(C_MiNT, &dummy)==C_FOUND) {
201 vectors_mask = 0;
202 }*/
203
204 SDL_AtariXbios_InstallVectors(vectors_mask);
205
206 device->free = GEM_DeleteDevice;
207
208 return device;
209}
210
211VideoBootStrap GEM_bootstrap = {
212 GEM_VID_DRIVER_NAME, "Atari GEM video driver",
213 GEM_Available, GEM_CreateDevice
214};
215
216static void VDI_ReadExtInfo(_THIS, short *work_out)
217{
218 unsigned long EdDI_version;
219 long cookie_EdDI;
220 Uint16 clut_type;
221
222 /* Read EdDI informations */
223 if (Getcookie(C_EdDI, &cookie_EdDI) == C_NOTFOUND) {
224 return;
225 }
226
227 EdDI_version = Atari_get_EdDI_version( (void *)cookie_EdDI);
228
229 vq_scrninfo(VDI_handle, work_out);
230
231 VDI_format = work_out[0];
232 clut_type = work_out[1];
233
234 /* With EdDI>=1.1, we can have screen pitch, address and format
235 * so we can directly write to screen without using vro_cpyfm
236 */
237 if (EdDI_version >= EDDI_11) {
238 VDI_pitch = work_out[5];
239 VDI_screen = (void *) *((unsigned long *) &work_out[6]);
240 }
241
242 switch(clut_type) {
243 case VDI_CLUT_HARDWARE:
244 {
245 int i;
246 Uint16 *tmp_p;
247
248 tmp_p = (Uint16 *)&work_out[16];
249
250 for (i=0;i<256;i++) {
251 vdi_index[*tmp_p++] = i;
252 }
253 }
254 break;
255 case VDI_CLUT_SOFTWARE:
256 {
257 int component; /* red, green, blue, alpha, overlay */
258 int num_bit;
259 unsigned short *tmp_p;
260
261 /* We can build masks with info here */
262 tmp_p = (unsigned short *) &work_out[16];
263 for (component=0;component<5;component++) {
264 for (num_bit=0;num_bit<16;num_bit++) {
265 unsigned short valeur;
266
267 valeur = *tmp_p++;
268
269 if (valeur == 0xffff) {
270 continue;
271 }
272
273 switch(component) {
274 case 0:
275 VDI_redmask |= 1<< valeur;
276 break;
277 case 1:
278 VDI_greenmask |= 1<< valeur;
279 break;
280 case 2:
281 VDI_bluemask |= 1<< valeur;
282 break;
283 case 3:
284 VDI_alphamask |= 1<< valeur;
285 break;
286 }
287 }
288 }
289 }
290
291 /* Remove lower green bits for Intel endian screen */
292 if ((VDI_greenmask == ((7<<13)|3)) || (VDI_greenmask == ((7<<13)|7))) {
293 VDI_greenmask &= ~(7<<13);
294 }
295 break;
296 case VDI_CLUT_NONE:
297 break;
298 }
299}
300
301int GEM_VideoInit(_THIS, SDL_PixelFormat *vformat)
302{
303 int i, menubar_size;
304 short work_in[12], work_out[272], dummy;
305
306 /* Open AES (Application Environment Services) */
307 if (appl_init() == -1) {
308 fprintf(stderr,"Can not open AES\n");
309 return 1;
310 }
311
312 /* Read version and features */
313 GEM_version = aes_global[0];
314 if (GEM_version >= 0x0410) {
315 short ap_gout[4], errorcode;
316
317 GEM_wfeatures=0;
318 errorcode=appl_getinfo(AES_WINDOW, &ap_gout[0], &ap_gout[1], &ap_gout[2], &ap_gout[3]);
319
320 if (errorcode==0) {
321 GEM_wfeatures=ap_gout[0];
322 }
323 }
324
325 /* Ask VDI physical workstation handle opened by AES */
326 VDI_handle = graf_handle(&dummy, &dummy, &dummy, &dummy);
327 if (VDI_handle<1) {
328 fprintf(stderr,"Wrong VDI handle %d returned by AES\n",VDI_handle);
329 return 1;
330 }
331
332 /* Open virtual VDI workstation */
333 work_in[0]=Getrez()+2;
334 for(i = 1; i < 10; i++)
335 work_in[i] = 1;
336 work_in[10] = 2;
337
338 v_opnvwk(work_in, &VDI_handle, work_out);
339 if (VDI_handle == 0) {
340 fprintf(stderr,"Can not open VDI virtual workstation\n");
341 return 1;
342 }
343
344 /* Read fullscreen size */
345 VDI_w = work_out[0] + 1;
346 VDI_h = work_out[1] + 1;
347
348 /* Read desktop size and position */
349 if (!wind_get(DESKTOP_HANDLE, WF_WORKXYWH, &GEM_desk_x, &GEM_desk_y, &GEM_desk_w, &GEM_desk_h)) {
350 fprintf(stderr,"Can not read desktop properties\n");
351 return 1;
352 }
353
354 /* Read bit depth */
355 vq_extnd(VDI_handle, 1, work_out);
356 VDI_bpp = work_out[4];
357 VDI_oldnumcolors=0;
358
359 switch(VDI_bpp) {
360 case 8:
361 VDI_pixelsize=1;
362 break;
363 case 15:
364 case 16:
365 VDI_pixelsize=2;
366 break;
367 case 24:
368 VDI_pixelsize=3;
369 break;
370 case 32:
371 VDI_pixelsize=4;
372 break;
373 default:
374 fprintf(stderr,"%d bits colour depth not supported\n",VDI_bpp);
375 return 1;
376 }
377
378 /* Setup hardware -> VDI palette mapping */
379 for(i = 16; i < 255; i++) {
380 vdi_index[i] = i;
381 }
382 vdi_index[255] = 1;
383
384 /* Save current palette */
385 if (VDI_bpp>8) {
386 VDI_oldnumcolors=1<<8;
387 } else {
388 VDI_oldnumcolors=1<<VDI_bpp;
389 }
390
391 for(i = 0; i < VDI_oldnumcolors; i++) {
392 short rgb[3];
393
394 vq_color(VDI_handle, i, 0, rgb);
395
396 VDI_oldpalette[i][0] = rgb[0];
397 VDI_oldpalette[i][1] = rgb[1];
398 VDI_oldpalette[i][2] = rgb[2];
399 }
400 VDI_setpalette = GEM_SetNewPalette;
401 SDL_memcpy(VDI_curpalette,VDI_oldpalette,sizeof(VDI_curpalette));
402
403 /* Setup screen info */
404 GEM_title_name = empty_name;
405 GEM_icon_name = empty_name;
406
407 GEM_handle = -1;
408 GEM_locked = SDL_FALSE;
409 GEM_win_fulled = SDL_FALSE;
410 GEM_fullscreen = SDL_FALSE;
411 GEM_lock_redraw = SDL_TRUE; /* Prevent redraw till buffers are setup */
412
413 VDI_screen = NULL;
414 VDI_pitch = VDI_w * VDI_pixelsize;
415 VDI_format = ( (VDI_bpp <= 8) ? VDI_FORMAT_INTER : VDI_FORMAT_PACK);
416 VDI_redmask = VDI_greenmask = VDI_bluemask = VDI_alphamask = 0;
417 VDI_ReadExtInfo(this, work_out);
418
419#ifdef DEBUG_VIDEO_GEM
420 printf("sdl:video:gem: screen: address=0x%08x, pitch=%d\n", VDI_screen, VDI_pitch);
421 printf("sdl:video:gem: format=%d\n", VDI_format);
422 printf("sdl:video:gem: masks: 0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
423 VDI_alphamask, VDI_redmask, VDI_greenmask, VDI_bluemask
424 );
425#endif
426
427 /* Setup destination mfdb */
428 VDI_dst_mfdb.fd_addr = NULL;
429
430 /* Determine the current screen size */
431 this->info.current_w = VDI_w;
432 this->info.current_h = VDI_h;
433
434 /* Determine the screen depth */
435 /* we change this during the SDL_SetVideoMode implementation... */
436 vformat->BitsPerPixel = VDI_bpp;
437
438 /* Set mouse cursor to arrow */
439 graf_mouse(ARROW, NULL);
440 GEM_cursor = NULL;
441
442 /* Init chunky to planar routine */
443 SDL_Atari_C2pConvert = SDL_Atari_C2pConvert8;
444
445 /* Setup VDI fill functions */
446 vsf_color(VDI_handle,0);
447 vsf_interior(VDI_handle,1);
448 vsf_perimeter(VDI_handle,0);
449
450 /* Menu bar save buffer */
451 menubar_size = GEM_desk_w * GEM_desk_y * VDI_pixelsize;
452 GEM_menubar=Atari_SysMalloc(menubar_size,MX_PREFTTRAM);
453
454 /* Fill video modes list */
455 SDL_modelist[0] = SDL_malloc(sizeof(SDL_Rect));
456 SDL_modelist[0]->x = 0;
457 SDL_modelist[0]->y = 0;
458 SDL_modelist[0]->w = VDI_w;
459 SDL_modelist[0]->h = VDI_h;
460
461 SDL_modelist[1] = NULL;
462
463#if SDL_VIDEO_OPENGL
464 SDL_AtariGL_InitPointers(this);
465#endif
466
467 this->info.wm_available = 1;
468
469 /* We're done! */
470 return(0);
471}
472
473SDL_Rect **GEM_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
474{
475 if (format->BitsPerPixel != VDI_bpp) {
476 return ((SDL_Rect **)NULL);
477 }
478
479 if (flags & SDL_FULLSCREEN) {
480 return (SDL_modelist);
481 }
482
483 return((SDL_Rect **)-1);
484}
485
486static void GEM_FreeBuffers(_THIS)
487{
488 /* Release buffer */
489 if ( GEM_buffer2 ) {
490 Mfree( GEM_buffer2 );
491 GEM_buffer2=NULL;
492 }
493
494 if ( GEM_buffer1 ) {
495 Mfree( GEM_buffer1 );
496 GEM_buffer1=NULL;
497 }
498}
499
500static void GEM_ClearRect(_THIS, short *rect)
501{
502 short oldrgb[3], rgb[3]={0,0,0};
503
504 vq_color(VDI_handle, vdi_index[0], 0, oldrgb);
505 vs_color(VDI_handle, vdi_index[0], rgb);
506
507 vsf_color(VDI_handle,0);
508 vsf_interior(VDI_handle,1);
509 vsf_perimeter(VDI_handle,0);
510 v_bar(VDI_handle, rect);
511
512 vs_color(VDI_handle, vdi_index[0], oldrgb);
513}
514
515static void GEM_ClearScreen(_THIS)
516{
517 short pxy[4];
518
519 v_hide_c(VDI_handle);
520
521 pxy[0] = pxy[1] = 0;
522 pxy[2] = VDI_w - 1;
523 pxy[3] = VDI_h - 1;
524 GEM_ClearRect(this, pxy);
525
526 v_show_c(VDI_handle, 1);
527}
528
529static void GEM_SetNewPalette(_THIS, Uint16 newpal[256][3])
530{
531 int i;
532 short rgb[3];
533
534 if (VDI_oldnumcolors==0)
535 return;
536
537 for(i = 0; i < VDI_oldnumcolors; i++) {
538 rgb[0] = newpal[i][0];
539 rgb[1] = newpal[i][1];
540 rgb[2] = newpal[i][2];
541
542 vs_color(VDI_handle, i, rgb);
543 }
544}
545
546static void GEM_LockScreen(_THIS)
547{
548 if (!GEM_locked) {
549 /* Lock AES */
550 wind_update(BEG_UPDATE);
551 wind_update(BEG_MCTRL);
552 /* Reserve memory space, used to be sure of compatibility */
553 form_dial( FMD_START, 0,0,0,0, 0,0,VDI_w,VDI_h);
554
555 /* Save menu bar */
556 if (GEM_menubar) {
557 MFDB mfdb_src;
558 short blitcoords[8];
559
560 mfdb_src.fd_addr=GEM_menubar;
561 mfdb_src.fd_w=GEM_desk_w;
562 mfdb_src.fd_h=GEM_desk_y;
563 mfdb_src.fd_wdwidth=GEM_desk_w>>4;
564 mfdb_src.fd_nplanes=VDI_bpp;
565 mfdb_src.fd_stand=
566 mfdb_src.fd_r1=
567 mfdb_src.fd_r2=
568 mfdb_src.fd_r3= 0;
569
570 blitcoords[0] = blitcoords[4] = 0;
571 blitcoords[1] = blitcoords[5] = 0;
572 blitcoords[2] = blitcoords[6] = GEM_desk_w-1;
573 blitcoords[3] = blitcoords[7] = GEM_desk_y-1;
574
575 vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &VDI_dst_mfdb, &mfdb_src);
576 }
577
578 GEM_locked=SDL_TRUE;
579 }
580}
581
582static void GEM_UnlockScreen(_THIS)
583{
584 if (GEM_locked) {
585 /* Restore menu bar */
586 if (GEM_menubar) {
587 MFDB mfdb_src;
588 short blitcoords[8];
589
590 mfdb_src.fd_addr=GEM_menubar;
591 mfdb_src.fd_w=GEM_desk_w;
592 mfdb_src.fd_h=GEM_desk_y;
593 mfdb_src.fd_wdwidth=GEM_desk_w>>4;
594 mfdb_src.fd_nplanes=VDI_bpp;
595 mfdb_src.fd_stand=
596 mfdb_src.fd_r1=
597 mfdb_src.fd_r2=
598 mfdb_src.fd_r3= 0;
599
600 blitcoords[0] = blitcoords[4] = 0;
601 blitcoords[1] = blitcoords[5] = 0;
602 blitcoords[2] = blitcoords[6] = GEM_desk_w-1;
603 blitcoords[3] = blitcoords[7] = GEM_desk_y-1;
604
605 vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &mfdb_src, &VDI_dst_mfdb);
606 }
607
608 /* Restore screen memory, and send REDRAW to all apps */
609 form_dial( FMD_FINISH, 0,0,0,0, 0,0,VDI_w,VDI_h);
610 /* Unlock AES */
611 wind_update(END_MCTRL);
612 wind_update(END_UPDATE);
613
614 GEM_locked=SDL_FALSE;
615 }
616}
617
618SDL_Surface *GEM_SetVideoMode(_THIS, SDL_Surface *current,
619 int width, int height, int bpp, Uint32 flags)
620{
621 Uint32 modeflags, screensize;
622 SDL_bool use_shadow1, use_shadow2;
623
624 /* width must be multiple of 16, for vro_cpyfm() and c2p_convert() */
625 if ((width & 15) != 0) {
626 width = (width | 15) +1;
627 }
628
629 /*--- Verify if asked mode can be used ---*/
630 if (VDI_bpp != bpp) {
631 SDL_SetError("%d bpp mode not supported", bpp);
632 return(NULL);
633 }
634
635 if (flags & SDL_FULLSCREEN) {
636 if ((VDI_w < width) || (VDI_h < height)) {
637 SDL_SetError("%dx%d mode is too large", width, height);
638 return(NULL);
639 }
640 }
641
642 /*--- Allocate the new pixel format for the screen ---*/
643 if ( ! SDL_ReallocFormat(current, VDI_bpp, VDI_redmask, VDI_greenmask, VDI_bluemask, VDI_alphamask) ) {
644 SDL_SetError("Couldn't allocate new pixel format for requested mode");
645 return(NULL);
646 }
647
648 screensize = width * height * VDI_pixelsize;
649
650#ifdef DEBUG_VIDEO_GEM
651 printf("sdl:video:gem: setvideomode(): %dx%dx%d = %d\n", width, height, bpp, screensize);
652#endif
653
654 /*--- Allocate shadow buffers if needed, and conversion operations ---*/
655 GEM_FreeBuffers(this);
656
657 GEM_bufops=0;
658 use_shadow1=use_shadow2=SDL_FALSE;
659 if (VDI_screen && (flags & SDL_FULLSCREEN)) {
660 if (VDI_format==VDI_FORMAT_INTER) {
661 use_shadow1=SDL_TRUE;
662 GEM_bufops = B2S_C2P_1TOS;
663 }
664 } else {
665 use_shadow1=SDL_TRUE;
666 if (VDI_format==VDI_FORMAT_PACK) {
667 GEM_bufops = B2S_VROCPYFM_1TOS;
668 } else {
669 use_shadow2=SDL_TRUE;
670 GEM_bufops = B2S_C2P_1TO2|B2S_VROCPYFM_2TOS;
671 }
672 }
673
674 if (use_shadow1) {
675 GEM_buffer1 = Atari_SysMalloc(screensize, MX_PREFTTRAM);
676 if (GEM_buffer1==NULL) {
677 SDL_SetError("Can not allocate %d KB for frame buffer", screensize>>10);
678 return NULL;
679 }
680 SDL_memset(GEM_buffer1, 0, screensize);
681#ifdef DEBUG_VIDEO_GEM
682 printf("sdl:video:gem: setvideomode(): allocated buffer 1\n");
683#endif
684 }
685
686 if (use_shadow2) {
687 GEM_buffer2 = Atari_SysMalloc(screensize, MX_PREFTTRAM);
688 if (GEM_buffer2==NULL) {
689 SDL_SetError("Can not allocate %d KB for shadow buffer", screensize>>10);
690 return NULL;
691 }
692 SDL_memset(GEM_buffer2, 0, screensize);
693#ifdef DEBUG_VIDEO_GEM
694 printf("sdl:video:gem: setvideomode(): allocated buffer 2\n");
695#endif
696 }
697
698 /*--- Initialize screen ---*/
699 modeflags = SDL_PREALLOC;
700 if (VDI_bpp == 8) {
701 modeflags |= SDL_HWPALETTE;
702 }
703
704 if (flags & SDL_FULLSCREEN) {
705 GEM_LockScreen(this);
706
707 GEM_ClearScreen(this);
708
709 modeflags |= SDL_FULLSCREEN;
710 if (VDI_screen && (VDI_format==VDI_FORMAT_PACK) && !use_shadow1) {
711 modeflags |= SDL_HWSURFACE;
712 } else {
713 modeflags |= SDL_SWSURFACE;
714 }
715
716 GEM_fullscreen = SDL_TRUE;
717 } else {
718 int old_win_type;
719 short x2,y2,w2,h2;
720
721 GEM_UnlockScreen(this);
722
723 /* Set window gadgets */
724 old_win_type = GEM_win_type;
725 if (!(flags & SDL_NOFRAME)) {
726 GEM_win_type=NAME|MOVER|CLOSER|SMALLER;
727 if (flags & SDL_RESIZABLE) {
728 GEM_win_type |= FULLER|SIZER;
729 modeflags |= SDL_RESIZABLE;
730 }
731 } else {
732 GEM_win_type=0;
733 modeflags |= SDL_NOFRAME;
734 }
735 modeflags |= SDL_SWSURFACE;
736
737 /* Recreate window ? only for different widget or non-created window */
738 if ((old_win_type != GEM_win_type) || (GEM_handle < 0)) {
739 /* Calculate window size */
740 if (!wind_calc(WC_BORDER, GEM_win_type, 0,0,width,height, &x2,&y2,&w2,&h2)) {
741 GEM_FreeBuffers(this);
742 SDL_SetError("Can not calculate window attributes");
743 return NULL;
744 }
745
746 /* Center window */
747 x2 = (GEM_desk_w-w2)>>1;
748 y2 = (GEM_desk_h-h2)>>1;
749 if (x2<0) {
750 x2 = 0;
751 }
752 if (y2<0) {
753 y2 = 0;
754 }
755 x2 += GEM_desk_x;
756 y2 += GEM_desk_y;
757
758 /* Destroy existing window */
759 if (GEM_handle >= 0) {
760 wind_close(GEM_handle);
761 wind_delete(GEM_handle);
762 }
763
764 /* Create window */
765 GEM_handle=wind_create(GEM_win_type, x2,y2,w2,h2);
766 if (GEM_handle<0) {
767 GEM_FreeBuffers(this);
768 SDL_SetError("Can not create window");
769 return NULL;
770 }
771
772#ifdef DEBUG_VIDEO_GEM
773 printf("sdl:video:gem: handle=%d\n", GEM_handle);
774#endif
775
776 /* Setup window name */
777 wind_set(GEM_handle,WF_NAME,(short)(((unsigned long)GEM_title_name)>>16),(short)(((unsigned long)GEM_title_name) & 0xffff),0,0);
778 GEM_refresh_name = SDL_FALSE;
779
780 /* Open the window */
781 wind_open(GEM_handle,x2,y2,w2,h2);
782 } else {
783 /* Resize window to fit asked video mode */
784 wind_get (GEM_handle, WF_WORKXYWH, &x2,&y2,&w2,&h2);
785 if (wind_calc(WC_BORDER, GEM_win_type, x2,y2,width,height, &x2,&y2,&w2,&h2)) {
786 wind_set (GEM_handle, WF_CURRXYWH, x2,y2,w2,h2);
787 }
788 }
789
790 GEM_fullscreen = SDL_FALSE;
791 }
792
793 /* Set up the new mode framebuffer */
794 current->w = width;
795 current->h = height;
796 if (use_shadow1) {
797 current->pixels = GEM_buffer1;
798 current->pitch = width * VDI_pixelsize;
799 } else {
800 current->pixels = VDI_screen;
801 current->pitch = VDI_pitch;
802 }
803
804#if SDL_VIDEO_OPENGL
805 if (flags & SDL_OPENGL) {
806 if (!SDL_AtariGL_Init(this, current)) {
807 GEM_FreeBuffers(this);
808 SDL_SetError("Can not create OpenGL context");
809 return NULL;
810 }
811
812 modeflags |= SDL_OPENGL;
813 }
814#endif
815
816 current->flags = modeflags;
817
818#ifdef DEBUG_VIDEO_GEM
819 printf("sdl:video:gem: surface: %dx%d\n", current->w, current->h);
820#endif
821
822 this->UpdateRects = GEM_UpdateRects;
823 GEM_lock_redraw = SDL_FALSE; /* Enable redraw */
824
825 /* We're done */
826 return(current);
827}
828
829static int GEM_AllocHWSurface(_THIS, SDL_Surface *surface)
830{
831 return -1;
832}
833
834static void GEM_FreeHWSurface(_THIS, SDL_Surface *surface)
835{
836 return;
837}
838
839static int GEM_LockHWSurface(_THIS, SDL_Surface *surface)
840{
841 return(0);
842}
843
844static void GEM_UnlockHWSurface(_THIS, SDL_Surface *surface)
845{
846 return;
847}
848
849static void GEM_UpdateRectsFullscreen(_THIS, int numrects, SDL_Rect *rects)
850{
851 SDL_Surface *surface;
852 int i, surf_width;
853
854 surface = this->screen;
855 /* Need to be a multiple of 16 pixels */
856 surf_width=surface->w;
857 if ((surf_width & 15) != 0) {
858 surf_width = (surf_width | 15) + 1;
859 }
860
861 if (GEM_bufops & (B2S_C2P_1TO2|B2S_C2P_1TOS)) {
862 void *destscr;
863 int destpitch;
864
865 if (GEM_bufops & B2S_C2P_1TOS) {
866 destscr = VDI_screen;
867 destpitch = VDI_pitch;
868 } else {
869 destscr = GEM_buffer2;
870 destpitch = surface->pitch;
871 }
872
873 for (i=0;i<numrects;i++) {
874 void *source,*destination;
875 int x1,x2;
876
877 x1 = rects[i].x & ~15;
878 x2 = rects[i].x+rects[i].w;
879 if (x2 & 15) {
880 x2 = (x2 | 15) +1;
881 }
882
883 source = surface->pixels;
884 source += surface->pitch * rects[i].y;
885 source += x1;
886
887 destination = destscr;
888 destination += destpitch * rects[i].y;
889 destination += x1;
890
891 SDL_Atari_C2pConvert(
892 source, destination,
893 x2-x1, rects[i].h,
894 SDL_FALSE,
895 surface->pitch, destpitch
896 );
897 }
898 }
899
900 if (GEM_bufops & (B2S_VROCPYFM_1TOS|B2S_VROCPYFM_2TOS)) {
901 MFDB mfdb_src;
902 short blitcoords[8];
903
904 mfdb_src.fd_addr=surface->pixels;
905 mfdb_src.fd_w=surf_width;
906 mfdb_src.fd_h=surface->h;
907 mfdb_src.fd_wdwidth= (surface->pitch/VDI_pixelsize) >> 4;
908 mfdb_src.fd_nplanes=surface->format->BitsPerPixel;
909 mfdb_src.fd_stand=
910 mfdb_src.fd_r1=
911 mfdb_src.fd_r2=
912 mfdb_src.fd_r3= 0;
913 if (GEM_bufops & B2S_VROCPYFM_2TOS) {
914 mfdb_src.fd_addr=GEM_buffer2;
915 }
916
917 for ( i=0; i<numrects; ++i ) {
918 blitcoords[0] = blitcoords[4] = rects[i].x;
919 blitcoords[1] = blitcoords[5] = rects[i].y;
920 blitcoords[2] = blitcoords[6] = rects[i].x + rects[i].w - 1;
921 blitcoords[3] = blitcoords[7] = rects[i].y + rects[i].h - 1;
922
923 vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &mfdb_src, &VDI_dst_mfdb);
924 }
925 }
926}
927
928static void GEM_UpdateRectsWindowed(_THIS, int numrects, SDL_Rect *rects)
929{
930 short pxy[4], wind_pxy[4];
931 int i;
932
933 if (wind_get(GEM_handle, WF_WORKXYWH, &wind_pxy[0], &wind_pxy[1], &wind_pxy[2], &wind_pxy[3])==0) {
934 return;
935 }
936
937 for ( i=0; i<numrects; ++i ) {
938 pxy[0] = wind_pxy[0] + rects[i].x;
939 pxy[1] = wind_pxy[1] + rects[i].y;
940 pxy[2] = rects[i].w;
941 pxy[3] = rects[i].h;
942
943 GEM_wind_redraw(this, GEM_handle, pxy);
944 }
945}
946
947static void GEM_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
948{
949 SDL_Surface *surface;
950
951 if (GEM_lock_redraw) {
952 return;
953 }
954
955 surface = this->screen;
956
957 if (surface->flags & SDL_FULLSCREEN) {
958 GEM_UpdateRectsFullscreen(this, numrects, rects);
959 } else {
960 GEM_UpdateRectsWindowed(this, numrects, rects);
961 }
962}
963
964static int GEM_FlipHWSurfaceFullscreen(_THIS, SDL_Surface *surface)
965{
966 int surf_width;
967
968 /* Need to be a multiple of 16 pixels */
969 surf_width=surface->w;
970 if ((surf_width & 15) != 0) {
971 surf_width = (surf_width | 15) + 1;
972 }
973
974 if (GEM_bufops & (B2S_C2P_1TO2|B2S_C2P_1TOS)) {
975 void *destscr;
976 int destpitch;
977
978 if (GEM_bufops & B2S_C2P_1TOS) {
979 destscr = VDI_screen;
980 destpitch = VDI_pitch;
981 } else {
982 destscr = GEM_buffer2;
983 destpitch = surface->pitch;
984 }
985
986 SDL_Atari_C2pConvert(
987 surface->pixels, destscr,
988 surf_width, surface->h,
989 SDL_FALSE,
990 surface->pitch, destpitch
991 );
992 }
993
994 if (GEM_bufops & (B2S_VROCPYFM_1TOS|B2S_VROCPYFM_2TOS)) {
995 MFDB mfdb_src;
996 short blitcoords[8];
997
998 mfdb_src.fd_w=surf_width;
999 mfdb_src.fd_h=surface->h;
1000 mfdb_src.fd_wdwidth=mfdb_src.fd_w >> 4;
1001 mfdb_src.fd_nplanes=surface->format->BitsPerPixel;
1002 mfdb_src.fd_stand=
1003 mfdb_src.fd_r1=
1004 mfdb_src.fd_r2=
1005 mfdb_src.fd_r3= 0;
1006 if (GEM_bufops & B2S_VROCPYFM_1TOS) {
1007 mfdb_src.fd_addr=surface->pixels;
1008 } else {
1009 mfdb_src.fd_addr=GEM_buffer2;
1010 }
1011
1012 blitcoords[0] = blitcoords[4] = 0;
1013 blitcoords[1] = blitcoords[5] = 0;
1014 blitcoords[2] = blitcoords[6] = surface->w - 1;
1015 blitcoords[3] = blitcoords[7] = surface->h - 1;
1016
1017 vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &mfdb_src, &VDI_dst_mfdb);
1018 }
1019
1020 return(0);
1021}
1022
1023static int GEM_FlipHWSurfaceWindowed(_THIS, SDL_Surface *surface)
1024{
1025 short pxy[8];
1026
1027 /* Update the whole window */
1028 wind_get(GEM_handle, WF_WORKXYWH, &pxy[0], &pxy[1], &pxy[2], &pxy[3]);
1029
1030 GEM_wind_redraw(this, GEM_handle, pxy);
1031
1032 return(0);
1033}
1034
1035static int GEM_FlipHWSurface(_THIS, SDL_Surface *surface)
1036{
1037 if (GEM_lock_redraw) {
1038 return(0);
1039 }
1040
1041 if (surface->flags & SDL_FULLSCREEN) {
1042 return GEM_FlipHWSurfaceFullscreen(this, surface);
1043 } else {
1044 return GEM_FlipHWSurfaceWindowed(this, surface);
1045 }
1046}
1047
1048static int GEM_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
1049{
1050 int i;
1051 SDL_Surface *surface;
1052
1053#ifdef DEBUG_VIDEO_GEM
1054 printf("sdl:video:gem: setcolors()\n");
1055#endif
1056
1057 /* Do not change palette in True Colour */
1058 surface = this->screen;
1059 if (surface->format->BitsPerPixel > 8) {
1060 return 1;
1061 }
1062
1063 for(i = 0; i < ncolors; i++)
1064 {
1065 int r, g, b;
1066 short rgb[3];
1067
1068 r = colors[i].r;
1069 g = colors[i].g;
1070 b = colors[i].b;
1071
1072 rgb[0] = VDI_curpalette[i][0] = (1000 * r) / 255;
1073 rgb[1] = VDI_curpalette[i][1] =(1000 * g) / 255;
1074 rgb[2] = VDI_curpalette[i][2] =(1000 * b) / 255;
1075
1076 vs_color(VDI_handle, vdi_index[firstcolor+i], rgb);
1077 }
1078
1079 return(1);
1080}
1081
1082#if 0
1083static int GEM_ToggleFullScreen(_THIS, int on)
1084{
1085 if (on) {
1086 GEM_LockScreen(this);
1087 } else {
1088 GEM_UnlockScreen(this);
1089 }
1090
1091 return(1);
1092}
1093#endif
1094
1095/* Note: If we are terminated, this could be called in the middle of
1096 another SDL video routine -- notably UpdateRects.
1097*/
1098void GEM_VideoQuit(_THIS)
1099{
1100 SDL_AtariXbios_RestoreVectors();
1101 if (GEM_usedevmouse) {
1102 SDL_AtariDevMouse_Close();
1103 }
1104
1105 GEM_FreeBuffers(this);
1106
1107#if SDL_VIDEO_OPENGL
1108 if (gl_active) {
1109 SDL_AtariGL_Quit(this, SDL_TRUE);
1110 }
1111#endif
1112
1113 /* Destroy window */
1114 if (GEM_handle>=0) {
1115 wind_close(GEM_handle);
1116 wind_delete(GEM_handle);
1117 GEM_handle=-1;
1118 }
1119
1120 GEM_UnlockScreen(this);
1121 if (GEM_menubar) {
1122 Mfree(GEM_menubar);
1123 GEM_menubar=NULL;
1124 }
1125
1126 appl_exit();
1127
1128 GEM_SetNewPalette(this, VDI_oldpalette);
1129
1130 /* Close VDI workstation */
1131 if (VDI_handle) {
1132 v_clsvwk(VDI_handle);
1133 }
1134
1135 /* Free mode list */
1136 if (SDL_modelist[0]) {
1137 SDL_free(SDL_modelist[0]);
1138 SDL_modelist[0]=NULL;
1139 }
1140
1141 this->screen->pixels = NULL;
1142}
1143
1144void GEM_wind_redraw(_THIS, int winhandle, short *inside)
1145{
1146 short todo[4];
1147
1148 /* Tell AES we are going to update */
1149 wind_update(BEG_UPDATE);
1150
1151 v_hide_c(VDI_handle);
1152
1153 /* Browse the rectangle list to redraw */
1154 if (wind_get(winhandle, WF_FIRSTXYWH, &todo[0], &todo[1], &todo[2], &todo[3])!=0) {
1155
1156 while (todo[2] && todo[3]) {
1157
1158 if (rc_intersect((GRECT *)inside,(GRECT *)todo)) {
1159 todo[2] += todo[0]-1;
1160 todo[3] += todo[1]-1;
1161 refresh_window(this, winhandle, todo);
1162 }
1163
1164 if (wind_get(winhandle, WF_NEXTXYWH, &todo[0], &todo[1], &todo[2], &todo[3])==0) {
1165 break;
1166 }
1167 }
1168
1169 }
1170
1171 /* Update finished */
1172 wind_update(END_UPDATE);
1173
1174 v_show_c(VDI_handle,1);
1175}
1176
1177static void refresh_window(_THIS, int winhandle, short *rect)
1178{
1179 MFDB mfdb_src;
1180 short pxy[8],wind_pxy[8];
1181 SDL_Surface *surface;
1182 int iconified;
1183
1184 /* Is window iconified ? */
1185 iconified = 0;
1186/* if (GEM_wfeatures & (1<<WF_ICONIFY))*/ {
1187 if (wind_get(winhandle, WF_ICONIFY, &wind_pxy[0], &wind_pxy[1], &wind_pxy[2], &wind_pxy[3])!=0) {
1188 iconified = wind_pxy[0];
1189 }
1190 }
1191
1192 if (wind_get(winhandle, WF_WORKXYWH, &wind_pxy[0], &wind_pxy[1], &wind_pxy[2], &wind_pxy[3])==0) {
1193 return;
1194 }
1195
1196 if (iconified && GEM_icon) {
1197 short icon_rect[4], dst_rect[4];
1198 short iconx,icony;
1199
1200 surface = GEM_icon;
1201
1202 GEM_ClearRect(this, rect);
1203
1204 /* Calculate centered icon(x,y,w,h) relative to window */
1205 iconx = (wind_pxy[2]-surface->w)>>1;
1206 icony = (wind_pxy[3]-surface->h)>>1;
1207
1208 icon_rect[0] = iconx;
1209 icon_rect[1] = icony;
1210 icon_rect[2] = surface->w;
1211 icon_rect[3] = surface->h;
1212
1213 /* Calculate redraw rectangle(x,y,w,h) relative to window */
1214 dst_rect[0] = rect[0]-wind_pxy[0];
1215 dst_rect[1] = rect[1]-wind_pxy[1];
1216 dst_rect[2] = rect[2]-rect[0]+1;
1217 dst_rect[3] = rect[3]-rect[1]+1;
1218
1219 /* Does the icon rectangle must be redrawn ? */
1220 if (!rc_intersect((GRECT *)icon_rect, (GRECT *)dst_rect)) {
1221 return;
1222 }
1223
1224#if DEBUG_VIDEO_GEM
1225 printf("sdl:video:gem: clip(0,0,%d,%d) to (%d,%d,%d,%d)\n",
1226 surface->w-1,surface->h-1, dst_rect[0],dst_rect[1],dst_rect[2],dst_rect[3]);
1227 printf("sdl:video:gem: icon(%d,%d,%d,%d)\n",
1228 icon_rect[0], icon_rect[1], icon_rect[2], icon_rect[3]);
1229 printf("sdl:video:gem: refresh_window(): draw icon\n");
1230#endif
1231
1232 /* Calculate icon(x1,y1,x2,y2) relative to screen */
1233 icon_rect[0] += wind_pxy[0];
1234 icon_rect[1] += wind_pxy[1];
1235 icon_rect[2] += icon_rect[0]-1;
1236 icon_rect[3] += icon_rect[1]-1;
1237
1238 /* Calculate intersection rectangle to redraw */
1239 pxy[4]=pxy[0]=MAX(icon_rect[0],rect[0]);
1240 pxy[5]=pxy[1]=MAX(icon_rect[1],rect[1]);
1241 pxy[6]=pxy[2]=MIN(icon_rect[2],rect[2]);
1242 pxy[7]=pxy[3]=MIN(icon_rect[3],rect[3]);
1243
1244 /* Calculate icon source image pos relative to window */
1245 pxy[0] -= wind_pxy[0]+iconx;
1246 pxy[1] -= wind_pxy[1]+icony;
1247 pxy[2] -= wind_pxy[0]+iconx;
1248 pxy[3] -= wind_pxy[1]+icony;
1249
1250 } else {
1251 surface = this->screen;
1252
1253#if DEBUG_VIDEO_GEM
1254 printf("sdl:video:gem: refresh_window(): draw frame buffer\n");
1255#endif
1256
1257 /* Redraw all window content */
1258 pxy[0] = rect[0]-wind_pxy[0];
1259 pxy[1] = rect[1]-wind_pxy[1];
1260 pxy[2] = rect[2]-wind_pxy[0];
1261 pxy[3] = rect[3]-wind_pxy[1];
1262
1263 pxy[4] = rect[0];
1264 pxy[5] = rect[1];
1265 pxy[6] = rect[2];
1266 pxy[7] = rect[3];
1267 }
1268
1269 if (GEM_bufops & B2S_C2P_1TO2) {
1270 void *src, *dest;
1271 int x1,x2;
1272
1273 x1 = (rect[0]-wind_pxy[0]) & ~15;
1274 x2 = rect[2]-wind_pxy[0];
1275 if (x2 & 15) {
1276 x2 = (x2 | 15) +1;
1277 }
1278
1279 src = surface->pixels;
1280 src += surface->pitch * (rect[1]-wind_pxy[1]);
1281 src += x1;
1282
1283 dest = GEM_buffer2;
1284 dest += surface->pitch * (rect[1]-wind_pxy[1]);
1285 dest += x1;
1286
1287 SDL_Atari_C2pConvert(
1288 src, dest,
1289 x2-x1, rect[3]-rect[1]+1,
1290 SDL_FALSE,
1291 surface->pitch, surface->pitch
1292 );
1293 }
1294
1295 mfdb_src.fd_addr=surface->pixels;
1296 {
1297 int width;
1298
1299 /* Need to be a multiple of 16 pixels */
1300 width=surface->w;
1301 if ((width & 15) != 0) {
1302 width = (width | 15) + 1;
1303 }
1304 mfdb_src.fd_w=width;
1305 }
1306 mfdb_src.fd_h=surface->h;
1307 mfdb_src.fd_nplanes=surface->format->BitsPerPixel;
1308 mfdb_src.fd_wdwidth=mfdb_src.fd_w>>4;
1309 mfdb_src.fd_stand=
1310 mfdb_src.fd_r1=
1311 mfdb_src.fd_r2=
1312 mfdb_src.fd_r3= 0;
1313
1314 if (GEM_bufops & B2S_VROCPYFM_2TOS) {
1315 mfdb_src.fd_addr=GEM_buffer2;
1316 }
1317
1318#if DEBUG_VIDEO_GEM
1319 printf("sdl:video:gem: redraw %dx%d: (%d,%d,%d,%d) to (%d,%d,%d,%d)\n",
1320 surface->w, surface->h,
1321 pxy[0],pxy[1],pxy[2],pxy[3],
1322 pxy[4],pxy[5],pxy[6],pxy[7]
1323 );
1324#endif
1325
1326 vro_cpyfm( VDI_handle, S_ONLY, pxy, &mfdb_src, &VDI_dst_mfdb);
1327}
1328
1329#if SDL_VIDEO_OPENGL
1330
1331static void GEM_GL_SwapBuffers(_THIS)
1332{
1333 SDL_AtariGL_SwapBuffers(this);
1334 GEM_FlipHWSurface(this, this->screen);
1335}
1336
1337#endif
diff --git a/apps/plugins/sdl/src/video/gem/SDL_gemvideo.h b/apps/plugins/sdl/src/video/gem/SDL_gemvideo.h
deleted file mode 100644
index f3a195453e..0000000000
--- a/apps/plugins/sdl/src/video/gem/SDL_gemvideo.h
+++ /dev/null
@@ -1,191 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_gemvideo_h
25#define _SDL_gemvideo_h
26
27#include "SDL_mutex.h"
28#include "../SDL_sysvideo.h"
29
30/* The implementation dependent data for the window manager cursor */
31struct WMcursor {
32 MFORM *mform_p;
33};
34
35/* Hidden "this" pointer for the video functions */
36#define _THIS SDL_VideoDevice *this
37
38/* Functions prototypes */
39void GEM_wind_redraw(_THIS, int winhandle, short *inside);
40
41/* Private display data */
42
43#define B2S_C2P_1TO2 (1<<0) /* C2P convert buffer 1 to buffer 2 */
44#define B2S_C2P_1TOS (1<<1) /* C2P convert buffer 1 to screen */
45#define B2S_VROCPYFM_1TOS (1<<2) /* vro_cpyfm() buffer 1 to screen */
46#define B2S_VROCPYFM_2TOS (1<<3) /* vro_cpyfm() buffer 2 to screen */
47
48#define SDL_NUMMODES 1 /* Fullscreen */
49
50struct SDL_PrivateVideoData {
51 Uint16 buf2scr_ops; /* Operations to get buffer to screen */
52 void *buffer1; /* Our shadow buffers */
53 void *buffer2;
54
55 /* VDI infos */
56 short vdi_handle; /* VDI handle */
57 short full_w, full_h; /* Fullscreen size */
58 short bpp; /* Colour depth */
59 short pixelsize; /* Bytes per pixel */
60 short old_numcolors; /* Number of colors in saved palette */
61 Uint16 pitch; /* Line length */
62 Uint16 format; /* Screen format */
63 void *screen; /* Screen address */
64 Uint32 red, green, blue, alpha; /* Screen components */
65 Uint32 screensize;
66 short blit_coords[8]; /* Coordinates for bitblt */
67 MFDB src_mfdb, dst_mfdb; /* VDI MFDB for bitblt */
68 Uint16 old_palette[256][3]; /* Saved current palette */
69 Uint16 cur_palette[256][3]; /* SDL application palette */
70 /* Function to set/restore palette */
71 void (*setpalette)(_THIS, Uint16 newpal[256][3]);
72
73 /* GEM infos */
74 short desk_x, desk_y; /* Desktop properties */
75 short desk_w, desk_h;
76 short win_handle; /* Our window handle */
77 int window_type; /* Window type */
78 const char *title_name; /* Window title */
79 const char *icon_name; /* Icon title */
80 short version; /* AES version */
81 short wfeatures; /* AES window features */
82 SDL_bool refresh_name; /* Change window title ? */
83 SDL_bool window_fulled; /* Window maximized ? */
84 SDL_bool mouse_relative; /* Report relative mouse movement */
85 SDL_bool locked; /* AES locked for fullscreen ? */
86 SDL_bool lock_redraw; /* Prevent redraw till buffers are setup */
87 short message[8]; /* To self-send an AES message */
88 void *menubar; /* Menu bar save buffer when going fullscreen */
89 SDL_bool use_dev_mouse; /* Use /dev/mouse ? */
90 WMcursor *cursor; /* To restore cursor when leaving/entering window */
91
92 SDL_bool fullscreen; /* Fullscreen or windowed mode ? */
93 SDL_Rect *SDL_modelist[SDL_NUMMODES+1]; /* Mode list */
94 SDL_Surface *icon; /* The icon */
95};
96
97/* Hidden structure -> variables names */
98#define VDI_handle (this->hidden->vdi_handle)
99#define VDI_w (this->hidden->full_w)
100#define VDI_h (this->hidden->full_h)
101#define VDI_bpp (this->hidden->bpp)
102#define VDI_pixelsize (this->hidden->pixelsize)
103#define VDI_oldnumcolors (this->hidden->old_numcolors)
104#define VDI_oldpalette (this->hidden->old_palette)
105#define VDI_curpalette (this->hidden->cur_palette)
106#define VDI_setpalette (this->hidden->setpalette)
107#define VDI_pitch (this->hidden->pitch)
108#define VDI_format (this->hidden->format)
109#define VDI_screen (this->hidden->screen)
110#define VDI_redmask (this->hidden->red)
111#define VDI_greenmask (this->hidden->green)
112#define VDI_bluemask (this->hidden->blue)
113#define VDI_alphamask (this->hidden->alpha)
114#define VDI_screensize (this->hidden->screensize)
115#define VDI_src_mfdb (this->hidden->src_mfdb)
116#define VDI_dst_mfdb (this->hidden->dst_mfdb)
117#define VDI_blit_coords (this->hidden->blit_coords)
118
119#define GEM_desk_x (this->hidden->desk_x)
120#define GEM_desk_y (this->hidden->desk_y)
121#define GEM_desk_w (this->hidden->desk_w)
122#define GEM_desk_h (this->hidden->desk_h)
123#define GEM_handle (this->hidden->win_handle)
124#define GEM_win_type (this->hidden->window_type)
125#define GEM_title_name (this->hidden->title_name)
126#define GEM_icon_name (this->hidden->icon_name)
127#define GEM_refresh_name (this->hidden->refresh_name)
128#define GEM_version (this->hidden->version)
129#define GEM_wfeatures (this->hidden->wfeatures)
130#define GEM_win_fulled (this->hidden->window_fulled)
131#define GEM_mouse_relative (this->hidden->mouse_relative)
132#define GEM_locked (this->hidden->locked)
133#define GEM_lock_redraw (this->hidden->lock_redraw)
134#define GEM_message (this->hidden->message)
135#define SDL_modelist (this->hidden->SDL_modelist)
136#define GEM_icon (this->hidden->icon)
137#define GEM_fullscreen (this->hidden->fullscreen)
138#define GEM_menubar (this->hidden->menubar)
139#define GEM_usedevmouse (this->hidden->use_dev_mouse)
140#define GEM_cursor (this->hidden->cursor)
141
142#define GEM_buffer1 (this->hidden->buffer1)
143#define GEM_buffer2 (this->hidden->buffer2)
144#define GEM_bufops (this->hidden->buf2scr_ops)
145
146#define VDI_FBMASK(amask, rmask, gmask, bmask) \
147 VDI_alphamask = (amask); \
148 VDI_redmask = (rmask); \
149 VDI_greenmask = (gmask); \
150 VDI_bluemask = (bmask);
151
152/*
153 Possible buffer to screen operations:
154
155 TC: 8 (chunky),15,16,24,32 bpp
156 8I: 8 bpp planes
157 FB: screen framebuffer address available
158 FS: fullscreen
159
160 TC, FB, FS:
161 - draw to screen
162 8I, FB, FS:
163 - draw to buffer 1
164 - C2P from buffer 1 to screen
165
166 TC, !FB, FS:
167 - draw to buffer 1
168 - vro_cpyfm() from buffer 1 to screen
169 8I, !FB, FS:
170 - draw to buffer 1
171 - C2P from buffer 1 to buffer 2
172 - vro_cpyfm() from buffer 2 to screen
173
174 TC, FB, !FS:
175 - draw to buffer 1
176 - vro_cpyfm() from buffer 1 to screen
177 8I, FB, !FS:
178 - draw to buffer 1
179 - C2P from buffer 1 to buffer 2
180 - vro_cpyfm() from buffer 2 to screen
181
182 TC, !FB, !FS:
183 - draw to buffer 1
184 - vro_cpyfm() from buffer 1 to screen
185 8I, !FB, !FS:
186 - draw to buffer 1
187 - C2P from buffer 1 to buffer 2
188 - vro_cpyfm() from buffer 2 to screen
189*/
190
191#endif /* _SDL_gemvideo_h */
diff --git a/apps/plugins/sdl/src/video/gem/SDL_gemwm.c b/apps/plugins/sdl/src/video/gem/SDL_gemwm.c
deleted file mode 100644
index 10776fd2e6..0000000000
--- a/apps/plugins/sdl/src/video/gem/SDL_gemwm.c
+++ /dev/null
@@ -1,116 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 GEM SDL video driver
26 Window manager functions
27
28 Patrice Mandin
29*/
30
31/* Mint includes */
32#include <gem.h>
33
34#include "SDL_gemwm_c.h"
35
36/* Defines */
37
38#define ICONWIDTH 64
39#define ICONHEIGHT 64
40
41/* Functions */
42
43void GEM_SetCaption(_THIS, const char *title, const char *icon)
44{
45 if (title) {
46 GEM_title_name = title;
47 GEM_refresh_name = SDL_TRUE;
48 }
49
50 if (icon) {
51 GEM_icon_name = icon;
52 GEM_refresh_name = SDL_TRUE;
53 }
54}
55
56void GEM_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
57{
58 SDL_Surface *sicon;
59 SDL_Rect bounds;
60
61#if 0
62 if ((GEM_wfeatures & (1<<WF_ICONIFY))==0) {
63 return;
64 }
65#endif
66
67 if (icon == NULL) {
68 return;
69 }
70
71 /* Convert icon to the screen format */
72 sicon = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h,
73 VDI_bpp, VDI_redmask, VDI_greenmask, VDI_bluemask, 0);
74 if ( sicon == NULL ) {
75 return;
76 }
77
78 bounds.x = 0;
79 bounds.y = 0;
80 bounds.w = icon->w;
81 bounds.h = icon->h;
82 if ( SDL_LowerBlit(icon, &bounds, sicon, &bounds) < 0 ) {
83 SDL_FreeSurface(sicon);
84 return;
85 }
86
87 GEM_icon = sicon;
88}
89
90int GEM_IconifyWindow(_THIS)
91{
92 if ((GEM_wfeatures & (1<<WF_ICONIFY))==0)
93 return 0;
94
95 GEM_message[0] = WM_ICONIFY;
96 GEM_message[1] = gl_apid;
97 GEM_message[2] = 0;
98 GEM_message[3] = GEM_handle;
99 GEM_message[4] = 0;
100 GEM_message[5] = GEM_desk_h-ICONHEIGHT;
101 GEM_message[6] = ICONWIDTH;
102 GEM_message[7] = ICONHEIGHT;
103
104 appl_write(gl_apid, sizeof(GEM_message), GEM_message);
105
106 return 1;
107}
108
109SDL_GrabMode GEM_GrabInput(_THIS, SDL_GrabMode mode)
110{
111 if (this->screen == NULL) {
112 return SDL_GRAB_OFF;
113 }
114
115 return mode;
116}
diff --git a/apps/plugins/sdl/src/video/gem/SDL_gemwm_c.h b/apps/plugins/sdl/src/video/gem/SDL_gemwm_c.h
deleted file mode 100644
index 59828b7eea..0000000000
--- a/apps/plugins/sdl/src/video/gem/SDL_gemwm_c.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * GEM SDL video driver implementation
26 * Window manager functions
27 *
28 * Patrice Mandin
29 */
30
31#include "SDL_gemvideo.h"
32
33/* Functions prototypes */
34extern void GEM_SetCaption(_THIS, const char *title, const char *icon);
35extern void GEM_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask);
36extern int GEM_IconifyWindow(_THIS);
37extern SDL_GrabMode GEM_GrabInput(_THIS, SDL_GrabMode mode);
diff --git a/apps/plugins/sdl/src/video/ggi/SDL_ggievents.c b/apps/plugins/sdl/src/video/ggi/SDL_ggievents.c
deleted file mode 100644
index d963fe16bc..0000000000
--- a/apps/plugins/sdl/src/video/ggi/SDL_ggievents.c
+++ /dev/null
@@ -1,264 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting GGI events into SDL events */
25
26#include <sys/types.h>
27#include <sys/time.h>
28#include <unistd.h>
29#include <fcntl.h>
30#include <termios.h>
31
32#include <ggi/keyboard.h>
33
34#include "SDL_ggikeys.h"
35
36#include "SDL.h"
37#include "../SDL_sysvideo.h"
38#include "../../events/SDL_sysevents.h"
39#include "../../events/SDL_events_c.h"
40#include "SDL_ggivideo.h"
41#include "SDL_ggievents_c.h"
42
43/* The translation tables from a GGI keycode to a SDL keysym */
44static SDLKey keymap[128];
45static SDL_keysym *GGI_TranslateKey(ggi_event *ev, SDL_keysym *keysym);
46
47static int posted = 0;
48
49void GGI_PumpEvents(_THIS)
50{
51 struct timeval *tvp, tv = { 0, 0 };
52 ggi_event ev;
53
54 tvp = &tv;
55
56/* ggiFlush(VIS); */
57
58 while (ggiEventPoll(VIS, emAll, tvp))
59/* while (ggiEventPoll(VIS, (emKeyboard | emPointer | emCommand), tvp)) */
60 {
61 int queueevent_mouse = 0, queueevent_kbd = 0;
62 static int buttons = 0;
63 static int mouse_x = 0, mouse_y = 0, mouse_z = 0;
64 int x = 0, y = 0, z = 0, rx = 0, ry = 0, rz = 0;
65 int pressed_mouse, pressed_kbd;
66 SDL_keysym keysym;
67
68 posted = 0;
69
70 /* FIXME: We do not actually want all events, only
71 * mouse and keyboard events. Having to handle all
72 * events will slow things down. */
73
74 ggiEventRead(VIS, &ev, emAll);
75/* ggiEventRead(VIS, &ev, (emKeyboard | emPointer | emCommand)); */
76
77 switch (ev.any.type)
78 {
79 case evPtrRelative:
80 x = ev.pmove.x;
81 y = ev.pmove.y;
82 z = ev.pmove.wheel;
83 posted += SDL_PrivateMouseMotion(0, 1, x, y);
84 break;
85 case evPtrAbsolute:
86 if (mouse_x != ev.pmove.x || mouse_y != ev.pmove.y || mouse_z != ev.pmove.wheel)
87 {
88 x = ev.pmove.x - mouse_x;
89 y = ev.pmove.y - mouse_y;
90 z = ev.pmove.wheel - mouse_z;
91 mouse_x = ev.pmove.x;
92 mouse_y = ev.pmove.y;
93 mouse_z = ev.pmove.wheel;
94 posted += SDL_PrivateMouseMotion(0, 1, x, y);
95 }
96 break;
97 case evPtrButtonPress:
98 posted += SDL_PrivateMouseButton(SDL_PRESSED, ev.pbutton.button, 0, 0);
99 break;
100 case evPtrButtonRelease:
101 posted += SDL_PrivateMouseButton(SDL_RELEASED, ev.pbutton.button, 0, 0);
102 break;
103 case evKeyPress:
104 case evKeyRepeat:
105 posted += SDL_PrivateKeyboard(SDL_PRESSED, GGI_TranslateKey(&ev, &keysym));
106 break;
107 case evKeyRelease:
108 posted += SDL_PrivateKeyboard(SDL_RELEASED, GGI_TranslateKey(&ev, &keysym));
109 break;
110 case evCommand:
111 fprintf(stderr, "Command event %x recieved\n", ev.cmd.code);
112 break;
113 default:
114 fprintf(stderr, "Unhandled event type %d\n", ev.any.type);
115 break;
116 }
117 }
118
119}
120
121void GGI_InitOSKeymap(_THIS)
122{
123 int i;
124
125 /* Initialize the GGI key translation table */
126 for ( i=0; i<SDL_arraysize(keymap); ++i )
127 keymap[i] = SDLK_UNKNOWN;
128
129 keymap[SCANCODE_ESCAPE] = SDLK_ESCAPE;
130 keymap[SCANCODE_1] = SDLK_1;
131 keymap[SCANCODE_2] = SDLK_2;
132 keymap[SCANCODE_3] = SDLK_3;
133 keymap[SCANCODE_4] = SDLK_4;
134 keymap[SCANCODE_5] = SDLK_5;
135 keymap[SCANCODE_6] = SDLK_6;
136 keymap[SCANCODE_7] = SDLK_7;
137 keymap[SCANCODE_8] = SDLK_8;
138 keymap[SCANCODE_9] = SDLK_9;
139 keymap[SCANCODE_0] = SDLK_0;
140 keymap[SCANCODE_MINUS] = SDLK_MINUS;
141 keymap[SCANCODE_EQUAL] = SDLK_EQUALS;
142 keymap[SCANCODE_BACKSPACE] = SDLK_BACKSPACE;
143 keymap[SCANCODE_TAB] = SDLK_TAB;
144 keymap[SCANCODE_Q] = SDLK_q;
145 keymap[SCANCODE_W] = SDLK_w;
146 keymap[SCANCODE_E] = SDLK_e;
147 keymap[SCANCODE_R] = SDLK_r;
148 keymap[SCANCODE_T] = SDLK_t;
149 keymap[SCANCODE_Y] = SDLK_y;
150 keymap[SCANCODE_U] = SDLK_u;
151 keymap[SCANCODE_I] = SDLK_i;
152 keymap[SCANCODE_O] = SDLK_o;
153 keymap[SCANCODE_P] = SDLK_p;
154 keymap[SCANCODE_BRACKET_LEFT] = SDLK_LEFTBRACKET;
155 keymap[SCANCODE_BRACKET_RIGHT] = SDLK_RIGHTBRACKET;
156 keymap[SCANCODE_ENTER] = SDLK_RETURN;
157 keymap[SCANCODE_LEFTCONTROL] = SDLK_LCTRL;
158 keymap[SCANCODE_A] = SDLK_a;
159 keymap[SCANCODE_S] = SDLK_s;
160 keymap[SCANCODE_D] = SDLK_d;
161 keymap[SCANCODE_F] = SDLK_f;
162 keymap[SCANCODE_G] = SDLK_g;
163 keymap[SCANCODE_H] = SDLK_h;
164 keymap[SCANCODE_J] = SDLK_j;
165 keymap[SCANCODE_K] = SDLK_k;
166 keymap[SCANCODE_L] = SDLK_l;
167 keymap[SCANCODE_SEMICOLON] = SDLK_SEMICOLON;
168 keymap[SCANCODE_APOSTROPHE] = SDLK_QUOTE;
169 keymap[SCANCODE_GRAVE] = SDLK_BACKQUOTE;
170 keymap[SCANCODE_LEFTSHIFT] = SDLK_LSHIFT;
171 keymap[SCANCODE_BACKSLASH] = SDLK_BACKSLASH;
172 keymap[SCANCODE_Z] = SDLK_z;
173 keymap[SCANCODE_X] = SDLK_x;
174 keymap[SCANCODE_C] = SDLK_c;
175 keymap[SCANCODE_V] = SDLK_v;
176 keymap[SCANCODE_B] = SDLK_b;
177 keymap[SCANCODE_N] = SDLK_n;
178 keymap[SCANCODE_M] = SDLK_m;
179 keymap[SCANCODE_COMMA] = SDLK_COMMA;
180 keymap[SCANCODE_PERIOD] = SDLK_PERIOD;
181 keymap[SCANCODE_SLASH] = SDLK_SLASH;
182 keymap[SCANCODE_RIGHTSHIFT] = SDLK_RSHIFT;
183 keymap[SCANCODE_KEYPADMULTIPLY] = SDLK_KP_MULTIPLY;
184 keymap[SCANCODE_LEFTALT] = SDLK_LALT;
185 keymap[SCANCODE_SPACE] = SDLK_SPACE;
186 keymap[SCANCODE_CAPSLOCK] = SDLK_CAPSLOCK;
187 keymap[SCANCODE_F1] = SDLK_F1;
188 keymap[SCANCODE_F2] = SDLK_F2;
189 keymap[SCANCODE_F3] = SDLK_F3;
190 keymap[SCANCODE_F4] = SDLK_F4;
191 keymap[SCANCODE_F5] = SDLK_F5;
192 keymap[SCANCODE_F6] = SDLK_F6;
193 keymap[SCANCODE_F7] = SDLK_F7;
194 keymap[SCANCODE_F8] = SDLK_F8;
195 keymap[SCANCODE_F9] = SDLK_F9;
196 keymap[SCANCODE_F10] = SDLK_F10;
197 keymap[SCANCODE_NUMLOCK] = SDLK_NUMLOCK;
198 keymap[SCANCODE_SCROLLLOCK] = SDLK_SCROLLOCK;
199 keymap[SCANCODE_KEYPAD7] = SDLK_KP7;
200 keymap[SCANCODE_CURSORUPLEFT] = SDLK_KP7;
201 keymap[SCANCODE_KEYPAD8] = SDLK_KP8;
202 keymap[SCANCODE_CURSORUP] = SDLK_KP8;
203 keymap[SCANCODE_KEYPAD9] = SDLK_KP9;
204 keymap[SCANCODE_CURSORUPRIGHT] = SDLK_KP9;
205 keymap[SCANCODE_KEYPADMINUS] = SDLK_KP_MINUS;
206 keymap[SCANCODE_KEYPAD4] = SDLK_KP4;
207 keymap[SCANCODE_CURSORLEFT] = SDLK_KP4;
208 keymap[SCANCODE_KEYPAD5] = SDLK_KP5;
209 keymap[SCANCODE_KEYPAD6] = SDLK_KP6;
210 keymap[SCANCODE_CURSORRIGHT] = SDLK_KP6;
211 keymap[SCANCODE_KEYPADPLUS] = SDLK_KP_PLUS;
212 keymap[SCANCODE_KEYPAD1] = SDLK_KP1;
213 keymap[SCANCODE_CURSORDOWNLEFT] = SDLK_KP1;
214 keymap[SCANCODE_KEYPAD2] = SDLK_KP2;
215 keymap[SCANCODE_CURSORDOWN] = SDLK_KP2;
216 keymap[SCANCODE_KEYPAD3] = SDLK_KP3;
217 keymap[SCANCODE_CURSORDOWNRIGHT] = SDLK_KP3;
218 keymap[SCANCODE_KEYPAD0] = SDLK_KP0;
219 keymap[SCANCODE_KEYPADPERIOD] = SDLK_KP_PERIOD;
220 keymap[SCANCODE_LESS] = SDLK_LESS;
221 keymap[SCANCODE_F11] = SDLK_F11;
222 keymap[SCANCODE_F12] = SDLK_F12;
223 keymap[SCANCODE_KEYPADENTER] = SDLK_KP_ENTER;
224 keymap[SCANCODE_RIGHTCONTROL] = SDLK_RCTRL;
225 keymap[SCANCODE_CONTROL] = SDLK_RCTRL;
226 keymap[SCANCODE_KEYPADDIVIDE] = SDLK_KP_DIVIDE;
227 keymap[SCANCODE_PRINTSCREEN] = SDLK_PRINT;
228 keymap[SCANCODE_RIGHTALT] = SDLK_RALT;
229 keymap[SCANCODE_BREAK] = SDLK_BREAK;
230 keymap[SCANCODE_BREAK_ALTERNATIVE] = SDLK_UNKNOWN;
231 keymap[SCANCODE_HOME] = SDLK_HOME;
232 keymap[SCANCODE_CURSORBLOCKUP] = SDLK_UP;
233 keymap[SCANCODE_PAGEUP] = SDLK_PAGEUP;
234 keymap[SCANCODE_CURSORBLOCKLEFT] = SDLK_LEFT;
235 keymap[SCANCODE_CURSORBLOCKRIGHT] = SDLK_RIGHT;
236 keymap[SCANCODE_END] = SDLK_END;
237 keymap[SCANCODE_CURSORBLOCKDOWN] = SDLK_DOWN;
238 keymap[SCANCODE_PAGEDOWN] = SDLK_PAGEDOWN;
239 keymap[SCANCODE_INSERT] = SDLK_INSERT;
240 keymap[SCANCODE_REMOVE] = SDLK_DELETE;
241 keymap[119] = SDLK_PAUSE;
242 keymap[SCANCODE_RIGHTWIN] = SDLK_RSUPER;
243 keymap[SCANCODE_LEFTWIN] = SDLK_LSUPER;
244 keymap[127] = SDLK_MENU;
245}
246
247
248
249static SDL_keysym *GGI_TranslateKey(gii_event *ev, SDL_keysym *keysym)
250{
251 /* Set the keysym information */
252 keysym->scancode = ev->key.button;
253 keysym->sym = keymap[ev->key.button];
254 keysym->mod = KMOD_NONE;
255
256 /* If UNICODE is on, get the UNICODE value for the key */
257 keysym->unicode = 0;
258 if (SDL_TranslateUNICODE)
259 {
260 keysym->unicode = GII_UNICODE(ev->key.sym);
261 }
262
263 return keysym;
264}
diff --git a/apps/plugins/sdl/src/video/ggi/SDL_ggievents_c.h b/apps/plugins/sdl/src/video/ggi/SDL_ggievents_c.h
deleted file mode 100755
index 2c661060c9..0000000000
--- a/apps/plugins/sdl/src/video/ggi/SDL_ggievents_c.h
+++ /dev/null
@@ -1,29 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_ggivideo.h"
25
26/* Functions to be exported */
27extern void GGI_InitOSKeymap(_THIS);
28extern void GGI_PumpEvents(_THIS);
29
diff --git a/apps/plugins/sdl/src/video/ggi/SDL_ggikeys.h b/apps/plugins/sdl/src/video/ggi/SDL_ggikeys.h
deleted file mode 100644
index 2868ee6ffa..0000000000
--- a/apps/plugins/sdl/src/video/ggi/SDL_ggikeys.h
+++ /dev/null
@@ -1,135 +0,0 @@
1
2#define SCANCODE_ESCAPE 1
3
4#define SCANCODE_1 2
5#define SCANCODE_2 3
6#define SCANCODE_3 4
7#define SCANCODE_4 5
8#define SCANCODE_5 6
9#define SCANCODE_6 7
10#define SCANCODE_7 8
11#define SCANCODE_8 9
12#define SCANCODE_9 10
13#define SCANCODE_0 11
14
15#define SCANCODE_MINUS 12
16#define SCANCODE_EQUAL 13
17
18#define SCANCODE_BACKSPACE 14
19#define SCANCODE_TAB 15
20
21#define SCANCODE_Q 16
22#define SCANCODE_W 17
23#define SCANCODE_E 18
24#define SCANCODE_R 19
25#define SCANCODE_T 20
26#define SCANCODE_Y 21
27#define SCANCODE_U 22
28#define SCANCODE_I 23
29#define SCANCODE_O 24
30#define SCANCODE_P 25
31#define SCANCODE_BRACKET_LEFT 26
32#define SCANCODE_BRACKET_RIGHT 27
33
34#define SCANCODE_ENTER 28
35
36#define SCANCODE_LEFTCONTROL 29
37
38#define SCANCODE_A 30
39#define SCANCODE_S 31
40#define SCANCODE_D 32
41#define SCANCODE_F 33
42#define SCANCODE_G 34
43#define SCANCODE_H 35
44#define SCANCODE_J 36
45#define SCANCODE_K 37
46#define SCANCODE_L 38
47#define SCANCODE_SEMICOLON 39
48#define SCANCODE_APOSTROPHE 40
49#define SCANCODE_GRAVE 41
50
51#define SCANCODE_LEFTSHIFT 42
52#define SCANCODE_BACKSLASH 43
53
54#define SCANCODE_Z 44
55#define SCANCODE_X 45
56#define SCANCODE_C 46
57#define SCANCODE_V 47
58#define SCANCODE_B 48
59#define SCANCODE_N 49
60#define SCANCODE_M 50
61#define SCANCODE_COMMA 51
62#define SCANCODE_PERIOD 52
63#define SCANCODE_SLASH 53
64
65#define SCANCODE_RIGHTSHIFT 54
66#define SCANCODE_KEYPADMULTIPLY 55
67
68#define SCANCODE_LEFTALT 56
69#define SCANCODE_SPACE 57
70#define SCANCODE_CAPSLOCK 58
71
72#define SCANCODE_F1 59
73#define SCANCODE_F2 60
74#define SCANCODE_F3 61
75#define SCANCODE_F4 62
76#define SCANCODE_F5 63
77#define SCANCODE_F6 64
78#define SCANCODE_F7 65
79#define SCANCODE_F8 66
80#define SCANCODE_F9 67
81#define SCANCODE_F10 68
82
83#define SCANCODE_NUMLOCK 69
84#define SCANCODE_SCROLLLOCK 70
85
86#define SCANCODE_KEYPAD7 71
87#define SCANCODE_CURSORUPLEFT 71
88#define SCANCODE_KEYPAD8 72
89#define SCANCODE_CURSORUP 72
90#define SCANCODE_KEYPAD9 73
91#define SCANCODE_CURSORUPRIGHT 73
92#define SCANCODE_KEYPADMINUS 74
93#define SCANCODE_KEYPAD4 75
94#define SCANCODE_CURSORLEFT 75
95#define SCANCODE_KEYPAD5 76
96#define SCANCODE_KEYPAD6 77
97#define SCANCODE_CURSORRIGHT 77
98#define SCANCODE_KEYPADPLUS 78
99#define SCANCODE_KEYPAD1 79
100#define SCANCODE_CURSORDOWNLEFT 79
101#define SCANCODE_KEYPAD2 80
102#define SCANCODE_CURSORDOWN 80
103#define SCANCODE_KEYPAD3 81
104#define SCANCODE_CURSORDOWNRIGHT 81
105#define SCANCODE_KEYPAD0 82
106#define SCANCODE_KEYPADPERIOD 83
107
108#define SCANCODE_LESS 86
109
110#define SCANCODE_F11 87
111#define SCANCODE_F12 88
112
113#define SCANCODE_KEYPADENTER 96
114#define SCANCODE_RIGHTCONTROL 97
115#define SCANCODE_CONTROL 97
116#define SCANCODE_KEYPADDIVIDE 98
117#define SCANCODE_PRINTSCREEN 99
118#define SCANCODE_RIGHTALT 100
119#define SCANCODE_BREAK 101 /* Beware: is 119 */
120#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */
121
122#define SCANCODE_HOME 102
123#define SCANCODE_CURSORBLOCKUP 90 /* Cursor key block */
124#define SCANCODE_PAGEUP 104
125#define SCANCODE_CURSORBLOCKLEFT 92 /* Cursor key block */
126#define SCANCODE_CURSORBLOCKRIGHT 94 /* Cursor key block */
127#define SCANCODE_END 107
128#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */
129#define SCANCODE_PAGEDOWN 109
130#define SCANCODE_INSERT 110
131#define SCANCODE_REMOVE 111
132
133#define SCANCODE_RIGHTWIN 126
134#define SCANCODE_LEFTWIN 125
135
diff --git a/apps/plugins/sdl/src/video/ggi/SDL_ggimouse.c b/apps/plugins/sdl/src/video/ggi/SDL_ggimouse.c
deleted file mode 100644
index 52c5337358..0000000000
--- a/apps/plugins/sdl/src/video/ggi/SDL_ggimouse.c
+++ /dev/null
@@ -1,32 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_mouse.h"
25#include "../../events/SDL_events_c.h"
26#include "SDL_ggimouse_c.h"
27
28
29/* The implementation dependent data for the window manager cursor */
30struct WMcursor {
31 int unused;
32};
diff --git a/apps/plugins/sdl/src/video/ggi/SDL_ggimouse_c.h b/apps/plugins/sdl/src/video/ggi/SDL_ggimouse_c.h
deleted file mode 100755
index c0ce295f2e..0000000000
--- a/apps/plugins/sdl/src/video/ggi/SDL_ggimouse_c.h
+++ /dev/null
@@ -1,26 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_ggivideo.h"
25
26/* Functions to be exported */
diff --git a/apps/plugins/sdl/src/video/ggi/SDL_ggivideo.c b/apps/plugins/sdl/src/video/ggi/SDL_ggivideo.c
deleted file mode 100644
index face49543e..0000000000
--- a/apps/plugins/sdl/src/video/ggi/SDL_ggivideo.c
+++ /dev/null
@@ -1,378 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* GGI-based SDL video driver implementation.
25*/
26
27#include <fcntl.h>
28#include <unistd.h>
29#include <sys/mman.h>
30
31#include <ggi/ggi.h>
32#include <ggi/gii.h>
33
34#include "SDL_video.h"
35#include "SDL_mouse.h"
36#include "../SDL_sysvideo.h"
37#include "../SDL_pixels_c.h"
38#include "../../events/SDL_events_c.h"
39#include "SDL_ggivideo.h"
40#include "SDL_ggimouse_c.h"
41#include "SDL_ggievents_c.h"
42
43
44struct private_hwdata
45{
46 ggi_visual_t vis;
47};
48
49ggi_visual_t VIS;
50
51/* Initialization/Query functions */
52static int GGI_VideoInit(_THIS, SDL_PixelFormat *vformat);
53static SDL_Rect **GGI_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
54static SDL_Surface *GGI_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
55static int GGI_SetColors(_THIS, int firstcolor, int ncolors,
56 SDL_Color *colors);
57static void GGI_VideoQuit(_THIS);
58
59/* Hardware surface functions */
60static int GGI_AllocHWSurface(_THIS, SDL_Surface *surface);
61static int GGI_LockHWSurface(_THIS, SDL_Surface *surface);
62static void GGI_UnlockHWSurface(_THIS, SDL_Surface *surface);
63static void GGI_FreeHWSurface(_THIS, SDL_Surface *surface);
64
65/* GGI driver bootstrap functions */
66
67static int GGI_Available(void)
68{
69 ggi_visual_t *vis;
70
71 vis = NULL;
72 if (ggiInit() == 0) {
73 vis = ggiOpen(NULL);
74 if (vis != NULL) {
75 ggiClose(vis);
76 }
77 }
78 return (vis != NULL);
79}
80
81static void GGI_DeleteDevice(SDL_VideoDevice *device)
82{
83 SDL_free(device->hidden);
84 SDL_free(device);
85}
86
87static SDL_VideoDevice *GGI_CreateDevice(int devindex)
88{
89 SDL_VideoDevice *device;
90
91 /* Initialize all variables that we clean on shutdown */
92 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
93 if ( device ) {
94 SDL_memset(device, 0, (sizeof *device));
95 device->hidden = (struct SDL_PrivateVideoData *)
96 SDL_malloc((sizeof *device->hidden));
97 }
98 if ( (device == NULL) || (device->hidden == NULL) ) {
99 SDL_OutOfMemory();
100 if ( device ) {
101 SDL_free(device);
102 }
103 return(0);
104 }
105 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
106
107 /* Set the function pointers */
108 device->VideoInit = GGI_VideoInit;
109 device->ListModes = GGI_ListModes;
110 device->SetVideoMode = GGI_SetVideoMode;
111 device->SetColors = GGI_SetColors;
112 device->UpdateRects = NULL;
113 device->VideoQuit = GGI_VideoQuit;
114 device->AllocHWSurface = GGI_AllocHWSurface;
115 device->CheckHWBlit = NULL;
116 device->FillHWRect = NULL;
117 device->SetHWColorKey = NULL;
118 device->SetHWAlpha = NULL;
119 device->LockHWSurface = GGI_LockHWSurface;
120 device->UnlockHWSurface = GGI_UnlockHWSurface;
121 device->FlipHWSurface = NULL;
122 device->FreeHWSurface = GGI_FreeHWSurface;
123 device->SetCaption = NULL;
124 device->SetIcon = NULL;
125 device->IconifyWindow = NULL;
126 device->GrabInput = NULL;
127 device->GetWMInfo = NULL;
128 device->InitOSKeymap = GGI_InitOSKeymap;
129 device->PumpEvents = GGI_PumpEvents;
130
131 device->free = GGI_DeleteDevice;
132
133 return device;
134}
135
136VideoBootStrap GGI_bootstrap = {
137 "ggi", "General Graphics Interface (GGI)",
138 GGI_Available, GGI_CreateDevice
139};
140
141
142static SDL_Rect video_mode;
143static SDL_Rect *SDL_modelist[4] = { NULL, NULL, NULL, NULL };
144
145int GGI_VideoInit(_THIS, SDL_PixelFormat *vformat)
146{
147 ggi_mode mode =
148 {
149 1,
150 { GGI_AUTO, GGI_AUTO },
151 { GGI_AUTO, GGI_AUTO },
152 { 0, 0 },
153 GT_AUTO,
154 { GGI_AUTO, GGI_AUTO }
155 };
156 struct private_hwdata *priv;
157 ggi_color pal[256], map[256];
158 const ggi_directbuffer *db;
159 int err, num_bufs;
160 ggi_pixel white, black;
161
162 priv = SDL_malloc(sizeof(struct private_hwdata));
163 if (priv == NULL)
164 {
165 SDL_SetError("Unhandled GGI mode type!\n");
166 GGI_VideoQuit(NULL);
167 }
168
169 if (ggiInit() != 0)
170 {
171 SDL_SetError("Unable to initialize GGI!\n");
172 GGI_VideoQuit(NULL);
173 }
174
175 VIS = ggiOpen(NULL);
176 if (VIS == NULL)
177 {
178 SDL_SetError("Unable to open default GGI visual!\n");
179 ggiExit();
180 GGI_VideoQuit(NULL);
181 }
182
183 ggiSetFlags(VIS, GGIFLAG_ASYNC);
184
185 /* Validate mode, autodetecting any GGI_AUTO or GT_AUTO fields */
186 ggiCheckMode(VIS, &mode);
187
188 /* At this point we should have a valid mode - try to set it */
189 err = ggiSetMode(VIS, &mode);
190
191 /* If we couldn't set _any_ modes, something is very wrong */
192 if (err)
193 {
194 SDL_SetError("Can't set a mode!\n");
195 ggiClose(VIS);
196 ggiExit();
197 GGI_VideoQuit(NULL);
198 }
199
200 /* Determine the current screen size */
201 this->info.current_w = mode.virt.x;
202 this->info.current_h = mode.virt.y;
203
204 /* Set a palette for palletized modes */
205 if (GT_SCHEME(mode.graphtype) == GT_PALETTE)
206 {
207 ggiSetColorfulPalette(VIS);
208 ggiGetPalette(VIS, 0, 1 << vformat->BitsPerPixel, pal);
209 }
210
211 /* Now we try to get the DirectBuffer info, which determines whether
212 * SDL can access hardware surfaces directly. */
213
214 num_bufs = ggiDBGetNumBuffers(VIS);
215
216 if (num_bufs > 0)
217 {
218 db = ggiDBGetBuffer(VIS, 0); /* Only handle one DB for now */
219
220 vformat->BitsPerPixel = db->buffer.plb.pixelformat->depth;
221
222 vformat->Rmask = db->buffer.plb.pixelformat->red_mask;
223 vformat->Gmask = db->buffer.plb.pixelformat->green_mask;
224 vformat->Bmask = db->buffer.plb.pixelformat->blue_mask;
225
226 /* Fill in our hardware acceleration capabilities */
227
228 this->info.wm_available = 0;
229 this->info.hw_available = 1;
230 this->info.video_mem = db->buffer.plb.stride * mode.virt.y;
231 }
232
233 video_mode.x = 0;
234 video_mode.y = 0;
235 video_mode.w = mode.virt.x;
236 video_mode.h = mode.virt.y;
237 SDL_modelist[((vformat->BitsPerPixel + 7) / 8) - 1] = &video_mode;
238
239 /* We're done! */
240 return(0);
241}
242
243static SDL_Rect **GGI_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
244{
245 return(&SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1]);
246}
247
248/* Various screen update functions available */
249static void GGI_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
250
251SDL_Surface *GGI_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags)
252{
253 ggi_mode mode =
254 {
255 1,
256 { GGI_AUTO, GGI_AUTO },
257 { GGI_AUTO, GGI_AUTO },
258 { 0, 0 },
259 GT_AUTO,
260 { GGI_AUTO, GGI_AUTO }
261 };
262 const ggi_directbuffer *db;
263 ggi_color pal[256];
264 int err;
265
266 fprintf(stderr, "GGI_SetVideoMode()\n");
267
268 mode.visible.x = mode.virt.x = width;
269 mode.visible.y = mode.virt.y = height;
270
271 /* Translate requested SDL bit depth into a GGI mode */
272 switch (bpp)
273 {
274 case 1: mode.graphtype = GT_1BIT; break;
275 case 2: mode.graphtype = GT_2BIT; break;
276 case 4: mode.graphtype = GT_4BIT; break;
277 case 8: mode.graphtype = GT_8BIT; break;
278 case 15: mode.graphtype = GT_15BIT; break;
279 case 16: mode.graphtype = GT_16BIT; break;
280 case 24: mode.graphtype = GT_24BIT; break;
281 case 32: mode.graphtype = GT_32BIT; break;
282 default:
283 SDL_SetError("Unknown SDL bit depth, using GT_AUTO....\n");
284 mode.graphtype = GT_AUTO;
285 }
286
287 /* Validate mode, autodetecting any GGI_AUTO or GT_AUTO fields */
288 ggiCheckMode(VIS, &mode);
289
290 /* At this point we should have a valid mode - try to set it */
291 err = ggiSetMode(VIS, &mode);
292
293 /* If we couldn't set _any_ modes, something is very wrong */
294 if (err)
295 {
296 SDL_SetError("Can't set a mode!\n");
297 ggiClose(VIS);
298 ggiExit();
299 GGI_VideoQuit(NULL);
300 }
301
302 /* Set a palette for palletized modes */
303 if (GT_SCHEME(mode.graphtype) == GT_PALETTE)
304 {
305 ggiSetColorfulPalette(VIS);
306 ggiGetPalette(VIS, 0, 1 << bpp, pal);
307 }
308
309 db = ggiDBGetBuffer(VIS, 0);
310
311 /* Set up the new mode framebuffer */
312 current->flags = (SDL_FULLSCREEN | SDL_HWSURFACE);
313 current->w = mode.virt.x;
314 current->h = mode.virt.y;
315 current->pitch = db->buffer.plb.stride;
316 current->pixels = db->read;
317
318 /* Set the blit function */
319 this->UpdateRects = GGI_DirectUpdate;
320
321 /* We're done */
322 return(current);
323}
324
325static int GGI_AllocHWSurface(_THIS, SDL_Surface *surface)
326{
327 return(-1);
328}
329static void GGI_FreeHWSurface(_THIS, SDL_Surface *surface)
330{
331 return;
332}
333static int GGI_LockHWSurface(_THIS, SDL_Surface *surface)
334{
335 return(0);
336}
337static void GGI_UnlockHWSurface(_THIS, SDL_Surface *surface)
338{
339 return;
340}
341
342static void GGI_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
343{
344 int i;
345
346/* ggiFlush(VIS); */
347
348 for (i = 0; i < numrects; i++)
349 {
350 ggiFlushRegion(VIS, rects[i].x, rects[i].y, rects[i].w, rects[i].h);
351 }
352 return;
353}
354
355int GGI_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
356{
357 int i;
358 ggi_color pal[256];
359
360 /* Set up the colormap */
361 for (i = 0; i < ncolors; i++)
362 {
363 pal[i].r = (colors[i].r << 8) | colors[i].r;
364 pal[i].g = (colors[i].g << 8) | colors[i].g;
365 pal[i].b = (colors[i].b << 8) | colors[i].b;
366 }
367
368 ggiSetPalette(VIS, firstcolor, ncolors, pal);
369
370 return 1;
371}
372
373void GGI_VideoQuit(_THIS)
374{
375}
376void GGI_FinalQuit(void)
377{
378}
diff --git a/apps/plugins/sdl/src/video/ggi/SDL_ggivideo.h b/apps/plugins/sdl/src/video/ggi/SDL_ggivideo.h
deleted file mode 100644
index 014dd098b4..0000000000
--- a/apps/plugins/sdl/src/video/ggi/SDL_ggivideo.h
+++ /dev/null
@@ -1,48 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_ggivideo_h
25#define _SDL_ggivideo_h
26
27#include <ggi/ggi.h>
28
29#include "SDL_mouse.h"
30#include "../SDL_sysvideo.h"
31
32#define _THIS SDL_VideoDevice *this
33
34/* Private display data */
35
36struct SDL_PrivateVideoData
37{
38 ggi_visual_t *ggivis;
39};
40
41extern ggi_visual_t VIS; /* FIXME: use the private data struct */
42
43extern int SDL_OpenKeyboard(void);
44extern void SDL_CloseKeyboard(void);
45extern int SDL_OpenMouse(void);
46extern void SDL_CloseMouse(void);
47
48#endif /* _SDL_ggivideo_h */
diff --git a/apps/plugins/sdl/src/video/ipod/SDL_ipodvideo.c b/apps/plugins/sdl/src/video/ipod/SDL_ipodvideo.c
deleted file mode 100644
index a2f3db3074..0000000000
--- a/apps/plugins/sdl/src/video/ipod/SDL_ipodvideo.c
+++ /dev/null
@@ -1,733 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <sys/types.h>
25#include <sys/ioctl.h>
26
27#include <unistd.h>
28#include <fcntl.h>
29#include <string.h>
30#include <termios.h>
31#include <ctype.h>
32
33#include <linux/vt.h>
34#include <linux/kd.h>
35#include <linux/keyboard.h>
36#include <linux/fb.h>
37
38#include "SDL_video.h"
39#include "SDL_mouse.h"
40#include "../SDL_sysvideo.h"
41#include "../SDL_pixels_c.h"
42#include "../../events/SDL_events_c.h"
43#include "SDL_sysevents.h"
44#include "SDL_ipodvideo.h"
45
46#define _THIS SDL_VideoDevice *this
47
48static int iPod_VideoInit (_THIS, SDL_PixelFormat *vformat);
49static SDL_Rect **iPod_ListModes (_THIS, SDL_PixelFormat *format, Uint32 flags);
50static SDL_Surface *iPod_SetVideoMode (_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
51static int iPod_SetColors (_THIS, int firstcolor, int ncolors, SDL_Color *colors);
52static void iPod_UpdateRects (_THIS, int nrects, SDL_Rect *rects);
53static void iPod_VideoQuit (_THIS);
54static void iPod_PumpEvents (_THIS);
55
56static long iPod_GetGeneration();
57
58static int initd = 0;
59static int kbfd = -1;
60static int fbfd = -1;
61static int oldvt = -1;
62static int curvt = -1;
63static int old_kbmode = -1;
64static long generation = 0;
65static struct termios old_termios, cur_termios;
66
67FILE *dbgout;
68
69#define LCD_DATA 0x10
70#define LCD_CMD 0x08
71#define IPOD_OLD_LCD_BASE 0xc0001000
72#define IPOD_OLD_LCD_RTC 0xcf001110
73#define IPOD_NEW_LCD_BASE 0x70003000
74#define IPOD_NEW_LCD_RTC 0x60005010
75
76static unsigned long lcd_base, lcd_rtc, lcd_width, lcd_height;
77
78static long iPod_GetGeneration()
79{
80 int i;
81 char cpuinfo[256];
82 char *ptr;
83 FILE *file;
84
85 if ((file = fopen("/proc/cpuinfo", "r")) != NULL) {
86 while (fgets(cpuinfo, sizeof(cpuinfo), file) != NULL)
87 if (SDL_strncmp(cpuinfo, "Revision", 8) == 0)
88 break;
89 fclose(file);
90 }
91 for (i = 0; !isspace(cpuinfo[i]); i++);
92 for (; isspace(cpuinfo[i]); i++);
93 ptr = cpuinfo + i + 2;
94
95 return SDL_strtol(ptr, NULL, 10);
96}
97
98static int iPod_Available()
99{
100 return 1;
101}
102
103static void iPod_DeleteDevice (SDL_VideoDevice *device)
104{
105 free (device->hidden);
106 free (device);
107}
108
109void iPod_InitOSKeymap (_THIS) {}
110
111static SDL_VideoDevice *iPod_CreateDevice (int devindex)
112{
113 SDL_VideoDevice *this;
114
115 this = (SDL_VideoDevice *)SDL_malloc (sizeof(SDL_VideoDevice));
116 if (this) {
117 memset (this, 0, sizeof *this);
118 this->hidden = (struct SDL_PrivateVideoData *) SDL_malloc (sizeof(struct SDL_PrivateVideoData));
119 }
120 if (!this || !this->hidden) {
121 SDL_OutOfMemory();
122 if (this)
123 SDL_free (this);
124 return 0;
125 }
126 memset (this->hidden, 0, sizeof(struct SDL_PrivateVideoData));
127
128 generation = iPod_GetGeneration();
129
130 this->VideoInit = iPod_VideoInit;
131 this->ListModes = iPod_ListModes;
132 this->SetVideoMode = iPod_SetVideoMode;
133 this->SetColors = iPod_SetColors;
134 this->UpdateRects = iPod_UpdateRects;
135 this->VideoQuit = iPod_VideoQuit;
136 this->AllocHWSurface = 0;
137 this->CheckHWBlit = 0;
138 this->FillHWRect = 0;
139 this->SetHWColorKey = 0;
140 this->SetHWAlpha = 0;
141 this->LockHWSurface = 0;
142 this->UnlockHWSurface = 0;
143 this->FlipHWSurface = 0;
144 this->FreeHWSurface = 0;
145 this->SetCaption = 0;
146 this->SetIcon = 0;
147 this->IconifyWindow = 0;
148 this->GrabInput = 0;
149 this->GetWMInfo = 0;
150 this->InitOSKeymap = iPod_InitOSKeymap;
151 this->PumpEvents = iPod_PumpEvents;
152 this->free = iPod_DeleteDevice;
153
154 return this;
155}
156
157VideoBootStrap iPod_bootstrap = {
158 "ipod", "iPod Framebuffer Driver",
159 iPod_Available, iPod_CreateDevice
160};
161
162//--//
163
164static int iPod_VideoInit (_THIS, SDL_PixelFormat *vformat)
165{
166 if (!initd) {
167 /*** Code adapted/copied from SDL fbcon driver. ***/
168
169 static const char * const tty0[] = { "/dev/tty0", "/dev/vc/0", 0 };
170 static const char * const vcs[] = { "/dev/vc/%d", "/dev/tty%d", 0 };
171 int i, tty0_fd;
172
173 dbgout = fdopen (open ("/etc/sdlpod.log", O_WRONLY | O_SYNC | O_APPEND), "a");
174 if (dbgout) {
175 setbuf (dbgout, 0);
176 fprintf (dbgout, "--> Started SDL <--\n");
177 }
178
179 // Try to query for a free VT
180 tty0_fd = -1;
181 for ( i=0; tty0[i] && (tty0_fd < 0); ++i ) {
182 tty0_fd = open(tty0[i], O_WRONLY, 0);
183 }
184 if ( tty0_fd < 0 ) {
185 tty0_fd = dup(0); /* Maybe stdin is a VT? */
186 }
187 ioctl(tty0_fd, VT_OPENQRY, &curvt);
188 close(tty0_fd);
189
190 tty0_fd = open("/dev/tty", O_RDWR, 0);
191 if ( tty0_fd >= 0 ) {
192 ioctl(tty0_fd, TIOCNOTTY, 0);
193 close(tty0_fd);
194 }
195
196 if ( (geteuid() == 0) && (curvt > 0) ) {
197 for ( i=0; vcs[i] && (kbfd < 0); ++i ) {
198 char vtpath[12];
199
200 SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], curvt);
201 kbfd = open(vtpath, O_RDWR);
202 }
203 }
204 if ( kbfd < 0 ) {
205 if (dbgout) fprintf (dbgout, "Couldn't open any VC\n");
206 return -1;
207 }
208 if (dbgout) fprintf (stderr, "Current VT: %d\n", curvt);
209
210 if (kbfd >= 0) {
211 /* Switch to the correct virtual terminal */
212 if ( curvt > 0 ) {
213 struct vt_stat vtstate;
214
215 if ( ioctl(kbfd, VT_GETSTATE, &vtstate) == 0 ) {
216 oldvt = vtstate.v_active;
217 }
218 if ( ioctl(kbfd, VT_ACTIVATE, curvt) == 0 ) {
219 if (dbgout) fprintf (dbgout, "Waiting for switch to this VT... ");
220 ioctl(kbfd, VT_WAITACTIVE, curvt);
221 if (dbgout) fprintf (dbgout, "done!\n");
222 }
223 }
224
225 // Set terminal input mode
226 if (tcgetattr (kbfd, &old_termios) < 0) {
227 if (dbgout) fprintf (dbgout, "Can't get termios\n");
228 return -1;
229 }
230 cur_termios = old_termios;
231 // cur_termios.c_iflag &= ~(ICRNL | INPCK | ISTRIP | IXON);
232 // cur_termios.c_iflag |= (BRKINT);
233 // cur_termios.c_lflag &= ~(ICANON | ECHO | ISIG | IEXTEN);
234 // cur_termios.c_oflag &= ~(OPOST);
235 // cur_termios.c_oflag |= (ONOCR | ONLRET);
236 cur_termios.c_lflag &= ~(ICANON | ECHO | ISIG);
237 cur_termios.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON);
238 cur_termios.c_cc[VMIN] = 0;
239 cur_termios.c_cc[VTIME] = 0;
240
241 if (tcsetattr (kbfd, TCSAFLUSH, &cur_termios) < 0) {
242 if (dbgout) fprintf (dbgout, "Can't set termios\n");
243 return -1;
244 }
245 if (ioctl (kbfd, KDSKBMODE, K_MEDIUMRAW) < 0) {
246 if (dbgout) fprintf (dbgout, "Can't set medium-raw mode\n");
247 return -1;
248 }
249 if (ioctl (kbfd, KDSETMODE, KD_GRAPHICS) < 0) {
250 if (dbgout) fprintf (dbgout, "Can't set graphics\n");
251 return -1;
252 }
253 }
254
255 // Open the framebuffer
256 if ((fbfd = open ("/dev/fb0", O_RDWR)) < 0) {
257 if (dbgout) fprintf (dbgout, "Can't open framebuffer\n");
258 return -1;
259 } else {
260 struct fb_var_screeninfo vinfo;
261
262 if (dbgout) fprintf (dbgout, "Generation: %ld\n", generation);
263
264 if (generation >= 40000) {
265 lcd_base = IPOD_NEW_LCD_BASE;
266 } else {
267 lcd_base = IPOD_OLD_LCD_BASE;
268 }
269
270 ioctl (fbfd, FBIOGET_VSCREENINFO, &vinfo);
271 close (fbfd);
272
273 if (lcd_base == IPOD_OLD_LCD_BASE)
274 lcd_rtc = IPOD_OLD_LCD_RTC;
275 else if (lcd_base == IPOD_NEW_LCD_BASE)
276 lcd_rtc = IPOD_NEW_LCD_RTC;
277 else {
278 SDL_SetError ("Unknown iPod version");
279 return -1;
280 }
281
282 lcd_width = vinfo.xres;
283 lcd_height = vinfo.yres;
284
285 if (dbgout) fprintf (dbgout, "LCD is %dx%d\n", lcd_width, lcd_height);
286 }
287
288 fcntl (kbfd, F_SETFL, O_RDWR | O_NONBLOCK);
289
290 /* Determine the current screen size */
291 this->info.current_w = lcd_width;
292 this->info.current_h = lcd_height;
293
294 if ((generation >= 60000) && (generation < 70000)) {
295 vformat->BitsPerPixel = 16;
296 vformat->Rmask = 0xF800;
297 vformat->Gmask = 0x07E0;
298 vformat->Bmask = 0x001F;
299 } else {
300 vformat->BitsPerPixel = 8;
301 vformat->Rmask = vformat->Gmask = vformat->Bmask = 0;
302 }
303
304 initd = 1;
305 if (dbgout) fprintf (dbgout, "Initialized.\n\n");
306 }
307 return 0;
308}
309
310static SDL_Rect **iPod_ListModes (_THIS, SDL_PixelFormat *format, Uint32 flags)
311{
312 int width, height, fd;
313 static SDL_Rect r;
314 static SDL_Rect *rs[2] = { &r, 0 };
315
316 if ((fd = open ("/dev/fb0", O_RDWR)) < 0) {
317 return 0;
318 } else {
319 struct fb_var_screeninfo vinfo;
320
321 ioctl (fbfd, FBIOGET_VSCREENINFO, &vinfo);
322 close (fbfd);
323
324 width = vinfo.xres;
325 height = vinfo.yres;
326 }
327 r.x = r.y = 0;
328 r.w = width;
329 r.h = height;
330 return rs;
331}
332
333
334static SDL_Surface *iPod_SetVideoMode (_THIS, SDL_Surface *current, int width, int height, int bpp,
335 Uint32 flags)
336{
337 Uint32 Rmask, Gmask, Bmask;
338 if (bpp > 8) {
339 Rmask = 0xF800;
340 Gmask = 0x07E0;
341 Bmask = 0x001F;
342 } else {
343 Rmask = Gmask = Bmask = 0;
344 }
345
346 if (this->hidden->buffer) SDL_free (this->hidden->buffer);
347 this->hidden->buffer = SDL_malloc (width * height * (bpp / 8));
348 if (!this->hidden->buffer) {
349 SDL_SetError ("Couldn't allocate buffer for requested mode");
350 return 0;
351 }
352
353 memset (this->hidden->buffer, 0, width * height * (bpp / 8));
354
355 if (!SDL_ReallocFormat (current, bpp, Rmask, Gmask, Bmask, 0)) {
356 SDL_SetError ("Couldn't allocate new pixel format");
357 SDL_free (this->hidden->buffer);
358 this->hidden->buffer = 0;
359 return 0;
360 }
361
362 if (bpp <= 8) {
363 int i, j;
364 for (i = 0; i < 256; i += 4) {
365 for (j = 0; j < 4; j++) {
366 current->format->palette->colors[i+j].r = 85 * j;
367 current->format->palette->colors[i+j].g = 85 * j;
368 current->format->palette->colors[i+j].b = 85 * j;
369 }
370 }
371 }
372
373 current->flags = flags & SDL_FULLSCREEN;
374 this->hidden->w = current->w = width;
375 this->hidden->h = current->h = height;
376 current->pitch = current->w * (bpp / 8);
377 current->pixels = this->hidden->buffer;
378
379 return current;
380}
381
382static int iPod_SetColors (_THIS, int firstcolor, int ncolors, SDL_Color *colors)
383{
384 if (SDL_VideoSurface && SDL_VideoSurface->format && SDL_VideoSurface->format->palette) {
385 int i, j;
386 for (i = 0; i < 256; i += 4) {
387 for (j = 0; j < 4; j++) {
388 SDL_VideoSurface->format->palette->colors[i+j].r = 85 * j;
389 SDL_VideoSurface->format->palette->colors[i+j].g = 85 * j;
390 SDL_VideoSurface->format->palette->colors[i+j].b = 85 * j;
391 }
392 }
393 }
394 return 0;
395}
396
397static void iPod_VideoQuit (_THIS)
398{
399 ioctl (kbfd, KDSETMODE, KD_TEXT);
400 tcsetattr (kbfd, TCSAFLUSH, &old_termios);
401 old_kbmode = -1;
402
403 if (oldvt > 0)
404 ioctl (kbfd, VT_ACTIVATE, oldvt);
405
406 if (kbfd > 0)
407 close (kbfd);
408
409 if (dbgout) {
410 fprintf (dbgout, "<-- Ended SDL -->\n");
411 fclose (dbgout);
412 }
413
414 kbfd = -1;
415}
416
417static char iPod_SC_keymap[] = {
418 0, /* 0 - no key */
419 '[' - 0x40, /* ESC (Ctrl+[) */
420 '1', '2', '3', '4', '5', '6', '7', '8', '9',
421 '-', '=',
422 '\b', '\t', /* Backspace, Tab (Ctrl+H,Ctrl+I) */
423 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']',
424 '\n', 0, /* Enter, Left CTRL */
425 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '`',
426 0, '\\', /* left shift, backslash */
427 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/',
428 0, '*', 0, ' ', 0, /* right shift, KP mul, left alt, space, capslock */
429 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F1-10 */
430 0, 0, /* numlock, scrollock */
431 '7', '8', '9', '-', '4', '5', '6', '+', '1', '2', '3', '0', '.', /* numeric keypad */
432 0, 0, /* padding */
433 0, 0, 0, /* "less" (?), F11, F12 */
434 0, 0, 0, 0, 0, 0, 0, /* padding */
435 '\n', 0, '/', 0, 0, /* KP enter, Rctrl, Ctrl, KP div, PrtSc, RAlt */
436 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Break, Home, Up, PgUp, Left, Right, End, Down, PgDn */
437 0, 0, /* Ins, Del */
438 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* padding */
439 0, 0, /* RWin, LWin */
440 0 /* no key */
441};
442
443
444static void iPod_keyboard()
445{
446 unsigned char keybuf[128];
447 int i, nread;
448 SDL_keysym keysym;
449 SDL_Event ev;
450
451 keysym.mod = 0;
452 keysym.scancode = 0xff;
453 memset (&ev, 0, sizeof(SDL_Event));
454
455 nread = read (kbfd, keybuf, 128);
456 for (i = 0; i < nread; i++) {
457 char ascii = iPod_SC_keymap[keybuf[i] & 0x7f];
458
459 if (dbgout) fprintf (dbgout, "Key! %02x is %c %s", keybuf[i], ascii, (keybuf[i] & 0x80)? "up" : "down");
460
461 keysym.sym = keysym.unicode = ascii;
462 ev.type = (keybuf[i] & 0x80)? SDL_KEYUP : SDL_KEYDOWN;
463 ev.key.state = 0;
464 ev.key.keysym = keysym;
465 SDL_PushEvent (&ev);
466 }
467}
468
469static void iPod_PumpEvents (_THIS)
470{
471 fd_set fdset;
472 int max_fd = 0;
473 static struct timeval zero;
474 int posted;
475
476 do {
477 posted = 0;
478
479 FD_ZERO (&fdset);
480 if (kbfd >= 0) {
481 FD_SET (kbfd, &fdset);
482 max_fd = kbfd;
483 }
484 if (dbgout) fprintf (dbgout, "Selecting");
485 if (select (max_fd + 1, &fdset, 0, 0, &zero) > 0) {
486 if (dbgout) fprintf (dbgout, " -> match!\n");
487 iPod_keyboard();
488 posted++;
489 }
490 if (dbgout) fprintf (dbgout, "\n");
491 } while (posted);
492}
493
494// enough space for 160x128x2
495static char ipod_scr[160 * (128/4)];
496
497#define outl(datum,addr) (*(volatile unsigned long *)(addr) = (datum))
498#define inl(addr) (*(volatile unsigned long *)(addr))
499
500/*** The following LCD code is taken from Linux kernel uclinux-2.4.24-uc0-ipod2,
501 file arch/armnommu/mach-ipod/fb.c. A few modifications have been made. ***/
502
503/* get current usec counter */
504static int M_timer_get_current(void)
505{
506 return inl(lcd_rtc);
507}
508
509/* check if number of useconds has past */
510static int M_timer_check(int clock_start, int usecs)
511{
512 unsigned long clock;
513 clock = inl(lcd_rtc);
514
515 if ( (clock - clock_start) >= usecs ) {
516 return 1;
517 } else {
518 return 0;
519 }
520}
521
522/* wait for LCD with timeout */
523static void M_lcd_wait_write(void)
524{
525 if ( (inl(lcd_base) & 0x8000) != 0 ) {
526 int start = M_timer_get_current();
527
528 do {
529 if ( (inl(lcd_base) & (unsigned int)0x8000) == 0 )
530 break;
531 } while ( M_timer_check(start, 1000) == 0 );
532 }
533}
534
535
536/* send LCD data */
537static void M_lcd_send_data(int data_lo, int data_hi)
538{
539 M_lcd_wait_write();
540
541 outl(data_lo, lcd_base + LCD_DATA);
542
543 M_lcd_wait_write();
544
545 outl(data_hi, lcd_base + LCD_DATA);
546
547}
548
549/* send LCD command */
550static void
551M_lcd_prepare_cmd(int cmd)
552{
553 M_lcd_wait_write();
554
555 outl(0x0, lcd_base + LCD_CMD);
556
557 M_lcd_wait_write();
558
559 outl(cmd, lcd_base + LCD_CMD);
560
561}
562
563/* send LCD command and data */
564static void M_lcd_cmd_and_data(int cmd, int data_lo, int data_hi)
565{
566 M_lcd_prepare_cmd(cmd);
567
568 M_lcd_send_data(data_lo, data_hi);
569}
570
571// Copied from uW
572static void M_update_display(int sx, int sy, int mx, int my)
573{
574 int y;
575 unsigned short cursor_pos;
576
577 sx >>= 3;
578 mx >>= 3;
579
580 cursor_pos = sx + (sy << 5);
581
582 for ( y = sy; y <= my; y++ ) {
583 unsigned char *img_data;
584 int x;
585
586 /* move the cursor */
587 M_lcd_cmd_and_data(0x11, cursor_pos >> 8, cursor_pos & 0xff);
588
589 /* setup for printing */
590 M_lcd_prepare_cmd(0x12);
591
592 img_data = ipod_scr + (sx << 1) + (y * (lcd_width/4));
593
594 /* loops up to 160 times */
595 for ( x = sx; x <= mx; x++ ) {
596 /* display eight pixels */
597 M_lcd_send_data(*(img_data + 1), *img_data);
598
599 img_data += 2;
600 }
601
602 /* update cursor pos counter */
603 cursor_pos += 0x20;
604 }
605}
606
607/* get current usec counter */
608static int C_timer_get_current(void)
609{
610 return inl(0x60005010);
611}
612
613/* check if number of useconds has past */
614static int C_timer_check(int clock_start, int usecs)
615{
616 unsigned long clock;
617 clock = inl(0x60005010);
618
619 if ( (clock - clock_start) >= usecs ) {
620 return 1;
621 } else {
622 return 0;
623 }
624}
625
626/* wait for LCD with timeout */
627static void C_lcd_wait_write(void)
628{
629 if ((inl(0x70008A0C) & 0x80000000) != 0) {
630 int start = C_timer_get_current();
631
632 do {
633 if ((inl(0x70008A0C) & 0x80000000) == 0)
634 break;
635 } while (C_timer_check(start, 1000) == 0);
636 }
637}
638static void C_lcd_cmd_data(int cmd, int data)
639{
640 C_lcd_wait_write();
641 outl(cmd | 0x80000000, 0x70008A0C);
642
643 C_lcd_wait_write();
644 outl(data | 0x80000000, 0x70008A0C);
645}
646
647static void C_update_display(int sx, int sy, int mx, int my)
648{
649 int height = (my - sy) + 1;
650 int width = (mx - sx) + 1;
651
652 char *addr = SDL_VideoSurface->pixels;
653
654 if (width & 1) width++;
655
656 /* start X and Y */
657 C_lcd_cmd_data(0x12, (sy & 0xff));
658 C_lcd_cmd_data(0x13, (((SDL_VideoSurface->w - 1) - sx) & 0xff));
659
660 /* max X and Y */
661 C_lcd_cmd_data(0x15, (((sy + height) - 1) & 0xff));
662 C_lcd_cmd_data(0x16, (((((SDL_VideoSurface->w - 1) - sx) - width) + 1) & 0xff));
663
664 addr += sx + sy * SDL_VideoSurface->pitch;
665
666 while (height > 0) {
667 int h, x, y, pixels_to_write;
668
669 pixels_to_write = (width * height) * 2;
670
671 /* calculate how much we can do in one go */
672 h = height;
673 if (pixels_to_write > 64000) {
674 h = (64000/2) / width;
675 pixels_to_write = (width * h) * 2;
676 }
677
678 outl(0x10000080, 0x70008A20);
679 outl((pixels_to_write - 1) | 0xC0010000, 0x70008A24);
680 outl(0x34000000, 0x70008A20);
681
682 /* for each row */
683 for (x = 0; x < h; x++)
684 {
685 /* for each column */
686 for (y = 0; y < width; y += 2) {
687 unsigned two_pixels;
688
689 two_pixels = addr[0] | (addr[1] << 16);
690 addr += 2;
691
692 while ((inl(0x70008A20) & 0x1000000) == 0);
693
694 /* output 2 pixels */
695 outl(two_pixels, 0x70008B00);
696 }
697
698 addr += SDL_VideoSurface->w - width;
699 }
700
701 while ((inl(0x70008A20) & 0x4000000) == 0);
702
703 outl(0x0, 0x70008A24);
704
705 height = height - h;
706 }
707}
708
709// Should work with photo. However, I don't have one, so I'm not sure.
710static void iPod_UpdateRects (_THIS, int nrects, SDL_Rect *rects)
711{
712 if (SDL_VideoSurface->format->BitsPerPixel == 16) {
713 C_update_display (0, 0, lcd_width, lcd_height);
714 } else {
715 int i, y, x;
716 for (i = 0; i < nrects; i++) {
717 SDL_Rect *r = rects + i;
718 if (!r) {
719 continue;
720 }
721
722 for (y = r->y; (y < r->y + r->h) && y < lcd_height; y++) {
723 for (x = r->x; (x < r->x + r->w) && x < lcd_width; x++) {
724 ipod_scr[y*(lcd_width/4) + x/4] &= ~(3 << (2 * (x%4)));
725 ipod_scr[y*(lcd_width/4) + x/4] |=
726 (((Uint8*)(SDL_VideoSurface->pixels))[ y*SDL_VideoSurface->pitch + x ] & 3) << (2 * (x%4));
727 }
728 }
729 }
730
731 M_update_display (0, 0, lcd_width, lcd_height);
732 }
733}
diff --git a/apps/plugins/sdl/src/video/ipod/SDL_ipodvideo.h b/apps/plugins/sdl/src/video/ipod/SDL_ipodvideo.h
deleted file mode 100644
index 921eee8546..0000000000
--- a/apps/plugins/sdl/src/video/ipod/SDL_ipodvideo.h
+++ /dev/null
@@ -1,38 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* iPod SDL framebuffer driver
25 * Joshua Oreman
26 * Main header file
27 */
28
29#ifndef _SDL_ipodvideo_h
30#define _SDL_ipodvideo_h
31
32struct SDL_PrivateVideoData {
33 char *buffer;
34 int w, h;
35};
36
37
38#endif
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_lowvideo.h b/apps/plugins/sdl/src/video/maccommon/SDL_lowvideo.h
deleted file mode 100644
index f3dac29091..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_lowvideo.h
+++ /dev/null
@@ -1,102 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowvideo_h
25#define _SDL_lowvideo_h
26
27#if defined(__APPLE__) && defined(__MACH__)
28#include <Carbon/Carbon.h>
29#elif TARGET_API_MAC_CARBON && (UNIVERSAL_INTERFACES_VERSION > 0x0335)
30#include <Carbon.h>
31#else
32#include <Quickdraw.h>
33#include <Palettes.h>
34#include <Menus.h>
35#include <DrawSprocket.h>
36#endif
37
38#if SDL_VIDEO_OPENGL
39typedef struct __AGLContextRec *AGLContext;
40#endif
41
42#include "SDL_video.h"
43#include "../SDL_sysvideo.h"
44
45/* Hidden "this" pointer for the video functions */
46#define _THIS SDL_VideoDevice *this
47
48#if !TARGET_API_MAC_CARBON /* not available in OS X (or more accurately, Carbon) */
49/* Global QuickDraw data */
50extern QDGlobals *theQD;
51#endif
52
53/* Private display data */
54struct SDL_PrivateVideoData {
55 GDevice **SDL_Display;
56 WindowRef SDL_Window;
57 SDL_Rect **SDL_modelist;
58 CTabHandle SDL_CTab;
59 PaletteHandle SDL_CPal;
60
61#if TARGET_API_MAC_CARBON
62 /* For entering and leaving fullscreen mode */
63 Ptr fullscreen_ctx;
64#endif
65
66 /* The current window document style */
67 int current_style;
68
69 /* Information about the last cursor position */
70 Point last_where;
71
72 /* Information about the last keys down */
73 EventModifiers last_mods;
74 KeyMap last_keys;
75
76 /* A handle to the Apple Menu */
77 MenuRef apple_menu;
78
79 /* Information used by DrawSprocket driver */
80 struct DSpInfo *dspinfo;
81
82#if SDL_VIDEO_OPENGL
83 AGLContext appleGLContext;
84
85 void *libraryHandle;
86#endif
87};
88/* Old variable names */
89#define SDL_Display (this->hidden->SDL_Display)
90#define SDL_Window (this->hidden->SDL_Window)
91#define SDL_modelist (this->hidden->SDL_modelist)
92#define SDL_CTab (this->hidden->SDL_CTab)
93#define SDL_CPal (this->hidden->SDL_CPal)
94#define fullscreen_ctx (this->hidden->fullscreen_ctx)
95#define current_style (this->hidden->current_style)
96#define last_where (this->hidden->last_where)
97#define last_mods (this->hidden->last_mods)
98#define last_keys (this->hidden->last_keys)
99#define apple_menu (this->hidden->apple_menu)
100#define glContext (this->hidden->appleGLContext)
101
102#endif /* _SDL_lowvideo_h */
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_macevents.c b/apps/plugins/sdl/src/video/maccommon/SDL_macevents.c
deleted file mode 100644
index 6e3fef2d60..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_macevents.c
+++ /dev/null
@@ -1,746 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <stdio.h>
25
26#if defined(__APPLE__) && defined(__MACH__)
27#include <Carbon/Carbon.h>
28#elif TARGET_API_MAC_CARBON && (UNIVERSAL_INTERFACES_VERSION > 0x0335)
29#include <Carbon.h>
30#else
31#include <Script.h>
32#include <LowMem.h>
33#include <Devices.h>
34#include <DiskInit.h>
35#include <ToolUtils.h>
36#endif
37
38#include "SDL_events.h"
39#include "SDL_video.h"
40#include "SDL_syswm.h"
41#include "../../events/SDL_events_c.h"
42#include "../../events/SDL_sysevents.h"
43#include "../SDL_cursor_c.h"
44#include "SDL_macevents_c.h"
45#include "SDL_mackeys.h"
46#include "SDL_macmouse_c.h"
47
48/* Define this to be able to collapse SDL windows.
49#define USE_APPEARANCE_MANAGER
50 */
51
52/* Macintosh resource constants */
53#define mApple 128 /* Apple menu resource */
54#define iAbout 1 /* About menu item */
55
56/* Functions to handle the About menu */
57static void Mac_DoAppleMenu(_THIS, long item);
58
59/* The translation table from a macintosh key scancode to a SDL keysym */
60static SDLKey MAC_keymap[256];
61static SDL_keysym *TranslateKey(int scancode, int modifiers,
62 SDL_keysym *keysym, int pressed);
63
64/* Handle activation and deactivation -- returns whether an event was posted */
65static int Mac_HandleActivate(int activate)
66{
67 if ( activate ) {
68 /* Show the current SDL application cursor */
69 SDL_SetCursor(NULL);
70
71 /* put our mask back case it changed during context switch */
72 SetEventMask(everyEvent & ~autoKeyMask);
73 } else {
74#if TARGET_API_MAC_CARBON
75 { Cursor cursor;
76 SetCursor(GetQDGlobalsArrow(&cursor));
77 }
78#else
79 SetCursor(&theQD->arrow);
80#endif
81 if ( ! Mac_cursor_showing ) {
82 ShowCursor();
83 Mac_cursor_showing = 1;
84 }
85 }
86 return(SDL_PrivateAppActive(activate, SDL_APPINPUTFOCUS));
87}
88
89static void myGlobalToLocal(_THIS, Point *pt)
90{
91 if ( SDL_VideoSurface && !(SDL_VideoSurface->flags&SDL_FULLSCREEN) ) {
92 GrafPtr saveport;
93 GetPort(&saveport);
94#if TARGET_API_MAC_CARBON
95 SetPort(GetWindowPort(SDL_Window));
96#else
97 SetPort(SDL_Window);
98#endif
99 GlobalToLocal(pt);
100 SetPort(saveport);
101 }
102}
103
104/* The main MacOS event handler */
105static int Mac_HandleEvents(_THIS, int wait4it)
106{
107 static int mouse_button = 1;
108 int i;
109 EventRecord event;
110
111#if TARGET_API_MAC_CARBON
112 /* There's no GetOSEvent() in the Carbon API. *sigh* */
113#define cooperative_multitasking 1
114#else
115 int cooperative_multitasking;
116 /* If we're running fullscreen, we can hog the MacOS events,
117 otherwise we had better play nicely with the other apps.
118 */
119 if ( this->screen && (this->screen->flags & SDL_FULLSCREEN) ) {
120 cooperative_multitasking = 0;
121 } else {
122 cooperative_multitasking = 1;
123 }
124#endif
125
126 /* If we call WaitNextEvent(), MacOS will check other processes
127 * and allow them to run, and perform other high-level processing.
128 */
129 if ( cooperative_multitasking || wait4it ) {
130 UInt32 wait_time;
131
132 /* Are we polling or not? */
133 if ( wait4it ) {
134 wait_time = 2147483647;
135 } else {
136 wait_time = 0;
137 }
138 WaitNextEvent(everyEvent, &event, wait_time, nil);
139 } else {
140#if ! TARGET_API_MAC_CARBON
141 GetOSEvent(everyEvent, &event);
142#endif
143 }
144
145#if TARGET_API_MAC_CARBON
146 /* for some reason, event.where isn't set ? */
147 GetGlobalMouse ( &event.where );
148#endif
149
150 /* Check for mouse motion */
151 if ( (event.where.h != last_where.h) ||
152 (event.where.v != last_where.v) ) {
153 Point pt;
154 pt = last_where = event.where;
155 myGlobalToLocal(this, &pt);
156 SDL_PrivateMouseMotion(0, 0, pt.h, pt.v);
157 }
158
159 /* Check the current state of the keyboard */
160 if ( SDL_GetAppState() & SDL_APPINPUTFOCUS ) {
161 KeyMap keys;
162 const Uint32 *keysptr = (Uint32 *) &keys;
163 const Uint32 *last_keysptr = (Uint32 *) &last_keys;
164
165 /* Check for special non-event keys */
166 if ( event.modifiers != last_mods ) {
167 static struct {
168 EventModifiers mask;
169 SDLKey key;
170 } mods[] = {
171 { alphaLock, SDLK_CAPSLOCK },
172#if 0 /* These are handled below in the GetKeys() code */
173 { cmdKey, SDLK_LMETA },
174 { shiftKey, SDLK_LSHIFT },
175 { rightShiftKey, SDLK_RSHIFT },
176 { optionKey, SDLK_LALT },
177 { rightOptionKey, SDLK_RALT },
178 { controlKey, SDLK_LCTRL },
179 { rightControlKey, SDLK_RCTRL },
180#endif /* 0 */
181 { 0, 0 }
182 };
183 SDL_keysym keysym;
184 Uint8 mode;
185 EventModifiers mod, mask;
186
187
188 /* Set up the keyboard event */
189 keysym.scancode = 0;
190 keysym.sym = SDLK_UNKNOWN;
191 keysym.mod = KMOD_NONE;
192 keysym.unicode = 0;
193
194 /* See what has changed, and generate events */
195 mod = event.modifiers;
196 for ( i=0; mods[i].mask; ++i ) {
197 mask = mods[i].mask;
198 if ( (mod&mask) != (last_mods&mask) ) {
199 keysym.sym = mods[i].key;
200 if ( (mod&mask) ||
201 (mods[i].key == SDLK_CAPSLOCK) ) {
202 mode = SDL_PRESSED;
203 } else {
204 mode = SDL_RELEASED;
205 }
206 SDL_PrivateKeyboard(mode, &keysym);
207 }
208 }
209
210 /* Save state for next time */
211 last_mods = mod;
212 }
213
214 /* Check for normal event keys, but we have to scan the
215 actual keyboard state because on Mac OS X a keydown event
216 is immediately followed by a keyup event.
217 */
218 GetKeys(keys);
219 if ( (keysptr[0] != last_keysptr[0]) ||
220 (keysptr[1] != last_keysptr[1]) ||
221 (keysptr[2] != last_keysptr[2]) ||
222 (keysptr[3] != last_keysptr[3]) ) {
223 SDL_keysym keysym;
224 int old_bit, new_bit;
225
226#ifdef DEBUG_KEYBOARD
227 fprintf(sterr, "New keys: 0x%x 0x%x 0x%x 0x%x\n",
228 new_keys[0], new_keys[1],
229 new_keys[2], new_keys[3]);
230#endif
231 for ( i=0; i<128; ++i ) {
232 old_bit = (((Uint8 *)last_keys)[i/8]>>(i%8)) & 0x01;
233 new_bit = (((Uint8 *)keys)[i/8]>>(i%8)) & 0x01;
234 if ( old_bit != new_bit ) {
235 /* Post the keyboard event */
236#ifdef DEBUG_KEYBOARD
237 fprintf(stderr,"Scancode: 0x%2.2X\n",i);
238#endif
239 SDL_PrivateKeyboard(new_bit,
240 TranslateKey(i, event.modifiers,
241 &keysym, new_bit));
242 }
243 }
244
245 /* Save state for next time */
246 last_keys[0] = keys[0];
247 last_keys[1] = keys[1];
248 last_keys[2] = keys[2];
249 last_keys[3] = keys[3];
250 }
251 }
252
253 /* Handle normal events */
254 switch (event.what) {
255 case mouseDown: {
256 WindowRef win;
257 short area;
258
259 area = FindWindow(event.where, &win);
260 /* Support switching between the SIOUX console
261 and SDL_Window by clicking in the window.
262 */
263 if ( win && (win != FrontWindow()) ) {
264 SelectWindow(win);
265 }
266 switch (area) {
267 case inMenuBar: /* Only the apple menu exists */
268 Mac_DoAppleMenu(this, MenuSelect(event.where));
269 HiliteMenu(0);
270 break;
271 case inDrag:
272#if TARGET_API_MAC_CARBON
273 DragWindow(win, event.where, NULL);
274#else
275 DragWindow(win, event.where, &theQD->screenBits.bounds);
276#endif
277 break;
278 case inGoAway:
279 if ( TrackGoAway(win, event.where) ) {
280 SDL_PrivateQuit();
281 }
282 break;
283 case inContent:
284 myGlobalToLocal(this, &event.where);
285 /* Treat command-click as right mouse button */
286 if ( event.modifiers & optionKey ) {
287 mouse_button = 2;
288 } else if ( event.modifiers & cmdKey ) {
289 mouse_button = 3;
290 } else {
291 mouse_button = 1;
292 }
293 SDL_PrivateMouseButton(SDL_PRESSED,
294 mouse_button, event.where.h, event.where.v);
295 break;
296 case inGrow: {
297 int newSize;
298
299 /* Don't allow resize if video mode isn't resizable */
300 if ( ! SDL_PublicSurface ||
301 ! (SDL_PublicSurface->flags & SDL_RESIZABLE) ) {
302 break;
303 }
304#if TARGET_API_MAC_CARBON
305 newSize = GrowWindow(win, event.where, NULL);
306#else
307 newSize = GrowWindow(win, event.where, &theQD->screenBits.bounds);
308#endif
309 if ( newSize ) {
310#if !TARGET_API_MAC_CARBON
311 EraseRect ( &theQD->screenBits.bounds );
312#endif
313 SizeWindow ( win, LoWord (newSize), HiWord (newSize), 1 );
314 SDL_PrivateResize ( LoWord (newSize), HiWord (newSize) );
315 }
316 } break;
317 case inZoomIn:
318 case inZoomOut:
319 if ( TrackBox (win, event.where, area )) {
320 Rect rect;
321#if !TARGET_API_MAC_CARBON
322 EraseRect ( &theQD->screenBits.bounds );
323#endif
324 ZoomWindow ( win, area, 0);
325 if ( area == inZoomIn ) {
326 GetWindowUserState(SDL_Window, &rect);
327 } else {
328 GetWindowStandardState(SDL_Window, &rect);
329 }
330 SDL_PrivateResize (rect.right-rect.left,
331 rect.bottom-rect.top);
332 }
333 break;
334#if TARGET_API_MAC_CARBON
335 case inCollapseBox:
336 if ( TrackBox (win, event.where, area )) {
337 if ( IsWindowCollapsable(win) ) {
338 CollapseWindow (win, !IsWindowCollapsed(win));
339 /* There should be something done like in inGrow case, but... */
340 }
341 }
342 break;
343#endif /* TARGET_API_MAC_CARBON */
344 case inSysWindow:
345#if TARGET_API_MAC_CARBON
346 /* Never happens in Carbon? */
347#else
348 SystemClick(&event, win);
349#endif
350 break;
351 default:
352 break;
353 }
354 }
355 break;
356 case mouseUp: {
357 myGlobalToLocal(this, &event.where);
358 /* Release the mouse button we simulated in the last press.
359 The drawback of this methos is we cannot press more than
360 one button. However, this doesn't matter, since there is
361 only a single logical mouse button, even if you have a
362 multi-button mouse, this doesn't matter at all.
363 */
364 SDL_PrivateMouseButton(SDL_RELEASED,
365 mouse_button, event.where.h, event.where.v);
366 }
367 break;
368#if 0 /* Handled above the switch statement */
369 case keyDown: {
370 SDL_keysym keysym;
371
372 SDL_PrivateKeyboard(SDL_PRESSED,
373 TranslateKey((event.message&keyCodeMask)>>8
374 event.modifiers, &keysym, 1));
375 }
376 break;
377 case keyUp: {
378 SDL_keysym keysym;
379
380 SDL_PrivateKeyboard(SDL_RELEASED,
381 TranslateKey((event.message&keyCodeMask)>>8
382 event.modifiers, &keysym, 0));
383 }
384 break;
385#endif
386 case updateEvt: {
387 BeginUpdate(SDL_Window);
388 #if SDL_VIDEO_OPENGL
389 if (SDL_VideoSurface->flags & SDL_OPENGL)
390 SDL_GL_SwapBuffers();
391 else
392 #endif
393 if ( (SDL_VideoSurface->flags & SDL_HWSURFACE) ==
394 SDL_SWSURFACE ) {
395 SDL_UpdateRect(SDL_VideoSurface, 0, 0, 0, 0);
396 }
397 EndUpdate(SDL_Window);
398 }
399 /* If this was an update event for the SIOUX console, we return 0
400 in order to stop an endless series of updates being triggered.
401 */
402 if ( (WindowRef) event.message != SDL_Window ) {
403 return 0;
404 }
405 break;
406 case activateEvt: {
407 Mac_HandleActivate(!!(event.modifiers & activeFlag));
408 }
409 break;
410 case diskEvt: {
411#if TARGET_API_MAC_CARBON
412 /* What are we supposed to do? */;
413#else
414 if ( ((event.message>>16)&0xFFFF) != noErr ) {
415 Point spot;
416 SetPt(&spot, 0x0070, 0x0050);
417 DIBadMount(spot, event.message);
418 }
419#endif
420 }
421 break;
422 case osEvt: {
423 switch ((event.message>>24) & 0xFF) {
424#if 0 /* Handled above the switch statement */
425 case mouseMovedMessage: {
426 myGlobalToLocal(this, &event.where);
427 SDL_PrivateMouseMotion(0, 0,
428 event.where.h, event.where.v);
429 }
430 break;
431#endif /* 0 */
432 case suspendResumeMessage: {
433 Mac_HandleActivate(!!(event.message & resumeFlag));
434 }
435 break;
436 }
437 }
438 break;
439 default: {
440 ;
441 }
442 break;
443 }
444 return (event.what != nullEvent);
445}
446
447
448void Mac_PumpEvents(_THIS)
449{
450 /* Process pending MacOS events */
451 while ( Mac_HandleEvents(this, 0) ) {
452 /* Loop and check again */;
453 }
454}
455
456void Mac_InitOSKeymap(_THIS)
457{
458 const void *KCHRPtr;
459 UInt32 state;
460 UInt32 value;
461 int i;
462 int world = SDLK_WORLD_0;
463
464 /* Map the MAC keysyms */
465 for ( i=0; i<SDL_arraysize(MAC_keymap); ++i )
466 MAC_keymap[i] = SDLK_UNKNOWN;
467
468 /* Defined MAC_* constants */
469 MAC_keymap[MK_ESCAPE] = SDLK_ESCAPE;
470 MAC_keymap[MK_F1] = SDLK_F1;
471 MAC_keymap[MK_F2] = SDLK_F2;
472 MAC_keymap[MK_F3] = SDLK_F3;
473 MAC_keymap[MK_F4] = SDLK_F4;
474 MAC_keymap[MK_F5] = SDLK_F5;
475 MAC_keymap[MK_F6] = SDLK_F6;
476 MAC_keymap[MK_F7] = SDLK_F7;
477 MAC_keymap[MK_F8] = SDLK_F8;
478 MAC_keymap[MK_F9] = SDLK_F9;
479 MAC_keymap[MK_F10] = SDLK_F10;
480 MAC_keymap[MK_F11] = SDLK_F11;
481 MAC_keymap[MK_F12] = SDLK_F12;
482 MAC_keymap[MK_PRINT] = SDLK_PRINT;
483 MAC_keymap[MK_SCROLLOCK] = SDLK_SCROLLOCK;
484 MAC_keymap[MK_PAUSE] = SDLK_PAUSE;
485 MAC_keymap[MK_POWER] = SDLK_POWER;
486 MAC_keymap[MK_BACKQUOTE] = SDLK_BACKQUOTE;
487 MAC_keymap[MK_1] = SDLK_1;
488 MAC_keymap[MK_2] = SDLK_2;
489 MAC_keymap[MK_3] = SDLK_3;
490 MAC_keymap[MK_4] = SDLK_4;
491 MAC_keymap[MK_5] = SDLK_5;
492 MAC_keymap[MK_6] = SDLK_6;
493 MAC_keymap[MK_7] = SDLK_7;
494 MAC_keymap[MK_8] = SDLK_8;
495 MAC_keymap[MK_9] = SDLK_9;
496 MAC_keymap[MK_0] = SDLK_0;
497 MAC_keymap[MK_MINUS] = SDLK_MINUS;
498 MAC_keymap[MK_EQUALS] = SDLK_EQUALS;
499 MAC_keymap[MK_BACKSPACE] = SDLK_BACKSPACE;
500 MAC_keymap[MK_INSERT] = SDLK_INSERT;
501 MAC_keymap[MK_HOME] = SDLK_HOME;
502 MAC_keymap[MK_PAGEUP] = SDLK_PAGEUP;
503 MAC_keymap[MK_NUMLOCK] = SDLK_NUMLOCK;
504 MAC_keymap[MK_KP_EQUALS] = SDLK_KP_EQUALS;
505 MAC_keymap[MK_KP_DIVIDE] = SDLK_KP_DIVIDE;
506 MAC_keymap[MK_KP_MULTIPLY] = SDLK_KP_MULTIPLY;
507 MAC_keymap[MK_TAB] = SDLK_TAB;
508 MAC_keymap[MK_q] = SDLK_q;
509 MAC_keymap[MK_w] = SDLK_w;
510 MAC_keymap[MK_e] = SDLK_e;
511 MAC_keymap[MK_r] = SDLK_r;
512 MAC_keymap[MK_t] = SDLK_t;
513 MAC_keymap[MK_y] = SDLK_y;
514 MAC_keymap[MK_u] = SDLK_u;
515 MAC_keymap[MK_i] = SDLK_i;
516 MAC_keymap[MK_o] = SDLK_o;
517 MAC_keymap[MK_p] = SDLK_p;
518 MAC_keymap[MK_LEFTBRACKET] = SDLK_LEFTBRACKET;
519 MAC_keymap[MK_RIGHTBRACKET] = SDLK_RIGHTBRACKET;
520 MAC_keymap[MK_BACKSLASH] = SDLK_BACKSLASH;
521 MAC_keymap[MK_DELETE] = SDLK_DELETE;
522 MAC_keymap[MK_END] = SDLK_END;
523 MAC_keymap[MK_PAGEDOWN] = SDLK_PAGEDOWN;
524 MAC_keymap[MK_KP7] = SDLK_KP7;
525 MAC_keymap[MK_KP8] = SDLK_KP8;
526 MAC_keymap[MK_KP9] = SDLK_KP9;
527 MAC_keymap[MK_KP_MINUS] = SDLK_KP_MINUS;
528 MAC_keymap[MK_CAPSLOCK] = SDLK_CAPSLOCK;
529 MAC_keymap[MK_a] = SDLK_a;
530 MAC_keymap[MK_s] = SDLK_s;
531 MAC_keymap[MK_d] = SDLK_d;
532 MAC_keymap[MK_f] = SDLK_f;
533 MAC_keymap[MK_g] = SDLK_g;
534 MAC_keymap[MK_h] = SDLK_h;
535 MAC_keymap[MK_j] = SDLK_j;
536 MAC_keymap[MK_k] = SDLK_k;
537 MAC_keymap[MK_l] = SDLK_l;
538 MAC_keymap[MK_SEMICOLON] = SDLK_SEMICOLON;
539 MAC_keymap[MK_QUOTE] = SDLK_QUOTE;
540 MAC_keymap[MK_RETURN] = SDLK_RETURN;
541 MAC_keymap[MK_KP4] = SDLK_KP4;
542 MAC_keymap[MK_KP5] = SDLK_KP5;
543 MAC_keymap[MK_KP6] = SDLK_KP6;
544 MAC_keymap[MK_KP_PLUS] = SDLK_KP_PLUS;
545 MAC_keymap[MK_LSHIFT] = SDLK_LSHIFT;
546 MAC_keymap[MK_z] = SDLK_z;
547 MAC_keymap[MK_x] = SDLK_x;
548 MAC_keymap[MK_c] = SDLK_c;
549 MAC_keymap[MK_v] = SDLK_v;
550 MAC_keymap[MK_b] = SDLK_b;
551 MAC_keymap[MK_n] = SDLK_n;
552 MAC_keymap[MK_m] = SDLK_m;
553 MAC_keymap[MK_COMMA] = SDLK_COMMA;
554 MAC_keymap[MK_PERIOD] = SDLK_PERIOD;
555 MAC_keymap[MK_SLASH] = SDLK_SLASH;
556#if 0 /* These are the same as the left versions - use left by default */
557 MAC_keymap[MK_RSHIFT] = SDLK_RSHIFT;
558#endif
559 MAC_keymap[MK_UP] = SDLK_UP;
560 MAC_keymap[MK_KP1] = SDLK_KP1;
561 MAC_keymap[MK_KP2] = SDLK_KP2;
562 MAC_keymap[MK_KP3] = SDLK_KP3;
563 MAC_keymap[MK_KP_ENTER] = SDLK_KP_ENTER;
564 MAC_keymap[MK_LCTRL] = SDLK_LCTRL;
565 MAC_keymap[MK_LALT] = SDLK_LALT;
566 MAC_keymap[MK_LMETA] = SDLK_LMETA;
567 MAC_keymap[MK_SPACE] = SDLK_SPACE;
568#if 0 /* These are the same as the left versions - use left by default */
569 MAC_keymap[MK_RMETA] = SDLK_RMETA;
570 MAC_keymap[MK_RALT] = SDLK_RALT;
571 MAC_keymap[MK_RCTRL] = SDLK_RCTRL;
572#endif
573 MAC_keymap[MK_LEFT] = SDLK_LEFT;
574 MAC_keymap[MK_DOWN] = SDLK_DOWN;
575 MAC_keymap[MK_RIGHT] = SDLK_RIGHT;
576 MAC_keymap[MK_KP0] = SDLK_KP0;
577 MAC_keymap[MK_KP_PERIOD] = SDLK_KP_PERIOD;
578
579#if defined(__APPLE__) && defined(__MACH__)
580 /* Wierd, these keys are on my iBook under Mac OS X
581 Note that the left arrow keysym is the same as left ctrl!?
582 */
583 MAC_keymap[MK_IBOOK_ENTER] = SDLK_KP_ENTER;
584 MAC_keymap[MK_IBOOK_RIGHT] = SDLK_RIGHT;
585 MAC_keymap[MK_IBOOK_DOWN] = SDLK_DOWN;
586 MAC_keymap[MK_IBOOK_UP] = SDLK_UP;
587 MAC_keymap[MK_IBOOK_LEFT] = SDLK_LEFT;
588#endif /* Mac OS X */
589
590 /* Up there we setup a static scancode->keysym map. However, it will not
591 * work very well on international keyboard. Hence we now query MacOS
592 * for its own keymap to adjust our own mapping table. However, this is
593 * bascially only useful for ascii char keys. This is also the reason
594 * why we keep the static table, too.
595 */
596
597 /* Get a pointer to the systems cached KCHR */
598 KCHRPtr = (void *)GetScriptManagerVariable(smKCHRCache);
599 if (KCHRPtr)
600 {
601 /* Loop over all 127 possible scan codes */
602 for (i = 0; i < 0x7F; i++)
603 {
604 /* We pretend a clean start to begin with (i.e. no dead keys active */
605 state = 0;
606
607 /* Now translate the key code to a key value */
608 value = KeyTranslate(KCHRPtr, i, &state) & 0xff;
609
610 /* If the state become 0, it was a dead key. We need to translate again,
611 passing in the new state, to get the actual key value */
612 if (state != 0)
613 value = KeyTranslate(KCHRPtr, i, &state) & 0xff;
614
615 /* Now we should have an ascii value, or 0. Try to figure out to which SDL symbol it maps */
616 if (value >= 128) /* Some non-ASCII char, map it to SDLK_WORLD_* */
617 MAC_keymap[i] = world++;
618 else if (value >= 32) /* non-control ASCII char */
619 MAC_keymap[i] = value;
620 }
621 }
622
623 /* The keypad codes are re-setup here, because the loop above cannot
624 * distinguish between a key on the keypad and a regular key. We maybe
625 * could get around this problem in another fashion: NSEvent's flags
626 * include a "NSNumericPadKeyMask" bit; we could check that and modify
627 * the symbol we return on the fly. However, this flag seems to exhibit
628 * some weird behaviour related to the num lock key
629 */
630 MAC_keymap[MK_KP0] = SDLK_KP0;
631 MAC_keymap[MK_KP1] = SDLK_KP1;
632 MAC_keymap[MK_KP2] = SDLK_KP2;
633 MAC_keymap[MK_KP3] = SDLK_KP3;
634 MAC_keymap[MK_KP4] = SDLK_KP4;
635 MAC_keymap[MK_KP5] = SDLK_KP5;
636 MAC_keymap[MK_KP6] = SDLK_KP6;
637 MAC_keymap[MK_KP7] = SDLK_KP7;
638 MAC_keymap[MK_KP8] = SDLK_KP8;
639 MAC_keymap[MK_KP9] = SDLK_KP9;
640 MAC_keymap[MK_KP_MINUS] = SDLK_KP_MINUS;
641 MAC_keymap[MK_KP_PLUS] = SDLK_KP_PLUS;
642 MAC_keymap[MK_KP_PERIOD] = SDLK_KP_PERIOD;
643 MAC_keymap[MK_KP_EQUALS] = SDLK_KP_EQUALS;
644 MAC_keymap[MK_KP_DIVIDE] = SDLK_KP_DIVIDE;
645 MAC_keymap[MK_KP_MULTIPLY] = SDLK_KP_MULTIPLY;
646 MAC_keymap[MK_KP_ENTER] = SDLK_KP_ENTER;
647}
648
649static SDL_keysym *TranslateKey(int scancode, int modifiers,
650 SDL_keysym *keysym, int pressed)
651{
652 /* Set the keysym information */
653 keysym->scancode = scancode;
654 keysym->sym = MAC_keymap[keysym->scancode];
655 keysym->mod = KMOD_NONE;
656 keysym->unicode = 0;
657 if ( pressed && SDL_TranslateUNICODE ) {
658 static unsigned long state = 0;
659 static Ptr keymap = nil;
660 Ptr new_keymap;
661
662 /* Get the current keyboard map resource */
663 new_keymap = (Ptr)GetScriptManagerVariable(smKCHRCache);
664 if ( new_keymap != keymap ) {
665 keymap = new_keymap;
666 state = 0;
667 }
668 keysym->unicode = KeyTranslate(keymap,
669 keysym->scancode|modifiers, &state) & 0xFFFF;
670 }
671 return(keysym);
672}
673
674void Mac_InitEvents(_THIS)
675{
676 /* Create apple menu bar */
677 apple_menu = GetMenu(mApple);
678 if ( apple_menu != nil ) {
679 AppendResMenu(apple_menu, 'DRVR');
680 InsertMenu(apple_menu, 0);
681 }
682 DrawMenuBar();
683
684 /* Get rid of spurious events at startup */
685 FlushEvents(everyEvent, 0);
686
687 /* Allow every event but keyrepeat */
688 SetEventMask(everyEvent & ~autoKeyMask);
689}
690
691void Mac_QuitEvents(_THIS)
692{
693 ClearMenuBar();
694 if ( apple_menu != nil ) {
695 ReleaseResource((char **)apple_menu);
696 }
697
698 /* Clean up pending events */
699 FlushEvents(everyEvent, 0);
700}
701
702static void Mac_DoAppleMenu(_THIS, long choice)
703{
704#if !TARGET_API_MAC_CARBON /* No Apple menu in OS X */
705 short menu, item;
706
707 item = (choice&0xFFFF);
708 choice >>= 16;
709 menu = (choice&0xFFFF);
710
711 switch (menu) {
712 case mApple: {
713 switch (item) {
714 case iAbout: {
715 /* Run the about box */;
716 }
717 break;
718 default: {
719 Str255 name;
720
721 GetMenuItemText(apple_menu, item, name);
722 OpenDeskAcc(name);
723 }
724 break;
725 }
726 }
727 break;
728 default: {
729 /* Ignore other menus */;
730 }
731 }
732#endif /* !TARGET_API_MAC_CARBON */
733}
734
735#if !TARGET_API_MAC_CARBON
736/* Since we don't initialize QuickDraw, we need to get a pointer to qd */
737struct QDGlobals *theQD = NULL;
738#endif
739
740/* Exported to the macmain code */
741void SDL_InitQuickDraw(struct QDGlobals *the_qd)
742{
743#if !TARGET_API_MAC_CARBON
744 theQD = the_qd;
745#endif
746}
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_macevents_c.h b/apps/plugins/sdl/src/video/maccommon/SDL_macevents_c.h
deleted file mode 100644
index f9a983bde1..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_macevents_c.h
+++ /dev/null
@@ -1,32 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "../macrom/SDL_romvideo.h"
25
26/* Functions exported by SDL_macevents.c for the video subsystem
27*/
28extern void Mac_InitEvents(_THIS);
29extern void Mac_QuitEvents(_THIS);
30
31extern void Mac_InitOSKeymap(_THIS);
32extern void Mac_PumpEvents(_THIS);
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_macgl.c b/apps/plugins/sdl/src/video/maccommon/SDL_macgl.c
deleted file mode 100644
index b7ded9bc5a..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_macgl.c
+++ /dev/null
@@ -1,197 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* AGL implementation of SDL OpenGL support */
25
26#include "SDL_lowvideo.h"
27#include "SDL_macgl_c.h"
28#include "SDL_loadso.h"
29
30
31/* krat: adding OpenGL support */
32int Mac_GL_Init(_THIS)
33{
34#if SDL_VIDEO_OPENGL
35 AGLPixelFormat format;
36 int i = 0;
37 GLint attributes [ 26 ]; /* 26 is max possible in this setup */
38 GLboolean noerr;
39
40 /* load the gl driver from a default path */
41 if ( ! this->gl_config.driver_loaded ) {
42 /* no driver has been loaded, use default (ourselves) */
43 if ( Mac_GL_LoadLibrary(this, NULL) < 0 ) {
44 return(-1);
45 }
46 }
47
48 attributes[i++] = AGL_RGBA;
49 if ( this->gl_config.red_size != 0 &&
50 this->gl_config.blue_size != 0 &&
51 this->gl_config.green_size != 0 ) {
52 attributes[i++] = AGL_RED_SIZE;
53 attributes[i++] = this->gl_config.red_size;
54 attributes[i++] = AGL_GREEN_SIZE;
55 attributes[i++] = this->gl_config.green_size;
56 attributes[i++] = AGL_BLUE_SIZE;
57 attributes[i++] = this->gl_config.blue_size;
58 attributes[i++] = AGL_ALPHA_SIZE;
59 attributes[i++] = this->gl_config.alpha_size;
60 }
61 if ( this->gl_config.double_buffer ) {
62 attributes[i++] = AGL_DOUBLEBUFFER;
63 }
64 if ( this->gl_config.depth_size != 0 ) {
65 attributes[i++] = AGL_DEPTH_SIZE;
66 attributes[i++] = this->gl_config.depth_size;
67 }
68 if ( this->gl_config.stencil_size != 0 ) {
69 attributes[i++] = AGL_STENCIL_SIZE;
70 attributes[i++] = this->gl_config.stencil_size;
71 }
72 if ( this->gl_config.accum_red_size != 0 &&
73 this->gl_config.accum_blue_size != 0 &&
74 this->gl_config.accum_green_size != 0 ) {
75
76 attributes[i++] = AGL_ACCUM_RED_SIZE;
77 attributes[i++] = this->gl_config.accum_red_size;
78 attributes[i++] = AGL_ACCUM_GREEN_SIZE;
79 attributes[i++] = this->gl_config.accum_green_size;
80 attributes[i++] = AGL_ACCUM_BLUE_SIZE;
81 attributes[i++] = this->gl_config.accum_blue_size;
82 attributes[i++] = AGL_ACCUM_ALPHA_SIZE;
83 attributes[i++] = this->gl_config.accum_alpha_size;
84 }
85 if ( this->gl_config.stereo ) {
86 attributes[i++] = AGL_STEREO;
87 }
88#if defined(AGL_SAMPLE_BUFFERS_ARB) && defined(AGL_SAMPLES_ARB)
89 if ( this->gl_config.multisamplebuffers != 0 ) {
90 attributes[i++] = AGL_SAMPLE_BUFFERS_ARB;
91 attributes[i++] = this->gl_config.multisamplebuffers;
92 }
93 if ( this->gl_config.multisamplesamples != 0 ) {
94 attributes[i++] = AGL_SAMPLES_ARB;
95 attributes[i++] = this->gl_config.multisamplesamples;
96 }
97#endif
98 if ( this->gl_config.accelerated > 0 ) {
99 attributes[i++] = AGL_ACCELERATED;
100 attributes[i++] = AGL_NO_RECOVERY;
101 }
102
103 attributes[i++] = AGL_ALL_RENDERERS;
104 attributes[i] = AGL_NONE;
105
106 format = aglChoosePixelFormat(NULL, 0, attributes);
107 if ( format == NULL ) {
108 SDL_SetError("Couldn't match OpenGL desired format");
109 return(-1);
110 }
111
112 glContext = aglCreateContext(format, NULL);
113 if ( glContext == NULL ) {
114 SDL_SetError("Couldn't create OpenGL context");
115 return(-1);
116 }
117 aglDestroyPixelFormat(format);
118
119 #if TARGET_API_MAC_CARBON
120 noerr = aglSetDrawable(glContext, GetWindowPort(SDL_Window));
121 #else
122 noerr = aglSetDrawable(glContext, (AGLDrawable)SDL_Window);
123 #endif
124
125 if(!noerr) {
126 SDL_SetError("Unable to bind GL context to window");
127 return(-1);
128 }
129 return(0);
130#else
131 SDL_SetError("OpenGL support not configured");
132 return(-1);
133#endif
134}
135
136void Mac_GL_Quit(_THIS)
137{
138#if SDL_VIDEO_OPENGL
139 if ( glContext != NULL ) {
140 aglSetCurrentContext(NULL);
141 aglSetDrawable(glContext, NULL);
142 aglDestroyContext(glContext);
143 glContext = NULL;
144 }
145#endif
146}
147
148#if SDL_VIDEO_OPENGL
149
150/* Make the current context active */
151int Mac_GL_MakeCurrent(_THIS)
152{
153 int retval;
154
155 retval = 0;
156 if( ! aglSetCurrentContext(glContext) ) {
157 SDL_SetError("Unable to make GL context current");
158 retval = -1;
159 }
160 return(retval);
161}
162
163void Mac_GL_SwapBuffers(_THIS)
164{
165 aglSwapBuffers(glContext);
166}
167
168int Mac_GL_LoadLibrary(_THIS, const char *location)
169{
170 if (location == NULL)
171#if __MACH__
172 location = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
173#else
174 location = "OpenGLLibrary";
175#endif
176
177 this->hidden->libraryHandle = SDL_LoadObject(location);
178
179 this->gl_config.driver_loaded = 1;
180 return (this->hidden->libraryHandle != NULL) ? 0 : -1;
181}
182
183void Mac_GL_UnloadLibrary(_THIS)
184{
185 SDL_UnloadObject(this->hidden->libraryHandle);
186
187 this->hidden->libraryHandle = NULL;
188 this->gl_config.driver_loaded = 0;
189}
190
191void* Mac_GL_GetProcAddress(_THIS, const char *proc)
192{
193 return SDL_LoadFunction( this->hidden->libraryHandle, proc );
194}
195
196#endif /* SDL_VIDEO_OPENGL */
197
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_macgl_c.h b/apps/plugins/sdl/src/video/maccommon/SDL_macgl_c.h
deleted file mode 100644
index 42cd70fbd2..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_macgl_c.h
+++ /dev/null
@@ -1,47 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/* AGL implementation of SDL OpenGL support */
24
25#include "SDL_config.h"
26
27#if SDL_VIDEO_OPENGL
28#include "SDL_opengl.h"
29#if __MACOSX__
30#include <AGL/agl.h> /* AGL.framework */
31#else
32#include <agl.h>
33#endif
34#endif /* SDL_VIDEO_OPENGL */
35
36/* OpenGL functions */
37extern int Mac_GL_Init(_THIS);
38extern void Mac_GL_Quit(_THIS);
39#if SDL_VIDEO_OPENGL
40extern int Mac_GL_MakeCurrent(_THIS);
41extern int Mac_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value);
42extern void Mac_GL_SwapBuffers(_THIS);
43extern int Mac_GL_LoadLibrary(_THIS, const char *location);
44extern void Mac_GL_UnloadLibrary(_THIS);
45extern void* Mac_GL_GetProcAddress(_THIS, const char *proc);
46#endif
47
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_mackeys.h b/apps/plugins/sdl/src/video/maccommon/SDL_mackeys.h
deleted file mode 100644
index dfed30da23..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_mackeys.h
+++ /dev/null
@@ -1,140 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23/* These are the Macintosh key scancode constants -- from Inside Macintosh */
24
25#define MK_ESCAPE 0x35
26#define MK_F1 0x7A
27#define MK_F2 0x78
28#define MK_F3 0x63
29#define MK_F4 0x76
30#define MK_F5 0x60
31#define MK_F6 0x61
32#define MK_F7 0x62
33#define MK_F8 0x64
34#define MK_F9 0x65
35#define MK_F10 0x6D
36#define MK_F11 0x67
37#define MK_F12 0x6F
38#define MK_PRINT 0x69
39#define MK_SCROLLOCK 0x6B
40#define MK_PAUSE 0x71
41#define MK_POWER 0x7F
42#define MK_BACKQUOTE 0x32
43#define MK_1 0x12
44#define MK_2 0x13
45#define MK_3 0x14
46#define MK_4 0x15
47#define MK_5 0x17
48#define MK_6 0x16
49#define MK_7 0x1A
50#define MK_8 0x1C
51#define MK_9 0x19
52#define MK_0 0x1D
53#define MK_MINUS 0x1B
54#define MK_EQUALS 0x18
55#define MK_BACKSPACE 0x33
56#define MK_INSERT 0x72
57#define MK_HOME 0x73
58#define MK_PAGEUP 0x74
59#define MK_NUMLOCK 0x47
60#define MK_KP_EQUALS 0x51
61#define MK_KP_DIVIDE 0x4B
62#define MK_KP_MULTIPLY 0x43
63#define MK_TAB 0x30
64#define MK_q 0x0C
65#define MK_w 0x0D
66#define MK_e 0x0E
67#define MK_r 0x0F
68#define MK_t 0x11
69#define MK_y 0x10
70#define MK_u 0x20
71#define MK_i 0x22
72#define MK_o 0x1F
73#define MK_p 0x23
74#define MK_LEFTBRACKET 0x21
75#define MK_RIGHTBRACKET 0x1E
76#define MK_BACKSLASH 0x2A
77#define MK_DELETE 0x75
78#define MK_END 0x77
79#define MK_PAGEDOWN 0x79
80#define MK_KP7 0x59
81#define MK_KP8 0x5B
82#define MK_KP9 0x5C
83#define MK_KP_MINUS 0x4E
84#define MK_CAPSLOCK 0x39
85#define MK_a 0x00
86#define MK_s 0x01
87#define MK_d 0x02
88#define MK_f 0x03
89#define MK_g 0x05
90#define MK_h 0x04
91#define MK_j 0x26
92#define MK_k 0x28
93#define MK_l 0x25
94#define MK_SEMICOLON 0x29
95#define MK_QUOTE 0x27
96#define MK_RETURN 0x24
97#define MK_KP4 0x56
98#define MK_KP5 0x57
99#define MK_KP6 0x58
100#define MK_KP_PLUS 0x45
101#define MK_LSHIFT 0x38
102#define MK_z 0x06
103#define MK_x 0x07
104#define MK_c 0x08
105#define MK_v 0x09
106#define MK_b 0x0B
107#define MK_n 0x2D
108#define MK_m 0x2E
109#define MK_COMMA 0x2B
110#define MK_PERIOD 0x2F
111#define MK_SLASH 0x2C
112#if 0 /* These are the same as the left versions - use left by default */
113#define MK_RSHIFT 0x38
114#endif
115#define MK_UP 0x7E
116#define MK_KP1 0x53
117#define MK_KP2 0x54
118#define MK_KP3 0x55
119#define MK_KP_ENTER 0x4C
120#define MK_LCTRL 0x3B
121#define MK_LALT 0x3A
122#define MK_LMETA 0x37
123#define MK_SPACE 0x31
124#if 0 /* These are the same as the left versions - use left by default */
125#define MK_RMETA 0x37
126#define MK_RALT 0x3A
127#define MK_RCTRL 0x3B
128#endif
129#define MK_LEFT 0x7B
130#define MK_DOWN 0x7D
131#define MK_RIGHT 0x7C
132#define MK_KP0 0x52
133#define MK_KP_PERIOD 0x41
134
135/* Wierd, these keys are on my iBook under Mac OS X */
136#define MK_IBOOK_ENTER 0x34
137#define MK_IBOOK_LEFT 0x3B
138#define MK_IBOOK_RIGHT 0x3C
139#define MK_IBOOK_DOWN 0x3D
140#define MK_IBOOK_UP 0x3E
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_macmouse.c b/apps/plugins/sdl/src/video/maccommon/SDL_macmouse.c
deleted file mode 100644
index f19ad1b966..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_macmouse.c
+++ /dev/null
@@ -1,129 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#if defined(__APPLE__) && defined(__MACH__)
25#include <Carbon/Carbon.h>
26#elif TARGET_API_MAC_CARBON && (UNIVERSAL_INTERFACES_VERSION > 0x0335)
27#include <Carbon.h>
28#else
29#include <Quickdraw.h>
30#endif
31
32/* Routines that are not supported by the Carbon API... */
33#if !TARGET_API_MAC_CARBON
34#include <CursorDevices.h>
35#endif
36
37#include "SDL_mouse.h"
38#include "SDL_macmouse_c.h"
39
40
41/* The implementation dependent data for the window manager cursor */
42struct WMcursor {
43 Cursor curs;
44};
45
46
47void Mac_FreeWMCursor(_THIS, WMcursor *cursor)
48{
49 SDL_free(cursor);
50}
51
52WMcursor *Mac_CreateWMCursor(_THIS,
53 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
54{
55 WMcursor *cursor;
56 int row, bytes;
57
58 /* Allocate the cursor memory */
59 cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor));
60 if ( cursor == NULL ) {
61 SDL_OutOfMemory();
62 return(NULL);
63 }
64 SDL_memset(cursor, 0, sizeof(*cursor));
65
66 if (w > 16)
67 w = 16;
68
69 if (h > 16)
70 h = 16;
71
72 bytes = (w+7)/8;
73
74 for ( row=0; row<h; ++row ) {
75 SDL_memcpy(&cursor->curs.data[row], data, bytes);
76 data += bytes;
77 }
78 for ( row=0; row<h; ++row ) {
79 SDL_memcpy(&cursor->curs.mask[row], mask, bytes);
80 mask += bytes;
81 }
82 cursor->curs.hotSpot.h = hot_x;
83 cursor->curs.hotSpot.v = hot_y;
84
85 /* That was easy. :) */
86 return(cursor);
87}
88
89int Mac_cursor_showing = 1;
90
91int Mac_ShowWMCursor(_THIS, WMcursor *cursor)
92{
93 if ( cursor == NULL ) {
94 if ( Mac_cursor_showing ) {
95 HideCursor();
96 Mac_cursor_showing = 0;
97 }
98 } else {
99 SetCursor(&cursor->curs);
100 if ( ! Mac_cursor_showing ) {
101 ShowCursor();
102 Mac_cursor_showing = 1;
103 }
104 }
105 return(1);
106}
107
108void Mac_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
109{
110#if !TARGET_API_MAC_CARBON
111 CursorDevice *cursordevice;
112
113 cursordevice = nil;
114 CursorDeviceNextDevice(&cursordevice);
115 if ( cursordevice != nil ) {
116 WindowPtr saveport;
117 Point where;
118
119 GetPort(&saveport);
120 SetPort(SDL_Window);
121 where.h = x;
122 where.v = y;
123 LocalToGlobal(&where);
124 SetPort(saveport);
125 CursorDeviceMoveTo(cursordevice, where.h, where.v);
126 }
127#endif /* !TARGET_API_MAC_CARBON */
128}
129
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_macmouse_c.h b/apps/plugins/sdl/src/video/maccommon/SDL_macmouse_c.h
deleted file mode 100644
index 18fb438b16..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_macmouse_c.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "../macrom/SDL_romvideo.h"
25
26/* Functions to be exported */
27extern void Mac_FreeWMCursor(_THIS, WMcursor *cursor);
28extern WMcursor *Mac_CreateWMCursor(_THIS,
29 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
30extern int Mac_ShowWMCursor(_THIS, WMcursor *cursor);
31extern void Mac_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
32
33/* Data to be exported */
34extern int Mac_cursor_showing;
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_macwm.c b/apps/plugins/sdl/src/video/maccommon/SDL_macwm.c
deleted file mode 100644
index 6f485a3fa9..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_macwm.c
+++ /dev/null
@@ -1,442 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#if defined(__APPLE__) && defined(__MACH__)
25#include <Carbon/Carbon.h>
26#elif TARGET_API_MAC_CARBON && (UNIVERSAL_INTERFACES_VERSION > 0x0335)
27#include <Carbon.h>
28#else
29#include <Windows.h>
30#include <Strings.h>
31#endif
32
33#if SDL_MACCLASSIC_GAMMA_SUPPORT
34#include <Devices.h>
35#include <Files.h>
36#include <MacTypes.h>
37#include <QDOffscreen.h>
38#include <Quickdraw.h>
39#include <Video.h>
40#endif
41
42#include "SDL_stdinc.h"
43#include "SDL_macwm_c.h"
44
45void Mac_SetCaption(_THIS, const char *title, const char *icon)
46{
47 /* Don't convert C to P string in place, because it may be read-only */
48 Str255 ptitle; /* MJS */
49 ptitle[0] = strlen (title);
50 SDL_memcpy(ptitle+1, title, ptitle[0]); /* MJS */
51 if (SDL_Window)
52 SetWTitle(SDL_Window, ptitle); /* MJS */
53}
54
55#if SDL_MACCLASSIC_GAMMA_SUPPORT
56/*
57 * ADC Gamma Ramp support...
58 *
59 * Mac Gamma Ramp code was originally from sample code provided by
60 * Apple Developer Connection, and not written specifically for SDL:
61 * "Contains: Functions to enable Mac OS device gamma adjustments using 3 channel 256 element 8 bit gamma ramps
62 * Written by: Geoff Stahl (ggs)
63 * Copyright: Copyright (c) 1999 Apple Computer, Inc., All Rights Reserved
64 * Disclaimer: You may incorporate this sample code into your applications without
65 * restriction, though the sample code has been provided "AS IS" and the
66 * responsibility for its operation is 100% yours. However, what you are
67 * not permitted to do is to redistribute the source as "DSC Sample Code"
68 * after having made changes. If you're going to re-distribute the source,
69 * we require that you make it clear in the source that the code was
70 * descended from Apple Sample Code, but that you've made changes."
71 * (The sample code has been integrated into this file, and thus is modified from the original Apple sources.)
72 */
73
74typedef struct recDeviceGamma /* storage for device handle and gamma table */
75{
76 GDHandle hGD; /* handle to device */
77 GammaTblPtr pDeviceGamma; /* pointer to device gamma table */
78} recDeviceGamma;
79typedef recDeviceGamma * precDeviceGamma;
80
81typedef struct recSystemGamma /* storage for system devices and gamma tables */
82{
83 short numDevices; /* number of devices */
84 precDeviceGamma * devGamma; /* array of pointers to device gamma records */
85} recSystemGamma;
86typedef recSystemGamma * precSystemGamma;
87
88static Ptr CopyGammaTable (GammaTblPtr pTableGammaIn)
89{
90 GammaTblPtr pTableGammaOut = NULL;
91 short tableSize, dataWidth;
92
93 if (pTableGammaIn) /* if there is a table to copy */
94 {
95 dataWidth = (pTableGammaIn->gDataWidth + 7) / 8; /* number of bytes per entry */
96 tableSize = sizeof (GammaTbl) + pTableGammaIn->gFormulaSize +
97 (pTableGammaIn->gChanCnt * pTableGammaIn->gDataCnt * dataWidth);
98 pTableGammaOut = (GammaTblPtr) NewPtr (tableSize); /* allocate new table */
99 if (pTableGammaOut)
100 BlockMove( (Ptr)pTableGammaIn, (Ptr)pTableGammaOut, tableSize); /* move everything */
101 }
102 return (Ptr)pTableGammaOut; /* return whatever we allocated, could be NULL */
103}
104
105static OSErr GetGammaTable (GDHandle hGD, GammaTblPtr * ppTableGammaOut)
106{
107 VDGammaRecord DeviceGammaRec;
108 CntrlParam cParam;
109 OSErr err;
110
111 cParam.ioCompletion = NULL; /* set up control params */
112 cParam.ioNamePtr = NULL;
113 cParam.ioVRefNum = 0;
114 cParam.ioCRefNum = (**hGD).gdRefNum;
115 cParam.csCode = cscGetGamma; /* Get Gamma commnd to device */
116 *(Ptr *)cParam.csParam = (Ptr) &DeviceGammaRec; /* record for gamma */
117
118 err = PBStatusSync( (ParmBlkPtr)&cParam ); /* get gamma */
119
120 *ppTableGammaOut = (GammaTblPtr)(DeviceGammaRec.csGTable); /* pull table out of record */
121
122 return err;
123}
124
125static Ptr GetDeviceGamma (GDHandle hGD)
126{
127 GammaTblPtr pTableGammaDevice = NULL;
128 GammaTblPtr pTableGammaReturn = NULL;
129 OSErr err;
130
131 err = GetGammaTable (hGD, &pTableGammaDevice); /* get a pointer to the devices table */
132 if ((noErr == err) && pTableGammaDevice) /* if succesful */
133 pTableGammaReturn = (GammaTblPtr) CopyGammaTable (pTableGammaDevice); /* copy to global */
134
135 return (Ptr) pTableGammaReturn;
136}
137
138static void DisposeGammaTable (Ptr pGamma)
139{
140 if (pGamma)
141 DisposePtr((Ptr) pGamma); /* get rid of it */
142}
143
144static void DisposeSystemGammas (Ptr* ppSystemGammas)
145{
146 precSystemGamma pSysGammaIn;
147 if (ppSystemGammas)
148 {
149 pSysGammaIn = (precSystemGamma) *ppSystemGammas;
150 if (pSysGammaIn)
151 {
152 short i;
153 for (i = 0; i < pSysGammaIn->numDevices; i++) /* for all devices */
154 if (pSysGammaIn->devGamma [i]) /* if pointer is valid */
155 {
156 DisposeGammaTable ((Ptr) pSysGammaIn->devGamma [i]->pDeviceGamma); /* dump gamma table */
157 DisposePtr ((Ptr) pSysGammaIn->devGamma [i]); /* dump device info */
158 }
159 DisposePtr ((Ptr) pSysGammaIn->devGamma); /* dump device pointer array */
160 DisposePtr ((Ptr) pSysGammaIn); /* dump system structure */
161 *ppSystemGammas = NULL;
162 }
163 }
164}
165
166static Boolean GetDeviceGammaRampGD (GDHandle hGD, Ptr pRamp)
167{
168 GammaTblPtr pTableGammaTemp = NULL;
169 long indexChan, indexEntry;
170 OSErr err;
171
172 if (pRamp) /* ensure pRamp is allocated */
173 {
174 err = GetGammaTable (hGD, &pTableGammaTemp); /* get a pointer to the current gamma */
175 if ((noErr == err) && pTableGammaTemp) /* if successful */
176 {
177 /* fill ramp */
178 unsigned char * pEntry = (unsigned char *) &pTableGammaTemp->gFormulaData + pTableGammaTemp->gFormulaSize; /* base of table */
179 short bytesPerEntry = (pTableGammaTemp->gDataWidth + 7) / 8; /* size, in bytes, of the device table entries */
180 short shiftRightValue = pTableGammaTemp->gDataWidth - 8; /* number of right shifts device -> ramp */
181 short channels = pTableGammaTemp->gChanCnt;
182 short entries = pTableGammaTemp->gDataCnt;
183 if (3 == channels) /* RGB format */
184 { /* note, this will create runs of entries if dest. is bigger (not linear interpolate) */
185 for (indexChan = 0; indexChan < channels; indexChan++)
186 for (indexEntry = 0; indexEntry < 256; indexEntry++)
187 *((unsigned char *) pRamp + (indexChan * 256) + indexEntry) =
188 *(pEntry + indexChan * entries * bytesPerEntry + indexEntry * entries * bytesPerEntry / 256) >> shiftRightValue;
189 }
190 else /* single channel format */
191 {
192 for (indexChan = 0; indexChan < 768; indexChan += 256) /* repeat for all 3 channels (step by ramp size) */
193 for (indexEntry = 0; indexEntry < 256; indexEntry++) /* for all entries set vramp value */
194 *((unsigned char *) pRamp + indexChan + indexEntry) =
195 *(pEntry + indexEntry * entries * bytesPerEntry / 256) >> shiftRightValue;
196 }
197 return true;
198 }
199 }
200 return false;
201}
202
203static Ptr GetSystemGammas (void)
204{
205 precSystemGamma pSysGammaOut; /* return pointer to system device gamma info */
206 short devCount = 0; /* number of devices attached */
207 Boolean fail = false;
208 GDHandle hGDevice;
209
210 pSysGammaOut = (precSystemGamma) NewPtr (sizeof (recSystemGamma)); /* allocate for structure */
211
212 hGDevice = GetDeviceList (); /* top of device list */
213 do /* iterate */
214 {
215 devCount++; /* count devices */
216 hGDevice = GetNextDevice (hGDevice); /* next device */
217 } while (hGDevice);
218
219 pSysGammaOut->devGamma = (precDeviceGamma *) NewPtr (sizeof (precDeviceGamma) * devCount); /* allocate for array of pointers to device records */
220 if (pSysGammaOut)
221 {
222 pSysGammaOut->numDevices = devCount; /* stuff count */
223
224 devCount = 0; /* reset iteration */
225 hGDevice = GetDeviceList ();
226 do
227 {
228 pSysGammaOut->devGamma [devCount] = (precDeviceGamma) NewPtr (sizeof (recDeviceGamma)); /* new device record */
229 if (pSysGammaOut->devGamma [devCount]) /* if we actually allocated memory */
230 {
231 pSysGammaOut->devGamma [devCount]->hGD = hGDevice; /* stuff handle */
232 pSysGammaOut->devGamma [devCount]->pDeviceGamma = (GammaTblPtr)GetDeviceGamma (hGDevice); /* copy gamma table */
233 }
234 else /* otherwise dump record on exit */
235 fail = true;
236 devCount++; /* next device */
237 hGDevice = GetNextDevice (hGDevice);
238 } while (hGDevice);
239 }
240 if (!fail) /* if we did not fail */
241 return (Ptr) pSysGammaOut; /* return pointer to structure */
242 else
243 {
244 DisposeSystemGammas ((Ptr *) &pSysGammaOut); /* otherwise dump the current structures (dispose does error checking) */
245 return NULL; /* could not complete */
246 }
247}
248
249static void RestoreDeviceGamma (GDHandle hGD, Ptr pGammaTable)
250{
251 VDSetEntryRecord setEntriesRec;
252 VDGammaRecord gameRecRestore;
253 CTabHandle hCTabDeviceColors;
254 Ptr csPtr;
255 OSErr err = noErr;
256
257 if (pGammaTable) /* if we have a table to restore */
258 {
259 gameRecRestore.csGTable = pGammaTable; /* setup restore record */
260 csPtr = (Ptr) &gameRecRestore;
261 err = Control((**hGD).gdRefNum, cscSetGamma, (Ptr) &csPtr); /* restore gamma */
262
263 if ((noErr == err) && (8 == (**(**hGD).gdPMap).pixelSize)) /* if successful and on an 8 bit device */
264 {
265 hCTabDeviceColors = (**(**hGD).gdPMap).pmTable; /* do SetEntries to force CLUT update */
266 setEntriesRec.csTable = (ColorSpec *) &(**hCTabDeviceColors).ctTable;
267 setEntriesRec.csStart = 0;
268 setEntriesRec.csCount = (**hCTabDeviceColors).ctSize;
269 csPtr = (Ptr) &setEntriesRec;
270
271 err = Control((**hGD).gdRefNum, cscSetEntries, (Ptr) &csPtr); /* SetEntries in CLUT */
272 }
273 }
274}
275
276static void RestoreSystemGammas (Ptr pSystemGammas)
277{
278 short i;
279 precSystemGamma pSysGammaIn = (precSystemGamma) pSystemGammas;
280 if (pSysGammaIn)
281 for (i = 0; i < pSysGammaIn->numDevices; i++) /* for all devices */
282 RestoreDeviceGamma (pSysGammaIn->devGamma [i]->hGD, (Ptr) pSysGammaIn->devGamma [i]->pDeviceGamma); /* restore gamma */
283}
284
285static Ptr CreateEmptyGammaTable (short channels, short entries, short bits)
286{
287 GammaTblPtr pTableGammaOut = NULL;
288 short tableSize, dataWidth;
289
290 dataWidth = (bits + 7) / 8; /* number of bytes per entry */
291 tableSize = sizeof (GammaTbl) + (channels * entries * dataWidth);
292 pTableGammaOut = (GammaTblPtr) NewPtrClear (tableSize); /* allocate new tabel */
293
294 if (pTableGammaOut) /* if we successfully allocated */
295 {
296 pTableGammaOut->gVersion = 0; /* set parameters based on input */
297 pTableGammaOut->gType = 0;
298 pTableGammaOut->gFormulaSize = 0;
299 pTableGammaOut->gChanCnt = channels;
300 pTableGammaOut->gDataCnt = entries;
301 pTableGammaOut->gDataWidth = bits;
302 }
303 return (Ptr)pTableGammaOut; /* return whatever we allocated */
304}
305
306static Boolean SetDeviceGammaRampGD (GDHandle hGD, Ptr pRamp)
307{
308 VDSetEntryRecord setEntriesRec;
309 VDGammaRecord gameRecRestore;
310 GammaTblPtr pTableGammaNew;
311 GammaTblPtr pTableGammaCurrent = NULL;
312 CTabHandle hCTabDeviceColors;
313 Ptr csPtr;
314 OSErr err;
315 short dataBits, entries, channels = 3; /* force three channels in the gamma table */
316
317 if (pRamp) /* ensure pRamp is allocated */
318 {
319 err= GetGammaTable (hGD, &pTableGammaCurrent); /* get pointer to current table */
320 if ((noErr == err) && pTableGammaCurrent)
321 {
322 dataBits = pTableGammaCurrent->gDataWidth; /* table must have same data width */
323 entries = pTableGammaCurrent->gDataCnt; /* table must be same size */
324 pTableGammaNew = (GammaTblPtr) CreateEmptyGammaTable (channels, entries, dataBits); /* our new table */
325 if (pTableGammaNew) /* if successful fill table */
326 {
327 unsigned char * pGammaBase = (unsigned char *) &pTableGammaNew->gFormulaData + pTableGammaNew->gFormulaSize; /* base of table */
328 if ((256 == entries) && (8 == dataBits)) /* simple case: direct mapping */
329 BlockMove ((Ptr)pRamp, (Ptr)pGammaBase, channels * entries); /* move everything */
330 else /* tough case handle entry, channel and data size disparities */
331 {
332 short indexChan, indexEntry;
333 short bytesPerEntry = (dataBits + 7) / 8; /* size, in bytes, of the device table entries */
334 short shiftRightValue = 8 - dataBits; /* number of right shifts ramp -> device */
335 shiftRightValue += ((bytesPerEntry - 1) * 8); /* multibyte entries and the need to map a byte at a time most sig. to least sig. */
336 for (indexChan = 0; indexChan < channels; indexChan++) /* for all the channels */
337 for (indexEntry = 0; indexEntry < entries; indexEntry++) /* for all the entries */
338 {
339 short currentShift = shiftRightValue; /* reset current bit shift */
340 long temp = *((unsigned char *)pRamp + (indexChan << 8) + (indexEntry << 8) / entries); /* get data from ramp */
341 short indexByte;
342 for (indexByte = 0; indexByte < bytesPerEntry; indexByte++) /* for all bytes */
343 {
344 if (currentShift < 0) /* shift data correctly for current byte */
345 *(pGammaBase++) = temp << -currentShift;
346 else
347 *(pGammaBase++) = temp >> currentShift;
348 currentShift -= 8; /* increment shift to align to next less sig. byte */
349 }
350 }
351 }
352
353 /* set gamma */
354 gameRecRestore.csGTable = (Ptr) pTableGammaNew; /* setup restore record */
355 csPtr = (Ptr) &gameRecRestore;
356 err = Control((**hGD).gdRefNum, cscSetGamma, (Ptr) &csPtr); /* restore gamma (note, display drivers may delay returning from this until VBL) */
357
358 if ((8 == (**(**hGD).gdPMap).pixelSize) && (noErr == err)) /* if successful and on an 8 bit device */
359 {
360 hCTabDeviceColors = (**(**hGD).gdPMap).pmTable; /* do SetEntries to force CLUT update */
361 setEntriesRec.csTable = (ColorSpec *) &(**hCTabDeviceColors).ctTable;
362 setEntriesRec.csStart = 0;
363 setEntriesRec.csCount = (**hCTabDeviceColors).ctSize;
364 csPtr = (Ptr) &setEntriesRec;
365 err = Control((**hGD).gdRefNum, cscSetEntries, (Ptr) &csPtr); /* SetEntries in CLUT */
366 }
367 DisposeGammaTable ((Ptr) pTableGammaNew); /* dump table */
368 if (noErr == err)
369 return true;
370 }
371 }
372 }
373 else /* set NULL gamma -> results in linear map */
374 {
375 gameRecRestore.csGTable = (Ptr) NULL; /* setup restore record */
376 csPtr = (Ptr) &gameRecRestore;
377 err = Control((**hGD).gdRefNum, cscSetGamma, (Ptr) &csPtr); /* restore gamma */
378
379 if ((8 == (**(**hGD).gdPMap).pixelSize) && (noErr == err)) /* if successful and on an 8 bit device */
380 {
381 hCTabDeviceColors = (**(**hGD).gdPMap).pmTable; /* do SetEntries to force CLUT update */
382 setEntriesRec.csTable = (ColorSpec *) &(**hCTabDeviceColors).ctTable;
383 setEntriesRec.csStart = 0;
384 setEntriesRec.csCount = (**hCTabDeviceColors).ctSize;
385 csPtr = (Ptr) &setEntriesRec;
386 err = Control((**hGD).gdRefNum, cscSetEntries, (Ptr) &csPtr); /* SetEntries in CLUT */
387 }
388 if (noErr == err)
389 return true;
390 }
391 return false; /* memory allocation or device control failed if we get here */
392}
393
394/* end of ADC Gamma Ramp support code... */
395
396static Ptr systemGammaPtr;
397
398void Mac_QuitGamma(_THIS)
399{
400 if (systemGammaPtr)
401 {
402 RestoreSystemGammas(systemGammaPtr);
403 DisposeSystemGammas(&systemGammaPtr);
404 }
405}
406
407static unsigned char shiftedRamp[3 * 256];
408
409int Mac_SetGammaRamp(_THIS, Uint16 *ramp)
410{
411 int i;
412 if (!systemGammaPtr)
413 systemGammaPtr = GetSystemGammas();
414 for (i = 0; i < 3 * 256; i++)
415 {
416 shiftedRamp[i] = ramp[i] >> 8;
417 }
418
419 if (SetDeviceGammaRampGD(GetMainDevice(), (Ptr) shiftedRamp))
420 return 0;
421 else
422 return -1;
423}
424
425int Mac_GetGammaRamp(_THIS, Uint16 *ramp)
426{
427 if (GetDeviceGammaRampGD(GetMainDevice(), (Ptr) shiftedRamp))
428 {
429 int i;
430 for (i = 0; i < 3 * 256; i++)
431 {
432 ramp[i] = shiftedRamp[i] << 8;
433 }
434 return 0;
435 }
436 else
437 return -1;
438}
439
440#endif /* SDL_MACCLASSIC_GAMMA_SUPPORT */
441
442
diff --git a/apps/plugins/sdl/src/video/maccommon/SDL_macwm_c.h b/apps/plugins/sdl/src/video/maccommon/SDL_macwm_c.h
deleted file mode 100644
index a0554d16dc..0000000000
--- a/apps/plugins/sdl/src/video/maccommon/SDL_macwm_c.h
+++ /dev/null
@@ -1,41 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "../macrom/SDL_romvideo.h"
25
26/* Functions to be exported */
27extern void Mac_SetCaption(_THIS, const char *title, const char *icon);
28
29/*
30 * There's no Carbonized gamma support in Mac OS X, since PBStatusSync() and
31 * Control() aren't supported in OS X's Carbonlib. Use the Quartz driver
32 * instead.
33 */
34#define SDL_MACCLASSIC_GAMMA_SUPPORT ((defined(__APPLE__) && defined(__MACH__)) == 0)
35
36#if SDL_MACCLASSIC_GAMMA_SUPPORT
37extern void Mac_QuitGamma(_THIS);
38extern int Mac_SetGammaRamp(_THIS, Uint16 *ramp);
39extern int Mac_GetGammaRamp(_THIS, Uint16 *ramp);
40#endif
41
diff --git a/apps/plugins/sdl/src/video/macdsp/SDL_dspvideo.c b/apps/plugins/sdl/src/video/macdsp/SDL_dspvideo.c
deleted file mode 100644
index aa31127669..0000000000
--- a/apps/plugins/sdl/src/video/macdsp/SDL_dspvideo.c
+++ /dev/null
@@ -1,1422 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Written by Darrell Walisser <dwaliss1@purdue.edu>
26
27 Implementation notes ----------------------------------------------------------------------
28
29 A bit on GWorlds in VRAM from technote 1182:
30
31 There are two important things to note about GWorld's allocated in
32 VRAM. First, the base address retrieved through GetPixBaseAddr or
33 read directly from the PixMap structure can become invalid anytime
34 memory is allocated in VRAM. This can occur either by explicit
35 allocations, such as calls to NewGWorld, or by implicit ones, such as
36 those associated with the internal texture allocation of OpenGL. The
37 stored pixel images themselves will still be valid but may have been
38 moved in VRAM, thus rendering any stored base addresses invalid.
39 You should never store an image's base address for longer than is
40 necessary and especially never across calls to NewGWorld or
41 texture-creation routines.
42
43 Secondly, an offscreen pixel image allocated in VRAM can be
44 purged at system task time by the display driver. This means any
45 time your application yields time such by calling WaitNextEvent or
46 SystemTask you can lose your VRAM GWorld contents. While this
47 happens infrequently, usually associated with display resolution or
48 pixel depth changes you must code for this eventuality. This purge
49 can occur whether or not the GWorld is locked or not. A return value
50 of false from LockPixels, a NULL return value from GetPixBaseAddr
51 or NULL in the baseAddr field of the PixMap mean that the pixel
52 image has been purged. To reallocate it you can either call
53 UpdateGWorld or Dispose your current GWorld through
54 DisposeGWorld and reallocate it via NewGWorld. Either way you must
55 then rebuild the pixel image.
56
57------------------------------------------------------------------------------------
58
59 Currently, I don't account for (1). In my testing, NewGWorld never invalidated
60 other existing GWorlds in VRAM. However, I do have protection for (2).
61 Namely, I am using GetOSEvent() instead of WaitNextEvent() so that there are no
62 context switches (the app hogs the CPU). Eventually a book-keeping system should
63 be coded to take care of (1) and (2).
64
65------------------------------------------------------------------------------------
66
67 System requirements (* denotes optional):
68
69 1. DrawSprocket 1.7.3
70 2. *MacOS 9 or later (but *not* Mac OS X) for hardware accelerated blit / fill
71 3. *May also require certain graphics hardware for (2). I trust that all Apple OEM
72 hardware will work. Third party accelerators may work if they have QuickDraw
73 acceleration in the drivers and the drivers have been updated for OS 9. The current
74 Voodoo 3 drivers (1.0b12) do not work.
75
76 Coding suggestions:
77
78 1. Use SDL_UpdateRects !
79
80 If no QuickDraw acceleration is present, double-buffered surfaces will use a back buffer
81 in System memory. I recommend you use SDL_UpdateRects with double-buffered surfaces
82 for best performance on these cards, since the overhead is nearly zero for VRAM back buffer.
83
84 2. Load most-resident surfaces first.
85
86 If you fill up VRAM or AGP memory, there is no contingency for purging to make room for the next one.
87 Therefore, you should load the surfaces you plan to use the most frequently first.
88 Sooner or later, I will code LRU replacement to help this.
89
90 TODO:
91 Some kind of posterized mode for resolutions < 640x480.
92 Window support / fullscreen toggle.
93 Figure out how much VRAM is available. Put in video->info->video_mem.
94 Track VRAM usage.
95
96 BUGS:
97 I can't create a hardware surface the same size as the screen?! How to fix?
98
99
100
101 COMPILE OPTIONS:
102
103 DSP_TRY_CC_AND_AA - Define if you want to try HWA color-key and alpha blitters
104 HW color-key blitting gives substantial improvements,
105 but hw alpha is neck-and-neck with SDL's soft bitter.
106
107 DSP_NO_SYNC_VBL - Define for HWA double-buffered surfaces: don't sync
108 pseudo-flip to monitor redraw.
109
110 DSP_NO_SYNC_OPENGL - Define for OpenGL surfaces: don't sync buffer swap. Synching buffer
111 swap may result in reduced performance, but can eliminate some
112 tearing artifacts.
113 CHANGELOG:
114 09/17/00 Lots of little tweaks. Build modelist in reverse order so largest contexts
115 list first. Compared various methods with ROM methods and fixed rez switch
116 crashing bug in GL Tron. (Woohoo!)
117*/
118
119#define DSP_TRY_CC_AND_AA
120
121/* #define DSP_NO_SYNC_VBL */
122
123#define DSP_NO_SYNC_OPENGL
124
125
126#if defined(__APPLE__) && defined(__MACH__)
127#include <Carbon/Carbon.h>
128#include <DrawSprocket/DrawSprocket.h>
129#elif TARGET_API_MAC_CARBON && (UNIVERSAL_INTERFACES_VERSION > 0x0335)
130#include <Carbon.h>
131#include <DrawSprocket.h>
132#else
133#include <LowMem.h>
134#include <Gestalt.h>
135#include <Devices.h>
136#include <DiskInit.h>
137#include <QDOffscreen.h>
138#include <DrawSprocket.h>
139#endif
140
141#include "SDL_video.h"
142#include "SDL_syswm.h"
143#include "../SDL_sysvideo.h"
144#include "../SDL_blit.h"
145#include "../SDL_pixels_c.h"
146#include "SDL_dspvideo.h"
147#include "../maccommon/SDL_macgl_c.h"
148#include "../maccommon/SDL_macwm_c.h"
149#include "../maccommon/SDL_macmouse_c.h"
150#include "../maccommon/SDL_macevents_c.h"
151
152/* Initialization/Query functions */
153static int DSp_VideoInit(_THIS, SDL_PixelFormat *vformat);
154static SDL_Rect **DSp_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
155static SDL_Surface *DSp_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
156static int DSp_SetColors(_THIS, int firstcolor, int ncolors,
157 SDL_Color *colors);
158static int DSp_CreatePalette(_THIS);
159static int DSp_DestroyPalette(_THIS);
160static void DSp_VideoQuit(_THIS);
161
162static int DSp_GetMainDevice (_THIS, GDHandle *device);
163static void DSp_IsHWAvailable (_THIS, SDL_PixelFormat *vformat);
164static void DSp_DSpUpdate(_THIS, int numrects, SDL_Rect *sdl_rects);
165static void DSp_DirectUpdate(_THIS, int numrects, SDL_Rect *sdl_rects);
166
167/* Hardware surface functions */
168static int DSp_SetHWAlpha(_THIS, SDL_Surface *surface, UInt8 alpha);
169static int DSp_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key);
170static int DSp_NewHWSurface(_THIS, CGrafPtr *port, int depth, int width, int height);
171static int DSp_AllocHWSurface(_THIS, SDL_Surface *surface);
172static int DSp_LockHWSurface(_THIS, SDL_Surface *surface);
173static void DSp_UnlockHWSurface(_THIS, SDL_Surface *surface);
174static void DSp_FreeHWSurface(_THIS, SDL_Surface *surface);
175static int DSp_FlipHWSurface(_THIS, SDL_Surface *surface);
176static int DSp_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dest);
177static int DSp_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
178 SDL_Surface *dst, SDL_Rect *dstrect);
179static int DSp_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color);
180
181#if SDL_VIDEO_OPENGL
182 static void DSp_GL_SwapBuffers (_THIS);
183#endif
184
185#if ! TARGET_API_MAC_CARBON
186
187 #define GetPortPixRowBytes(x) ( (*(x->portPixMap))->rowBytes )
188 #define GetGDevPixMap(x) ((**(x)).gdPMap)
189 #define GetPortPixMap(x) ((*(x)).portPixMap)
190
191 #define GetPixDepth(y) ((**(y)).pixelSize)
192 //#define GetPixRowBytes(y) ((**(y)).rowBytes)
193 //#define GetPixBaseAddr(y) ((**(y)).baseAddr)
194 #define GetPixCTab(y) ((**(y)).pmTable)
195 #define GetPortBitMapForCopyBits(x) (&(((GrafPtr)(x))->portBits))
196
197#else
198 #define GetPortPixRowBytes(x) (GetPixRowBytes(GetPortPixMap(x)) )
199 #define GetGDevPixMap(x) ((**(x)).gdPMap)
200
201#endif
202
203typedef struct private_hwdata {
204
205 GWorldPtr offscreen; // offscreen gworld in VRAM or AGP
206
207 #ifdef DSP_TRY_CC_AND_AA
208 GWorldPtr mask; // transparent mask
209 RGBColor alpha; // alpha color
210 RGBColor trans; // transparent color
211 #endif
212
213} private_hwdata;
214
215typedef private_hwdata private_swdata ; /* have same fields */
216
217/* Macintosh toolbox driver bootstrap functions */
218
219static int DSp_Available(void)
220{
221 /* Check for DrawSprocket */
222#if ! TARGET_API_MAC_OSX
223 /* This check is only meaningful if you weak-link DrawSprocketLib */
224 return ((Ptr)DSpStartup != (Ptr)kUnresolvedCFragSymbolAddress);
225#else
226 return 1; // DrawSprocket.framework doesn't have it all, but it's there
227#endif
228}
229
230static void DSp_DeleteDevice(SDL_VideoDevice *device)
231{
232 /* -dw- taking no chances with null pointers */
233 if (device) {
234
235 if (device->hidden) {
236
237 if (device->hidden->dspinfo)
238 SDL_free(device->hidden->dspinfo);
239
240 SDL_free(device->hidden);
241 }
242 SDL_free(device);
243 }
244}
245
246static SDL_VideoDevice *DSp_CreateDevice(int devindex)
247{
248 SDL_VideoDevice *device;
249
250 /* Initialize all variables that we clean on shutdown */
251 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
252 if ( device ) {
253 SDL_memset(device, 0, sizeof (*device));
254 device->hidden = (struct SDL_PrivateVideoData *)
255 SDL_malloc((sizeof *device->hidden));
256 if (device->hidden)
257 SDL_memset(device->hidden, 0, sizeof ( *(device->hidden) ) );
258 }
259 if ( (device == NULL) || (device->hidden == NULL) ) {
260 SDL_OutOfMemory();
261
262 if ( device ) {
263
264 if (device->hidden)
265 SDL_free(device->hidden);
266
267 SDL_free(device);
268 }
269
270 return(NULL);
271 }
272
273 /* Allocate DrawSprocket information */
274 device->hidden->dspinfo = (struct DSpInfo *)SDL_malloc(
275 (sizeof *device->hidden->dspinfo));
276 if ( device->hidden->dspinfo == NULL ) {
277 SDL_OutOfMemory();
278 SDL_free(device->hidden);
279 SDL_free(device);
280 return(0);
281 }
282 SDL_memset(device->hidden->dspinfo, 0, (sizeof *device->hidden->dspinfo));
283
284 /* Set the function pointers */
285 device->VideoInit = DSp_VideoInit;
286 device->ListModes = DSp_ListModes;
287 device->SetVideoMode = DSp_SetVideoMode;
288 device->SetColors = DSp_SetColors;
289 device->UpdateRects = NULL;
290 device->VideoQuit = DSp_VideoQuit;
291 device->AllocHWSurface = DSp_AllocHWSurface;
292 device->CheckHWBlit = NULL;
293 device->FillHWRect = NULL;
294 device->SetHWColorKey = NULL;
295 device->SetHWAlpha = NULL;
296 device->LockHWSurface = DSp_LockHWSurface;
297 device->UnlockHWSurface = DSp_UnlockHWSurface;
298 device->FlipHWSurface = DSp_FlipHWSurface;
299 device->FreeHWSurface = DSp_FreeHWSurface;
300#if SDL_MACCLASSIC_GAMMA_SUPPORT
301 device->SetGammaRamp = Mac_SetGammaRamp;
302 device->GetGammaRamp = Mac_GetGammaRamp;
303#endif
304#if SDL_VIDEO_OPENGL
305 device->GL_MakeCurrent = Mac_GL_MakeCurrent;
306 device->GL_SwapBuffers = DSp_GL_SwapBuffers;
307 device->GL_LoadLibrary = Mac_GL_LoadLibrary;
308 device->GL_GetProcAddress = Mac_GL_GetProcAddress;
309#endif
310 device->SetCaption = NULL;
311 device->SetIcon = NULL;
312 device->IconifyWindow = NULL;
313 device->GrabInput = NULL;
314 device->GetWMInfo = NULL;
315 device->FreeWMCursor = Mac_FreeWMCursor;
316 device->CreateWMCursor = Mac_CreateWMCursor;
317 device->ShowWMCursor = Mac_ShowWMCursor;
318 device->WarpWMCursor = Mac_WarpWMCursor;
319 device->InitOSKeymap = Mac_InitOSKeymap;
320 device->PumpEvents = Mac_PumpEvents;
321
322 device->GrabInput = NULL;
323 device->CheckMouseMode = NULL;
324
325 device->free = DSp_DeleteDevice;
326
327 return device;
328}
329
330VideoBootStrap DSp_bootstrap = {
331 "DSp", "MacOS DrawSprocket",
332 DSp_Available, DSp_CreateDevice
333};
334
335/* Use DSp/Display Manager to build mode list for given screen */
336static SDL_Rect** DSp_BuildModeList (const GDHandle gDevice, int *displayWidth, int *displayHeight)
337{
338 DSpContextAttributes attributes;
339 DSpContextReference context;
340 DisplayIDType displayID;
341 SDL_Rect temp_list [16];
342 SDL_Rect **mode_list;
343 int width, height, i, j;
344
345 #if TARGET_API_MAC_OSX
346
347 displayID = 0;
348
349 #else
350 /* Ask Display Manager for integer id of screen device */
351 if ( DMGetDisplayIDByGDevice (gDevice, &displayID, SDL_TRUE) != noErr ) {
352 return NULL;
353 }
354 #endif
355 /* Get the first possible DSp context on this device */
356 if ( DSpGetFirstContext (displayID, &context) != noErr ) {
357 return NULL;
358 }
359
360 if ( DSpContext_GetAttributes (context, &attributes) != noErr )
361 return NULL;
362
363 *displayWidth = attributes.displayWidth;
364 *displayHeight = attributes.displayHeight;
365
366 for ( i = 0; i < SDL_arraysize(temp_list); i++ ) {
367 width = attributes.displayWidth;
368 height = attributes.displayHeight;
369
370 temp_list [i].x = 0 | attributes.displayBestDepth;
371 temp_list [i].y = 0;
372 temp_list [i].w = width;
373 temp_list [i].h = height;
374
375 /* DSp will report many different contexts with the same width and height. */
376 /* They will differ in bit depth and refresh rate. */
377 /* We will ignore them until we reach one with a different width/height */
378 /* When there are no more contexts to look at, we will quit building the list*/
379 while ( width == attributes.displayWidth && height == attributes.displayHeight ) {
380
381 OSStatus err = DSpGetNextContext (context, &context);
382 if (err != noErr)
383 if (err == kDSpContextNotFoundErr)
384 goto done;
385 else
386 return NULL;
387
388 if ( DSpContext_GetAttributes (context, &attributes) != noErr )
389 return NULL;
390
391 temp_list [i].x |= attributes.displayBestDepth;
392 }
393 }
394done:
395 i++; /* i was not incremented before kicking out of the loop */
396
397 mode_list = (SDL_Rect**) SDL_malloc (sizeof (SDL_Rect*) * (i+1));
398 if (mode_list) {
399
400 /* -dw- new stuff: build in reverse order so largest sizes list first */
401 for (j = i-1; j >= 0; j--) {
402 mode_list [j] = (SDL_Rect*) SDL_malloc (sizeof (SDL_Rect));
403 if (mode_list [j])
404 SDL_memcpy (mode_list [j], &(temp_list [j]), sizeof (SDL_Rect));
405 else {
406 SDL_OutOfMemory ();
407 return NULL;
408 }
409 }
410 mode_list [i] = NULL; /* append null to the end */
411 }
412 else {
413 SDL_OutOfMemory ();
414 return NULL;
415 }
416
417 return mode_list;
418}
419
420static void DSp_IsHWAvailable (_THIS, SDL_PixelFormat *vformat)
421{
422 /*
423 VRAM GWorlds are only available on OS 9 or later.
424 Even with OS 9, some display drivers won't support it,
425 so we create a test GWorld and check for errors.
426 */
427
428 long versionSystem;
429
430 dsp_vram_available = SDL_FALSE;
431 dsp_agp_available = SDL_FALSE;
432
433 Gestalt ('sysv', &versionSystem);
434 if (0x00000860 < (versionSystem & 0x0000FFFF)) {
435
436 GWorldPtr offscreen;
437 OSStatus err;
438 Rect bounds;
439
440 SetRect (&bounds, 0, 0, 320, 240);
441
442#if useDistantHdwrMem && useLocalHdwrMem
443 err = NewGWorld (&offscreen, vformat->BitsPerPixel, &bounds, NULL, SDL_Display, useDistantHdwrMem | noNewDevice);
444 if (err == noErr) {
445 dsp_vram_available = SDL_TRUE;
446 DisposeGWorld (offscreen);
447 }
448
449 err = NewGWorld (&offscreen, vformat->BitsPerPixel, &bounds, NULL, SDL_Display, useLocalHdwrMem | noNewDevice);
450 if (err == noErr) {
451 DisposeGWorld (offscreen);
452 dsp_agp_available = SDL_TRUE;
453 }
454#endif
455 }
456}
457
458static int DSp_GetMainDevice (_THIS, GDHandle *device)
459{
460
461#if TARGET_API_MAC_OSX
462 /* DSpUserSelectContext not available on OS X */
463 *device = GetMainDevice();
464 return 0;
465#else
466
467 DSpContextAttributes attrib;
468 DSpContextReference context;
469 DisplayIDType display_id;
470 GDHandle main_device;
471 GDHandle device_list;
472
473 device_list = GetDeviceList ();
474 main_device = GetMainDevice ();
475
476 /* Quick check to avoid slower method when only one display exists */
477 if ( (**device_list).gdNextGD == NULL ) {
478 *device = main_device;
479 return 0;
480 }
481
482 SDL_memset (&attrib, 0, sizeof (DSpContextAttributes));
483
484 /* These attributes are hopefully supported on all devices...*/
485 attrib.displayWidth = 640;
486 attrib.displayHeight = 480;
487 attrib.displayBestDepth = 8;
488 attrib.backBufferBestDepth = 8;
489 attrib.displayDepthMask = kDSpDepthMask_All;
490 attrib.backBufferDepthMask = kDSpDepthMask_All;
491 attrib.colorNeeds = kDSpColorNeeds_Require;
492 attrib.pageCount = 1;
493
494 if (noErr != DMGetDisplayIDByGDevice (main_device, &display_id, SDL_FALSE)) {
495 SDL_SetError ("Display Manager couldn't associate GDevice with a Display ID");
496 return (-1);
497 }
498
499 /* Put up dialog on main display to select which display to use */
500 if (noErr != DSpUserSelectContext (&attrib, display_id, NULL, &context)) {
501 SDL_SetError ("DrawSprocket couldn't create a context");
502 return (-1);
503 }
504
505 if (noErr != DSpContext_GetDisplayID (context, &display_id)) {
506 SDL_SetError ("DrawSprocket couldn't get display ID");
507 return (-1);
508 }
509
510 if (noErr != DMGetGDeviceByDisplayID (display_id, &main_device, SDL_FALSE)) {
511 SDL_SetError ("Display Manager couldn't associate Display ID with GDevice");
512 return (-1);
513 }
514
515 *device = main_device;
516 return (0);
517#endif
518}
519
520static int DSp_VideoInit(_THIS, SDL_PixelFormat *vformat)
521{
522 NumVersion dsp_version = { 0x01, 0x00, 0x00, 0x00 };
523
524#if UNIVERSAL_INTERFACES_VERSION > 0x0320
525 dsp_version = DSpGetVersion ();
526#endif
527
528 if ( (dsp_version.majorRev == 1 && dsp_version.minorAndBugRev < 0x73) ||
529 (dsp_version.majorRev < 1) ) {
530
531 /* StandardAlert (kAlertStopAlert, "\pError!",
532 "\pI need DrawSprocket 1.7.3 or later!\n"
533 "You can find a newer version at http://www.apple.com/swupdates.",
534 NULL, NULL);
535 */
536 SDL_SetError ("DrawSprocket version is too old. Need 1.7.3 or later.");
537 return (-1);
538 }
539
540 if ( DSpStartup () != noErr ) {
541 SDL_SetError ("DrawSprocket couldn't startup");
542 return(-1);
543 }
544
545 /* Start DSpintosh events */
546 Mac_InitEvents(this);
547
548 /* Get a handle to the main monitor, or choose one on multiple monitor setups */
549 if ( DSp_GetMainDevice(this, &SDL_Display) < 0)
550 return (-1);
551
552 /* Determine pixel format */
553 vformat->BitsPerPixel = GetPixDepth ( (**SDL_Display).gdPMap );
554 dsp_old_depth = vformat->BitsPerPixel;
555
556 switch (vformat->BitsPerPixel) {
557 case 16:
558 vformat->Rmask = 0x00007c00;
559 vformat->Gmask = 0x000003e0;
560 vformat->Bmask = 0x0000001f;
561 break;
562 default:
563 break;
564 }
565
566 if ( DSp_CreatePalette (this) < 0 ) {
567 SDL_SetError ("Could not create palette");
568 return (-1);
569 }
570
571 /* Get a list of available fullscreen modes */
572 SDL_modelist = DSp_BuildModeList (SDL_Display,
573 &this->info.current_w, &this->info.current_h);
574 if (SDL_modelist == NULL) {
575 SDL_SetError ("DrawSprocket could not build a mode list");
576 return (-1);
577 }
578
579 /* Check for VRAM and AGP GWorlds for HW Blitting */
580 DSp_IsHWAvailable (this, vformat);
581
582 this->info.wm_available = 0;
583
584 if (dsp_vram_available || dsp_agp_available) {
585
586 this->info.hw_available = SDL_TRUE;
587
588 this->CheckHWBlit = DSp_CheckHWBlit;
589 this->info.blit_hw = SDL_TRUE;
590
591 this->FillHWRect = DSp_FillHWRect;
592 this->info.blit_fill = SDL_TRUE;
593
594 #ifdef DSP_TRY_CC_AND_AA
595 this->SetHWColorKey = DSp_SetHWColorKey;
596 this->info.blit_hw_CC = SDL_TRUE;
597
598 this->SetHWAlpha = DSp_SetHWAlpha;
599 this->info.blit_hw_A = SDL_TRUE;
600 #endif
601
602 }
603
604 return(0);
605}
606
607static SDL_Rect **DSp_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
608{
609 static SDL_Rect *dsp_modes[16];
610 int i = 0, j = 0;
611
612 if ( format->BitsPerPixel == 0 )
613 return ( (SDL_Rect**) NULL );
614
615 while (SDL_modelist[i] != NULL) {
616
617 if (SDL_modelist[i]->x & format->BitsPerPixel) {
618 dsp_modes[j] = SDL_modelist[i];
619 j++;
620 }
621 i++;
622 }
623
624 dsp_modes[j] = NULL;
625
626 return dsp_modes;
627}
628
629/* Various screen update functions available */
630static void DSp_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
631
632#if ! TARGET_API_MAC_OSX
633
634static volatile unsigned int retrace_count = 0; /* -dw- need volatile because it updates asychronously */
635
636Boolean DSp_VBLProc ( DSpContextReference context, void *ref_con )
637{
638 retrace_count++;
639
640 return 1; /* Darrell, is this right? */
641}
642
643static void DSp_SetHWError (OSStatus err, int is_agp)
644{
645 char message[1024];
646 const char *fmt, *mem;
647
648 if ( is_agp ) {
649 mem = "AGP Memory";
650 } else {
651 mem = "VRAM";
652 }
653 switch(err) {
654 case memFullErr:
655 fmt = "Hardware surface possible but not enough %s available";
656 break;
657 case cDepthErr:
658 fmt = "Hardware surface possible but invalid color depth";
659 break;
660 default:
661 fmt = "Hardware surface could not be allocated in %s - unknown error";
662 break;
663 }
664 SDL_snprintf(message, SDL_arraysize(message), fmt, mem);
665 SDL_SetError(message);
666}
667#endif // TARGET_API_MAC_OSX
668
669/* put up a dialog to verify display change */
670static int DSp_ConfirmSwitch () {
671
672 /* resource id's for dialog */
673 const int rDialog = 1002;
674 const int bCancel = 1;
675 const int bOK = 2;
676
677 DialogPtr dialog;
678 OSStatus err;
679 SInt32 response;
680 DialogItemIndex item = 0;
681 GrafPtr savePort;
682
683 GetPort (&savePort);
684
685 dialog = GetNewDialog (rDialog, NULL, (WindowPtr) -1);
686 if (dialog == NULL)
687 return (0);
688
689#if TARGET_API_MAC_CARBON
690 SetPort (GetDialogPort(dialog));
691#else
692 SetPort ((WindowPtr) dialog);
693#endif
694
695 SetDialogDefaultItem (dialog, bCancel);
696 SetDialogCancelItem (dialog, bCancel);
697
698 SetEventMask (everyEvent);
699 FlushEvents (everyEvent, 0);
700
701 /* On MacOS 8.5 or later, we can make the dialog go away after 15 seconds */
702 /* This is good since it's possible user can't even see the dialog! */
703 /* Requires linking to DialogsLib */
704 err = Gestalt(gestaltSystemVersion,&response);
705 if (err == noErr && response >= 0x00000850) {
706 SetDialogTimeout(dialog, bCancel, 15);
707 }
708
709 do {
710
711 ModalDialog ( NULL, &item );
712
713 } while ( item != bCancel && item != bOK && err != noErr);
714
715
716 DisposeDialog (dialog);
717 SetPort (savePort);
718
719 SetEventMask(everyEvent - autoKeyMask);
720 FlushEvents(everyEvent, 0);
721
722 return (item - 1);
723}
724
725static void DSp_UnsetVideoMode(_THIS, SDL_Surface *current)
726{
727
728
729 if ( current->flags & SDL_OPENGL ) {
730 Mac_GL_Quit (this);
731 }
732
733 if (dsp_context != NULL) {
734
735 GWorldPtr front;
736 DSpContext_GetFrontBuffer (dsp_context, &front);
737
738 if (front != dsp_back_buffer)
739 DisposeGWorld (dsp_back_buffer);
740
741 if (current->hwdata)
742 SDL_free(current->hwdata);
743
744 DSpContext_SetState (dsp_context, kDSpContextState_Inactive );
745 DSpContext_Release (dsp_context);
746
747 dsp_context = NULL;
748 }
749
750 if (SDL_Window != NULL) {
751 DisposeWindow (SDL_Window);
752 SDL_Window = NULL;
753 }
754
755 current->pixels = NULL;
756 current->flags = 0;
757}
758
759static SDL_Surface *DSp_SetVideoMode(_THIS,
760 SDL_Surface *current, int width, int height, int bpp, Uint32 flags)
761{
762
763#if !TARGET_API_MAC_OSX
764 DisplayIDType display_id;
765 Fixed freq;
766#endif
767 DSpContextAttributes attrib;
768 OSStatus err;
769 UInt32 rmask = 0, gmask = 0, bmask = 0;
770
771 int page_count;
772 int double_buf;
773 int hw_surface;
774 int use_dsp_back_buffer;
775
776 DSp_UnsetVideoMode (this, current);
777
778 if (bpp != dsp_old_depth)
779 DSp_DestroyPalette (this);
780
781 double_buf = (flags & SDL_DOUBLEBUF) != 0;
782 hw_surface = (flags & SDL_HWSURFACE) != 0;
783 use_dsp_back_buffer = !dsp_vram_available || !hw_surface ;
784
785 current->flags |= SDL_FULLSCREEN;
786
787rebuild:
788
789 if ( double_buf && use_dsp_back_buffer ) {
790 page_count = 2;
791 } else {
792 page_count = 1;
793 }
794
795 SDL_memset (&attrib, 0, sizeof (DSpContextAttributes));
796 attrib.displayWidth = width;
797 attrib.displayHeight = height;
798 attrib.displayBestDepth = bpp;
799 attrib.backBufferBestDepth = bpp;
800 attrib.displayDepthMask = kDSpDepthMask_All;
801 attrib.backBufferDepthMask = kDSpDepthMask_All;
802 attrib.colorNeeds = kDSpColorNeeds_Require;
803 attrib.colorTable = 0;
804 attrib.pageCount = page_count;
805 #if TARGET_API_MAC_OSX || UNIVERSAL_INTERFACES_VERSION == 0x0320
806
807 if ( DSpFindBestContext (&attrib, &dsp_context) != noErr ) {
808 SDL_SetError ("DrawSprocket couldn't find a context");
809 return NULL;
810 }
811
812 #else
813 if ( noErr != DMGetDisplayIDByGDevice (SDL_Display, &display_id, SDL_FALSE) ) {
814 SDL_SetError ("Display Manager couldn't associate GDevice with display_id");
815 return NULL;
816 }
817 if ( DSpFindBestContextOnDisplayID(&attrib, &dsp_context, display_id) != noErr ) {
818 SDL_SetError ("DrawSprocket couldn't find a suitable context on given display");
819 return NULL;
820 }
821
822 #endif
823 if ( DSpContext_Reserve (dsp_context, &attrib) != noErr ) {
824 SDL_SetError ("DrawSprocket couldn't get the needed resources to build the display");
825 return NULL;
826 }
827
828 if ( (err = DSpContext_SetState (dsp_context, kDSpContextState_Active)) != noErr ) {
829
830 if (err == kDSpConfirmSwitchWarning) {
831
832 if ( ! DSp_ConfirmSwitch () ) {
833
834 DSpContext_Release (dsp_context);
835 dsp_context = NULL;
836 SDL_SetError ("User cancelled display switch");
837 return NULL;
838 }
839 else
840 /* Have to reactivate context. Why? */
841 DSpContext_SetState (dsp_context, kDSpContextState_Active);
842
843 }
844 else {
845 SDL_SetError ("DrawSprocket couldn't activate the context");
846 return NULL;
847 }
848 }
849
850
851 if (bpp != dsp_old_depth) {
852
853 DSp_CreatePalette (this);
854
855 /* update format if display depth changed */
856 if (bpp == 16) {
857
858 rmask = 0x00007c00;
859 gmask = 0x000003e0;
860 bmask = 0x0000001f;
861 }
862 if ( ! SDL_ReallocFormat (current, bpp, rmask, gmask, bmask, 0 ) ) {
863
864 SDL_SetError ("Could not reallocate video format.");
865 return(NULL);
866 }
867 }
868
869 if (!double_buf) {
870
871 /* single-buffer context */
872 DSpContext_GetFrontBuffer (dsp_context, &dsp_back_buffer);
873
874 current->hwdata = (private_hwdata*) SDL_malloc (sizeof (private_hwdata));
875 if (current ->hwdata == NULL) {
876 SDL_OutOfMemory ();
877 return NULL;
878 }
879 current->hwdata->offscreen = dsp_back_buffer;
880 current->flags |= SDL_HWSURFACE;
881 this->UpdateRects = DSp_DirectUpdate;
882 }
883 else if ( use_dsp_back_buffer ) {
884
885 DSpContext_GetBackBuffer (dsp_context, kDSpBufferKind_Normal, &dsp_back_buffer);
886
887 current->flags |= SDL_DOUBLEBUF | SDL_SWSURFACE; /* only front buffer is in VRAM */
888 this->UpdateRects = DSp_DSpUpdate;
889 }
890 else if ( DSp_NewHWSurface(this, &dsp_back_buffer, bpp, width-1, height-1) == 0 ) {
891
892 current->hwdata = (private_hwdata*) SDL_malloc (sizeof (private_hwdata));
893 if (current ->hwdata == NULL) {
894 SDL_OutOfMemory ();
895 return NULL;
896 }
897
898 SDL_memset (current->hwdata, 0, sizeof (private_hwdata));
899 current->hwdata->offscreen = dsp_back_buffer;
900 current->flags |= SDL_DOUBLEBUF | SDL_HWSURFACE;
901 this->UpdateRects = DSp_DirectUpdate; /* hardware doesn't do update rects, must be page-flipped */
902 }
903 else {
904
905 DSpContext_Release (dsp_context);
906 use_dsp_back_buffer = SDL_TRUE;
907 goto rebuild;
908 }
909
910 current->pitch = GetPortPixRowBytes(dsp_back_buffer) & 0x3FFF;
911 current->pixels = GetPixBaseAddr(GetPortPixMap(dsp_back_buffer));
912
913 current->w = width;
914 current->h = height;
915
916 #if ! TARGET_API_MAC_OSX
917
918 if (use_dsp_back_buffer) {
919
920 DSpContext_GetMonitorFrequency (dsp_context, &freq);
921 DSpContext_SetMaxFrameRate (dsp_context, freq >> 16);
922 }
923
924
925 if ( (current->flags & SDL_HWSURFACE) || (current->flags & SDL_OPENGL) )
926 DSpContext_SetVBLProc (dsp_context, DSp_VBLProc, NULL);
927 #endif
928
929 if (bpp == 8)
930 current->flags |= SDL_HWPALETTE;
931
932 if (flags & SDL_OPENGL) {
933
934 Rect rect;
935 RGBColor rgb = { 0.0, 0.0, 0.0 };
936 GrafPtr save_port;
937
938 SetRect (&rect, 0, 0, width, height);
939 SDL_Window = NewCWindow(nil, &( (**SDL_Display).gdRect), "\p", SDL_TRUE, plainDBox, (WindowPtr)-1, SDL_FALSE, 0);
940
941 if (SDL_Window == NULL) {
942
943 SDL_SetError ("DSp_SetVideoMode : OpenGL window could not be created.");
944 return NULL;
945 }
946
947 /* Set window color to black to avoid white flash*/
948 GetPort (&save_port);
949#if TARGET_API_MAC_CARBON
950 SetPort (GetWindowPort(SDL_Window));
951#else
952 SetPort (SDL_Window);
953#endif
954 RGBForeColor (&rgb);
955 PaintRect (&rect);
956 SetPort (save_port);
957
958 SetPortWindowPort (SDL_Window);
959 SelectWindow (SDL_Window);
960
961 if ( Mac_GL_Init (this) < 0 ) {
962
963 SDL_SetError ("DSp_SetVideoMode : could not create OpenGL context.");
964 return NULL;
965 }
966
967 current->flags |= SDL_OPENGL;
968 }
969
970 return current;
971}
972
973#ifdef DSP_TRY_CC_AND_AA
974
975static int DSp_MakeHWMask (_THIS, SDL_Surface *surface)
976{
977 GDHandle save_device;
978 CGrafPtr save_port;
979 GWorldPtr temp;
980 RGBColor black = { 0, 0, 0 };
981 RGBColor white = { 0xFFFF, 0xFFFF, 0xFFFF };
982 Rect rect;
983
984 Uint32 depth = GetPixDepth ( GetGDevPixMap (SDL_Display) );
985
986 SetRect (&rect, 0, 0, surface->w, surface->h);
987
988 if ( noErr != NewGWorld (&(surface->hwdata->mask), depth, &rect, 0, SDL_Display, 0 ) < 0 ) {
989
990 SDL_OutOfMemory ();
991 return (-1);
992 }
993
994 if ( noErr != NewGWorld (&temp, depth, &rect, 0 , SDL_Display, 0 ) ) {
995
996 SDL_OutOfMemory ();
997 return (-1);
998 }
999
1000
1001 GetGWorld (&save_port, &save_device);
1002 SetGWorld (surface->hwdata->mask, SDL_Display);
1003
1004 RGBForeColor (&white);
1005 PaintRect (&rect);
1006
1007 RGBBackColor (&(surface->hwdata->trans));
1008
1009 CopyBits ( GetPortBitMapForCopyBits(surface->hwdata->offscreen),
1010 GetPortBitMapForCopyBits(surface->hwdata->mask),
1011 &rect, &rect, transparent, NULL );
1012
1013 SetGWorld (surface->hwdata->mask, SDL_Display);
1014 SetGWorld (save_port, save_device);
1015 return (0);
1016}
1017
1018static int DSp_SetHWAlpha(_THIS, SDL_Surface *surface, UInt8 alpha)
1019{
1020 surface->hwdata->alpha.red = (alpha / 255.0) * 65535;
1021 surface->hwdata->alpha.blue = (alpha / 255.0) * 65535;
1022 surface->hwdata->alpha.green = (alpha / 255.0) * 65535;
1023
1024 surface->flags |= SDL_SRCALPHA;
1025
1026 if (surface->flags & SDL_SRCCOLORKEY) {
1027 return(DSp_MakeHWMask (this, surface));
1028 }
1029 return(0);
1030}
1031
1032static int DSp_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key)
1033{
1034 CGrafPtr save_port;
1035 GDHandle save_device;
1036
1037 GetGWorld (&save_port, &save_device);
1038 SetGWorld (surface->hwdata->offscreen, NULL);
1039
1040 Index2Color (key, &(surface->hwdata->trans));
1041 surface->flags |= SDL_SRCCOLORKEY;
1042
1043 SetGWorld (save_port, save_device);
1044
1045 if ( surface->flags & SDL_SRCALPHA ) {
1046 return(DSp_MakeHWMask (this, surface));
1047 }
1048 return(0);
1049}
1050
1051#endif /* DSP_TRY_CC_AND_AA */
1052
1053static int DSp_NewHWSurface(_THIS, CGrafPtr *port, int depth, int width, int height) {
1054
1055 OSStatus err;
1056 Rect bounds;
1057
1058 SetRect (&bounds, 0, 0, width, height);
1059
1060 #if useDistantHdwrMem && useLocalHdwrMem
1061 if (dsp_vram_available) {
1062 /* try VRAM */
1063 err = NewGWorld (port, depth, &bounds, 0 , SDL_Display, useDistantHdwrMem | noNewDevice );
1064 if (err != noErr)
1065 DSp_SetHWError (err, SDL_FALSE);
1066 else
1067 return (0);
1068 }
1069
1070 if (dsp_agp_available) {
1071 /* try AGP */
1072 err = NewGWorld (port, depth, &bounds, 0 , SDL_Display, useLocalHdwrMem | noNewDevice );
1073
1074 if (err != noErr)
1075 DSp_SetHWError (err, SDL_TRUE);
1076 else
1077 return (0);
1078 }
1079#endif
1080
1081 return (-1);
1082}
1083
1084static int DSp_AllocHWSurface(_THIS, SDL_Surface *surface)
1085{
1086 GWorldPtr temp;
1087
1088 if ( DSp_NewHWSurface (this, &temp, surface->format->BitsPerPixel, surface->w, surface->h) < 0 )
1089 return (-1);
1090
1091 surface->hwdata = (private_hwdata*) SDL_malloc (sizeof (private_hwdata));
1092 if (surface->hwdata == NULL) {
1093 SDL_OutOfMemory ();
1094 return -1;
1095 }
1096
1097 SDL_memset (surface->hwdata, 0, sizeof(private_hwdata));
1098 surface->hwdata->offscreen = temp;
1099 surface->pitch = GetPixRowBytes (GetPortPixMap (temp)) & 0x3FFF;
1100 surface->pixels = GetPixBaseAddr (GetPortPixMap (temp));
1101 surface->flags |= SDL_HWSURFACE;
1102#ifdef DSP_TRY_CC_AND_AA
1103 surface->flags |= SDL_HWACCEL;
1104#endif
1105 return 0;
1106}
1107
1108static void DSp_FreeHWSurface(_THIS, SDL_Surface *surface)
1109{
1110 if (surface->hwdata->offscreen != NULL)
1111 DisposeGWorld (surface->hwdata->offscreen);
1112 SDL_free(surface->hwdata);
1113
1114 surface->pixels = NULL;
1115}
1116
1117static int DSp_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dest)
1118{
1119 int accelerated;
1120
1121 /* Set initial acceleration on */
1122 src->flags |= SDL_HWACCEL;
1123
1124 /* Set the surface attributes */
1125 if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
1126 if ( ! this->info.blit_hw_A ) {
1127 src->flags &= ~SDL_HWACCEL;
1128 }
1129 }
1130 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
1131 if ( ! this->info.blit_hw_CC ) {
1132 src->flags &= ~SDL_HWACCEL;
1133 }
1134 }
1135
1136 /* Check to see if final surface blit is accelerated */
1137 accelerated = !!(src->flags & SDL_HWACCEL);
1138 if ( accelerated ) {
1139 src->map->hw_blit = DSp_HWAccelBlit;
1140 }
1141 return(accelerated);
1142}
1143
1144static int DSp_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
1145 SDL_Surface *dst, SDL_Rect *dstrect)
1146{
1147 CGrafPtr save_port;
1148 GDHandle save_device;
1149 Rect src_rect, dst_rect;
1150 RGBColor black = { 0, 0, 0 };
1151 RGBColor white = { 0xFFFF, 0xFFFF, 0xFFFF };
1152
1153#ifdef DSP_TRY_CC_AND_AA
1154 UInt32 mode;
1155#endif
1156
1157 SetRect (&src_rect, srcrect->x, srcrect->y, srcrect->x + srcrect->w, srcrect->y + srcrect->h);
1158 SetRect (&dst_rect, dstrect->x, dstrect->y, dstrect->x + dstrect->w, dstrect->y + dstrect->h);
1159
1160 GetGWorld (&save_port, &save_device);
1161 SetGWorld (dst->hwdata->offscreen, NULL);
1162
1163 RGBForeColor (&black);
1164 RGBBackColor (&white);
1165
1166#ifdef DSP_TRY_CC_AND_AA
1167
1168 if ( (src->flags & SDL_SRCCOLORKEY) &&
1169 (src->flags & SDL_SRCALPHA) ) {
1170
1171 OpColor (&(src->hwdata->alpha));
1172
1173 CopyDeepMask ( GetPortBitMapForCopyBits(src->hwdata->offscreen),
1174 GetPortBitMapForCopyBits(src->hwdata->mask),
1175 GetPortBitMapForCopyBits(dst->hwdata->offscreen),
1176 &src_rect, &src_rect, &dst_rect,
1177 blend,
1178 NULL );
1179 }
1180 else {
1181
1182 if ( src->flags & SDL_SRCCOLORKEY) {
1183 RGBBackColor (&(src->hwdata->trans) );
1184 mode = transparent;
1185 }
1186 else if (src->flags & SDL_SRCALPHA) {
1187
1188 OpColor (&(src->hwdata->alpha));
1189 mode = blend;
1190 }
1191 else {
1192
1193 mode = srcCopy;
1194 }
1195
1196 CopyBits ( GetPortBitMapForCopyBits(src->hwdata->offscreen),
1197 GetPortBitMapForCopyBits(dst->hwdata->offscreen),
1198 &src_rect, &dst_rect, mode, NULL );
1199 }
1200#else
1201
1202 CopyBits ( &(((GrafPtr)(src->hwdata->offscreen))->portBits),
1203 &(((GrafPtr)(dst->hwdata->offscreen))->portBits),
1204 &src_rect, &dst_rect, srcCopy, NULL );
1205
1206#endif /* DSP_TRY_CC_AND_AA */
1207
1208 SetGWorld (save_port, save_device);
1209
1210 return(0);
1211}
1212
1213static int DSp_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color)
1214{
1215 CGrafPtr save_port;
1216 GDHandle save_device;
1217 Rect fill_rect;
1218 RGBColor rgb;
1219
1220 SetRect (&fill_rect, rect->x, rect->y, rect->x + rect->w, rect->y + rect->h);
1221
1222 GetGWorld (&save_port, &save_device);
1223 SetGWorld (dst->hwdata->offscreen, NULL);
1224
1225 Index2Color (color, &rgb);
1226
1227 RGBForeColor (&rgb);
1228 PaintRect (&fill_rect);
1229
1230 SetGWorld (save_port, save_device);
1231
1232 return(0);
1233}
1234
1235static int DSp_FlipHWSurface(_THIS, SDL_Surface *surface)
1236{
1237 if ( (surface->flags & SDL_HWSURFACE) ) {
1238 CGrafPtr dsp_front_buffer, save_port;
1239 Rect rect;
1240
1241 #if ! TARGET_API_MAC_OSX
1242 unsigned int old_count;
1243 #endif
1244
1245 /* pseudo page flipping for VRAM back buffer*/
1246 DSpContext_GetFrontBuffer (dsp_context, &dsp_front_buffer);
1247 SetRect (&rect, 0, 0, surface->w-1, surface->h-1);
1248
1249 GetPort ((GrafPtr *)&save_port);
1250 SetPort ((GrafPtr)dsp_front_buffer);
1251
1252 /* wait for retrace */
1253 /* I have tried doing the swap in interrupt routine (VBL Proc) to do */
1254 /* it asynchronously, but apparently CopyBits isn't interrupt safe */
1255
1256 #if ! TARGET_API_MAC_OSX
1257 #ifndef DSP_NO_SYNC_VBL
1258 old_count = retrace_count;
1259 while (old_count == retrace_count)
1260 ;
1261 #endif
1262 #endif
1263
1264 CopyBits ( GetPortBitMapForCopyBits(dsp_back_buffer),
1265 GetPortBitMapForCopyBits(dsp_front_buffer),
1266 &rect, &rect, srcCopy, NULL );
1267
1268 SetPort ((GrafPtr)save_port);
1269
1270 } else {
1271 /* not really page flipping at all: DSp just blits the dirty rectangles from DSp_UpdateRects */
1272 Boolean busy_flag;
1273 DSpContext_SwapBuffers (dsp_context, NULL, &busy_flag); /* this waits for VBL */
1274 DSpContext_GetBackBuffer (dsp_context, kDSpBufferKind_Normal, &dsp_back_buffer);
1275 surface->pixels = GetPixBaseAddr( GetPortPixMap(dsp_back_buffer) );
1276 }
1277 return(0);
1278}
1279
1280static int DSp_LockHWSurface(_THIS, SDL_Surface *surface)
1281{
1282 if ( LockPixels (GetGWorldPixMap (surface->hwdata->offscreen)) )
1283 return 0;
1284 else
1285 return -1;
1286}
1287
1288static void DSp_UnlockHWSurface(_THIS, SDL_Surface *surface)
1289{
1290 UnlockPixels (GetGWorldPixMap (surface->hwdata->offscreen));
1291}
1292
1293static void DSp_DirectUpdate(_THIS, int numrects, SDL_Rect *sdl_rects)
1294{
1295 return;
1296}
1297
1298static void DSp_DSpUpdate(_THIS, int numrects, SDL_Rect *sdl_rects)
1299{
1300#if ! TARGET_API_MAC_OSX /* Unsupported DSp in here */
1301 int i;
1302 Rect rect;
1303
1304 for (i = 0; i < numrects; i++) {
1305
1306 rect.top = sdl_rects[i].y;
1307 rect.left = sdl_rects[i].x;
1308 rect.bottom = sdl_rects[i].h + sdl_rects[i].y;
1309 rect.right = sdl_rects[i].w + sdl_rects[i].x;
1310
1311 DSpContext_InvalBackBufferRect (dsp_context, &rect);
1312 }
1313#endif
1314}
1315
1316static int DSp_CreatePalette(_THIS) {
1317
1318
1319 /* Create our palette */
1320 SDL_CTab = (CTabHandle)NewHandle(sizeof(ColorSpec)*256 + 8);
1321 if ( SDL_CTab == nil ) {
1322 SDL_OutOfMemory();
1323 return(-1);
1324 }
1325 (**SDL_CTab).ctSeed = GetCTSeed();
1326 (**SDL_CTab).ctFlags = 0;
1327 (**SDL_CTab).ctSize = 255;
1328 CTabChanged(SDL_CTab);
1329 SDL_CPal = NewPalette(256, SDL_CTab, pmExplicit+pmTolerant, 0);
1330
1331 return 0;
1332}
1333
1334static int DSp_DestroyPalette(_THIS) {
1335
1336 /* Free palette and restore original one */
1337 if ( SDL_CTab != nil ) {
1338 DisposeHandle((Handle)SDL_CTab);
1339 SDL_CTab = nil;
1340 }
1341 if ( SDL_CPal != nil ) {
1342 DisposePalette(SDL_CPal);
1343 SDL_CPal = nil;
1344 }
1345 RestoreDeviceClut(SDL_Display);
1346
1347 return (0);
1348}
1349
1350static int DSp_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
1351{
1352 CTabHandle cTab;
1353
1354 int i;
1355
1356 cTab = SDL_CTab;
1357
1358 /* Verify the range of colors */
1359 if ( (firstcolor+ncolors) > ((**cTab).ctSize+1) ) {
1360 return(0);
1361 }
1362
1363 /* Set the screen palette and update the display */
1364 for(i = 0; i < ncolors; i++) {
1365 int j = firstcolor + i;
1366 (**cTab).ctTable[j].value = j;
1367 (**cTab).ctTable[j].rgb.red = colors[i].r << 8 | colors[i].r;
1368 (**cTab).ctTable[j].rgb.green = colors[i].g << 8 | colors[i].g;
1369 (**cTab).ctTable[j].rgb.blue = colors[i].b << 8 | colors[i].b;
1370 }
1371
1372 SetGDevice(SDL_Display);
1373 SetEntries(0, (**cTab).ctSize, (ColorSpec *)&(**cTab).ctTable);
1374
1375 return(1);
1376}
1377
1378void DSp_VideoQuit(_THIS)
1379{
1380 int i;
1381
1382 /* Free current video mode */
1383 DSp_UnsetVideoMode(this, this->screen);
1384
1385 /* Free Palette and restore original */
1386 DSp_DestroyPalette (this);
1387
1388#if SDL_MACCLASSIC_GAMMA_SUPPORT
1389 Mac_QuitGamma(this);
1390#endif
1391
1392 /* Free list of video modes */
1393 if ( SDL_modelist != NULL ) {
1394 for ( i=0; SDL_modelist[i]; i++ ) {
1395 SDL_free(SDL_modelist[i]);
1396 }
1397 SDL_free(SDL_modelist);
1398 SDL_modelist = NULL;
1399 }
1400
1401 /* Unload DrawSprocket */
1402 DSpShutdown ();
1403}
1404
1405#if SDL_VIDEO_OPENGL
1406
1407/* swap buffers with v-sync */
1408static void DSp_GL_SwapBuffers (_THIS) {
1409
1410 #ifndef DSP_NO_SYNC_OPENGL
1411
1412 unsigned int old_count;
1413
1414 old_count = retrace_count;
1415 while (old_count == retrace_count)
1416 ;
1417 #endif
1418
1419 aglSwapBuffers (glContext);
1420}
1421
1422#endif
diff --git a/apps/plugins/sdl/src/video/macdsp/SDL_dspvideo.h b/apps/plugins/sdl/src/video/macdsp/SDL_dspvideo.h
deleted file mode 100644
index 7fc0896d1d..0000000000
--- a/apps/plugins/sdl/src/video/macdsp/SDL_dspvideo.h
+++ /dev/null
@@ -1,54 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_dspvideo_h
25#define _SDL_dspvideo_h
26
27#if TARGET_API_MAC_OSX
28# include <DrawSprocket/DrawSprocket.h> /* Drawsprocket.framework */
29#else
30#include <DrawSprocket.h>
31#endif
32
33#include "../maccommon/SDL_lowvideo.h"
34
35/* DrawSprocket specific information */
36struct DSpInfo {
37 DSpContextReference dsp_context;
38 CGrafPtr dsp_back_buffer;
39 int dsp_old_depth;
40
41 /* Flags for hw acceleration */
42 int dsp_vram_available;
43 int dsp_agp_available;
44
45
46};
47/* Old variable names */
48#define dsp_context (this->hidden->dspinfo->dsp_context)
49#define dsp_back_buffer (this->hidden->dspinfo->dsp_back_buffer)
50#define dsp_old_depth (this->hidden->dspinfo->dsp_old_depth)
51#define dsp_vram_available (this->hidden->dspinfo->dsp_vram_available)
52#define dsp_agp_available (this->hidden->dspinfo->dsp_agp_available)
53
54#endif /* _SDL_dspvideo_h */
diff --git a/apps/plugins/sdl/src/video/macrom/SDL_romvideo.c b/apps/plugins/sdl/src/video/macrom/SDL_romvideo.c
deleted file mode 100644
index 4c48881bf6..0000000000
--- a/apps/plugins/sdl/src/video/macrom/SDL_romvideo.c
+++ /dev/null
@@ -1,745 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#if defined(__APPLE__) && defined(__MACH__)
25#include <Carbon/Carbon.h>
26#if USE_QUICKTIME
27#include <QuickTime/Movies.h>
28#endif
29#elif TARGET_API_MAC_CARBON && (UNIVERSAL_INTERFACES_VERSION > 0x0335)
30#include <Carbon.h>
31/* The fullscreen code requires the QuickTime framework, and the window
32 is still at the back on Mac OS X, which is where this code is needed.
33 */
34#if USE_QUICKTIME
35#include <Movies.h>
36#endif
37#else
38#include <Quickdraw.h>
39#include <LowMem.h>
40#include <Gestalt.h>
41#include <Devices.h>
42#include <DiskInit.h>
43#include <QDOffscreen.h>
44#endif
45
46#include "SDL_video.h"
47#include "SDL_syswm.h"
48#include "../SDL_sysvideo.h"
49#include "SDL_romvideo.h"
50#include "../maccommon/SDL_macgl_c.h"
51#include "../maccommon/SDL_macwm_c.h"
52#include "../maccommon/SDL_macmouse_c.h"
53#include "../maccommon/SDL_macevents_c.h"
54
55/* Initialization/Query functions */
56static int ROM_VideoInit(_THIS, SDL_PixelFormat *vformat);
57static SDL_Rect **ROM_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
58static SDL_Surface *ROM_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
59static int ROM_SetColors(_THIS, int firstcolor, int ncolors,
60 SDL_Color *colors);
61static void ROM_VideoQuit(_THIS);
62
63/* Hardware surface functions */
64static int ROM_AllocHWSurface(_THIS, SDL_Surface *surface);
65static int ROM_LockHWSurface(_THIS, SDL_Surface *surface);
66static void ROM_UnlockHWSurface(_THIS, SDL_Surface *surface);
67static void ROM_FreeHWSurface(_THIS, SDL_Surface *surface);
68
69#if !TARGET_API_MAC_CARBON /* This seems not to be available? -sts Aug 2000 */
70/* Saved state for the menu bar */
71static RgnHandle gSaveGrayRgn = nil;
72static short gSaveMenuBar = 0;
73static Boolean gSaveCSVis = true;
74
75#if powerc
76/* Mixed mode glue to activate the 68K emulator and twiddle a register */
77#define ONEWORDSTUB(p1) \
78 { 0x41FA, 0x0010, 0x209F, (p1), 0x41FA, \
79 0x0008, 0x2F10, 0x4E75, 0x0000, 0x0000, 0x0000 }
80
81#define TWOWORDSTUB(p1,p2) \
82 { 0x41FA, 0x0012, 0x209F, (p1), (p2), 0x41FA, \
83 0x0008, 0x2F10, 0x4E75, 0x0000, 0x0000, 0x0000 }
84
85#define THREEWORDSTUB(p1,p2,p3) \
86 { 0x41FA, 0x0014, 0x209F, (p1), (p2), (p3), 0x41FA, \
87 0x0008, 0x2F10, 0x4E75, 0x0000, 0x0000, 0x0000 }
88
89/* ControlStrip inline glue for PowerPC */
90static pascal Boolean SBIsControlStripVisible(void)
91{
92 static short procData[] = TWOWORDSTUB(0x7000, 0xAAF2);
93 ProcInfoType procInfo = kD0DispatchedPascalStackBased
94 | RESULT_SIZE(SIZE_CODE(sizeof(Boolean)))
95 | DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE(kFourByteCode);
96
97 return((Boolean) CallUniversalProc((UniversalProcPtr) procData, procInfo, 0x00));
98}
99
100static pascal void SBShowHideControlStrip(Boolean showIt)
101{
102 static short procData[] = THREEWORDSTUB(0x303C, 0x0101, 0xAAF2);
103 ProcInfoType procInfo = kD0DispatchedPascalStackBased
104 | DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE(kFourByteCode)
105 | DISPATCHED_STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(Boolean)));
106
107 CallUniversalProc((UniversalProcPtr) procData, procInfo, 0x01, showIt);
108}
109#endif /* powerc */
110#endif /* !TARGET_API_MAC_CARBON */
111
112/* Macintosh toolbox driver bootstrap functions */
113
114static int ROM_Available(void)
115{
116 return(1);
117}
118
119static void ROM_DeleteDevice(SDL_VideoDevice *device)
120{
121 SDL_free(device->hidden);
122 SDL_free(device);
123}
124
125static SDL_VideoDevice *ROM_CreateDevice(int devindex)
126{
127 SDL_VideoDevice *device;
128
129 /* Initialize all variables that we clean on shutdown */
130 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
131 if ( device ) {
132 SDL_memset(device, 0, (sizeof *device));
133 device->hidden = (struct SDL_PrivateVideoData *)
134 SDL_malloc((sizeof *device->hidden));
135 }
136 if ( (device == NULL) || (device->hidden == NULL) ) {
137 SDL_OutOfMemory();
138 if ( device ) {
139 SDL_free(device);
140 }
141 return(0);
142 }
143 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
144
145 /* Set the function pointers */
146 device->VideoInit = ROM_VideoInit;
147 device->ListModes = ROM_ListModes;
148 device->SetVideoMode = ROM_SetVideoMode;
149 device->SetColors = ROM_SetColors;
150 device->UpdateRects = NULL;
151 device->VideoQuit = ROM_VideoQuit;
152 device->AllocHWSurface = ROM_AllocHWSurface;
153 device->CheckHWBlit = NULL;
154 device->FillHWRect = NULL;
155 device->SetHWColorKey = NULL;
156 device->SetHWAlpha = NULL;
157 device->LockHWSurface = ROM_LockHWSurface;
158 device->UnlockHWSurface = ROM_UnlockHWSurface;
159 device->FlipHWSurface = NULL;
160 device->FreeHWSurface = ROM_FreeHWSurface;
161#if SDL_MACCLASSIC_GAMMA_SUPPORT
162 device->SetGammaRamp = Mac_SetGammaRamp;
163 device->GetGammaRamp = Mac_GetGammaRamp;
164#endif
165#if SDL_VIDEO_OPENGL
166 device->GL_MakeCurrent = Mac_GL_MakeCurrent;
167 device->GL_SwapBuffers = Mac_GL_SwapBuffers;
168 device->GL_LoadLibrary = Mac_GL_LoadLibrary;
169 device->GL_GetProcAddress = Mac_GL_GetProcAddress;
170#endif /* Have OpenGL */
171 device->SetCaption = Mac_SetCaption;
172 device->SetIcon = NULL;
173 device->IconifyWindow = NULL;
174 device->GrabInput = NULL;
175 device->GetWMInfo = NULL;
176 device->FreeWMCursor = Mac_FreeWMCursor;
177 device->CreateWMCursor = Mac_CreateWMCursor;
178 device->ShowWMCursor = Mac_ShowWMCursor;
179 device->WarpWMCursor = Mac_WarpWMCursor;
180 device->InitOSKeymap = Mac_InitOSKeymap;
181 device->PumpEvents = Mac_PumpEvents;
182
183 device->free = ROM_DeleteDevice;
184
185 return device;
186}
187
188VideoBootStrap TOOLBOX_bootstrap = {
189 "toolbox", "MacOS ROM Toolbox",
190 ROM_Available, ROM_CreateDevice
191};
192
193
194static int ROM_VideoInit(_THIS, SDL_PixelFormat *vformat)
195{
196 long info;
197
198 /* Check out some things about the system */
199 Gestalt(gestaltQuickdrawVersion, &info);
200 if ( info == gestaltOriginalQD ) {
201 SDL_SetError("Color Quickdraw not available");
202 return(-1);
203 }
204
205 /* Start ROMintosh events */
206 Mac_InitEvents(this);
207
208 /* Get a handle to the main monitor */
209 SDL_Display = GetMainDevice();
210
211 /* Determine the current screen size */
212 this->info.current_w = (**SDL_Display).gdRect.right;
213 this->info.current_h = (**SDL_Display).gdRect.bottom;
214
215 /* Determine pixel format */
216 vformat->BitsPerPixel = (**(**SDL_Display).gdPMap).pixelSize;
217 switch (vformat->BitsPerPixel) {
218 case 16: /* 5-5-5 RGB */
219 vformat->Rmask = 0x00007c00;
220 vformat->Gmask = 0x000003e0;
221 vformat->Bmask = 0x0000001f;
222 break;
223 default:
224 break;
225 }
226
227 /* Create our palette */
228 SDL_CTab = (CTabHandle)NewHandle(sizeof(ColorSpec)*256 + 8);
229 if ( SDL_CTab == nil ) {
230 SDL_OutOfMemory();
231 return(-1);
232 }
233 (**SDL_CTab).ctSeed = GetCTSeed();
234 (**SDL_CTab).ctFlags = 0;
235 (**SDL_CTab).ctSize = 255;
236 CTabChanged(SDL_CTab);
237 SDL_CPal = NewPalette(256, SDL_CTab, pmExplicit+pmTolerant, 0);
238
239 /* Get a list of available fullscreen modes */
240 SDL_modelist = (SDL_Rect **)SDL_malloc((1+1)*sizeof(SDL_Rect *));
241 if ( SDL_modelist ) {
242 SDL_modelist[0] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect));
243 if ( SDL_modelist[0] ) {
244 SDL_modelist[0]->x = 0;
245 SDL_modelist[0]->y = 0;
246 SDL_modelist[0]->w = (**SDL_Display).gdRect.right;
247 SDL_modelist[0]->h = (**SDL_Display).gdRect.bottom;
248 }
249 SDL_modelist[1] = NULL;
250 }
251
252 /* Fill in some window manager capabilities */
253 this->info.wm_available = 1;
254
255 /* We're done! */
256 return(0);
257}
258
259static SDL_Rect **ROM_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
260{
261 if ( this->screen->format->BitsPerPixel == format->BitsPerPixel ) {
262 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
263 return(SDL_modelist);
264 } else {
265 return((SDL_Rect **)-1);
266 }
267 } else {
268 return((SDL_Rect **)0);
269 }
270}
271
272static void ROM_HideMenuBar(_THIS)
273{
274#if !TARGET_API_MAC_CARBON /* This seems not to be available? -sts Aug 2000 */
275 RgnHandle drawRgn = nil;
276 RgnHandle tempRgn = nil;
277 RgnHandle grayRgn = nil;
278 WindowPtr window = nil;
279 GDHandle gd = nil;
280 GrafPtr savePort;
281 long response;
282 short height;
283 EventRecord theEvent;
284
285 height = GetMBarHeight();
286
287 if ( height > 0 ) {
288 tempRgn = NewRgn();
289 drawRgn = NewRgn();
290 gSaveGrayRgn = NewRgn();
291 if ( ! tempRgn || ! drawRgn || ! gSaveGrayRgn ) {
292 goto CLEANUP;
293 }
294 grayRgn = GetGrayRgn(); /* No need to check for this */
295
296 GetPort(&savePort);
297
298 /* Hide the control strip if it's present, and record its
299 previous position into the dirty region for redrawing.
300 This isn't necessary, but may help catch stray bits. */
301 CopyRgn(grayRgn, tempRgn);
302 if (!Gestalt(gestaltControlStripAttr, &response) &&
303 (response & (1L << gestaltControlStripExists))) {
304 gSaveCSVis = SBIsControlStripVisible();
305 if (gSaveCSVis)
306 SBShowHideControlStrip(false);
307 }
308 DiffRgn(grayRgn, tempRgn, drawRgn);
309
310 /* Save the gray region once the control strip is hidden*/
311 CopyRgn(grayRgn, gSaveGrayRgn);
312
313 /* Change the menu height in lowmem */
314 gSaveMenuBar = height;
315 LMSetMBarHeight(0);
316
317 /* Walk the monitor rectangles, and combine any pieces that
318 aren't in GrayRgn: menubar, round corners, fake floaters. */
319 for(gd = GetDeviceList(); gd; gd = GetNextDevice(gd))
320 {
321 if (!TestDeviceAttribute(gd, screenDevice)) continue;
322 if (!TestDeviceAttribute(gd, screenActive)) continue;
323
324 RectRgn(tempRgn, &(*gd)->gdRect); /* Get the whole screen */
325 DiffRgn(tempRgn, grayRgn, tempRgn); /* Subtract out GrayRgn */
326 UnionRgn(tempRgn, drawRgn, drawRgn);/* Combine all the bits */
327 }
328
329 /* Add the bits into the GrayRgn */
330 UnionRgn(drawRgn, grayRgn, grayRgn);
331
332 /* Modify the vis regions of exposed windows */
333 window = (FrontWindow()) ? FrontWindow() : (WindowPtr) -1L;
334 PaintBehind(window, drawRgn);
335 CalcVisBehind(window, drawRgn);
336
337 SetPort(savePort);
338
339 /* Yield time so that floaters can catch up */
340 EventAvail(0, &theEvent);
341 EventAvail(0, &theEvent);
342 EventAvail(0, &theEvent);
343 EventAvail(0, &theEvent);
344 }
345
346CLEANUP:
347
348 if (tempRgn) DisposeRgn(tempRgn);
349 if (drawRgn) DisposeRgn(drawRgn);
350#endif /* !TARGET_API_MAC_CARBON */
351}
352
353static void ROM_ShowMenuBar(_THIS)
354{
355#if !TARGET_API_MAC_CARBON /* This seems not to be available? -sts Aug 2000 */
356 RgnHandle drawRgn = nil;
357 RgnHandle menuRgn = nil;
358 RgnHandle tempRgn = nil;
359 RgnHandle grayRgn = nil;
360 WindowPtr window = nil;
361 GrafPtr wMgrPort;
362 GrafPtr savePort;
363 Rect menuRect;
364 long response;
365 short height;
366 EventRecord theEvent;
367 RGBColor saveRGB;
368 RGBColor blackRGB = { 0, 0, 0 };
369
370 height = GetMBarHeight();
371
372 if ((height <= 0) && (gSaveMenuBar > 0)) {
373 drawRgn = NewRgn();
374 menuRgn = NewRgn();
375 tempRgn = NewRgn();
376 if ( ! tempRgn || ! drawRgn || ! gSaveGrayRgn ) {
377 goto CLEANUP;
378 }
379 grayRgn = GetGrayRgn(); /* No need to check for this */
380
381 GetPort(&savePort);
382 GetWMgrPort(&wMgrPort);
383
384 /* Set the height properly */
385 LMSetMBarHeight(gSaveMenuBar);
386
387 /* Restore the old GrayRgn: rounded corners, etc, but not
388 the menubar -- subtract that out first! */
389 if (gSaveGrayRgn)
390 {
391 menuRect = (*GetMainDevice())->gdRect;
392 menuRect.bottom = menuRect.top + gSaveMenuBar;
393 RectRgn(menuRgn, &menuRect);
394
395 DiffRgn(grayRgn, gSaveGrayRgn, drawRgn); /* What do we inval? */
396 DiffRgn(drawRgn, menuRgn, drawRgn); /* Clip out the menu */
397
398 /* Now redraw the corners and other bits black */
399 SetPort(wMgrPort);
400 GetClip(tempRgn);
401 SetClip(drawRgn);
402 GetForeColor(&saveRGB);
403 RGBForeColor(&blackRGB);
404 PaintRgn(drawRgn);
405 RGBForeColor(&saveRGB);
406 SetClip(tempRgn);
407 SetPort(savePort);
408
409 UnionRgn(drawRgn, menuRgn, drawRgn); /* Put back the menu */
410
411 /* Now actually restore the GrayRgn */
412 CopyRgn(gSaveGrayRgn, grayRgn);
413 DisposeRgn(gSaveGrayRgn);
414 gSaveGrayRgn = nil;
415 }
416
417 /* Modify the vis regions of exposed windows and draw menubar */
418 window = (FrontWindow()) ? FrontWindow() : (WindowPtr) -1L;
419 PaintBehind(window, drawRgn);
420 CalcVisBehind(window, drawRgn);
421 DrawMenuBar();
422
423 SetPort(savePort);
424 gSaveMenuBar = 0;
425
426 /* Now show the control strip if it's present */
427 if (!Gestalt(gestaltControlStripAttr, &response) &&
428 (response & (1L << gestaltControlStripExists)))
429 {
430 if (gSaveCSVis && !SBIsControlStripVisible())
431 SBShowHideControlStrip(true);
432 gSaveCSVis = true;
433 }
434
435 /* Yield time so that floaters can catch up */
436 EventAvail(0, &theEvent);
437 EventAvail(0, &theEvent);
438 EventAvail(0, &theEvent);
439 EventAvail(0, &theEvent);
440 }
441
442CLEANUP:
443
444 if (drawRgn) DisposeRgn(drawRgn);
445 if (menuRgn) DisposeRgn(menuRgn);
446 if (tempRgn) DisposeRgn(tempRgn);
447#endif /* !TARGET_API_MAC_CARBON */
448}
449
450/* Various screen update functions available */
451static void ROM_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
452static void ROM_WindowUpdate(_THIS, int numrects, SDL_Rect *rects);
453
454static void ROM_UnsetVideoMode(_THIS, SDL_Surface *current)
455{
456 /* Free the current window, if any */
457 if ( SDL_Window != nil ) {
458 GWorldPtr memworld;
459
460 /* Handle OpenGL support */
461 Mac_GL_Quit(this);
462
463 memworld = (GWorldPtr)GetWRefCon(SDL_Window);
464 if ( memworld != nil ) {
465 UnlockPixels(GetGWorldPixMap(memworld));
466 DisposeGWorld(memworld);
467 }
468 if ( (current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
469#if USE_QUICKTIME
470 EndFullScreen(fullscreen_ctx, nil);
471 SDL_Window = nil;
472#else
473 ROM_ShowMenuBar(this);
474#endif
475 }
476 }
477 current->pixels = NULL;
478 current->flags &= ~(SDL_HWSURFACE|SDL_FULLSCREEN);
479}
480
481static SDL_Surface *ROM_SetVideoMode(_THIS, SDL_Surface *current,
482 int width, int height, int bpp, Uint32 flags)
483{
484 Rect wrect, orect;
485#if TARGET_API_MAC_CARBON
486 Rect tmprect;
487#endif
488
489 /* Free any previous video mode */
490 ROM_UnsetVideoMode(this, current);
491
492 /* Create the ROM window and SDL video surface */
493 current->flags = 0; /* Clear flags */
494 current->w = width;
495 current->h = height;
496 SetRect(&wrect, 0, 0, width, height);
497 if ( SDL_Window ) {
498 /* If we recreate the window, don't move it around */
499#if TARGET_API_MAC_CARBON
500 orect = *GetWindowPortBounds(SDL_Window, &tmprect);
501#else
502 orect = SDL_Window->portRect;
503#endif
504 OffsetRect(&wrect, orect.left, orect.top);
505 } else {
506 /* Center the window the first time we show it */
507 OffsetRect(&wrect,
508 (SDL_modelist[0]->w-width)/2, (SDL_modelist[0]->h-height)/2);
509 }
510
511#if defined(__MACOSX__) && !USE_QUICKTIME
512 /* Hum.. fullscreen mode is broken */
513 flags &= ~SDL_FULLSCREEN;
514#endif
515 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
516 /* Create the fullscreen window and use screen bits */
517 current->flags |= SDL_HWSURFACE|SDL_FULLSCREEN;
518 if ( SDL_Window ) {
519 DisposeWindow(SDL_Window);
520 }
521#if USE_QUICKTIME
522 BeginFullScreen(&fullscreen_ctx, nil, 0,0, &SDL_Window, nil, 0);
523#else
524 SDL_Window = NewCWindow(nil, &wrect, "\p", true, plainDBox,
525 (WindowPtr)-1, false, 0);
526 ROM_HideMenuBar(this);
527#endif
528 current->pitch = (**(**SDL_Display).gdPMap).rowBytes & 0x3FFF;
529 current->pixels = (**(**SDL_Display).gdPMap).baseAddr;
530 this->UpdateRects = ROM_DirectUpdate;
531 } else {
532 GWorldPtr memworld;
533 PixMapHandle pixmap;
534 int style;
535
536 style = noGrowDocProc;
537 if ( flags & SDL_NOFRAME ) {
538 style = plainDBox;
539 current->flags |= SDL_NOFRAME;
540 } else
541 if ( flags & SDL_RESIZABLE ) {
542 style = zoomDocProc;
543 current->flags |= SDL_RESIZABLE;
544 }
545 if ( SDL_Window && (style == current_style) ) {
546 /* Resize existing window, if necessary */
547 if ( ((orect.right-orect.left) != width) ||
548 ((orect.bottom-orect.top) != height) ) {
549 SizeWindow(SDL_Window, width, height, false);
550 }
551 } else {
552 /* Recreate the window in the new style */
553 if ( SDL_Window ) {
554 DisposeWindow(SDL_Window);
555 }
556 SDL_Window = NewCWindow(nil, &wrect, "\p", true,
557 style, (WindowPtr)-1, true, 0);
558
559 /* Set the window title, if any */
560 { char *title;
561 SDL_WM_GetCaption(&title, NULL);
562 if ( title ) {
563 Mac_SetCaption(this, title, NULL);
564 }
565 }
566 }
567 current_style = style;
568 SetPalette(SDL_Window, SDL_CPal, false);
569 ActivatePalette(SDL_Window);
570 if ( NewGWorld(&memworld, 0,
571#if TARGET_API_MAC_CARBON
572 GetWindowPortBounds(SDL_Window, &tmprect),
573#else
574 &SDL_Window->portRect,
575#endif
576 SDL_CTab, nil, 0) != noErr ) {
577 SDL_SetError("NewGWorld() failed");
578 return(NULL);
579 }
580 SetWRefCon(SDL_Window, (long)memworld);
581 pixmap = GetGWorldPixMap(memworld);
582 LockPixels(pixmap);
583 current->pitch = (**pixmap).rowBytes & 0x3FFF;
584 current->pixels = GetPixBaseAddr(pixmap);
585 this->UpdateRects = ROM_WindowUpdate;
586 }
587 SetPortWindowPort(SDL_Window);
588 SelectWindow(SDL_Window);
589
590 /* Handle OpenGL support */
591 if ( flags & SDL_OPENGL ) {
592 if ( Mac_GL_Init(this) == 0 ) {
593 current->flags |= SDL_OPENGL;
594 } else {
595 current = NULL;
596 }
597 }
598
599 if ( (flags & SDL_HWPALETTE) && (flags & SDL_FULLSCREEN) )
600 current->flags |= SDL_HWPALETTE;
601
602 /* We're live! */
603 return(current);
604}
605
606/* We don't actually allow hardware surfaces other than the main one */
607static int ROM_AllocHWSurface(_THIS, SDL_Surface *surface)
608{
609 return(-1);
610}
611static void ROM_FreeHWSurface(_THIS, SDL_Surface *surface)
612{
613 return;
614}
615static int ROM_LockHWSurface(_THIS, SDL_Surface *surface)
616{
617 return(0);
618}
619static void ROM_UnlockHWSurface(_THIS, SDL_Surface *surface)
620{
621 return;
622}
623
624static void ROM_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
625{
626 /* The application is already updating the visible video memory */
627 return;
628}
629
630static void ROM_WindowUpdate(_THIS, int numrects, SDL_Rect *rects)
631{
632 GWorldPtr memworld;
633 GrafPtr saveport;
634 CGrafPtr thePort;
635 const BitMap *memBits;
636 const BitMap *winBits;
637 int i;
638 Rect update;
639
640 /* Copy from the offscreen GWorld to the window port */
641 GetPort(&saveport);
642 SetPortWindowPort(SDL_Window);
643 thePort = GetWindowPort(SDL_Window);
644 memworld = (GWorldPtr)GetWRefCon(SDL_Window);
645#if TARGET_API_MAC_CARBON && ACCESSOR_CALLS_ARE_FUNCTIONS
646 memBits = GetPortBitMapForCopyBits((CGrafPtr) memworld);
647#else
648 memBits = &((GrafPtr)memworld)->portBits;
649#endif
650#if TARGET_API_MAC_CARBON && ACCESSOR_CALLS_ARE_FUNCTIONS
651 winBits = GetPortBitMapForCopyBits(thePort);
652#else
653 winBits = &SDL_Window->portBits;
654#endif
655 for ( i=0; i<numrects; ++i ) {
656 update.left = rects[i].x;
657 update.right = rects[i].x+rects[i].w;
658 update.top = rects[i].y;
659 update.bottom = rects[i].y+rects[i].h;
660 CopyBits(memBits, winBits,
661 &update, &update, srcCopy, nil);
662 }
663#if TARGET_API_MAC_CARBON
664 if ( QDIsPortBuffered(thePort) ) {
665 QDFlushPortBuffer(thePort, NULL);
666 }
667#endif
668 SetPort(saveport);
669}
670
671static int ROM_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
672{
673 CTabHandle cTab;
674 int i;
675
676 /* Get the colortable from the either the display or window */
677 if ( (this->screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
678 cTab = (**(**SDL_Display).gdPMap).pmTable;
679 } else {
680 cTab = SDL_CTab;
681 }
682
683 /* Verify the range of colors */
684 if ( (firstcolor+ncolors) > ((**cTab).ctSize+1) ) {
685 return(0);
686 }
687
688 /* Set the screen palette and update the display */
689 for ( i=0; i< ncolors; ++i ) {
690 int j = firstcolor + i;
691 (**cTab).ctTable[j].value = j;
692 (**cTab).ctTable[j].rgb.red = colors[i].r << 8 | colors[i].r;
693 (**cTab).ctTable[j].rgb.green = colors[i].g << 8 | colors[i].g;
694 (**cTab).ctTable[j].rgb.blue = colors[i].b << 8 | colors[i].b;
695 }
696
697#if 0
698 if ( (this->screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN )
699#endif
700 {
701 GDevice **odisplay;
702 odisplay = GetGDevice();
703 SetGDevice(SDL_Display);
704 SetEntries(0, (**cTab).ctSize, (ColorSpec *)&(**cTab).ctTable);
705 SetGDevice(odisplay);
706 }
707 return(1);
708}
709
710void ROM_VideoQuit(_THIS)
711{
712 int i;
713
714 /* Free current video mode */
715 ROM_UnsetVideoMode(this, this->screen);
716 if ( SDL_Window ) {
717 DisposeWindow(SDL_Window);
718 SDL_Window = nil;
719 }
720
721 /* Free palette and restore original one */
722 if ( SDL_CTab != nil ) {
723 DisposeHandle((Handle)SDL_CTab);
724 SDL_CTab = nil;
725 }
726 if ( SDL_CPal != nil ) {
727 DisposePalette(SDL_CPal);
728 SDL_CPal = nil;
729 }
730 RestoreDeviceClut(GetMainDevice());
731
732#if SDL_MACCLASSIC_GAMMA_SUPPORT
733 Mac_QuitGamma(this);
734#endif
735
736 /* Free list of video modes */
737 if ( SDL_modelist != NULL ) {
738 for ( i=0; SDL_modelist[i]; ++i ) {
739 SDL_free(SDL_modelist[i]);
740 }
741 SDL_free(SDL_modelist);
742 SDL_modelist = NULL;
743 }
744}
745
diff --git a/apps/plugins/sdl/src/video/macrom/SDL_romvideo.h b/apps/plugins/sdl/src/video/macrom/SDL_romvideo.h
deleted file mode 100644
index 0380f918fa..0000000000
--- a/apps/plugins/sdl/src/video/macrom/SDL_romvideo.h
+++ /dev/null
@@ -1,29 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_romvideo_h
25#define _SDL_romvideo_h
26
27#include "../maccommon/SDL_lowvideo.h"
28
29#endif /* _SDL_romvideo_h */
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxevents.c b/apps/plugins/sdl/src/video/nanox/SDL_nxevents.c
deleted file mode 100644
index 788c794d2d..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxevents.c
+++ /dev/null
@@ -1,382 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5 Copyright (C) 2002 Greg Haerr <greg@censoft.com>
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public
9 License as published by the Free Software Foundation; either
10 version 2 of the License, or (at your option) any later version.
11
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
16
17 You should have received a copy of the GNU Library General Public
18 License along with this library; if not, write to the Free
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
21 Sam Lantinga
22 slouken@libsdl.org
23
24 Hsieh-Fu Tsai
25 clare@setabox.com
26*/
27#include "SDL_config.h"
28
29#include "SDL_keysym.h"
30#include "../../events/SDL_events_c.h"
31
32#include "SDL_nxevents_c.h"
33#include "SDL_nximage_c.h"
34
35// The translation tables from a nanox keysym to a SDL keysym
36static SDLKey NX_NONASCII_keymap [MWKEY_LAST + 1] ;
37
38void NX_InitOSKeymap (_THIS)
39{
40 int i ;
41
42 Dprintf ("enter NX_InitOSKeymap\n") ;
43
44 // Map the nanox scancodes to SDL keysyms
45 for (i = 0; i < SDL_arraysize (NX_NONASCII_keymap); ++ i)
46 NX_NONASCII_keymap [i] = SDLK_UNKNOWN ;
47
48 NX_NONASCII_keymap [MWKEY_LEFT & 0xFF] = SDLK_LEFT ;
49 NX_NONASCII_keymap [MWKEY_RIGHT & 0xFF] = SDLK_RIGHT ;
50 NX_NONASCII_keymap [MWKEY_UP & 0xFF] = SDLK_UP ;
51 NX_NONASCII_keymap [MWKEY_DOWN & 0xFF] = SDLK_DOWN ;
52 NX_NONASCII_keymap [MWKEY_INSERT & 0xFF] = SDLK_INSERT ;
53 NX_NONASCII_keymap [MWKEY_DELETE & 0xFF] = SDLK_DELETE ;
54 NX_NONASCII_keymap [MWKEY_HOME & 0xFF] = SDLK_HOME ;
55 NX_NONASCII_keymap [MWKEY_END & 0xFF] = SDLK_END ;
56 NX_NONASCII_keymap [MWKEY_PAGEUP & 0xFF] = SDLK_PAGEUP ;
57 NX_NONASCII_keymap [MWKEY_PAGEDOWN & 0xFF] = SDLK_PAGEDOWN ;
58
59 NX_NONASCII_keymap [MWKEY_KP0 & 0xFF] = SDLK_KP0 ;
60 NX_NONASCII_keymap [MWKEY_KP1 & 0xFF] = SDLK_KP1 ;
61 NX_NONASCII_keymap [MWKEY_KP2 & 0xFF] = SDLK_KP2 ;
62 NX_NONASCII_keymap [MWKEY_KP3 & 0xFF] = SDLK_KP3 ;
63 NX_NONASCII_keymap [MWKEY_KP4 & 0xFF] = SDLK_KP4 ;
64 NX_NONASCII_keymap [MWKEY_KP5 & 0xFF] = SDLK_KP5 ;
65 NX_NONASCII_keymap [MWKEY_KP6 & 0xFF] = SDLK_KP6 ;
66 NX_NONASCII_keymap [MWKEY_KP7 & 0xFF] = SDLK_KP7 ;
67 NX_NONASCII_keymap [MWKEY_KP8 & 0xFF] = SDLK_KP8 ;
68 NX_NONASCII_keymap [MWKEY_KP9 & 0xFF] = SDLK_KP9 ;
69 NX_NONASCII_keymap [MWKEY_KP_PERIOD & 0xFF] = SDLK_KP_PERIOD ;
70 NX_NONASCII_keymap [MWKEY_KP_DIVIDE & 0xFF] = SDLK_KP_DIVIDE ;
71 NX_NONASCII_keymap [MWKEY_KP_MULTIPLY & 0xFF] = SDLK_KP_MULTIPLY ;
72 NX_NONASCII_keymap [MWKEY_KP_MINUS & 0xFF] = SDLK_KP_MINUS ;
73 NX_NONASCII_keymap [MWKEY_KP_PLUS & 0xFF] = SDLK_KP_PLUS ;
74 NX_NONASCII_keymap [MWKEY_KP_ENTER & 0xFF] = SDLK_KP_ENTER ;
75 NX_NONASCII_keymap [MWKEY_KP_EQUALS & 0xFF] = SDLK_KP_EQUALS ;
76
77 NX_NONASCII_keymap [MWKEY_F1 & 0xFF] = SDLK_F1 ;
78 NX_NONASCII_keymap [MWKEY_F2 & 0xFF] = SDLK_F2 ;
79 NX_NONASCII_keymap [MWKEY_F3 & 0xFF] = SDLK_F3 ;
80 NX_NONASCII_keymap [MWKEY_F4 & 0xFF] = SDLK_F4 ;
81 NX_NONASCII_keymap [MWKEY_F5 & 0xFF] = SDLK_F5 ;
82 NX_NONASCII_keymap [MWKEY_F6 & 0xFF] = SDLK_F6 ;
83 NX_NONASCII_keymap [MWKEY_F7 & 0xFF] = SDLK_F7 ;
84 NX_NONASCII_keymap [MWKEY_F8 & 0xFF] = SDLK_F8 ;
85 NX_NONASCII_keymap [MWKEY_F9 & 0xFF] = SDLK_F9 ;
86 NX_NONASCII_keymap [MWKEY_F10 & 0xFF] = SDLK_F10 ;
87 NX_NONASCII_keymap [MWKEY_F11 & 0xFF] = SDLK_F11 ;
88 NX_NONASCII_keymap [MWKEY_F12 & 0xFF] = SDLK_F12 ;
89
90 NX_NONASCII_keymap [MWKEY_NUMLOCK & 0xFF] = SDLK_NUMLOCK ;
91 NX_NONASCII_keymap [MWKEY_CAPSLOCK & 0xFF] = SDLK_CAPSLOCK ;
92 NX_NONASCII_keymap [MWKEY_SCROLLOCK & 0xFF] = SDLK_SCROLLOCK ;
93 NX_NONASCII_keymap [MWKEY_LSHIFT & 0xFF] = SDLK_LSHIFT ;
94 NX_NONASCII_keymap [MWKEY_RSHIFT & 0xFF] = SDLK_RSHIFT ;
95 NX_NONASCII_keymap [MWKEY_LCTRL & 0xFF] = SDLK_LCTRL ;
96 NX_NONASCII_keymap [MWKEY_RCTRL & 0xFF] = SDLK_RCTRL ;
97 NX_NONASCII_keymap [MWKEY_LALT & 0xFF] = SDLK_LALT ;
98 NX_NONASCII_keymap [MWKEY_RALT & 0xFF] = SDLK_RALT ;
99 NX_NONASCII_keymap [MWKEY_LMETA & 0xFF] = SDLK_LMETA ;
100 NX_NONASCII_keymap [MWKEY_RMETA & 0xFF] = SDLK_RMETA ;
101 NX_NONASCII_keymap [MWKEY_ALTGR & 0xFF] = SDLK_MODE ;
102
103 NX_NONASCII_keymap [MWKEY_PRINT & 0xFF] = SDLK_PRINT ;
104 NX_NONASCII_keymap [MWKEY_SYSREQ & 0xFF] = SDLK_SYSREQ ;
105 NX_NONASCII_keymap [MWKEY_PAUSE & 0xFF] = SDLK_PAUSE ;
106 NX_NONASCII_keymap [MWKEY_BREAK & 0xFF] = SDLK_BREAK ;
107 NX_NONASCII_keymap [MWKEY_MENU & 0xFF] = SDLK_MENU ;
108
109 Dprintf ("leave NX_InitOSKeymap\n") ;
110}
111
112SDL_keysym * NX_TranslateKey (GR_EVENT_KEYSTROKE * keystroke, SDL_keysym * keysym)
113{
114 GR_KEY ch = keystroke -> ch ;
115
116 Dprintf ("enter NX_TranslateKey\n") ;
117
118 keysym -> scancode = keystroke -> scancode ;
119 keysym -> sym = SDLK_UNKNOWN ;
120
121 if (ch & MWKEY_NONASCII_MASK) {
122 keysym -> sym = NX_NONASCII_keymap [ch & 0xFF] ;
123 } else {
124 keysym -> sym = ch & 0x7F ;
125 }
126
127 keysym -> mod = KMOD_NONE ;
128
129#if 1 // Retrieve more mode information
130 {
131 GR_KEYMOD mod = keystroke -> modifiers ;
132
133 if (mod & MWKMOD_LSHIFT)
134 keysym -> mod |= KMOD_LSHIFT ;
135 if (mod & MWKMOD_RSHIFT)
136 keysym -> mod |= KMOD_RSHIFT ;
137 if (mod & MWKMOD_LCTRL)
138 keysym -> mod |= KMOD_LCTRL ;
139 if (mod & MWKMOD_RCTRL)
140 keysym -> mod |= KMOD_RCTRL ;
141 if (mod & MWKMOD_LALT)
142 keysym -> mod |= KMOD_LALT ;
143 if (mod & MWKMOD_RALT)
144 keysym -> mod |= KMOD_RALT ;
145 if (mod & MWKMOD_LMETA)
146 keysym -> mod |= KMOD_LMETA ;
147 if (mod & MWKMOD_RMETA)
148 keysym -> mod |= KMOD_RMETA ;
149 if (mod & MWKMOD_NUM)
150 keysym -> mod |= KMOD_NUM ;
151 if (mod & MWKMOD_CAPS)
152 keysym -> mod |= KMOD_CAPS ;
153 if (mod & MWKMOD_ALTGR)
154 keysym -> mod |= KMOD_MODE ;
155 }
156#endif
157
158 keysym -> unicode = ch ;
159
160 Dprintf ("leave NX_TranslateKey\n") ;
161 return keysym ;
162}
163
164static int check_boundary (_THIS, int x, int y)
165{
166 if (x < OffsetX || y < OffsetY || x > OffsetX + this -> screen -> w ||
167 y > OffsetY + this -> screen -> h)
168 return 0 ;
169
170 return 1 ;
171}
172
173void NX_PumpEvents (_THIS)
174{
175 GR_EVENT event ;
176 static GR_BUTTON last_button_down = 0 ;
177
178 GrCheckNextEvent (& event) ;
179 while (event.type != GR_EVENT_TYPE_NONE) {
180
181 // dispatch event
182 switch (event.type) {
183 case GR_EVENT_TYPE_MOUSE_ENTER :
184 {
185 Dprintf ("mouse enter\n") ;
186 SDL_PrivateAppActive (1, SDL_APPMOUSEFOCUS) ;
187 break ;
188 }
189
190 case GR_EVENT_TYPE_MOUSE_EXIT :
191 {
192 Dprintf ("mouse exit\n") ;
193 SDL_PrivateAppActive (0, SDL_APPMOUSEFOCUS) ;
194 break ;
195 }
196
197 case GR_EVENT_TYPE_FOCUS_IN :
198 {
199 Dprintf ("focus in\n") ;
200 SDL_PrivateAppActive (1, SDL_APPINPUTFOCUS) ;
201 break ;
202 }
203
204 case GR_EVENT_TYPE_FOCUS_OUT :
205 {
206 Dprintf ("focus out\n") ;
207 SDL_PrivateAppActive (0, SDL_APPINPUTFOCUS) ;
208 break ;
209 }
210
211 case GR_EVENT_TYPE_MOUSE_MOTION :
212 {
213 Dprintf ("mouse motion\n") ;
214
215 if (SDL_VideoSurface) {
216 if (currently_fullscreen) {
217 if (check_boundary (this, event.button.x, event.button.y)) {
218 SDL_PrivateMouseMotion (0, 0, event.button.x - OffsetX,
219 event.button.y - OffsetY) ;
220 }
221 } else {
222 SDL_PrivateMouseMotion (0, 0, event.button.x, event.button.y) ;
223 }
224 }
225 break ;
226 }
227
228 case GR_EVENT_TYPE_BUTTON_DOWN :
229 {
230 int button = event.button.buttons ;
231
232 Dprintf ("button down\n") ;
233
234 switch (button) {
235 case MWBUTTON_L :
236 button = 1 ;
237 break ;
238 case MWBUTTON_M :
239 button = 2 ;
240 break ;
241 case MWBUTTON_R :
242 button = 3 ;
243 break ;
244 default :
245 button = 0 ;
246 }
247 last_button_down = button ;
248
249 if (currently_fullscreen) {
250 if (check_boundary (this, event.button.x, event.button.y)) {
251 SDL_PrivateMouseButton (SDL_PRESSED, button,
252 event.button.x - OffsetX, event.button.y - OffsetY) ;
253 }
254 } else {
255 SDL_PrivateMouseButton (SDL_PRESSED, button,
256 event.button.x, event.button.y) ;
257 }
258 break ;
259 }
260
261 // do not konw which button is released
262 case GR_EVENT_TYPE_BUTTON_UP :
263 {
264 Dprintf ("button up\n") ;
265
266 if (currently_fullscreen) {
267 if (check_boundary (this, event.button.x, event.button.y)) {
268 SDL_PrivateMouseButton (SDL_RELEASED, last_button_down,
269 event.button.x - OffsetX, event.button.y - OffsetY) ;
270 }
271 } else {
272 SDL_PrivateMouseButton (SDL_RELEASED, last_button_down,
273 event.button.x, event.button.y) ;
274 }
275 last_button_down = 0 ;
276 break ;
277 }
278
279 case GR_EVENT_TYPE_KEY_DOWN :
280 {
281 SDL_keysym keysym ;
282
283 Dprintf ("key down\n") ;
284 SDL_PrivateKeyboard (SDL_PRESSED,
285 NX_TranslateKey (& event.keystroke, & keysym)) ;
286 break ;
287 }
288
289 case GR_EVENT_TYPE_KEY_UP :
290 {
291 SDL_keysym keysym ;
292
293 Dprintf ("key up\n") ;
294 SDL_PrivateKeyboard (SDL_RELEASED,
295 NX_TranslateKey (& event.keystroke, & keysym)) ;
296 break ;
297 }
298
299 case GR_EVENT_TYPE_CLOSE_REQ :
300 {
301 Dprintf ("close require\n") ;
302 SDL_PrivateQuit () ;
303 break ;
304 }
305
306 case GR_EVENT_TYPE_EXPOSURE :
307 {
308 Dprintf ("event_type_exposure\n") ;
309 if (SDL_VideoSurface) {
310 NX_RefreshDisplay (this) ;//, & event.exposure) ;
311 }
312 break ;
313 }
314
315 case GR_EVENT_TYPE_UPDATE :
316 {
317 switch (event.update.utype) {
318 case GR_UPDATE_MAP :
319 {
320 Dprintf ("GR_UPDATE_MAP\n") ;
321 // If we're not active, make ourselves active
322 if (!(SDL_GetAppState () & SDL_APPACTIVE)) {
323 // Send an internal activate event
324 SDL_PrivateAppActive (1, SDL_APPACTIVE) ;
325 }
326 if (SDL_VideoSurface) {
327 NX_RefreshDisplay (this) ;
328 }
329 break ;
330 }
331
332 case GR_UPDATE_UNMAP :
333 case GR_UPDATE_UNMAPTEMP :
334 {
335 Dprintf ("GR_UPDATE_UNMAP or GR_UPDATE_UNMAPTEMP\n") ;
336 // If we're active, make ourselves inactive
337 if (SDL_GetAppState () & SDL_APPACTIVE) {
338 // Send an internal deactivate event
339 SDL_PrivateAppActive (0, SDL_APPACTIVE | SDL_APPINPUTFOCUS) ;
340 }
341 break ;
342 }
343
344 case GR_UPDATE_SIZE :
345 {
346 Dprintf ("GR_UPDATE_SIZE\n") ;
347 SDL_PrivateResize (event.update.width, event.update.height) ;
348 break ;
349 }
350
351 case GR_UPDATE_MOVE :
352 case GR_UPDATE_REPARENT :
353 {
354 Dprintf ("GR_UPDATE_MOVE or GR_UPDATE_REPARENT\n") ;
355#ifdef ENABLE_NANOX_DIRECT_FB
356 if (Clientfb) {
357 /* Get current window position and fb pointer*/
358 if (currently_fullscreen)
359 GrGetWindowFBInfo(FSwindow, &fbinfo);
360 else
361 GrGetWindowFBInfo(SDL_Window, &fbinfo);
362 }
363#endif
364 break ;
365 }
366
367 default :
368 Dprintf ("unknown GR_EVENT_TYPE_UPDATE\n") ;
369 break ;
370 }
371 break ;
372 }
373
374 default :
375 {
376 Dprintf ("pump event default\n") ;
377 }
378 }
379
380 GrCheckNextEvent (& event) ;
381 }
382}
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxevents_c.h b/apps/plugins/sdl/src/video/nanox/SDL_nxevents_c.h
deleted file mode 100644
index b3b4f979bb..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxevents_c.h
+++ /dev/null
@@ -1,32 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
15
16 You should have received a copy of the GNU Library General Public
17 License along with this library; if not, write to the Free
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 Sam Lantinga
21 slouken@libsdl.org
22
23 Hsieh-Fu Tsai
24 clare@setabox.com
25*/
26#include "SDL_config.h"
27
28#include "SDL_nxvideo.h"
29
30// Functions to be exported
31extern void NX_InitOSKeymap (_THIS) ;
32extern void NX_PumpEvents (_THIS) ;
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nximage.c b/apps/plugins/sdl/src/video/nanox/SDL_nximage.c
deleted file mode 100644
index 23d3157cb0..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nximage.c
+++ /dev/null
@@ -1,230 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5 Copyright (C) 2002 Greg Haerr <greg@censoft.com>
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public
9 License as published by the Free Software Foundation; either
10 version 2 of the License, or (at your option) any later version.
11
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
16
17 You should have received a copy of the GNU Library General Public
18 License along with this library; if not, write to the Free
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
21 Sam Lantinga
22 slouken@libsdl.org
23
24 Hsieh-Fu Tsai
25 clare@setabox.com
26*/
27#include "SDL_config.h"
28
29#include "SDL_nximage_c.h"
30
31void NX_NormalUpdate (_THIS, int numrects, SDL_Rect * rects)
32{
33 int i, j, xinc, yinc, destinc, rowinc ;
34 int x, y, w, h ;
35 unsigned char * src = NULL, * dest = NULL ;
36
37 Dprintf ("enter NX_NormalUpdate\n") ;
38
39 /* These are the values for the incoming image */
40 xinc = this -> screen -> format -> BytesPerPixel ;
41 yinc = this -> screen -> pitch ;
42
43 for (i = 0; i < numrects; ++ i) {
44 x = rects [i].x, y = rects [i].y ;
45 w = rects [i].w, h = rects [i].h ;
46 src = SDL_Image + y * yinc + x * xinc ;
47#ifdef ENABLE_NANOX_DIRECT_FB
48 if (Clientfb) {
49 if (currently_fullscreen)
50 dest = fbinfo.winpixels + (((y+OffsetY) * fbinfo.pitch) +
51 ((x+OffsetX) * fbinfo.bytespp));
52 else
53 dest = fbinfo.winpixels + ((y * fbinfo.pitch) + (x * fbinfo.bytespp));
54 destinc = fbinfo.pitch;
55 }
56 else
57#endif
58 {
59 dest = Image_buff ;
60 destinc = w * xinc ;
61 }
62 rowinc = w * xinc;
63
64 // apply GammaRamp table
65 if ((pixel_type == MWPF_TRUECOLOR0888 || pixel_type == MWPF_TRUECOLOR888)
66 && GammaRamp_R && GammaRamp_G && GammaRamp_B) {
67 Uint8 * ptrsrc ;
68 Uint8 * ptrdst ;
69 int k ;
70
71 for (j = h; j > 0; -- j, src += yinc, dest += destinc) {
72 ptrsrc = src ;
73 ptrdst = dest ;
74 for (k = w; k > 0; -- k) {
75 *ptrdst++ = GammaRamp_B [*ptrsrc++] >> 8;
76 *ptrdst++ = GammaRamp_G [*ptrsrc++] >> 8;
77 *ptrdst++ = GammaRamp_R [*ptrsrc++] >> 8;
78 *ptrdst++ = 0;
79 ++ptrsrc;
80 }
81 }
82 }
83#if 1 /* This is needed for microwindows 0.90 or older */
84 else if (pixel_type == MWPF_TRUECOLOR0888 || pixel_type == MWPF_TRUECOLOR888) {
85 Uint8 * ptrsrc ;
86 Uint8 * ptrdst ;
87 int k ;
88
89 for (j = h; j > 0; -- j, src += yinc, dest += destinc) {
90 ptrsrc = src ;
91 ptrdst = dest ;
92 for (k = w; k > 0; -- k) {
93 *ptrdst++ = *ptrsrc++;
94 *ptrdst++ = *ptrsrc++;
95 *ptrdst++ = *ptrsrc++;
96 *ptrdst++ = 0;
97 ++ptrsrc;
98 }
99 }
100 }
101#endif
102 else
103 {
104 for (j = h; j > 0; -- j, src += yinc, dest += destinc)
105 SDL_memcpy (dest, src, rowinc) ;
106 }
107 if (!Clientfb) {
108 if (currently_fullscreen) {
109 GrArea (FSwindow, SDL_GC, x + OffsetX, y + OffsetY, w, h, Image_buff,
110 pixel_type) ;
111 } else {
112 GrArea (SDL_Window, SDL_GC, x, y, w, h, Image_buff, pixel_type) ;
113 }
114 }
115 }
116 GrFlush();
117
118 Dprintf ("leave NX_NormalUpdate\n") ;
119}
120
121int NX_SetupImage (_THIS, SDL_Surface * screen)
122{
123 int size = screen -> h * screen -> pitch ;
124
125 Dprintf ("enter NX_SetupImage\n") ;
126
127 screen -> pixels = (void *) SDL_malloc (size) ;
128
129 if (!Clientfb) {
130 Image_buff = (unsigned char *) SDL_malloc (size) ;
131 if (screen -> pixels == NULL || Image_buff == NULL) {
132 SDL_free (screen -> pixels) ;
133 SDL_free (Image_buff) ;
134 SDL_OutOfMemory () ;
135 return -1 ;
136 }
137 }
138
139 SDL_Image = (unsigned char *) screen -> pixels ;
140
141 this -> UpdateRects = NX_NormalUpdate ;
142
143 Dprintf ("leave NX_SetupImage\n") ;
144 return 0 ;
145}
146
147void NX_DestroyImage (_THIS, SDL_Surface * screen)
148{
149 Dprintf ("enter NX_DestroyImage\n") ;
150
151 if (SDL_Image) SDL_free (SDL_Image) ;
152 if (Image_buff) SDL_free (Image_buff) ;
153 if (screen) screen -> pixels = NULL ;
154
155 Dprintf ("leave NX_DestroyImage\n") ;
156}
157
158int NX_ResizeImage (_THIS, SDL_Surface * screen, Uint32 flags)
159{
160 int retval ;
161 GR_SCREEN_INFO si ;
162
163 Dprintf ("enter NX_ResizeImage\n") ;
164
165 NX_DestroyImage (this, screen) ;
166 retval = NX_SetupImage (this, screen) ;
167
168 GrGetScreenInfo (& si) ;
169 OffsetX = (si.cols - screen -> w) / 2 ;
170 OffsetY = (si.rows - screen -> h) / 2 ;
171
172#ifdef ENABLE_NANOX_DIRECT_FB
173 if (Clientfb) {
174 /* Get current window position and fb pointer*/
175 if (currently_fullscreen)
176 GrGetWindowFBInfo(FSwindow, &fbinfo);
177 else
178 GrGetWindowFBInfo(SDL_Window, &fbinfo);
179 }
180#endif
181 Dprintf ("leave NX_ResizeImage\n") ;
182 return retval ;
183}
184
185void NX_RefreshDisplay (_THIS)
186{
187 Dprintf ("enter NX_RefreshDisplay\n") ;
188
189 // Don't refresh a display that doesn't have an image (like GL)
190 if (! SDL_Image) {
191 return;
192 }
193
194#ifdef ENABLE_NANOX_DIRECT_FB
195 if (Clientfb) {
196 int j;
197 char *src, *dest = NULL;
198 int xinc, yinc, rowinc;
199
200 GrGetWindowFBInfo(SDL_Window, &fbinfo);
201
202 xinc = this -> screen -> format -> BytesPerPixel ;
203 yinc = this -> screen -> pitch ;
204
205 src = SDL_Image;
206 if (currently_fullscreen)
207 dest = fbinfo.winpixels + ((OffsetY * fbinfo.pitch) +
208 (OffsetX * fbinfo.bytespp));
209 else
210 dest = fbinfo.winpixels;
211 rowinc = xinc * this -> screen -> w;
212
213 for (j = this -> screen -> h; j > 0; -- j, src += yinc, dest += fbinfo.pitch)
214 SDL_memcpy (dest, src, rowinc) ;
215 }
216 else
217#endif
218 {
219 if (currently_fullscreen) {
220 GrArea (FSwindow, SDL_GC, OffsetX, OffsetY, this -> screen -> w,
221 this -> screen -> h, SDL_Image, pixel_type) ;
222 } else {
223 GrArea (SDL_Window, SDL_GC, 0, 0, this -> screen -> w,
224 this -> screen -> h, SDL_Image, pixel_type) ;
225 }
226 }
227 GrFlush();
228
229 Dprintf ("leave NX_RefreshDisplay\n") ;
230}
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nximage_c.h b/apps/plugins/sdl/src/video/nanox/SDL_nximage_c.h
deleted file mode 100644
index 0bf29e561a..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nximage_c.h
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
15
16 You should have received a copy of the GNU Library General Public
17 License along with this library; if not, write to the Free
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 Sam Lantinga
21 slouken@libsdl.org
22
23 Hsieh-Fu Tsai
24 clare@setabox.com
25*/
26#include "SDL_config.h"
27
28#include "SDL_nxvideo.h"
29
30extern int NX_SetupImage (_THIS, SDL_Surface * screen) ;
31extern void NX_DestroyImage (_THIS, SDL_Surface * screen) ;
32extern int NX_ResizeImage (_THIS, SDL_Surface * screen, Uint32 flags) ;
33
34extern void NX_NormalUpdate (_THIS, int numrects, SDL_Rect * rects) ;
35extern void NX_RefreshDisplay (_THIS) ;
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxmodes.c b/apps/plugins/sdl/src/video/nanox/SDL_nxmodes.c
deleted file mode 100644
index bcf74e50cc..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxmodes.c
+++ /dev/null
@@ -1,84 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
15
16 You should have received a copy of the GNU Library General Public
17 License along with this library; if not, write to the Free
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 Sam Lantinga
21 slouken@libsdl.org
22
23 Hsieh-Fu Tsai
24 clare@setabox.com
25*/
26#include "SDL_config.h"
27
28#include "SDL_stdinc.h"
29#include "SDL_nxmodes_c.h"
30
31SDL_Rect ** NX_ListModes (_THIS, SDL_PixelFormat * format, Uint32 flags)
32{
33 if (flags & SDL_FULLSCREEN)
34 return SDL_modelist ;
35
36 if (SDL_Visual.bpp == format -> BitsPerPixel) {
37 return ((SDL_Rect **) -1) ;
38 } else {
39 return ((SDL_Rect **) 0) ;
40 }
41}
42
43void NX_FreeVideoModes (_THIS)
44{
45 int i ;
46
47 if (SDL_modelist) {
48 for (i = 0; SDL_modelist [i]; ++ i) {
49 SDL_free (SDL_modelist [i]) ;
50 }
51 SDL_free (SDL_modelist) ;
52 SDL_modelist = NULL;
53 }
54}
55
56int NX_EnterFullScreen (_THIS)
57{
58 if (! currently_fullscreen) {
59 GR_SCREEN_INFO si ;
60
61 GrGetScreenInfo (& si) ;
62 GrResizeWindow (FSwindow, si.cols, si.rows) ;
63 GrUnmapWindow (SDL_Window) ;
64 GrMapWindow (FSwindow) ;
65 GrRaiseWindow (FSwindow) ;
66 GrSetFocus (FSwindow) ;
67 currently_fullscreen = 1 ;
68 }
69
70 return 1 ;
71}
72
73int NX_LeaveFullScreen (_THIS)
74{
75 if (currently_fullscreen) {
76 GrUnmapWindow (FSwindow) ;
77 GrMapWindow (SDL_Window) ;
78 GrRaiseWindow (SDL_Window) ;
79 GrSetFocus (SDL_Window) ;
80 currently_fullscreen = 0 ;
81 }
82
83 return 0 ;
84}
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxmodes_c.h b/apps/plugins/sdl/src/video/nanox/SDL_nxmodes_c.h
deleted file mode 100644
index fe2e655e98..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxmodes_c.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
15
16 You should have received a copy of the GNU Library General Public
17 License along with this library; if not, write to the Free
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 Sam Lantinga
21 slouken@libsdl.org
22
23 Hsieh-Fu Tsai
24 clare@setabox.com
25*/
26#include "SDL_config.h"
27
28#include "SDL_nxvideo.h"
29#include <SDL.h>
30
31extern SDL_Rect ** NX_ListModes (_THIS, SDL_PixelFormat * format, Uint32 flags) ;
32extern void NX_FreeVideoModes (_THIS) ;
33extern int NX_EnterFullScreen (_THIS) ;
34extern int NX_LeaveFullScreen (_THIS) ;
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxmouse.c b/apps/plugins/sdl/src/video/nanox/SDL_nxmouse.c
deleted file mode 100644
index 9c8f38205d..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxmouse.c
+++ /dev/null
@@ -1,79 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
15
16 You should have received a copy of the GNU Library General Public
17 License along with this library; if not, write to the Free
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 Sam Lantinga
21 slouken@libsdl.org
22
23 Hsieh-Fu Tsai
24 clare@setabox.com
25*/
26#include "SDL_config.h"
27
28#include "../../events/SDL_events_c.h"
29
30#include "SDL_nxmouse_c.h"
31
32// The implementation dependent data for the window manager cursor
33struct WMcursor {
34 int unused ;
35} ;
36
37WMcursor * NX_CreateWMCursor (_THIS,
38 Uint8 * data, Uint8 * mask, int w, int h, int hot_x, int hot_y)
39{
40 WMcursor * cursor ;
41
42 Dprintf ("enter NX_CreateWMCursor\n") ;
43
44 cursor = (WMcursor *) SDL_malloc (sizeof (WMcursor)) ;
45 if (cursor == NULL) {
46 SDL_OutOfMemory () ;
47 return NULL ;
48 }
49
50 Dprintf ("leave NX_CreateWMCursor\n") ;
51 return cursor ;
52}
53
54void NX_FreeWMCursor (_THIS, WMcursor * cursor)
55{
56 Dprintf ("NX_FreeWMCursor\n") ;
57 SDL_free (cursor) ;
58 return ;
59}
60
61void NX_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
62{
63 GR_WINDOW_INFO info ;
64
65 Dprintf ("enter NX_WarpWMCursor\n") ;
66 SDL_Lock_EventThread () ;
67
68 GrGetWindowInfo (SDL_Window, & info) ;
69 GrMoveCursor (info.x + x, info.y + y) ;
70
71 SDL_Unlock_EventThread () ;
72 Dprintf ("leave NX_WarpWMCursor\n") ;
73}
74
75int NX_ShowWMCursor (_THIS, WMcursor * cursor)
76{
77 Dprintf ("NX_ShowWMCursor\n") ;
78 return 1 ;
79}
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxmouse_c.h b/apps/plugins/sdl/src/video/nanox/SDL_nxmouse_c.h
deleted file mode 100644
index d7fedb5362..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxmouse_c.h
+++ /dev/null
@@ -1,29 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_nxvideo.h"
25
26extern WMcursor * NX_CreateWMCursor (_THIS, Uint8 * data, Uint8 * mask, int w, int h, int hot_x, int hot_y) ;
27void NX_FreeWMCursor (_THIS, WMcursor * cursor) ;
28extern void NX_WarpWMCursor (_THIS, Uint16 x, Uint16 y) ;
29extern int NX_ShowWMCursor (_THIS, WMcursor * cursor) ;
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxvideo.c b/apps/plugins/sdl/src/video/nanox/SDL_nxvideo.c
deleted file mode 100644
index b188e09581..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxvideo.c
+++ /dev/null
@@ -1,544 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5 Copyright (C) 2002 Greg Haerr <greg@censoft.com>
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public
9 License as published by the Free Software Foundation; either
10 version 2 of the License, or (at your option) any later version.
11
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
16
17 You should have received a copy of the GNU Library General Public
18 License along with this library; if not, write to the Free
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
21 Sam Lantinga
22 slouken@libsdl.org
23
24 Hsieh-Fu Tsai
25 clare@setabox.com
26*/
27#include "SDL_config.h"
28
29#include "SDL_thread.h"
30#include "SDL_video.h"
31#include "../SDL_pixels_c.h"
32#include "../../events/SDL_events_c.h"
33
34#define MWINCLUDECOLORS
35#include "SDL_nxvideo.h"
36#include "SDL_nxmodes_c.h"
37#include "SDL_nxwm_c.h"
38#include "SDL_nxmouse_c.h"
39#include "SDL_nximage_c.h"
40#include "SDL_nxevents_c.h"
41
42// Initialization/Query functions
43static int NX_VideoInit (_THIS, SDL_PixelFormat * vformat) ;
44static SDL_Surface * NX_SetVideoMode (_THIS, SDL_Surface * current, int width, int height, int bpp, Uint32 flags) ;
45static int NX_SetColors (_THIS, int firstcolor, int ncolors, SDL_Color * colors) ;
46static void NX_VideoQuit (_THIS) ;
47static void NX_DestroyWindow (_THIS, SDL_Surface * screen) ;
48static int NX_ToggleFullScreen (_THIS, int on) ;
49static void NX_UpdateMouse (_THIS) ;
50static int NX_SetGammaRamp (_THIS, Uint16 * ramp) ;
51static int NX_GetGammaRamp (_THIS, Uint16 * ramp) ;
52
53// Microwin driver bootstrap functions
54static int NX_Available ()
55{
56 Dprintf ("enter NX_Available\n") ;
57
58 if (GrOpen () < 0) return 0 ;
59 GrClose () ;
60
61 Dprintf ("leave NX_Available\n") ;
62 return 1 ;
63}
64
65static void NX_DeleteDevice (SDL_VideoDevice * device)
66{
67 Dprintf ("enter NX_DeleteDevice\n") ;
68
69 if (device) {
70 if (device -> hidden) SDL_free (device -> hidden) ;
71 if (device -> gl_data) SDL_free (device -> gl_data) ;
72 SDL_free (device) ;
73 }
74
75 Dprintf ("leave NX_DeleteDevice\n") ;
76}
77
78static SDL_VideoDevice * NX_CreateDevice (int devindex)
79{
80 SDL_VideoDevice * device ;
81
82 Dprintf ("enter NX_CreateDevice\n") ;
83
84 // Initialize all variables that we clean on shutdown
85 device = (SDL_VideoDevice *) SDL_malloc (sizeof (SDL_VideoDevice)) ;
86 if (device) {
87 SDL_memset (device, 0, (sizeof * device)) ;
88 device -> hidden = (struct SDL_PrivateVideoData *)
89 SDL_malloc ((sizeof * device -> hidden)) ;
90 device -> gl_data = NULL ;
91 }
92 if ((device == NULL) || (device -> hidden == NULL)) {
93 SDL_OutOfMemory () ;
94 NX_DeleteDevice (device) ;
95 return 0 ;
96 }
97 SDL_memset (device -> hidden, 0, (sizeof * device -> hidden)) ;
98
99 // Set the function pointers
100 device -> VideoInit = NX_VideoInit ;
101 device -> ListModes = NX_ListModes ;
102 device -> SetVideoMode = NX_SetVideoMode ;
103 device -> ToggleFullScreen = NX_ToggleFullScreen ;
104 device -> UpdateMouse = NX_UpdateMouse ;
105 device -> CreateYUVOverlay = NULL ;
106 device -> SetColors = NX_SetColors ;
107 device -> UpdateRects = NULL ;
108 device -> VideoQuit = NX_VideoQuit;
109 device -> AllocHWSurface = NULL ;
110 device -> CheckHWBlit = NULL ;
111 device -> FillHWRect = NULL ;
112 device -> SetHWColorKey = NULL ;
113 device -> SetHWAlpha = NULL ;
114 device -> LockHWSurface = NULL ;
115 device -> UnlockHWSurface = NULL ;
116 device -> FlipHWSurface = NULL ;
117 device -> FreeHWSurface = NULL ;
118 device -> SetGamma = NULL ;
119 device -> GetGamma = NULL ;
120 device -> SetGammaRamp = NX_SetGammaRamp ;
121 device -> GetGammaRamp = NX_GetGammaRamp ;
122
123#if SDL_VIDEO_OPENGL
124 device -> GL_LoadLibrary = NULL ;
125 device -> GL_GetProcAddress = NULL ;
126 device -> GL_GetAttribute = NULL ;
127 device -> GL_MakeCurrent = NULL ;
128 device -> GL_SwapBuffers = NULL ;
129#endif
130
131 device -> SetIcon = NULL ;
132 device -> SetCaption = NX_SetCaption;
133 device -> IconifyWindow = NULL ;
134 device -> GrabInput = NULL ;
135 device -> GetWMInfo = NX_GetWMInfo ;
136 device -> FreeWMCursor = NX_FreeWMCursor ;
137 device -> CreateWMCursor = NX_CreateWMCursor ;
138 device -> ShowWMCursor = NX_ShowWMCursor ;
139 device -> WarpWMCursor = NX_WarpWMCursor ;
140 device -> CheckMouseMode = NULL ;
141 device -> InitOSKeymap = NX_InitOSKeymap ;
142 device -> PumpEvents = NX_PumpEvents ;
143
144 device -> free = NX_DeleteDevice ;
145
146 Dprintf ("leave NX_CreateDevice\n") ;
147 return device ;
148}
149
150VideoBootStrap NX_bootstrap = {
151 "nanox", "nanox", NX_Available, NX_CreateDevice
152} ;
153
154static void create_aux_windows (_THIS)
155{
156 GR_WM_PROPERTIES props ;
157
158 Dprintf ("enter create_aux_windows\n") ;
159
160 // Don't create any extra windows if we are being managed
161 if (SDL_windowid) {
162 FSwindow = 0 ;
163 return ;
164 }
165
166 if (FSwindow && FSwindow != GR_ROOT_WINDOW_ID) {
167 GrDestroyWindow (FSwindow) ;
168 }
169
170 FSwindow = GrNewWindow (GR_ROOT_WINDOW_ID, 0, 0, 1, 1, 0, BLACK, BLACK) ;
171 props.flags = GR_WM_FLAGS_PROPS ;
172 props.props = GR_WM_PROPS_NODECORATE ;
173 GrSetWMProperties (FSwindow, & props) ;
174
175 GrSelectEvents (FSwindow, (GR_EVENT_MASK_EXPOSURE |
176 GR_EVENT_MASK_BUTTON_DOWN | GR_EVENT_MASK_BUTTON_UP |
177 GR_EVENT_MASK_FOCUS_IN | GR_EVENT_MASK_FOCUS_OUT |
178 GR_EVENT_MASK_KEY_DOWN | GR_EVENT_MASK_KEY_UP |
179 GR_EVENT_MASK_MOUSE_ENTER | GR_EVENT_MASK_MOUSE_EXIT |
180 GR_EVENT_MASK_MOUSE_MOTION | GR_EVENT_MASK_UPDATE |
181 GR_EVENT_MASK_CLOSE_REQ)) ;
182
183 Dprintf ("leave create_aux_windows\n") ;
184}
185
186int NX_VideoInit (_THIS, SDL_PixelFormat * vformat)
187{
188 GR_SCREEN_INFO si ;
189
190 Dprintf ("enter NX_VideoInit\n") ;
191
192 if (GrOpen () < 0) {
193 SDL_SetError ("GrOpen() fail") ;
194 return -1 ;
195 }
196
197 // use share memory to speed up
198#ifdef NANOX_SHARE_MEMORY
199 GrReqShmCmds (0xFFFF);
200#endif
201
202 SDL_Window = 0 ;
203 FSwindow = 0 ;
204
205 GammaRamp_R = NULL ;
206 GammaRamp_G = NULL ;
207 GammaRamp_B = NULL ;
208
209 GrGetScreenInfo (& si) ;
210 SDL_Visual.bpp = si.bpp ;
211
212 /* Determine the current screen size */
213 this->info.current_w = si.cols ;
214 this->info.current_h = si.rows ;
215
216 // GetVideoMode
217 SDL_modelist = (SDL_Rect **) SDL_malloc (sizeof (SDL_Rect *) * 2) ;
218 if (SDL_modelist) {
219 SDL_modelist [0] = (SDL_Rect *) SDL_malloc (sizeof(SDL_Rect)) ;
220 if (SDL_modelist [0]) {
221 SDL_modelist [0] -> x = 0 ;
222 SDL_modelist [0] -> y = 0 ;
223 SDL_modelist [0] -> w = si.cols ;
224 SDL_modelist [0] -> h = si.rows ;
225 }
226 SDL_modelist [1] = NULL ;
227 }
228
229 pixel_type = si.pixtype;
230 SDL_Visual.red_mask = si.rmask;
231 SDL_Visual.green_mask = si.gmask;
232 SDL_Visual.blue_mask = si.bmask;
233
234 vformat -> BitsPerPixel = SDL_Visual.bpp ;
235 if (vformat -> BitsPerPixel > 8) {
236 vformat -> Rmask = SDL_Visual.red_mask ;
237 vformat -> Gmask = SDL_Visual.green_mask ;
238 vformat -> Bmask = SDL_Visual.blue_mask ;
239 }
240
241 // See if we have been passed a window to use
242 SDL_windowid = getenv ("SDL_WINDOWID") ;
243
244 // Create the fullscreen (and managed windows : no implement)
245 create_aux_windows (this) ;
246
247 Dprintf ("leave NX_VideoInit\n") ;
248 return 0 ;
249}
250
251void NX_VideoQuit (_THIS)
252{
253 Dprintf ("enter NX_VideoQuit\n") ;
254
255 // Start shutting down the windows
256 NX_DestroyImage (this, this -> screen) ;
257 NX_DestroyWindow (this, this -> screen) ;
258 if (FSwindow && FSwindow != GR_ROOT_WINDOW_ID) {
259 GrDestroyWindow (FSwindow) ;
260 }
261 NX_FreeVideoModes (this) ;
262 SDL_free (GammaRamp_R) ;
263 SDL_free (GammaRamp_G) ;
264 SDL_free (GammaRamp_B) ;
265
266#ifdef ENABLE_NANOX_DIRECT_FB
267 if (Clientfb)
268 GrCloseClientFramebuffer();
269#endif
270 GrClose () ;
271
272 Dprintf ("leave NX_VideoQuit\n") ;
273}
274
275static void NX_DestroyWindow (_THIS, SDL_Surface * screen)
276{
277 Dprintf ("enter NX_DestroyWindow\n") ;
278
279 if (! SDL_windowid) {
280 if (screen && (screen -> flags & SDL_FULLSCREEN)) {
281 screen -> flags &= ~ SDL_FULLSCREEN ;
282 NX_LeaveFullScreen (this) ;
283 }
284
285 // Destroy the output window
286 if (SDL_Window && SDL_Window != GR_ROOT_WINDOW_ID) {
287 GrDestroyWindow (SDL_Window) ;
288 }
289 }
290
291 // Free the graphics context
292 if (! SDL_GC) {
293 GrDestroyGC (SDL_GC) ;
294 SDL_GC = 0;
295 }
296
297 Dprintf ("leave NX_DestroyWindow\n") ;
298}
299
300static int NX_CreateWindow (_THIS, SDL_Surface * screen,
301 int w, int h, int bpp, Uint32 flags)
302{
303 Dprintf ("enter NX_CreateWindow\n") ;
304
305 // If a window is already present, destroy it and start fresh
306 if (SDL_Window && SDL_Window != GR_ROOT_WINDOW_ID) {
307 NX_DestroyWindow (this, screen) ;
308 }
309
310 // See if we have been given a window id
311 if (SDL_windowid) {
312 SDL_Window = SDL_strtol (SDL_windowid, NULL, 0) ;
313 } else {
314 SDL_Window = 0 ;
315 }
316
317 if ( ! SDL_ReallocFormat (screen, bpp, SDL_Visual.red_mask,
318 SDL_Visual.green_mask, SDL_Visual.blue_mask, 0))
319 return -1;
320
321 // Create (or use) the nanox display window
322 if (! SDL_windowid) {
323
324 SDL_Window = GrNewWindow (GR_ROOT_WINDOW_ID, 0, 0, w, h, 0, BLACK, WHITE) ;
325
326 GrSelectEvents (SDL_Window, (GR_EVENT_MASK_EXPOSURE |
327 GR_EVENT_MASK_BUTTON_DOWN | GR_EVENT_MASK_BUTTON_UP |
328 GR_EVENT_MASK_FOCUS_IN | GR_EVENT_MASK_FOCUS_OUT |
329 GR_EVENT_MASK_KEY_DOWN | GR_EVENT_MASK_KEY_UP |
330 GR_EVENT_MASK_MOUSE_ENTER | GR_EVENT_MASK_MOUSE_EXIT |
331 GR_EVENT_MASK_MOUSE_MOTION | GR_EVENT_MASK_UPDATE |
332 GR_EVENT_MASK_CLOSE_REQ)) ;
333 }
334
335 /* Create the graphics context here, once we have a window */
336 SDL_GC = GrNewGC () ;
337 if (SDL_GC == 0) {
338 SDL_SetError("Couldn't create graphics context");
339 return(-1);
340 }
341
342 // Map them both and go fullscreen, if requested
343 if (! SDL_windowid) {
344 GrMapWindow (SDL_Window) ;
345 if (flags & SDL_FULLSCREEN) {
346 screen -> flags |= SDL_FULLSCREEN ;
347 NX_EnterFullScreen (this) ;
348 } else {
349 screen -> flags &= ~ SDL_FULLSCREEN ;
350 }
351 }
352
353#ifdef ENABLE_NANOX_DIRECT_FB
354 /* attempt allocating the client side framebuffer */
355 Clientfb = GrOpenClientFramebuffer();
356 /* NULL return will default to using GrArea()*/
357#endif
358
359 Dprintf ("leave NX_CreateWindow\n") ;
360 return 0 ;
361}
362
363SDL_Surface * NX_SetVideoMode (_THIS, SDL_Surface * current,
364 int width, int height, int bpp, Uint32 flags)
365{
366 Dprintf ("enter NX_SetVideoMode\n") ;
367
368 // Lock the event thread, in multi-threading environments
369 SDL_Lock_EventThread () ;
370
371 bpp = SDL_Visual.bpp ;
372 if (NX_CreateWindow (this, current, width, height, bpp, flags) < 0) {
373 current = NULL;
374 goto done;
375 }
376
377 if (current -> w != width || current -> h != height) {
378 current -> w = width ;
379 current -> h = height ;
380 current -> pitch = SDL_CalculatePitch (current) ;
381 NX_ResizeImage (this, current, flags) ;
382 }
383
384 /* Clear these flags and set them only if they are in the new set. */
385 current -> flags &= ~(SDL_RESIZABLE|SDL_NOFRAME);
386 current -> flags |= (flags & (SDL_RESIZABLE | SDL_NOFRAME)) ;
387
388 done:
389 SDL_Unlock_EventThread () ;
390
391 Dprintf ("leave NX_SetVideoMode\n") ;
392
393 // We're done!
394 return current ;
395}
396
397// ncolors <= 256
398int NX_SetColors (_THIS, int firstcolor, int ncolors, SDL_Color * colors)
399{
400 int i ;
401 GR_PALETTE pal ;
402
403 Dprintf ("enter NX_SetColors\n") ;
404
405 if (ncolors > 256) return 0 ;
406
407 pal.count = ncolors ;
408 for (i = 0; i < ncolors; ++ i) {
409 pal.palette [i].r = colors [i].r ;
410 pal.palette [i].g = colors [i].g ;
411 pal.palette [i].b = colors [i].b ;
412 }
413 GrSetSystemPalette (firstcolor, & pal) ;
414
415 Dprintf ("leave NX_SetColors\n") ;
416 return 1 ;
417}
418
419static int NX_ToggleFullScreen (_THIS, int on)
420{
421 SDL_Rect rect ;
422 Uint32 event_thread ;
423
424 Dprintf ("enter NX_ToggleFullScreen\n") ;
425
426 // Don't switch if we don't own the window
427 if (SDL_windowid) return 0 ;
428
429 // Don't lock if we are the event thread
430 event_thread = SDL_EventThreadID () ;
431 if (event_thread && (SDL_ThreadID () == event_thread)) {
432 event_thread = 0 ;
433 }
434 if (event_thread) {
435 SDL_Lock_EventThread() ;
436 }
437
438 if (on) {
439 NX_EnterFullScreen (this) ;
440 } else {
441 this -> screen -> flags &= ~ SDL_FULLSCREEN ;
442 NX_LeaveFullScreen (this) ;
443 }
444
445 rect.x = rect.y = 0 ;
446 rect.w = this -> screen -> w, rect.h = this -> screen -> h ;
447 NX_NormalUpdate (this, 1, & rect) ;
448
449 if (event_thread) {
450 SDL_Unlock_EventThread () ;
451 }
452
453 Dprintf ("leave NX_ToggleFullScreen\n") ;
454 return 1 ;
455}
456
457// Update the current mouse state and position
458static void NX_UpdateMouse (_THIS)
459{
460 int x, y ;
461 GR_WINDOW_INFO info ;
462 GR_SCREEN_INFO si ;
463
464
465 Dprintf ("enter NX_UpdateMouse\n") ;
466
467 // Lock the event thread, in multi-threading environments
468 SDL_Lock_EventThread () ;
469
470 GrGetScreenInfo (& si) ;
471 GrGetWindowInfo (SDL_Window, & info) ;
472 x = si.xpos - info.x ;
473 y = si.ypos - info.y ;
474 if (x >= 0 && x <= info.width && y >= 0 && y <= info.height) {
475 SDL_PrivateAppActive (1, SDL_APPMOUSEFOCUS) ;
476 SDL_PrivateMouseMotion (0, 0, x, y);
477 } else {
478 SDL_PrivateAppActive (0, SDL_APPMOUSEFOCUS) ;
479 }
480
481 SDL_Unlock_EventThread () ;
482 Dprintf ("leave NX_UpdateMouse\n") ;
483}
484
485static int NX_SetGammaRamp (_THIS, Uint16 * ramp)
486{
487 int i ;
488 Uint16 * red, * green, * blue ;
489
490 Dprintf ("enter NX_SetGammaRamp\n") ;
491
492 if (SDL_Visual.bpp != 32 && SDL_Visual.bpp != 24) return -1 ;
493
494 if (! GammaRamp_R) GammaRamp_R = (Uint16 *) SDL_malloc (sizeof (Uint16) * CI_SIZE) ;
495 if (! GammaRamp_G) GammaRamp_G = (Uint16 *) SDL_malloc (sizeof (Uint16) * CI_SIZE) ;
496 if (! GammaRamp_B) GammaRamp_B = (Uint16 *) SDL_malloc (sizeof (Uint16) * CI_SIZE) ;
497 if ((! GammaRamp_R) || (! GammaRamp_G) || (! GammaRamp_B)) {
498 SDL_OutOfMemory () ;
499 return -1 ;
500 }
501
502 for (i = 0; i < CI_SIZE; ++ i)
503 GammaRamp_R [i] = GammaRamp_G [i] = GammaRamp_B [i] = i ;
504
505 red = ramp ;
506 green = ramp + CI_SIZE ;
507 blue = green + CI_SIZE ;
508
509 for (i = 0; i < CI_SIZE; ++ i) {
510 GammaRamp_R [i] = red [i] ;
511 GammaRamp_G [i] = green [i] ;
512 GammaRamp_B [i] = blue [i] ;
513 }
514 SDL_UpdateRect(this->screen, 0, 0, 0, 0);
515
516 Dprintf ("leave NX_SetGammaRamp\n") ;
517 return 0 ;
518}
519
520static int NX_GetGammaRamp (_THIS, Uint16 * ramp)
521{
522 int i ;
523 Uint16 * red, * green, * blue ;
524
525 Dprintf ("enter NX_GetGammaRamp\n") ;
526
527 if (SDL_Visual.bpp != 32 && SDL_Visual.bpp != 24) return -1 ;
528 red = ramp ;
529 green = ramp + CI_SIZE ;
530 blue = green + CI_SIZE ;
531 if (GammaRamp_R && GammaRamp_G && GammaRamp_B) {
532 for (i = 0; i < CI_SIZE; ++ i) {
533 red [i] = GammaRamp_R [i] ;
534 green [i] = GammaRamp_G [i] ;
535 blue [i] = GammaRamp_B [i] ;
536 }
537 } else {
538 for (i = 0; i < CI_SIZE; ++ i)
539 red [i] = green [i] = blue [i] = i ;
540 }
541
542 Dprintf ("leave NX_GetGammaRamp\n") ;
543 return 0 ;
544}
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxvideo.h b/apps/plugins/sdl/src/video/nanox/SDL_nxvideo.h
deleted file mode 100644
index 1d858d96f2..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxvideo.h
+++ /dev/null
@@ -1,96 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
15
16 You should have received a copy of the GNU Library General Public
17 License along with this library; if not, write to the Free
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 Sam Lantinga
21 slouken@libsdl.org
22
23 Hsieh-Fu Tsai
24 clare@setabox.com
25*/
26#include "SDL_config.h"
27
28#ifndef _SDL_nxvideo_h
29#define _SDL_nxvideo_h
30
31#include <microwin/nano-X.h>
32
33#include "../SDL_sysvideo.h"
34
35#ifdef ENABLE_NANOX_DEBUG
36#define Dprintf printf
37#else
38#define Dprintf(ignore...)
39#endif
40
41// Hidden "this" pointer for the video functions
42#define _THIS SDL_VideoDevice * this
43
44// Private display data
45typedef struct NX_SDL_VISUAL {
46 int bpp ;
47 Uint32 red_mask ;
48 Uint32 green_mask ;
49 Uint32 blue_mask ;
50} nx_sdl_visual_t ;
51
52struct SDL_PrivateVideoData {
53 GR_WINDOW_ID SDL_Window ;
54 GR_WINDOW_ID FSwindow ;
55 // Flag: true if we have been passed a window
56 char * SDL_windowid ;
57 GR_GC_ID GC ;
58 unsigned char * Image ;
59 unsigned char * Image_buff ; /* for GrArea*/
60 unsigned char * Clientfb; /* for DirectFB*/
61 nx_sdl_visual_t SDL_Visual ;
62 // The current list of available video modes
63 SDL_Rect ** modelist ;
64 int currently_fullscreen ;
65 // for fullscreen
66 int OffsetX, OffsetY ;
67 // for GammaRamp
68 Uint16 * GammaRamp_R, * GammaRamp_G, * GammaRamp_B ;
69 // for GrArea, r_mask, g_mask, b_mask
70 int pixel_type ;
71#ifdef ENABLE_NANOX_DIRECT_FB
72 GR_WINDOW_FB_INFO fbinfo;
73#endif
74} ;
75
76#define SDL_Window (this -> hidden -> SDL_Window)
77#define FSwindow (this -> hidden -> FSwindow)
78#define SDL_windowid (this -> hidden -> SDL_windowid)
79#define SDL_GC (this -> hidden -> GC)
80#define SDL_Image (this -> hidden -> Image)
81#define Image_buff (this -> hidden -> Image_buff)
82#define Clientfb (this -> hidden -> Clientfb)
83#define SDL_Visual (this -> hidden -> SDL_Visual)
84#define SDL_modelist (this -> hidden -> modelist)
85#define currently_fullscreen (this -> hidden -> currently_fullscreen)
86#define OffsetX (this -> hidden -> OffsetX)
87#define OffsetY (this -> hidden -> OffsetY)
88#define GammaRamp_R (this -> hidden -> GammaRamp_R)
89#define GammaRamp_G (this -> hidden -> GammaRamp_G)
90#define GammaRamp_B (this -> hidden -> GammaRamp_B)
91#define pixel_type (this -> hidden -> pixel_type)
92#define fbinfo (this -> hidden -> fbinfo)
93
94#define CI_SIZE 256 // color index size
95
96#endif // _SDL_nxvideo_h
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxwm.c b/apps/plugins/sdl/src/video/nanox/SDL_nxwm.c
deleted file mode 100644
index c60ebb0461..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxwm.c
+++ /dev/null
@@ -1,61 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
15
16 You should have received a copy of the GNU Library General Public
17 License along with this library; if not, write to the Free
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 Sam Lantinga
21 slouken@libsdl.org
22
23 Hsieh-Fu Tsai
24 clare@setabox.com
25*/
26#include "SDL_config.h"
27
28#include "SDL_syswm.h"
29#include "../../events/SDL_events_c.h"
30
31#include "SDL_nxwm_c.h"
32
33void NX_SetCaption (_THIS, const char * title, const char * icon)
34{
35 Dprintf ("enter NX_SetCaption\n") ;
36
37 // Lock the event thread, in multi-threading environments
38 SDL_Lock_EventThread () ;
39
40 if (SDL_Window)
41 GrSetWindowTitle (SDL_Window, title) ;
42
43 SDL_Unlock_EventThread () ;
44 Dprintf ("leave NX_SetCaption\n") ;
45}
46
47int NX_GetWMInfo (_THIS, SDL_SysWMinfo * info)
48{
49 Dprintf ("enter NX_GetWMInfo\n") ;
50
51 if (info -> version.major <= SDL_MAJOR_VERSION) {
52 info -> window = SDL_Window ;
53 return 1 ;
54 } else {
55 SDL_SetError("Application not compiled with SDL %d.%d\n",
56 SDL_MAJOR_VERSION, SDL_MINOR_VERSION) ;
57 return -1 ;
58 }
59
60 Dprintf ("leave NX_GetWMInfo\n") ;
61}
diff --git a/apps/plugins/sdl/src/video/nanox/SDL_nxwm_c.h b/apps/plugins/sdl/src/video/nanox/SDL_nxwm_c.h
deleted file mode 100644
index 77be794f2c..0000000000
--- a/apps/plugins/sdl/src/video/nanox/SDL_nxwm_c.h
+++ /dev/null
@@ -1,32 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4 Copyright (C) 2001 Hsieh-Fu Tsai
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
15
16 You should have received a copy of the GNU Library General Public
17 License along with this library; if not, write to the Free
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 Sam Lantinga
21 slouken@libsdl.org
22
23 Hsieh-Fu Tsai
24 clare@setabox.com
25*/
26#include "SDL_config.h"
27
28#include "SDL_nxvideo.h"
29
30// Functions to be exported
31extern void NX_SetCaption (_THIS, const char * title, const char * icon) ;
32extern int NX_GetWMInfo (_THIS, SDL_SysWMinfo * info) ;
diff --git a/apps/plugins/sdl/src/video/nds/SDL_ndsevents.c b/apps/plugins/sdl/src/video/nds/SDL_ndsevents.c
deleted file mode 100644
index a4f0fbe694..0000000000
--- a/apps/plugins/sdl/src/video/nds/SDL_ndsevents.c
+++ /dev/null
@@ -1,83 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Being a nds driver, there's no event stream. We just define stubs for
25 most of the API. */
26#include <nds.h>
27#include "SDL.h"
28#include "../../events/SDL_sysevents.h"
29#include "../../events/SDL_events_c.h"
30#include "SDL_ndsvideo.h"
31#include "SDL_ndsevents_c.h"
32
33static SDLKey keymap[NDS_NUMKEYS];
34char keymem[NDS_NUMKEYS]; /* memorize states of buttons */
35
36void NDS_PumpEvents(_THIS)
37{
38 scanKeys();
39 int i;
40 SDL_keysym keysym;
41 keysym.mod=KMOD_NONE;
42 for(i=0;i<NDS_NUMKEYS;i++)
43 {
44 keysym.scancode=i;
45 keysym.sym=keymap[i];
46 if(keysHeld()&(1<<i) && !keymem[i])
47 {
48 keymem[i]=1;
49 //printf("key released %d\n",i);
50 SDL_PrivateKeyboard(SDL_RELEASED, &keysym);
51 }
52 if(!(keysHeld()&(1<<i)) && keymem[i])
53 {
54 keymem[i]=0;
55 //printf("key pressed %d\n",i);
56 SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
57 }
58 }
59 //touchPosition touch;
60 //touch=touchReadXY();
61 //if (touch.px!=0 || touch.py!=0)
62 // SDL_PrivateMouseMotion(SDL_PRESSED, 0, touch.px, touch.py);
63}
64
65void NDS_InitOSKeymap(_THIS)
66{
67 SDL_memset(keymem,1,NDS_NUMKEYS);
68 keymap[KEY_A]=SDLK_a;
69 keymap[KEY_B]=SDLK_s;
70 keymap[KEY_X]=SDLK_w;
71 keymap[KEY_Y]=SDLK_d;
72 keymap[KEY_L]=SDLK_q;
73 keymap[KEY_R]=SDLK_e;
74 keymap[KEY_UP]=SDLK_UP;
75 keymap[KEY_DOWN]=SDLK_DOWN;
76 keymap[KEY_LEFT]=SDLK_LEFT;
77 keymap[KEY_RIGHT]=SDLK_RIGHT;
78 keymap[KEY_SELECT]=SDLK_SPACE;
79 keymap[KEY_START]=SDLK_RETURN;
80}
81
82/* end of SDL_gbaevents.c ... */
83
diff --git a/apps/plugins/sdl/src/video/nds/SDL_ndsevents_c.h b/apps/plugins/sdl/src/video/nds/SDL_ndsevents_c.h
deleted file mode 100644
index fcd0ef2da4..0000000000
--- a/apps/plugins/sdl/src/video/nds/SDL_ndsevents_c.h
+++ /dev/null
@@ -1,51 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_ndsvideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29extern void NDS_InitOSKeymap(_THIS);
30extern void NDS_PumpEvents(_THIS);
31
32#define NDS_NUMKEYS 12
33
34/*
35#define NDS_JOYPADREG 0x4000130
36#define NDS_JOYPAD (*(volatile Uint16*)NDS_JOYPADREG)
37
38#define NDS_NUMKEYS 10
39#define NDS_KEYA (0)
40#define NDS_KEYB (1)
41#define NDS_KEYSEL (2)
42#define NDS_KEYSTART (3)
43#define NDS_KEYRIGHT (4)
44#define NDS_KEYLEFT (5)
45#define NDS_KEYUP (6)
46#define NDS_KEYDOWN (7)
47#define NDS_KEYR (8)
48#define NDS_KEYL (9)
49*/
50/* end of SDL_NDSevents_c.h ... */
51
diff --git a/apps/plugins/sdl/src/video/nds/SDL_ndsmouse.c b/apps/plugins/sdl/src/video/nds/SDL_ndsmouse.c
deleted file mode 100644
index bba1417d7c..0000000000
--- a/apps/plugins/sdl/src/video/nds/SDL_ndsmouse.c
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_error.h"
25#include "SDL_mouse.h"
26#include "../../events/SDL_events_c.h"
27
28#include "SDL_ndsmouse_c.h"
29
30
31/* The implementation dependent data for the window manager cursor */
32struct WMcursor {
33 int unused;
34};
diff --git a/apps/plugins/sdl/src/video/nds/SDL_ndsmouse_c.h b/apps/plugins/sdl/src/video/nds/SDL_ndsmouse_c.h
deleted file mode 100644
index 76adf029b6..0000000000
--- a/apps/plugins/sdl/src/video/nds/SDL_ndsmouse_c.h
+++ /dev/null
@@ -1,26 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_ndsvideo.h"
25
26/* Functions to be exported */
diff --git a/apps/plugins/sdl/src/video/nds/SDL_ndsvideo.c b/apps/plugins/sdl/src/video/nds/SDL_ndsvideo.c
deleted file mode 100644
index d0ee8bf4c2..0000000000
--- a/apps/plugins/sdl/src/video/nds/SDL_ndsvideo.c
+++ /dev/null
@@ -1,500 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <nds.h>
25#include <nds/registers_alt.h>
26#include "SDL.h"
27#include "SDL_error.h"
28#include "SDL_video.h"
29#include "SDL_mouse.h"
30#include "../SDL_sysvideo.h"
31#include "../SDL_pixels_c.h"
32#include "../../events/SDL_events_c.h"
33
34#include "SDL_ndsvideo.h"
35#include "SDL_ndsevents_c.h"
36#include "SDL_ndsmouse_c.h"
37
38#define NDSVID_DRIVER_NAME "nds"
39
40/* Initialization/Query functions */
41static int NDS_VideoInit(_THIS, SDL_PixelFormat *vformat);
42static SDL_Rect **NDS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
43static SDL_Surface *NDS_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
44static int NDS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
45static void NDS_VideoQuit(_THIS);
46
47/* Hardware surface functions */
48static int NDS_AllocHWSurface(_THIS, SDL_Surface *surface);
49static int NDS_LockHWSurface(_THIS, SDL_Surface *surface);
50static int NDS_FlipHWSurface(_THIS, SDL_Surface *surface);
51static void NDS_UnlockHWSurface(_THIS, SDL_Surface *surface);
52static void NDS_FreeHWSurface(_THIS, SDL_Surface *surface);
53
54/* etc. */
55static void NDS_UpdateRects(_THIS, int numrects, SDL_Rect *rects);
56
57/* NDS driver bootstrap functions */
58
59static int NDS_Available(void)
60{
61 return(1);
62}
63
64static void NDS_DeleteDevice(SDL_VideoDevice *device)
65{
66 SDL_free(device->hidden);
67 SDL_free(device);
68}
69
70void on_irq_vblank()
71{
72 // Disable interrupts
73 //REG_IME = 0;
74 scanKeys();
75
76 // VBLANK_INTR_WAIT_FLAGS |= IRQ_VBLANK;
77 // REG_IF |= IRQ_VBLANK;
78 //REG_IF = REG_IF;
79
80 // Enable interrupts
81 //REG_IME = 1;
82}
83
84static int HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
85 SDL_Surface *dst, SDL_Rect *dstrect)
86 {
87 return 0;
88 }
89
90static int CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst)
91{
92 if (src->flags & SDL_SRCALPHA) return false;
93 if (src->flags & SDL_SRCCOLORKEY) return false;
94 if (src->flags & SDL_HWPALETTE ) return false;
95 if (dst->flags & SDL_SRCALPHA) return false;
96 if (dst->flags & SDL_SRCCOLORKEY) return false;
97 if (dst->flags & SDL_HWPALETTE ) return false;
98
99 if (src->format->BitsPerPixel != dst->format->BitsPerPixel) return false;
100 if (src->format->BytesPerPixel != dst->format->BytesPerPixel) return false;
101
102 src->map->hw_blit = HWAccelBlit;
103 return true;
104}
105
106static SDL_VideoDevice *NDS_CreateDevice(int devindex)
107{
108 SDL_VideoDevice *device=0;
109
110
111 /* Initialize all variables that we clean on shutdown */
112 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
113 if ( device ) {
114 SDL_memset(device, 0, (sizeof *device));
115 device->hidden = (struct SDL_PrivateVideoData *)
116 SDL_malloc((sizeof *device->hidden));
117 }
118 if ( (device == NULL) || (device->hidden == NULL) ) {
119 SDL_OutOfMemory();
120 if ( device ) {
121 SDL_free(device);
122 }
123 return(0);
124 }
125 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
126
127 /* Set the function pointers */
128 device->VideoInit = NDS_VideoInit;
129 device->ListModes = NDS_ListModes;
130 device->SetVideoMode = NDS_SetVideoMode;
131 device->CreateYUVOverlay = NULL;
132 device->SetColors = NDS_SetColors;
133 device->UpdateRects = NDS_UpdateRects;
134 device->VideoQuit = NDS_VideoQuit;
135 device->AllocHWSurface = NDS_AllocHWSurface;
136 device->CheckHWBlit = CheckHWBlit;
137 device->FillHWRect = NULL;
138 device->SetHWColorKey = NULL;
139 device->SetHWAlpha = NULL;
140 device->LockHWSurface = NDS_LockHWSurface;
141 device->UnlockHWSurface = NDS_UnlockHWSurface;
142 device->FlipHWSurface = NDS_FlipHWSurface;
143 device->FreeHWSurface = NDS_FreeHWSurface;
144 device->SetCaption = NULL;
145 device->SetIcon = NULL;
146 device->IconifyWindow = NULL;
147 device->GrabInput = NULL;
148 device->GetWMInfo = NULL;
149 device->InitOSKeymap = NDS_InitOSKeymap;
150 device->PumpEvents = NDS_PumpEvents;
151 device->info.blit_hw=1;
152
153 device->free = NDS_DeleteDevice;
154 return device;
155}
156
157VideoBootStrap NDS_bootstrap = {
158 NDSVID_DRIVER_NAME, "SDL NDS video driver",
159 NDS_Available, NDS_CreateDevice
160};
161
162 u16* frontBuffer;// = (u16*)(0x06000000);
163 u16* backBuffer;// = (u16*)(0x06000000 + 256 * 256 * 2);
164int NDS_VideoInit(_THIS, SDL_PixelFormat *vformat)
165{
166 //printf("WARNING: You are using the SDL NDS video driver!\n");
167
168 /* Determine the screen depth (use default 8-bit depth) */
169 /* we change this during the SDL_SetVideoMode implementation... */
170 vformat->BitsPerPixel = 16; // mode 3
171 vformat->BytesPerPixel = 2;
172 vformat->Rmask = 0x0000f800;
173 vformat->Gmask = 0x000007e0;
174 vformat->Bmask = 0x0000001f;
175 powerON(POWER_ALL);
176 irqInit();
177 irqSet(IRQ_VBLANK, on_irq_vblank);
178 irqEnable(IRQ_VBLANK);
179
180 //set the mode for 2 text layers and two extended background layers
181 //videoSetMode(MODE_5_2D | DISPLAY_BG3_ACTIVE);
182 videoSetMode(MODE_6_2D| DISPLAY_BG2_ACTIVE);
183
184 //set the sub background up for text display (we could just print to one
185 //of the main display text backgrounds just as easily
186 videoSetModeSub(MODE_0_2D | DISPLAY_BG0_ACTIVE); //sub bg 0 will be used to print text
187
188 //set the first two banks as background memory and the third as sub background memory
189 //D is not used..if you need a bigger background then you will need to map
190 //more vram banks consecutivly (VRAM A-D are all 0x20000 bytes in size)
191 //vramSetMainBanks(VRAM_A_MAIN_BG_0x6000000, VRAM_B_MAIN_BG_0x6020000,VRAM_C_SUB_BG , VRAM_D_LCD);
192 vramSetMainBanks(VRAM_A_MAIN_BG,VRAM_B_MAIN_BG,VRAM_C_MAIN_BG,VRAM_D_MAIN_BG);
193 //vramSetBankA(VRAM_A_MAIN_BG);
194 //vramSetBankB(VRAM_B_MAIN_BG);
195 //vramSetBankC(VRAM_C_MAIN_BG);
196 //vramSetBankD(VRAM_D_MAIN_BG);
197 //vramSetBankE(VRAM_E_MAIN_BG);
198 //vramSetBankF(VRAM_F_MAIN_BG);
199 //vramSetBankG(VRAM_G_MAIN_BG);
200 vramSetBankH(VRAM_H_SUB_BG);
201 vramSetBankI(VRAM_I_LCD);
202
203 ////////////////set up text background for text/////////////////////
204 SUB_BG0_CR = BG_MAP_BASE(8);
205
206 BG_PALETTE_SUB[255] = RGB15(31,31,31);//by default font will be rendered with color 255
207 ///////////////set up our bitmap background///////////////////////
208
209 //BG3_CR = BG_BMP16_512x512;
210
211 //these are rotation backgrounds so you must set the rotation attributes:
212 //these are fixed point numbers with the low 8 bits the fractional part
213 //this basicaly gives it a 1:1 translation in x and y so you get a nice flat bitmap
214 /* BG3_XDX = 1<<8;
215 BG3_XDY = 0;
216 BG3_YDX = 0;
217 BG3_YDY = 1<<8;
218 //our bitmap looks a bit better if we center it so scroll down (256 - 192) / 2
219 BG3_CX = 0;
220 BG3_CY = 0;
221 */
222 //consoleInit() is a lot more flexible but this gets you up and running quick
223 consoleInitDefault((u16*)SCREEN_BASE_BLOCK_SUB(8), (u16*)CHAR_BASE_BLOCK_SUB(0), 16);
224
225
226 frontBuffer =(u16*)(0x06000000);
227 //backBuffer =(u16*)(0x06000000 + 1024 * 512*2);
228
229 //lcdSwap();
230 /* We're done! */
231 return(0);
232}
233
234SDL_Rect **NDS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
235{
236 return (SDL_Rect **) -1;
237}
238
239SDL_Surface *NDS_SetVideoMode(_THIS, SDL_Surface *current,
240 int width, int height, int bpp, Uint32 flags)
241{
242 Uint32 Rmask, Gmask, Bmask, Amask;
243
244 //if(width > 1024 || height > 512 || bpp > 16)
245 // return(NULL);
246
247 if(bpp >8) {
248 bpp=16;
249 Rmask = 0x0000001F;
250 Gmask = 0x000003E0;
251 Bmask = 0x00007C00;
252 Amask = 0x00008000;
253
254 videoSetMode(MODE_5_2D| DISPLAY_BG2_ACTIVE);
255
256 vramSetMainBanks(VRAM_A_MAIN_BG,VRAM_B_MAIN_BG,VRAM_C_MAIN_BG,VRAM_D_MAIN_BG);
257
258 BG2_CR = BG_BMP16_512x512;
259 BG2_XDX = ((width / 256) << 8) | (width % 256) ;
260 BG2_XDY = 0;
261 BG2_YDX = 0;
262 BG2_YDY = ((height / 192) << 8) | ((height % 192) + (height % 192) / 3) ;
263 BG2_CX = 0;
264 BG2_CY = 0;
265// for (i=0;i<256*192;i++)
266// frontBuffer[i] = RGB15(31,0,0)|BIT(15);
267 }
268 else
269 if(bpp <= 8) {
270 bpp=8;
271 Rmask = 0x00000000;
272 Gmask = 0x00000000;
273 Bmask = 0x00000000;
274 BG2_CR = BG_BMP8_1024x512;
275 BG2_XDX = ((width / 256) << 8) | (width % 256) ;
276 BG2_XDY = 0;
277 BG2_YDX = 0;
278 BG2_YDY = ((height / 192) << 8) | ((height % 192) + (height % 192) / 3) ;
279
280 }
281 else
282 if(bpp < 15) bpp=15;
283 if(width<=256) width=256;
284 else
285 if(width<256) width=256;
286 if(height<=192) height=192;
287 else
288 if(height<192) height=192;
289
290 if(bpp==8)
291 {
292 if(width<256) width=256;
293 if(height<192) height=192;
294 this->hidden->ndsmode=4;
295 }
296
297 if(bpp==15)
298 {
299 if(width<256) this->hidden->ndsmode=5;
300 else this->hidden->ndsmode=3;
301 }
302
303 this->hidden->buffer= frontBuffer;//NDS_VRAM_BASE;
304
305 //NDS_DISPCNT = NDS_DISP_MODE(this->hidden->ndsmode)|NDS_DISP_BG2;
306
307 //fprintf(stderr,"Setting mode %dx%d (ndsmode %d)\n", width, height,this->hidden->ndsmode);
308
309 // FIXME: How do I tell that 15 bits mode is 555?
310
311 SDL_memset(this->hidden->buffer, 0, 1024 * 512* ((this->hidden->ndsmode==4 || this->hidden->ndsmode==5) ? 2 : 1 ) * ((bpp+7) / 8));
312
313 /* Allocate the new pixel format for the screen */
314 if ( ! SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, Amask) ) {
315 this->hidden->buffer = NULL;
316 SDL_SetError("Couldn't allocate new pixel format for requested mode");
317 return(NULL);
318 }
319
320 /* Set up the new mode framebuffer */
321 current->flags = flags | SDL_FULLSCREEN | SDL_HWSURFACE | (this->hidden->ndsmode > 0 ? SDL_DOUBLEBUF : 0);
322 this->hidden->w = current->w = width;
323 this->hidden->h = current->h = height;
324 current->pixels = frontBuffer;
325
326 if (flags & SDL_DOUBLEBUF) {
327 this->hidden->secondbufferallocd=1;
328 backBuffer=(u16*)SDL_malloc(1024*512*2);
329 current->pixels = backBuffer;
330 }
331 if(bpp==8)
332 current->pitch =1024;
333 else
334 current->pitch =512*2;
335
336 /* We're done */
337 return(current);
338}
339
340static int NDS_AllocHWSurface(_THIS, SDL_Surface *surface)
341{
342 if(this->hidden->secondbufferallocd) {
343 //printf("double double buffer alloc\n");
344 return -1;
345 }
346 //if(this->hidden->ndsmode==3)
347 //{
348 // printf("no 2nd buffer in mode3\n");
349 // return -1;
350 //}
351 //printf("second buffer\n");
352 //this->hidden->secondbufferallocd=1;
353 //backBuffer=(u16*)malloc(1024*512*2);
354 //surface->pixels = backBuffer;
355
356 return(0);
357}
358static void NDS_FreeHWSurface(_THIS, SDL_Surface *surface)
359{
360 //free(backBuffer);
361 this->hidden->secondbufferallocd=0;
362}
363int z=0;
364/* We need to wait for vertical retrace on page flipped displays */
365static int NDS_LockHWSurface(_THIS, SDL_Surface *surface)
366{
367/*
368 uint8* a = surface->pixels;
369 int i,j;
370 a += 5 * SCREEN_WIDTH + 5;
371 for( i = 0; i < 195; ++i) {
372 uint16* line = a + (SCREEN_WIDTH * i);
373 for( j = 0; j < 158; ++j) {
374 *line++ = RGB15(155,155,25);
375 }
376 }
377*/
378 //if (z <256)
379 // BG_PALETTE[z++]=RGB15(255-z,z,255-z);
380
381
382 return(0);
383}
384
385static void NDS_UnlockHWSurface(_THIS, SDL_Surface *surface)
386{
387 return;
388}
389
390static int NDS_FlipHWSurface(_THIS, SDL_Surface *surface)
391{
392 if(this->hidden->secondbufferallocd){
393 while(DISP_Y!=192);
394 while(DISP_Y==192);
395 //printf("flip");
396
397 dmaCopyAsynch(backBuffer,frontBuffer,1024*512);
398 }
399 //printf("flip\n");
400 //u16* temp = surface->pixels;
401 //surface->pixels = frontBuffer;
402 //frontBuffer = temp;
403 /* u8* vram=BG_GFX;
404 int x,y;
405 for(y = 0; y < 512; y++)
406 dmaCopy(&frontBuffer[y*rects->w], &vram[y*512],512);
407 //unsigned char buf;
408
409 //printf("NDS_FlipHWSurface\n");
410 //printf("ptr now: 0x%x\n",surface->pixels);
411
412 while(DISP_Y!=192);
413 while(DISP_Y==192);
414 //swap
415 u16* temp = frontBuffer;
416 frontBuffer = backBuffer;
417 backBuffer = temp;
418
419 //flip
420 //base is 16KB and screen size is 256x256x2 (128KB)
421 BG2_CR ^= BG_BMP_BASE( 512 / 16 ); */
422/*
423 if(surface->pixels == frontBuffer)//NDS_VRAM_BASE)
424 {
425 while(DISP_Y!=192);
426 while(DISP_Y==192);
427 //swap
428 u16* temp = backBuffer;
429 backBuffer = frontBuffer;
430 frontBuffer = temp;
431
432 //flip
433 //base is 16KB and screen size is 256x256x2 (128KB)
434 BG3_CR ^= BG_BMP_BASE( 128 / 16 );
435 }
436 else
437 {
438
439 while(DISP_Y!=192);
440 while(DISP_Y==192);
441 //swap
442 u16* temp = frontBuffer;
443 frontBuffer = backBuffer;
444 backBuffer = temp;
445
446 //flip
447 //base is 16KB and screen size is 256x256x2 (128KB)
448 BG3_CR ^= BG_BMP_BASE( 128 / 16 );
449
450 }
451 */
452 //printf("ptr then: 0x%x\n",surface->pixels);
453
454 //printf("setting dispcnt to 0x%x\n",NDS_DISPCNT = NDS_DISP_MODE(this->hidden->ndsmode)|NDS_DISP_BG2| buf);
455 return(0);
456}
457
458static void NDS_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
459{
460 //fprintf(stderr,"update\n");
461 /* do nothing. */
462 //dmaCopy(frontBuffer,BG_GFX,512*512);
463 /*
464 u8* vram=(u8*)BG_GFX;
465 int x,y;
466 for(y = 0; y < 512; y++)
467 dmaCopy(&frontBuffer[y*rects->w], &vram[y*512],512);
468 */
469
470}
471
472int NDS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
473{
474 //printf("SetColors\n");
475 short r,g,b;
476
477 if(this->hidden->ndsmode != 4)
478 {
479 printf("This is not a palettized mode\n");
480 return -1;
481 }
482
483 int i,j=firstcolor+ncolors;
484 for(i=firstcolor;i<j;i++)
485 {
486 r=colors[i].r>>3;
487 g=colors[i].g>>3;
488 b=colors[i].b>>3;
489 BG_PALETTE[i]=RGB15(r, g, b);
490 }
491
492 return(0);
493}
494
495/* Note: If we are terminated, this could be called in the middle of
496 another SDL video routine -- notably UpdateRects.
497*/
498void NDS_VideoQuit(_THIS)
499{
500}
diff --git a/apps/plugins/sdl/src/video/nds/SDL_ndsvideo.h b/apps/plugins/sdl/src/video/nds/SDL_ndsvideo.h
deleted file mode 100644
index 015f655421..0000000000
--- a/apps/plugins/sdl/src/video/nds/SDL_ndsvideo.h
+++ /dev/null
@@ -1,61 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_ndsvideo_h
25#define _SDL_ndsvideo_h
26
27#include "SDL_mouse.h"
28#include "../SDL_sysvideo.h"
29
30/* Hidden "this" pointer for the video functions */
31#define _THIS SDL_VideoDevice *this
32
33
34/* Private display data */
35
36struct SDL_PrivateVideoData {
37 int w, h;
38 void *buffer;
39 short ndsmode;
40 short secondbufferallocd;
41};
42
43/*
44#define NDS_VIDC_BASE 0x4000000
45#define NDS_DISPCNT (*(volatile Uint32*)(NDS_VIDC_BASE))
46#define NDS_VIDC_SCANLINE (NDS_VIDC_BASE+6)
47#define NDS_SCANLINE (*(volatile Uint8*)(NDS_VIDC_SCANLINE))
48
49#define NDS_DISP_MODE(n) (n&7)
50#define NDS_DISP_BG2 0x400
51#define NDS_DISP_FB 0x10
52
53#define NDS_PAL_BASE 0x5000000
54#define NDS_BGPAL ((volatile Uint16*)(NDS_PAL_BASE))
55#define NDS_OBJPAL ((volatile Uint16*)(NDS_PAL_BASE+0x200))
56
57#define NDS_VRAM_BASE 0x6000000
58#define NDS_VRAM_2NDBUF 0x600a000
59#define NDS_VRAM = ((volatile Uint16* )NDS_VRAM_BASE)
60*/
61#endif /* _SDL_ndsvideo_h */
diff --git a/apps/plugins/sdl/src/video/os2fslib/SDL_os2fslib.c b/apps/plugins/sdl/src/video/os2fslib/SDL_os2fslib.c
deleted file mode 100644
index a902d1fe7f..0000000000
--- a/apps/plugins/sdl/src/video/os2fslib/SDL_os2fslib.c
+++ /dev/null
@@ -1,3018 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#define _ULS_CALLCONV_
25#define CALLCONV _System
26#include <unidef.h> // Unicode API
27#include <uconv.h> // Unicode API (codepage conversion)
28
29#include <process.h>
30#include <time.h>
31
32#include "SDL_video.h"
33#include "SDL_mouse.h"
34#include "../SDL_sysvideo.h"
35#include "../SDL_pixels_c.h"
36#include "../../events/SDL_events_c.h"
37
38#include "SDL_os2fslib.h"
39
40static ULONG ulFCFToUse =
41 FCF_TITLEBAR |
42 FCF_SYSMENU |
43 FCF_MINBUTTON |
44 FCF_MAXBUTTON |
45 FCF_NOBYTEALIGN |
46 FCF_SIZEBORDER |
47 FCF_TASKLIST;
48
49static int bMouseCaptured = 0;
50static int bMouseCapturable = 0;
51static HPOINTER hptrGlobalPointer = NULL;
52static HPOINTER hptrCurrentIcon = NULL;
53static int iWindowSizeX = 320;
54static int iWindowSizeY = 200;
55static int bWindowResized = 0;
56
57#pragma pack(1)
58typedef struct BMPINFO
59{
60 BITMAPINFO;
61 RGB clr;
62} BMPINFO, *PBMPINFO;
63#pragma pack()
64
65
66// Backdoors:
67DECLSPEC void SDLCALL SDL_OS2FSLIB_SetFCFToUse(ULONG ulFCF)
68{
69 ulFCFToUse = ulFCF;
70}
71
72// Configuration defines:
73
74// We have to report empty alpha mask, otherwise SDL will select
75// alpha blitters, and this will have unwanted results, as we don't
76// support alpha channel in FSLib yet.
77#define REPORT_EMPTY_ALPHA_MASK
78
79// Experimental: Move every FSLib_BitBlt() call into window message
80// processing function.
81// This may fix dirt left on desktop. Or not.
82//#define BITBLT_IN_WINMESSAGEPROC
83
84// Experimental-2: Use WinLockWindowUpdate() in around bitblts!
85// This is not enabled, because it seems to cause more problems
86// than good.
87//#define USE_WINLOCKWINDOWUPDATE_AROUND_BITBLTS
88
89// Use the following to show resized image instead of black stuff
90// even if the surface is resizable.
91//#define RESIZE_EVEN_IF_RESIZABLE
92
93/* The translation table from a VK keysym to a SDL keysym */
94static SDLKey HWScanKeyMap[256];
95static SDL_keysym *TranslateKey(int vkey, int chcode, int scancode, SDL_keysym *keysym, int iPressed);
96static int iShiftIsPressed;
97
98#ifdef BITBLT_IN_WINMESSAGEPROC
99#define WM_UPDATERECTSREQUEST WM_USER+50
100#endif
101
102#ifdef USE_WINLOCKWINDOWUPDATE_AROUND_BITBLTS
103#define FSLIB_BITBLT(hwnd, buffer, top, left, width, height) \
104 { \
105 WinLockWindowUpdate(HWND_DESKTOP, HWND_DESKTOP); \
106 FSLib_BitBlt(hwnd, buffer, top, left, width, height); \
107 WinLockWindowUpdate(HWND_DESKTOP, NULL); \
108 }
109#else
110#define FSLIB_BITBLT(hwnd, buffer, top, left, width, height) \
111 FSLib_BitBlt(hwnd, buffer, top, left, width, height);
112#endif
113
114/////////////////////////////////////////////////////////////////////
115//
116// SetAccessableWindowPos
117//
118// Same as WinSetWindowPos(), but takes care for the window to be
119// always on the screen, the titlebar will be accessable everytime.
120//
121/////////////////////////////////////////////////////////////////////
122static BOOL SetAccessableWindowPos(HWND hwnd, HWND hwndInsertBehind,
123 LONG x, LONG y,
124 LONG cx, LONG cy,
125 ULONG fl)
126{
127 SWP swpDesktop, swp;
128 // Get desktop area
129 WinQueryWindowPos(HWND_DESKTOP, &swpDesktop);
130
131 if ((fl & SWP_MOVE) && (fl & SWP_SIZE))
132 {
133 // If both moving and sizing, then change size and pos now!!
134 if (x+cx>swpDesktop.cx)
135 x = swpDesktop.cx - cx;
136 if (x<0)
137 x = 0;
138 if (y<0)
139 y = 0;
140 if (y+cy>swpDesktop.cy)
141 y = swpDesktop.cy - cy;
142 return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl);
143 } else
144 if (fl & SWP_MOVE)
145 {
146 // Just moving
147 WinQueryWindowPos(hwnd, &swp);
148 if (x+swp.cx>swpDesktop.cx)
149 x = swpDesktop.cx - swp.cx;
150 if (x<0)
151 x = 0;
152 if (y<0)
153 y = 0;
154 if (y+swp.cy>swpDesktop.cy)
155 y = swpDesktop.cy - swp.cy;
156 return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl);
157 } else
158 if (fl & SWP_SIZE)
159 {
160 // Just sizing
161 WinQueryWindowPos(hwnd, &swp);
162 x = swp.x;
163 y = swp.y;
164 if (x+cx>swpDesktop.cx)
165 x = swpDesktop.cx - cx;
166 if (x<0)
167 x = 0;
168 if (y<0)
169 y = 0;
170 if (y+cy>swpDesktop.cy)
171 y = swpDesktop.cy - cy;
172 return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl | SWP_MOVE);
173 } else
174 return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl);
175}
176
177static UniChar NativeCharToUniChar(int chcode)
178{
179 UniChar ucResult = (UniChar) chcode;
180 int rc;
181 UconvObject ucoTemp;
182 char achFrom[2];
183 char *pchFrom;
184 size_t iFromCount;
185 UniChar aucTo[10];
186 UniChar *pucTo;
187 size_t iToCount;
188 size_t iNonIdentical;
189
190 // Create unicode convert object
191 rc = UniCreateUconvObject(L"", &ucoTemp);
192 if (rc!=ULS_SUCCESS)
193 {
194 // Could not create convert object!
195 return ucResult;
196 }
197
198 // Convert language code string to unicode string
199 achFrom[0] = (char) chcode;
200 achFrom[1] = 0;
201 iFromCount = sizeof(char) * 2;
202 iToCount = sizeof(UniChar) * 2;
203 pucTo = &(aucTo[0]);
204 pchFrom = &(achFrom[0]);
205
206 rc = UniUconvToUcs(ucoTemp,
207 &pchFrom,
208 &iFromCount,
209 &pucTo,
210 &iToCount,
211 &iNonIdentical);
212
213 if (rc!=ULS_SUCCESS)
214 {
215 // Could not convert language code to UCS string!
216 UniFreeUconvObject(ucoTemp);
217 return ucResult;
218 }
219
220 UniFreeUconvObject(ucoTemp);
221
222#ifdef DEBUG_BUILD
223 printf("%02x converted to %02x\n", (int) chcode, (int) (aucTo[0]));
224#endif
225
226 return aucTo[0];
227}
228
229/////////////////////////////////////////////////////////////////////
230//
231// TranslateKey
232//
233// This creates SDL Keycodes from VK_ and hardware scan codes
234//
235/////////////////////////////////////////////////////////////////////
236static SDL_keysym *TranslateKey(int vkey, int chcode, int scancode, SDL_keysym *keysym, int iPressed)
237{
238 keysym->scancode = (unsigned char) scancode;
239 keysym->mod = KMOD_NONE;
240 keysym->unicode = 0;
241
242 if (iPressed && SDL_TranslateUNICODE)
243 {
244 if (chcode)
245 keysym->unicode = NativeCharToUniChar(chcode);
246 else
247 keysym->unicode = vkey;
248 }
249
250 keysym->sym = HWScanKeyMap[scancode];
251
252 // Now stuffs based on state of shift key(s)!
253 if (vkey == VK_SHIFT)
254 {
255 iShiftIsPressed = iPressed;
256 }
257
258 if ((iShiftIsPressed) && (SDL_TranslateUNICODE))
259 {
260 // Change syms, if Unicode stuff is required
261 // I think it's silly, but it's SDL...
262 switch (keysym->sym)
263 {
264 case SDLK_BACKQUOTE:
265 keysym->sym = '~';
266 break;
267 case SDLK_1:
268 keysym->sym = SDLK_EXCLAIM;
269 break;
270 case SDLK_2:
271 keysym->sym = SDLK_AT;
272 break;
273 case SDLK_3:
274 keysym->sym = SDLK_HASH;
275 break;
276 case SDLK_4:
277 keysym->sym = SDLK_DOLLAR;
278 break;
279 case SDLK_5:
280 keysym->sym = '%';
281 break;
282 case SDLK_6:
283 keysym->sym = SDLK_CARET;
284 break;
285 case SDLK_7:
286 keysym->sym = SDLK_AMPERSAND;
287 break;
288 case SDLK_8:
289 keysym->sym = SDLK_ASTERISK;
290 break;
291 case SDLK_9:
292 keysym->sym = SDLK_LEFTPAREN;
293 break;
294 case SDLK_0:
295 keysym->sym = SDLK_RIGHTPAREN;
296 break;
297 case SDLK_MINUS:
298 keysym->sym = SDLK_UNDERSCORE;
299 break;
300 case SDLK_PLUS:
301 keysym->sym = SDLK_EQUALS;
302 break;
303
304 case SDLK_LEFTBRACKET:
305 keysym->sym = '{';
306 break;
307 case SDLK_RIGHTBRACKET:
308 keysym->sym = '}';
309 break;
310
311 case SDLK_SEMICOLON:
312 keysym->sym = SDLK_COLON;
313 break;
314 case SDLK_QUOTE:
315 keysym->sym = SDLK_QUOTEDBL;
316 break;
317 case SDLK_BACKSLASH:
318 keysym->sym = '|';
319 break;
320
321 case SDLK_COMMA:
322 keysym->sym = SDLK_LESS;
323 break;
324 case SDLK_PERIOD:
325 keysym->sym = SDLK_GREATER;
326 break;
327 case SDLK_SLASH:
328 keysym->sym = SDLK_QUESTION;
329 break;
330
331 default:
332 break;
333 }
334 }
335 return keysym;
336}
337
338#define CONVERTMOUSEPOSITION() \
339 /* We have to inverse the mouse position, because every non-os/2 system */ \
340 /* has a coordinate system where the (0;0) is the top-left corner, */ \
341 /* while on os/2 it's the bottom left corner! */ \
342 if (FSLib_QueryFSMode(hwnd)) \
343 { \
344 /* We're in FS mode! */ \
345 /* In FS mode our window is as big as fullscreen mode, but not necessary as */ \
346 /* big as the source buffer (can be bigger) */ \
347 /* So, limit mouse pos to source buffer size! */ \
348 if (ppts->x<0) ppts->x = 0; \
349 if (ppts->y<0) ppts->y = 0; \
350 if (ppts->x>=pVideo->hidden->SrcBufferDesc.uiXResolution) ppts->x = pVideo->hidden->SrcBufferDesc.uiXResolution-1; \
351 if (ppts->y>=pVideo->hidden->SrcBufferDesc.uiYResolution) ppts->y = pVideo->hidden->SrcBufferDesc.uiYResolution-1; \
352 pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ \
353 ptl.x = ppts->x; ptl.y = ppts->y; \
354 WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1); \
355 WinSetPointerPos(HWND_DESKTOP, ptl.x, ptl.y); \
356 /* Then convert OS/2 position to SDL position */ \
357 ppts->y = pVideo->hidden->SrcBufferDesc.uiYResolution - ppts->y - 1; \
358 } else \
359 { \
360 SWP swpClient; \
361 /* We're in windowed mode! */ \
362 WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient); \
363 /* Convert OS/2 mouse position to SDL position, and also scale it! */ \
364 (ppts->x) = (ppts->x) * pVideo->hidden->SrcBufferDesc.uiXResolution / swpClient.cx; \
365 (ppts->y) = (ppts->y) * pVideo->hidden->SrcBufferDesc.uiYResolution / swpClient.cy; \
366 (ppts->y) = pVideo->hidden->SrcBufferDesc.uiYResolution - (ppts->y) - 1; \
367 }
368
369
370
371/////////////////////////////////////////////////////////////////////
372//
373// WndProc
374//
375// This is the message processing window procedure for the
376// SDLWindowClass, which is the client window in our application.
377// It handles switching back and away from the app (taking care of
378// going out and back to and from fullscreen mode), sending keystrokes
379// and mouse events to where it has to be sent, etc...
380//
381/////////////////////////////////////////////////////////////////////
382static MRESULT EXPENTRY WndProc( HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
383{
384 HPS ps;
385 RECTL rcl;
386 SDL_VideoDevice *pVideo = NULL;
387
388 switch (msg)
389 {
390 case WM_CHAR: // Keypress notification
391#ifdef DEBUG_BUILD
392// printf("WM_CHAR\n"); fflush(stdout);
393#endif
394 pVideo = WinQueryWindowPtr(hwnd, 0);
395 if (pVideo)
396 {
397 /*
398 // We skip repeated keys:
399 if (CHARMSG(&msg)->cRepeat>1)
400 {
401#ifdef DEBUG_BUILD
402// printf("Repeated key (%d), skipping...\n", CHARMSG(&msg)->cRepeat); fflush(stdout);
403#endif
404 return (MRESULT) TRUE;
405 }
406 */
407
408 // If it's not repeated, then let's see if its pressed or released!
409 if (SHORT1FROMMP(mp1) & KC_KEYUP)
410 {
411 // A key has been released
412 SDL_keysym keysym;
413
414#ifdef DEBUG_BUILD
415// printf("WM_CHAR, keyup, code is [0x%0x]\n", CHAR4FROMMP(mp1)); // HW scan code
416#endif
417
418 // One problem is with F1, which gets only the keyup message because
419 // it is a system key.
420 // So, when we get keyup message, we simulate keydown too!
421 // UPDATE:
422 // This problem should be solved now, that the accelerator keys are
423 // disabled for this window!
424 /*
425 if (SHORT2FROMMP(mp2)==VK_F1)
426 {
427 SDL_PrivateKeyboard(SDL_PRESSED, TranslateKey(SHORT2FROMMP(mp2), // VK_ code
428 SHORT1FROMMP(mp2), // Character code
429 CHAR4FROMMP(mp1), // HW Scan code
430 &keysym,0));
431 }*/
432
433 SDL_PrivateKeyboard(SDL_RELEASED, TranslateKey(SHORT2FROMMP(mp2), // VK_ code
434 SHORT1FROMMP(mp2), // Character code
435 CHAR4FROMMP(mp1), // HW Scan code
436 &keysym,0));
437
438 } else
439 {
440 // A key has been pressed
441 SDL_keysym keysym;
442
443#ifdef DEBUG_BUILD
444// printf("WM_CHAR, keydown, code is [0x%0x]\n", CHAR4FROMMP(mp1)); // HW scan code
445#endif
446 // Check for fastkeys: ALT+HOME to toggle FS mode
447 // ALT+END to close app
448 if ((SHORT1FROMMP(mp1) & KC_ALT) &&
449 (SHORT2FROMMP(mp2) == VK_HOME))
450 {
451#ifdef DEBUG_BUILD
452 printf(" Pressed ALT+HOME!\n"); fflush(stdout);
453#endif
454 // Only switch between fullscreen and back if it's not
455 // a resizable mode!
456 if (
457 (!pVideo->hidden->pSDLSurface) ||
458 ((pVideo->hidden->pSDLSurface)
459 && ((pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE)==0)
460 )
461 )
462 FSLib_ToggleFSMode(hwnd, !FSLib_QueryFSMode(hwnd));
463#ifdef DEBUG_BUILD
464 else
465 printf(" Resizable mode, so discarding ALT+HOME!\n"); fflush(stdout);
466#endif
467 } else
468 if ((SHORT1FROMMP(mp1) & KC_ALT) &&
469 (SHORT2FROMMP(mp2) == VK_END))
470 {
471#ifdef DEBUG_BUILD
472 printf(" Pressed ALT+END!\n"); fflush(stdout);
473#endif
474 // Close window, and get out of loop!
475 // Also send event to SDL application, but we won't
476 // wait for it to be processed!
477 SDL_PrivateQuit();
478 WinPostMsg(hwnd, WM_QUIT, 0, 0);
479 } else
480 {
481
482 SDL_PrivateKeyboard(SDL_PRESSED, TranslateKey(SHORT2FROMMP(mp2), // VK_ code
483 SHORT1FROMMP(mp2), // Character code
484 CHAR4FROMMP(mp1), // HW Scan code
485 &keysym,1));
486
487 }
488 }
489 }
490 return (MRESULT) TRUE;
491
492 case WM_TRANSLATEACCEL:
493 {
494 PQMSG pqmsg;
495 pqmsg = (PQMSG) mp1;
496 if (mp1)
497 {
498 if (pqmsg->msg == WM_CHAR)
499 {
500 // WM_CHAR message!
501 // Let's filter the ALT keypress and all other acceleration keys!
502 return (MRESULT) FALSE;
503 }
504 }
505 break; // Default processing (pass to parent until frame control)
506 }
507
508 case WM_PAINT: // Window redraw!
509#ifdef DEBUG_BUILD
510 printf("WM_PAINT (0x%x)\n", hwnd); fflush(stdout);
511#endif
512 ps = WinBeginPaint(hwnd,0,&rcl);
513 pVideo = FSLib_GetUserParm(hwnd);
514 if (pVideo)
515 {
516 if (!pVideo->hidden->pSDLSurface)
517 {
518 RECTL rclRect;
519 // So, don't blit now!
520#ifdef DEBUG_BUILD
521 printf("WM_PAINT : Skipping blit while resizing (Pre!)!\n"); fflush(stdout);
522#endif
523 WinQueryWindowRect(hwnd, &rclRect);
524 // Fill with black
525 WinFillRect(ps, &rclRect, CLR_BLACK);
526 } else
527 {
528 if (DosRequestMutexSem(pVideo->hidden->hmtxUseSrcBuffer, 1000)==NO_ERROR)
529 {
530 int iTop, iLeft, iWidth, iHeight;
531 int iXScaleError, iYScaleError;
532 int iXScaleError2, iYScaleError2;
533 SWP swp;
534
535 // Re-blit the modified area!
536 // For this, we have to calculate the points, scaled!
537 WinQueryWindowPos(hwnd, &swp);
538#ifdef DEBUG_BUILD
539 printf("WM_PAINT : WinSize: %d %d, BufSize: %d %d\n",
540 swp.cx,
541 swp.cy,
542 pVideo->hidden->SrcBufferDesc.uiXResolution,
543 pVideo->hidden->SrcBufferDesc.uiYResolution
544 );
545 fflush(stdout);
546#endif
547
548#ifndef RESIZE_EVEN_IF_RESIZABLE
549 // But only blit if the window is not resizable, or if
550 // the window is resizable and the source buffer size is the
551 // same as the destination buffer size!
552 if ((!pVideo->hidden->pSDLSurface) ||
553 ((pVideo->hidden->pSDLSurface) &&
554 (pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE) &&
555 ((swp.cx != pVideo->hidden->SrcBufferDesc.uiXResolution) ||
556 (swp.cy != pVideo->hidden->SrcBufferDesc.uiYResolution)
557 ) &&
558 (!FSLib_QueryFSMode(hwnd))
559 )
560 )
561 {
562 RECTL rclRect;
563 // Resizable surface and in resizing!
564 // So, don't blit now!
565#ifdef DEBUG_BUILD
566 printf("WM_PAINT : Skipping blit while resizing!\n"); fflush(stdout);
567#endif
568 WinQueryWindowRect(hwnd, &rclRect);
569 // Fill with black
570 WinFillRect(ps, &rclRect, CLR_BLACK);
571 } else
572#endif
573 {
574
575 iXScaleError = (pVideo->hidden->SrcBufferDesc.uiXResolution-1) / swp.cx;
576 iYScaleError = (pVideo->hidden->SrcBufferDesc.uiYResolution-1) / swp.cy;
577 if (iXScaleError<0) iXScaleError = 0;
578 if (iYScaleError<0) iYScaleError = 0;
579 iXScaleError2 = (swp.cx-1)/(pVideo->hidden->SrcBufferDesc.uiXResolution);
580 iYScaleError2 = (swp.cy-1)/(pVideo->hidden->SrcBufferDesc.uiYResolution);
581 if (iXScaleError2<0) iXScaleError2 = 0;
582 if (iYScaleError2<0) iYScaleError2 = 0;
583
584 iTop = (swp.cy - rcl.yTop) * pVideo->hidden->SrcBufferDesc.uiYResolution / swp.cy - iYScaleError;
585 iLeft = rcl.xLeft * pVideo->hidden->SrcBufferDesc.uiXResolution / swp.cx - iXScaleError;
586 iWidth = ((rcl.xRight-rcl.xLeft) * pVideo->hidden->SrcBufferDesc.uiXResolution + swp.cx-1)
587 / swp.cx + 2*iXScaleError;
588 iHeight = ((rcl.yTop-rcl.yBottom) * pVideo->hidden->SrcBufferDesc.uiYResolution + swp.cy-1)
589 / swp.cy + 2*iYScaleError;
590
591 iWidth+=iXScaleError2;
592 iHeight+=iYScaleError2;
593
594 if (iTop<0) iTop = 0;
595 if (iLeft<0) iLeft = 0;
596 if (iTop+iHeight>pVideo->hidden->SrcBufferDesc.uiYResolution) iHeight = pVideo->hidden->SrcBufferDesc.uiYResolution-iTop;
597 if (iLeft+iWidth>pVideo->hidden->SrcBufferDesc.uiXResolution) iWidth = pVideo->hidden->SrcBufferDesc.uiXResolution-iLeft;
598
599#ifdef DEBUG_BUILD
600 printf("WM_PAINT : BitBlt: %d %d -> %d %d (Buf %d x %d)\n",
601 iTop, iLeft, iWidth, iHeight,
602 pVideo->hidden->SrcBufferDesc.uiXResolution,
603 pVideo->hidden->SrcBufferDesc.uiYResolution
604 );
605 fflush(stdout);
606#endif
607
608 FSLIB_BITBLT(hwnd, pVideo->hidden->pchSrcBuffer, iTop, iLeft, iWidth, iHeight);
609 }
610
611 DosReleaseMutexSem(pVideo->hidden->hmtxUseSrcBuffer);
612 }
613 }
614 }
615#ifdef DEBUG_BUILD
616 else
617 {
618 printf("WM_PAINT : No pVideo!\n"); fflush(stdout);
619 }
620#endif
621 WinEndPaint(ps);
622#ifdef DEBUG_BUILD
623 printf("WM_PAINT : Done.\n");
624 fflush(stdout);
625#endif
626 return 0;
627
628 case WM_SIZE:
629 {
630#ifdef DEBUG_BUILD
631 printf("WM_SIZE : (%d %d)\n",
632 SHORT1FROMMP(mp2), SHORT2FROMMP(mp2)); fflush(stdout);
633#endif
634 iWindowSizeX = SHORT1FROMMP(mp2);
635 iWindowSizeY = SHORT2FROMMP(mp2);
636 bWindowResized = 1;
637
638 // Make sure the window will be redrawn
639 WinInvalidateRegion(hwnd, NULL, TRUE);
640 }
641 break;
642
643 case WM_FSLIBNOTIFICATION:
644#ifdef DEBUG_BUILD
645 printf("WM_FSLIBNOTIFICATION\n"); fflush(stdout);
646#endif
647 if ((int)mp1 == FSLN_TOGGLEFSMODE)
648 {
649 // FS mode changed, reblit image!
650 pVideo = FSLib_GetUserParm(hwnd);
651 if (pVideo)
652 {
653 if (!pVideo->hidden->pSDLSurface)
654 {
655 // Resizable surface and in resizing!
656 // So, don't blit now!
657#ifdef DEBUG_BUILD
658 printf("WM_FSLIBNOTIFICATION : Can not blit if there is no surface, doing nothing.\n"); fflush(stdout);
659#endif
660 } else
661 {
662 if (DosRequestMutexSem(pVideo->hidden->hmtxUseSrcBuffer, 1000)==NO_ERROR)
663 {
664 if (pVideo->hidden->pSDLSurface)
665 {
666#ifndef RESIZE_EVEN_IF_RESIZABLE
667 SWP swp;
668
669 // But only blit if the window is not resizable, or if
670 // the window is resizable and the source buffer size is the
671 // same as the destination buffer size!
672 WinQueryWindowPos(hwnd, &swp);
673 if ((!pVideo->hidden->pSDLSurface) ||
674 (
675 (pVideo->hidden->pSDLSurface) &&
676 (pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE) &&
677 ((swp.cx != pVideo->hidden->SrcBufferDesc.uiXResolution) ||
678 (swp.cy != pVideo->hidden->SrcBufferDesc.uiYResolution)
679 ) &&
680 (!FSLib_QueryFSMode(hwnd))
681 )
682 )
683 {
684 // Resizable surface and in resizing!
685 // So, don't blit now!
686#ifdef DEBUG_BUILD
687 printf("WM_FSLIBNOTIFICATION : Cannot blit while resizing, doing nothing.\n"); fflush(stdout);
688#endif
689 } else
690#endif
691 {
692#ifdef DEBUG_BUILD
693 printf("WM_FSLIBNOTIFICATION : Blitting!\n"); fflush(stdout);
694#endif
695 FSLIB_BITBLT(hwnd, pVideo->hidden->pchSrcBuffer,
696 0, 0,
697 pVideo->hidden->SrcBufferDesc.uiXResolution,
698 pVideo->hidden->SrcBufferDesc.uiYResolution);
699 }
700 }
701#ifdef DEBUG_BUILD
702 else
703 printf("WM_FSLIBNOTIFICATION : No public surface!\n"); fflush(stdout);
704#endif
705
706 DosReleaseMutexSem(pVideo->hidden->hmtxUseSrcBuffer);
707 }
708 }
709 }
710 }
711 return (MPARAM) 1;
712
713 case WM_ACTIVATE:
714#ifdef DEBUG_BUILD
715 printf("WM_ACTIVATE\n"); fflush(stdout);
716#endif
717
718 pVideo = FSLib_GetUserParm(hwnd);
719 if (pVideo)
720 {
721 pVideo->hidden->fInFocus = (int) mp1;
722 if (pVideo->hidden->fInFocus)
723 {
724 // Went into focus
725 if ((pVideo->hidden->iMouseVisible) && (!bMouseCaptured))
726 WinSetPointer(HWND_DESKTOP, WinQuerySysPointer(HWND_DESKTOP, SPTR_ARROW, FALSE));
727 else
728 WinSetPointer(HWND_DESKTOP, NULL);
729
730 if (bMouseCapturable)
731 {
732 // Re-capture the mouse, if we captured it before!
733 WinSetCapture(HWND_DESKTOP, hwnd);
734 bMouseCaptured = 1;
735 {
736 SWP swpClient;
737 POINTL ptl;
738 // Center the mouse to the middle of the window!
739 WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient);
740 ptl.x = 0; ptl.y = 0;
741 WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1);
742 pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */
743 WinSetPointerPos(HWND_DESKTOP,
744 ptl.x + swpClient.cx/2,
745 ptl.y + swpClient.cy/2);
746 }
747 }
748 } else
749 {
750 // Went out of focus
751 WinSetPointer(HWND_DESKTOP, WinQuerySysPointer(HWND_DESKTOP, SPTR_ARROW, FALSE));
752
753 if (bMouseCaptured)
754 {
755 // Release the mouse
756 WinSetCapture(HWND_DESKTOP, hwnd);
757 bMouseCaptured = 0;
758 }
759 }
760 }
761#ifdef DEBUG_BUILD
762 printf("WM_ACTIVATE done\n"); fflush(stdout);
763#endif
764
765 break;
766
767 case WM_BUTTON1DOWN:
768#ifdef DEBUG_BUILD
769 printf("WM_BUTTON1DOWN\n"); fflush(stdout);
770#endif
771
772 pVideo = FSLib_GetUserParm(hwnd);
773 if (pVideo)
774 {
775 SDL_PrivateMouseButton(SDL_PRESSED,
776 SDL_BUTTON_LEFT,
777 0, 0); // Don't report mouse movement!
778
779 if (bMouseCapturable)
780 {
781 // We should capture the mouse!
782 if (!bMouseCaptured)
783 {
784 WinSetCapture(HWND_DESKTOP, hwnd);
785 WinSetPointer(HWND_DESKTOP, NULL);
786 bMouseCaptured = 1;
787 {
788 SWP swpClient;
789 POINTL ptl;
790 // Center the mouse to the middle of the window!
791 WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient);
792 ptl.x = 0; ptl.y = 0;
793 WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1);
794 pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */
795 WinSetPointerPos(HWND_DESKTOP,
796 ptl.x + swpClient.cx/2,
797 ptl.y + swpClient.cy/2);
798 }
799 }
800 }
801 }
802 break;
803 case WM_BUTTON1UP:
804#ifdef DEBUG_BUILD
805 printf("WM_BUTTON1UP\n"); fflush(stdout);
806#endif
807 SDL_PrivateMouseButton(SDL_RELEASED,
808 SDL_BUTTON_LEFT,
809 0, 0); // Don't report mouse movement!
810 break;
811 case WM_BUTTON2DOWN:
812#ifdef DEBUG_BUILD
813 printf("WM_BUTTON2DOWN\n"); fflush(stdout);
814#endif
815
816 pVideo = FSLib_GetUserParm(hwnd);
817 if (pVideo)
818 {
819 SDL_PrivateMouseButton(SDL_PRESSED,
820 SDL_BUTTON_RIGHT,
821 0, 0); // Don't report mouse movement!
822
823 if (bMouseCapturable)
824 {
825 // We should capture the mouse!
826 if (!bMouseCaptured)
827 {
828 WinSetCapture(HWND_DESKTOP, hwnd);
829 WinSetPointer(HWND_DESKTOP, NULL);
830 bMouseCaptured = 1;
831 {
832 SWP swpClient;
833 POINTL ptl;
834 // Center the mouse to the middle of the window!
835 WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient);
836 ptl.x = 0; ptl.y = 0;
837 WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1);
838 pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */
839 WinSetPointerPos(HWND_DESKTOP,
840 ptl.x + swpClient.cx/2,
841 ptl.y + swpClient.cy/2);
842 }
843 }
844 }
845
846 }
847 break;
848 case WM_BUTTON2UP:
849#ifdef DEBUG_BUILD
850 printf("WM_BUTTON2UP\n"); fflush(stdout);
851#endif
852 SDL_PrivateMouseButton(SDL_RELEASED,
853 SDL_BUTTON_RIGHT,
854 0, 0); // Don't report mouse movement!
855 break;
856 case WM_BUTTON3DOWN:
857#ifdef DEBUG_BUILD
858 printf("WM_BUTTON3DOWN\n"); fflush(stdout);
859#endif
860
861 pVideo = FSLib_GetUserParm(hwnd);
862 if (pVideo)
863 {
864 SDL_PrivateMouseButton(SDL_PRESSED,
865 SDL_BUTTON_MIDDLE,
866 0, 0); // Don't report mouse movement!
867
868 if (bMouseCapturable)
869 {
870 // We should capture the mouse!
871 if (!bMouseCaptured)
872 {
873 WinSetCapture(HWND_DESKTOP, hwnd);
874 WinSetPointer(HWND_DESKTOP, NULL);
875 bMouseCaptured = 1;
876 {
877 SWP swpClient;
878 POINTL ptl;
879 // Center the mouse to the middle of the window!
880 WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient);
881 ptl.x = 0; ptl.y = 0;
882 WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1);
883 pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */
884 WinSetPointerPos(HWND_DESKTOP,
885 ptl.x + swpClient.cx/2,
886 ptl.y + swpClient.cy/2);
887 }
888 }
889 }
890 }
891 break;
892 case WM_BUTTON3UP:
893#ifdef DEBUG_BUILD
894 printf("WM_BUTTON3UP\n"); fflush(stdout);
895#endif
896 SDL_PrivateMouseButton(SDL_RELEASED,
897 SDL_BUTTON_MIDDLE,
898 0, 0); // Don't report mouse movement!
899 break;
900 case WM_MOUSEMOVE:
901#ifdef DEBUG_BUILD
902// printf("WM_MOUSEMOVE\n"); fflush(stdout);
903#endif
904
905 pVideo = FSLib_GetUserParm(hwnd);
906 if (pVideo)
907 {
908 if (pVideo->hidden->iSkipWMMOUSEMOVE)
909 {
910 pVideo->hidden->iSkipWMMOUSEMOVE--;
911 } else
912 {
913 POINTS *ppts = (POINTS *) (&mp1);
914 POINTL ptl;
915
916 if (bMouseCaptured)
917 {
918 SWP swpClient;
919
920 WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient);
921
922 // Send relative mouse position, and re-center the mouse
923 // Reposition the mouse to the center of the screen/window
924 SDL_PrivateMouseMotion(0, // Buttons not changed
925 1, // Relative position
926 ppts->x - (swpClient.cx/2),
927 (swpClient.cy/2) - ppts->y);
928
929 ptl.x = 0; ptl.y = 0;
930 WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1);
931 pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */
932 // Center the mouse to the middle of the window!
933 WinSetPointerPos(HWND_DESKTOP,
934 ptl.x + swpClient.cx/2,
935 ptl.y + swpClient.cy/2);
936 } else
937 {
938 CONVERTMOUSEPOSITION();
939
940 // Send absolute mouse position
941 SDL_PrivateMouseMotion(0, // Buttons not changed
942 0, // Absolute position
943 ppts->x,
944 ppts->y);
945 }
946 }
947 if ((pVideo->hidden->iMouseVisible) && (!bMouseCaptured))
948 {
949#ifdef DEBUG_BUILD
950// printf("WM_MOUSEMOVE : ptr = %p\n", hptrGlobalPointer); fflush(stdout);
951#endif
952
953 if (hptrGlobalPointer)
954 WinSetPointer(HWND_DESKTOP, hptrGlobalPointer);
955 else
956 WinSetPointer(HWND_DESKTOP, WinQuerySysPointer(HWND_DESKTOP, SPTR_ARROW, FALSE));
957 }
958 else
959 {
960 WinSetPointer(HWND_DESKTOP, NULL);
961 }
962 }
963#ifdef DEBUG_BUILD
964// printf("WM_MOUSEMOVE done\n"); fflush(stdout);
965#endif
966
967 return (MRESULT) FALSE;
968 case WM_CLOSE: // Window close
969#ifdef DEBUG_BUILD
970 printf("WM_CLOSE\n"); fflush(stdout);
971#endif
972
973 pVideo = FSLib_GetUserParm(hwnd);
974 if (pVideo)
975 {
976 // Send Quit message to the SDL application!
977 SDL_PrivateQuit();
978 return 0;
979 }
980 break;
981
982#ifdef BITBLT_IN_WINMESSAGEPROC
983 case WM_UPDATERECTSREQUEST:
984 pVideo = FSLib_GetUserParm(hwnd);
985 if ((pVideo) && (pVideo->hidden->pSDLSurface))
986 {
987 if (DosRequestMutexSem(pVideo->hidden->hmtxUseSrcBuffer, SEM_INDEFINITE_WAIT)==NO_ERROR)
988 {
989 int numrects;
990 SDL_Rect *rects;
991 int i;
992 SWP swp;
993
994 numrects = (int) mp1;
995 rects = (SDL_Rect *) mp2;
996
997 WinQueryWindowPos(hwnd, &swp);
998#ifndef RESIZE_EVEN_IF_RESIZABLE
999 if ((!pVideo->hidden->pSDLSurface) ||
1000 (
1001 (pVideo->hidden->pSDLSurface) &&
1002 (pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE) &&
1003 ((swp.cx != pVideo->hidden->SrcBufferDesc.uiXResolution) ||
1004 (swp.cy != pVideo->hidden->SrcBufferDesc.uiYResolution)
1005 ) &&
1006 (!FSLib_QueryFSMode(hwnd))
1007 )
1008 )
1009 {
1010 // Resizable surface and in resizing!
1011 // So, don't blit now!
1012#ifdef DEBUG_BUILD
1013 printf("[WM_UPDATERECTSREQUEST] : Skipping blit while resizing!\n"); fflush(stdout);
1014#endif
1015 } else
1016#endif
1017 {
1018#ifdef DEBUG_BUILD
1019 printf("[WM_UPDATERECTSREQUEST] : Blitting!\n"); fflush(stdout);
1020#endif
1021
1022 // Blit the changed areas
1023 for (i=0; i<numrects; i++)
1024 FSLIB_BITBLT(hwnd, pVideo->hidden->pchSrcBuffer,
1025 rects[i].y, rects[i].x, rects[i].w, rects[i].h);
1026 }
1027 DosReleaseMutexSem(pVideo->hidden->hmtxUseSrcBuffer);
1028 }
1029 }
1030 return 0;
1031#endif
1032
1033 default:
1034#ifdef DEBUG_BUILD
1035 printf("Unhandled: %x\n", msg); fflush(stdout);
1036#endif
1037
1038 break;
1039 }
1040 // Run the default window procedure for unhandled stuffs
1041 return WinDefWindowProc(hwnd, msg, mp1, mp2);
1042}
1043
1044/////////////////////////////////////////////////////////////////////
1045//
1046// FrameWndProc
1047//
1048// This is the message processing window procedure for the
1049// frame window of SDLWindowClass.
1050//
1051/////////////////////////////////////////////////////////////////////
1052static MRESULT EXPENTRY FrameWndProc( HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
1053{
1054 PFNWP pOldFrameProc;
1055 MRESULT result;
1056 PTRACKINFO ti;
1057 int cx, cy, ncx, ncy;
1058 RECTL rclTemp;
1059 PSWP pswpTemp;
1060
1061 SDL_VideoDevice *pVideo = NULL;
1062
1063 pVideo = (SDL_VideoDevice *) WinQueryWindowULong(hwnd, QWL_USER);
1064
1065 pOldFrameProc = pVideo->hidden->pfnOldFrameProc;
1066
1067 if ((pVideo->hidden->bProportionalResize) &&
1068 (msg==WM_ADJUSTWINDOWPOS) &&
1069 (!FSLib_QueryFSMode(pVideo->hidden->hwndClient))
1070 )
1071 {
1072 pswpTemp = (PSWP) mp1;
1073
1074 /* Resizing? */
1075 if (pswpTemp->fl & SWP_SIZE)
1076 {
1077 /* Calculate client size */
1078 rclTemp.xLeft = pswpTemp->x;
1079 rclTemp.xRight = pswpTemp->x + pswpTemp->cx;
1080 rclTemp.yBottom = pswpTemp->y;
1081 rclTemp.yTop = pswpTemp->y + pswpTemp->cy;
1082 WinCalcFrameRect(hwnd, &rclTemp, TRUE);
1083
1084 ncx = cx = rclTemp.xRight - rclTemp.xLeft;
1085 ncy = cy = rclTemp.yTop - rclTemp.yBottom;
1086
1087 /* Calculate new size to keep it proportional */
1088
1089 if ((pVideo->hidden->ulResizingFlag & TF_LEFT) || (pVideo->hidden->ulResizingFlag & TF_RIGHT))
1090 {
1091 /* The window is resized horizontally */
1092 ncy = pVideo->hidden->SrcBufferDesc.uiYResolution * cx / pVideo->hidden->SrcBufferDesc.uiXResolution;
1093 } else
1094 if ((pVideo->hidden->ulResizingFlag & TF_TOP) || (pVideo->hidden->ulResizingFlag & TF_BOTTOM))
1095 {
1096 /* The window is resized vertically */
1097 ncx = pVideo->hidden->SrcBufferDesc.uiXResolution * cy / pVideo->hidden->SrcBufferDesc.uiYResolution;
1098 }
1099
1100 /* Calculate back frame coordinates */
1101 rclTemp.xLeft = pswpTemp->x;
1102 rclTemp.xRight = pswpTemp->x + ncx;
1103 rclTemp.yBottom = pswpTemp->y;
1104 rclTemp.yTop = pswpTemp->y + ncy;
1105 WinCalcFrameRect(hwnd, &rclTemp, FALSE);
1106
1107 /* Store new size/position info */
1108 pswpTemp->cx = rclTemp.xRight - rclTemp.xLeft;
1109
1110 if (!(pVideo->hidden->ulResizingFlag & TF_TOP))
1111 {
1112 pswpTemp->y = pswpTemp->y + pswpTemp->cy - (rclTemp.yTop - rclTemp.yBottom);
1113 pswpTemp->cy = rclTemp.yTop - rclTemp.yBottom;
1114 } else
1115 {
1116 pswpTemp->cy = rclTemp.yTop - rclTemp.yBottom;
1117 }
1118 }
1119 }
1120
1121 result = (*pOldFrameProc)(hwnd, msg, mp1, mp2);
1122
1123 if ((pVideo->hidden->bProportionalResize) && (msg==WM_QUERYTRACKINFO))
1124 {
1125 ti = (PTRACKINFO) mp2;
1126
1127 /* Store the direction of resizing */
1128 if ((ti->fs & TF_LEFT) || (ti->fs & TF_RIGHT) ||
1129 (ti->fs & TF_TOP) || (ti->fs & TF_BOTTOM))
1130 pVideo->hidden->ulResizingFlag = ti->fs;
1131 }
1132
1133 return result;
1134}
1135
1136/////////////////////////////////////////////////////////////////////
1137//
1138// PMThreadFunc
1139//
1140// This function implements the PM-Thread, which initializes the
1141// application window itself, the DIVE, and start message processing.
1142//
1143/////////////////////////////////////////////////////////////////////
1144int iNumOfPMThreadInstances = 0; // Global!
1145static void PMThreadFunc(void *pParm)
1146{
1147 SDL_VideoDevice *pVideo = pParm;
1148 HAB hab;
1149 HMQ hmq;
1150 QMSG msg;
1151 ULONG fcf;
1152
1153#ifdef DEBUG_BUILD
1154 printf("[PMThreadFunc] : Starting\n"); fflush(stdout);
1155#endif
1156
1157 iNumOfPMThreadInstances++;
1158
1159 // Initialize PM, create a message queue.
1160
1161 hab=WinInitialize(0);
1162 hmq=WinCreateMsgQueue(hab,0);
1163 if (hmq==0)
1164 {
1165#ifdef DEBUG_BUILD
1166 printf("[PMThreadFunc] : Could not create message queue!\n");
1167 printf(" It might be that the application using SDL is not a PM app!\n");
1168 fflush(stdout);
1169#endif
1170 pVideo->hidden->iPMThreadStatus = 2;
1171 } else
1172 {
1173 int rc;
1174 RECTL rectl;
1175
1176 fcf = ulFCFToUse; // Get from global setting
1177
1178#ifdef DEBUG_BUILD
1179 printf("[PMThreadFunc] : FSLib_CreateWindow()!\n");
1180 fflush(stdout);
1181#endif
1182
1183 rc = FSLib_CreateWindow(HWND_DESKTOP, 0, &fcf,
1184 "SDL Application",
1185 NULLHANDLE, 0,
1186 &(pVideo->hidden->SrcBufferDesc),
1187 WndProc,
1188 &(pVideo->hidden->hwndClient),
1189 &(pVideo->hidden->hwndFrame));
1190
1191#ifdef DEBUG_BUILD
1192 printf("[PMThreadFunc] : FSLib_CreateWindow() rc = %d\n", rc);
1193 fflush(stdout);
1194#endif
1195
1196 if (!rc)
1197 {
1198#ifdef DEBUG_BUILD
1199 printf("[PMThreadFunc] : Could not create FSLib window!\n");
1200 fflush(stdout);
1201#endif
1202 pVideo->hidden->iPMThreadStatus = 3;
1203 } else
1204 {
1205#ifdef DEBUG_BUILD
1206 printf("[PMThreadFunc] : FSLib_AddUserParm()!\n");
1207 fflush(stdout);
1208#endif
1209
1210 // Store pVideo pointer in window data for client window, so
1211 // it will know the instance to which it belongs to.
1212 FSLib_AddUserParm(pVideo->hidden->hwndClient, pVideo);
1213
1214 // Now set default image width height and fourcc!
1215#ifdef DEBUG_BUILD
1216 printf("[PMThreadFunc] : SetWindowPos()!\n");
1217 fflush(stdout);
1218#endif
1219
1220 // Set the position and size of the main window,
1221 // and make it visible!
1222 // Calculate frame window size from client window size
1223 rectl.xLeft = 0;
1224 rectl.yBottom = 0;
1225 rectl.xRight = pVideo->hidden->SrcBufferDesc.uiXResolution; // Noninclusive
1226 rectl.yTop = pVideo->hidden->SrcBufferDesc.uiYResolution; // Noninclusive
1227 WinCalcFrameRect(pVideo->hidden->hwndFrame, &rectl, FALSE);
1228
1229 SetAccessableWindowPos(pVideo->hidden->hwndFrame,
1230 HWND_TOP,
1231 (WinQuerySysValue (HWND_DESKTOP, SV_CXSCREEN) - (rectl.xRight-rectl.xLeft)) / 2,
1232 (WinQuerySysValue (HWND_DESKTOP, SV_CYSCREEN) - (rectl.yTop-rectl.yBottom)) / 2,
1233 (rectl.xRight-rectl.xLeft),
1234 (rectl.yTop-rectl.yBottom),
1235 SWP_SIZE | SWP_ACTIVATE | SWP_SHOW | SWP_MOVE);
1236
1237 // Subclass frame procedure and store old window proc address
1238 pVideo->hidden->pfnOldFrameProc =
1239 WinSubclassWindow(pVideo->hidden->hwndFrame, FrameWndProc);
1240 WinSetWindowULong(pVideo->hidden->hwndFrame, QWL_USER, (ULONG) pVideo);
1241
1242#ifdef DEBUG_BUILD
1243 printf("[PMThreadFunc] : Entering message loop\n"); fflush(stdout);
1244#endif
1245 pVideo->hidden->iPMThreadStatus = 1;
1246
1247 while (WinGetMsg(hab, (PQMSG)&msg, 0, 0, 0))
1248 WinDispatchMsg(hab, (PQMSG) &msg);
1249
1250#ifdef DEBUG_BUILD
1251 printf("[PMThreadFunc] : Leaving message loop\n"); fflush(stdout);
1252#endif
1253 // We should release the captured the mouse!
1254 if (bMouseCaptured)
1255 {
1256 WinSetCapture(HWND_DESKTOP, NULLHANDLE);
1257 bMouseCaptured = 0;
1258 }
1259 // Destroy our window
1260 WinDestroyWindow(pVideo->hidden->hwndFrame); pVideo->hidden->hwndFrame=NULL;
1261 // Show pointer to make sure it will not be left hidden.
1262 WinSetPointer(HWND_DESKTOP, WinQuerySysPointer(HWND_DESKTOP, SPTR_ARROW, FALSE));
1263 WinShowPointer(HWND_DESKTOP, TRUE);
1264 }
1265 // Uninitialize PM
1266 WinDestroyMsgQueue(hmq);
1267 // All done!
1268 pVideo->hidden->iPMThreadStatus = 0;
1269 }
1270 WinTerminate(hab);
1271 /* Commented out, should not be needed anymore, because we send it
1272 from WM_CLOSE.
1273 // Notify SDL that it should really die now...
1274 SDL_PrivateQuit(); SDL_PrivateQuit(); SDL_PrivateQuit(); //... :))
1275 */
1276#ifdef DEBUG_BUILD
1277 printf("[PMThreadFunc] : End, status is %d!\n", pVideo->hidden->iPMThreadStatus); fflush(stdout);
1278#endif
1279
1280 iNumOfPMThreadInstances--;
1281
1282 // HACK to prevent zombie and hanging SDL applications, which does not take
1283 // care of closing the window for some reason:
1284 // There are some apps which do not process messages, so do a lot of things
1285 // without noticing that the application should close. To close these,
1286 // I've thought about the following:
1287 // If the window is closed (the execution came here), I wait a bit to
1288 // give time to the app to finish its execution. If it does not, I kill it
1289 // using DosExit(). Brute force, but should work.
1290 if (pVideo->hidden->iPMThreadStatus==0)
1291 {
1292 DosSleep(5000); // Wait 5 secs
1293 // If a new PM thread has been spawned (reinitializing video mode), then all right.
1294 // Otherwise, we have a problem, the app doesn't want to stop. Kill!
1295 if (iNumOfPMThreadInstances==0)
1296 {
1297#ifdef DEBUG_BUILD
1298 printf("[PMThreadFunc] : It seems that the application haven't terminated itself\n"); fflush(stdout);
1299 printf("[PMThreadFunc] : in the last 5 seconds, so we go berserk.\n"); fflush(stdout);
1300 printf("[PMThreadFunc] : Brute force mode. :) Killing process! Dieeeee...\n"); fflush(stdout);
1301#endif
1302 DosExit(EXIT_PROCESS, -1);
1303 }
1304 }
1305 _endthread();
1306}
1307
1308struct WMcursor
1309{
1310 HBITMAP hbm;
1311 HPOINTER hptr;
1312 char *pchData;
1313};
1314
1315/* Free a window manager cursor */
1316void os2fslib_FreeWMCursor(_THIS, WMcursor *cursor)
1317{
1318 if (cursor)
1319 {
1320 GpiDeleteBitmap(cursor->hbm);
1321 WinDestroyPointer(cursor->hptr);
1322 SDL_free(cursor->pchData);
1323 SDL_free(cursor);
1324 }
1325}
1326
1327/* Local functions to convert the SDL cursor mask into OS/2 format */
1328static void memnot(Uint8 *dst, Uint8 *src, int len)
1329{
1330 while ( len-- > 0 )
1331 *dst++ = ~*src++;
1332}
1333static void memxor(Uint8 *dst, Uint8 *src1, Uint8 *src2, int len)
1334{
1335 while ( len-- > 0 )
1336 *dst++ = (*src1++)^(*src2++);
1337}
1338
1339/* Create a black/white window manager cursor */
1340WMcursor *os2fslib_CreateWMCursor_Win(_THIS, Uint8 *data, Uint8 *mask,
1341 int w, int h, int hot_x, int hot_y)
1342{
1343 HPOINTER hptr;
1344 HBITMAP hbm;
1345 BITMAPINFOHEADER bmih;
1346 BMPINFO bmi;
1347 HPS hps;
1348 char *pchTemp;
1349 char *xptr, *aptr;
1350 int maxx, maxy;
1351 int i, run, pad;
1352 WMcursor *pResult;
1353
1354 maxx = WinQuerySysValue(HWND_DESKTOP, SV_CXPOINTER);
1355 maxy = WinQuerySysValue(HWND_DESKTOP, SV_CYPOINTER);
1356
1357 // Check for max size!
1358 if ((w>maxx) || (h>maxy))
1359 return (WMcursor *) NULL;
1360
1361 pResult = (WMcursor *) SDL_malloc(sizeof(WMcursor));
1362 if (!pResult) return (WMcursor *) NULL;
1363
1364 pchTemp = (char *) SDL_malloc((maxx + 7)/8 * maxy*2);
1365 if (!pchTemp)
1366 {
1367 SDL_free(pResult);
1368 return (WMcursor *) NULL;
1369 }
1370
1371 SDL_memset(pchTemp, 0, (maxx + 7)/8 * maxy*2);
1372
1373 hps = WinGetPS(_this->hidden->hwndClient);
1374
1375 bmi.cbFix = sizeof(BITMAPINFOHEADER);
1376 bmi.cx = maxx;
1377 bmi.cy = 2*maxy;
1378 bmi.cPlanes = 1;
1379 bmi.cBitCount = 1;
1380 bmi.argbColor[0].bBlue = 0x00;
1381 bmi.argbColor[0].bGreen = 0x00;
1382 bmi.argbColor[0].bRed = 0x00;
1383 bmi.argbColor[1].bBlue = 0x00;
1384 bmi.argbColor[1].bGreen = 0x00;
1385 bmi.argbColor[1].bRed = 0xff;
1386
1387 SDL_memset(&bmih, 0, sizeof(BITMAPINFOHEADER));
1388 bmih.cbFix = sizeof(BITMAPINFOHEADER);
1389 bmih.cx = maxx;
1390 bmih.cy = 2*maxy;
1391 bmih.cPlanes = 1;
1392 bmih.cBitCount = 1;
1393
1394 run = (w+7)/8;
1395 pad = (maxx+7)/8 - run;
1396
1397 for (i=0; i<h; i++)
1398 {
1399 xptr = pchTemp + (maxx+7)/8 * (maxy-1-i);
1400 aptr = pchTemp + (maxx+7)/8 * (maxy+maxy-1-i);
1401 memxor(xptr, data, mask, run);
1402 xptr += run;
1403 data += run;
1404 memnot(aptr, mask, run);
1405 mask += run;
1406 aptr += run;
1407 SDL_memset(xptr, 0, pad);
1408 xptr += pad;
1409 SDL_memset(aptr, ~0, pad);
1410 aptr += pad;
1411 }
1412 pad += run;
1413 for (i=h ; i<maxy; i++ )
1414 {
1415 xptr = pchTemp + (maxx+7)/8 * (maxy-1-i);
1416 aptr = pchTemp + (maxx+7)/8 * (maxy+maxy-1-i);
1417
1418 SDL_memset(xptr, 0, (maxx+7)/8);
1419 xptr += (maxx+7)/8;
1420 SDL_memset(aptr, ~0, (maxx+7)/8);
1421 aptr += (maxx+7)/8;
1422 }
1423
1424 hbm = GpiCreateBitmap(hps, (PBITMAPINFOHEADER2)&bmih, CBM_INIT, (PBYTE) pchTemp, (PBITMAPINFO2)&bmi);
1425 hptr = WinCreatePointer(HWND_DESKTOP, hbm, TRUE, hot_x, maxy - hot_y - 1);
1426
1427#ifdef DEBUG_BUILD
1428 printf("HotSpot : %d ; %d\n", hot_x, hot_y);
1429 printf("HPS returned : %x\n", (ULONG)hps);
1430 printf("HBITMAP returned : %x\n", (ULONG)hbm);
1431 printf("HPOINTER returned: %x\n", (ULONG)hptr);
1432#endif
1433
1434 WinReleasePS(hps);
1435
1436#ifdef DEBUG_BUILD
1437 printf("[CreateWMCursor] : ptr = %p\n", hptr); fflush(stdout);
1438#endif
1439
1440 pResult->hptr = hptr;
1441 pResult->hbm = hbm;
1442 pResult->pchData = pchTemp;
1443
1444#ifdef DEBUG_BUILD
1445 printf("[CreateWMCursor] : ptr = %p return.\n", hptr); fflush(stdout);
1446#endif
1447
1448 return (WMcursor *) pResult;
1449}
1450
1451WMcursor *os2fslib_CreateWMCursor_FS(_THIS, Uint8 *data, Uint8 *mask,
1452 int w, int h, int hot_x, int hot_y)
1453{
1454#ifdef DEBUG_BUILD
1455 printf("[CreateWMCursor_FS] : returning pointer NULL\n"); fflush(stdout);
1456#endif
1457
1458 // In FS mode we'll use software cursor
1459 return (WMcursor *) NULL;
1460}
1461
1462/* Show the specified cursor, or hide if cursor is NULL */
1463int os2fslib_ShowWMCursor(_THIS, WMcursor *cursor)
1464{
1465#ifdef DEBUG_BUILD
1466 printf("[ShowWMCursor] : ptr = %p\n", cursor); fflush(stdout);
1467#endif
1468
1469 if (cursor)
1470 {
1471 WinSetPointer(HWND_DESKTOP, cursor->hptr);
1472 hptrGlobalPointer = cursor->hptr;
1473 _this->hidden->iMouseVisible = 1;
1474 }
1475 else
1476 {
1477 WinSetPointer(HWND_DESKTOP, FALSE);
1478 hptrGlobalPointer = NULL;
1479 _this->hidden->iMouseVisible = 0;
1480 }
1481
1482#ifdef DEBUG_BUILD
1483 printf("[ShowWMCursor] : ptr = %p, DONE\n", cursor); fflush(stdout);
1484#endif
1485
1486 return 1;
1487}
1488
1489/* Warp the window manager cursor to (x,y)
1490 If NULL, a mouse motion event is posted internally.
1491 */
1492void os2fslib_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
1493{
1494 LONG lx, ly;
1495 SWP swpClient;
1496 POINTL ptlPoints;
1497 WinQueryWindowPos(_this->hidden->hwndClient, &swpClient);
1498 ptlPoints.x = swpClient.x;
1499 ptlPoints.y = swpClient.y;
1500 WinMapWindowPoints(_this->hidden->hwndFrame, HWND_DESKTOP, &ptlPoints, 1);
1501 lx = ptlPoints.x + (x*swpClient.cx) / _this->hidden->SrcBufferDesc.uiXResolution;
1502 ly = ptlPoints.y + swpClient.cy - ((y*swpClient.cy) / _this->hidden->SrcBufferDesc.uiYResolution) - 1;
1503
1504 SDL_PrivateMouseMotion(0, // Buttons not changed
1505 0, // Absolute position
1506 x,
1507 y);
1508
1509 WinSetPointerPos(HWND_DESKTOP, lx, ly);
1510
1511}
1512
1513/* If not NULL, this is called when a mouse motion event occurs */
1514void os2fslib_MoveWMCursor(_THIS, int x, int y)
1515{
1516 /*
1517 SDL_Rect rect;
1518
1519#ifdef DEBUG_BUILD
1520 printf("[MoveWMCursor] : at %d ; %d\n", x, y); fflush(stdout);
1521#endif
1522
1523 rect.x = x;
1524 rect.y = y;
1525 rect.w = 32;
1526 rect.h = 32;
1527 os2fslib_UpdateRects(_this, 1, &rect);
1528 // TODO!
1529 */
1530}
1531
1532/* Determine whether the mouse should be in relative mode or not.
1533 This function is called when the input grab state or cursor
1534 visibility state changes.
1535 If the cursor is not visible, and the input is grabbed, the
1536 driver can place the mouse in relative mode, which may result
1537 in higher accuracy sampling of the pointer motion.
1538 */
1539void os2fslib_CheckMouseMode(_THIS)
1540{
1541}
1542
1543static void os2fslib_PumpEvents(_THIS)
1544{
1545 // Notify SDL that if window has been resized!
1546 if (
1547 (_this->hidden->pSDLSurface) &&
1548 (_this->hidden->pSDLSurface->flags & SDL_RESIZABLE) &&
1549 (
1550 (_this->hidden->SrcBufferDesc.uiXResolution!=iWindowSizeX) ||
1551 (_this->hidden->SrcBufferDesc.uiYResolution!=iWindowSizeY)
1552 ) &&
1553 (iWindowSizeX>0) &&
1554 (iWindowSizeY>0)
1555 )
1556 {
1557 static time_t prev_time;
1558 time_t curr_time;
1559
1560 curr_time = time(NULL);
1561 if ((difftime(curr_time, prev_time)>=0.25) ||
1562 (bWindowResized))
1563 {
1564 // Make sure we won't flood the event queue with resize events,
1565 // only send them at 250 msecs!
1566 // (or when the window is resized)
1567#ifdef DEBUG_BUILD
1568 printf("[os2fslib_PumpEvents] : Calling PrivateResize (%d %d).\n",
1569 iWindowSizeX, iWindowSizeY);
1570 fflush(stdout);
1571#endif
1572 // Tell SDL the new size
1573 SDL_PrivateResize(iWindowSizeX, iWindowSizeY);
1574 prev_time = curr_time;
1575 bWindowResized = 0;
1576 }
1577 }
1578}
1579
1580/* We don't actually allow hardware surfaces other than the main one */
1581static int os2fslib_AllocHWSurface(_THIS, SDL_Surface *surface)
1582{
1583 return(-1);
1584}
1585static void os2fslib_FreeHWSurface(_THIS, SDL_Surface *surface)
1586{
1587 return;
1588}
1589
1590/* We need to wait for vertical retrace on page flipped displays */
1591static int os2fslib_LockHWSurface(_THIS, SDL_Surface *surface)
1592{
1593 return(0);
1594}
1595
1596static void os2fslib_UnlockHWSurface(_THIS, SDL_Surface *surface)
1597{
1598 return;
1599}
1600
1601static int os2fslib_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
1602{
1603 printf("[os2fslib_SetColors] : TODO!\n"); fflush(stdout);
1604 // TODO: Implement paletted modes
1605 return(1);
1606}
1607
1608static void os2fslib_DestroyIcon(HWND hwndFrame)
1609{
1610 if (hptrCurrentIcon)
1611 {
1612 WinDestroyPointer(hptrCurrentIcon);
1613 hptrCurrentIcon = NULL;
1614
1615 WinSendMsg(hwndFrame,
1616 WM_SETICON,
1617 NULL,
1618 NULL);
1619 }
1620
1621}
1622
1623/* Set the window icon image */
1624void os2fslib_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
1625{
1626 HWND hwndFrame;
1627 SDL_Surface *icon_rgb;
1628 HPOINTER hptrIcon;
1629 HBITMAP hbm;
1630 BITMAPINFOHEADER bmih;
1631 BMPINFO bmi;
1632 HPS hps;
1633 char *pchTemp;
1634 char *pptr, *mptr, *dptr, *dmptr;
1635 int maxx, maxy, w, h, x, y;
1636 SDL_Rect bounds;
1637
1638#ifdef DEBUG_BUILD
1639 printf("[os2fslib_SetIcon] : Creating and setting new icon\n"); fflush(stdout);
1640#endif
1641
1642 hwndFrame = WinQueryWindow(_this->hidden->hwndClient, QW_PARENT);
1643
1644 // Make sure the old icon resource will be free'd!
1645 os2fslib_DestroyIcon(hwndFrame);
1646
1647 if ((!icon) || (!mask))
1648 return;
1649
1650 w = icon->w;
1651 h = icon->h;
1652
1653 maxx = WinQuerySysValue(HWND_DESKTOP, SV_CXICON);
1654 maxy = WinQuerySysValue(HWND_DESKTOP, SV_CYICON);
1655
1656 // Check for max size!
1657 if ((w>maxx) || (h>maxy))
1658 return;
1659
1660 pchTemp = (char *) SDL_malloc(w * h*2 * 4);
1661 if (!pchTemp)
1662 return;
1663
1664 SDL_memset(pchTemp, 0, w * h*2 * 4);
1665
1666 // Convert surface to RGB, if it's not RGB yet!
1667 icon_rgb = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h,
1668 32, 0, 0, 0, 0);
1669 if ( icon_rgb == NULL )
1670 {
1671 SDL_free(pchTemp);
1672 return;
1673 }
1674 bounds.x = 0;
1675 bounds.y = 0;
1676 bounds.w = icon->w;
1677 bounds.h = icon->h;
1678 if ( SDL_LowerBlit(icon, &bounds, icon_rgb, &bounds) < 0 )
1679 {
1680 SDL_FreeSurface(icon_rgb);
1681 SDL_free(pchTemp);
1682 return;
1683 }
1684
1685 /* Copy pixels upside-down from RGB surface into BMP, masked with the icon mask */
1686
1687 // Pixels
1688 pptr = (char *) (icon_rgb->pixels);
1689 // Mask
1690 mptr = mask;
1691
1692 for (y=0; y<h; y++)
1693 {
1694 unsigned char uchMaskByte;
1695
1696 // Destination
1697 dptr = pchTemp + w*4 * (h-y-1);
1698 // Destination mask
1699 dmptr = pchTemp + w*h*4 + w*4 * (h-y-1);
1700
1701 for (x=0; x<w; x++)
1702 {
1703 if (x%8==0)
1704 {
1705 uchMaskByte = (unsigned char) (*mptr);
1706 mptr++;
1707 } else
1708 uchMaskByte <<= 1;
1709
1710 if (uchMaskByte & 0x80)
1711 {
1712 // Copy RGB
1713 *dptr++ = *pptr++;
1714 *dptr++ = *pptr++;
1715 *dptr++ = *pptr++;
1716 *dptr++ = *pptr++;
1717
1718 *dmptr++ = 0;
1719 *dmptr++ = 0;
1720 *dmptr++ = 0;
1721 *dmptr++ = 0;
1722 } else
1723 {
1724 // Set pixels to fully transparent
1725 *dptr++ = 0; pptr++;
1726 *dptr++ = 0; pptr++;
1727 *dptr++ = 0; pptr++;
1728 *dptr++ = 0; pptr++;
1729
1730 *dmptr++ = 255;
1731 *dmptr++ = 255;
1732 *dmptr++ = 255;
1733 *dmptr++ = 255;
1734 }
1735 }
1736 }
1737
1738 // There is no more need for the RGB surface
1739 SDL_FreeSurface(icon_rgb);
1740
1741 hps = WinGetPS(_this->hidden->hwndClient);
1742
1743 bmi.cbFix = sizeof(BITMAPINFOHEADER);
1744 bmi.cx = w;
1745 bmi.cy = 2*h;
1746 bmi.cPlanes = 1;
1747 bmi.cBitCount = 32;
1748
1749 SDL_memset(&bmih, 0, sizeof(BITMAPINFOHEADER));
1750 bmih.cbFix = sizeof(BITMAPINFOHEADER);
1751 bmih.cx = w;
1752 bmih.cy = 2*h;
1753 bmih.cPlanes = 1;
1754 bmih.cBitCount = 32;
1755
1756 hbm = GpiCreateBitmap(hps, (PBITMAPINFOHEADER2)&bmih, CBM_INIT, (PBYTE) pchTemp, (PBITMAPINFO2)&bmi);
1757 hptrIcon = WinCreatePointer(HWND_DESKTOP, hbm, FALSE, 0, 0);
1758
1759 WinReleasePS(hps);
1760
1761 // Free pixel array
1762 SDL_free(pchTemp);
1763
1764 // Change icon in frame window
1765 WinSendMsg(hwndFrame,
1766 WM_SETICON,
1767 (MPARAM) hptrIcon,
1768 NULL);
1769
1770 /*
1771 // Change icon in switchlist
1772 // Seems like it's not needed, the WM_SETICON already does it.
1773 {
1774 PID pidFrame;
1775 HSWITCH hswitchFrame;
1776 SWCNTRL swctl;
1777
1778 WinQueryWindowProcess(hwndFrame, &pidFrame, NULL);
1779 hswitchFrame = WinQuerySwitchHandle(hwndFrame, pidFrame);
1780 WinQuerySwitchEntry(hswitchFrame, &swctl);
1781
1782 swctl.hwndIcon = hptrIcon;
1783
1784 WinChangeSwitchEntry(hswitchFrame, &swctl);
1785 }
1786 */
1787
1788 // Store icon handle in global variable
1789 hptrCurrentIcon = hptrIcon;
1790}
1791
1792// ------------------------ REAL FUNCTIONS -----------------
1793
1794
1795static void os2fslib_SetCursorManagementFunctions(_THIS, int iForWindowedMode)
1796{
1797 if (iForWindowedMode)
1798 {
1799 _this->FreeWMCursor = os2fslib_FreeWMCursor;
1800 _this->CreateWMCursor = os2fslib_CreateWMCursor_Win;
1801 _this->ShowWMCursor = os2fslib_ShowWMCursor;
1802 _this->WarpWMCursor = os2fslib_WarpWMCursor;
1803 _this->MoveWMCursor = os2fslib_MoveWMCursor;
1804 _this->CheckMouseMode = NULL;//os2fslib_CheckMouseMode;
1805 } else
1806 {
1807 // We'll have software mouse cursor in FS mode!
1808 _this->FreeWMCursor = os2fslib_FreeWMCursor;
1809 _this->CreateWMCursor = os2fslib_CreateWMCursor_FS;
1810 _this->ShowWMCursor = os2fslib_ShowWMCursor;
1811 _this->WarpWMCursor = os2fslib_WarpWMCursor;
1812 _this->MoveWMCursor = os2fslib_MoveWMCursor;
1813 _this->CheckMouseMode = NULL;//os2fslib_CheckMouseMode;
1814 }
1815}
1816
1817static void os2fslib_InitOSKeymap(_THIS)
1818{
1819 int i;
1820
1821 iShiftIsPressed = 0;
1822
1823 /* Map the VK and CH keysyms */
1824 for ( i=0; i<=255; ++i )
1825 HWScanKeyMap[i] = SDLK_UNKNOWN;
1826
1827 // First line of keyboard:
1828 HWScanKeyMap[0x1] = SDLK_ESCAPE;
1829 HWScanKeyMap[0x3b] = SDLK_F1;
1830 HWScanKeyMap[0x3c] = SDLK_F2;
1831 HWScanKeyMap[0x3d] = SDLK_F3;
1832 HWScanKeyMap[0x3e] = SDLK_F4;
1833 HWScanKeyMap[0x3f] = SDLK_F5;
1834 HWScanKeyMap[0x40] = SDLK_F6;
1835 HWScanKeyMap[0x41] = SDLK_F7;
1836 HWScanKeyMap[0x42] = SDLK_F8;
1837 HWScanKeyMap[0x43] = SDLK_F9;
1838 HWScanKeyMap[0x44] = SDLK_F10;
1839 HWScanKeyMap[0x57] = SDLK_F11;
1840 HWScanKeyMap[0x58] = SDLK_F12;
1841 HWScanKeyMap[0x5d] = SDLK_PRINT;
1842 HWScanKeyMap[0x46] = SDLK_SCROLLOCK;
1843 HWScanKeyMap[0x5f] = SDLK_PAUSE;
1844
1845 // Second line of keyboard:
1846 HWScanKeyMap[0x29] = SDLK_BACKQUOTE;
1847 HWScanKeyMap[0x2] = SDLK_1;
1848 HWScanKeyMap[0x3] = SDLK_2;
1849 HWScanKeyMap[0x4] = SDLK_3;
1850 HWScanKeyMap[0x5] = SDLK_4;
1851 HWScanKeyMap[0x6] = SDLK_5;
1852 HWScanKeyMap[0x7] = SDLK_6;
1853 HWScanKeyMap[0x8] = SDLK_7;
1854 HWScanKeyMap[0x9] = SDLK_8;
1855 HWScanKeyMap[0xa] = SDLK_9;
1856 HWScanKeyMap[0xb] = SDLK_0;
1857 HWScanKeyMap[0xc] = SDLK_MINUS;
1858 HWScanKeyMap[0xd] = SDLK_EQUALS;
1859 HWScanKeyMap[0xe] = SDLK_BACKSPACE;
1860 HWScanKeyMap[0x68] = SDLK_INSERT;
1861 HWScanKeyMap[0x60] = SDLK_HOME;
1862 HWScanKeyMap[0x62] = SDLK_PAGEUP;
1863 HWScanKeyMap[0x45] = SDLK_NUMLOCK;
1864 HWScanKeyMap[0x5c] = SDLK_KP_DIVIDE;
1865 HWScanKeyMap[0x37] = SDLK_KP_MULTIPLY;
1866 HWScanKeyMap[0x4a] = SDLK_KP_MINUS;
1867
1868 // Third line of keyboard:
1869 HWScanKeyMap[0xf] = SDLK_TAB;
1870 HWScanKeyMap[0x10] = SDLK_q;
1871 HWScanKeyMap[0x11] = SDLK_w;
1872 HWScanKeyMap[0x12] = SDLK_e;
1873 HWScanKeyMap[0x13] = SDLK_r;
1874 HWScanKeyMap[0x14] = SDLK_t;
1875 HWScanKeyMap[0x15] = SDLK_y;
1876 HWScanKeyMap[0x16] = SDLK_u;
1877 HWScanKeyMap[0x17] = SDLK_i;
1878 HWScanKeyMap[0x18] = SDLK_o;
1879 HWScanKeyMap[0x19] = SDLK_p;
1880 HWScanKeyMap[0x1a] = SDLK_LEFTBRACKET;
1881 HWScanKeyMap[0x1b] = SDLK_RIGHTBRACKET;
1882 HWScanKeyMap[0x1c] = SDLK_RETURN;
1883 HWScanKeyMap[0x69] = SDLK_DELETE;
1884 HWScanKeyMap[0x65] = SDLK_END;
1885 HWScanKeyMap[0x67] = SDLK_PAGEDOWN;
1886 HWScanKeyMap[0x47] = SDLK_KP7;
1887 HWScanKeyMap[0x48] = SDLK_KP8;
1888 HWScanKeyMap[0x49] = SDLK_KP9;
1889 HWScanKeyMap[0x4e] = SDLK_KP_PLUS;
1890
1891 // Fourth line of keyboard:
1892 HWScanKeyMap[0x3a] = SDLK_CAPSLOCK;
1893 HWScanKeyMap[0x1e] = SDLK_a;
1894 HWScanKeyMap[0x1f] = SDLK_s;
1895 HWScanKeyMap[0x20] = SDLK_d;
1896 HWScanKeyMap[0x21] = SDLK_f;
1897 HWScanKeyMap[0x22] = SDLK_g;
1898 HWScanKeyMap[0x23] = SDLK_h;
1899 HWScanKeyMap[0x24] = SDLK_j;
1900 HWScanKeyMap[0x25] = SDLK_k;
1901 HWScanKeyMap[0x26] = SDLK_l;
1902 HWScanKeyMap[0x27] = SDLK_SEMICOLON;
1903 HWScanKeyMap[0x28] = SDLK_QUOTE;
1904 HWScanKeyMap[0x2b] = SDLK_BACKSLASH;
1905 HWScanKeyMap[0x4b] = SDLK_KP4;
1906 HWScanKeyMap[0x4c] = SDLK_KP5;
1907 HWScanKeyMap[0x4d] = SDLK_KP6;
1908
1909 // Fifth line of keyboard:
1910 HWScanKeyMap[0x2a] = SDLK_LSHIFT;
1911 HWScanKeyMap[0x56] = SDLK_WORLD_1; // Code 161, letter i' on hungarian keyboard
1912 HWScanKeyMap[0x2c] = SDLK_z;
1913 HWScanKeyMap[0x2d] = SDLK_x;
1914 HWScanKeyMap[0x2e] = SDLK_c;
1915 HWScanKeyMap[0x2f] = SDLK_v;
1916 HWScanKeyMap[0x30] = SDLK_b;
1917 HWScanKeyMap[0x31] = SDLK_n;
1918 HWScanKeyMap[0x32] = SDLK_m;
1919 HWScanKeyMap[0x33] = SDLK_COMMA;
1920 HWScanKeyMap[0x34] = SDLK_PERIOD;
1921 HWScanKeyMap[0x35] = SDLK_SLASH;
1922 HWScanKeyMap[0x36] = SDLK_RSHIFT;
1923 HWScanKeyMap[0x61] = SDLK_UP;
1924 HWScanKeyMap[0x4f] = SDLK_KP1;
1925 HWScanKeyMap[0x50] = SDLK_KP2;
1926 HWScanKeyMap[0x51] = SDLK_KP3;
1927 HWScanKeyMap[0x5a] = SDLK_KP_ENTER;
1928
1929 // Sixth line of keyboard:
1930 HWScanKeyMap[0x1d] = SDLK_LCTRL;
1931 HWScanKeyMap[0x7e] = SDLK_LSUPER; // Windows key
1932 HWScanKeyMap[0x38] = SDLK_LALT;
1933 HWScanKeyMap[0x39] = SDLK_SPACE;
1934 HWScanKeyMap[0x5e] = SDLK_RALT;// Actually, altgr on my keyboard...
1935 HWScanKeyMap[0x7f] = SDLK_RSUPER;
1936 HWScanKeyMap[0x7c] = SDLK_MENU;
1937 HWScanKeyMap[0x5b] = SDLK_RCTRL;
1938 HWScanKeyMap[0x63] = SDLK_LEFT;
1939 HWScanKeyMap[0x66] = SDLK_DOWN;
1940 HWScanKeyMap[0x64] = SDLK_RIGHT;
1941 HWScanKeyMap[0x52] = SDLK_KP0;
1942 HWScanKeyMap[0x53] = SDLK_KP_PERIOD;
1943}
1944
1945
1946/* Iconify the window.
1947 This function returns 1 if there is a window manager and the
1948 window was actually iconified, it returns 0 otherwise.
1949 */
1950int os2fslib_IconifyWindow(_THIS)
1951{
1952 HAB hab;
1953 HMQ hmq;
1954 ERRORID hmqerror;
1955
1956 // If there is no more window, nothing we can do!
1957 if (_this->hidden->iPMThreadStatus!=1) return 0;
1958
1959 // Cannot do anything in fullscreen mode!
1960 if (FSLib_QueryFSMode(_this->hidden->hwndClient))
1961 return 0;
1962
1963 // Make sure this thread is prepared for using the Presentation Manager!
1964 hab = WinInitialize(0);
1965 hmq = WinCreateMsgQueue(hab,0);
1966 // Remember if there was an error at WinCreateMsgQueue(), because we don't
1967 // want to destroy somebody else's queue later. :)
1968 hmqerror = WinGetLastError(hab);
1969
1970 WinSetWindowPos(_this->hidden->hwndFrame, HWND_TOP,
1971 0, 0, 0, 0, SWP_MINIMIZE);
1972
1973 // Now destroy the message queue, if we've created it!
1974 if (ERRORIDERROR(hmqerror)==0)
1975 WinDestroyMsgQueue(hmq);
1976
1977 return 1;
1978}
1979
1980static SDL_GrabMode os2fslib_GrabInput(_THIS, SDL_GrabMode mode)
1981{
1982 HAB hab;
1983 HMQ hmq;
1984 ERRORID hmqerror;
1985
1986
1987 // If there is no more window, nothing we can do!
1988 if (_this->hidden->iPMThreadStatus!=1)
1989 return SDL_GRAB_OFF;
1990
1991 // Make sure this thread is prepared for using the Presentation Manager!
1992 hab = WinInitialize(0);
1993 hmq = WinCreateMsgQueue(hab,0);
1994 // Remember if there was an error at WinCreateMsgQueue(), because we don't
1995 // want to destroy somebody else's queue later. :)
1996 hmqerror = WinGetLastError(hab);
1997
1998
1999 if (mode == SDL_GRAB_OFF)
2000 {
2001#ifdef DEBUG_BUILD
2002 printf("[os2fslib_GrabInput] : Releasing mouse\n"); fflush(stdout);
2003#endif
2004
2005 // Release the mouse
2006 bMouseCapturable = 0;
2007 if (bMouseCaptured)
2008 {
2009 WinSetCapture(HWND_DESKTOP, NULLHANDLE);
2010 bMouseCaptured = 0;
2011 }
2012 } else
2013 {
2014#ifdef DEBUG_BUILD
2015 printf("[os2fslib_GrabInput] : Capturing mouse\n"); fflush(stdout);
2016#endif
2017
2018 // Capture the mouse
2019 bMouseCapturable = 1;
2020 if (WinQueryFocus(HWND_DESKTOP) == _this->hidden->hwndClient)
2021 {
2022 WinSetCapture(HWND_DESKTOP, _this->hidden->hwndClient);
2023 bMouseCaptured = 1;
2024 {
2025 SWP swpClient;
2026 POINTL ptl;
2027 // Center the mouse to the middle of the window!
2028 WinQueryWindowPos(_this->hidden->hwndClient, &swpClient);
2029 ptl.x = 0; ptl.y = 0;
2030 WinMapWindowPoints(_this->hidden->hwndClient, HWND_DESKTOP, &ptl, 1);
2031 _this->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */
2032 WinSetPointerPos(HWND_DESKTOP,
2033 ptl.x + swpClient.cx/2,
2034 ptl.y + swpClient.cy/2);
2035 }
2036 }
2037 }
2038
2039 // Now destroy the message queue, if we've created it!
2040 if (ERRORIDERROR(hmqerror)==0)
2041 WinDestroyMsgQueue(hmq);
2042
2043 return mode;
2044}
2045
2046/* Set the title and icon text */
2047static void os2fslib_SetCaption(_THIS, const char *title, const char *icon)
2048{
2049 HAB hab;
2050 HMQ hmq;
2051 ERRORID hmqerror;
2052
2053 // If there is no more window, nothing we can do!
2054 if (_this->hidden->iPMThreadStatus!=1) return;
2055
2056 // Make sure this thread is prepared for using the Presentation Manager!
2057 hab = WinInitialize(0);
2058 hmq = WinCreateMsgQueue(hab,0);
2059 // Remember if there was an error at WinCreateMsgQueue(), because we don't
2060 // want to destroy somebody else's queue later. :)
2061 hmqerror = WinGetLastError(hab);
2062
2063 WinSetWindowText(_this->hidden->hwndFrame, (char *) title);
2064
2065 // Now destroy the message queue, if we've created it!
2066 if (ERRORIDERROR(hmqerror)==0)
2067 WinDestroyMsgQueue(hmq);
2068}
2069
2070static int os2fslib_ToggleFullScreen(_THIS, int on)
2071{
2072#ifdef DEBUG_BUILD
2073 printf("[os2fslib_ToggleFullScreen] : %d\n", on); fflush(stdout);
2074#endif
2075 // If there is no more window, nothing we can do!
2076 if (_this->hidden->iPMThreadStatus!=1) return 0;
2077
2078 FSLib_ToggleFSMode(_this->hidden->hwndClient, on);
2079 /* Cursor manager functions to Windowed/FS mode*/
2080 os2fslib_SetCursorManagementFunctions(_this, !on);
2081 return 1;
2082}
2083
2084/* This is called after the video mode has been set, to get the
2085 initial mouse state. It should queue events as necessary to
2086 properly represent the current mouse focus and position.
2087 */
2088static void os2fslib_UpdateMouse(_THIS)
2089{
2090 POINTL ptl;
2091 HAB hab;
2092 HMQ hmq;
2093 ERRORID hmqerror;
2094 SWP swpClient;
2095
2096 // If there is no more window, nothing we can do!
2097 if (_this->hidden->iPMThreadStatus!=1) return;
2098
2099
2100 // Make sure this thread is prepared for using the Presentation Manager!
2101 hab = WinInitialize(0);
2102 hmq = WinCreateMsgQueue(hab,0);
2103 // Remember if there was an error at WinCreateMsgQueue(), because we don't
2104 // want to destroy somebody else's queue later. :)
2105 hmqerror = WinGetLastError(hab);
2106
2107
2108
2109 if (_this->hidden->fInFocus)
2110 {
2111 // If our app is in focus
2112 SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
2113 SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS);
2114 SDL_PrivateAppActive(1, SDL_APPACTIVE);
2115 WinQueryPointerPos(HWND_DESKTOP, &ptl);
2116 WinMapWindowPoints(HWND_DESKTOP, _this->hidden->hwndClient, &ptl, 1);
2117 WinQueryWindowPos(_this->hidden->hwndClient, &swpClient);
2118 // Convert OS/2 mouse position to SDL position, and also scale it!
2119 ptl.x = ptl.x * _this->hidden->SrcBufferDesc.uiXResolution / swpClient.cx;
2120 ptl.y = ptl.y * _this->hidden->SrcBufferDesc.uiYResolution / swpClient.cy;
2121 ptl.y = _this->hidden->SrcBufferDesc.uiYResolution - ptl.y - 1;
2122 SDL_PrivateMouseMotion(0, 0, (Sint16) (ptl.x), (Sint16) (ptl.y));
2123 } else
2124 {
2125 // If we're not in focus
2126 SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
2127 SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS);
2128 SDL_PrivateAppActive(0, SDL_APPACTIVE);
2129 SDL_PrivateMouseMotion(0, 0, (Sint16) -1, (Sint16) -1);
2130 }
2131
2132 // Now destroy the message queue, if we've created it!
2133 if (ERRORIDERROR(hmqerror)==0)
2134 WinDestroyMsgQueue(hmq);
2135
2136}
2137
2138/* This pointer should exist in the native video subsystem and should
2139 point to an appropriate update function for the current video mode
2140 */
2141static void os2fslib_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
2142{
2143 // If there is no more window, nothing we can do!
2144 if (_this->hidden->iPMThreadStatus!=1) return;
2145
2146#ifdef BITBLT_IN_WINMESSAGEPROC
2147 WinSendMsg(_this->hidden->hwndClient,
2148 WM_UPDATERECTSREQUEST,
2149 (MPARAM) numrects,
2150 (MPARAM) rects);
2151#else
2152 if (DosRequestMutexSem(_this->hidden->hmtxUseSrcBuffer, SEM_INDEFINITE_WAIT)==NO_ERROR)
2153 {
2154 int i;
2155
2156 if (_this->hidden->pSDLSurface)
2157 {
2158#ifndef RESIZE_EVEN_IF_RESIZABLE
2159 SWP swp;
2160 // But only blit if the window is not resizable, or if
2161 // the window is resizable and the source buffer size is the
2162 // same as the destination buffer size!
2163 WinQueryWindowPos(_this->hidden->hwndClient, &swp);
2164 if ((_this->hidden->pSDLSurface) &&
2165 (_this->hidden->pSDLSurface->flags & SDL_RESIZABLE) &&
2166 ((swp.cx != _this->hidden->SrcBufferDesc.uiXResolution) ||
2167 (swp.cy != _this->hidden->SrcBufferDesc.uiYResolution)
2168 ) &&
2169 (!FSLib_QueryFSMode(_this->hidden->hwndClient))
2170 )
2171 {
2172 // Resizable surface and in resizing!
2173 // So, don't blit now!
2174#ifdef DEBUG_BUILD
2175 printf("[UpdateRects] : Skipping blit while resizing!\n"); fflush(stdout);
2176#endif
2177 } else
2178#endif
2179 {
2180 /*
2181 // Blit the whole window
2182 FSLIB_BITBLT(_this->hidden->hwndClient, _this->hidden->pchSrcBuffer,
2183 0, 0,
2184 _this->hidden->SrcBufferDesc.uiXResolution,
2185 _this->hidden->SrcBufferDesc.uiYResolution);
2186 */
2187#ifdef DEBUG_BUILD
2188 printf("[os2fslib_UpdateRects] : Blitting!\n"); fflush(stdout);
2189#endif
2190
2191 // Blit the changed areas
2192 for (i=0; i<numrects; i++)
2193 FSLIB_BITBLT(_this->hidden->hwndClient, _this->hidden->pchSrcBuffer,
2194 rects[i].y, rects[i].x, rects[i].w, rects[i].h);
2195 }
2196 }
2197#ifdef DEBUG_BUILD
2198 else
2199 printf("[os2fslib_UpdateRects] : No public surface!\n"); fflush(stdout);
2200#endif
2201 DosReleaseMutexSem(_this->hidden->hmtxUseSrcBuffer);
2202 }
2203#ifdef DEBUG_BUILD
2204 else
2205 printf("[os2fslib_UpdateRects] : Error in mutex!\n"); fflush(stdout);
2206#endif
2207#endif
2208}
2209
2210
2211/* Reverse the effects VideoInit() -- called if VideoInit() fails
2212 or if the application is shutting down the video subsystem.
2213 */
2214static void os2fslib_VideoQuit(_THIS)
2215{
2216#ifdef DEBUG_BUILD
2217 printf("[os2fslib_VideoQuit]\n"); fflush(stdout);
2218#endif
2219 // Close PM stuff if running!
2220 if (_this->hidden->iPMThreadStatus == 1)
2221 {
2222 int iTimeout;
2223 WinPostMsg(_this->hidden->hwndFrame, WM_QUIT, (MPARAM) 0, (MPARAM) 0);
2224 // HACK: We had this line before:
2225 //DosWaitThread((TID *) &(_this->hidden->tidPMThread), DCWW_WAIT);
2226 // We don't use it, because the PMThread will never stop, or if it stops,
2227 // it will kill the whole process as a emergency fallback.
2228 // So, we only check for the iPMThreadStatus stuff!
2229#ifdef DEBUG_BUILD
2230 printf("[os2fslib_VideoQuit] : Waiting for PM thread to die\n"); fflush(stdout);
2231#endif
2232
2233 iTimeout=0;
2234 while ((_this->hidden->iPMThreadStatus == 1) && (iTimeout<100))
2235 {
2236 iTimeout++;
2237 DosSleep(64);
2238 }
2239
2240#ifdef DEBUG_BUILD
2241 printf("[os2fslib_VideoQuit] : End of wait.\n"); fflush(stdout);
2242#endif
2243
2244 if (_this->hidden->iPMThreadStatus == 1)
2245 {
2246#ifdef DEBUG_BUILD
2247 printf("[os2fslib_VideoQuit] : Killing PM thread!\n"); fflush(stdout);
2248#endif
2249
2250 _this->hidden->iPMThreadStatus = 0;
2251 DosKillThread(_this->hidden->tidPMThread);
2252
2253 if (_this->hidden->hwndFrame)
2254 {
2255#ifdef DEBUG_BUILD
2256 printf("[os2fslib_VideoQuit] : Destroying PM window!\n"); fflush(stdout);
2257#endif
2258
2259 WinDestroyWindow(_this->hidden->hwndFrame); _this->hidden->hwndFrame=NULL;
2260 }
2261 }
2262
2263 }
2264
2265 // Free result of an old ListModes() call, because there is
2266 // no FreeListModes() call in SDL!
2267 if (_this->hidden->pListModesResult)
2268 {
2269 SDL_free(_this->hidden->pListModesResult); _this->hidden->pListModesResult = NULL;
2270 }
2271
2272 // Free list of available fullscreen modes
2273 if (_this->hidden->pAvailableFSLibVideoModes)
2274 {
2275 FSLib_FreeVideoModeList(_this->hidden->pAvailableFSLibVideoModes);
2276 _this->hidden->pAvailableFSLibVideoModes = NULL;
2277 }
2278
2279 // Free application icon if we had one
2280 if (hptrCurrentIcon)
2281 {
2282 WinDestroyPointer(hptrCurrentIcon);
2283 hptrCurrentIcon = NULL;
2284 }
2285}
2286
2287/* Set the requested video mode, returning a surface which will be
2288 set to the SDL_VideoSurface. The width and height will already
2289 be verified by ListModes(), and the video subsystem is free to
2290 set the mode to a supported bit depth different from the one
2291 specified -- the desired bpp will be emulated with a shadow
2292 surface if necessary. If a new mode is returned, this function
2293 should take care of cleaning up the current mode.
2294 */
2295static SDL_Surface *os2fslib_SetVideoMode(_THIS, SDL_Surface *current,
2296 int width, int height, int bpp, Uint32 flags)
2297{
2298 static int bFirstCall = 1;
2299 FSLib_VideoMode_p pModeInfo, pModeInfoFound;
2300 FSLib_VideoMode TempModeInfo;
2301 HAB hab;
2302 HMQ hmq;
2303 ERRORID hmqerror;
2304 RECTL rectl;
2305 SDL_Surface *pResult;
2306
2307 // If there is no more window, nothing we can do!
2308 if (_this->hidden->iPMThreadStatus!=1) return NULL;
2309
2310#ifdef DEBUG_BUILD
2311 printf("[os2fslib_SetVideoMode] : Request for %dx%d @ %dBPP, flags=0x%x\n", width, height, bpp, flags); fflush(stdout);
2312#endif
2313
2314 // We don't support palette modes!
2315 if (bpp==8) bpp=32;
2316
2317 // Also, we don't support resizable modes in fullscreen mode.
2318 if (flags & SDL_RESIZABLE)
2319 flags &= ~SDL_FULLSCREEN;
2320
2321 // No double buffered mode
2322 if (flags & SDL_DOUBLEBUF)
2323 flags &= ~SDL_DOUBLEBUF;
2324
2325 // And, we don't support HWSURFACE yet.
2326 if (flags & SDL_HWSURFACE)
2327 {
2328 flags &= ~SDL_HWSURFACE;
2329 flags |= SDL_SWSURFACE;
2330 }
2331
2332#ifdef DEBUG_BUILD
2333 printf("[os2fslib_SetVideoMode] : Changed request to %dx%d @ %dBPP, flags=0x%x\n", width, height, bpp, flags); fflush(stdout);
2334#endif
2335
2336 // First check if there is such a video mode they want!
2337 pModeInfoFound = NULL;
2338
2339 // For fullscreen mode we don't support every resolution!
2340 // So, go through the video modes, and check for such a resolution!
2341 pModeInfoFound = NULL;
2342 pModeInfo = _this->hidden->pAvailableFSLibVideoModes;
2343
2344 while (pModeInfo)
2345 {
2346 // Check all available fullscreen modes for this resolution
2347 if ((pModeInfo->uiXResolution == width) &&
2348 (pModeInfo->uiYResolution == height) &&
2349 (pModeInfo->uiBPP!=8)) // palettized modes not yet supported
2350 {
2351 // If good resolution, try to find the exact BPP, or at least
2352 // something similar...
2353 if (!pModeInfoFound)
2354 pModeInfoFound = pModeInfo;
2355 else
2356 if ((pModeInfoFound->uiBPP!=bpp) &&
2357 (pModeInfoFound->uiBPP<pModeInfo->uiBPP))
2358 pModeInfoFound = pModeInfo;
2359 }
2360 pModeInfo = pModeInfo->pNext;
2361 }
2362
2363 // If we did not find a good fullscreen mode, then try a similar
2364 if (!pModeInfoFound)
2365 {
2366#ifdef DEBUG_BUILD
2367 printf("[os2fslib_SetVideoMode] : Requested video mode not found, looking for a similar one!\n"); fflush(stdout);
2368#endif
2369 // Go through the video modes again, and find a similar resolution!
2370 pModeInfo = _this->hidden->pAvailableFSLibVideoModes;
2371 while (pModeInfo)
2372 {
2373 // Check all available fullscreen modes for this resolution
2374 if ((pModeInfo->uiXResolution >= width) &&
2375 (pModeInfo->uiYResolution >= height) &&
2376 (pModeInfo->uiBPP == bpp))
2377 {
2378 if (!pModeInfoFound)
2379 pModeInfoFound = pModeInfo;
2380 else
2381 if (((pModeInfoFound->uiXResolution-width)*(pModeInfoFound->uiYResolution-height))>
2382 ((pModeInfo->uiXResolution-width)*(pModeInfo->uiYResolution-height)))
2383 {
2384 // Found a mode which is closer than the current one
2385 pModeInfoFound = pModeInfo;
2386 }
2387 }
2388 pModeInfo = pModeInfo->pNext;
2389 }
2390 }
2391
2392 // If we did not find a good fullscreen mode, then return NULL
2393 if (!pModeInfoFound)
2394 {
2395#ifdef DEBUG_BUILD
2396 printf("[os2fslib_SetVideoMode] : Requested video mode not found!\n"); fflush(stdout);
2397#endif
2398 return NULL;
2399 }
2400
2401#ifdef DEBUG_BUILD
2402 printf("[os2fslib_SetVideoMode] : Found mode!\n"); fflush(stdout);
2403#endif
2404
2405 // We'll possibly adjust the structure, so copy out the values
2406 // into TempModeInfo!
2407 SDL_memcpy(&TempModeInfo, pModeInfoFound, sizeof(TempModeInfo));
2408 pModeInfoFound = &TempModeInfo;
2409
2410 if (flags & SDL_RESIZABLE)
2411 {
2412#ifdef DEBUG_BUILD
2413 printf("[os2fslib_SetVideoMode] : Requested mode is resizable, changing width/height\n"); fflush(stdout);
2414#endif
2415 // Change width and height to requested one!
2416 TempModeInfo.uiXResolution = width;
2417 TempModeInfo.uiYResolution = height;
2418 TempModeInfo.uiScanLineSize = width * ((TempModeInfo.uiBPP+7)/8);
2419 }
2420
2421 // We can try create new surface!
2422
2423 // Make sure this thread is prepared for using the Presentation Manager!
2424 hab = WinInitialize(0);
2425 hmq = WinCreateMsgQueue(hab,0);
2426 // Remember if there was an error at WinCreateMsgQueue(), because we don't
2427 // want to destroy somebody else's queue later. :)
2428 hmqerror = WinGetLastError(hab);
2429
2430
2431
2432 if (DosRequestMutexSem(_this->hidden->hmtxUseSrcBuffer, SEM_INDEFINITE_WAIT)==NO_ERROR)
2433 {
2434#ifdef DEBUG_BUILD
2435 printf("[os2fslib_SetVideoMode] : Creating new SW surface\n"); fflush(stdout);
2436#endif
2437
2438 // Create new software surface!
2439 pResult = SDL_CreateRGBSurface(SDL_SWSURFACE,
2440 pModeInfoFound->uiXResolution,
2441 pModeInfoFound->uiYResolution,
2442 pModeInfoFound->uiBPP,
2443 ((unsigned int) pModeInfoFound->PixelFormat.ucRedMask) << pModeInfoFound->PixelFormat.ucRedPosition,
2444 ((unsigned int) pModeInfoFound->PixelFormat.ucGreenMask) << pModeInfoFound->PixelFormat.ucGreenPosition,
2445 ((unsigned int) pModeInfoFound->PixelFormat.ucBlueMask) << pModeInfoFound->PixelFormat.ucBluePosition,
2446 ((unsigned int) pModeInfoFound->PixelFormat.ucAlphaMask) << pModeInfoFound->PixelFormat.ucAlphaPosition);
2447
2448 if (pResult == NULL)
2449 {
2450 DosReleaseMutexSem(_this->hidden->hmtxUseSrcBuffer);
2451 SDL_OutOfMemory();
2452 return NULL;
2453 }
2454
2455#ifdef DEBUG_BUILD
2456 printf("[os2fslib_SetVideoMode] : Adjusting pixel format\n"); fflush(stdout);
2457#endif
2458
2459 // Adjust pixel format mask!
2460 pResult->format->Rmask = ((unsigned int) pModeInfoFound->PixelFormat.ucRedMask) << pModeInfoFound->PixelFormat.ucRedPosition;
2461 pResult->format->Rshift = pModeInfoFound->PixelFormat.ucRedPosition;
2462 pResult->format->Rloss = pModeInfoFound->PixelFormat.ucRedAdjust;
2463 pResult->format->Gmask = ((unsigned int) pModeInfoFound->PixelFormat.ucGreenMask) << pModeInfoFound->PixelFormat.ucGreenPosition;
2464 pResult->format->Gshift = pModeInfoFound->PixelFormat.ucGreenPosition;
2465 pResult->format->Gloss = pModeInfoFound->PixelFormat.ucGreenAdjust;
2466 pResult->format->Bmask = ((unsigned int) pModeInfoFound->PixelFormat.ucBlueMask) << pModeInfoFound->PixelFormat.ucBluePosition;
2467 pResult->format->Bshift = pModeInfoFound->PixelFormat.ucBluePosition;
2468 pResult->format->Bloss = pModeInfoFound->PixelFormat.ucBlueAdjust;
2469 pResult->format->Amask = ((unsigned int) pModeInfoFound->PixelFormat.ucAlphaMask) << pModeInfoFound->PixelFormat.ucAlphaPosition;
2470 pResult->format->Ashift = pModeInfoFound->PixelFormat.ucAlphaPosition;
2471 pResult->format->Aloss = pModeInfoFound->PixelFormat.ucAlphaAdjust;
2472
2473#ifdef REPORT_EMPTY_ALPHA_MASK
2474 pResult->format->Amask =
2475 pResult->format->Ashift =
2476 pResult->format->Aloss = 0;
2477#endif
2478
2479 // Adjust surface flags
2480 pResult->flags |= (flags & SDL_FULLSCREEN);
2481 pResult->flags |= (flags & SDL_RESIZABLE);
2482
2483 // It might be that the software surface pitch is not the same as
2484 // the pitch we have, so adjust that!
2485 pModeInfoFound->uiScanLineSize = pResult->pitch;
2486
2487 // Store new source buffer parameters!
2488 SDL_memcpy(&(_this->hidden->SrcBufferDesc), pModeInfoFound, sizeof(*pModeInfoFound));
2489 _this->hidden->pchSrcBuffer = pResult->pixels;
2490
2491#ifdef DEBUG_BUILD
2492 printf("[os2fslib_SetVideoMode] : Telling FSLib the stuffs\n"); fflush(stdout);
2493#endif
2494
2495 // Tell the FSLib window the new source image format
2496 FSLib_SetSrcBufferDesc(_this->hidden->hwndClient, &(_this->hidden->SrcBufferDesc));
2497
2498 if (
2499 ((flags & SDL_RESIZABLE)==0) ||
2500 (bFirstCall)
2501 )
2502 {
2503 bFirstCall = 0;
2504#ifdef DEBUG_BUILD
2505 printf("[os2fslib_SetVideoMode] : Modifying window size\n"); fflush(stdout);
2506#endif
2507
2508 // Calculate frame window size from client window size
2509 rectl.xLeft = 0;
2510 rectl.yBottom = 0;
2511 rectl.xRight = pModeInfoFound->uiXResolution; // Noninclusive
2512 rectl.yTop = pModeInfoFound->uiYResolution; // Noninclusive
2513 WinCalcFrameRect(_this->hidden->hwndFrame, &rectl, FALSE);
2514
2515 // Set the new size of the main window
2516 SetAccessableWindowPos(_this->hidden->hwndFrame,
2517 HWND_TOP,
2518 0, 0,
2519 (rectl.xRight-rectl.xLeft),
2520 (rectl.yTop-rectl.yBottom),
2521 SWP_SIZE | SWP_ACTIVATE | SWP_SHOW);
2522 }
2523
2524 // Set fullscreen mode flag, and switch to fullscreen if needed!
2525 if (flags & SDL_FULLSCREEN)
2526 {
2527#ifdef DEBUG_BUILD
2528 printf("[os2fslib_SetVideoMode] : Also trying to switch to fullscreen\n");
2529 fflush(stdout);
2530#endif
2531 FSLib_ToggleFSMode(_this->hidden->hwndClient, 1);
2532 /* Cursor manager functions to FS mode*/
2533 os2fslib_SetCursorManagementFunctions(_this, 0);
2534 } else
2535 {
2536#ifdef DEBUG_BUILD
2537 printf("[os2fslib_SetVideoMode] : Also trying to switch to desktop mode\n");
2538 fflush(stdout);
2539#endif
2540 FSLib_ToggleFSMode(_this->hidden->hwndClient, 0);
2541 /* Cursor manager functions to Windowed mode*/
2542 os2fslib_SetCursorManagementFunctions(_this, 1);
2543 }
2544
2545 _this->hidden->pSDLSurface = pResult;
2546
2547 DosReleaseMutexSem(_this->hidden->hmtxUseSrcBuffer);
2548 } else
2549 {
2550#ifdef DEBUG_BUILD
2551 printf("[os2fslib_SetVideoMode] : Could not get hmtxUseSrcBuffer!\n"); fflush(stdout);
2552#endif
2553
2554 pResult = NULL;
2555 }
2556
2557 // As we have the new surface, we don't need the current one anymore!
2558 if ((pResult) && (current))
2559 {
2560#ifdef DEBUG_BUILD
2561 printf("[os2fslib_SetVideoMode] : Freeing old surface\n"); fflush(stdout);
2562#endif
2563 SDL_FreeSurface(current);
2564 }
2565
2566 // Redraw window
2567 WinInvalidateRegion(_this->hidden->hwndClient, NULL, TRUE);
2568
2569 // Now destroy the message queue, if we've created it!
2570 if (ERRORIDERROR(hmqerror)==0)
2571 {
2572#ifdef DEBUG_BUILD
2573 printf("[os2fslib_SetVideoMode] : Destroying message queue\n"); fflush(stdout);
2574#endif
2575 WinDestroyMsgQueue(hmq);
2576 }
2577
2578#ifdef DEBUG_BUILD
2579 printf("[os2fslib_SetVideoMode] : Done\n"); fflush(stdout);
2580#endif
2581
2582 /* We're done */
2583
2584 // Return with the new surface!
2585 return pResult;
2586}
2587
2588/* List the available video modes for the given pixel format, sorted
2589 from largest to smallest.
2590 */
2591static SDL_Rect **os2fslib_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
2592{
2593#ifdef DEBUG_BUILD
2594 printf("[os2fslib_ListModes] : ListModes of %d Bpp\n", format->BitsPerPixel);
2595#endif
2596 // Destroy result of previous call, if there is any
2597 if (_this->hidden->pListModesResult)
2598 {
2599 SDL_free(_this->hidden->pListModesResult); _this->hidden->pListModesResult = NULL;
2600 }
2601
2602 // For resizable and windowed mode we support every resolution!
2603 if ((flags & SDL_RESIZABLE) && ((flags & SDL_FULLSCREEN) == 0))
2604 return (SDL_Rect **)-1;
2605
2606 // Check if they need fullscreen or non-fullscreen video modes!
2607 if ((flags & SDL_FULLSCREEN) == 0)
2608
2609 {
2610 // For windowed mode we support every resolution!
2611 return (SDL_Rect **)-1;
2612 } else
2613 {
2614 FSLib_VideoMode_p pFSMode;
2615 // For fullscreen mode we don't support every resolution!
2616 // Now create a new list
2617 pFSMode = _this->hidden->pAvailableFSLibVideoModes;
2618 while (pFSMode)
2619 {
2620 if (pFSMode->uiBPP == format->BitsPerPixel)
2621 {
2622 SDL_Rect *pRect = (SDL_Rect *) SDL_malloc(sizeof(SDL_Rect));
2623 if (pRect)
2624 {
2625 // Fill description
2626 pRect->x = 0;
2627 pRect->y = 0;
2628 pRect->w = pFSMode->uiXResolution;
2629 pRect->h = pFSMode->uiYResolution;
2630#ifdef DEBUG_BUILD
2631// printf("!!! Seems to be good!\n");
2632// printf("F: %dx%d\n", pRect->w, pRect->h);
2633#endif
2634 // And insert into list of pRects
2635 if (!(_this->hidden->pListModesResult))
2636 {
2637#ifdef DEBUG_BUILD
2638// printf("!!! Inserting to beginning\n");
2639#endif
2640
2641 // We're the first one to be inserted!
2642 _this->hidden->pListModesResult = (SDL_Rect**) SDL_malloc(2*sizeof(SDL_Rect*));
2643 if (_this->hidden->pListModesResult)
2644 {
2645 _this->hidden->pListModesResult[0] = pRect;
2646 _this->hidden->pListModesResult[1] = NULL;
2647 } else
2648 {
2649 SDL_free(pRect);
2650 }
2651 } else
2652 {
2653 // We're not the first ones, so find the place where we
2654 // have to insert ourselves
2655 SDL_Rect **pNewList;
2656 int iPlace, iNumOfSlots, i;
2657
2658#ifdef DEBUG_BUILD
2659// printf("!!! Searching where to insert\n");
2660#endif
2661
2662 iPlace = -1; iNumOfSlots = 1; // Count the last NULL too!
2663 for (i=0; _this->hidden->pListModesResult[i]; i++)
2664 {
2665 iNumOfSlots++;
2666 if (iPlace==-1)
2667 {
2668 if ((_this->hidden->pListModesResult[i]->w*_this->hidden->pListModesResult[i]->h)<
2669 (pRect->w*pRect->h))
2670 {
2671 iPlace = i;
2672 }
2673 }
2674 }
2675 if (iPlace==-1) iPlace = iNumOfSlots-1;
2676
2677#ifdef DEBUG_BUILD
2678// printf("!!! From %d slots, it will be at %d\n", iNumOfSlots, iPlace);
2679#endif
2680
2681 pNewList = (SDL_Rect**) SDL_realloc(_this->hidden->pListModesResult, (iNumOfSlots+1)*sizeof(SDL_Rect*));
2682 if (pNewList)
2683 {
2684 for (i=iNumOfSlots;i>iPlace;i--)
2685 pNewList[i] = pNewList[i-1];
2686 pNewList[iPlace] = pRect;
2687 _this->hidden->pListModesResult = pNewList;
2688 } else
2689 {
2690 SDL_free(pRect);
2691 }
2692 }
2693 }
2694 }
2695 pFSMode = pFSMode->pNext;
2696 }
2697 }
2698#ifdef DEBUG_BUILD
2699// printf("Returning list\n");
2700#endif
2701 return _this->hidden->pListModesResult;
2702}
2703
2704/* Initialize the native video subsystem, filling 'vformat' with the
2705 "best" display pixel format, returning 0 or -1 if there's an error.
2706 */
2707static int os2fslib_VideoInit(_THIS, SDL_PixelFormat *vformat)
2708{
2709 FSLib_VideoMode_p pDesktopMode;
2710
2711#ifdef DEBUG_BUILD
2712 printf("[os2fslib_VideoInit] : Enter\n"); fflush(stdout);
2713#endif
2714
2715 // Report the best pixel format. For this,
2716 // we'll use the current desktop format.
2717 pDesktopMode = FSLib_GetDesktopVideoMode();
2718 if (!pDesktopMode)
2719 {
2720 SDL_SetError("Could not query desktop video mode!");
2721#ifdef DEBUG_BUILD
2722 printf("[os2fslib_VideoInit] : Could not query desktop video mode!\n");
2723#endif
2724 return -1;
2725 }
2726
2727 /* Determine the current screen size */
2728 _this->info.current_w = pDesktopMode->uiXResolution;
2729 _this->info.current_h = pDesktopMode->uiYResolution;
2730
2731 /* Determine the screen depth */
2732 vformat->BitsPerPixel = pDesktopMode->uiBPP;
2733 vformat->BytesPerPixel = (vformat->BitsPerPixel+7)/8;
2734
2735 vformat->Rmask = ((unsigned int) pDesktopMode->PixelFormat.ucRedMask) << pDesktopMode->PixelFormat.ucRedPosition;
2736 vformat->Rshift = pDesktopMode->PixelFormat.ucRedPosition;
2737 vformat->Rloss = pDesktopMode->PixelFormat.ucRedAdjust;
2738 vformat->Gmask = ((unsigned int) pDesktopMode->PixelFormat.ucGreenMask) << pDesktopMode->PixelFormat.ucGreenPosition;
2739 vformat->Gshift = pDesktopMode->PixelFormat.ucGreenPosition;
2740 vformat->Gloss = pDesktopMode->PixelFormat.ucGreenAdjust;
2741 vformat->Bmask = ((unsigned int) pDesktopMode->PixelFormat.ucBlueMask) << pDesktopMode->PixelFormat.ucBluePosition;
2742 vformat->Bshift = pDesktopMode->PixelFormat.ucBluePosition;
2743 vformat->Bloss = pDesktopMode->PixelFormat.ucBlueAdjust;
2744 vformat->Amask = ((unsigned int) pDesktopMode->PixelFormat.ucAlphaMask) << pDesktopMode->PixelFormat.ucAlphaPosition;
2745 vformat->Ashift = pDesktopMode->PixelFormat.ucAlphaPosition;
2746 vformat->Aloss = pDesktopMode->PixelFormat.ucAlphaAdjust;
2747
2748#ifdef REPORT_EMPTY_ALPHA_MASK
2749 vformat->Amask =
2750 vformat->Ashift =
2751 vformat->Aloss = 0;
2752#endif
2753
2754 // Fill in some window manager capabilities
2755 _this->info.wm_available = 1;
2756
2757 // Initialize some internal variables
2758 _this->hidden->pListModesResult = NULL;
2759 _this->hidden->fInFocus = 0;
2760 _this->hidden->iSkipWMMOUSEMOVE = 0;
2761 _this->hidden->iMouseVisible = 1;
2762
2763 if (getenv("SDL_USE_PROPORTIONAL_WINDOW"))
2764 _this->hidden->bProportionalResize = 1;
2765 else
2766 {
2767 PPIB pib;
2768 PTIB tib;
2769 char *pchFileName, *pchTemp;
2770 char achConfigFile[CCHMAXPATH];
2771 FILE *hFile;
2772
2773 /* No environment variable to have proportional window.
2774 * Ok, let's check if this executable is in config file!
2775 */
2776 _this->hidden->bProportionalResize = 0;
2777
2778 DosGetInfoBlocks(&tib, &pib);
2779 pchTemp = pchFileName = pib->pib_pchcmd;
2780 while (*pchTemp)
2781 {
2782 if (*pchTemp=='\\')
2783 pchFileName = pchTemp+1;
2784 pchTemp++;
2785 }
2786 if (getenv("HOME"))
2787 {
2788 sprintf(achConfigFile, "%s\\.sdl.proportionals", getenv("HOME"));
2789 hFile = fopen(achConfigFile, "rt");
2790 if (!hFile)
2791 {
2792 /* Seems like the file cannot be opened or does not exist.
2793 * Let's try to create it with defaults!
2794 */
2795 hFile = fopen(achConfigFile, "wt");
2796 if (hFile)
2797 {
2798 fprintf(hFile, "; This file is a config file of SDL/2, containing\n");
2799 fprintf(hFile, "; the list of executables that must have proportional\n");
2800 fprintf(hFile, "; windows.\n");
2801 fprintf(hFile, ";\n");
2802 fprintf(hFile, "; You can add executable filenames into this file,\n");
2803 fprintf(hFile, "; one under the other. If SDL finds that a given\n");
2804 fprintf(hFile, "; program is in this list, then that application\n");
2805 fprintf(hFile, "; will have proportional windows, just like if\n");
2806 fprintf(hFile, "; the SET SDL_USE_PROPORTIONAL_WINDOW env. variable\n");
2807 fprintf(hFile, "; would have been set for that process.\n");
2808 fprintf(hFile, ";\n");
2809 fprintf(hFile, "\n");
2810 fprintf(hFile, "dosbox.exe\n");
2811 fclose(hFile);
2812 }
2813
2814 hFile = fopen(achConfigFile, "rt");
2815 }
2816
2817 if (hFile)
2818 {
2819 while (fgets(achConfigFile, sizeof(achConfigFile), hFile))
2820 {
2821 /* Cut \n from end of string */
2822
2823 while (achConfigFile[strlen(achConfigFile)-1] == '\n')
2824 achConfigFile[strlen(achConfigFile)-1] = 0;
2825
2826 /* Compare... */
2827 if (stricmp(achConfigFile, pchFileName)==0)
2828 {
2829 /* Found it in config file! */
2830 _this->hidden->bProportionalResize = 1;
2831 break;
2832 }
2833 }
2834 fclose(hFile);
2835 }
2836 }
2837 }
2838
2839 DosCreateMutexSem(NULL, &(_this->hidden->hmtxUseSrcBuffer), 0, FALSE);
2840
2841 // Now create our window with a default size
2842
2843 // For this, we select the first available fullscreen mode as
2844 // current window size!
2845 SDL_memcpy(&(_this->hidden->SrcBufferDesc), _this->hidden->pAvailableFSLibVideoModes, sizeof(_this->hidden->SrcBufferDesc));
2846 // Allocate new video buffer!
2847 _this->hidden->pchSrcBuffer = (char *) SDL_malloc(_this->hidden->pAvailableFSLibVideoModes->uiScanLineSize * _this->hidden->pAvailableFSLibVideoModes->uiYResolution);
2848 if (!_this->hidden->pchSrcBuffer)
2849 {
2850#ifdef DEBUG_BUILD
2851 printf("[os2fslib_VideoInit] : Yikes, not enough memory for new video buffer!\n"); fflush(stdout);
2852#endif
2853 SDL_SetError("Not enough memory for new video buffer!\n");
2854 return -1;
2855 }
2856
2857 // For this, we need a message processing thread.
2858 // We'll create a new thread for this, which will do everything
2859 // what is related to PM
2860 _this->hidden->iPMThreadStatus = 0;
2861 _this->hidden->tidPMThread = _beginthread(PMThreadFunc, NULL, 65536, (void *) _this);
2862 if (_this->hidden->tidPMThread <= 0)
2863 {
2864#ifdef DEBUG_BUILD
2865 printf("[os2fslib_VideoInit] : Could not create PM thread!\n");
2866#endif
2867 SDL_SetError("Could not create PM thread");
2868 return -1;
2869 }
2870#ifdef USE_DOSSETPRIORITY
2871 // Burst the priority of PM Thread!
2872 DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, _this->hidden->tidPMThread);
2873#endif
2874 // Wait for the PM thread to initialize!
2875 while (_this->hidden->iPMThreadStatus==0)
2876 DosSleep(32);
2877 // If the PM thread could not set up everything, then
2878 // report an error!
2879 if (_this->hidden->iPMThreadStatus!=1)
2880 {
2881#ifdef DEBUG_BUILD
2882 printf("[os2fslib_VideoInit] : PMThread reported an error : %d\n", _this->hidden->iPMThreadStatus);
2883#endif
2884 SDL_SetError("Error initializing PM thread");
2885 return -1;
2886 }
2887
2888 return 0;
2889}
2890
2891
2892static void os2fslib_DeleteDevice(_THIS)
2893{
2894#ifdef DEBUG_BUILD
2895 printf("[os2fslib_DeleteDevice]\n"); fflush(stdout);
2896#endif
2897 // Free used memory
2898 FSLib_FreeVideoModeList(_this->hidden->pAvailableFSLibVideoModes);
2899 if (_this->hidden->pListModesResult)
2900 SDL_free(_this->hidden->pListModesResult);
2901 if (_this->hidden->pchSrcBuffer)
2902 SDL_free(_this->hidden->pchSrcBuffer);
2903 DosCloseMutexSem(_this->hidden->hmtxUseSrcBuffer);
2904 SDL_free(_this->hidden);
2905 SDL_free(_this);
2906 FSLib_Uninitialize();
2907}
2908
2909static int os2fslib_Available(void)
2910{
2911
2912 // If we can run, it means that we could load FSLib,
2913 // so we assume that it's available then!
2914 return 1;
2915}
2916
2917static void os2fslib_MorphToPM()
2918{
2919 PPIB pib;
2920 PTIB tib;
2921
2922 DosGetInfoBlocks(&tib, &pib);
2923
2924 // Change flag from VIO to PM:
2925 if (pib->pib_ultype==2) pib->pib_ultype = 3;
2926}
2927
2928static SDL_VideoDevice *os2fslib_CreateDevice(int devindex)
2929{
2930 SDL_VideoDevice *device;
2931
2932#ifdef DEBUG_BUILD
2933 printf("[os2fslib_CreateDevice] : Enter\n"); fflush(stdout);
2934#endif
2935
2936 /* Initialize all variables that we clean on shutdown */
2937 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
2938 if ( device )
2939 {
2940 SDL_memset(device, 0, (sizeof *device));
2941 // Also allocate memory for private data
2942 device->hidden = (struct SDL_PrivateVideoData *) SDL_malloc((sizeof(struct SDL_PrivateVideoData)));
2943 }
2944 if ( (device == NULL) || (device->hidden == NULL) )
2945 {
2946 SDL_OutOfMemory();
2947 if ( device )
2948 SDL_free(device);
2949 return NULL;
2950 }
2951 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
2952
2953 /* Set the function pointers */
2954#ifdef DEBUG_BUILD
2955 printf("[os2fslib_CreateDevice] : VideoInit is %p\n", os2fslib_VideoInit); fflush(stdout);
2956#endif
2957
2958 /* Initialization/Query functions */
2959 device->VideoInit = os2fslib_VideoInit;
2960 device->ListModes = os2fslib_ListModes;
2961 device->SetVideoMode = os2fslib_SetVideoMode;
2962 device->ToggleFullScreen = os2fslib_ToggleFullScreen;
2963 device->UpdateMouse = os2fslib_UpdateMouse;
2964 device->CreateYUVOverlay = NULL;
2965 device->SetColors = os2fslib_SetColors;
2966 device->UpdateRects = os2fslib_UpdateRects;
2967 device->VideoQuit = os2fslib_VideoQuit;
2968 /* Hardware acceleration functions */
2969 device->AllocHWSurface = os2fslib_AllocHWSurface;
2970 device->CheckHWBlit = NULL;
2971 device->FillHWRect = NULL;
2972 device->SetHWColorKey = NULL;
2973 device->SetHWAlpha = NULL;
2974 device->LockHWSurface = os2fslib_LockHWSurface;
2975 device->UnlockHWSurface = os2fslib_UnlockHWSurface;
2976 device->FlipHWSurface = NULL;
2977 device->FreeHWSurface = os2fslib_FreeHWSurface;
2978 /* Window manager functions */
2979 device->SetCaption = os2fslib_SetCaption;
2980 device->SetIcon = os2fslib_SetIcon;
2981 device->IconifyWindow = os2fslib_IconifyWindow;
2982 device->GrabInput = os2fslib_GrabInput;
2983 device->GetWMInfo = NULL;
2984 /* Cursor manager functions to Windowed mode*/
2985 os2fslib_SetCursorManagementFunctions(device, 1);
2986 /* Event manager functions */
2987 device->InitOSKeymap = os2fslib_InitOSKeymap;
2988 device->PumpEvents = os2fslib_PumpEvents;
2989 /* The function used to dispose of this structure */
2990 device->free = os2fslib_DeleteDevice;
2991
2992 // Make sure we'll be able to use Win* API even if the application
2993 // was linked to be a VIO application!
2994 os2fslib_MorphToPM();
2995
2996 // Now initialize FSLib, and query available video modes!
2997 if (!FSLib_Initialize())
2998 {
2999 // Could not initialize FSLib!
3000#ifdef DEBUG_BUILD
3001 printf("[os2fslib_CreateDevice] : Could not initialize FSLib!\n");
3002#endif
3003 SDL_SetError("Could not initialize FSLib!");
3004 SDL_free(device->hidden);
3005 SDL_free(device);
3006 return NULL;
3007 }
3008 device->hidden->pAvailableFSLibVideoModes =
3009 FSLib_GetVideoModeList();
3010
3011 return device;
3012}
3013
3014VideoBootStrap OS2FSLib_bootstrap = {
3015 "os2fslib", "OS/2 Video Output using FSLib",
3016 os2fslib_Available, os2fslib_CreateDevice
3017};
3018
diff --git a/apps/plugins/sdl/src/video/os2fslib/SDL_os2fslib.h b/apps/plugins/sdl/src/video/os2fslib/SDL_os2fslib.h
deleted file mode 100644
index 6d58baf0af..0000000000
--- a/apps/plugins/sdl/src/video/os2fslib/SDL_os2fslib.h
+++ /dev/null
@@ -1,71 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_os2fslib_h
25#define _SDL_os2fslib_h
26
27
28// OS2 specific includes
29#define INCL_TYPES
30#define INCL_DOS
31#define INCL_DOSERRORS
32#define INCL_DOSPROCESS
33#define INCL_WIN
34#define INCL_GPI
35#include <os2.h>
36
37#include <FSLib.h>
38
39/* Hidden "this" pointer for the video functions */
40#define _THIS SDL_VideoDevice *_this
41
42/* Private display data */
43struct SDL_PrivateVideoData
44{
45 FSLib_VideoMode_p pAvailableFSLibVideoModes;
46 SDL_Rect **pListModesResult; // Allocated memory to return list of modes for os2fslib_ListModes() API
47
48 FSLib_VideoMode SrcBufferDesc; // Description of current source image buffer
49 char *pchSrcBuffer; // The source image buffer itself
50 SDL_Surface *pSDLSurface; // The SDL surface describing the buffer
51 HMTX hmtxUseSrcBuffer; // Mutex semaphore to manipulate src buffer
52 HWND hwndFrame, hwndClient; // Window handle of frame and client
53 int iPMThreadStatus; // 0: Not running
54 // 1: Running
55 // Other: Not running, had an error
56 int tidPMThread; // Thread ID of PM Thread
57 int fInFocus; // True if we're in focus!
58 int iSkipWMMOUSEMOVE; // Number of WM_MOUSEMOVE messages to skip!
59 int iMouseVisible; //
60
61 PFNWP pfnOldFrameProc; // Old window frame procedure
62 int bProportionalResize; // 0: No proportional resizing
63 // 1: Do proportional resizing
64 ULONG ulResizingFlag; // First resizing flag value
65};
66
67/* OS/2 specific backdoor function to be able to set FrameControlFlags of */
68/* the SDL window before creating it. */
69extern DECLSPEC void SDLCALL SDL_OS2FSLIB_SetFCFToUse(ULONG ulFCF);
70
71#endif /* _SDL_os2fslib_h */
diff --git a/apps/plugins/sdl/src/video/os2fslib/SDL_vkeys.h b/apps/plugins/sdl/src/video/os2fslib/SDL_vkeys.h
deleted file mode 100644
index 79380d5541..0000000000
--- a/apps/plugins/sdl/src/video/os2fslib/SDL_vkeys.h
+++ /dev/null
@@ -1,74 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23#ifndef VK_0
24#define VK_0 '0'
25#define VK_1 '1'
26#define VK_2 '2'
27#define VK_3 '3'
28#define VK_4 '4'
29#define VK_5 '5'
30#define VK_6 '6'
31#define VK_7 '7'
32#define VK_8 '8'
33#define VK_9 '9'
34#define VK_A 'A'
35#define VK_B 'B'
36#define VK_C 'C'
37#define VK_D 'D'
38#define VK_E 'E'
39#define VK_F 'F'
40#define VK_G 'G'
41#define VK_H 'H'
42#define VK_I 'I'
43#define VK_J 'J'
44#define VK_K 'K'
45#define VK_L 'L'
46#define VK_M 'M'
47#define VK_N 'N'
48#define VK_O 'O'
49#define VK_P 'P'
50#define VK_Q 'Q'
51#define VK_R 'R'
52#define VK_S 'S'
53#define VK_T 'T'
54#define VK_U 'U'
55#define VK_V 'V'
56#define VK_W 'W'
57#define VK_X 'X'
58#define VK_Y 'Y'
59#define VK_Z 'Z'
60#endif /* VK_0 */
61
62/* These keys haven't been defined, but were experimentally determined */
63#define VK_SEMICOLON 0xBA
64#define VK_EQUALS 0xBB
65#define VK_COMMA 0xBC
66#define VK_MINUS 0xBD
67#define VK_PERIOD 0xBE
68#define VK_SLASH 0xBF
69#define VK_GRAVE 0xC0
70#define VK_LBRACKET 0xDB
71#define VK_BACKSLASH 0xDC
72#define VK_RBRACKET 0xDD
73#define VK_APOSTROPHE 0xDE
74#define VK_BACKTICK 0xDF
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_events.c b/apps/plugins/sdl/src/video/photon/SDL_ph_events.c
deleted file mode 100644
index 9b7538c4b0..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_events.c
+++ /dev/null
@@ -1,624 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting photon events into SDL events */
25
26#include <stdio.h>
27#include <setjmp.h>
28#include <sys/time.h>
29
30#include <Ph.h>
31#include <photon/PkKeyDef.h>
32
33#include "SDL.h"
34#include "SDL_syswm.h"
35#include "../SDL_sysvideo.h"
36#include "../../events/SDL_sysevents.h"
37#include "../../events/SDL_events_c.h"
38#include "SDL_ph_video.h"
39#include "SDL_ph_modes_c.h"
40#include "SDL_ph_image_c.h"
41#include "SDL_ph_events_c.h"
42#include "SDL_phyuv_c.h"
43
44/* The translation tables from a photon keysym to a SDL keysym */
45static SDLKey ODD_keymap[256];
46static SDLKey MISC_keymap[0xFF + 1];
47SDL_keysym *ph_TranslateKey(PhKeyEvent_t *key, SDL_keysym *keysym);
48
49/* Check to see if this is a repeated key.
50 (idea shamelessly lifted from GII -- thanks guys! :) */
51static int ph_WarpedMotion(_THIS, PhEvent_t *winEvent)
52{
53 PhRect_t *rect = PhGetRects( winEvent );
54
55 int centre_x, centre_y;
56 int dx, dy;
57 short abs_x, abs_y;
58 int posted;
59
60 centre_x = SDL_VideoSurface->w / 2;
61 centre_y = SDL_VideoSurface->h / 2;
62
63 dx = rect->ul.x - centre_x;
64 dy = rect->ul.y - centre_y;
65
66 posted = SDL_PrivateMouseMotion( 0, 1, dx, dy );
67
68 /* Move mouse cursor to middle of the window */
69 PtGetAbsPosition( window, &abs_x, &abs_y );
70 PhMoveCursorAbs(PhInputGroup(NULL), abs_x + centre_x, abs_y + centre_y);
71
72 return (posted);
73}
74
75/* Control which motion flags the window has set, a flags value of -1 sets
76 * MOTION_BUTTON and MOTION_NOBUTTON */
77
78static void set_motion_sensitivity(_THIS, unsigned int flags)
79{
80 int rid;
81 int fields = Ph_EV_PTR_MOTION_BUTTON | Ph_EV_PTR_MOTION_NOBUTTON;
82 PhRegion_t region;
83
84 if( window )
85 {
86 rid = PtWidgetRid(window);
87 if( rid != 0 && PhRegionQuery(rid, &region, NULL, NULL, 0) == 0 )
88 {
89 region.events_sense=(region.events_sense & ~fields)|(flags & fields);
90 PhRegionChange(Ph_REGION_EV_SENSE, 0, &region, NULL, NULL);
91 }
92 }
93}
94
95/* Convert the photon button state value to an SDL value */
96static Uint8 ph2sdl_mousebutton(unsigned short button_state)
97{
98 Uint8 mouse_button = 0;
99
100 if (button_state & Ph_BUTTON_SELECT)
101 mouse_button |= SDL_BUTTON_LEFT;
102 if (button_state & Ph_BUTTON_MENU)
103 mouse_button |= SDL_BUTTON_RIGHT;
104 if (button_state & Ph_BUTTON_ADJUST)
105 mouse_button |= SDL_BUTTON_MIDDLE;
106
107 return (mouse_button);
108}
109
110static int ph_DispatchEvent(_THIS)
111{
112 int posted;
113 PhRect_t* rect;
114 PhPointerEvent_t* pointerEvent;
115 PhKeyEvent_t* keyEvent;
116 PhWindowEvent_t* winEvent;
117 int i, buttons;
118 SDL_Rect sdlrects[PH_SDL_MAX_RECTS];
119
120 posted = 0;
121
122 switch (phevent->type)
123 {
124 case Ph_EV_BOUNDARY:
125 {
126 if (phevent->subtype == Ph_EV_PTR_ENTER)
127 {
128 posted = SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
129 }
130 else if (phevent->subtype ==Ph_EV_PTR_LEAVE)
131 {
132 posted = SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
133 }
134 }
135 break;
136
137 case Ph_EV_PTR_MOTION_BUTTON:
138 case Ph_EV_PTR_MOTION_NOBUTTON:
139 {
140 if (SDL_VideoSurface)
141 {
142 pointerEvent = PhGetData(phevent);
143 rect = PhGetRects(phevent);
144
145 if (mouse_relative)
146 {
147 posted = ph_WarpedMotion(this, phevent);
148 }
149 else
150 {
151 posted = SDL_PrivateMouseMotion(0, 0, rect->ul.x, rect->ul.y);
152 }
153 }
154 }
155 break;
156
157 case Ph_EV_BUT_PRESS:
158 {
159 pointerEvent = PhGetData(phevent);
160 buttons = ph2sdl_mousebutton(pointerEvent->buttons);
161 if (buttons != 0)
162 {
163 posted = SDL_PrivateMouseButton(SDL_PRESSED, buttons, 0, 0);
164 }
165 }
166 break;
167
168 case Ph_EV_BUT_RELEASE:
169 {
170 pointerEvent = PhGetData(phevent);
171 buttons = ph2sdl_mousebutton(pointerEvent->buttons);
172 if (phevent->subtype == Ph_EV_RELEASE_REAL && buttons != 0)
173 {
174 posted = SDL_PrivateMouseButton(SDL_RELEASED, buttons, 0, 0);
175 }
176 else if(phevent->subtype == Ph_EV_RELEASE_PHANTOM)
177 {
178 /* If the mouse is outside the window,
179 * only a phantom release event is sent, so
180 * check if the window doesn't have mouse focus.
181 * Not perfect, maybe checking the mouse button
182 * state for Ph_EV_BOUNDARY events would be
183 * better. */
184 if ((SDL_GetAppState() & SDL_APPMOUSEFOCUS) == 0)
185 {
186 posted = SDL_PrivateMouseButton(SDL_RELEASED, buttons, 0, 0);
187 }
188 }
189 }
190 break;
191
192 case Ph_EV_WM:
193 {
194 winEvent = PhGetData(phevent);
195
196 /* losing focus */
197 if ((winEvent->event_f==Ph_WM_FOCUS) && (winEvent->event_state==Ph_WM_EVSTATE_FOCUSLOST))
198 {
199 set_motion_sensitivity(this, Ph_EV_PTR_MOTION_BUTTON);
200 posted = SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS);
201 }
202 /* gaining focus */
203 else if ((winEvent->event_f==Ph_WM_FOCUS) && (winEvent->event_state==Ph_WM_EVSTATE_FOCUS))
204 {
205 set_motion_sensitivity(this, -1);
206 posted = SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS);
207 }
208 /* request quit */
209 else if (winEvent->event_f==Ph_WM_CLOSE)
210 {
211 posted = SDL_PrivateQuit();
212 }
213 /* request hide/unhide */
214 else if (winEvent->event_f==Ph_WM_HIDE)
215 {
216 if (currently_hided)
217 {
218 /* got unhide window event */
219 /* TODO: restore application's palette if in palette mode */
220 currently_hided=0;
221 }
222 else
223 {
224 /* got hide window event */
225 /* TODO: restore original palette if in palette mode */
226 currently_hided=1;
227 }
228 }
229 /* request to resize */
230 else if (winEvent->event_f==Ph_WM_RESIZE)
231 {
232 currently_maximized=0;
233 #if (_NTO_VERSION < 630)
234 SDL_PrivateResize(winEvent->size.w+1, winEvent->size.h+1);
235 #else
236 /* QNX 6.3.0 have this bug fixed */
237 SDL_PrivateResize(winEvent->size.w, winEvent->size.h);
238 #endif /* _NTO_VERSION */
239 }
240 /* request to move */
241 else if (winEvent->event_f==Ph_WM_MOVE)
242 {
243 if (current_overlay!=NULL)
244 {
245 int lockedstate=current_overlay->hwdata->locked;
246 int chromastate=current_overlay->hwdata->ischromakey;
247 int error;
248 SDL_Rect src, dst;
249
250 current_overlay->hwdata->locked=1;
251 src.x = 0;
252 src.y = 0;
253 src.w = current_overlay->w;
254 src.y = current_overlay->h;
255 dst.x=current_overlay->hwdata->CurrentViewPort.pos.x;
256 dst.y=current_overlay->hwdata->CurrentViewPort.pos.y;
257 dst.w=current_overlay->hwdata->CurrentViewPort.size.w;
258 dst.h=current_overlay->hwdata->CurrentViewPort.size.h;
259 current_overlay->hwdata->ischromakey=0;
260 error=ph_DisplayYUVOverlay(this, current_overlay, &src, &dst);
261 if (!error)
262 {
263 current_overlay->hwdata->ischromakey=chromastate;
264 current_overlay->hwdata->locked=lockedstate;
265 }
266 }
267 }
268 /* maximize request */
269 else if (winEvent->event_f==Ph_WM_MAX)
270 {
271 /* window already moved and resized here */
272 currently_maximized=1;
273 }
274 /* restore request */
275 else if (winEvent->event_f==Ph_WM_RESTORE)
276 {
277 /* window already moved and resized here */
278 currently_maximized=0;
279 }
280 }
281 break;
282
283 /* window has been resized, moved or removed */
284 case Ph_EV_EXPOSE:
285 {
286 if (phevent->num_rects!=0)
287 {
288 int numrects;
289
290 if (SDL_VideoSurface)
291 {
292 rect = PhGetRects(phevent);
293 if (phevent->num_rects>PH_SDL_MAX_RECTS)
294 {
295 /* sorry, buffers underrun, we'll update only first PH_SDL_MAX_RECTS rects */
296 numrects=PH_SDL_MAX_RECTS;
297 }
298
299 for(i=0; i<phevent->num_rects; i++)
300 {
301 sdlrects[i].x = rect[i].ul.x;
302 sdlrects[i].y = rect[i].ul.y;
303 sdlrects[i].w = rect[i].lr.x - rect[i].ul.x + 1;
304 sdlrects[i].h = rect[i].lr.y - rect[i].ul.y + 1;
305 }
306
307 this->UpdateRects(this, phevent->num_rects, sdlrects);
308
309 if (current_overlay!=NULL)
310 {
311 int lockedstate=current_overlay->hwdata->locked;
312 int error;
313 SDL_Rect src, dst;
314
315 current_overlay->hwdata->locked=1;
316 src.x = 0;
317 src.y = 0;
318 src.w = current_overlay->w;
319 src.y = current_overlay->h;
320 dst.x=current_overlay->hwdata->CurrentViewPort.pos.x;
321 dst.y=current_overlay->hwdata->CurrentViewPort.pos.y;
322 dst.w=current_overlay->hwdata->CurrentViewPort.size.w;
323 dst.h=current_overlay->hwdata->CurrentViewPort.size.h;
324 current_overlay->hwdata->forcedredraw=1;
325 error=ph_DisplayYUVOverlay(this, current_overlay, &src, &dst);
326 if (!error)
327 {
328 current_overlay->hwdata->forcedredraw=0;
329 current_overlay->hwdata->locked=lockedstate;
330 }
331 }
332 }
333 }
334 }
335 break;
336
337 case Ph_EV_KEY:
338 {
339 SDL_keysym keysym;
340
341 posted = 0;
342
343 keyEvent = PhGetData(phevent);
344
345 if (Pk_KF_Key_Down & keyEvent->key_flags)
346 {
347 /* split the wheel events from real key events */
348 if ((keyEvent->key_cap==Pk_Up) && (keyEvent->key_scan==0) && ((keyEvent->key_flags & Pk_KF_Scan_Valid)==Pk_KF_Scan_Valid))
349 {
350 posted = SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELUP, 0, 0);
351 break;
352 }
353 if ((keyEvent->key_cap==Pk_Down) && (keyEvent->key_scan==0) && ((keyEvent->key_flags & Pk_KF_Scan_Valid)==Pk_KF_Scan_Valid))
354 {
355 posted = SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELDOWN, 0, 0);
356 break;
357 }
358 posted = SDL_PrivateKeyboard(SDL_PRESSED, ph_TranslateKey(keyEvent, &keysym));
359 }
360 else /* must be key release */
361 {
362 /* split the wheel events from real key events */
363 if ((keyEvent->key_cap==Pk_Up) && (keyEvent->key_scan==0) && ((keyEvent->key_flags & Pk_KF_Scan_Valid)==Pk_KF_Scan_Valid))
364 {
365 posted = SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELUP, 0, 0);
366 break;
367 }
368 if ((keyEvent->key_cap==Pk_Down) && (keyEvent->key_scan==0) && ((keyEvent->key_flags & Pk_KF_Scan_Valid)==Pk_KF_Scan_Valid))
369 {
370 posted = SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELDOWN, 0, 0);
371 break;
372 }
373 posted = SDL_PrivateKeyboard(SDL_RELEASED, ph_TranslateKey( keyEvent, &keysym));
374 }
375 }
376 break;
377
378 case Ph_EV_INFO:
379 {
380 if (phevent->subtype==Ph_OFFSCREEN_INVALID)
381 {
382 unsigned long* EvInfoData;
383
384 EvInfoData=(unsigned long*)PhGetData(phevent);
385
386 switch (*EvInfoData)
387 {
388 case Pg_VIDEO_MODE_SWITCHED:
389 {
390 }
391 break;
392 case Pg_ENTERED_DIRECT:
393 {
394 }
395 break;
396 case Pg_EXITED_DIRECT:
397 {
398 }
399 break;
400 case Pg_DRIVER_STARTED:
401 {
402 }
403 break;
404 }
405 }
406 }
407 break;
408 }
409
410 return(posted);
411}
412
413/* perform a blocking read if no events available */
414int ph_Pending(_THIS)
415{
416 /* Flush the display connection and look to see if events are queued */
417 PgFlush();
418
419 while (1)
420 {
421 switch(PhEventPeek(phevent, EVENT_SIZE))
422 {
423 case Ph_EVENT_MSG:
424 return 1;
425 case -1:
426 SDL_SetError("ph_Pending(): PhEventNext failed.\n");
427 return 0;
428 default:
429 return 0;
430 }
431 }
432
433 /* Oh well, nothing is ready .. */
434 return(0);
435}
436
437void ph_PumpEvents(_THIS)
438{
439 /* Flush the display connection and look to see if events are queued */
440 PgFlush();
441
442 while (ph_Pending(this))
443 {
444 PtEventHandler(phevent);
445 ph_DispatchEvent(this);
446 }
447}
448
449void ph_InitKeymap(void)
450{
451 int i;
452
453 /* Odd keys used in international keyboards */
454 for (i=0; i<SDL_arraysize(ODD_keymap); ++i)
455 {
456 ODD_keymap[i] = SDLK_UNKNOWN;
457 }
458
459 /* Map the miscellaneous keys */
460 for (i=0; i<SDL_arraysize(MISC_keymap); ++i)
461 {
462 MISC_keymap[i] = SDLK_UNKNOWN;
463 }
464
465 MISC_keymap[Pk_BackSpace&0xFF] = SDLK_BACKSPACE;
466 MISC_keymap[Pk_Tab&0xFF] = SDLK_TAB;
467 MISC_keymap[Pk_Clear&0xFF] = SDLK_CLEAR;
468 MISC_keymap[Pk_Return&0xFF] = SDLK_RETURN;
469 MISC_keymap[Pk_Pause&0xFF] = SDLK_PAUSE;
470 MISC_keymap[Pk_Escape&0xFF] = SDLK_ESCAPE;
471 MISC_keymap[Pk_Delete&0xFF] = SDLK_DELETE;
472
473 MISC_keymap[Pk_KP_0&0xFF] = SDLK_KP0;
474 MISC_keymap[Pk_KP_1&0xFF] = SDLK_KP1;
475 MISC_keymap[Pk_KP_2&0xFF] = SDLK_KP2;
476 MISC_keymap[Pk_KP_3&0xFF] = SDLK_KP3;
477 MISC_keymap[Pk_KP_4&0xFF] = SDLK_KP4;
478 MISC_keymap[Pk_KP_5&0xFF] = SDLK_KP5;
479 MISC_keymap[Pk_KP_6&0xFF] = SDLK_KP6;
480 MISC_keymap[Pk_KP_7&0xFF] = SDLK_KP7;
481 MISC_keymap[Pk_KP_8&0xFF] = SDLK_KP8;
482 MISC_keymap[Pk_KP_9&0xFF] = SDLK_KP9;
483
484 MISC_keymap[Pk_KP_Decimal&0xFF] = SDLK_KP_PERIOD;
485 MISC_keymap[Pk_KP_Divide&0xFF] = SDLK_KP_DIVIDE;
486 MISC_keymap[Pk_KP_Multiply&0xFF] = SDLK_KP_MULTIPLY;
487 MISC_keymap[Pk_KP_Subtract&0xFF] = SDLK_KP_MINUS;
488 MISC_keymap[Pk_KP_Add&0xFF] = SDLK_KP_PLUS;
489 MISC_keymap[Pk_KP_Enter&0xFF] = SDLK_KP_ENTER;
490 MISC_keymap[Pk_KP_Equal&0xFF] = SDLK_KP_EQUALS;
491
492 MISC_keymap[Pk_Up&0xFF] = SDLK_UP;
493 MISC_keymap[Pk_Down&0xFF] = SDLK_DOWN;
494 MISC_keymap[Pk_Right&0xFF] = SDLK_RIGHT;
495 MISC_keymap[Pk_Left&0xFF] = SDLK_LEFT;
496 MISC_keymap[Pk_Insert&0xFF] = SDLK_INSERT;
497 MISC_keymap[Pk_Home&0xFF] = SDLK_HOME;
498 MISC_keymap[Pk_End&0xFF] = SDLK_END;
499 MISC_keymap[Pk_Pg_Up&0xFF] = SDLK_PAGEUP;
500 MISC_keymap[Pk_Pg_Down&0xFF] = SDLK_PAGEDOWN;
501
502 MISC_keymap[Pk_F1&0xFF] = SDLK_F1;
503 MISC_keymap[Pk_F2&0xFF] = SDLK_F2;
504 MISC_keymap[Pk_F3&0xFF] = SDLK_F3;
505 MISC_keymap[Pk_F4&0xFF] = SDLK_F4;
506 MISC_keymap[Pk_F5&0xFF] = SDLK_F5;
507 MISC_keymap[Pk_F6&0xFF] = SDLK_F6;
508 MISC_keymap[Pk_F7&0xFF] = SDLK_F7;
509 MISC_keymap[Pk_F8&0xFF] = SDLK_F8;
510 MISC_keymap[Pk_F9&0xFF] = SDLK_F9;
511 MISC_keymap[Pk_F10&0xFF] = SDLK_F10;
512 MISC_keymap[Pk_F11&0xFF] = SDLK_F11;
513 MISC_keymap[Pk_F12&0xFF] = SDLK_F12;
514 MISC_keymap[Pk_F13&0xFF] = SDLK_F13;
515 MISC_keymap[Pk_F14&0xFF] = SDLK_F14;
516 MISC_keymap[Pk_F15&0xFF] = SDLK_F15;
517
518 MISC_keymap[Pk_Num_Lock&0xFF] = SDLK_NUMLOCK;
519 MISC_keymap[Pk_Caps_Lock&0xFF] = SDLK_CAPSLOCK;
520 MISC_keymap[Pk_Scroll_Lock&0xFF] = SDLK_SCROLLOCK;
521 MISC_keymap[Pk_Shift_R&0xFF] = SDLK_RSHIFT;
522 MISC_keymap[Pk_Shift_L&0xFF] = SDLK_LSHIFT;
523 MISC_keymap[Pk_Control_R&0xFF] = SDLK_RCTRL;
524 MISC_keymap[Pk_Control_L&0xFF] = SDLK_LCTRL;
525 MISC_keymap[Pk_Alt_R&0xFF] = SDLK_RALT;
526 MISC_keymap[Pk_Alt_L&0xFF] = SDLK_LALT;
527 MISC_keymap[Pk_Meta_R&0xFF] = SDLK_RMETA;
528 MISC_keymap[Pk_Meta_L&0xFF] = SDLK_LMETA;
529 MISC_keymap[Pk_Super_L&0xFF] = SDLK_LSUPER;
530 MISC_keymap[Pk_Super_R&0xFF] = SDLK_RSUPER;
531 MISC_keymap[Pk_Mode_switch&0xFF] = SDLK_MODE; /* "Alt Gr" key */
532
533 MISC_keymap[Pk_Help&0xFF] = SDLK_HELP;
534 MISC_keymap[Pk_Print&0xFF] = SDLK_PRINT;
535 MISC_keymap[Pk_Break&0xFF] = SDLK_BREAK;
536 MISC_keymap[Pk_Menu&0xFF] = SDLK_MENU; /* Windows "Menu" key */
537
538 MISC_keymap[Pk_Hyper_R&0xFF] = SDLK_RSUPER; /* Right "Windows" */
539
540 /* Left "Windows" key, but it can't be catched by application */
541 MISC_keymap[Pk_Hyper_L&0xFF] = SDLK_LSUPER;
542}
543
544static unsigned long cap;
545
546SDL_keysym *ph_TranslateKey(PhKeyEvent_t *key, SDL_keysym *keysym)
547{
548 /* 'sym' is set to the value of the key with modifiers applied to it.
549 This member is valid only if Pk_KF_Sym_Valid is set in the key_flags.
550 We will assume it is valid. */
551
552 /* FIXME: This needs to check whether the cap & scancode is valid */
553
554 cap = key->key_cap;
555
556 switch (cap>>8)
557 {
558 case 0x00: /* Latin 1 */
559 case 0x01: /* Latin 2 */
560 case 0x02: /* Latin 3 */
561 case 0x03: /* Latin 4 */
562 case 0x04: /* Katakana */
563 case 0x05: /* Arabic */
564 case 0x06: /* Cyrillic */
565 case 0x07: /* Greek */
566 case 0x08: /* Technical */
567 case 0x0A: /* Publishing */
568 case 0x0C: /* Hebrew */
569 case 0x0D: /* Thai */
570 keysym->sym = (SDLKey)(cap&0xFF);
571 /* Map capital letter syms to lowercase */
572 if ((keysym->sym >= 'A')&&(keysym->sym <= 'Z'))
573 keysym->sym += ('a'-'A');
574 break;
575 case 0xF0:
576 keysym->sym = MISC_keymap[cap&0xFF];
577 break;
578 default:
579 keysym->sym = SDLK_UNKNOWN;
580 break;
581 }
582
583 keysym->scancode = key->key_scan;
584 keysym->unicode = 0;
585
586 if (SDL_TranslateUNICODE)
587 {
588 char utf8[MB_CUR_MAX];
589 int utf8len;
590 wchar_t unicode;
591
592 switch (keysym->scancode)
593 {
594 /* Esc key */
595 case 0x01: keysym->unicode = 27;
596 break;
597 /* BackSpace key */
598 case 0x0E: keysym->unicode = 127;
599 break;
600 /* Enter key */
601 case 0x1C: keysym->unicode = 10;
602 break;
603 default:
604 utf8len = PhKeyToMb(utf8, key);
605 if (utf8len > 0)
606 {
607 utf8len = mbtowc(&unicode, utf8, utf8len);
608 if (utf8len > 0)
609 {
610 keysym->unicode = unicode;
611 }
612 }
613 break;
614 }
615
616 }
617
618 return (keysym);
619}
620
621void ph_InitOSKeymap(_THIS)
622{
623 ph_InitKeymap();
624}
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_events_c.h b/apps/plugins/sdl/src/video/photon/SDL_ph_events_c.h
deleted file mode 100644
index 4aa939b3d9..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_events_c.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SDL_PH_EVENTS_H__
25#define __SDL_PH_EVENTS_H__
26
27#include "SDL_ph_video.h"
28
29#define PH_SDL_MAX_RECTS 256
30#define PH_EVENT_SAFETY_POOL 512
31#define EVENT_SIZE (sizeof(PhEvent_t) + 1000 + PH_EVENT_SAFETY_POOL)
32
33/* Functions to be exported */
34extern void ph_InitOSKeymap(_THIS);
35extern void ph_PumpEvents(_THIS);
36
37#endif /* __SDL_PH_EVENTS_H__ */
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_gl.c b/apps/plugins/sdl/src/video/photon/SDL_ph_gl.c
deleted file mode 100644
index 3121777639..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_gl.c
+++ /dev/null
@@ -1,406 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <dlfcn.h>
25#include "SDL.h"
26#include "SDL_ph_gl.h"
27
28#if SDL_VIDEO_OPENGL
29
30#if (_NTO_VERSION >= 630)
31 /* PhotonGL functions */
32 GLPH_DECLARE_FUNCS;
33#endif /* 6.3.0 */
34
35#if (_NTO_VERSION < 630)
36void ph_GL_SwapBuffers(_THIS)
37{
38 PgSetRegion(PtWidgetRid(window));
39 PdOpenGLContextSwapBuffers(oglctx);
40}
41#else
42void ph_GL_SwapBuffers(_THIS)
43{
44 qnxgl_swap_buffers(oglbuffers);
45}
46#endif /* 6.3.0 */
47
48int ph_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value)
49{
50 switch (attrib)
51 {
52 case SDL_GL_DOUBLEBUFFER:
53 *value=this->gl_config.double_buffer;
54 break;
55 case SDL_GL_STENCIL_SIZE:
56 *value=this->gl_config.stencil_size;
57 break;
58 case SDL_GL_DEPTH_SIZE:
59 *value=this->gl_config.depth_size;
60 break;
61#if (_NTO_VERSION >= 630)
62 case SDL_GL_RED_SIZE:
63 *value=this->gl_config.red_size;
64 break;
65 case SDL_GL_GREEN_SIZE:
66 *value=this->gl_config.green_size;
67 break;
68 case SDL_GL_BLUE_SIZE:
69 *value=this->gl_config.blue_size;
70 break;
71 case SDL_GL_ALPHA_SIZE:
72 *value=this->gl_config.alpha_size;
73 break;
74 case SDL_GL_ACCUM_RED_SIZE:
75 *value=this->gl_config.accum_red_size;
76 break;
77 case SDL_GL_ACCUM_GREEN_SIZE:
78 *value=this->gl_config.accum_green_size;
79 break;
80 case SDL_GL_ACCUM_BLUE_SIZE:
81 *value=this->gl_config.accum_blue_size;
82 break;
83 case SDL_GL_ACCUM_ALPHA_SIZE:
84 *value=this->gl_config.accum_alpha_size;
85 break;
86 case SDL_GL_STEREO:
87 *value=this->gl_config.stereo;
88 break;
89#endif /* 6.3.0 */
90 default:
91 *value=0;
92 return(-1);
93 }
94 return 0;
95}
96
97#if (_NTO_VERSION < 630)
98int ph_GL_LoadLibrary(_THIS, const char* path)
99{
100 /* if code compiled with SDL_VIDEO_OPENGL, that mean that library already linked */
101 this->gl_config.driver_loaded = 1;
102
103 return 0;
104}
105#else
106int ph_GL_LoadLibrary(_THIS, const char* path)
107{
108 void* handle;
109 int dlopen_flags=RTLD_WORLD | RTLD_GROUP;
110
111 if (this->gl_config.dll_handle!=NULL)
112 {
113 return 0;
114 }
115
116 handle = dlopen(path, dlopen_flags);
117
118 if (handle==NULL)
119 {
120 SDL_SetError("ph_GL_LoadLibrary(): Could not load OpenGL library");
121 return -1;
122 }
123
124 this->gl_config.dll_handle = handle;
125 this->gl_config.driver_loaded = 1;
126
127 SDL_strlcpy(this->gl_config.driver_path, path, SDL_arraysize(this->gl_config.driver_path));
128
129 return 0;
130}
131#endif /* 6.3.0 */
132
133#if (_NTO_VERSION < 630)
134void* ph_GL_GetProcAddress(_THIS, const char* proc)
135{
136 return NULL;
137}
138#else
139void* ph_GL_GetProcAddress(_THIS, const char* proc)
140{
141 void* function;
142
143 if (this->gl_config.dll_handle==NULL)
144 {
145 ph_GL_LoadLibrary(this, DEFAULT_OPENGL);
146 if (this->gl_config.dll_handle==NULL)
147 {
148 return NULL;
149 }
150 }
151
152 function=qnxgl_get_func(proc, oglctx, 0);
153 if (function==NULL)
154 {
155 function=dlsym(this->gl_config.dll_handle, proc);
156 }
157
158 return function;
159}
160#endif /* 6.3.0 */
161
162#if (_NTO_VERSION < 630)
163int ph_GL_MakeCurrent(_THIS)
164{
165 PgSetRegion(PtWidgetRid(window));
166
167 if (oglctx!=NULL)
168 {
169 PhDCSetCurrent(oglctx);
170 }
171
172 return 0;
173}
174#else
175int ph_GL_MakeCurrent(_THIS)
176{
177 PgSetRegion(PtWidgetRid(window));
178
179 if (oglctx!=NULL)
180 {
181 if (qnxgl_set_current(oglctx) == -1)
182 {
183 return -1;
184 }
185 }
186
187 return 0;
188}
189#endif /* 6.3.0 */
190
191#if (_NTO_VERSION < 630)
192
193/* This code is actual for the Photon3D Runtime which was available prior to 6.3 only */
194
195int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags)
196{
197 PhDim_t dim;
198 uint64_t OGLAttrib[PH_OGL_MAX_ATTRIBS];
199 int exposepost=0;
200 int OGLargc;
201
202 dim.w=width;
203 dim.h=height;
204
205 if ((oglctx!=NULL) && (oglflags==flags) && (oglbpp==bpp))
206 {
207 PdOpenGLContextResize(oglctx, &dim);
208 PhDCSetCurrent(oglctx);
209 return 0;
210 }
211 else
212 {
213 if (oglctx!=NULL)
214 {
215 PhDCSetCurrent(NULL);
216 PhDCRelease(oglctx);
217 oglctx=NULL;
218 exposepost=1;
219 }
220 }
221
222 OGLargc=0;
223 if (this->gl_config.depth_size)
224 {
225 OGLAttrib[OGLargc++]=PHOGL_ATTRIB_DEPTH_BITS;
226 OGLAttrib[OGLargc++]=this->gl_config.depth_size;
227 }
228 if (this->gl_config.stencil_size)
229 {
230 OGLAttrib[OGLargc++]=PHOGL_ATTRIB_STENCIL_BITS;
231 OGLAttrib[OGLargc++]=this->gl_config.stencil_size;
232 }
233 OGLAttrib[OGLargc++]=PHOGL_ATTRIB_FORCE_SW;
234 if (flags & SDL_FULLSCREEN)
235 {
236 OGLAttrib[OGLargc++]=PHOGL_ATTRIB_FULLSCREEN;
237 OGLAttrib[OGLargc++]=PHOGL_ATTRIB_DIRECT;
238 OGLAttrib[OGLargc++]=PHOGL_ATTRIB_FULLSCREEN_BEST;
239 OGLAttrib[OGLargc++]=PHOGL_ATTRIB_FULLSCREEN_CENTER;
240 }
241 OGLAttrib[OGLargc++]=PHOGL_ATTRIB_NONE;
242
243 if (this->gl_config.double_buffer)
244 {
245 oglctx=PdCreateOpenGLContext(2, &dim, 0, OGLAttrib);
246 }
247 else
248 {
249 oglctx=PdCreateOpenGLContext(1, &dim, 0, OGLAttrib);
250 }
251
252 if (oglctx==NULL)
253 {
254 SDL_SetError("ph_SetupOpenGLContext(): cannot create OpenGL context !\n");
255 return -1;
256 }
257
258 PhDCSetCurrent(oglctx);
259
260 PtFlush();
261
262 oglflags=flags;
263 oglbpp=bpp;
264
265 if (exposepost!=0)
266 {
267 /* OpenGL context has been recreated, so report about this fact */
268 SDL_PrivateExpose();
269 }
270
271 return 0;
272}
273
274#else /* _NTO_VERSION */
275
276/* This code is actual for the built-in PhGL support, which became available since 6.3 */
277
278int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags)
279{
280 qnxgl_buf_attrib_t qnxgl_attribs[PH_OGL_MAX_ATTRIBS];
281 qnxgl_buf_attrib_t* qnxgl_attribs_slide;
282 int num_interfaces = 0;
283 int num_buffers = 0;
284
285 /* Initialize the OpenGL subsystem */
286
287 num_interfaces = qnxgl_init(NULL, NULL, 0);
288
289 if (num_interfaces < 0)
290 {
291 SDL_SetError("ph_SetupOpenGLContext(): cannot initialize OpenGL subsystem !\n");
292 return -1;
293 }
294 if (num_interfaces == 0)
295 {
296 SDL_SetError("ph_SetupOpenGLContext(): there are no available OpenGL renderers was found !\n");
297 return -1;
298 }
299
300 /* Driver is linked */
301 this->gl_config.driver_loaded=1;
302
303 /* Initialize the OpenGL context attributes */
304 qnxgl_attribs_slide=qnxgl_attribs;
305
306 /* Depth size */
307 if (this->gl_config.depth_size)
308 {
309 fprintf(stderr, "setted depth size %d\n", this->gl_config.depth_size);
310 qnxgl_attribs_slide = qnxgl_attrib_set_depth(qnxgl_attribs_slide, this->gl_config.depth_size);
311 }
312
313 /* Stencil size */
314 if (this->gl_config.stencil_size)
315 {
316 qnxgl_attribs_slide = qnxgl_attrib_set_stencil(qnxgl_attribs_slide, this->gl_config.stencil_size);
317 }
318
319 /* The sum of the accum bits of each channel */
320 if ((this->gl_config.accum_red_size != 0) && (this->gl_config.accum_blue_size != 0) &&
321 (this->gl_config.accum_green_size != 0))
322 {
323 qnxgl_attribs_slide = qnxgl_attrib_set_accum(qnxgl_attribs_slide,
324 this->gl_config.accum_red_size + this->gl_config.accum_blue_size +
325 this->gl_config.accum_green_size + this->gl_config.accum_alpha_size);
326 }
327
328 /* Stereo mode */
329 if (this->gl_config.stereo)
330 {
331 qnxgl_attribs_slide = qnxgl_attrib_set_stereo(qnxgl_attribs_slide);
332 }
333
334 /* Fullscreen mode */
335 if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)
336 {
337 qnxgl_attribs_slide = qnxgl_attrib_set_hint_fullscreen(qnxgl_attribs_slide);
338 }
339
340 /* Double buffering mode */
341 if (this->gl_config.double_buffer)
342 {
343 num_buffers=2;
344 }
345 else
346 {
347 num_buffers=1;
348 }
349
350 /* Loading the function pointers so we can use the extensions */
351 GLPH_LOAD_FUNCS_GC(oglctx);
352
353 /* Set the buffers region to be that of our window's region */
354 qnxgl_attribs_slide = glph_attrib_set_region(qnxgl_attribs_slide, PtWidgetRid(window));
355
356 /* End of the attributes array */
357 qnxgl_attribs_slide = qnxgl_attrib_set_end(qnxgl_attribs_slide);
358
359 /* Create the buffers with the specified color model */
360 fprintf(stderr, "ARGB: %d, %d, %d, %d\n", this->gl_config.alpha_size, this->gl_config.red_size, this->gl_config.green_size, this->gl_config.blue_size);
361 oglbuffers = qnxgl_buffers_create(
362 QNXGL_FORMAT_BEST_RGB,
363/* __QNXGL_BUILD_FORMAT(0, __QNXGL_COLOR_MODEL_RGB, this->gl_config.alpha_size,
364 this->gl_config.red_size, this->gl_config.green_size, this->gl_config.blue_size), */
365 num_buffers, width, height, qnxgl_attribs, -1);
366
367
368 if (oglbuffers == NULL)
369 {
370 SDL_SetError("ph_SetupOpenGLContext(): failed to create OpenGL buffers !\n");
371 qnxgl_finish();
372 return -1;
373 }
374
375 /* Create a QNXGL context for the previously created buffer */
376 oglctx = qnxgl_context_create(oglbuffers, NULL);
377
378 if (oglctx == NULL)
379 {
380 SDL_SetError("ph_SetupOpenGLContext(): failed to create OpenGL context !\n");
381 qnxgl_buffers_destroy(oglbuffers);
382 qnxgl_finish();
383 return -1;
384 }
385
386 /* Attempt to make the context current so we can use OpenGL commands */
387 if (qnxgl_set_current(oglctx) == -1)
388 {
389 SDL_SetError("ph_SetupOpenGLContext(): failed to make the OpenGL context current !\n");
390 qnxgl_context_destroy(oglctx);
391 qnxgl_buffers_destroy(oglbuffers);
392 qnxgl_finish();
393 return -1;
394 }
395
396 PtFlush();
397
398 oglflags=flags;
399 oglbpp=bpp;
400
401 return 0;
402}
403
404#endif /* _NTO_VERSION */
405
406#endif /* SDL_VIDEO_OPENGL */
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_gl.h b/apps/plugins/sdl/src/video/photon/SDL_ph_gl.h
deleted file mode 100644
index 1fb134abf3..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_gl.h
+++ /dev/null
@@ -1,41 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SDL_PH_GL_H__
25#define __SDL_PH_GL_H__
26
27#include "SDL_ph_video.h"
28
29#define DEFAULT_OPENGL "/usr/lib/libGL.so"
30
31#if SDL_VIDEO_OPENGL
32 void ph_GL_SwapBuffers(_THIS);
33 int ph_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value);
34 int ph_GL_LoadLibrary(_THIS, const char* path);
35 void* ph_GL_GetProcAddress(_THIS, const char* proc);
36 int ph_GL_MakeCurrent(_THIS);
37
38 int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags);
39#endif /* SDL_VIDEO_OPENGL */
40
41#endif /* __SDL_PH_GL_H__ */
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_image.c b/apps/plugins/sdl/src/video/photon/SDL_ph_image.c
deleted file mode 100644
index 7d64970ce6..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_image.c
+++ /dev/null
@@ -1,1059 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <Ph.h>
25#include <photon/Pg.h>
26
27#include "SDL_endian.h"
28#include "SDL_video.h"
29#include "../SDL_pixels_c.h"
30#include "SDL_ph_video.h"
31#include "SDL_ph_image_c.h"
32#include "SDL_ph_modes_c.h"
33#include "SDL_ph_gl.h"
34
35int ph_SetupImage(_THIS, SDL_Surface *screen)
36{
37 PgColor_t* palette=NULL;
38 int type=0;
39 int bpp;
40
41 bpp=screen->format->BitsPerPixel;
42
43 /* Determine image type */
44 switch(bpp)
45 {
46 case 8:{
47 type = Pg_IMAGE_PALETTE_BYTE;
48 }
49 break;
50 case 15:{
51 type = Pg_IMAGE_DIRECT_555;
52 }
53 break;
54 case 16:{
55 type = Pg_IMAGE_DIRECT_565;
56 }
57 break;
58 case 24:{
59 type = Pg_IMAGE_DIRECT_888;
60 }
61 break;
62 case 32:{
63 type = Pg_IMAGE_DIRECT_8888;
64 }
65 break;
66 default:{
67 SDL_SetError("ph_SetupImage(): unsupported bpp=%d !\n", bpp);
68 return -1;
69 }
70 break;
71 }
72
73 /* palette emulation code */
74 if ((bpp==8) && (desktoppal==SDLPH_PAL_EMULATE))
75 {
76 /* creating image palette */
77 palette=SDL_malloc(_Pg_MAX_PALETTE*sizeof(PgColor_t));
78 if (palette==NULL)
79 {
80 SDL_SetError("ph_SetupImage(): can't allocate memory for palette !\n");
81 return -1;
82 }
83 PgGetPalette(palette);
84
85 /* using shared memory for speed (set last param to 1) */
86 if ((SDL_Image = PhCreateImage(NULL, screen->w, screen->h, type, palette, _Pg_MAX_PALETTE, 1)) == NULL)
87 {
88 SDL_SetError("ph_SetupImage(): PhCreateImage() failed for bpp=8 !\n");
89 SDL_free(palette);
90 return -1;
91 }
92 }
93 else
94 {
95 /* using shared memory for speed (set last param to 1) */
96 if ((SDL_Image = PhCreateImage(NULL, screen->w, screen->h, type, NULL, 0, 1)) == NULL)
97 {
98 SDL_SetError("ph_SetupImage(): PhCreateImage() failed for bpp=%d !\n", bpp);
99 return -1;
100 }
101 }
102
103 screen->pixels = SDL_Image->image;
104 screen->pitch = SDL_Image->bpl;
105
106 this->UpdateRects = ph_NormalUpdate;
107
108 return 0;
109}
110
111int ph_SetupOCImage(_THIS, SDL_Surface *screen)
112{
113 int type = 0;
114 int bpp;
115
116 OCImage.flags = screen->flags;
117
118 bpp=screen->format->BitsPerPixel;
119
120 /* Determine image type */
121 switch(bpp)
122 {
123 case 8: {
124 type = Pg_IMAGE_PALETTE_BYTE;
125 }
126 break;
127 case 15:{
128 type = Pg_IMAGE_DIRECT_555;
129 }
130 break;
131 case 16:{
132 type = Pg_IMAGE_DIRECT_565;
133 }
134 break;
135 case 24:{
136 type = Pg_IMAGE_DIRECT_888;
137 }
138 break;
139 case 32:{
140 type = Pg_IMAGE_DIRECT_8888;
141 }
142 break;
143 default:{
144 SDL_SetError("ph_SetupOCImage(): unsupported bpp=%d !\n", bpp);
145 return -1;
146 }
147 break;
148 }
149
150 /* Currently offscreen contexts with the same bit depth as display bpp only can be created */
151 OCImage.offscreen_context = PdCreateOffscreenContext(0, screen->w, screen->h, Pg_OSC_MEM_PAGE_ALIGN);
152
153 if (OCImage.offscreen_context == NULL)
154 {
155 SDL_SetError("ph_SetupOCImage(): PdCreateOffscreenContext() function failed !\n");
156 return -1;
157 }
158
159 screen->pitch = OCImage.offscreen_context->pitch;
160
161 OCImage.dc_ptr = (unsigned char *)PdGetOffscreenContextPtr(OCImage.offscreen_context);
162
163 if (OCImage.dc_ptr == NULL)
164 {
165 SDL_SetError("ph_SetupOCImage(): PdGetOffscreenContextPtr function failed !\n");
166 PhDCRelease(OCImage.offscreen_context);
167 return -1;
168 }
169
170 OCImage.FrameData0 = OCImage.dc_ptr;
171 OCImage.CurrentFrameData = OCImage.FrameData0;
172 OCImage.current = 0;
173
174 PhDCSetCurrent(OCImage.offscreen_context);
175
176 screen->pixels = OCImage.CurrentFrameData;
177
178 this->UpdateRects = ph_OCUpdate;
179
180 return 0;
181}
182
183int ph_SetupFullScreenImage(_THIS, SDL_Surface* screen)
184{
185 OCImage.flags = screen->flags;
186
187 /* Begin direct and fullscreen mode */
188 if (!ph_EnterFullScreen(this, screen, PH_ENTER_DIRECTMODE))
189 {
190 return -1;
191 }
192
193 /* store palette for fullscreen */
194 if ((screen->format->BitsPerPixel==8) && (desktopbpp!=8))
195 {
196 PgGetPalette(savedpal);
197 PgGetPalette(syspalph);
198 }
199
200 OCImage.offscreen_context = PdCreateOffscreenContext(0, 0, 0, Pg_OSC_MAIN_DISPLAY | Pg_OSC_MEM_PAGE_ALIGN | Pg_OSC_CRTC_SAFE);
201 if (OCImage.offscreen_context == NULL)
202 {
203 SDL_SetError("ph_SetupFullScreenImage(): PdCreateOffscreenContext() function failed !\n");
204 return -1;
205 }
206
207 if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF)
208 {
209 OCImage.offscreen_backcontext = PdDupOffscreenContext(OCImage.offscreen_context, Pg_OSC_MEM_PAGE_ALIGN | Pg_OSC_CRTC_SAFE);
210 if (OCImage.offscreen_backcontext == NULL)
211 {
212 SDL_SetError("ph_SetupFullScreenImage(): PdCreateOffscreenContext(back) function failed !\n");
213 return -1;
214 }
215 }
216
217 OCImage.FrameData0 = (unsigned char *)PdGetOffscreenContextPtr(OCImage.offscreen_context);
218 if (OCImage.FrameData0 == NULL)
219 {
220 SDL_SetError("ph_SetupFullScreenImage(): PdGetOffscreenContextPtr() function failed !\n");
221 ph_DestroyImage(this, screen);
222 return -1;
223 }
224
225 if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF)
226 {
227 OCImage.FrameData1 = (unsigned char *)PdGetOffscreenContextPtr(OCImage.offscreen_backcontext);
228 if (OCImage.FrameData1 == NULL)
229 {
230 SDL_SetError("ph_SetupFullScreenImage(back): PdGetOffscreenContextPtr() function failed !\n");
231 ph_DestroyImage(this, screen);
232 return -1;
233 }
234 }
235
236 /* wait for the hardware */
237 PgFlush();
238 PgWaitHWIdle();
239
240 if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF)
241 {
242 OCImage.current = 0;
243 PhDCSetCurrent(OCImage.offscreen_context);
244 screen->pitch = OCImage.offscreen_context->pitch;
245 screen->pixels = OCImage.FrameData0;
246
247 /* emulate 640x400 videomode */
248 if (videomode_emulatemode==1)
249 {
250 int i;
251
252 for (i=0; i<40; i++)
253 {
254 SDL_memset(screen->pixels+screen->pitch*i, 0x00, screen->pitch);
255 }
256 for (i=440; i<480; i++)
257 {
258 SDL_memset(screen->pixels+screen->pitch*i, 0x00, screen->pitch);
259 }
260 screen->pixels+=screen->pitch*40;
261 }
262 PgSwapDisplay(OCImage.offscreen_backcontext, 0);
263 }
264 else
265 {
266 OCImage.current = 0;
267 PhDCSetCurrent(OCImage.offscreen_context);
268 screen->pitch = OCImage.offscreen_context->pitch;
269 screen->pixels = OCImage.FrameData0;
270
271 /* emulate 640x400 videomode */
272 if (videomode_emulatemode==1)
273 {
274 int i;
275
276 for (i=0; i<40; i++)
277 {
278 SDL_memset(screen->pixels+screen->pitch*i, 0x00, screen->pitch);
279 }
280 for (i=440; i<480; i++)
281 {
282 SDL_memset(screen->pixels+screen->pitch*i, 0x00, screen->pitch);
283 }
284 screen->pixels+=screen->pitch*40;
285 }
286 }
287
288 this->UpdateRects = ph_OCDCUpdate;
289
290 /* wait for the hardware */
291 PgFlush();
292 PgWaitHWIdle();
293
294 return 0;
295}
296
297#if SDL_VIDEO_OPENGL
298
299int ph_SetupOpenGLImage(_THIS, SDL_Surface* screen)
300{
301 this->UpdateRects = ph_OpenGLUpdate;
302 screen->pixels=NULL;
303 screen->pitch=NULL;
304
305 #if (_NTO_VERSION >= 630)
306 if ((screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)
307 {
308 if (!ph_EnterFullScreen(this, screen, PH_IGNORE_DIRECTMODE))
309 {
310 screen->flags &= ~SDL_FULLSCREEN;
311 return -1;
312 }
313 }
314 #endif /* 6.3.0 */
315
316 if (ph_SetupOpenGLContext(this, screen->w, screen->h, screen->format->BitsPerPixel, screen->flags)!=0)
317 {
318 screen->flags &= ~SDL_OPENGL;
319 return -1;
320 }
321
322 return 0;
323}
324
325#endif /* SDL_VIDEO_OPENGL */
326
327void ph_DestroyImage(_THIS, SDL_Surface* screen)
328{
329
330#if SDL_VIDEO_OPENGL
331 if ((screen->flags & SDL_OPENGL)==SDL_OPENGL)
332 {
333 if (oglctx)
334 {
335 #if (_NTO_VERSION < 630)
336 PhDCSetCurrent(NULL);
337 PhDCRelease(oglctx);
338 #else
339 qnxgl_context_destroy(oglctx);
340 qnxgl_buffers_destroy(oglbuffers);
341 qnxgl_finish();
342 #endif /* 6.3.0 */
343 oglctx=NULL;
344 oglbuffers=NULL;
345 oglflags=0;
346 oglbpp=0;
347 }
348
349 #if (_NTO_VERSION >= 630)
350 if (currently_fullscreen)
351 {
352 ph_LeaveFullScreen(this);
353 }
354 #endif /* 6.3.0 */
355
356 return;
357 }
358#endif /* SDL_VIDEO_OPENGL */
359
360 if (currently_fullscreen)
361 {
362 /* if we right now in 8bpp fullscreen we must release palette */
363 if ((screen->format->BitsPerPixel==8) && (desktopbpp!=8))
364 {
365 PgSetPalette(syspalph, 0, -1, 0, 0, 0);
366 PgSetPalette(savedpal, 0, 0, _Pg_MAX_PALETTE, Pg_PALSET_GLOBAL | Pg_PALSET_FORCE_EXPOSE, 0);
367 PgFlush();
368 }
369 ph_LeaveFullScreen(this);
370 }
371
372 if (OCImage.offscreen_context != NULL)
373 {
374 PhDCRelease(OCImage.offscreen_context);
375 OCImage.offscreen_context = NULL;
376 OCImage.FrameData0 = NULL;
377 }
378 if (OCImage.offscreen_backcontext != NULL)
379 {
380 PhDCRelease(OCImage.offscreen_backcontext);
381 OCImage.offscreen_backcontext = NULL;
382 OCImage.FrameData1 = NULL;
383 }
384 OCImage.CurrentFrameData = NULL;
385
386 if (SDL_Image)
387 {
388 /* if palette allocated, free it */
389 if (SDL_Image->palette)
390 {
391 SDL_free(SDL_Image->palette);
392 }
393 PgShmemDestroy(SDL_Image->image);
394 SDL_free(SDL_Image);
395 }
396
397 /* Must be zeroed everytime */
398 SDL_Image = NULL;
399
400 if (screen)
401 {
402 screen->pixels = NULL;
403 }
404}
405
406int ph_UpdateHWInfo(_THIS)
407{
408 PgVideoModeInfo_t vmode;
409 PgHWCaps_t hwcaps;
410
411 /* Update video ram amount */
412 if (PgGetGraphicsHWCaps(&hwcaps) < 0)
413 {
414 SDL_SetError("ph_UpdateHWInfo(): GetGraphicsHWCaps() function failed !\n");
415 return -1;
416 }
417 this->info.video_mem=hwcaps.currently_available_video_ram/1024;
418
419 /* obtain current mode capabilities */
420 if (PgGetVideoModeInfo(hwcaps.current_video_mode, &vmode) < 0)
421 {
422 SDL_SetError("ph_UpdateHWInfo(): GetVideoModeInfo() function failed !\n");
423 return -1;
424 }
425
426 if ((vmode.mode_capabilities1 & PgVM_MODE_CAP1_OFFSCREEN) == PgVM_MODE_CAP1_OFFSCREEN)
427 {
428 /* this is a special test for drivers which tries to lie about offscreen capability */
429 if (hwcaps.currently_available_video_ram!=0)
430 {
431 this->info.hw_available = 1;
432 }
433 else
434 {
435 this->info.hw_available = 0;
436 }
437 }
438 else
439 {
440 this->info.hw_available = 0;
441 }
442
443 if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_RECTANGLE) == PgVM_MODE_CAP2_RECTANGLE)
444 {
445 this->info.blit_fill = 1;
446 }
447 else
448 {
449 this->info.blit_fill = 0;
450 }
451
452 if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_BITBLT) == PgVM_MODE_CAP2_BITBLT)
453 {
454 this->info.blit_hw = 1;
455 }
456 else
457 {
458 this->info.blit_hw = 0;
459 }
460
461 if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_ALPHA_BLEND) == PgVM_MODE_CAP2_ALPHA_BLEND)
462 {
463 this->info.blit_hw_A = 1;
464 }
465 else
466 {
467 this->info.blit_hw_A = 0;
468 }
469
470 if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_CHROMA) == PgVM_MODE_CAP2_CHROMA)
471 {
472 this->info.blit_hw_CC = 1;
473 }
474 else
475 {
476 this->info.blit_hw_CC = 0;
477 }
478
479 return 0;
480}
481
482int ph_SetupUpdateFunction(_THIS, SDL_Surface* screen, Uint32 flags)
483{
484 int setupresult=-1;
485
486 ph_DestroyImage(this, screen);
487
488#if SDL_VIDEO_OPENGL
489 if ((flags & SDL_OPENGL)==SDL_OPENGL)
490 {
491 setupresult=ph_SetupOpenGLImage(this, screen);
492 }
493 else
494 {
495#endif
496 if ((flags & SDL_FULLSCREEN)==SDL_FULLSCREEN)
497 {
498 setupresult=ph_SetupFullScreenImage(this, screen);
499 }
500 else
501 {
502 if ((flags & SDL_HWSURFACE)==SDL_HWSURFACE)
503 {
504 setupresult=ph_SetupOCImage(this, screen);
505 }
506 else
507 {
508 setupresult=ph_SetupImage(this, screen);
509 }
510 }
511#if SDL_VIDEO_OPENGL
512 }
513#endif
514 if (setupresult!=-1)
515 {
516 ph_UpdateHWInfo(this);
517 }
518
519 return setupresult;
520}
521
522int ph_AllocHWSurface(_THIS, SDL_Surface* surface)
523{
524 PgHWCaps_t hwcaps;
525
526 if (surface->hwdata!=NULL)
527 {
528 SDL_SetError("ph_AllocHWSurface(): hwdata already exists!\n");
529 return -1;
530 }
531 surface->hwdata=SDL_malloc(sizeof(struct private_hwdata));
532 SDL_memset(surface->hwdata, 0x00, sizeof(struct private_hwdata));
533 surface->hwdata->offscreenctx=PdCreateOffscreenContext(0, surface->w, surface->h, Pg_OSC_MEM_PAGE_ALIGN);
534 if (surface->hwdata->offscreenctx == NULL)
535 {
536 SDL_SetError("ph_AllocHWSurface(): PdCreateOffscreenContext() function failed !\n");
537 return -1;
538 }
539 surface->pixels=PdGetOffscreenContextPtr(surface->hwdata->offscreenctx);
540 if (surface->pixels==NULL)
541 {
542 PhDCRelease(surface->hwdata->offscreenctx);
543 SDL_SetError("ph_AllocHWSurface(): PdGetOffscreenContextPtr() function failed !\n");
544 return -1;
545 }
546 surface->pitch=surface->hwdata->offscreenctx->pitch;
547 surface->flags|=SDL_HWSURFACE;
548 surface->flags|=SDL_PREALLOC;
549
550#if 0 /* FIXME */
551 /* create simple offscreen lock */
552 surface->hwdata->crlockparam.flags=0;
553 if (PdCreateOffscreenLock(surface->hwdata->offscreenctx, &surface->hwdata->crlockparam)!=EOK)
554 {
555 PhDCRelease(surface->hwdata->offscreenctx);
556 SDL_SetError("ph_AllocHWSurface(): Can't create offscreen lock !\n");
557 return -1;
558 }
559#endif /* 0 */
560
561 /* Update video ram amount */
562 if (PgGetGraphicsHWCaps(&hwcaps) < 0)
563 {
564 PdDestroyOffscreenLock(surface->hwdata->offscreenctx);
565 PhDCRelease(surface->hwdata->offscreenctx);
566 SDL_SetError("ph_AllocHWSurface(): GetGraphicsHWCaps() function failed !\n");
567 return -1;
568 }
569 this->info.video_mem=hwcaps.currently_available_video_ram/1024;
570
571 return 0;
572}
573
574void ph_FreeHWSurface(_THIS, SDL_Surface* surface)
575{
576 PgHWCaps_t hwcaps;
577
578 if (surface->hwdata==NULL)
579 {
580 SDL_SetError("ph_FreeHWSurface(): no hwdata!\n");
581 return;
582 }
583 if (surface->hwdata->offscreenctx == NULL)
584 {
585 SDL_SetError("ph_FreeHWSurface(): no offscreen context to delete!\n");
586 return;
587 }
588
589#if 0 /* FIXME */
590 /* unlock the offscreen context if it has been locked before destroy it */
591 if (PdIsOffscreenLocked(surface->hwdata->offscreenctx)==Pg_OSC_LOCKED)
592 {
593 PdUnlockOffscreen(surface->hwdata->offscreenctx);
594 }
595
596 PdDestroyOffscreenLock(surface->hwdata->offscreenctx);
597#endif /* 0 */
598
599 PhDCRelease(surface->hwdata->offscreenctx);
600
601 SDL_free(surface->hwdata);
602 surface->hwdata=NULL;
603
604 /* Update video ram amount */
605 if (PgGetGraphicsHWCaps(&hwcaps) < 0)
606 {
607 SDL_SetError("ph_FreeHWSurface(): GetGraphicsHWCaps() function failed !\n");
608 return;
609 }
610 this->info.video_mem=hwcaps.currently_available_video_ram/1024;
611
612 return;
613}
614
615int ph_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst)
616{
617 if ((src->hwdata==NULL) && (src != this->screen))
618 {
619 SDL_SetError("ph_CheckHWBlit(): Source surface haven't hardware specific data.\n");
620 src->flags&=~SDL_HWACCEL;
621 return -1;
622 }
623 if ((src->flags & SDL_HWSURFACE) != SDL_HWSURFACE)
624 {
625 SDL_SetError("ph_CheckHWBlit(): Source surface isn't a hardware surface.\n");
626 src->flags&=~SDL_HWACCEL;
627 return -1;
628 }
629
630 if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY)
631 {
632 if (this->info.blit_hw_CC!=1)
633 {
634 src->flags&=~SDL_HWACCEL;
635 src->map->hw_blit=NULL;
636 return -1;
637 }
638 }
639
640 if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA)
641 {
642 if (this->info.blit_hw_A!=1)
643 {
644 src->flags&=~SDL_HWACCEL;
645 src->map->hw_blit=NULL;
646 return -1;
647 }
648 }
649
650 src->flags|=SDL_HWACCEL;
651 src->map->hw_blit = ph_HWAccelBlit;
652
653 return 1;
654}
655
656PgColor_t ph_ExpandColor(_THIS, SDL_Surface* surface, Uint32 color)
657{
658 Uint32 truecolor;
659
660 /* Photon API accepts true colors only during hw filling operations */
661 switch(surface->format->BitsPerPixel)
662 {
663 case 8:
664 {
665 if ((surface->format->palette) && (color<=surface->format->palette->ncolors))
666 {
667 truecolor=PgRGB(surface->format->palette->colors[color].r,
668 surface->format->palette->colors[color].g,
669 surface->format->palette->colors[color].b);
670 }
671 else
672 {
673 SDL_SetError("ph_ExpandColor(): Color out of range for the 8bpp mode !\n");
674 return 0xFFFFFFFFUL;
675 }
676 }
677 break;
678 case 15:
679 {
680 truecolor = ((color & 0x00007C00UL) << 9) | /* R */
681 ((color & 0x000003E0UL) << 6) | /* G */
682 ((color & 0x0000001FUL) << 3) | /* B */
683 ((color & 0x00007000UL) << 4) | /* R compensation */
684 ((color & 0x00000380UL) << 1) | /* G compensation */
685 ((color & 0x0000001CUL) >> 2); /* B compensation */
686 }
687 break;
688 case 16:
689 {
690 truecolor = ((color & 0x0000F800UL) << 8) | /* R */
691 ((color & 0x000007E0UL) << 5) | /* G */
692 ((color & 0x0000001FUL) << 3) | /* B */
693 ((color & 0x0000E000UL) << 3) | /* R compensation */
694 ((color & 0x00000600UL) >> 1) | /* G compensation */
695 ((color & 0x0000001CUL) >> 2); /* B compensation */
696
697 }
698 break;
699 case 24:
700 {
701 truecolor=color & 0x00FFFFFFUL;
702 }
703 break;
704 case 32:
705 {
706 truecolor=color;
707 }
708 break;
709 default:
710 {
711 SDL_SetError("ph_ExpandColor(): Unsupported depth for the hardware operations !\n");
712 return 0xFFFFFFFFUL;
713 }
714 }
715
716 return truecolor;
717}
718
719int ph_FillHWRect(_THIS, SDL_Surface* surface, SDL_Rect* rect, Uint32 color)
720{
721 PgColor_t oldcolor;
722 Uint32 truecolor;
723 int ydisp=0;
724
725 if (this->info.blit_fill!=1)
726 {
727 return -1;
728 }
729
730 truecolor=ph_ExpandColor(this, surface, color);
731 if (truecolor==0xFFFFFFFFUL)
732 {
733 return -1;
734 }
735
736 oldcolor=PgSetFillColor(truecolor);
737
738 /* 640x400 videomode emulation */
739 if (videomode_emulatemode==1)
740 {
741 ydisp+=40;
742 }
743
744 PgDrawIRect(rect->x, rect->y+ydisp, rect->w+rect->x-1, rect->h+rect->y+ydisp-1, Pg_DRAW_FILL);
745 PgSetFillColor(oldcolor);
746 PgFlush();
747 PgWaitHWIdle();
748
749 return 0;
750}
751
752int ph_FlipHWSurface(_THIS, SDL_Surface* screen)
753{
754 PhArea_t farea;
755
756 if ((screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)
757 {
758 /* flush all drawing ops before blitting */
759 PgFlush();
760 PgWaitHWIdle();
761
762 farea.pos.x=0;
763 farea.pos.y=0;
764 farea.size.w=screen->w;
765 farea.size.h=screen->h;
766
767 /* emulate 640x400 videomode */
768 if (videomode_emulatemode==1)
769 {
770 farea.pos.y+=40;
771 }
772
773 PgContextBlitArea(OCImage.offscreen_context, &farea, OCImage.offscreen_backcontext, &farea);
774
775 /* flush the blitting */
776 PgFlush();
777 PgWaitHWIdle();
778 }
779 return 0;
780}
781
782int ph_LockHWSurface(_THIS, SDL_Surface* surface)
783{
784
785#if 0 /* FIXME */
786 int lockresult;
787
788 if (surface->hwdata == NULL)
789 {
790 return;
791 }
792
793 surface->hwdata->lockparam.flags=0;
794 surface->hwdata->lockparam.time_out=NULL;
795 lockresult=PdLockOffscreen(surface->hwdata->offscreenctx, &surface->hwdata->lockparam);
796
797 switch (lockresult)
798 {
799 case EOK:
800 break;
801 case Pg_OSC_LOCK_DEADLOCK:
802 SDL_SetError("ph_LockHWSurface(): Deadlock detected !\n");
803 return -1;
804 case Pg_OSC_LOCK_INVALID:
805 SDL_SetError("ph_LockHWSurface(): Lock invalid !\n");
806 return -1;
807 default:
808 SDL_SetError("ph_LockHWSurface(): Can't lock the surface !\n");
809 return -1;
810 }
811#endif /* 0 */
812
813 return 0;
814}
815
816void ph_UnlockHWSurface(_THIS, SDL_Surface* surface)
817{
818
819#if 0 /* FIXME */
820 int unlockresult;
821
822 if ((surface == NULL) || (surface->hwdata == NULL))
823 {
824 return;
825 }
826
827 if (PdIsOffscreenLocked(surface->hwdata->offscreenctx)==Pg_OSC_LOCKED)
828 {
829 unlockresult=PdUnlockOffscreen(surface->hwdata->offscreenctx);
830 }
831#endif /* 0 */
832
833 return;
834}
835
836int ph_HWAccelBlit(SDL_Surface* src, SDL_Rect* srcrect, SDL_Surface* dst, SDL_Rect* dstrect)
837{
838 SDL_VideoDevice* this=current_video;
839 PhArea_t srcarea;
840 PhArea_t dstarea;
841 int ydisp=0;
842
843 /* 640x400 videomode emulation */
844 if (videomode_emulatemode==1)
845 {
846 ydisp+=40;
847 }
848
849 srcarea.pos.x=srcrect->x;
850 srcarea.pos.y=srcrect->y;
851 srcarea.size.w=srcrect->w;
852 srcarea.size.h=srcrect->h;
853
854 dstarea.pos.x=dstrect->x;
855 dstarea.pos.y=dstrect->y;
856 dstarea.size.w=dstrect->w;
857 dstarea.size.h=dstrect->h;
858
859 if (((src == this->screen) || (src->hwdata!=NULL)) && ((dst == this->screen) || (dst->hwdata!=NULL)))
860 {
861 if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY)
862 {
863 ph_SetHWColorKey(this, src, src->format->colorkey);
864 PgChromaOn();
865 }
866
867 if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA)
868 {
869 ph_SetHWAlpha(this, src, src->format->alpha);
870 PgAlphaOn();
871 }
872
873 if (dst == this->screen)
874 {
875 if (src == this->screen)
876 {
877 /* blitting from main screen to main screen */
878 dstarea.pos.y+=ydisp;
879 srcarea.pos.y+=ydisp;
880 PgContextBlitArea(OCImage.offscreen_context, &srcarea, OCImage.offscreen_context, &dstarea);
881 }
882 else
883 {
884 /* blitting from offscreen to main screen */
885 dstarea.pos.y+=ydisp;
886 PgContextBlitArea(src->hwdata->offscreenctx, &srcarea, OCImage.offscreen_context, &dstarea);
887 }
888 }
889 else
890 {
891 if (src == this->screen)
892 {
893 /* blitting from main screen to offscreen */
894 srcarea.pos.y+=ydisp;
895 PgContextBlitArea(OCImage.offscreen_context, &srcarea, dst->hwdata->offscreenctx, &dstarea);
896 }
897 else
898 {
899 /* blitting offscreen to offscreen */
900 PgContextBlitArea(src->hwdata->offscreenctx, &srcarea, dst->hwdata->offscreenctx, &dstarea);
901 }
902 }
903
904 if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA)
905 {
906 PgAlphaOff();
907 }
908
909 if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY)
910 {
911 PgChromaOff();
912 }
913 }
914 else
915 {
916 SDL_SetError("ph_HWAccelBlit(): Source or target surface is not a hardware surface !\n");
917 return -1;
918 }
919
920 PgFlush();
921 PgWaitHWIdle();
922
923 return 0;
924}
925
926int ph_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key)
927{
928 if (this->info.blit_hw_CC!=1)
929 {
930 return -1;
931 }
932
933 if (surface->hwdata!=NULL)
934 {
935 surface->hwdata->colorkey=ph_ExpandColor(this, surface, key);
936 if (surface->hwdata->colorkey==0xFFFFFFFFUL)
937 {
938 return -1;
939 }
940 }
941 PgSetChroma(surface->hwdata->colorkey, Pg_CHROMA_SRC_MATCH | Pg_CHROMA_NODRAW);
942
943 return 0;
944}
945
946int ph_SetHWAlpha(_THIS, SDL_Surface* surface, Uint8 alpha)
947{
948 if (this->info.blit_hw_A!=1)
949 {
950 return -1;
951 }
952
953 PgSetAlphaBlend(NULL, alpha);
954
955 return 0;
956}
957
958#if SDL_VIDEO_OPENGL
959void ph_OpenGLUpdate(_THIS, int numrects, SDL_Rect* rects)
960{
961 this->GL_SwapBuffers(this);
962
963 return;
964}
965#endif /* SDL_VIDEO_OPENGL */
966
967void ph_NormalUpdate(_THIS, int numrects, SDL_Rect *rects)
968{
969 PhPoint_t ph_pos;
970 PhRect_t ph_rect;
971 int i;
972
973 for (i=0; i<numrects; ++i)
974 {
975 if (rects[i].w==0) /* Clipped? dunno why but this occurs sometime. */
976 {
977 continue;
978 }
979
980 if (rects[i].h==0) /* Clipped? dunno why but this occurs sometime. */
981 {
982 continue;
983 }
984
985 ph_pos.x = rects[i].x;
986 ph_pos.y = rects[i].y;
987 ph_rect.ul.x = rects[i].x;
988 ph_rect.ul.y = rects[i].y;
989 ph_rect.lr.x = rects[i].x + rects[i].w;
990 ph_rect.lr.y = rects[i].y + rects[i].h;
991
992 if (PgDrawPhImageRectmx(&ph_pos, SDL_Image, &ph_rect, 0) < 0)
993 {
994 SDL_SetError("ph_NormalUpdate(): PgDrawPhImageRectmx failed!\n");
995 return;
996 }
997 }
998
999 if (PgFlush() < 0)
1000 {
1001 SDL_SetError("ph_NormalUpdate(): PgFlush() function failed!\n");
1002 }
1003}
1004
1005void ph_OCUpdate(_THIS, int numrects, SDL_Rect *rects)
1006{
1007 int i;
1008
1009 PhPoint_t zero = {0, 0};
1010 PhArea_t src_rect;
1011 PhArea_t dest_rect;
1012
1013 PgSetTranslation(&zero, 0);
1014 PgSetRegion(PtWidgetRid(window));
1015 PgSetClipping(0, NULL);
1016
1017 PgFlush();
1018 PgWaitHWIdle();
1019
1020 for (i=0; i<numrects; ++i)
1021 {
1022 if (rects[i].w == 0) /* Clipped? */
1023 {
1024 continue;
1025 }
1026
1027 if (rects[i].h == 0) /* Clipped? */
1028 {
1029 continue;
1030 }
1031
1032 src_rect.pos.x=rects[i].x;
1033 src_rect.pos.y=rects[i].y;
1034 dest_rect.pos.x=rects[i].x;
1035 dest_rect.pos.y=rects[i].y;
1036
1037 src_rect.size.w=rects[i].w;
1038 src_rect.size.h=rects[i].h;
1039 dest_rect.size.w=rects[i].w;
1040 dest_rect.size.h=rects[i].h;
1041
1042 PgContextBlitArea(OCImage.offscreen_context, &src_rect, NULL, &dest_rect);
1043 }
1044
1045 if (PgFlush() < 0)
1046 {
1047 SDL_SetError("ph_OCUpdate(): PgFlush failed.\n");
1048 }
1049}
1050
1051void ph_OCDCUpdate(_THIS, int numrects, SDL_Rect *rects)
1052{
1053 PgWaitHWIdle();
1054
1055 if (PgFlush() < 0)
1056 {
1057 SDL_SetError("ph_OCDCUpdate(): PgFlush failed.\n");
1058 }
1059}
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_image_c.h b/apps/plugins/sdl/src/video/photon/SDL_ph_image_c.h
deleted file mode 100644
index cfd96698c4..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_image_c.h
+++ /dev/null
@@ -1,59 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SDL_PH_IMAGE_H__
25#define __SDL_PH_IMAGE_H__
26
27#include "../../events/SDL_events_c.h"
28#include "SDL_ph_video.h"
29
30struct private_hwdata
31{
32 PdOffscreenContext_t* offscreenctx;
33 PdOSCCreateLockParams_t crlockparam;
34 PdOSCLockParams_t lockparam;
35 Uint32 colorkey;
36};
37
38extern int ph_SetupImage(_THIS, SDL_Surface* screen);
39extern void ph_DestroyImage(_THIS, SDL_Surface* screen);
40extern int ph_SetupUpdateFunction(_THIS, SDL_Surface* screen, Uint32 flags);
41
42extern int ph_AllocHWSurface(_THIS, SDL_Surface* surface);
43extern void ph_FreeHWSurface(_THIS, SDL_Surface* surface);
44extern int ph_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst);
45extern int ph_FillHWRect(_THIS, SDL_Surface* surface, SDL_Rect* rect, Uint32 color);
46extern int ph_LockHWSurface(_THIS, SDL_Surface* surface);
47extern void ph_UnlockHWSurface(_THIS, SDL_Surface* surface);
48extern int ph_FlipHWSurface(_THIS, SDL_Surface* surface);
49extern int ph_SetHWColorKey(_THIS, SDL_Surface* surface, Uint32 key);
50extern int ph_SetHWAlpha(_THIS, SDL_Surface* surface, Uint8 alpha);
51extern int ph_HWAccelBlit(SDL_Surface* src, SDL_Rect *srcrect, SDL_Surface* dst, SDL_Rect* dstrect);
52extern int ph_UpdateHWInfo(_THIS);
53
54extern void ph_NormalUpdate(_THIS, int numrects, SDL_Rect* rects);
55extern void ph_OCUpdate(_THIS, int numrects, SDL_Rect* rects);
56extern void ph_OCDCUpdate(_THIS, int numrects, SDL_Rect* rects);
57extern void ph_OpenGLUpdate(_THIS, int numrects, SDL_Rect* rects);
58
59#endif /* __SDL_PH_IMAGE_H__ */
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_modes.c b/apps/plugins/sdl/src/video/photon/SDL_ph_modes.c
deleted file mode 100644
index 8c2bf7e4bf..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_modes.c
+++ /dev/null
@@ -1,390 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_ph_modes_c.h"
25
26static PgVideoModeInfo_t mode_info;
27static PgVideoModes_t mode_list;
28
29/* The current list of available video modes */
30SDL_Rect SDL_modelist[PH_MAX_VIDEOMODES];
31SDL_Rect* SDL_modearray[PH_MAX_VIDEOMODES];
32
33static int compare_modes_by_res(const void* mode1, const void* mode2)
34{
35 PgVideoModeInfo_t mode1_info;
36 PgVideoModeInfo_t mode2_info;
37
38 if (PgGetVideoModeInfo(*(unsigned short*)mode1, &mode1_info) < 0)
39 {
40 return 0;
41 }
42
43 if (PgGetVideoModeInfo(*(unsigned short*)mode2, &mode2_info) < 0)
44 {
45 return 0;
46 }
47
48 if (mode1_info.width == mode2_info.width)
49 {
50 return mode2_info.height - mode1_info.height;
51 }
52 else
53 {
54 return mode2_info.width - mode1_info.width;
55 }
56}
57
58SDL_Rect **ph_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
59{
60 int i = 0;
61 int j = 0;
62 SDL_Rect Amodelist[PH_MAX_VIDEOMODES];
63
64 for (i=0; i<PH_MAX_VIDEOMODES; i++)
65 {
66 SDL_modearray[i]=&SDL_modelist[i];
67 }
68
69 if (PgGetVideoModeList(&mode_list) < 0)
70 {
71 SDL_SetError("ph_ListModes(): PgGetVideoModeList() function failed !\n");
72 return NULL;
73 }
74
75 mode_info.bits_per_pixel = 0;
76
77 for (i=0; i < mode_list.num_modes; i++)
78 {
79 if (PgGetVideoModeInfo(mode_list.modes[i], &mode_info) < 0)
80 {
81 SDL_SetError("ph_ListModes(): PgGetVideoModeInfo() function failed on mode: 0x%X.\n", mode_list.modes[i]);
82 return NULL;
83 }
84 if(mode_info.bits_per_pixel == format->BitsPerPixel)
85 {
86 Amodelist[j].w = mode_info.width;
87 Amodelist[j].h = mode_info.height;
88 Amodelist[j].x = 0;
89 Amodelist[j].y = 0;
90 j++;
91 }
92 }
93
94 /* reorder biggest for smallest, assume width dominates */
95
96 for(i=0; i<j; i++)
97 {
98 SDL_modelist[i].w = Amodelist[j - i - 1].w;
99 SDL_modelist[i].h = Amodelist[j - i - 1].h;
100 SDL_modelist[i].x = Amodelist[j - i - 1].x;
101 SDL_modelist[i].y = Amodelist[j - i - 1].y;
102 }
103 SDL_modearray[j]=NULL;
104
105 return SDL_modearray;
106}
107
108void ph_FreeVideoModes(_THIS)
109{
110 return;
111}
112
113/* return the mode associated with width, height and bpp */
114/* if there is no mode then zero is returned */
115int ph_GetVideoMode(int width, int height, int bpp)
116{
117 int i;
118 int modestage=0;
119 int closestmode=0;
120
121 if (PgGetVideoModeList(&mode_list) < 0)
122 {
123 return -1;
124 }
125
126 /* special case for the double-sized 320x200 mode */
127 if ((width==640) && (height==400))
128 {
129 modestage=1;
130 }
131
132 /* search list for exact match */
133 for (i=0; i<mode_list.num_modes; i++)
134 {
135 if (PgGetVideoModeInfo(mode_list.modes[i], &mode_info) < 0)
136 {
137 return 0;
138 }
139
140 if ((mode_info.width == width) && (mode_info.height == height) &&
141 (mode_info.bits_per_pixel == bpp))
142 {
143 return mode_list.modes[i];
144 }
145 else
146 {
147 if ((modestage) && (mode_info.width == width) && (mode_info.height == height+80) &&
148 (mode_info.bits_per_pixel == bpp))
149 {
150 modestage=2;
151 closestmode=mode_list.modes[i];
152 }
153 }
154 }
155
156 /* if we are here, then no 640x400xbpp mode found and we'll emulate it via 640x480xbpp mode */
157 if (modestage==2)
158 {
159 return closestmode;
160 }
161
162 return (i == mode_list.num_modes) ? 0 : mode_list.modes[i];
163}
164
165/* return the mode associated with width, height and bpp */
166/* if requested bpp is not found the mode with closest bpp is returned */
167int get_mode_any_format(int width, int height, int bpp)
168{
169 int i, closest, delta, min_delta;
170
171 if (PgGetVideoModeList(&mode_list) < 0)
172 {
173 return -1;
174 }
175
176 SDL_qsort(mode_list.modes, mode_list.num_modes, sizeof(unsigned short), compare_modes_by_res);
177
178 for(i=0;i<mode_list.num_modes;i++)
179 {
180 if (PgGetVideoModeInfo(mode_list.modes[i], &mode_info) < 0)
181 {
182 return 0;
183 }
184 if ((mode_info.width == width) && (mode_info.height == height))
185 {
186 break;
187 }
188 }
189
190 if (i<mode_list.num_modes)
191 {
192 /* get closest bpp */
193 closest = i++;
194 if (mode_info.bits_per_pixel == bpp)
195 {
196 return mode_list.modes[closest];
197 }
198
199 min_delta = abs(mode_info.bits_per_pixel - bpp);
200
201 while(1)
202 {
203 if (PgGetVideoModeInfo(mode_list.modes[i], &mode_info) < 0)
204 {
205 return 0;
206 }
207
208 if ((mode_info.width != width) || (mode_info.height != height))
209 {
210 break;
211 }
212 else
213 {
214 if (mode_info.bits_per_pixel == bpp)
215 {
216 closest = i;
217 break;
218 }
219 else
220 {
221 delta = abs(mode_info.bits_per_pixel - bpp);
222 if (delta < min_delta)
223 {
224 closest = i;
225 min_delta = delta;
226 }
227 i++;
228 }
229 }
230 }
231 return mode_list.modes[closest];
232 }
233
234 return 0;
235}
236
237int ph_ToggleFullScreen(_THIS, int on)
238{
239 return -1;
240}
241
242int ph_EnterFullScreen(_THIS, SDL_Surface* screen, int fmode)
243{
244 PgDisplaySettings_t settings;
245 int mode;
246 char* refreshrate;
247 int refreshratenum;
248
249 if (!currently_fullscreen)
250 {
251 /* Get the video mode and set it */
252 if (screen->flags & SDL_ANYFORMAT)
253 {
254 if ((mode = get_mode_any_format(screen->w, screen->h, screen->format->BitsPerPixel)) == 0)
255 {
256 SDL_SetError("ph_EnterFullScreen(): can't find appropriate video mode !\n");
257 return 0;
258 }
259 }
260 else
261 {
262 if ((mode = ph_GetVideoMode(screen->w, screen->h, screen->format->BitsPerPixel)) == 0)
263 {
264 SDL_SetError("ph_EnterFullScreen(): can't find appropriate video mode !\n");
265 return 0;
266 }
267 if (PgGetVideoModeInfo(mode, &mode_info) < 0)
268 {
269 SDL_SetError("ph_EnterFullScreen(): can't get video mode capabilities !\n");
270 return 0;
271 }
272 if (mode_info.height != screen->h)
273 {
274 if ((mode_info.height==480) && (screen->h==400))
275 {
276 videomode_emulatemode=1;
277 }
278 }
279 else
280 {
281 videomode_emulatemode=0;
282 }
283 }
284
285 /* save old video mode caps */
286 PgGetVideoMode(&settings);
287 old_video_mode=settings.mode;
288 old_refresh_rate=settings.refresh;
289
290 /* setup new video mode */
291 settings.mode = mode;
292 settings.refresh = 0;
293 settings.flags = 0;
294
295 refreshrate=SDL_getenv("SDL_PHOTON_FULLSCREEN_REFRESH");
296 if (refreshrate!=NULL)
297 {
298 if (SDL_sscanf(refreshrate, "%d", &refreshratenum)==1)
299 {
300 settings.refresh = refreshratenum;
301 }
302 }
303
304 if (PgSetVideoMode(&settings) < 0)
305 {
306 SDL_SetError("ph_EnterFullScreen(): PgSetVideoMode() call failed !\n");
307 return 0;
308 }
309
310 if (this->screen)
311 {
312 if ((this->screen->flags & SDL_OPENGL)==SDL_OPENGL)
313 {
314#if !SDL_VIDEO_OPENGL || (_NTO_VERSION < 630)
315 return 0; /* 6.3.0 */
316#endif
317 }
318 }
319
320 if (fmode==0)
321 {
322 if (OCImage.direct_context==NULL)
323 {
324 OCImage.direct_context=(PdDirectContext_t*)PdCreateDirectContext();
325 if (!OCImage.direct_context)
326 {
327 SDL_SetError("ph_EnterFullScreen(): Can't create direct context !\n");
328 ph_LeaveFullScreen(this);
329 return 0;
330 }
331 }
332 OCImage.oldDC=PdDirectStart(OCImage.direct_context);
333 }
334
335 currently_fullscreen = 1;
336 }
337 PgFlush();
338
339 return 1;
340}
341
342int ph_LeaveFullScreen(_THIS)
343{
344 PgDisplaySettings_t oldmode_settings;
345
346 if (currently_fullscreen)
347 {
348 if ((this->screen) && ((this->screen->flags & SDL_OPENGL)==SDL_OPENGL))
349 {
350#if !SDL_VIDEO_OPENGL || (_NTO_VERSION < 630)
351 return 0;
352#endif
353 }
354
355 /* release routines starts here */
356 {
357 if (OCImage.direct_context)
358 {
359 PdDirectStop(OCImage.direct_context);
360 PdReleaseDirectContext(OCImage.direct_context);
361 OCImage.direct_context=NULL;
362 }
363 if (OCImage.oldDC)
364 {
365 PhDCSetCurrent(OCImage.oldDC);
366 OCImage.oldDC=NULL;
367 }
368
369 currently_fullscreen=0;
370
371 /* Restore old video mode */
372 if (old_video_mode != -1)
373 {
374 oldmode_settings.mode = (unsigned short) old_video_mode;
375 oldmode_settings.refresh = (unsigned short) old_refresh_rate;
376 oldmode_settings.flags = 0;
377
378 if (PgSetVideoMode(&oldmode_settings) < 0)
379 {
380 SDL_SetError("Ph_LeaveFullScreen(): PgSetVideoMode() function failed !\n");
381 return 0;
382 }
383 }
384
385 old_video_mode=-1;
386 old_refresh_rate=-1;
387 }
388 }
389 return 1;
390}
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_modes_c.h b/apps/plugins/sdl/src/video/photon/SDL_ph_modes_c.h
deleted file mode 100644
index 117c5a3a91..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_modes_c.h
+++ /dev/null
@@ -1,43 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SDL_PH_MODES_H__
25#define __SDL_PH_MODES_H__
26
27#include "SDL_ph_video.h"
28
29#define PH_MAX_VIDEOMODES 127
30
31#define PH_ENTER_DIRECTMODE 0
32#define PH_IGNORE_DIRECTMODE 1
33
34extern SDL_Rect **ph_ListModes(_THIS,SDL_PixelFormat *format, Uint32 flags);
35extern void ph_FreeVideoModes(_THIS);
36extern int ph_ResizeFullScreen(_THIS);
37extern int ph_EnterFullScreen(_THIS, SDL_Surface* screen, int fmode);
38extern int ph_LeaveFullScreen(_THIS);
39extern int ph_GetVideoMode(int width, int height, int bpp);
40extern int get_mode_any_format(int width, int height, int bpp);
41extern int ph_ToggleFullScreen(_THIS, int on);
42
43#endif /* __SDL_PH_MODES_H__ */
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_mouse.c b/apps/plugins/sdl/src/video/photon/SDL_ph_mouse.c
deleted file mode 100644
index a25aa1fc85..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_mouse.c
+++ /dev/null
@@ -1,220 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_mouse.h"
25#include "../../events/SDL_events_c.h"
26#include "../SDL_cursor_c.h"
27#include "SDL_ph_mouse_c.h"
28
29struct WMcursor
30{
31 PhCursorDef_t *ph_cursor ;
32};
33
34void ph_FreeWMCursor(_THIS, WMcursor *cursor)
35{
36 if (window != NULL)
37 {
38 SDL_Lock_EventThread();
39
40 if (PtSetResource(window, Pt_ARG_CURSOR_TYPE, Ph_CURSOR_INHERIT, 0) < 0)
41 {
42 /* TODO: output error msg */
43 }
44
45 SDL_Unlock_EventThread();
46 }
47
48 SDL_free(cursor);
49}
50
51WMcursor *ph_CreateWMCursor(_THIS, Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
52{
53 WMcursor* cursor;
54 int clen, i;
55 unsigned char bit, databit, maskbit;
56
57 /* Allocate and initialize the cursor memory */
58 if ((cursor = (WMcursor*)SDL_malloc(sizeof(WMcursor))) == NULL)
59 {
60 SDL_OutOfMemory();
61 return(NULL);
62 }
63 SDL_memset(cursor,0,sizeof(WMcursor));
64
65 cursor->ph_cursor = (PhCursorDef_t *) SDL_malloc(sizeof(PhCursorDef_t) + 32*4*2);
66
67 if (cursor->ph_cursor == NULL)
68 {
69 SDL_SetError("ph_CreateWMCursor(): cursor malloc failed !\n");
70 return NULL;
71 }
72
73 SDL_memset(cursor->ph_cursor,0,(sizeof(PhCursorDef_t) + 32*4*2));
74
75 cursor->ph_cursor->hdr.type =Ph_RDATA_CURSOR;
76 cursor->ph_cursor->size1.x = (short)w;
77 cursor->ph_cursor->size1.y = (short)h;
78 cursor->ph_cursor->offset1.x = (short)hot_x;
79 cursor->ph_cursor->offset1.y = (short)hot_y;
80 cursor->ph_cursor->bytesperline1 = (char)w/8;
81 cursor->ph_cursor->color1 = Pg_WHITE;
82 cursor->ph_cursor->size2.x = (short)w;
83 cursor->ph_cursor->size2.y = (short)h;
84 cursor->ph_cursor->offset2.x = (short)hot_x;
85 cursor->ph_cursor->offset2.y = (short)hot_y;
86 cursor->ph_cursor->bytesperline2 = (char)w/8;
87 cursor->ph_cursor->color2 = Pg_BLACK;
88
89 clen = (w/8)*h;
90
91 /* Copy the mask and the data to different bitmap planes */
92 for (i=0; i<clen; ++i)
93 {
94 for (bit = 0; bit < 8; bit++)
95 {
96 databit = data[i] & (1 << bit);
97 maskbit = mask[i] & (1 << bit);
98
99 cursor->ph_cursor->images[i] |= (databit == 0) ? maskbit : 0;
100 /* If the databit != 0, treat it as a black pixel and
101 * ignore the maskbit (can't do an inverted color) */
102 cursor->ph_cursor->images[i+clen] |= databit;
103 }
104 }
105
106 /* #bytes following the hdr struct */
107 cursor->ph_cursor->hdr.len =sizeof(PhCursorDef_t) + clen*2 - sizeof(PhRegionDataHdr_t);
108
109 return (cursor);
110}
111
112PhCursorDef_t ph_GetWMPhCursor(WMcursor *cursor)
113{
114 return (*cursor->ph_cursor);
115}
116
117int ph_ShowWMCursor(_THIS, WMcursor* cursor)
118{
119 PtArg_t args[3];
120 int nargs = 0;
121
122 /* Don't do anything if the display is gone */
123 if (window == NULL)
124 {
125 return (0);
126 }
127
128 /* looks like photon can't draw mouse cursor in direct mode */
129 if ((this->screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)
130 {
131 /* disable the fake mouse in the fullscreen OpenGL mode */
132 if ((this->screen->flags & SDL_OPENGL) == SDL_OPENGL)
133 {
134 cursor=NULL;
135 }
136 else
137 {
138 return (0);
139 }
140 }
141
142 /* Set the photon cursor, or blank if cursor is NULL */
143 if (cursor!=NULL)
144 {
145 PtSetArg(&args[0], Pt_ARG_CURSOR_TYPE, Ph_CURSOR_BITMAP, 0);
146 /* Could set next to any PgColor_t value */
147 PtSetArg(&args[1], Pt_ARG_CURSOR_COLOR, Ph_CURSOR_DEFAULT_COLOR , 0);
148 PtSetArg(&args[2], Pt_ARG_BITMAP_CURSOR, cursor->ph_cursor, (cursor->ph_cursor->hdr.len + sizeof(PhRegionDataHdr_t)));
149 nargs = 3;
150 }
151 else /* Ph_CURSOR_NONE */
152 {
153 PtSetArg(&args[0], Pt_ARG_CURSOR_TYPE, Ph_CURSOR_NONE, 0);
154 nargs = 1;
155 }
156
157 SDL_Lock_EventThread();
158
159 if (PtSetResources(window, nargs, args) < 0 )
160 {
161 return (0);
162 }
163
164 SDL_Unlock_EventThread();
165
166 return (1);
167}
168
169
170void ph_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
171{
172 short abs_x, abs_y;
173
174 SDL_Lock_EventThread();
175 PtGetAbsPosition( window, &abs_x, &abs_y );
176 PhMoveCursorAbs( PhInputGroup(NULL), x + abs_x, y + abs_y );
177 SDL_Unlock_EventThread();
178}
179
180
181void ph_CheckMouseMode(_THIS)
182{
183 /* If the mouse is hidden and input is grabbed, we use relative mode */
184 if ( !(SDL_cursorstate & CURSOR_VISIBLE) && (this->input_grab != SDL_GRAB_OFF))
185 {
186 mouse_relative = 1;
187 }
188 else
189 {
190 mouse_relative = 0;
191 }
192}
193
194
195void ph_UpdateMouse(_THIS)
196{
197 PhCursorInfo_t phcursor;
198 short abs_x;
199 short abs_y;
200
201 /* Lock the event thread, in multi-threading environments */
202 SDL_Lock_EventThread();
203
204 /* synchronizing photon mouse cursor position and SDL mouse position, if cursor appears over window. */
205 PtGetAbsPosition(window, &abs_x, &abs_y);
206 PhQueryCursor(PhInputGroup(NULL), &phcursor);
207 if (((phcursor.pos.x >= abs_x) && (phcursor.pos.x <= abs_x + this->screen->w)) &&
208 ((phcursor.pos.y >= abs_y) && (phcursor.pos.y <= abs_y + this->screen->h)))
209 {
210 SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
211 SDL_PrivateMouseMotion(0, 0, phcursor.pos.x-abs_x, phcursor.pos.y-abs_y);
212 }
213 else
214 {
215 SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
216 }
217
218 /* Unlock the event thread, in multi-threading environments */
219 SDL_Unlock_EventThread();
220}
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_mouse_c.h b/apps/plugins/sdl/src/video/photon/SDL_ph_mouse_c.h
deleted file mode 100644
index 55a92b606b..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_mouse_c.h
+++ /dev/null
@@ -1,39 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SDL_PH_MOUSE_H__
25#define __SDL_PH_MOUSE_H__
26
27#include "SDL_ph_video.h"
28
29/* Functions to be exported */
30extern void ph_FreeWMCursor(_THIS, WMcursor *cursor);
31extern WMcursor *ph_CreateWMCursor(_THIS,
32 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
33extern PhCursorDef_t ph_GetWMPhCursor(WMcursor *cursor);
34extern int ph_ShowWMCursor(_THIS, WMcursor *cursor);
35extern void ph_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
36extern void ph_CheckMouseMode(_THIS);
37extern void ph_UpdateMouse(_THIS);
38
39#endif /* __SDL_PH_MOUSE_H__ */
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_video.c b/apps/plugins/sdl/src/video/photon/SDL_ph_video.c
deleted file mode 100644
index 5e1a82b0ea..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_video.c
+++ /dev/null
@@ -1,648 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <unistd.h>
25#include <sys/ioctl.h>
26
27#include "SDL_endian.h"
28#include "SDL_timer.h"
29#include "SDL_thread.h"
30#include "SDL_video.h"
31#include "SDL_mouse.h"
32#include "../SDL_sysvideo.h"
33#include "../SDL_pixels_c.h"
34#include "../../events/SDL_events_c.h"
35#include "SDL_ph_video.h"
36#include "SDL_ph_modes_c.h"
37#include "SDL_ph_image_c.h"
38#include "SDL_ph_events_c.h"
39#include "SDL_ph_mouse_c.h"
40#include "SDL_ph_wm_c.h"
41#include "SDL_ph_gl.h"
42#include "SDL_phyuv_c.h"
43#include "../blank_cursor.h"
44
45static int ph_VideoInit(_THIS, SDL_PixelFormat *vformat);
46static SDL_Surface *ph_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
47static int ph_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
48static void ph_VideoQuit(_THIS);
49static void ph_DeleteDevice(SDL_VideoDevice *device);
50
51static int phstatus=-1;
52
53static int ph_Available(void)
54{
55 if (phstatus!=0)
56 {
57 phstatus=PtInit(NULL);
58 if (phstatus==0)
59 {
60 return 1;
61 }
62 else
63 {
64 return 0;
65 }
66 }
67 return 1;
68}
69
70static SDL_VideoDevice* ph_CreateDevice(int devindex)
71{
72 SDL_VideoDevice* device;
73
74 /* Initialize all variables that we clean on shutdown */
75 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
76 if (device)
77 {
78 SDL_memset(device, 0, (sizeof *device));
79 device->hidden = (struct SDL_PrivateVideoData*)SDL_malloc((sizeof *device->hidden));
80 device->gl_data = NULL;
81 }
82 if ((device == NULL) || (device->hidden == NULL))
83 {
84 SDL_OutOfMemory();
85 ph_DeleteDevice(device);
86 return NULL;
87 }
88 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
89
90 /* Set the driver flags */
91 device->handles_any_size = 1;
92
93 /* Set the function pointers */
94 device->CreateYUVOverlay = ph_CreateYUVOverlay;
95 device->VideoInit = ph_VideoInit;
96 device->ListModes = ph_ListModes;
97 device->SetVideoMode = ph_SetVideoMode;
98 device->ToggleFullScreen = ph_ToggleFullScreen;
99 device->UpdateMouse = ph_UpdateMouse;
100 device->SetColors = ph_SetColors;
101 device->UpdateRects = NULL; /* set up in ph_SetupUpdateFunction */
102 device->VideoQuit = ph_VideoQuit;
103 device->AllocHWSurface = ph_AllocHWSurface;
104 device->CheckHWBlit = ph_CheckHWBlit;
105 device->FillHWRect = ph_FillHWRect;
106 device->SetHWColorKey = ph_SetHWColorKey;
107 device->SetHWAlpha = ph_SetHWAlpha;
108 device->LockHWSurface = ph_LockHWSurface;
109 device->UnlockHWSurface = ph_UnlockHWSurface;
110 device->FlipHWSurface = ph_FlipHWSurface;
111 device->FreeHWSurface = ph_FreeHWSurface;
112 device->SetCaption = ph_SetCaption;
113 device->SetIcon = NULL;
114 device->IconifyWindow = ph_IconifyWindow;
115 device->GrabInput = ph_GrabInput;
116 device->GetWMInfo = ph_GetWMInfo;
117 device->FreeWMCursor = ph_FreeWMCursor;
118 device->CreateWMCursor = ph_CreateWMCursor;
119 device->ShowWMCursor = ph_ShowWMCursor;
120 device->WarpWMCursor = ph_WarpWMCursor;
121 device->MoveWMCursor = NULL;
122 device->CheckMouseMode = ph_CheckMouseMode;
123 device->InitOSKeymap = ph_InitOSKeymap;
124 device->PumpEvents = ph_PumpEvents;
125
126 /* OpenGL support. */
127#if SDL_VIDEO_OPENGL
128 device->GL_MakeCurrent = ph_GL_MakeCurrent;
129 device->GL_SwapBuffers = ph_GL_SwapBuffers;
130 device->GL_GetAttribute = ph_GL_GetAttribute;
131 device->GL_LoadLibrary = ph_GL_LoadLibrary;
132 device->GL_GetProcAddress = ph_GL_GetProcAddress;
133#endif /* SDL_VIDEO_OPENGL */
134
135 device->free = ph_DeleteDevice;
136
137 return device;
138}
139
140VideoBootStrap ph_bootstrap = {
141 "photon", "QNX Photon video output",
142 ph_Available, ph_CreateDevice
143};
144
145static void ph_DeleteDevice(SDL_VideoDevice *device)
146{
147 if (device)
148 {
149 if (device->hidden)
150 {
151 SDL_free(device->hidden);
152 device->hidden = NULL;
153 }
154 if (device->gl_data)
155 {
156 SDL_free(device->gl_data);
157 device->gl_data = NULL;
158 }
159 SDL_free(device);
160 device = NULL;
161 }
162}
163
164static PtWidget_t *ph_CreateWindow(_THIS)
165{
166 PtWidget_t *widget;
167
168 widget = PtCreateWidget(PtWindow, NULL, 0, NULL);
169
170 return widget;
171}
172
173static int ph_SetupWindow(_THIS, int w, int h, int flags)
174{
175 PtArg_t args[32];
176 PhPoint_t pos = {0, 0};
177 PhDim_t* olddim;
178 PhDim_t dim = {w, h};
179 PhRect_t desktopextent;
180 int nargs = 0;
181 const char* windowpos;
182 const char* iscentered;
183 int x, y;
184
185 /* check if window size has been changed by Window Manager */
186 PtGetResource(window, Pt_ARG_DIM, &olddim, 0);
187 if ((olddim->w!=w) || (olddim->h!=h))
188 {
189 PtSetArg(&args[nargs++], Pt_ARG_DIM, &dim, 0);
190 }
191
192 if ((flags & SDL_RESIZABLE) == SDL_RESIZABLE)
193 {
194 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_CLOSE);
195 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, Ph_WM_MAX | Ph_WM_RESTORE | Ph_WM_RESIZE);
196 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, Ph_WM_RESIZE | Ph_WM_MOVE | Ph_WM_CLOSE | Ph_WM_MAX | Ph_WM_RESTORE);
197 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_MAX | Ph_WM_RENDER_COLLAPSE | Ph_WM_RENDER_RETURN);
198 PtSetArg(&args[nargs++], Pt_ARG_RESIZE_FLAGS, Pt_TRUE, Pt_RESIZE_XY_AS_REQUIRED);
199 }
200 else
201 {
202 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_RESIZE | Ph_WM_MAX | Ph_WM_RESTORE | Ph_WM_CLOSE);
203 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_FALSE, Ph_WM_RESIZE | Ph_WM_MAX | Ph_WM_RESTORE);
204 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, Ph_WM_MOVE | Ph_WM_CLOSE);
205 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_MAX | Ph_WM_RENDER_COLLAPSE | Ph_WM_RENDER_RETURN);
206 PtSetArg(&args[nargs++], Pt_ARG_RESIZE_FLAGS, Pt_FALSE, Pt_RESIZE_XY_AS_REQUIRED);
207 }
208
209 if (((flags & SDL_NOFRAME)==SDL_NOFRAME) || ((flags & SDL_FULLSCREEN)==SDL_FULLSCREEN))
210 {
211 if ((flags & SDL_RESIZABLE) != SDL_RESIZABLE)
212 {
213 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, Pt_TRUE);
214 }
215 else
216 {
217 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, Pt_TRUE);
218 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_BORDER);
219 }
220 }
221 else
222 {
223 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, Ph_WM_RENDER_BORDER | Ph_WM_RENDER_TITLE |
224 Ph_WM_RENDER_CLOSE | Ph_WM_RENDER_MENU | Ph_WM_RENDER_MIN);
225 }
226
227 if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)
228 {
229 PtSetArg(&args[nargs++], Pt_ARG_POS, &pos, 0);
230 PtSetArg(&args[nargs++], Pt_ARG_BASIC_FLAGS, Pt_TRUE, Pt_BASIC_PREVENT_FILL);
231 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, Ph_WM_FFRONT | Ph_WM_MAX | Ph_WM_TOFRONT | Ph_WM_CONSWITCH);
232 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISFRONT | Ph_WM_STATE_ISFOCUS | Ph_WM_STATE_ISALTKEY);
233 }
234 else
235 {
236 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_FFRONT | Ph_WM_CONSWITCH);
237 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_FALSE, Ph_WM_STATE_ISFRONT);
238 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISALTKEY);
239
240 if ((flags & SDL_HWSURFACE) == SDL_HWSURFACE)
241 {
242 PtSetArg(&args[nargs++], Pt_ARG_BASIC_FLAGS, Pt_TRUE, Pt_BASIC_PREVENT_FILL);
243 }
244 else
245 {
246 PtSetArg(&args[nargs++], Pt_ARG_FILL_COLOR, Pg_BLACK, 0);
247 }
248 if (!currently_maximized)
249 {
250 windowpos = SDL_getenv("SDL_VIDEO_WINDOW_POS");
251 iscentered = SDL_getenv("SDL_VIDEO_CENTERED");
252
253 if ((iscentered) || ((windowpos) && (SDL_strcmp(windowpos, "center")==0)))
254 {
255 PhWindowQueryVisible(Ph_QUERY_CONSOLE, 0, 0, &desktopextent);
256 if (desktop_mode.width>w)
257 {
258 pos.x = (desktop_mode.width - w)/2;
259 }
260 if (desktop_mode.height>h)
261 {
262 pos.y = (desktop_mode.height - h)/2;
263 }
264
265 pos.x+=desktopextent.ul.x;
266 pos.y+=desktopextent.ul.y;
267 PtSetArg(&args[nargs++], Pt_ARG_POS, &pos, 0);
268 }
269 else
270 {
271 if (windowpos)
272 {
273 if (SDL_sscanf(windowpos, "%d,%d", &x, &y) == 2)
274 {
275 if ((x<desktop_mode.width) && (y<desktop_mode.height))
276 {
277 PhWindowQueryVisible(Ph_QUERY_CONSOLE, 0, 0, &desktopextent);
278 pos.x=x+desktopextent.ul.x;
279 pos.y=y+desktopextent.ul.y;
280 }
281 PtSetArg(&args[nargs++], Pt_ARG_POS, &pos, 0);
282 }
283 }
284 }
285 }
286
287 /* if window is maximized render it as maximized */
288 if (currently_maximized)
289 {
290 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISMAX);
291 }
292 else
293 {
294 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_FALSE, Ph_WM_STATE_ISMAX);
295 }
296
297 /* do not grab the keyboard by default */
298 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_FALSE, Ph_WM_STATE_ISALTKEY);
299
300 /* bring the focus to the window */
301 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISFOCUS);
302
303 /* allow to catch hide event */
304 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, Ph_WM_HIDE);
305 PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, Ph_WM_HIDE);
306 }
307
308 PtSetResources(window, nargs, args);
309 PtRealizeWidget(window);
310 PtWindowToFront(window);
311
312#if 0 /* FIXME */
313 PtGetResource(window, Pt_ARG_POS, &olddim, 0);
314 fprintf(stderr, "POSITION: %d, %d\n", olddim->w, olddim->h);
315#endif
316
317 return 0;
318}
319
320static const struct ColourMasks* ph_GetColourMasks(int bpp)
321{
322 /* The alpha mask doesn't appears to be needed */
323 static const struct ColourMasks phColorMasks[5] = {
324 /* 8 bit */ {0, 0, 0, 0, 8},
325 /* 15 bit ARGB */ {0x7C00, 0x03E0, 0x001F, 0x8000, 15},
326 /* 16 bit RGB */ {0xF800, 0x07E0, 0x001F, 0x0000, 16},
327 /* 24 bit RGB */ {0xFF0000, 0x00FF00, 0x0000FF, 0x000000, 24},
328 /* 32 bit ARGB */ {0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, 32},
329 };
330
331 switch (bpp)
332 {
333 case 8:
334 return &phColorMasks[0];
335 case 15:
336 return &phColorMasks[1];
337 case 16:
338 return &phColorMasks[2];
339 case 24:
340 return &phColorMasks[3];
341 case 32:
342 return &phColorMasks[4];
343 }
344 return NULL;
345}
346
347static int ph_VideoInit(_THIS, SDL_PixelFormat* vformat)
348{
349 PgHWCaps_t hwcaps;
350 int i;
351
352 window=NULL;
353 desktoppal=SDLPH_PAL_NONE;
354
355#if SDL_VIDEO_OPENGL
356 oglctx=NULL;
357 oglbuffers=NULL;
358 oglflags=0;
359 oglbpp=0;
360#endif
361
362 old_video_mode=-1;
363 old_refresh_rate=-1;
364
365 if (NULL == (phevent = SDL_malloc(EVENT_SIZE)))
366 {
367 SDL_OutOfMemory();
368 return -1;
369 }
370 SDL_memset(phevent, 0x00, EVENT_SIZE);
371
372 window = ph_CreateWindow(this);
373 if (window == NULL)
374 {
375 SDL_SetError("ph_VideoInit(): Couldn't create video window !\n");
376 return -1;
377 }
378
379 /* Create the blank cursor */
380 SDL_BlankCursor = this->CreateWMCursor(this, blank_cdata, blank_cmask,
381 (int)BLANK_CWIDTH, (int)BLANK_CHEIGHT,
382 (int)BLANK_CHOTX, (int)BLANK_CHOTY);
383
384 if (SDL_BlankCursor == NULL)
385 {
386 return -1;
387 }
388
389 if (PgGetGraphicsHWCaps(&hwcaps) < 0)
390 {
391 SDL_SetError("ph_VideoInit(): GetGraphicsHWCaps function failed !\n");
392 this->FreeWMCursor(this, SDL_BlankCursor);
393 return -1;
394 }
395
396 if (PgGetVideoModeInfo(hwcaps.current_video_mode, &desktop_mode) < 0)
397 {
398 SDL_SetError("ph_VideoInit(): PgGetVideoModeInfo function failed !\n");
399 this->FreeWMCursor(this, SDL_BlankCursor);
400 return -1;
401 }
402
403 /* Determine the current screen size */
404 this->info.current_w = desktop_mode.width;
405 this->info.current_h = desktop_mode.height;
406
407 /* We need to return BytesPerPixel as it in used by CreateRGBsurface */
408 vformat->BitsPerPixel = desktop_mode.bits_per_pixel;
409 vformat->BytesPerPixel = desktop_mode.bytes_per_scanline/desktop_mode.width;
410 desktopbpp = desktop_mode.bits_per_pixel;
411
412 /* save current palette */
413 if (desktopbpp==8)
414 {
415 PgGetPalette(savedpal);
416 PgGetPalette(syspalph);
417 }
418 else
419 {
420 for(i=0; i<_Pg_MAX_PALETTE; i++)
421 {
422 savedpal[i]=PgRGB(0, 0, 0);
423 syspalph[i]=PgRGB(0, 0, 0);
424 }
425 }
426
427 currently_fullscreen = 0;
428 currently_hided = 0;
429 currently_maximized = 0;
430 current_overlay = NULL;
431
432 OCImage.direct_context = NULL;
433 OCImage.offscreen_context = NULL;
434 OCImage.offscreen_backcontext = NULL;
435 OCImage.oldDC = NULL;
436 OCImage.CurrentFrameData = NULL;
437 OCImage.FrameData0 = NULL;
438 OCImage.FrameData1 = NULL;
439 videomode_emulatemode = 0;
440
441 this->info.wm_available = 1;
442
443 ph_UpdateHWInfo(this);
444
445 return 0;
446}
447
448static SDL_Surface* ph_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags)
449{
450 const struct ColourMasks* mask;
451
452 /* Lock the event thread, in multi-threading environments */
453 SDL_Lock_EventThread();
454
455 current->flags = flags;
456
457 /* if we do not have desired fullscreen mode, then fallback into window mode */
458 if (((current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) && (ph_GetVideoMode(width, height, bpp)==0))
459 {
460 current->flags &= ~SDL_FULLSCREEN;
461 current->flags &= ~SDL_NOFRAME;
462 current->flags &= ~SDL_RESIZABLE;
463 }
464
465 ph_SetupWindow(this, width, height, current->flags);
466
467 mask = ph_GetColourMasks(bpp);
468 if (mask != NULL)
469 {
470 SDL_ReallocFormat(current, mask->bpp, mask->red, mask->green, mask->blue, 0);
471 }
472 else
473 {
474 SDL_SetError("ph_SetVideoMode(): desired bpp is not supported by photon !\n");
475 return NULL;
476 }
477
478 if ((current->flags & SDL_OPENGL)==SDL_OPENGL)
479 {
480#if !SDL_VIDEO_OPENGL
481 /* if no built-in OpenGL support */
482 SDL_SetError("ph_SetVideoMode(): no OpenGL support, you need to recompile SDL.\n");
483 current->flags &= ~SDL_OPENGL;
484 return NULL;
485#endif /* SDL_VIDEO_OPENGL */
486 }
487 else
488 {
489 /* Initialize internal variables */
490 if ((current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)
491 {
492 if (bpp==8)
493 {
494 desktoppal=SDLPH_PAL_SYSTEM;
495 }
496
497 current->flags &= ~SDL_RESIZABLE; /* no resize for Direct Context */
498 current->flags |= SDL_HWSURFACE;
499 }
500 else
501 {
502 /* remove this if we'll have support for the non-fullscreen sw/hw+doublebuf one day */
503 current->flags &= ~SDL_DOUBLEBUF;
504
505 /* Use offscreen memory if SDL_HWSURFACE flag is set */
506 if ((current->flags & SDL_HWSURFACE) == SDL_HWSURFACE)
507 {
508 if (desktopbpp!=bpp)
509 {
510 current->flags &= ~SDL_HWSURFACE;
511 }
512 }
513
514 /* using palette emulation code in window mode */
515 if (bpp==8)
516 {
517 if (desktopbpp>=15)
518 {
519 desktoppal = SDLPH_PAL_EMULATE;
520 }
521 else
522 {
523 desktoppal = SDLPH_PAL_SYSTEM;
524 }
525 }
526 else
527 {
528 desktoppal = SDLPH_PAL_NONE;
529 }
530 }
531 }
532
533 current->w = width;
534 current->h = height;
535
536 if (desktoppal==SDLPH_PAL_SYSTEM)
537 {
538 current->flags|=SDL_HWPALETTE;
539 }
540
541 /* Must call at least once for setup image planes */
542 if (ph_SetupUpdateFunction(this, current, current->flags)==-1)
543 {
544 /* Error string was filled in the ph_SetupUpdateFunction() */
545 return NULL;
546 }
547
548 /* finish window drawing, if we are not in fullscreen, of course */
549 if ((current->flags & SDL_FULLSCREEN) != SDL_FULLSCREEN)
550 {
551 PtFlush();
552 }
553 else
554 {
555 PgFlush();
556 }
557
558 visualbpp=bpp;
559
560 ph_UpdateHWInfo(this);
561
562 SDL_Unlock_EventThread();
563
564 /* We've done! */
565 return (current);
566}
567
568static void ph_VideoQuit(_THIS)
569{
570 /* restore palette */
571 if (desktopbpp==8)
572 {
573 PgSetPalette(syspalph, 0, -1, 0, 0, 0);
574 PgSetPalette(savedpal, 0, 0, _Pg_MAX_PALETTE, Pg_PALSET_GLOBAL | Pg_PALSET_FORCE_EXPOSE, 0);
575 PgFlush();
576 }
577
578 ph_DestroyImage(this, SDL_VideoSurface);
579
580 if (window)
581 {
582 PtUnrealizeWidget(window);
583 PtDestroyWidget(window);
584 window=NULL;
585 }
586
587 if (phevent!=NULL)
588 {
589 SDL_free(phevent);
590 phevent=NULL;
591 }
592}
593
594static int ph_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
595{
596 int i;
597 SDL_Rect updaterect;
598
599 updaterect.x = updaterect.y = 0;
600 updaterect.w = this->screen->w;
601 updaterect.h = this->screen->h;
602
603 /* palette emulation code, using palette of the PhImage_t struct */
604 if (desktoppal==SDLPH_PAL_EMULATE)
605 {
606 if ((SDL_Image) && (SDL_Image->palette))
607 {
608 for (i=firstcolor; i<firstcolor+ncolors; i++)
609 {
610 syspalph[i] = PgRGB(colors[i-firstcolor].r, colors[i-firstcolor].g, colors[i-firstcolor].b);
611 SDL_Image->palette[i] = syspalph[i];
612 }
613
614 /* image needs to be redrawn */
615 this->UpdateRects(this, 1, &updaterect);
616 }
617 }
618 else
619 {
620 if (desktoppal==SDLPH_PAL_SYSTEM)
621 {
622 for (i=firstcolor; i<firstcolor+ncolors; i++)
623 {
624 syspalph[i] = PgRGB(colors[i-firstcolor].r, colors[i-firstcolor].g, colors[i-firstcolor].b);
625 }
626
627 if ((this->screen->flags & SDL_FULLSCREEN) != SDL_FULLSCREEN)
628 {
629 /* window mode must use soft palette */
630 PgSetPalette(&syspalph[firstcolor], 0, firstcolor, ncolors, Pg_PALSET_GLOBAL, 0);
631 /* image needs to be redrawn */
632 this->UpdateRects(this, 1, &updaterect);
633 }
634 else
635 {
636 /* fullscreen mode must use hardware palette */
637 PgSetPalette(&syspalph[firstcolor], 0, firstcolor, ncolors, Pg_PALSET_GLOBAL, 0);
638 }
639 }
640 else
641 {
642 /* SDLPH_PAL_NONE do nothing */
643 }
644 }
645
646 return 1;
647}
648
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_video.h b/apps/plugins/sdl/src/video/photon/SDL_ph_video.h
deleted file mode 100644
index 3995d3505e..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_video.h
+++ /dev/null
@@ -1,157 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SDL_PH_VIDEO_H__
25#define __SDL_PH_VIDEO_H__
26
27#include "SDL_mouse.h"
28#include "../SDL_sysvideo.h"
29
30#include <sys/neutrino.h>
31
32#include <Ph.h>
33#include <Pt.h>
34#include <photon/Pg.h>
35#include <photon/PdDirect.h>
36
37#if SDL_VIDEO_OPENGL
38 #if (_NTO_VERSION < 630)
39 #include <photon/PdGL.h>
40 #else
41 #include <GL/qnxgl.h>
42 #include <GL/GLPh.h>
43 #endif /* 6.3.0 */
44#endif /* SDL_VIDEO_OPENGL */
45
46/* Hidden "this" pointer for the video functions */
47#define _THIS SDL_VideoDevice* this
48
49#define PH_OGL_MAX_ATTRIBS 32
50
51#define SDLPH_PAL_NONE 0x00000000L
52#define SDLPH_PAL_EMULATE 0x00000001L
53#define SDLPH_PAL_SYSTEM 0x00000002L
54
55typedef struct
56{
57 unsigned char* Y;
58 unsigned char* V;
59 unsigned char* U;
60} FRAMEDATA;
61
62/* Mask values for SDL_ReallocFormat() */
63struct ColourMasks
64{
65 Uint32 red;
66 Uint32 green;
67 Uint32 blue;
68 Uint32 alpha;
69 Uint32 bpp;
70};
71
72/* Private display data */
73struct SDL_PrivateVideoData
74{
75 PgDisplaySettings_t mode_settings;
76 PtWidget_t *Window; /* used to handle input events */
77 PhImage_t *image; /* used to display image */
78#if SDL_VIDEO_OPENGL
79 #if (_NTO_VERSION < 630)
80 PdOpenGLContext_t* OGLContext; /* OpenGL context */
81 void* OGLBuffers; /* OpenGL buffers (unused) */
82 #else
83 qnxglc_t* OGLContext; /* OpenGL context for the 6.3 */
84 qnxgl_bufs_t* OGLBuffers; /* OpenGL buffers for the 6.3 */
85 #endif /* 630 */
86
87 Uint32 OGLFlags; /* OpenGL flags */
88 Uint32 OGLBPP; /* OpenGL bpp */
89#endif /* SDL_VIDEO_OPENGL */
90 PgColor_t savedpal[_Pg_MAX_PALETTE];
91 PgColor_t syspalph[_Pg_MAX_PALETTE];
92
93 struct
94 {
95 PdDirectContext_t* direct_context;
96 PdOffscreenContext_t* offscreen_context;
97 PdOffscreenContext_t* offscreen_backcontext;
98 PhDrawContext_t* oldDC;
99 uint8_t* dc_ptr;
100 unsigned char* CurrentFrameData;
101 unsigned char* FrameData0;
102 unsigned char* FrameData1;
103 Uint32 current;
104 Uint32 flags;
105 } ocimage;
106
107 PgHWCaps_t graphics_card_caps; /* Graphics card caps at the moment of start */
108 PgVideoModeInfo_t desktop_mode; /* Current desktop video mode information */
109 int old_video_mode; /* Stored mode before fullscreen switch */
110 int old_refresh_rate; /* Stored refresh rate befor fullscreen switch */
111
112 int mouse_relative;
113 WMcursor* BlankCursor;
114 uint32_t videomode_emulatemode;
115
116 Uint32 visualbpp; /* current visual bpp */
117 Uint32 desktopbpp; /* bpp of desktop at the moment of start */
118 Uint32 desktoppal; /* palette mode emulation or system */
119
120 int currently_fullscreen;
121 int currently_hided; /* 1 - window hided (minimazed), 0 - normal */
122 int currently_maximized; /* 1 - window hided (minimazed), 0 - normal */
123
124 PhEvent_t* event;
125 SDL_Overlay* overlay;
126};
127
128#define mode_settings (this->hidden->mode_settings)
129#define window (this->hidden->Window)
130#define SDL_Image (this->hidden->image)
131#define OCImage (this->hidden->ocimage)
132#define old_video_mode (this->hidden->old_video_mode)
133#define old_refresh_rate (this->hidden->old_refresh_rate)
134#define graphics_card_caps (this->hidden->graphics_card_caps)
135#define desktopbpp (this->hidden->desktopbpp)
136#define visualbpp (this->hidden->visualbpp)
137#define desktoppal (this->hidden->desktoppal)
138#define savedpal (this->hidden->savedpal)
139#define syspalph (this->hidden->syspalph)
140#define currently_fullscreen (this->hidden->currently_fullscreen)
141#define currently_hided (this->hidden->currently_hided)
142#define currently_maximized (this->hidden->currently_maximized)
143#define phevent (this->hidden->event)
144#define current_overlay (this->hidden->overlay)
145#define desktop_mode (this->hidden->desktop_mode)
146#define mouse_relative (this->hidden->mouse_relative)
147#define SDL_BlankCursor (this->hidden->BlankCursor)
148#define videomode_emulatemode (this->hidden->videomode_emulatemode)
149
150#if SDL_VIDEO_OPENGL
151 #define oglctx (this->hidden->OGLContext)
152 #define oglbuffers (this->hidden->OGLBuffers)
153 #define oglflags (this->hidden->OGLFlags)
154 #define oglbpp (this->hidden->OGLBPP)
155#endif /* SDL_VIDEO_OPENGL */
156
157#endif /* __SDL_PH_VIDEO_H__ */
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_wm.c b/apps/plugins/sdl/src/video/photon/SDL_ph_wm.c
deleted file mode 100644
index 8e75d0b577..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_wm.c
+++ /dev/null
@@ -1,118 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <Ph.h>
25#include <photon/PpProto.h>
26#include <photon/PhWm.h>
27#include <photon/wmapi.h>
28
29#include "SDL_version.h"
30#include "SDL_timer.h"
31#include "SDL_video.h"
32#include "SDL_syswm.h"
33#include "../SDL_pixels_c.h"
34#include "../../events/SDL_events_c.h"
35#include "SDL_ph_modes_c.h"
36#include "SDL_ph_wm_c.h"
37
38void ph_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
39{
40 return;
41}
42
43/* Set window caption */
44void ph_SetCaption(_THIS, const char *title, const char *icon)
45{
46 SDL_Lock_EventThread();
47
48 /* sanity check for set caption call before window init */
49 if (window!=NULL)
50 {
51 PtSetResource(window, Pt_ARG_WINDOW_TITLE, title, 0);
52 }
53
54 SDL_Unlock_EventThread();
55}
56
57/* Iconify current window */
58int ph_IconifyWindow(_THIS)
59{
60 PhWindowEvent_t windowevent;
61
62 SDL_Lock_EventThread();
63
64 SDL_memset(&windowevent, 0, sizeof(windowevent));
65 windowevent.event_f = Ph_WM_HIDE;
66 windowevent.event_state = Ph_WM_EVSTATE_HIDE;
67 windowevent.rid = PtWidgetRid(window);
68 PtForwardWindowEvent(&windowevent);
69
70 SDL_Unlock_EventThread();
71
72 return 0;
73}
74
75SDL_GrabMode ph_GrabInputNoLock(_THIS, SDL_GrabMode mode)
76{
77 short abs_x, abs_y;
78
79 if( mode == SDL_GRAB_OFF )
80 {
81 PtSetResource(window, Pt_ARG_WINDOW_STATE, Pt_FALSE, Ph_WM_STATE_ISALTKEY);
82 }
83 else
84 {
85 PtSetResource(window, Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISALTKEY);
86
87 PtGetAbsPosition(window, &abs_x, &abs_y);
88 PhMoveCursorAbs(PhInputGroup(NULL), abs_x + SDL_VideoSurface->w/2, abs_y + SDL_VideoSurface->h/2);
89 }
90
91 SDL_Unlock_EventThread();
92
93 return(mode);
94}
95
96SDL_GrabMode ph_GrabInput(_THIS, SDL_GrabMode mode)
97{
98 SDL_Lock_EventThread();
99 mode = ph_GrabInputNoLock(this, mode);
100 SDL_Unlock_EventThread();
101
102 return(mode);
103}
104
105
106int ph_GetWMInfo(_THIS, SDL_SysWMinfo *info)
107{
108 if (info->version.major <= SDL_MAJOR_VERSION)
109 {
110 return 1;
111 }
112 else
113 {
114 SDL_SetError("Application not compiled with SDL %d.%d\n",
115 SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
116 return -1;
117 }
118}
diff --git a/apps/plugins/sdl/src/video/photon/SDL_ph_wm_c.h b/apps/plugins/sdl/src/video/photon/SDL_ph_wm_c.h
deleted file mode 100644
index 72bbfd217d..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_ph_wm_c.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SDL_PH_WM_H__
25#define __SDL_PH_WM_H__
26
27#include "SDL_ph_video.h"
28
29/* Functions to be exported */
30extern void ph_SetCaption(_THIS, const char *title, const char *icon);
31extern void ph_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask);
32extern int ph_IconifyWindow(_THIS);
33extern SDL_GrabMode ph_GrabInputNoLock(_THIS, SDL_GrabMode mode);
34extern SDL_GrabMode ph_GrabInput(_THIS, SDL_GrabMode mode);
35extern int ph_GetWMInfo(_THIS, SDL_SysWMinfo *info);
36
37#endif /* __SDL_PH_WM_H__ */
diff --git a/apps/plugins/sdl/src/video/photon/SDL_phyuv.c b/apps/plugins/sdl/src/video/photon/SDL_phyuv.c
deleted file mode 100644
index 06c72fded4..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_phyuv.c
+++ /dev/null
@@ -1,504 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the QNX Realtime Platform version of SDL YUV video overlays */
25
26#include <errno.h>
27
28#include <Ph.h>
29#include <Pt.h>
30
31#include "SDL_video.h"
32#include "SDL_phyuv_c.h"
33#include "../SDL_yuvfuncs.h"
34
35#define OVERLAY_STATE_UNINIT 0
36#define OVERLAY_STATE_ACTIVE 1
37
38/* The functions are used to manipulate software video overlays */
39static struct private_yuvhwfuncs ph_yuvfuncs =
40{
41 ph_LockYUVOverlay,
42 ph_UnlockYUVOverlay,
43 ph_DisplayYUVOverlay,
44 ph_FreeYUVOverlay
45};
46
47int grab_ptrs2(PgVideoChannel_t* channel, FRAMEDATA* Frame0, FRAMEDATA* Frame1)
48{
49 int planes = 0;
50
51 /* Buffers have moved; re-obtain the pointers */
52 Frame0->Y = (unsigned char *)PdGetOffscreenContextPtr(channel->yplane1);
53 Frame1->Y = (unsigned char *)PdGetOffscreenContextPtr(channel->yplane2);
54 Frame0->U = (unsigned char *)PdGetOffscreenContextPtr(channel->vplane1);
55 Frame1->U = (unsigned char *)PdGetOffscreenContextPtr(channel->vplane2);
56 Frame0->V = (unsigned char *)PdGetOffscreenContextPtr(channel->uplane1);
57 Frame1->V = (unsigned char *)PdGetOffscreenContextPtr(channel->uplane2);
58
59 if (Frame0->Y)
60 planes++;
61
62 if (Frame0->U)
63 planes++;
64
65 if (Frame0->V)
66 planes++;
67
68 return planes;
69}
70
71SDL_Overlay* ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface* display)
72{
73 SDL_Overlay* overlay;
74 struct private_yuvhwdata* hwdata;
75 int vidport;
76 int rtncode;
77 int planes;
78 int i=0;
79 PhPoint_t pos;
80
81 /* Create the overlay structure */
82 overlay = SDL_calloc(1, sizeof(SDL_Overlay));
83
84 if (overlay == NULL)
85 {
86 SDL_OutOfMemory();
87 return NULL;
88 }
89
90 /* Fill in the basic members */
91 overlay->format = format;
92 overlay->w = width;
93 overlay->h = height;
94 overlay->hwdata = NULL;
95
96 /* Set up the YUV surface function structure */
97 overlay->hwfuncs = &ph_yuvfuncs;
98
99 /* Create the pixel data and lookup tables */
100 hwdata = SDL_calloc(1, sizeof(struct private_yuvhwdata));
101
102 if (hwdata == NULL)
103 {
104 SDL_OutOfMemory();
105 SDL_FreeYUVOverlay(overlay);
106 return NULL;
107 }
108
109 overlay->hwdata = hwdata;
110
111 PhDCSetCurrent(0);
112 if (overlay->hwdata->channel == NULL)
113 {
114 if ((overlay->hwdata->channel = PgCreateVideoChannel(Pg_VIDEO_CHANNEL_SCALER, 0)) == NULL)
115 {
116 SDL_SetError("ph_CreateYUVOverlay(): Create channel failed: %s\n", strerror(errno));
117 SDL_FreeYUVOverlay(overlay);
118 return NULL;
119
120 }
121 }
122
123 overlay->hwdata->forcedredraw=0;
124
125 PtGetAbsPosition(window, &pos.x, &pos.y);
126 overlay->hwdata->CurrentWindowPos.x = pos.x;
127 overlay->hwdata->CurrentWindowPos.y = pos.y;
128 overlay->hwdata->CurrentViewPort.pos.x = 0;
129 overlay->hwdata->CurrentViewPort.pos.y = 0;
130 overlay->hwdata->CurrentViewPort.size.w = width;
131 overlay->hwdata->CurrentViewPort.size.h = height;
132 overlay->hwdata->State = OVERLAY_STATE_UNINIT;
133 overlay->hwdata->FrameData0 = (FRAMEDATA *) SDL_calloc(1, sizeof(FRAMEDATA));
134 overlay->hwdata->FrameData1 = (FRAMEDATA *) SDL_calloc(1, sizeof(FRAMEDATA));
135
136 vidport = -1;
137 i=0;
138
139 overlay->hwdata->ischromakey=0;
140
141 do {
142 SDL_memset(&overlay->hwdata->caps, 0x00, sizeof(PgScalerCaps_t));
143 overlay->hwdata->caps.size = sizeof(PgScalerCaps_t);
144 rtncode = PgGetScalerCapabilities(overlay->hwdata->channel, i, &overlay->hwdata->caps);
145 if (rtncode==0)
146 {
147 if (overlay->hwdata->caps.format==format)
148 {
149 if ((overlay->hwdata->caps.flags & Pg_SCALER_CAP_DST_CHROMA_KEY) == Pg_SCALER_CAP_DST_CHROMA_KEY)
150 {
151 overlay->hwdata->ischromakey=1;
152 }
153 vidport=1;
154 break;
155 }
156 }
157 else
158 {
159 break;
160 }
161 i++;
162 } while(1);
163
164
165 if (vidport == -1)
166 {
167 SDL_SetError("No available video ports for requested format\n");
168 SDL_FreeYUVOverlay(overlay);
169 return NULL;
170 }
171
172 overlay->hwdata->format = format;
173 overlay->hwdata->props.format = format;
174 overlay->hwdata->props.size = sizeof(PgScalerProps_t);
175 overlay->hwdata->props.src_dim.w = width;
176 overlay->hwdata->props.src_dim.h = height;
177
178 /* overlay->hwdata->chromakey = PgGetOverlayChromaColor(); */
179 overlay->hwdata->chromakey = PgRGB(12, 6, 12); /* very dark pink color */
180 overlay->hwdata->props.color_key = overlay->hwdata->chromakey;
181
182 PhAreaToRect(&overlay->hwdata->CurrentViewPort, &overlay->hwdata->props.viewport);
183
184 overlay->hwdata->props.flags = Pg_SCALER_PROP_DOUBLE_BUFFER;
185
186 if ((overlay->hwdata->ischromakey)&&(overlay->hwdata->chromakey))
187 {
188 overlay->hwdata->props.flags |= Pg_SCALER_PROP_CHROMA_ENABLE;
189 overlay->hwdata->props.flags |= Pg_SCALER_PROP_CHROMA_SPECIFY_KEY_MASK;
190 }
191 else
192 {
193 overlay->hwdata->props.flags &= ~Pg_SCALER_PROP_CHROMA_ENABLE;
194 }
195
196 rtncode = PgConfigScalerChannel(overlay->hwdata->channel, &overlay->hwdata->props);
197
198 switch(rtncode)
199 {
200 case -1: SDL_SetError("PgConfigScalerChannel failed\n");
201 SDL_FreeYUVOverlay(overlay);
202 return NULL;
203 case 1:
204 case 0:
205 default:
206 break;
207 }
208
209 planes = grab_ptrs2(overlay->hwdata->channel, overlay->hwdata->FrameData0, overlay->hwdata->FrameData1);
210
211 if(overlay->hwdata->channel->yplane1 != NULL)
212 overlay->hwdata->YStride = overlay->hwdata->channel->yplane1->pitch;
213 if(overlay->hwdata->channel->vplane1 != NULL)
214 overlay->hwdata->UStride = overlay->hwdata->channel->vplane1->pitch;
215 if(overlay->hwdata->channel->uplane1 != NULL)
216 overlay->hwdata->VStride = overlay->hwdata->channel->uplane1->pitch;
217
218 /* check for the validness of all planes */
219 if ((overlay->hwdata->channel->yplane1 == NULL) &&
220 (overlay->hwdata->channel->uplane1 == NULL) &&
221 (overlay->hwdata->channel->vplane1 == NULL))
222 {
223 SDL_FreeYUVOverlay(overlay);
224 SDL_SetError("PgConfigScaler() returns all planes equal NULL\n");
225 return NULL;
226 }
227/*
228 overlay->hwdata->current = PgNextVideoFrame(overlay->hwdata->channel);
229
230 if (overlay->hwdata->current==0)
231 {
232 overlay->hwdata->CurrentFrameData = overlay->hwdata->FrameData0;
233 }
234 else
235 {
236 overlay->hwdata->CurrentFrameData = overlay->hwdata->FrameData1;
237 }
238*/
239 overlay->hwdata->CurrentFrameData = overlay->hwdata->FrameData0;
240
241/*
242 overlay->hwdata->locked = 1;
243*/
244
245 /* Find the pitch and offset values for the overlay */
246 overlay->planes = planes;
247 overlay->pitches = SDL_calloc(overlay->planes, sizeof(Uint16));
248 overlay->pixels = SDL_calloc(overlay->planes, sizeof(Uint8*));
249 if (!overlay->pitches || !overlay->pixels)
250 {
251 SDL_OutOfMemory();
252 SDL_FreeYUVOverlay(overlay);
253 return(NULL);
254 }
255
256 if (overlay->planes > 0)
257 {
258 overlay->pitches[0] = overlay->hwdata->channel->yplane1->pitch;
259 overlay->pixels[0] = overlay->hwdata->CurrentFrameData->Y;
260 }
261 if (overlay->planes > 1)
262 {
263 overlay->pitches[1] = overlay->hwdata->channel->vplane1->pitch;
264 overlay->pixels[1] = overlay->hwdata->CurrentFrameData->U;
265 }
266 if (overlay->planes > 2)
267 {
268 overlay->pitches[2] = overlay->hwdata->channel->uplane1->pitch;
269 overlay->pixels[2] = overlay->hwdata->CurrentFrameData->V;
270 }
271
272 overlay->hwdata->State = OVERLAY_STATE_ACTIVE;
273 overlay->hwdata->scaler_on = 0;
274 overlay->hw_overlay = 1;
275
276 current_overlay=overlay;
277
278 return overlay;
279}
280
281int ph_LockYUVOverlay(_THIS, SDL_Overlay* overlay)
282{
283 if (overlay == NULL)
284 {
285 return -1;
286 }
287
288 overlay->hwdata->locked = 1;
289
290/* overlay->hwdata->current = PgNextVideoFrame(overlay->hwdata->channel);
291 if (overlay->hwdata->current == -1)
292 {
293 SDL_SetError("ph_LockYUVOverlay: PgNextFrame() failed, bailing out\n");
294 SDL_FreeYUVOverlay(overlay);
295 return 0;
296 }
297
298 if (overlay->hwdata->current == 0)
299 {
300 overlay->hwdata->CurrentFrameData = overlay->hwdata->FrameData0;
301 }
302 else
303 {
304 overlay->hwdata->CurrentFrameData = overlay->hwdata->FrameData1;
305 }
306
307 if (overlay->planes > 0)
308 {
309 overlay->pitches[0] = overlay->hwdata->channel->yplane1->pitch;
310 overlay->pixels[0] = overlay->hwdata->CurrentFrameData->Y;
311 }
312 if (overlay->planes > 1)
313 {
314 overlay->pitches[1] = overlay->hwdata->channel->uplane1->pitch;
315 overlay->pixels[1] = overlay->hwdata->CurrentFrameData->U;
316 }
317 if (overlay->planes > 2)
318 {
319 overlay->pitches[2] = overlay->hwdata->channel->vplane1->pitch;
320 overlay->pixels[2] = overlay->hwdata->CurrentFrameData->V;
321 }
322*/
323
324 return(0);
325}
326
327void ph_UnlockYUVOverlay(_THIS, SDL_Overlay* overlay)
328{
329 if (overlay == NULL)
330 {
331 return;
332 }
333
334 overlay->hwdata->locked = 0;
335}
336
337int ph_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect* dst)
338{
339 int rtncode;
340 PhPoint_t pos;
341 SDL_Rect backrect;
342 PhRect_t windowextent;
343 int winchanged=0;
344
345 if ((overlay == NULL) || (overlay->hwdata==NULL))
346 {
347 return -1;
348 }
349
350 if (overlay->hwdata->State == OVERLAY_STATE_UNINIT)
351 {
352 return -1;
353 }
354
355 PtGetAbsPosition(window, &pos.x, &pos.y);
356 if ((pos.x!=overlay->hwdata->CurrentWindowPos.x) ||
357 (pos.y!=overlay->hwdata->CurrentWindowPos.y))
358 {
359 winchanged=1;
360 overlay->hwdata->CurrentWindowPos.x=pos.x;
361 overlay->hwdata->CurrentWindowPos.y=pos.y;
362 }
363
364 /* If CurrentViewPort position/size has been changed, then move/resize the viewport */
365 if ((overlay->hwdata->CurrentViewPort.pos.x != dst->x) ||
366 (overlay->hwdata->CurrentViewPort.pos.y != dst->y) ||
367 (overlay->hwdata->CurrentViewPort.size.w != dst->w) ||
368 (overlay->hwdata->CurrentViewPort.size.h != dst->h) ||
369 (overlay->hwdata->scaler_on==0) || (winchanged==1) ||
370 (overlay->hwdata->forcedredraw==1))
371 {
372
373 if (overlay->hwdata->ischromakey==1)
374 {
375 /* restore screen behind the overlay/chroma color. */
376 backrect.x=overlay->hwdata->CurrentViewPort.pos.x;
377 backrect.y=overlay->hwdata->CurrentViewPort.pos.y;
378 backrect.w=overlay->hwdata->CurrentViewPort.size.w;
379 backrect.h=overlay->hwdata->CurrentViewPort.size.h;
380 this->UpdateRects(this, 1, &backrect);
381
382 /* Draw the new rectangle of the chroma color at the viewport position */
383 PgSetFillColor(overlay->hwdata->chromakey);
384 PgDrawIRect(dst->x, dst->y, dst->x+dst->w-1, dst->y+dst->h-1, Pg_DRAW_FILL);
385 PgFlush();
386 }
387
388 overlay->hwdata->props.flags |= Pg_SCALER_PROP_SCALER_ENABLE;
389 overlay->hwdata->scaler_on = 1;
390
391 PhWindowQueryVisible(Ph_QUERY_CONSOLE, 0, PtWidgetRid(window), &windowextent);
392 overlay->hwdata->CurrentViewPort.pos.x = pos.x-windowextent.ul.x+dst->x;
393 overlay->hwdata->CurrentViewPort.pos.y = pos.y-windowextent.ul.y+dst->y;
394 overlay->hwdata->CurrentViewPort.size.w = dst->w;
395 overlay->hwdata->CurrentViewPort.size.h = dst->h;
396 PhAreaToRect(&overlay->hwdata->CurrentViewPort, &overlay->hwdata->props.viewport);
397 overlay->hwdata->CurrentViewPort.pos.x = dst->x;
398 overlay->hwdata->CurrentViewPort.pos.y = dst->y;
399
400 rtncode = PgConfigScalerChannel(overlay->hwdata->channel, &(overlay->hwdata->props));
401
402 switch(rtncode)
403 {
404 case -1:
405 SDL_SetError("PgConfigScalerChannel() function failed\n");
406 SDL_FreeYUVOverlay(overlay);
407 return -1;
408 case 1:
409 grab_ptrs2(overlay->hwdata->channel, overlay->hwdata->FrameData0, overlay->hwdata->FrameData1);
410 break;
411 case 0:
412 default:
413 break;
414 }
415 }
416
417
418/*
419 if (overlay->hwdata->locked==0)
420 {
421 overlay->hwdata->current = PgNextVideoFrame(overlay->hwdata->channel);
422 if (overlay->hwdata->current == -1)
423 {
424 SDL_SetError("ph_LockYUVOverlay: PgNextFrame() failed, bailing out\n");
425 SDL_FreeYUVOverlay(overlay);
426 return 0;
427 }
428
429 if (overlay->hwdata->current == 0)
430 {
431 overlay->hwdata->CurrentFrameData = overlay->hwdata->FrameData0;
432 }
433 else
434 {
435 overlay->hwdata->CurrentFrameData = overlay->hwdata->FrameData1;
436 }
437
438 if (overlay->planes > 0)
439 {
440 overlay->pitches[0] = overlay->hwdata->channel->yplane1->pitch;
441 overlay->pixels[0] = overlay->hwdata->CurrentFrameData->Y;
442 }
443 if (overlay->planes > 1)
444 {
445 overlay->pitches[1] = overlay->hwdata->channel->uplane1->pitch;
446 overlay->pixels[1] = overlay->hwdata->CurrentFrameData->U;
447 }
448 if (overlay->planes > 2)
449 {
450 overlay->pitches[2] = overlay->hwdata->channel->vplane1->pitch;
451 overlay->pixels[2] = overlay->hwdata->CurrentFrameData->V;
452 }
453 }
454*/
455
456 return 0;
457}
458
459void ph_FreeYUVOverlay(_THIS, SDL_Overlay *overlay)
460{
461 SDL_Rect backrect;
462
463 if (overlay == NULL)
464 {
465 return;
466 }
467
468 if (overlay->hwdata == NULL)
469 {
470 return;
471 }
472
473 current_overlay=NULL;
474
475 /* restore screen behind the overlay/chroma color. */
476 backrect.x=overlay->hwdata->CurrentViewPort.pos.x;
477 backrect.y=overlay->hwdata->CurrentViewPort.pos.y;
478 backrect.w=overlay->hwdata->CurrentViewPort.size.w;
479 backrect.h=overlay->hwdata->CurrentViewPort.size.h;
480 this->UpdateRects(this, 1, &backrect);
481
482 /* it is need for some buggy drivers, that can't hide overlay before */
483 /* freeing buffer, so we got trash on the srceen */
484 overlay->hwdata->props.flags &= ~Pg_SCALER_PROP_SCALER_ENABLE;
485 PgConfigScalerChannel(overlay->hwdata->channel, &(overlay->hwdata->props));
486
487 overlay->hwdata->scaler_on = 0;
488 overlay->hwdata->State = OVERLAY_STATE_UNINIT;
489
490 if (overlay->hwdata->channel != NULL)
491 {
492 PgDestroyVideoChannel(overlay->hwdata->channel);
493 overlay->hwdata->channel = NULL;
494 return;
495 }
496
497 overlay->hwdata->CurrentFrameData = NULL;
498
499 SDL_free(overlay->hwdata->FrameData0);
500 SDL_free(overlay->hwdata->FrameData1);
501 overlay->hwdata->FrameData0 = NULL;
502 overlay->hwdata->FrameData1 = NULL;
503 SDL_free(overlay->hwdata);
504}
diff --git a/apps/plugins/sdl/src/video/photon/SDL_phyuv_c.h b/apps/plugins/sdl/src/video/photon/SDL_phyuv_c.h
deleted file mode 100644
index c6f73feb9f..0000000000
--- a/apps/plugins/sdl/src/video/photon/SDL_phyuv_c.h
+++ /dev/null
@@ -1,62 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef __SDL_PH_YUV_H__
25#define __SDL_PH_YUV_H__
26
27/* This is the photon implementation of YUV video overlays */
28
29#include "SDL_video.h"
30#include "SDL_ph_video.h"
31
32struct private_yuvhwdata
33{
34 FRAMEDATA* CurrentFrameData;
35 FRAMEDATA* FrameData0;
36 FRAMEDATA* FrameData1;
37 PgScalerProps_t props;
38 PgScalerCaps_t caps;
39 PgVideoChannel_t* channel;
40 PhArea_t CurrentViewPort;
41 PhPoint_t CurrentWindowPos;
42 long format;
43 int scaler_on;
44 int current;
45 long YStride;
46 long VStride;
47 long UStride;
48 int ischromakey;
49 long chromakey;
50 int forcedredraw;
51 unsigned long State;
52 long flags;
53 int locked;
54};
55
56extern SDL_Overlay* ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface* display);
57extern int ph_LockYUVOverlay(_THIS, SDL_Overlay* overlay);
58extern void ph_UnlockYUVOverlay(_THIS, SDL_Overlay* overlay);
59extern int ph_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect* dst);
60extern void ph_FreeYUVOverlay(_THIS, SDL_Overlay* overlay);
61
62#endif /* __SDL_PH_YUV_H__ */
diff --git a/apps/plugins/sdl/src/video/picogui/SDL_pgevents.c b/apps/plugins/sdl/src/video/picogui/SDL_pgevents.c
deleted file mode 100644
index 5006c07edf..0000000000
--- a/apps/plugins/sdl/src/video/picogui/SDL_pgevents.c
+++ /dev/null
@@ -1,117 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 Micah Dowty
23 micahjd@users.sourceforge.net
24*/
25#include "SDL_config.h"
26
27#include "SDL.h"
28#include "../../events/SDL_sysevents.h"
29#include "../../events/SDL_events_c.h"
30#include "SDL_pgvideo.h"
31#include "SDL_pgevents_c.h"
32
33int PG_HandleClose(struct pgEvent *evt)
34{
35 SDL_PrivateQuit();
36 return 1; /* Intercept the event's normal quit handling */
37}
38
39int PG_HandleResize(struct pgEvent *evt)
40{
41 SDL_PrivateResize(evt->e.size.w, evt->e.size.h);
42 return 0;
43}
44
45int PG_HandleKey(struct pgEvent *evt)
46{
47 SDL_keysym sym;
48 SDL_memset(&sym,0,sizeof(sym));
49 sym.sym = evt->e.kbd.key;
50 sym.mod = evt->e.kbd.mods;
51 SDL_PrivateKeyboard(evt->type == PG_WE_KBD_KEYDOWN, &sym);
52 return 0;
53}
54
55int PG_HandleChar(struct pgEvent *evt)
56{
57 SDL_keysym sym;
58 SDL_memset(&sym,0,sizeof(sym));
59 sym.unicode = evt->e.kbd.key;
60 sym.mod = evt->e.kbd.mods;
61 SDL_PrivateKeyboard(evt->type == PG_WE_KBD_KEYDOWN, &sym);
62 return 0;
63}
64
65int PG_HandleMouseButton(struct pgEvent *evt)
66{
67 /* We need to focus the canvas when it's clicked */
68 if (evt->extra) {
69 SDL_VideoDevice *this = (SDL_VideoDevice *) evt->extra;
70 pgFocus(this->hidden->wCanvas);
71 }
72 SDL_PrivateMouseButton(evt->type == PG_WE_PNTR_DOWN, evt->e.pntr.chbtn,
73 evt->e.pntr.x, evt->e.pntr.y);
74 return 0;
75}
76
77int PG_HandleMouseMotion(struct pgEvent *evt)
78{
79 SDL_PrivateMouseMotion(evt->e.pntr.btn,0,evt->e.pntr.x, evt->e.pntr.y);
80 return 0;
81}
82
83void PG_PumpEvents(_THIS)
84{
85 /* Process all pending events */
86 pgEventPoll();
87}
88
89void PG_InitOSKeymap(_THIS)
90{
91 /* We need no keymap */
92}
93
94void PG_InitEvents(_THIS)
95{
96 /* Turn on all the mouse and keyboard triggers for our canvas, normally less important
97 * events like mouse movement are ignored to save bandwidth. */
98 pgSetWidget(this->hidden->wCanvas, PG_WP_TRIGGERMASK,
99 pgGetWidget(this->hidden->wCanvas, PG_WP_TRIGGERMASK) |
100 PG_TRIGGER_UP | PG_TRIGGER_DOWN | PG_TRIGGER_MOVE |
101 PG_TRIGGER_KEYUP | PG_TRIGGER_KEYDOWN | PG_TRIGGER_CHAR,0);
102
103 /* Start our canvas out focused, so we get keyboard input */
104 pgFocus(this->hidden->wCanvas);
105
106 /* Set up bindings for all the above event handlers */
107 pgBind(this->hidden->wApp, PG_WE_CLOSE, &PG_HandleClose, NULL);
108 pgBind(this->hidden->wCanvas, PG_WE_BUILD, &PG_HandleResize, NULL);
109 pgBind(this->hidden->wCanvas, PG_WE_KBD_CHAR, &PG_HandleChar, NULL);
110 pgBind(this->hidden->wCanvas, PG_WE_KBD_KEYUP, &PG_HandleKey, NULL);
111 pgBind(this->hidden->wCanvas, PG_WE_KBD_KEYDOWN, &PG_HandleKey, NULL);
112 pgBind(this->hidden->wCanvas, PG_WE_PNTR_MOVE, &PG_HandleMouseMotion, NULL);
113 pgBind(this->hidden->wCanvas, PG_WE_PNTR_UP, &PG_HandleMouseButton, NULL);
114 pgBind(this->hidden->wCanvas, PG_WE_PNTR_DOWN, &PG_HandleMouseButton, this);
115}
116
117/* end of SDL_pgevents.c ... */
diff --git a/apps/plugins/sdl/src/video/picogui/SDL_pgevents_c.h b/apps/plugins/sdl/src/video/picogui/SDL_pgevents_c.h
deleted file mode 100644
index a54e225129..0000000000
--- a/apps/plugins/sdl/src/video/picogui/SDL_pgevents_c.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 Micah Dowty
23 micahjd@users.sourceforge.net
24*/
25#include "SDL_config.h"
26
27#include "SDL_pgvideo.h"
28
29/* Variables and functions exported by SDL_sysevents.c to other parts
30 of the native video subsystem (SDL_sysvideo.c)
31*/
32extern void PG_PumpEvents(_THIS);
33extern void PG_InitEvents(_THIS);
34extern void PG_InitOSKeymap(_THIS);
35
36/* end of SDL_pgevents_c.h ... */
37
diff --git a/apps/plugins/sdl/src/video/picogui/SDL_pgvideo.c b/apps/plugins/sdl/src/video/picogui/SDL_pgvideo.c
deleted file mode 100644
index 18b3fe4e50..0000000000
--- a/apps/plugins/sdl/src/video/picogui/SDL_pgvideo.c
+++ /dev/null
@@ -1,364 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 Micah Dowty
23 micahjd@users.sourceforge.net
24*/
25#include "SDL_config.h"
26
27#include "SDL_video.h"
28#include "SDL_mouse.h"
29#include "../SDL_sysvideo.h"
30#include "../SDL_pixels_c.h"
31#include "../../events/SDL_events_c.h"
32
33#include "SDL_pgvideo.h"
34#include "SDL_pgevents_c.h"
35
36#define PGVID_DRIVER_NAME "picogui"
37
38/* Initialization/Query functions */
39static int PG_VideoInit(_THIS, SDL_PixelFormat *vformat);
40static SDL_Rect **PG_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
41static SDL_Surface *PG_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
42static int PG_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
43static void PG_VideoQuit(_THIS);
44
45/* Hardware surface functions */
46static int PG_AllocHWSurface(_THIS, SDL_Surface *surface);
47static int PG_LockHWSurface(_THIS, SDL_Surface *surface);
48static void PG_UnlockHWSurface(_THIS, SDL_Surface *surface);
49static void PG_FreeHWSurface(_THIS, SDL_Surface *surface);
50
51/* etc. */
52static void PG_UpdateRects(_THIS, int numrects, SDL_Rect *rects);
53
54// The implementation dependent data for the window manager cursor
55struct WMcursor {
56 /* Our cursor is a PicoGUI theme */
57 pghandle theme;
58} ;
59
60/* WM functions */
61void PG_SetCaption(_THIS, const char *title, const char *icon);
62WMcursor * PG_CreateWMCursor (_THIS,Uint8 * data, Uint8 * mask,
63 int w, int h, int hot_x, int hot_y);
64void PG_FreeWMCursor (_THIS, WMcursor * cursor);
65void PG_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
66int PG_ShowWMCursor (_THIS, WMcursor * cursor);
67
68/* PicoGUI driver bootstrap functions */
69
70static int PG_Available(void)
71{
72 /* FIXME: The current client lib doesn't give a way to see if the picogui
73 * server is reachable without causing a fatal error if it isn't.
74 * This should be fixed in cli_c2, but until then assume we can
75 * connect. Since more common drivers like X11 are probed first anyway,
76 * this shouldn't be a huge problem.
77 */
78 return(1);
79}
80
81static void PG_DeleteDevice(SDL_VideoDevice *device)
82{
83 SDL_free(device->hidden);
84 SDL_free(device);
85}
86
87static SDL_VideoDevice *PG_CreateDevice(int devindex)
88{
89 SDL_VideoDevice *device;
90
91 /* Initialize all variables that we clean on shutdown */
92 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
93 if ( device ) {
94 SDL_memset(device, 0, (sizeof *device));
95 device->hidden = (struct SDL_PrivateVideoData *)
96 SDL_malloc((sizeof *device->hidden));
97 }
98 if ( (device == NULL) || (device->hidden == NULL) ) {
99 SDL_OutOfMemory();
100 if ( device ) {
101 SDL_free(device);
102 }
103 return(0);
104 }
105 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
106
107 /* Set the function pointers */
108 device->VideoInit = PG_VideoInit;
109 device->ListModes = PG_ListModes;
110 device->SetVideoMode = PG_SetVideoMode;
111 device->CreateYUVOverlay = NULL;
112 device->SetColors = PG_SetColors;
113 device->UpdateRects = PG_UpdateRects;
114 device->VideoQuit = PG_VideoQuit;
115 device->AllocHWSurface = PG_AllocHWSurface;
116 device->CheckHWBlit = NULL;
117 device->FillHWRect = NULL;
118 device->SetHWColorKey = NULL;
119 device->SetHWAlpha = NULL;
120 device->LockHWSurface = PG_LockHWSurface;
121 device->UnlockHWSurface = PG_UnlockHWSurface;
122 device->FlipHWSurface = NULL;
123 device->FreeHWSurface = PG_FreeHWSurface;
124 device->SetCaption = PG_SetCaption;
125 device->SetIcon = NULL;
126 device->IconifyWindow = NULL;
127 device->GrabInput = NULL;
128
129 device->PumpEvents = PG_PumpEvents;
130 device->InitOSKeymap = PG_InitOSKeymap;
131
132 device->ShowWMCursor = PG_ShowWMCursor;
133 device->CreateWMCursor = PG_CreateWMCursor;
134 device->FreeWMCursor = PG_FreeWMCursor;
135 device->WarpWMCursor = PG_WarpWMCursor;
136
137 device->free = PG_DeleteDevice;
138
139 return device;
140}
141
142VideoBootStrap PG_bootstrap = {
143 PGVID_DRIVER_NAME, "PicoGUI SDL driver",
144 PG_Available, PG_CreateDevice
145};
146
147
148int PG_VideoInit(_THIS, SDL_PixelFormat *vformat)
149{
150 /* Connect to the PicoGUI server. No way to process command line args yet,
151 * but since this is based on SHM it's not important to be able to specify
152 * a remote PicoGUI server.
153 *
154 * FIXME: Another nitpick about the current client lib is there's no
155 * clean way to indicate that command line args are not available.
156 */
157 pgInit(0,(char**)"");
158 this->hidden->mi = *pgGetVideoMode();
159
160 /* Create a picogui application and canvas. We'll populate the canvas later. */
161 this->hidden->wApp = pgRegisterApp(PG_APP_NORMAL,"SDL",0);
162 this->hidden->wCanvas = pgNewWidget(PG_WIDGET_CANVAS,0,0);
163 pgSetWidget(PGDEFAULT,
164 PG_WP_SIDE, PG_S_ALL,
165 0);
166
167 PG_InitEvents(this);
168
169 /* Determine the current screen size */
170 this->info.current_w = this->hidden->mi.lxres;
171 this->info.current_h = this->hidden->mi.lyres;
172
173 /* Determine the screen depth.
174 * We change this during the SDL_SetVideoMode implementation...
175 * Round up to the nearest Bytes per pixel
176 */
177 vformat->BitsPerPixel = this->hidden->mi.bpp;
178 vformat->BytesPerPixel = this->hidden->mi.bpp >> 3;
179 if (this->hidden->mi.bpp & 7)
180 vformat->BytesPerPixel++;
181
182 /* We're done! */
183 return(0);
184}
185
186SDL_Rect **PG_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
187{
188 return (SDL_Rect **) -1;
189}
190
191SDL_Surface *PG_SetVideoMode(_THIS, SDL_Surface *current,
192 int width, int height, int bpp, Uint32 flags)
193{
194 if ( this->hidden->bitmap ) {
195 /* Free old bitmap */
196 if (current->pixels) {
197 shmdt(current->pixels);
198 current->pixels = NULL;
199 }
200 pgDelete(this->hidden->bitmap);
201 }
202
203 /* Allocate the new pixel format for the screen */
204 if ( ! SDL_ReallocFormat(current, bpp, 0, 0, 0, 0) ) {
205 SDL_SetError("Couldn't allocate new pixel format for requested mode");
206 return(NULL);
207 }
208
209 /* Create a new picogui bitmap */
210 this->hidden->bitmap = pgCreateBitmap(width,height);
211 this->hidden->shm = *pgMakeSHMBitmap(this->hidden->bitmap);
212 current->pixels = shmat(shmget(this->hidden->shm.shm_key,
213 this->hidden->shm.shm_length,0),NULL,0);
214
215 /* Reset the canvas, and draw persistent and incremental grops.
216 * Use mapping and offsets to center it.
217 */
218
219 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_NUKE, 0);
220
221 /* 0. Set the source position during incremental rendering
222 */
223 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROP, 5, PG_GROP_SETSRC,0,0,0,0);
224 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROPFLAGS, 1, PG_GROPF_INCREMENTAL);
225
226 /* 1. Incremental bitmap rendering
227 */
228 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROP, 6, PG_GROP_BITMAP,
229 0,0,0,0,this->hidden->bitmap);
230 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROPFLAGS, 1, PG_GROPF_INCREMENTAL);
231
232 /* 2. Normal bitmap rendering
233 */
234 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROP, 6, PG_GROP_BITMAP,
235 0,0,this->hidden->shm.width,this->hidden->shm.height,this->hidden->bitmap);
236
237 /* Set up the new mode framebuffer */
238 current->flags = 0;
239 current->w = this->hidden->shm.width;
240 current->h = this->hidden->shm.height;
241 current->pitch = this->hidden->shm.pitch;
242
243 /* Set up pixel format */
244 current->format->BitsPerPixel = this->hidden->shm.bpp;
245 current->format->BytesPerPixel = this->hidden->shm.bpp >> 3;
246 if (this->hidden->shm.bpp & 7)
247 current->format->BytesPerPixel++;
248 current->format->palette = NULL;
249 current->format->Rmask = this->hidden->shm.red_mask;
250 current->format->Gmask = this->hidden->shm.green_mask;
251 current->format->Bmask = this->hidden->shm.blue_mask;
252 current->format->Amask = this->hidden->shm.alpha_mask;
253 current->format->Rshift = this->hidden->shm.red_shift;
254 current->format->Gshift = this->hidden->shm.green_shift;
255 current->format->Bshift = this->hidden->shm.blue_shift;
256 current->format->Ashift = this->hidden->shm.alpha_shift;
257 current->format->Rloss = 8 - this->hidden->shm.red_length;
258 current->format->Gloss = 8 - this->hidden->shm.green_length;
259 current->format->Bloss = 8 - this->hidden->shm.blue_length;
260 current->format->Aloss = 8 - this->hidden->shm.alpha_length;
261
262 /* Draw the app */
263 pgUpdate();
264
265 /* We're done */
266 return(current);
267}
268
269/* We don't actually allow hardware surfaces other than the main one */
270static int PG_AllocHWSurface(_THIS, SDL_Surface *surface)
271{
272 return(-1);
273}
274static void PG_FreeHWSurface(_THIS, SDL_Surface *surface)
275{
276 return;
277}
278
279/* We need to wait for vertical retrace on page flipped displays */
280static int PG_LockHWSurface(_THIS, SDL_Surface *surface)
281{
282 return(0);
283}
284
285static void PG_UnlockHWSurface(_THIS, SDL_Surface *surface)
286{
287 return;
288}
289
290static void PG_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
291{
292 int i;
293
294 for (i = 0; i < numrects; i++) {
295 if (rects[i].w <= 0 || rects[i].h <= 0)
296 continue;
297
298 /* Schedule an incremental update for this rectangle, using
299 * the canvas gropnodes we've loaded beforehand.
300 */
301 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_FINDGROP, 1, 0);
302 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_MOVEGROP, 4,
303 rects[i].x, rects[i].y,
304 rects[i].w, rects[i].h);
305 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_FINDGROP, 1, 1);
306 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_MOVEGROP, 4,
307 rects[i].x, rects[i].y,
308 rects[i].w, rects[i].h);
309
310 /* Go perform the update */
311 pgWriteCmd(this->hidden->wCanvas, PGCANVAS_INCREMENTAL, 0);
312 pgSubUpdate(this->hidden->wCanvas);
313 }
314}
315
316int PG_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
317{
318 /* do nothing of note. */
319 return(1);
320}
321
322/* Note: If we are terminated, this could be called in the middle of
323 another SDL video routine -- notably UpdateRects.
324*/
325void PG_VideoQuit(_THIS)
326{
327 if (this->screen->pixels != NULL)
328 {
329 shmdt(this->screen->pixels);
330 this->screen->pixels = NULL;
331 pgDelete(this->hidden->bitmap);
332 }
333 pgDelete(this->hidden->wCanvas);
334 pgDelete(this->hidden->wApp);
335}
336
337void PG_SetCaption(_THIS, const char *title, const char *icon)
338{
339 if (title != NULL)
340 pgReplaceText(this->hidden->wApp, title);
341 pgUpdate();
342}
343
344/* FIXME: The cursor stuff isn't implemented yet! */
345
346WMcursor * PG_CreateWMCursor (_THIS,Uint8 * data, Uint8 * mask,
347 int w, int h, int hot_x, int hot_y)
348{
349 static WMcursor dummy;
350 return &dummy;
351}
352
353void PG_FreeWMCursor (_THIS, WMcursor * cursor)
354{
355}
356
357void PG_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
358{
359}
360
361int PG_ShowWMCursor (_THIS, WMcursor * cursor)
362{
363 return 1;
364}
diff --git a/apps/plugins/sdl/src/video/picogui/SDL_pgvideo.h b/apps/plugins/sdl/src/video/picogui/SDL_pgvideo.h
deleted file mode 100644
index 155f86b67d..0000000000
--- a/apps/plugins/sdl/src/video/picogui/SDL_pgvideo.h
+++ /dev/null
@@ -1,50 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21
22 Micah Dowty
23 micahjd@users.sourceforge.net
24*/
25#include "SDL_config.h"
26
27#ifndef _SDL_pgvideo_h
28#define _SDL_pgvideo_h
29
30#include "SDL_mouse.h"
31#include "SDL_mutex.h"
32#include "../SDL_sysvideo.h"
33
34#include <picogui.h>
35#include <sys/shm.h>
36
37/* Hidden "this" pointer for the video functions */
38#define _THIS SDL_VideoDevice *this
39
40
41/* Private display data */
42
43struct SDL_PrivateVideoData {
44 pghandle wApp, wCanvas; /* PicoGUI widgets */
45 pghandle bitmap;
46 struct pgshmbitmap shm; /* shared memory info */
47 struct pgmodeinfo mi; /* PicoGUI video mode info structure */
48};
49
50#endif /* _SDL_pgvideo_h */
diff --git a/apps/plugins/sdl/src/video/ps2gs/SDL_gsevents.c b/apps/plugins/sdl/src/video/ps2gs/SDL_gsevents.c
deleted file mode 100644
index 1b842afe39..0000000000
--- a/apps/plugins/sdl/src/video/ps2gs/SDL_gsevents.c
+++ /dev/null
@@ -1,977 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting console events into SDL events */
25
26#include <sys/types.h>
27#include <sys/time.h>
28#include <sys/ioctl.h>
29#include <unistd.h>
30#include <fcntl.h>
31#include <errno.h>
32#include <limits.h>
33
34/* For parsing /proc */
35#include <dirent.h>
36#include <ctype.h>
37
38#include <linux/vt.h>
39#include <linux/kd.h>
40#include <linux/keyboard.h>
41
42#include "SDL_mutex.h"
43#include "../SDL_sysvideo.h"
44#include "../../events/SDL_sysevents.h"
45#include "../../events/SDL_events_c.h"
46#include "SDL_gsvideo.h"
47#include "SDL_gsevents_c.h"
48#include "SDL_gskeys.h"
49
50#ifndef GPM_NODE_FIFO
51#define GPM_NODE_FIFO "/dev/gpmdata"
52#endif
53
54/* The translation tables from a console scancode to a SDL keysym */
55#define NUM_VGAKEYMAPS (1<<KG_CAPSSHIFT)
56static Uint16 vga_keymap[NUM_VGAKEYMAPS][NR_KEYS];
57static SDLKey keymap[128];
58static Uint16 keymap_temp[128]; /* only used at startup */
59static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym);
60
61/* Ugh, we have to duplicate the kernel's keysym mapping code...
62 Oh, it's not so bad. :-)
63
64 FIXME: Add keyboard LED handling code
65 */
66static void GS_vgainitkeymaps(int fd)
67{
68 struct kbentry entry;
69 int map, i;
70
71 /* Don't do anything if we are passed a closed keyboard */
72 if ( fd < 0 ) {
73 return;
74 }
75
76 /* Load all the keysym mappings */
77 for ( map=0; map<NUM_VGAKEYMAPS; ++map ) {
78 SDL_memset(vga_keymap[map], 0, NR_KEYS*sizeof(Uint16));
79 for ( i=0; i<NR_KEYS; ++i ) {
80 entry.kb_table = map;
81 entry.kb_index = i;
82 if ( ioctl(fd, KDGKBENT, &entry) == 0 ) {
83 /* fill keytemp. This replaces SDL_fbkeys.h */
84 if ( (map == 0) && (i<128) ) {
85 keymap_temp[i] = entry.kb_value;
86 }
87 /* The "Enter" key is a special case */
88 if ( entry.kb_value == K_ENTER ) {
89 entry.kb_value = K(KT_ASCII,13);
90 }
91 /* Handle numpad specially as well */
92 if ( KTYP(entry.kb_value) == KT_PAD ) {
93 switch ( entry.kb_value ) {
94 case K_P0:
95 case K_P1:
96 case K_P2:
97 case K_P3:
98 case K_P4:
99 case K_P5:
100 case K_P6:
101 case K_P7:
102 case K_P8:
103 case K_P9:
104 vga_keymap[map][i]=entry.kb_value;
105 vga_keymap[map][i]+= '0';
106 break;
107 case K_PPLUS:
108 vga_keymap[map][i]=K(KT_ASCII,'+');
109 break;
110 case K_PMINUS:
111 vga_keymap[map][i]=K(KT_ASCII,'-');
112 break;
113 case K_PSTAR:
114 vga_keymap[map][i]=K(KT_ASCII,'*');
115 break;
116 case K_PSLASH:
117 vga_keymap[map][i]=K(KT_ASCII,'/');
118 break;
119 case K_PENTER:
120 vga_keymap[map][i]=K(KT_ASCII,'\r');
121 break;
122 case K_PCOMMA:
123 vga_keymap[map][i]=K(KT_ASCII,',');
124 break;
125 case K_PDOT:
126 vga_keymap[map][i]=K(KT_ASCII,'.');
127 break;
128 default:
129 break;
130 }
131 }
132 /* Do the normal key translation */
133 if ( (KTYP(entry.kb_value) == KT_LATIN) ||
134 (KTYP(entry.kb_value) == KT_ASCII) ||
135 (KTYP(entry.kb_value) == KT_LETTER) ) {
136 vga_keymap[map][i] = entry.kb_value;
137 }
138 }
139 }
140 }
141}
142
143int GS_InGraphicsMode(_THIS)
144{
145 return((keyboard_fd >= 0) && (saved_kbd_mode >= 0));
146}
147
148int GS_EnterGraphicsMode(_THIS)
149{
150 struct termios keyboard_termios;
151
152 /* Set medium-raw keyboard mode */
153 if ( (keyboard_fd >= 0) && !GS_InGraphicsMode(this) ) {
154
155 /* Switch to the correct virtual terminal */
156 if ( current_vt > 0 ) {
157 struct vt_stat vtstate;
158
159 if ( ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0 ) {
160 saved_vt = vtstate.v_active;
161 }
162 if ( ioctl(keyboard_fd, VT_ACTIVATE, current_vt) == 0 ) {
163 ioctl(keyboard_fd, VT_WAITACTIVE, current_vt);
164 }
165 }
166
167 /* Set the terminal input mode */
168 if ( tcgetattr(keyboard_fd, &saved_kbd_termios) < 0 ) {
169 SDL_SetError("Unable to get terminal attributes");
170 if ( keyboard_fd > 0 ) {
171 close(keyboard_fd);
172 }
173 keyboard_fd = -1;
174 return(-1);
175 }
176 if ( ioctl(keyboard_fd, KDGKBMODE, &saved_kbd_mode) < 0 ) {
177 SDL_SetError("Unable to get current keyboard mode");
178 if ( keyboard_fd > 0 ) {
179 close(keyboard_fd);
180 }
181 keyboard_fd = -1;
182 return(-1);
183 }
184 keyboard_termios = saved_kbd_termios;
185 keyboard_termios.c_lflag &= ~(ICANON | ECHO | ISIG);
186 keyboard_termios.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON);
187 keyboard_termios.c_cc[VMIN] = 0;
188 keyboard_termios.c_cc[VTIME] = 0;
189 if (tcsetattr(keyboard_fd, TCSAFLUSH, &keyboard_termios) < 0) {
190 GS_CloseKeyboard(this);
191 SDL_SetError("Unable to set terminal attributes");
192 return(-1);
193 }
194 /* This will fail if we aren't root or this isn't our tty */
195 if ( ioctl(keyboard_fd, KDSKBMODE, K_MEDIUMRAW) < 0 ) {
196 GS_CloseKeyboard(this);
197 SDL_SetError("Unable to set keyboard in raw mode");
198 return(-1);
199 }
200 if ( ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS) < 0 ) {
201 GS_CloseKeyboard(this);
202 SDL_SetError("Unable to set keyboard in graphics mode");
203 return(-1);
204 }
205 }
206 return(keyboard_fd);
207}
208
209void GS_LeaveGraphicsMode(_THIS)
210{
211 if ( GS_InGraphicsMode(this) ) {
212 ioctl(keyboard_fd, KDSETMODE, KD_TEXT);
213 ioctl(keyboard_fd, KDSKBMODE, saved_kbd_mode);
214 tcsetattr(keyboard_fd, TCSAFLUSH, &saved_kbd_termios);
215 saved_kbd_mode = -1;
216
217 /* Head back over to the original virtual terminal */
218 if ( saved_vt > 0 ) {
219 ioctl(keyboard_fd, VT_ACTIVATE, saved_vt);
220 }
221 }
222}
223
224void GS_CloseKeyboard(_THIS)
225{
226 if ( keyboard_fd >= 0 ) {
227 GS_LeaveGraphicsMode(this);
228 if ( keyboard_fd > 0 ) {
229 close(keyboard_fd);
230 }
231 }
232 keyboard_fd = -1;
233}
234
235int GS_OpenKeyboard(_THIS)
236{
237 /* Open only if not already opened */
238 if ( keyboard_fd < 0 ) {
239 char *tty0[] = { "/dev/tty0", "/dev/vc/0", NULL };
240 char *vcs[] = { "/dev/vc/%d", "/dev/tty%d", NULL };
241 int i, tty0_fd;
242
243 /* Try to query for a free virtual terminal */
244 tty0_fd = -1;
245 for ( i=0; tty0[i] && (tty0_fd < 0); ++i ) {
246 tty0_fd = open(tty0[i], O_WRONLY, 0);
247 }
248 if ( tty0_fd < 0 ) {
249 tty0_fd = dup(0); /* Maybe stdin is a VT? */
250 }
251 ioctl(tty0_fd, VT_OPENQRY, &current_vt);
252 close(tty0_fd);
253 if ( (geteuid() == 0) && (current_vt > 0) ) {
254 for ( i=0; vcs[i] && (keyboard_fd < 0); ++i ) {
255 char vtpath[12];
256
257 SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], current_vt);
258 keyboard_fd = open(vtpath, O_RDWR, 0);
259#ifdef DEBUG_KEYBOARD
260 fprintf(stderr, "vtpath = %s, fd = %d\n",
261 vtpath, keyboard_fd);
262#endif /* DEBUG_KEYBOARD */
263
264 /* This needs to be our controlling tty
265 so that the kernel ioctl() calls work
266 */
267 if ( keyboard_fd >= 0 ) {
268 tty0_fd = open("/dev/tty", O_RDWR, 0);
269 if ( tty0_fd >= 0 ) {
270 ioctl(tty0_fd, TIOCNOTTY, 0);
271 close(tty0_fd);
272 }
273 }
274 }
275 }
276 if ( keyboard_fd < 0 ) {
277 /* Last resort, maybe our tty is a usable VT */
278 current_vt = 0;
279 keyboard_fd = open("/dev/tty", O_RDWR);
280 }
281#ifdef DEBUG_KEYBOARD
282 fprintf(stderr, "Current VT: %d\n", current_vt);
283#endif
284 saved_kbd_mode = -1;
285
286 /* Make sure that our input is a console terminal */
287 { int dummy;
288 if ( ioctl(keyboard_fd, KDGKBMODE, &dummy) < 0 ) {
289 close(keyboard_fd);
290 keyboard_fd = -1;
291 SDL_SetError("Unable to open a console terminal");
292 }
293 }
294
295 /* Set up keymap */
296 GS_vgainitkeymaps(keyboard_fd);
297 }
298 return(keyboard_fd);
299}
300
301static enum {
302 MOUSE_NONE = -1,
303 MOUSE_GPM, /* Note: GPM uses the MSC protocol */
304 MOUSE_PS2,
305 MOUSE_IMPS2,
306 MOUSE_MS,
307 MOUSE_BM,
308 NUM_MOUSE_DRVS
309} mouse_drv = MOUSE_NONE;
310
311void GS_CloseMouse(_THIS)
312{
313 if ( mouse_fd > 0 ) {
314 close(mouse_fd);
315 }
316 mouse_fd = -1;
317}
318
319/* Returns processes listed in /proc with the desired name */
320static int find_pid(DIR *proc, const char *wanted_name)
321{
322 struct dirent *entry;
323 int pid;
324
325 /* First scan proc for the gpm process */
326 pid = 0;
327 while ( (pid == 0) && ((entry=readdir(proc)) != NULL) ) {
328 if ( isdigit(entry->d_name[0]) ) {
329 FILE *status;
330 char path[PATH_MAX];
331 char name[PATH_MAX];
332
333 SDL_snprintf(path, SDL_arraysize(path), "/proc/%s/status", entry->d_name);
334 status=fopen(path, "r");
335 if ( status ) {
336 name[0] = '\0';
337 fscanf(status, "Name: %s", name);
338 if ( SDL_strcmp(name, wanted_name) == 0 ) {
339 pid = atoi(entry->d_name);
340 }
341 fclose(status);
342 }
343 }
344 }
345 return pid;
346}
347
348/* Returns true if /dev/gpmdata is being written to by gpm */
349static int gpm_available(void)
350{
351 int available;
352 DIR *proc;
353 int pid;
354 int cmdline, len, arglen;
355 char path[PATH_MAX];
356 char args[PATH_MAX], *arg;
357
358 /* Don't bother looking if the fifo isn't there */
359 if ( access(GPM_NODE_FIFO, F_OK) < 0 ) {
360 return(0);
361 }
362
363 available = 0;
364 proc = opendir("/proc");
365 if ( proc ) {
366 while ( (pid=find_pid(proc, "gpm")) > 0 ) {
367 SDL_snprintf(path, SDL_arraysize(path), "/proc/%d/cmdline", pid);
368 cmdline = open(path, O_RDONLY, 0);
369 if ( cmdline >= 0 ) {
370 len = read(cmdline, args, sizeof(args));
371 arg = args;
372 while ( len > 0 ) {
373 if ( SDL_strcmp(arg, "-R") == 0 ) {
374 available = 1;
375 }
376 arglen = SDL_strlen(arg)+1;
377 len -= arglen;
378 arg += arglen;
379 }
380 close(cmdline);
381 }
382 }
383 closedir(proc);
384 }
385 return available;
386}
387
388
389/* rcg06112001 Set up IMPS/2 mode, if possible. This gives
390 * us access to the mousewheel, etc. Returns zero if
391 * writes to device failed, but you still need to query the
392 * device to see which mode it's actually in.
393 */
394static int set_imps2_mode(int fd)
395{
396 /* If you wanted to control the mouse mode (and we do :) ) ...
397 Set IMPS/2 protocol:
398 {0xf3,200,0xf3,100,0xf3,80}
399 Reset mouse device:
400 {0xFF}
401 */
402 Uint8 set_imps2[] = {0xf3, 200, 0xf3, 100, 0xf3, 80};
403 Uint8 reset = 0xff;
404 fd_set fdset;
405 struct timeval tv;
406 int retval = 0;
407
408 if ( write(fd, &set_imps2, sizeof(set_imps2)) == sizeof(set_imps2) ) {
409 if (write(fd, &reset, sizeof (reset)) == sizeof (reset) ) {
410 retval = 1;
411 }
412 }
413
414 /* Get rid of any chatter from the above */
415 FD_ZERO(&fdset);
416 FD_SET(fd, &fdset);
417 tv.tv_sec = 0;
418 tv.tv_usec = 0;
419 while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) {
420 char temp[32];
421 read(fd, temp, sizeof(temp));
422 }
423
424 return retval;
425}
426
427
428/* Returns true if the mouse uses the IMPS/2 protocol */
429static int detect_imps2(int fd)
430{
431 int imps2;
432
433 imps2 = 0;
434
435 if ( SDL_getenv("SDL_MOUSEDEV_IMPS2") ) {
436 imps2 = 1;
437 }
438 if ( ! imps2 ) {
439 Uint8 query_ps2 = 0xF2;
440 fd_set fdset;
441 struct timeval tv;
442
443 /* Get rid of any mouse motion noise */
444 FD_ZERO(&fdset);
445 FD_SET(fd, &fdset);
446 tv.tv_sec = 0;
447 tv.tv_usec = 0;
448 while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) {
449 char temp[32];
450 read(fd, temp, sizeof(temp));
451 }
452
453 /* Query for the type of mouse protocol */
454 if ( write(fd, &query_ps2, sizeof (query_ps2)) == sizeof (query_ps2)) {
455 Uint8 ch = 0;
456
457 /* Get the mouse protocol response */
458 do {
459 FD_ZERO(&fdset);
460 FD_SET(fd, &fdset);
461 tv.tv_sec = 1;
462 tv.tv_usec = 0;
463 if ( select(fd+1, &fdset, 0, 0, &tv) < 1 ) {
464 break;
465 }
466 } while ( (read(fd, &ch, sizeof (ch)) == sizeof (ch)) &&
467 ((ch == 0xFA) || (ch == 0xAA)) );
468
469 /* Experimental values (Logitech wheelmouse) */
470#ifdef DEBUG_MOUSE
471fprintf(stderr, "Last mouse mode: 0x%x\n", ch);
472#endif
473 if ( ch == 3 ) {
474 imps2 = 1;
475 }
476 }
477 }
478 return imps2;
479}
480
481int GS_OpenMouse(_THIS)
482{
483 int i;
484 const char *mousedev;
485 const char *mousedrv;
486
487 mousedrv = SDL_getenv("SDL_MOUSEDRV");
488 mousedev = SDL_getenv("SDL_MOUSEDEV");
489 mouse_fd = -1;
490
491 /* STD MICE */
492
493 if ( mousedev == NULL ) {
494 /* FIXME someday... allow multiple mice in this driver */
495 char *ps2mice[] = {
496 "/dev/input/mice", "/dev/usbmouse", "/dev/psaux", NULL
497 };
498 /* First try to use GPM in repeater mode */
499 if ( mouse_fd < 0 ) {
500 if ( gpm_available() ) {
501 mouse_fd = open(GPM_NODE_FIFO, O_RDONLY, 0);
502 if ( mouse_fd >= 0 ) {
503#ifdef DEBUG_MOUSE
504fprintf(stderr, "Using GPM mouse\n");
505#endif
506 mouse_drv = MOUSE_GPM;
507 }
508 }
509 }
510 /* Now try to use a modern PS/2 mouse */
511 for ( i=0; (mouse_fd < 0) && ps2mice[i]; ++i ) {
512 mouse_fd = open(ps2mice[i], O_RDWR, 0);
513 if (mouse_fd < 0) {
514 mouse_fd = open(ps2mice[i], O_RDONLY, 0);
515 }
516 if (mouse_fd >= 0) {
517 /* rcg06112001 Attempt to set IMPS/2 mode */
518 if ( i == 0 ) {
519 set_imps2_mode(mouse_fd);
520 }
521 if (detect_imps2(mouse_fd)) {
522#ifdef DEBUG_MOUSE
523fprintf(stderr, "Using IMPS2 mouse\n");
524#endif
525 mouse_drv = MOUSE_IMPS2;
526 } else {
527 mouse_drv = MOUSE_PS2;
528#ifdef DEBUG_MOUSE
529fprintf(stderr, "Using PS2 mouse\n");
530#endif
531 }
532 }
533 }
534 /* Next try to use a PPC ADB port mouse */
535 if ( mouse_fd < 0 ) {
536 mouse_fd = open("/dev/adbmouse", O_RDONLY, 0);
537 if ( mouse_fd >= 0 ) {
538#ifdef DEBUG_MOUSE
539fprintf(stderr, "Using ADB mouse\n");
540#endif
541 mouse_drv = MOUSE_BM;
542 }
543 }
544 }
545 /* Default to a serial Microsoft mouse */
546 if ( mouse_fd < 0 ) {
547 if ( mousedev == NULL ) {
548 mousedev = "/dev/mouse";
549 }
550 mouse_fd = open(mousedev, O_RDONLY, 0);
551 if ( mouse_fd >= 0 ) {
552 struct termios mouse_termios;
553
554 /* Set the sampling speed to 1200 baud */
555 tcgetattr(mouse_fd, &mouse_termios);
556 mouse_termios.c_iflag = IGNBRK | IGNPAR;
557 mouse_termios.c_oflag = 0;
558 mouse_termios.c_lflag = 0;
559 mouse_termios.c_line = 0;
560 mouse_termios.c_cc[VTIME] = 0;
561 mouse_termios.c_cc[VMIN] = 1;
562 mouse_termios.c_cflag = CREAD | CLOCAL | HUPCL;
563 mouse_termios.c_cflag |= CS8;
564 mouse_termios.c_cflag |= B1200;
565 tcsetattr(mouse_fd, TCSAFLUSH, &mouse_termios);
566#ifdef DEBUG_MOUSE
567fprintf(stderr, "Using Microsoft mouse on %s\n", mousedev);
568#endif
569 mouse_drv = MOUSE_MS;
570 }
571 }
572 if ( mouse_fd < 0 ) {
573 mouse_drv = MOUSE_NONE;
574 }
575 return(mouse_fd);
576}
577
578static int posted = 0;
579
580void GS_vgamousecallback(int button, int dx, int dy)
581{
582 int button_1, button_3;
583 int button_state;
584 int state_changed;
585 int i;
586 Uint8 state;
587
588 if ( dx || dy ) {
589 posted += SDL_PrivateMouseMotion(0, 1, dx, dy);
590 }
591
592 /* Swap button 1 and 3 */
593 button_1 = (button & 0x04) >> 2;
594 button_3 = (button & 0x01) << 2;
595 button &= ~0x05;
596 button |= (button_1|button_3);
597
598 /* See what changed */
599 button_state = SDL_GetMouseState(NULL, NULL);
600 state_changed = button_state ^ button;
601 for ( i=0; i<8; ++i ) {
602 if ( state_changed & (1<<i) ) {
603 if ( button & (1<<i) ) {
604 state = SDL_PRESSED;
605 } else {
606 state = SDL_RELEASED;
607 }
608 posted += SDL_PrivateMouseButton(state, i+1, 0, 0);
609 }
610 }
611}
612
613/* For now, use GPM, PS/2, and MS protocols
614 Driver adapted from the SVGAlib mouse driver code (taken from gpm, etc.)
615 */
616static void handle_mouse(_THIS)
617{
618 static int start = 0;
619 static unsigned char mousebuf[BUFSIZ];
620 int i, nread;
621 int button = 0;
622 int dx = 0, dy = 0;
623 int packetsize = 0;
624
625 /* Figure out the mouse packet size */
626 switch (mouse_drv) {
627 case MOUSE_NONE:
628 /* Ack! */
629 read(mouse_fd, mousebuf, BUFSIZ);
630 return;
631 case MOUSE_GPM:
632 packetsize = 5;
633 break;
634 case MOUSE_IMPS2:
635 packetsize = 4;
636 break;
637 case MOUSE_PS2:
638 case MOUSE_MS:
639 case MOUSE_BM:
640 packetsize = 3;
641 break;
642 case NUM_MOUSE_DRVS:
643 /* Uh oh.. */
644 packetsize = 0;
645 break;
646 }
647
648 /* Read as many packets as possible */
649 nread = read(mouse_fd, &mousebuf[start], BUFSIZ-start);
650 if ( nread < 0 ) {
651 return;
652 }
653 nread += start;
654#ifdef DEBUG_MOUSE
655 fprintf(stderr, "Read %d bytes from mouse, start = %d\n", nread, start);
656#endif
657 for ( i=0; i<(nread-(packetsize-1)); i += packetsize ) {
658 switch (mouse_drv) {
659 case MOUSE_NONE:
660 break;
661 case MOUSE_GPM:
662 /* GPM protocol has 0x80 in high byte */
663 if ( (mousebuf[i] & 0xF8) != 0x80 ) {
664 /* Go to next byte */
665 i -= (packetsize-1);
666 continue;
667 }
668 /* Get current mouse state */
669 button = (~mousebuf[i]) & 0x07;
670 dx = (signed char)(mousebuf[i+1]) +
671 (signed char)(mousebuf[i+3]);
672 dy = -((signed char)(mousebuf[i+2]) +
673 (signed char)(mousebuf[i+4]));
674 break;
675 case MOUSE_PS2:
676 /* PS/2 protocol has nothing in high byte */
677 if ( (mousebuf[i] & 0xC0) != 0 ) {
678 /* Go to next byte */
679 i -= (packetsize-1);
680 continue;
681 }
682 /* Get current mouse state */
683 button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/
684 (mousebuf[i] & 0x02) >> 1 | /*Right*/
685 (mousebuf[i] & 0x01) << 2; /*Left*/
686 dx = (mousebuf[i] & 0x10) ?
687 mousebuf[i+1] - 256 : mousebuf[i+1];
688 dy = (mousebuf[i] & 0x20) ?
689 -(mousebuf[i+2] - 256) : -mousebuf[i+2];
690 break;
691 case MOUSE_IMPS2:
692 /* Get current mouse state */
693 button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/
694 (mousebuf[i] & 0x02) >> 1 | /*Right*/
695 (mousebuf[i] & 0x01) << 2 | /*Left*/
696 (mousebuf[i] & 0x40) >> 3 | /* 4 */
697 (mousebuf[i] & 0x80) >> 3; /* 5 */
698 dx = (mousebuf[i] & 0x10) ?
699 mousebuf[i+1] - 256 : mousebuf[i+1];
700 dy = (mousebuf[i] & 0x20) ?
701 -(mousebuf[i+2] - 256) : -mousebuf[i+2];
702 switch (mousebuf[i+3]&0x0F) {
703 case 0x0E: /* DX = +1 */
704 case 0x02: /* DX = -1 */
705 break;
706 case 0x0F: /* DY = +1 (map button 4) */
707 FB_vgamousecallback(button | (1<<3),
708 1, 0, 0);
709 break;
710 case 0x01: /* DY = -1 (map button 5) */
711 FB_vgamousecallback(button | (1<<4),
712 1, 0, 0);
713 break;
714 }
715 break;
716 case MOUSE_MS:
717 /* Microsoft protocol has 0x40 in high byte */
718 if ( (mousebuf[i] & 0x40) != 0x40 ) {
719 /* Go to next byte */
720 i -= (packetsize-1);
721 continue;
722 }
723 /* Get current mouse state */
724 button = ((mousebuf[i] & 0x20) >> 3) |
725 ((mousebuf[i] & 0x10) >> 4);
726 dx = (signed char)(((mousebuf[i] & 0x03) << 6) |
727 (mousebuf[i + 1] & 0x3F));
728 dy = (signed char)(((mousebuf[i] & 0x0C) << 4) |
729 (mousebuf[i + 2] & 0x3F));
730 break;
731 case MOUSE_BM:
732 /* BusMouse protocol has 0xF8 in high byte */
733 if ( (mousebuf[i] & 0xF8) != 0x80 ) {
734 /* Go to next byte */
735 i -= (packetsize-1);
736 continue;
737 }
738 /* Get current mouse state */
739 button = (~mousebuf[i]) & 0x07;
740 dx = (signed char)mousebuf[i+1];
741 dy = -(signed char)mousebuf[i+2];
742 break;
743 case NUM_MOUSE_DRVS:
744 /* Uh oh.. */
745 dx = 0;
746 dy = 0;
747 break;
748 }
749 GS_vgamousecallback(button, dx, dy);
750 }
751 if ( i < nread ) {
752 SDL_memcpy(mousebuf, &mousebuf[i], (nread-i));
753 start = (nread-i);
754 } else {
755 start = 0;
756 }
757 return;
758}
759
760static void handle_keyboard(_THIS)
761{
762 unsigned char keybuf[BUFSIZ];
763 int i, nread;
764 int pressed;
765 int scancode;
766 SDL_keysym keysym;
767
768 nread = read(keyboard_fd, keybuf, BUFSIZ);
769 for ( i=0; i<nread; ++i ) {
770 scancode = keybuf[i] & 0x7F;
771 if ( keybuf[i] & 0x80 ) {
772 pressed = SDL_RELEASED;
773 } else {
774 pressed = SDL_PRESSED;
775 }
776 TranslateKey(scancode, &keysym);
777 posted += SDL_PrivateKeyboard(pressed, &keysym);
778 }
779}
780
781void GS_PumpEvents(_THIS)
782{
783 fd_set fdset;
784 int max_fd;
785 static struct timeval zero;
786
787 do {
788 posted = 0;
789
790 FD_ZERO(&fdset);
791 max_fd = 0;
792 if ( keyboard_fd >= 0 ) {
793 FD_SET(keyboard_fd, &fdset);
794 if ( max_fd < keyboard_fd ) {
795 max_fd = keyboard_fd;
796 }
797 }
798 if ( mouse_fd >= 0 ) {
799 FD_SET(mouse_fd, &fdset);
800 if ( max_fd < mouse_fd ) {
801 max_fd = mouse_fd;
802 }
803 }
804 if ( select(max_fd+1, &fdset, NULL, NULL, &zero) > 0 ) {
805 if ( keyboard_fd >= 0 ) {
806 if ( FD_ISSET(keyboard_fd, &fdset) ) {
807 handle_keyboard(this);
808 }
809 }
810 if ( mouse_fd >= 0 ) {
811 if ( FD_ISSET(mouse_fd, &fdset) ) {
812 handle_mouse(this);
813 }
814 }
815 }
816 } while ( posted );
817}
818
819void GS_InitOSKeymap(_THIS)
820{
821 int i;
822
823 /* Initialize the Linux key translation table */
824
825 /* First get the ascii keys and others not well handled */
826 for (i=0; i<SDL_arraysize(keymap); ++i) {
827 switch(i) {
828 /* These aren't handled by the x86 kernel keymapping (?) */
829 case SCANCODE_PRINTSCREEN:
830 keymap[i] = SDLK_PRINT;
831 break;
832 case SCANCODE_BREAK:
833 keymap[i] = SDLK_BREAK;
834 break;
835 case SCANCODE_BREAK_ALTERNATIVE:
836 keymap[i] = SDLK_PAUSE;
837 break;
838 case SCANCODE_LEFTSHIFT:
839 keymap[i] = SDLK_LSHIFT;
840 break;
841 case SCANCODE_RIGHTSHIFT:
842 keymap[i] = SDLK_RSHIFT;
843 break;
844 case SCANCODE_LEFTCONTROL:
845 keymap[i] = SDLK_LCTRL;
846 break;
847 case SCANCODE_RIGHTCONTROL:
848 keymap[i] = SDLK_RCTRL;
849 break;
850 case SCANCODE_RIGHTWIN:
851 keymap[i] = SDLK_RSUPER;
852 break;
853 case SCANCODE_LEFTWIN:
854 keymap[i] = SDLK_LSUPER;
855 break;
856 case 127:
857 keymap[i] = SDLK_MENU;
858 break;
859 /* this should take care of all standard ascii keys */
860 default:
861 keymap[i] = KVAL(vga_keymap[0][i]);
862 break;
863 }
864 }
865 for (i=0; i<SDL_arraysize(keymap); ++i) {
866 switch(keymap_temp[i]) {
867 case K_F1: keymap[i] = SDLK_F1; break;
868 case K_F2: keymap[i] = SDLK_F2; break;
869 case K_F3: keymap[i] = SDLK_F3; break;
870 case K_F4: keymap[i] = SDLK_F4; break;
871 case K_F5: keymap[i] = SDLK_F5; break;
872 case K_F6: keymap[i] = SDLK_F6; break;
873 case K_F7: keymap[i] = SDLK_F7; break;
874 case K_F8: keymap[i] = SDLK_F8; break;
875 case K_F9: keymap[i] = SDLK_F9; break;
876 case K_F10: keymap[i] = SDLK_F10; break;
877 case K_F11: keymap[i] = SDLK_F11; break;
878 case K_F12: keymap[i] = SDLK_F12; break;
879
880 case K_DOWN: keymap[i] = SDLK_DOWN; break;
881 case K_LEFT: keymap[i] = SDLK_LEFT; break;
882 case K_RIGHT: keymap[i] = SDLK_RIGHT; break;
883 case K_UP: keymap[i] = SDLK_UP; break;
884
885 case K_P0: keymap[i] = SDLK_KP0; break;
886 case K_P1: keymap[i] = SDLK_KP1; break;
887 case K_P2: keymap[i] = SDLK_KP2; break;
888 case K_P3: keymap[i] = SDLK_KP3; break;
889 case K_P4: keymap[i] = SDLK_KP4; break;
890 case K_P5: keymap[i] = SDLK_KP5; break;
891 case K_P6: keymap[i] = SDLK_KP6; break;
892 case K_P7: keymap[i] = SDLK_KP7; break;
893 case K_P8: keymap[i] = SDLK_KP8; break;
894 case K_P9: keymap[i] = SDLK_KP9; break;
895 case K_PPLUS: keymap[i] = SDLK_KP_PLUS; break;
896 case K_PMINUS: keymap[i] = SDLK_KP_MINUS; break;
897 case K_PSTAR: keymap[i] = SDLK_KP_MULTIPLY; break;
898 case K_PSLASH: keymap[i] = SDLK_KP_DIVIDE; break;
899 case K_PENTER: keymap[i] = SDLK_KP_ENTER; break;
900 case K_PDOT: keymap[i] = SDLK_KP_PERIOD; break;
901
902 case K_SHIFT: if ( keymap[i] != SDLK_RSHIFT )
903 keymap[i] = SDLK_LSHIFT;
904 break;
905 case K_SHIFTL: keymap[i] = SDLK_LSHIFT; break;
906 case K_SHIFTR: keymap[i] = SDLK_RSHIFT; break;
907 case K_CTRL: if ( keymap[i] != SDLK_RCTRL )
908 keymap[i] = SDLK_LCTRL;
909 break;
910 case K_CTRLL: keymap[i] = SDLK_LCTRL; break;
911 case K_CTRLR: keymap[i] = SDLK_RCTRL; break;
912 case K_ALT: keymap[i] = SDLK_LALT; break;
913 case K_ALTGR: keymap[i] = SDLK_RALT; break;
914
915 case K_INSERT: keymap[i] = SDLK_INSERT; break;
916 case K_REMOVE: keymap[i] = SDLK_DELETE; break;
917 case K_PGUP: keymap[i] = SDLK_PAGEUP; break;
918 case K_PGDN: keymap[i] = SDLK_PAGEDOWN; break;
919 case K_FIND: keymap[i] = SDLK_HOME; break;
920 case K_SELECT: keymap[i] = SDLK_END; break;
921
922 case K_NUM: keymap[i] = SDLK_NUMLOCK; break;
923 case K_CAPS: keymap[i] = SDLK_CAPSLOCK; break;
924
925 case K_F13: keymap[i] = SDLK_PRINT; break;
926 case K_HOLD: keymap[i] = SDLK_SCROLLOCK; break;
927 case K_PAUSE: keymap[i] = SDLK_PAUSE; break;
928
929 case 127: keymap[i] = SDLK_BACKSPACE; break;
930
931 default: break;
932 }
933 }
934}
935
936static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym)
937{
938 /* Set the keysym information */
939 keysym->scancode = scancode;
940 keysym->sym = keymap[scancode];
941 keysym->mod = KMOD_NONE;
942
943 /* If UNICODE is on, get the UNICODE value for the key */
944 keysym->unicode = 0;
945 if ( SDL_TranslateUNICODE ) {
946 int map;
947 SDLMod modstate;
948
949 modstate = SDL_GetModState();
950 map = 0;
951 if ( modstate & KMOD_SHIFT ) {
952 map |= (1<<KG_SHIFT);
953 }
954 if ( modstate & KMOD_CTRL ) {
955 map |= (1<<KG_CTRL);
956 }
957 if ( modstate & KMOD_ALT ) {
958 map |= (1<<KG_ALT);
959 }
960 if ( modstate & KMOD_MODE ) {
961 map |= (1<<KG_ALTGR);
962 }
963 if ( KTYP(vga_keymap[map][scancode]) == KT_LETTER ) {
964 if ( modstate & KMOD_CAPS ) {
965 map ^= (1<<KG_SHIFT);
966 }
967 }
968 if ( KTYP(vga_keymap[map][scancode]) == KT_PAD ) {
969 if ( modstate & KMOD_NUM ) {
970 keysym->unicode=KVAL(vga_keymap[map][scancode]);
971 }
972 } else {
973 keysym->unicode = KVAL(vga_keymap[map][scancode]);
974 }
975 }
976 return(keysym);
977}
diff --git a/apps/plugins/sdl/src/video/ps2gs/SDL_gsevents_c.h b/apps/plugins/sdl/src/video/ps2gs/SDL_gsevents_c.h
deleted file mode 100644
index 6758ab3e9e..0000000000
--- a/apps/plugins/sdl/src/video/ps2gs/SDL_gsevents_c.h
+++ /dev/null
@@ -1,38 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_gsvideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29extern int GS_OpenKeyboard(_THIS);
30extern void GS_CloseKeyboard(_THIS);
31extern int GS_OpenMouse(_THIS);
32extern void GS_CloseMouse(_THIS);
33extern int GS_EnterGraphicsMode(_THIS);
34extern int GS_InGraphicsMode(_THIS);
35extern void GS_LeaveGraphicsMode(_THIS);
36
37extern void GS_InitOSKeymap(_THIS);
38extern void GS_PumpEvents(_THIS);
diff --git a/apps/plugins/sdl/src/video/ps2gs/SDL_gskeys.h b/apps/plugins/sdl/src/video/ps2gs/SDL_gskeys.h
deleted file mode 100644
index 2b01b6b2e3..0000000000
--- a/apps/plugins/sdl/src/video/ps2gs/SDL_gskeys.h
+++ /dev/null
@@ -1,139 +0,0 @@
1
2/* Scancodes for the Linux framebuffer console
3 - Taken with thanks from SVGAlib 1.4.0
4*/
5
6#define SCANCODE_ESCAPE 1
7
8#define SCANCODE_1 2
9#define SCANCODE_2 3
10#define SCANCODE_3 4
11#define SCANCODE_4 5
12#define SCANCODE_5 6
13#define SCANCODE_6 7
14#define SCANCODE_7 8
15#define SCANCODE_8 9
16#define SCANCODE_9 10
17#define SCANCODE_0 11
18
19#define SCANCODE_MINUS 12
20#define SCANCODE_EQUAL 13
21
22#define SCANCODE_BACKSPACE 14
23#define SCANCODE_TAB 15
24
25#define SCANCODE_Q 16
26#define SCANCODE_W 17
27#define SCANCODE_E 18
28#define SCANCODE_R 19
29#define SCANCODE_T 20
30#define SCANCODE_Y 21
31#define SCANCODE_U 22
32#define SCANCODE_I 23
33#define SCANCODE_O 24
34#define SCANCODE_P 25
35#define SCANCODE_BRACKET_LEFT 26
36#define SCANCODE_BRACKET_RIGHT 27
37
38#define SCANCODE_ENTER 28
39
40#define SCANCODE_LEFTCONTROL 29
41
42#define SCANCODE_A 30
43#define SCANCODE_S 31
44#define SCANCODE_D 32
45#define SCANCODE_F 33
46#define SCANCODE_G 34
47#define SCANCODE_H 35
48#define SCANCODE_J 36
49#define SCANCODE_K 37
50#define SCANCODE_L 38
51#define SCANCODE_SEMICOLON 39
52#define SCANCODE_APOSTROPHE 40
53#define SCANCODE_GRAVE 41
54
55#define SCANCODE_LEFTSHIFT 42
56#define SCANCODE_BACKSLASH 43
57
58#define SCANCODE_Z 44
59#define SCANCODE_X 45
60#define SCANCODE_C 46
61#define SCANCODE_V 47
62#define SCANCODE_B 48
63#define SCANCODE_N 49
64#define SCANCODE_M 50
65#define SCANCODE_COMMA 51
66#define SCANCODE_PERIOD 52
67#define SCANCODE_SLASH 53
68
69#define SCANCODE_RIGHTSHIFT 54
70#define SCANCODE_KEYPADMULTIPLY 55
71
72#define SCANCODE_LEFTALT 56
73#define SCANCODE_SPACE 57
74#define SCANCODE_CAPSLOCK 58
75
76#define SCANCODE_F1 59
77#define SCANCODE_F2 60
78#define SCANCODE_F3 61
79#define SCANCODE_F4 62
80#define SCANCODE_F5 63
81#define SCANCODE_F6 64
82#define SCANCODE_F7 65
83#define SCANCODE_F8 66
84#define SCANCODE_F9 67
85#define SCANCODE_F10 68
86
87#define SCANCODE_NUMLOCK 69
88#define SCANCODE_SCROLLLOCK 70
89
90#define SCANCODE_KEYPAD7 71
91#define SCANCODE_CURSORUPLEFT 71
92#define SCANCODE_KEYPAD8 72
93#define SCANCODE_CURSORUP 72
94#define SCANCODE_KEYPAD9 73
95#define SCANCODE_CURSORUPRIGHT 73
96#define SCANCODE_KEYPADMINUS 74
97#define SCANCODE_KEYPAD4 75
98#define SCANCODE_CURSORLEFT 75
99#define SCANCODE_KEYPAD5 76
100#define SCANCODE_KEYPAD6 77
101#define SCANCODE_CURSORRIGHT 77
102#define SCANCODE_KEYPADPLUS 78
103#define SCANCODE_KEYPAD1 79
104#define SCANCODE_CURSORDOWNLEFT 79
105#define SCANCODE_KEYPAD2 80
106#define SCANCODE_CURSORDOWN 80
107#define SCANCODE_KEYPAD3 81
108#define SCANCODE_CURSORDOWNRIGHT 81
109#define SCANCODE_KEYPAD0 82
110#define SCANCODE_KEYPADPERIOD 83
111
112#define SCANCODE_LESS 86
113
114#define SCANCODE_F11 87
115#define SCANCODE_F12 88
116
117#define SCANCODE_KEYPADENTER 96
118#define SCANCODE_RIGHTCONTROL 97
119#define SCANCODE_CONTROL 97
120#define SCANCODE_KEYPADDIVIDE 98
121#define SCANCODE_PRINTSCREEN 99
122#define SCANCODE_RIGHTALT 100
123#define SCANCODE_BREAK 101 /* Beware: is 119 */
124#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */
125
126#define SCANCODE_HOME 102
127#define SCANCODE_CURSORBLOCKUP 103 /* Cursor key block */
128#define SCANCODE_PAGEUP 104
129#define SCANCODE_CURSORBLOCKLEFT 105 /* Cursor key block */
130#define SCANCODE_CURSORBLOCKRIGHT 106 /* Cursor key block */
131#define SCANCODE_END 107
132#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */
133#define SCANCODE_PAGEDOWN 109
134#define SCANCODE_INSERT 110
135#define SCANCODE_REMOVE 111
136
137#define SCANCODE_RIGHTWIN 126
138#define SCANCODE_LEFTWIN 125
139
diff --git a/apps/plugins/sdl/src/video/ps2gs/SDL_gsmouse.c b/apps/plugins/sdl/src/video/ps2gs/SDL_gsmouse.c
deleted file mode 100644
index e0d320d660..0000000000
--- a/apps/plugins/sdl/src/video/ps2gs/SDL_gsmouse.c
+++ /dev/null
@@ -1,146 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <sys/ioctl.h>
25
26#include "SDL_mouse.h"
27#include "../../events/SDL_events_c.h"
28#include "../SDL_cursor_c.h"
29#include "SDL_gsvideo.h"
30#include "SDL_gsmouse_c.h"
31
32
33/* The implementation dependent data for the window manager cursor */
34struct WMcursor {
35 int unused;
36};
37
38/* There isn't any implementation dependent data */
39void GS_FreeWMCursor(_THIS, WMcursor *cursor)
40{
41 return;
42}
43
44/* There isn't any implementation dependent data */
45WMcursor *GS_CreateWMCursor(_THIS,
46 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
47{
48 return((WMcursor *)0x01);
49}
50
51static void GS_MoveCursor(_THIS, SDL_Cursor *cursor, int x, int y)
52{
53 SDL_Surface *screen;
54 struct ps2_image image;
55 SDL_Rect area;
56 int mouse_y1, mouse_y2;
57 void *saved_pixels;
58 int screen_updated;
59
60 /* Lock so we don't interrupt an update with mouse motion */
61 SDL_LockCursor();
62
63 /* Make sure any pending DMA has completed */
64 if ( dma_pending ) {
65 ioctl(console_fd, PS2IOC_SENDQCT, 1);
66 dma_pending = 0;
67 }
68
69 /* Remove the cursor image from the DMA area */
70 screen = this->screen;
71 saved_pixels = screen->pixels;
72 screen->pixels = mapped_mem + screen->offset;
73 screen_updated = 0;
74 if ( cursor_drawn ) {
75 SDL_EraseCursorNoLock(screen);
76 cursor_drawn = 0;
77 screen_updated = 1;
78 }
79
80 /* Save the current mouse area */
81 SDL_MouseRect(&area);
82 mouse_y1 = area.y;
83 mouse_y2 = area.y+area.h;
84
85 /* Only draw the new cursor if there was one passed in */
86 if ( cursor ) {
87 /* Set the new location */
88 cursor->area.x = (x - cursor->hot_x);
89 cursor->area.y = (y - cursor->hot_y);
90
91 /* Draw the cursor at the new location */
92 if ( (SDL_cursorstate & CURSOR_VISIBLE) && screen->pixels ) {
93 SDL_DrawCursorNoLock(screen);
94 cursor_drawn = 1;
95 screen_updated = 1;
96 }
97 }
98 screen->pixels = saved_pixels;
99
100 /* Update the affected area of the screen */
101 if ( screen_updated ) {
102 SDL_MouseRect(&area);
103 if ( area.y < mouse_y1 ) {
104 mouse_y1 = area.y;
105 }
106 if ( (area.y+area.h) > mouse_y2 ) {
107 mouse_y2 = area.y+area.h;
108 }
109 image = screen_image;
110 image.y += screen->offset / screen->pitch + mouse_y1;
111 image.h = mouse_y2 - mouse_y1;
112 image.ptr = mapped_mem +
113 (image.y - screen_image.y) * screen->pitch;
114 ioctl(console_fd, PS2IOC_LOADIMAGE, &image);
115
116 /* Need to scale offscreen image to TV output */
117 if ( image.y > 0 ) {
118 scaleimage_nonblock(console_fd,
119 tex_tags_mem, scale_tags_mem);
120 }
121 }
122
123 /* We're finished */
124 SDL_UnlockCursor();
125}
126
127void GS_MoveWMCursor(_THIS, int x, int y)
128{
129 GS_MoveCursor(this, SDL_cursor, x, y);
130}
131
132int GS_ShowWMCursor(_THIS, WMcursor *wmcursor)
133{
134 SDL_Cursor *cursor;
135 int x, y;
136
137 /* Draw the cursor at the appropriate location */
138 SDL_GetMouseState(&x, &y);
139 if ( wmcursor ) {
140 cursor = SDL_cursor;
141 } else {
142 cursor = NULL;
143 }
144 GS_MoveCursor(this, cursor, x, y);
145 return(1);
146}
diff --git a/apps/plugins/sdl/src/video/ps2gs/SDL_gsmouse_c.h b/apps/plugins/sdl/src/video/ps2gs/SDL_gsmouse_c.h
deleted file mode 100644
index c507ed4a60..0000000000
--- a/apps/plugins/sdl/src/video/ps2gs/SDL_gsmouse_c.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_gsvideo.h"
25
26/* This is the maximum size of the cursor sprite */
27#define CURSOR_W 32
28#define CURSOR_H 32
29#define CURSOR_W_POW 5 /* 32 = 2^5 */
30#define CURSOR_H_POW 5 /* 32 = 2^5 */
31
32/* Functions to be exported */
33extern void GS_FreeWMCursor(_THIS, WMcursor *cursor);
34extern WMcursor *GS_CreateWMCursor(_THIS,
35 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
36extern void GS_MoveWMCursor(_THIS, int x, int y);
37extern int GS_ShowWMCursor(_THIS, WMcursor *cursor);
diff --git a/apps/plugins/sdl/src/video/ps2gs/SDL_gsvideo.c b/apps/plugins/sdl/src/video/ps2gs/SDL_gsvideo.c
deleted file mode 100644
index e172c60dc1..0000000000
--- a/apps/plugins/sdl/src/video/ps2gs/SDL_gsvideo.c
+++ /dev/null
@@ -1,689 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Framebuffer console based SDL video driver implementation.
25*/
26
27#include <fcntl.h>
28#include <unistd.h>
29#include <sys/ioctl.h>
30#include <sys/mman.h>
31
32#include "SDL_video.h"
33#include "SDL_mouse.h"
34#include "../SDL_sysvideo.h"
35#include "../SDL_pixels_c.h"
36#include "../../events/SDL_events_c.h"
37#include "../SDL_cursor_c.h"
38#include "SDL_gsvideo.h"
39#include "SDL_gsmouse_c.h"
40#include "SDL_gsevents_c.h"
41#include "SDL_gsyuv_c.h"
42
43
44/* Initialization/Query functions */
45static int GS_VideoInit(_THIS, SDL_PixelFormat *vformat);
46static SDL_Rect **GS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
47static SDL_Surface *GS_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
48static int GS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
49static void GS_VideoQuit(_THIS);
50
51/* Hardware surface functions */
52static int GS_AllocHWSurface(_THIS, SDL_Surface *surface);
53static int GS_LockHWSurface(_THIS, SDL_Surface *surface);
54static void GS_UnlockHWSurface(_THIS, SDL_Surface *surface);
55static void GS_FreeHWSurface(_THIS, SDL_Surface *surface);
56
57/* GS driver bootstrap functions */
58
59static int GS_Available(void)
60{
61 int console, memory;
62
63 console = open(PS2_DEV_GS, O_RDWR, 0);
64 if ( console >= 0 ) {
65 close(console);
66 }
67 memory = open(PS2_DEV_MEM, O_RDWR, 0);
68 if ( memory >= 0 ) {
69 close(memory);
70 }
71 return((console >= 0) && (memory >= 0));
72}
73
74static void GS_DeleteDevice(SDL_VideoDevice *device)
75{
76 SDL_free(device->hidden);
77 SDL_free(device);
78}
79
80static SDL_VideoDevice *GS_CreateDevice(int devindex)
81{
82 SDL_VideoDevice *this;
83
84 /* Initialize all variables that we clean on shutdown */
85 this = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
86 if ( this ) {
87 SDL_memset(this, 0, (sizeof *this));
88 this->hidden = (struct SDL_PrivateVideoData *)
89 SDL_malloc((sizeof *this->hidden));
90 }
91 if ( (this == NULL) || (this->hidden == NULL) ) {
92 SDL_OutOfMemory();
93 if ( this ) {
94 SDL_free(this);
95 }
96 return(0);
97 }
98 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
99 mouse_fd = -1;
100 keyboard_fd = -1;
101
102 /* Set the function pointers */
103 this->VideoInit = GS_VideoInit;
104 this->ListModes = GS_ListModes;
105 this->SetVideoMode = GS_SetVideoMode;
106 this->CreateYUVOverlay = GS_CreateYUVOverlay;
107 this->SetColors = GS_SetColors;
108 this->UpdateRects = NULL;
109 this->VideoQuit = GS_VideoQuit;
110 this->AllocHWSurface = GS_AllocHWSurface;
111 this->CheckHWBlit = NULL;
112 this->FillHWRect = NULL;
113 this->SetHWColorKey = NULL;
114 this->SetHWAlpha = NULL;
115 this->LockHWSurface = GS_LockHWSurface;
116 this->UnlockHWSurface = GS_UnlockHWSurface;
117 this->FlipHWSurface = NULL;
118 this->FreeHWSurface = GS_FreeHWSurface;
119 this->SetIcon = NULL;
120 this->SetCaption = NULL;
121 this->GetWMInfo = NULL;
122 this->FreeWMCursor = GS_FreeWMCursor;
123 this->CreateWMCursor = GS_CreateWMCursor;
124 this->ShowWMCursor = GS_ShowWMCursor;
125 this->MoveWMCursor = GS_MoveWMCursor;
126 this->InitOSKeymap = GS_InitOSKeymap;
127 this->PumpEvents = GS_PumpEvents;
128
129 this->free = GS_DeleteDevice;
130
131 return this;
132}
133
134VideoBootStrap PS2GS_bootstrap = {
135 "ps2gs", "PlayStation 2 Graphics Synthesizer",
136 GS_Available, GS_CreateDevice
137};
138
139/* These are the pixel formats for the 32, 24, and 16 bit video modes */
140static struct {
141 int bpp;
142 Uint32 r;
143 Uint32 g;
144 Uint32 b;
145} GS_pixelmasks[] = {
146 { 32, 0x000000FF, /* RGB little-endian */
147 0x0000FF00,
148 0x00FF0000 },
149 { 24, 0x000000FF, /* RGB little-endian */
150 0x0000FF00,
151 0x00FF0000 },
152 { 16, 0x0000001f, /* RGB little-endian */
153 0x000003e0,
154 0x00007c00 },
155};
156/* This is a mapping from SDL bytes-per-pixel to GS pixel format */
157static int GS_formatmap[] = {
158 -1, /* 0 bpp, not a legal value */
159 -1, /* 8 bpp, not supported (yet?) */
160 PS2_GS_PSMCT16, /* 16 bpp */
161 PS2_GS_PSMCT24, /* 24 bpp */
162 PS2_GS_PSMCT32 /* 32 bpp */
163};
164
165static unsigned long long head_tags[] __attribute__((aligned(16))) = {
166 4 | (1LL << 60), /* GIFtag */
167 0x0e, /* A+D */
168 0, /* 2 */
169 PS2_GS_BITBLTBUF,
170 0, /* 4 */
171 PS2_GS_TRXPOS,
172 0, /* 6 */
173 PS2_GS_TRXREG,
174 0, /* 8 */
175 PS2_GS_TRXDIR
176};
177
178#define MAXIMG (32767 * 16)
179#define MAXTAGS 8
180
181static inline int loadimage_nonblock(int fd, struct ps2_image *image, int size,
182 unsigned long long *hm,
183 unsigned long long *im)
184{
185 struct ps2_plist plist;
186 struct ps2_packet packet[1 + MAXTAGS * 2];
187 int isize;
188 int pnum, it, eop;
189 char *data;
190
191 /* initialize the variables */
192 data = (char *)image->ptr;
193 pnum = it = eop = 0;
194 plist.packet = packet;
195
196 /* make BITBLT packet */
197 packet[pnum].ptr = hm;
198 packet[pnum].len = sizeof(head_tags);
199 pnum++;
200 hm[2] = ((unsigned long long)image->fbp << 32) |
201 ((unsigned long long)image->fbw << 48) |
202 ((unsigned long long)image->psm << 56);
203 hm[4] = ((unsigned long long)image->x << 32) |
204 ((unsigned long long)image->y << 48);
205 hm[6] = (unsigned long long)image->w |
206 ((unsigned long long)image->h << 32);
207
208 /* make image mode tags */
209 while (!eop) {
210 isize = size > MAXIMG ? MAXIMG : size;
211 size -= isize;
212 eop = (size == 0);
213
214 packet[pnum].ptr = &im[it];
215 packet[pnum].len = sizeof(unsigned long long) * 2;
216 pnum++;
217 im[it++] = (isize >> 4) | (eop ? (1 << 15) : 0) | (2LL << 58);
218 im[it++] = 0;
219
220 packet[pnum].ptr = (void *)data;
221 packet[pnum].len = isize;
222 pnum++;
223 data += isize;
224 }
225 plist.num = pnum;
226
227 return ioctl(fd, PS2IOC_SENDL, &plist);
228}
229
230static unsigned long long tex_tags[] __attribute__((aligned(16))) = {
231 3 | (1LL << 60), /* GIFtag */
232 0x0e, /* A+D */
233 0, /* 2 */
234 PS2_GS_TEX0_1,
235 (1 << 5) + (1 << 6),
236 PS2_GS_TEX1_1,
237 0,
238 PS2_GS_TEXFLUSH
239};
240static unsigned long long scale_tags[] __attribute__((aligned(16))) = {
241 5 | (1LL << 60), /* GIFtag */
242 0x0e, /* A+D */
243 6 + (1 << 4) + (1 << 8),
244 PS2_GS_PRIM,
245 ((unsigned long long)0 * 16) + (((unsigned long long)0 * 16) << 16),
246 PS2_GS_UV,
247 ((unsigned long long)0 * 16) + (((unsigned long long)0 * 16) << 16),
248 PS2_GS_XYZ2,
249 0, /* 8 */
250 PS2_GS_UV,
251 0, /* 10 */
252 PS2_GS_XYZ2
253};
254
255
256int scaleimage_nonblock(int fd, unsigned long long *tm, unsigned long long *sm)
257{
258 struct ps2_plist plist;
259 struct ps2_packet packet[2];
260
261 /* initialize the variables */
262 plist.num = 2;
263 plist.packet = packet;
264
265 packet[0].ptr = tm;
266 packet[0].len = sizeof(tex_tags);
267 packet[1].ptr = sm;
268 packet[1].len = sizeof(scale_tags);
269
270 return ioctl(fd, PS2IOC_SENDL, &plist);
271}
272
273static int power_of_2(int value)
274{
275 int shift;
276
277 for ( shift = 0; (1<<shift) < value; ++shift ) {
278 /* Keep looking */ ;
279 }
280 return(shift);
281}
282
283static int GS_VideoInit(_THIS, SDL_PixelFormat *vformat)
284{
285 struct ps2_screeninfo vinfo;
286
287 /* Initialize the library */
288 console_fd = open(PS2_DEV_GS, O_RDWR, 0);
289 if ( console_fd < 0 ) {
290 SDL_SetError("Unable to open %s", PS2_DEV_GS);
291 return(-1);
292 }
293 memory_fd = open(PS2_DEV_MEM, O_RDWR, 0);
294 if ( memory_fd < 0 ) {
295 close(console_fd);
296 console_fd = -1;
297 SDL_SetError("Unable to open %s", PS2_DEV_MEM);
298 return(-1);
299 }
300
301 if ( ioctl(console_fd, PS2IOC_GSCREENINFO, &vinfo) < 0 ) {
302 close(memory_fd);
303 close(console_fd);
304 console_fd = -1;
305 SDL_SetError("Couldn't get console pixel format");
306 return(-1);
307 }
308
309 /* Determine the current screen size */
310 this->info.current_w = vinfo.w;
311 this->info.current_h = vinfo.h;
312
313 /* Determine the current screen depth */
314 switch (vinfo.psm) {
315 /* Supported pixel formats */
316 case PS2_GS_PSMCT32:
317 case PS2_GS_PSMCT24:
318 case PS2_GS_PSMCT16:
319 break;
320 default:
321 GS_VideoQuit(this);
322 SDL_SetError("Unknown console pixel format: %d", vinfo.psm);
323 return(-1);
324 }
325 vformat->BitsPerPixel = GS_pixelmasks[vinfo.psm].bpp;
326 vformat->Rmask = GS_pixelmasks[vinfo.psm].r;
327 vformat->Gmask = GS_pixelmasks[vinfo.psm].g;
328 vformat->Bmask = GS_pixelmasks[vinfo.psm].b;
329 saved_vinfo = vinfo;
330
331 /* Enable mouse and keyboard support */
332 if ( GS_OpenKeyboard(this) < 0 ) {
333 GS_VideoQuit(this);
334 SDL_SetError("Unable to open keyboard");
335 return(-1);
336 }
337 if ( GS_OpenMouse(this) < 0 ) {
338 const char *sdl_nomouse;
339
340 sdl_nomouse = SDL_getenv("SDL_NOMOUSE");
341 if ( ! sdl_nomouse ) {
342 GS_VideoQuit(this);
343 SDL_SetError("Unable to open mouse");
344 return(-1);
345 }
346 }
347
348 /* We're done! */
349 return(0);
350}
351
352static SDL_Rect **GS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
353{
354 static SDL_Rect GS_vesa_mode_list[] = {
355 { 0, 0, 1280, 1024 },
356 { 0, 0, 1024, 768 },
357 { 0, 0, 800, 600 },
358 { 0, 0, 640, 480 }
359 };
360 static SDL_Rect *GS_vesa_modes[] = {
361 &GS_vesa_mode_list[0],
362 &GS_vesa_mode_list[1],
363 &GS_vesa_mode_list[2],
364 &GS_vesa_mode_list[3],
365 NULL
366 };
367 static SDL_Rect GS_tvout_stretch;
368 static SDL_Rect GS_tvout_mode;
369 static SDL_Rect *GS_tvout_modes[3];
370 SDL_Rect **modes = NULL;
371
372 switch (format->BitsPerPixel) {
373 case 16:
374 case 24:
375 case 32:
376 if ( saved_vinfo.mode == PS2_GS_VESA ) {
377 modes = GS_vesa_modes;
378 } else {
379 int i, j = 0;
380
381// FIXME - what's wrong with the stretch code at 16 bpp?
382if ( format->BitsPerPixel != 32 ) break;
383 /* Add a mode that we could possibly stretch to */
384 for ( i=0; GS_vesa_modes[i]; ++i ) {
385 if ( (GS_vesa_modes[i]->w == saved_vinfo.w) &&
386 (GS_vesa_modes[i]->h != saved_vinfo.h) ) {
387 GS_tvout_stretch.w=GS_vesa_modes[i]->w;
388 GS_tvout_stretch.h=GS_vesa_modes[i]->h;
389 GS_tvout_modes[j++] = &GS_tvout_stretch;
390 break;
391 }
392 }
393 /* Add the current TV video mode */
394 GS_tvout_mode.w = saved_vinfo.w;
395 GS_tvout_mode.h = saved_vinfo.h;
396 GS_tvout_modes[j++] = &GS_tvout_mode;
397 GS_tvout_modes[j++] = NULL;
398
399 /* Return the created list of modes */
400 modes = GS_tvout_modes;
401 }
402 break;
403 default:
404 break;
405 }
406 return(modes);
407}
408
409/* Various screen update functions available */
410static void GS_DMAFullUpdate(_THIS, int numrects, SDL_Rect *rects);
411
412static SDL_Surface *GS_SetVideoMode(_THIS, SDL_Surface *current,
413 int width, int height, int bpp, Uint32 flags)
414{
415 struct ps2_screeninfo vinfo;
416
417 /* Set the terminal into graphics mode */
418 if ( GS_EnterGraphicsMode(this) < 0 ) {
419 return(NULL);
420 }
421
422 /* Set the video mode and get the final screen format */
423 if ( ioctl(console_fd, PS2IOC_GSCREENINFO, &vinfo) < 0 ) {
424 SDL_SetError("Couldn't get console screen info");
425 return(NULL);
426 }
427 if ( (vinfo.w != width) || (vinfo.h != height) ||
428 (GS_pixelmasks[vinfo.psm].bpp != bpp) ) {
429 /* If we're not in VESA mode, we have to scale resolution */
430 if ( saved_vinfo.mode == PS2_GS_VESA ) {
431 switch (width) {
432 case 640:
433 vinfo.res = PS2_GS_640x480;
434 break;
435 case 800:
436 vinfo.res = PS2_GS_800x600;
437 break;
438 case 1024:
439 vinfo.res = PS2_GS_1024x768;
440 break;
441 case 1280:
442 vinfo.res = PS2_GS_1280x1024;
443 break;
444 default:
445 SDL_SetError("Unsupported resolution: %dx%d\n",
446 width, height);
447 return(NULL);
448 }
449 vinfo.res |= (PS2_GS_75Hz << 8);
450 vinfo.w = width;
451 vinfo.h = height;
452 }
453 vinfo.fbp = 0;
454 vinfo.psm = GS_formatmap[bpp/8];
455 if ( vinfo.psm < 0 ) {
456 SDL_SetError("Unsupported depth: %d bpp\n", bpp);
457 return(NULL);
458 }
459 if ( ioctl(console_fd, PS2IOC_SSCREENINFO, &vinfo) < 0 ) {
460 SDL_SetError("Couldn't set console screen info");
461 return(NULL);
462 }
463
464 /* Unmap the previous DMA buffer */
465 if ( mapped_mem ) {
466 munmap(mapped_mem, mapped_len);
467 mapped_mem = NULL;
468 }
469 }
470 if ( ! SDL_ReallocFormat(current, GS_pixelmasks[vinfo.psm].bpp,
471 GS_pixelmasks[vinfo.psm].r,
472 GS_pixelmasks[vinfo.psm].g,
473 GS_pixelmasks[vinfo.psm].b, 0) ) {
474 return(NULL);
475 }
476
477 /* Set up the new mode framebuffer */
478 current->flags = SDL_FULLSCREEN;
479 current->w = width;
480 current->h = height;
481 current->pitch = SDL_CalculatePitch(current);
482
483 /* Memory map the DMA area for block memory transfer */
484 if ( ! mapped_mem ) {
485 pixels_len = height * current->pitch;
486 mapped_len = pixels_len +
487 /* Screen update DMA command area */
488 sizeof(head_tags) + ((2 * MAXTAGS) * 16);
489 if ( saved_vinfo.mode != PS2_GS_VESA ) {
490 mapped_len += sizeof(tex_tags) + sizeof(scale_tags);
491 }
492 mapped_mem = mmap(0, mapped_len, PROT_READ|PROT_WRITE,
493 MAP_SHARED, memory_fd, 0);
494 if ( mapped_mem == MAP_FAILED ) {
495 SDL_SetError("Unable to map %d bytes for DMA",
496 mapped_len);
497 mapped_mem = NULL;
498 return(NULL);
499 }
500
501 /* Set up the entire screen for DMA transfer */
502 screen_image.ptr = mapped_mem;
503 screen_image.fbp = 0;
504 screen_image.fbw = (vinfo.w + 63) / 64;
505 screen_image.psm = vinfo.psm;
506 screen_image.x = 0;
507 if ( vinfo.h == height ) {
508 screen_image.y = 0;
509 } else {
510 /* Put image offscreen and scale to screen height */
511 screen_image.y = vinfo.h;
512 }
513 screen_image.w = current->w;
514 screen_image.h = current->h;
515
516 /* get screen image data size (qword aligned) */
517 screen_image_size = (screen_image.w * screen_image.h);
518 switch (screen_image.psm) {
519 case PS2_GS_PSMCT32:
520 screen_image_size *= 4;
521 break;
522 case PS2_GS_PSMCT24:
523 screen_image_size *= 3;
524 break;
525 case PS2_GS_PSMCT16:
526 screen_image_size *= 2;
527 break;
528 }
529 screen_image_size = (screen_image_size + 15) & ~15;
530
531 /* Set up the memory for screen update DMA commands */
532 head_tags_mem = (unsigned long long *)
533 (mapped_mem + pixels_len);
534 image_tags_mem = (unsigned long long *)
535 ((caddr_t)head_tags_mem + sizeof(head_tags));
536 SDL_memcpy(head_tags_mem, head_tags, sizeof(head_tags));
537 if ( saved_vinfo.mode != PS2_GS_VESA ) {
538 tex_tags_mem = (unsigned long long *)
539 ((caddr_t)image_tags_mem + ((2*MAXTAGS)*16));
540 scale_tags_mem = (unsigned long long *)
541 ((caddr_t)tex_tags_mem + sizeof(tex_tags));
542 SDL_memcpy(tex_tags_mem, tex_tags, sizeof(tex_tags));
543 tex_tags_mem[2] =
544 (vinfo.h * vinfo.w) / 64 +
545 ((unsigned long long)screen_image.fbw << 14) +
546 ((unsigned long long)screen_image.psm << 20) +
547 ((unsigned long long)power_of_2(screen_image.w) << 26) +
548 ((unsigned long long)power_of_2(screen_image.h) << 30) +
549 ((unsigned long long)1 << 34) +
550 ((unsigned long long)1 << 35);
551 SDL_memcpy(scale_tags_mem, scale_tags, sizeof(scale_tags));
552 scale_tags_mem[8] =
553 ((unsigned long long)screen_image.w * 16) +
554 (((unsigned long long)screen_image.h * 16) << 16);
555 scale_tags_mem[10] =
556 ((unsigned long long)vinfo.w * 16) +
557 (((unsigned long long)vinfo.h * 16) << 16);
558 }
559 }
560 current->pixels = NULL;
561 if ( SDL_getenv("SDL_FULLSCREEN_UPDATE") ) {
562 /* Correct semantics */
563 current->flags |= SDL_ASYNCBLIT;
564 } else {
565 /* We lie here - the screen memory isn't really the visible
566 display memory and still requires an update, but this
567 has the desired effect for most applications.
568 */
569 current->flags |= SDL_HWSURFACE;
570 }
571
572 /* Set the update rectangle function */
573 this->UpdateRects = GS_DMAFullUpdate;
574
575 /* We're done */
576 return(current);
577}
578
579/* We don't support hardware surfaces yet */
580static int GS_AllocHWSurface(_THIS, SDL_Surface *surface)
581{
582 return(-1);
583}
584static void GS_FreeHWSurface(_THIS, SDL_Surface *surface)
585{
586 return;
587}
588static int GS_LockHWSurface(_THIS, SDL_Surface *surface)
589{
590 if ( surface == this->screen ) {
591 /* Since mouse motion affects 'pixels', lock it */
592 SDL_LockCursor();
593
594 /* Make sure any pending DMA has completed */
595 if ( dma_pending ) {
596 ioctl(console_fd, PS2IOC_SENDQCT, 1);
597 dma_pending = 0;
598 }
599
600 /* If the cursor is drawn on the DMA area, remove it */
601 if ( cursor_drawn ) {
602 surface->pixels = mapped_mem + surface->offset;
603 SDL_EraseCursorNoLock(this->screen);
604 cursor_drawn = 0;
605 }
606
607 /* Set the surface pixels to the base of the DMA area */
608 surface->pixels = mapped_mem;
609
610 /* We're finished! */
611 SDL_UnlockCursor();
612 }
613 return(0);
614}
615static void GS_UnlockHWSurface(_THIS, SDL_Surface *surface)
616{
617 if ( surface == this->screen ) {
618 /* Since mouse motion affects 'pixels', lock it */
619 SDL_LockCursor();
620 surface->pixels = NULL;
621 SDL_UnlockCursor();
622 }
623}
624
625static void GS_DMAFullUpdate(_THIS, int numrects, SDL_Rect *rects)
626{
627 /* Lock so we aren't interrupted by a mouse update */
628 SDL_LockCursor();
629
630 /* Make sure any pending DMA has completed */
631 if ( dma_pending ) {
632 ioctl(console_fd, PS2IOC_SENDQCT, 1);
633 dma_pending = 0;
634 }
635
636 /* If the mouse is visible, draw it on the DMA area */
637 if ( (SDL_cursorstate & CURSOR_VISIBLE) && !cursor_drawn ) {
638 this->screen->pixels = mapped_mem + this->screen->offset;
639 SDL_DrawCursorNoLock(this->screen);
640 this->screen->pixels = NULL;
641 cursor_drawn = 1;
642 }
643
644 /* Put the image onto the screen */
645 loadimage_nonblock(console_fd,
646 &screen_image, screen_image_size,
647 head_tags_mem, image_tags_mem);
648 if ( screen_image.y > 0 ) {
649 /* Need to scale offscreen image to TV output */
650 ioctl(console_fd, PS2IOC_SENDQCT, 1);
651 dma_pending = 0;
652 scaleimage_nonblock(console_fd, tex_tags_mem, scale_tags_mem);
653 } else {
654 dma_pending = 1;
655 }
656
657 /* We're finished! */
658 SDL_UnlockCursor();
659}
660
661static int GS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
662{
663 return(0);
664}
665
666static void GS_VideoQuit(_THIS)
667{
668 /* Close console and input file descriptors */
669 if ( console_fd > 0 ) {
670 /* Unmap the video framebuffer */
671 if ( mapped_mem ) {
672 /* Unmap the video framebuffer */
673 munmap(mapped_mem, mapped_len);
674 mapped_mem = NULL;
675 }
676 close(memory_fd);
677
678 /* Restore the original video mode */
679 if ( GS_InGraphicsMode(this) ) {
680 ioctl(console_fd, PS2IOC_SSCREENINFO, &saved_vinfo);
681 }
682
683 /* We're all done with the graphics device */
684 close(console_fd);
685 console_fd = -1;
686 }
687 GS_CloseMouse(this);
688 GS_CloseKeyboard(this);
689}
diff --git a/apps/plugins/sdl/src/video/ps2gs/SDL_gsvideo.h b/apps/plugins/sdl/src/video/ps2gs/SDL_gsvideo.h
deleted file mode 100644
index 8972d70366..0000000000
--- a/apps/plugins/sdl/src/video/ps2gs/SDL_gsvideo.h
+++ /dev/null
@@ -1,95 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_gsvideo_h
25#define _SDL_gsvideo_h
26
27#include <sys/types.h>
28#include <termios.h>
29#include <linux/ps2/dev.h>
30#include <linux/ps2/gs.h>
31
32#include "SDL_mouse.h"
33#include "SDL_mutex.h"
34#include "../SDL_sysvideo.h"
35
36/* Hidden "this" pointer for the video functions */
37#define _THIS SDL_VideoDevice *this
38
39
40/* Private display data */
41struct SDL_PrivateVideoData {
42 /* Gotta love that simple PS2 graphics interface. :) */
43 int console_fd;
44 int memory_fd;
45 struct ps2_screeninfo saved_vinfo;
46
47 /* Ye olde linux keyboard code */
48 int current_vt;
49 int saved_vt;
50 int keyboard_fd;
51 int saved_kbd_mode;
52 struct termios saved_kbd_termios;
53
54 /* Ye olde linux mouse code */
55 int mouse_fd;
56 int cursor_drawn;
57
58 /* The memory mapped DMA area and associated variables */
59 caddr_t mapped_mem;
60 int pixels_len;
61 int mapped_len;
62 struct ps2_image screen_image;
63 int screen_image_size;
64 unsigned long long *head_tags_mem;
65 unsigned long long *image_tags_mem;
66 unsigned long long *tex_tags_mem;
67 unsigned long long *scale_tags_mem;
68 int dma_pending;
69};
70/* Old variable names */
71#define console_fd (this->hidden->console_fd)
72#define memory_fd (this->hidden->memory_fd)
73#define saved_vinfo (this->hidden->saved_vinfo)
74#define current_vt (this->hidden->current_vt)
75#define saved_vt (this->hidden->saved_vt)
76#define keyboard_fd (this->hidden->keyboard_fd)
77#define saved_kbd_mode (this->hidden->saved_kbd_mode)
78#define saved_kbd_termios (this->hidden->saved_kbd_termios)
79#define mouse_fd (this->hidden->mouse_fd)
80#define cursor_drawn (this->hidden->cursor_drawn)
81#define mapped_mem (this->hidden->mapped_mem)
82#define pixels_len (this->hidden->pixels_len)
83#define mapped_len (this->hidden->mapped_len)
84#define screen_image (this->hidden->screen_image)
85#define screen_image_size (this->hidden->screen_image_size)
86#define head_tags_mem (this->hidden->head_tags_mem)
87#define image_tags_mem (this->hidden->image_tags_mem)
88#define tex_tags_mem (this->hidden->tex_tags_mem)
89#define scale_tags_mem (this->hidden->scale_tags_mem)
90#define dma_pending (this->hidden->dma_pending)
91
92/* Shared between the mouse and video code for screen update scaling */
93extern int scaleimage_nonblock(int fd,
94 unsigned long long *tm, unsigned long long *sm);
95#endif /* _SDL_gsvideo_h */
diff --git a/apps/plugins/sdl/src/video/ps2gs/SDL_gsyuv.c b/apps/plugins/sdl/src/video/ps2gs/SDL_gsyuv.c
deleted file mode 100644
index ec52a69b25..0000000000
--- a/apps/plugins/sdl/src/video/ps2gs/SDL_gsyuv.c
+++ /dev/null
@@ -1,461 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the Playstation 2 implementation of YUV video overlays */
25
26#include <fcntl.h>
27#include <unistd.h>
28#include <sys/ioctl.h>
29#include <sys/mman.h>
30#include <asm/page.h> /* For definition of PAGE_SIZE */
31
32#include "SDL_video.h"
33#include "SDL_gsyuv_c.h"
34#include "../SDL_yuvfuncs.h"
35
36/* The maximum number of 16x16 pixel block converted at once */
37#define MAX_MACROBLOCKS 1024 /* 2^10 macroblocks at once */
38
39/* The functions used to manipulate video overlays */
40static struct private_yuvhwfuncs gs_yuvfuncs = {
41 GS_LockYUVOverlay,
42 GS_UnlockYUVOverlay,
43 GS_DisplayYUVOverlay,
44 GS_FreeYUVOverlay
45};
46
47struct private_yuvhwdata {
48 int ipu_fd;
49 Uint8 *pixels;
50 int macroblocks;
51 int dma_len;
52 caddr_t dma_mem;
53 caddr_t ipu_imem;
54 caddr_t ipu_omem;
55 caddr_t dma_tags;
56 unsigned long long *stretch_x1y1;
57 unsigned long long *stretch_x2y2;
58 struct ps2_plist plist;
59
60 /* These are just so we don't have to allocate them separately */
61 Uint16 pitches[3];
62 Uint8 *planes[3];
63};
64
65static int power_of_2(int value)
66{
67 int shift;
68
69 for ( shift = 0; (1<<shift) < value; ++shift ) {
70 /* Keep looking */ ;
71 }
72 return(shift);
73}
74
75SDL_Overlay *GS_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display)
76{
77 SDL_Overlay *overlay;
78 struct private_yuvhwdata *hwdata;
79 int map_offset;
80 unsigned long long *tags;
81 caddr_t base;
82 int bpp;
83 int fbp, fbw, psm;
84 int x, y, w, h;
85 int pnum;
86 struct ps2_packet *packet;
87 struct ps2_packet tex_packet;
88
89 /* We can only decode blocks of 16x16 pixels */
90 if ( (width & 15) || (height & 15) ) {
91 SDL_SetError("Overlay width/height must be multiples of 16");
92 return(NULL);
93 }
94 /* Make sure the image isn't too large for a single DMA transfer */
95 if ( ((width/16) * (height/16)) > MAX_MACROBLOCKS ) {
96 SDL_SetError("Overlay too large (maximum size: %d pixels)",
97 MAX_MACROBLOCKS * 16 * 16);
98 return(NULL);
99 }
100
101 /* Double-check the requested format. For simplicity, we'll only
102 support planar YUV formats.
103 */
104 switch (format) {
105 case SDL_YV12_OVERLAY:
106 case SDL_IYUV_OVERLAY:
107 /* Supported planar YUV format */
108 break;
109 default:
110 SDL_SetError("Unsupported YUV format");
111 return(NULL);
112 }
113
114 /* Create the overlay structure */
115 overlay = (SDL_Overlay *)SDL_malloc(sizeof *overlay);
116 if ( overlay == NULL ) {
117 SDL_OutOfMemory();
118 return(NULL);
119 }
120 SDL_memset(overlay, 0, (sizeof *overlay));
121
122 /* Fill in the basic members */
123 overlay->format = format;
124 overlay->w = width;
125 overlay->h = height;
126
127 /* Set up the YUV surface function structure */
128 overlay->hwfuncs = &gs_yuvfuncs;
129 overlay->hw_overlay = 1;
130
131 /* Create the pixel data */
132 hwdata = (struct private_yuvhwdata *)SDL_malloc(sizeof *hwdata);
133 overlay->hwdata = hwdata;
134 if ( hwdata == NULL ) {
135 SDL_FreeYUVOverlay(overlay);
136 SDL_OutOfMemory();
137 return(NULL);
138 }
139 hwdata->ipu_fd = -1;
140 hwdata->pixels = (Uint8 *)SDL_malloc(width*height*2);
141 if ( hwdata->pixels == NULL ) {
142 SDL_FreeYUVOverlay(overlay);
143 SDL_OutOfMemory();
144 return(NULL);
145 }
146 hwdata->macroblocks = (width/16) * (height/16);
147
148 /* Find the pitch and offset values for the overlay */
149 overlay->pitches = hwdata->pitches;
150 overlay->pixels = hwdata->planes;
151 switch (format) {
152 case SDL_YV12_OVERLAY:
153 case SDL_IYUV_OVERLAY:
154 overlay->pitches[0] = overlay->w;
155 overlay->pitches[1] = overlay->pitches[0] / 2;
156 overlay->pitches[2] = overlay->pitches[0] / 2;
157 overlay->pixels[0] = hwdata->pixels;
158 overlay->pixels[1] = overlay->pixels[0] +
159 overlay->pitches[0] * overlay->h;
160 overlay->pixels[2] = overlay->pixels[1] +
161 overlay->pitches[1] * overlay->h / 2;
162 overlay->planes = 3;
163 break;
164 default:
165 /* We should never get here (caught above) */
166 break;
167 }
168
169 /* Theoretically we could support several concurrent decode
170 streams queueing up on the same file descriptor, but for
171 simplicity we'll support only one. Opening the IPU more
172 than once will fail with EBUSY.
173 */
174 hwdata->ipu_fd = open("/dev/ps2ipu", O_RDWR);
175 if ( hwdata->ipu_fd < 0 ) {
176 SDL_FreeYUVOverlay(overlay);
177 SDL_SetError("Playstation 2 IPU busy");
178 return(NULL);
179 }
180
181 /* Allocate a DMA area for pixel conversion */
182 bpp = this->screen->format->BytesPerPixel;
183 map_offset = (mapped_len + (sysconf(_SC_PAGESIZE) - 1)) & ~(sysconf(_SC_PAGESIZE) - 1);
184 hwdata->dma_len = hwdata->macroblocks * (16 * 16 + 8 * 8 + 8 * 8) +
185 width * height * bpp +
186 hwdata->macroblocks * (16 * sizeof(long long)) +
187 12 * sizeof(long long);
188 hwdata->dma_mem = mmap(0, hwdata->dma_len, PROT_READ|PROT_WRITE,
189 MAP_SHARED, memory_fd, map_offset);
190 if ( hwdata->dma_mem == MAP_FAILED ) {
191 hwdata->ipu_imem = (caddr_t)0;
192 SDL_FreeYUVOverlay(overlay);
193 SDL_SetError("Unable to map %d bytes for DMA", hwdata->dma_len);
194 return(NULL);
195 }
196 hwdata->ipu_imem = hwdata->dma_mem;
197 hwdata->ipu_omem = hwdata->ipu_imem +
198 hwdata->macroblocks * (16 * 16 + 8 * 8 + 8 * 8);
199 hwdata->dma_tags = hwdata->ipu_omem + width * height * bpp;
200
201 /* Allocate memory for the DMA packets */
202 hwdata->plist.num = hwdata->macroblocks * 4 + 1;
203 hwdata->plist.packet = (struct ps2_packet *)SDL_malloc(
204 hwdata->plist.num*sizeof(struct ps2_packet));
205 if ( ! hwdata->plist.packet ) {
206 SDL_FreeYUVOverlay(overlay);
207 SDL_OutOfMemory();
208 return(NULL);
209 }
210 pnum = 0;
211 packet = hwdata->plist.packet;
212
213 /* Set up the tags to send the image to the screen */
214 tags = (unsigned long long *)hwdata->dma_tags;
215 base = hwdata->ipu_omem;
216 fbp = screen_image.fbp;
217 fbw = screen_image.fbw;
218 psm = screen_image.psm;
219 y = screen_image.y + screen_image.h; /* Offscreen video memory */
220 for ( h=height/16; h; --h ) {
221 x = 0; /* Visible video memory */
222 for ( w=width/16; w; --w ) {
223 /* The head tag */
224 packet[pnum].ptr = &tags[0];
225 packet[pnum].len = 10 * sizeof(*tags);
226 ++pnum;
227 tags[0] = 4 | (1LL << 60); /* GIFtag */
228 tags[1] = 0x0e; /* A+D */
229 tags[2] = ((unsigned long long)fbp << 32) |
230 ((unsigned long long)fbw << 48) |
231 ((unsigned long long)psm << 56);
232 tags[3] = PS2_GS_BITBLTBUF;
233 tags[4] = ((unsigned long long)x << 32) |
234 ((unsigned long long)y << 48);
235 tags[5] = PS2_GS_TRXPOS;
236 tags[6] = (unsigned long long)16 |
237 ((unsigned long long)16 << 32);
238 tags[7] = PS2_GS_TRXREG;
239 tags[8] = 0;
240 tags[9] = PS2_GS_TRXDIR;
241 /* Now the actual image data */
242 packet[pnum].ptr = &tags[10];
243 packet[pnum].len = 2 * sizeof(*tags);
244 ++pnum;
245 tags[10] = ((16*16*bpp) >> 4) | (2LL << 58);
246 tags[11] = 0;
247 packet[pnum].ptr = (void *)base;
248 packet[pnum].len = 16 * 16 * bpp;
249 ++pnum;
250 packet[pnum].ptr = &tags[12];
251 packet[pnum].len = 2 * sizeof(*tags);
252 ++pnum;
253 tags[12] = (0 >> 4) | (1 << 15) | (2LL << 58);
254 tags[13] = 0;
255
256 tags += 16;
257 base += 16 * 16 * bpp;
258
259 x += 16;
260 }
261 y += 16;
262 }
263
264 /* Set up the texture memory area for the video */
265 tex_packet.ptr = tags;
266 tex_packet.len = 8 * sizeof(*tags);
267 tags[0] = 3 | (1LL << 60); /* GIFtag */
268 tags[1] = 0x0e; /* A+D */
269 tags[2] = ((screen_image.y + screen_image.h) * screen_image.w) / 64 +
270 ((unsigned long long)fbw << 14) +
271 ((unsigned long long)psm << 20) +
272 ((unsigned long long)power_of_2(width) << 26) +
273 ((unsigned long long)power_of_2(height) << 30) +
274 ((unsigned long long)1 << 34) +
275 ((unsigned long long)1 << 35);
276 tags[3] = PS2_GS_TEX0_1;
277 tags[4] = (1 << 5) + (1 << 6);
278 tags[5] = PS2_GS_TEX1_1;
279 tags[6] = 0;
280 tags[7] = PS2_GS_TEXFLUSH;
281 ioctl(console_fd, PS2IOC_SEND, &tex_packet);
282
283 /* Set up the tags for scaling the image */
284 packet[pnum].ptr = tags;
285 packet[pnum].len = 12 * sizeof(*tags);
286 ++pnum;
287 tags[0] = 5 | (1LL << 60); /* GIFtag */
288 tags[1] = 0x0e; /* A+D */
289 tags[2] = 6 + (1 << 4) + (1 << 8);
290 tags[3] = PS2_GS_PRIM;
291 tags[4] = ((unsigned long long)0 * 16) +
292 (((unsigned long long)0 * 16) << 16);
293 tags[5] = PS2_GS_UV;
294 tags[6] = 0; /* X1, Y1 */
295 tags[7] = PS2_GS_XYZ2;
296 hwdata->stretch_x1y1 = &tags[6];
297 tags[8] = ((unsigned long long)overlay->w * 16) +
298 (((unsigned long long)overlay->h * 16) << 16);
299 tags[9] = PS2_GS_UV;
300 tags[10] = 0; /* X2, Y2 */
301 tags[11] = PS2_GS_XYZ2;
302 hwdata->stretch_x2y2 = &tags[10];
303
304 /* We're all done.. */
305 return(overlay);
306}
307
308int GS_LockYUVOverlay(_THIS, SDL_Overlay *overlay)
309{
310 return(0);
311}
312
313void GS_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay)
314{
315 return;
316}
317
318int GS_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst)
319{
320 struct private_yuvhwdata *hwdata;
321 __u32 cmd;
322 struct ps2_packet packet;
323 int h, w, i;
324 Uint32 *lum, *Cr, *Cb;
325 int lum_pitch;
326 int crb_pitch;
327 Uint32 *lum_src, *Cr_src, *Cb_src;
328 Uint32 *srcp, *dstp;
329 unsigned int x, y;
330 SDL_Surface *screen;
331
332 /* Find out where the various portions of the image are */
333 hwdata = overlay->hwdata;
334 switch (overlay->format) {
335 case SDL_YV12_OVERLAY:
336 lum = (Uint32 *)overlay->pixels[0];
337 Cr = (Uint32 *)overlay->pixels[1];
338 Cb = (Uint32 *)overlay->pixels[2];
339 break;
340 case SDL_IYUV_OVERLAY:
341 lum = (Uint32 *)overlay->pixels[0];
342 Cr = (Uint32 *)overlay->pixels[2];
343 Cb = (Uint32 *)overlay->pixels[1];
344 default:
345 SDL_SetError("Unsupported YUV format in blit (?)");
346 return(-1);
347 }
348 dstp = (Uint32 *)hwdata->ipu_imem;
349 lum_pitch = overlay->w/4;
350 crb_pitch = (overlay->w/2)/4;
351
352 /* Copy blocks of 16x16 pixels to the DMA area */
353 for ( h=overlay->h/16; h; --h ) {
354 lum_src = lum;
355 Cr_src = Cr;
356 Cb_src = Cb;
357 for ( w=overlay->w/16; w; --w ) {
358 srcp = lum_src;
359 for ( i=0; i<16; ++i ) {
360 dstp[0] = srcp[0];
361 dstp[1] = srcp[1];
362 dstp[2] = srcp[2];
363 dstp[3] = srcp[3];
364 srcp += lum_pitch;
365 dstp += 4;
366 }
367 srcp = Cb_src;
368 for ( i=0; i<8; ++i ) {
369 dstp[0] = srcp[0];
370 dstp[1] = srcp[1];
371 srcp += crb_pitch;
372 dstp += 2;
373 }
374 srcp = Cr_src;
375 for ( i=0; i<8; ++i ) {
376 dstp[0] = srcp[0];
377 dstp[1] = srcp[1];
378 srcp += crb_pitch;
379 dstp += 2;
380 }
381 lum_src += 16 / 4;
382 Cb_src += 8 / 4;
383 Cr_src += 8 / 4;
384 }
385 lum += lum_pitch * 16;
386 Cr += crb_pitch * 8;
387 Cb += crb_pitch * 8;
388 }
389
390 /* Send the macroblock data to the IPU */
391#ifdef DEBUG_YUV
392 fprintf(stderr, "Sending data to IPU..\n");
393#endif
394 packet.ptr = hwdata->ipu_imem;
395 packet.len = hwdata->macroblocks * (16 * 16 + 8 * 8 + 8 * 8);
396 ioctl(hwdata->ipu_fd, PS2IOC_SENDA, &packet);
397
398 /* Trigger the DMA to the IPU for conversion */
399#ifdef DEBUG_YUV
400 fprintf(stderr, "Trigging conversion command\n");
401#endif
402 cmd = (7 << 28) + hwdata->macroblocks;
403 if ( screen_image.psm == PS2_GS_PSMCT16 ) {
404 cmd += (1 << 27) + /* Output RGB 555 */
405 (1 << 26); /* Dither output */
406 }
407 ioctl(hwdata->ipu_fd, PS2IOC_SIPUCMD, &cmd);
408
409 /* Retrieve the converted image from the IPU */
410#ifdef DEBUG_YUV
411 fprintf(stderr, "Retrieving data from IPU..\n");
412#endif
413 packet.ptr = hwdata->ipu_omem;
414 packet.len = overlay->w * overlay->h *
415 this->screen->format->BytesPerPixel;
416 ioctl(hwdata->ipu_fd, PS2IOC_RECV, &packet);
417
418#ifdef DEBUG_YUV
419 fprintf(stderr, "Copying image to screen..\n");
420#endif
421 /* Wait for previous DMA to complete */
422 ioctl(console_fd, PS2IOC_SENDQCT, 1);
423
424 /* Send the current image to the screen and scale it */
425 screen = this->screen;
426 x = (unsigned int)dst->x;
427 y = (unsigned int)dst->y;
428 if ( screen->offset ) {
429 x += (screen->offset % screen->pitch) /
430 screen->format->BytesPerPixel;
431 y += (screen->offset / screen->pitch);
432 }
433 y += screen_image.y;
434 *hwdata->stretch_x1y1 = (x * 16) + ((y * 16) << 16);
435 x += (unsigned int)dst->w;
436 y += (unsigned int)dst->h;
437 *hwdata->stretch_x2y2 = (x * 16) + ((y * 16) << 16);
438 return ioctl(console_fd, PS2IOC_SENDL, &hwdata->plist);
439}
440
441void GS_FreeYUVOverlay(_THIS, SDL_Overlay *overlay)
442{
443 struct private_yuvhwdata *hwdata;
444
445 hwdata = overlay->hwdata;
446 if ( hwdata ) {
447 if ( hwdata->ipu_fd >= 0 ) {
448 close(hwdata->ipu_fd);
449 }
450 if ( hwdata->dma_mem ) {
451 munmap(hwdata->dma_mem, hwdata->dma_len);
452 }
453 if ( hwdata->plist.packet ) {
454 SDL_free(hwdata->plist.packet);
455 }
456 if ( hwdata->pixels ) {
457 SDL_free(hwdata->pixels);
458 }
459 SDL_free(hwdata);
460 }
461}
diff --git a/apps/plugins/sdl/src/video/ps2gs/SDL_gsyuv_c.h b/apps/plugins/sdl/src/video/ps2gs/SDL_gsyuv_c.h
deleted file mode 100644
index d9ffad6f5c..0000000000
--- a/apps/plugins/sdl/src/video/ps2gs/SDL_gsyuv_c.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the Playstation 2 implementation of YUV video overlays */
25
26#include "SDL_video.h"
27#include "SDL_gsvideo.h"
28
29extern SDL_Overlay *GS_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display);
30
31extern int GS_LockYUVOverlay(_THIS, SDL_Overlay *overlay);
32
33extern void GS_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay);
34
35extern int GS_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst);
36
37extern void GS_FreeYUVOverlay(_THIS, SDL_Overlay *overlay);
diff --git a/apps/plugins/sdl/src/video/ps3/SDL_ps3events.c b/apps/plugins/sdl/src/video/ps3/SDL_ps3events.c
deleted file mode 100644
index e39efcc4f0..0000000000
--- a/apps/plugins/sdl/src/video/ps3/SDL_ps3events.c
+++ /dev/null
@@ -1,44 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28#include "SDL_config.h"
29
30#include "../../events/SDL_sysevents.h"
31#include "../../events/SDL_events_c.h"
32#include "SDL_ps3video.h"
33#include "SDL_ps3events_c.h"
34
35void PS3_PumpEvents(_THIS)
36{
37 return;
38}
39
40void PS3_InitOSKeymap(_THIS)
41{
42 return;
43}
44
diff --git a/apps/plugins/sdl/src/video/ps3/SDL_ps3events_c.h b/apps/plugins/sdl/src/video/ps3/SDL_ps3events_c.h
deleted file mode 100644
index fd11209af1..0000000000
--- a/apps/plugins/sdl/src/video/ps3/SDL_ps3events_c.h
+++ /dev/null
@@ -1,41 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28#include "SDL_config.h"
29
30#ifndef _SDL_ps3events_h
31#define _SDL_ps3events_h
32
33#include "SDL_ps3video.h"
34
35extern void PS3_InitOSKeymap(_THIS);
36extern void PS3_PumpEvents(_THIS);
37
38extern void enable_cursor(int enable);
39
40#endif /* _SDL_ps3events_h */
41
diff --git a/apps/plugins/sdl/src/video/ps3/SDL_ps3video.c b/apps/plugins/sdl/src/video/ps3/SDL_ps3video.c
deleted file mode 100644
index d5519e051e..0000000000
--- a/apps/plugins/sdl/src/video/ps3/SDL_ps3video.c
+++ /dev/null
@@ -1,621 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28#include "SDL_config.h"
29
30#include "SDL_video.h"
31#include "../SDL_sysvideo.h"
32#include "SDL_ps3events_c.h"
33#include "SDL_ps3video.h"
34#include "SDL_ps3yuv_c.h"
35#include "spulibs/spu_common.h"
36
37#include <fcntl.h>
38#include <stdlib.h>
39#include <sys/ioctl.h>
40#include <linux/kd.h>
41#include <sys/mman.h>
42
43#include <linux/fb.h>
44#include <asm/ps3fb.h>
45#include <libspe2.h>
46#include <malloc.h>
47
48/* SDL_VideoDevice functions */
49static int PS3_Available();
50static SDL_VideoDevice *PS3_CreateDevice(int devindex);
51static int PS3_VideoInit(_THIS, SDL_PixelFormat * vformat);
52static void PS3_VideoQuit(_THIS);
53static void PS3_DeleteDevice(SDL_VideoDevice * device);
54static SDL_Surface *PS3_SetVideoMode(_THIS, SDL_Surface * current, int width, int height, int bpp, Uint32 flags);
55static SDL_Rect **PS3_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags);
56
57/* Hardware surface functions */
58static int PS3_AllocHWSurface(_THIS, SDL_Surface * surface);
59static void PS3_FreeHWSurface(_THIS, SDL_Surface * surface);
60static int PS3_LockHWSurface(_THIS, SDL_Surface * surface);
61static void PS3_UnlockHWSurface(_THIS, SDL_Surface * surface);
62static int PS3_FlipDoubleBuffer(_THIS, SDL_Surface * surface);
63static void PS3_DoubleBufferUpdate(_THIS, int numrects, SDL_Rect * rects);
64
65/* SPU specific functions */
66int SPE_Start(_THIS, spu_data_t * spe_data);
67int SPE_Stop(_THIS, spu_data_t * spe_data);
68int SPE_Boot(_THIS, spu_data_t * spe_data);
69int SPE_Shutdown(_THIS, spu_data_t * spe_data);
70int SPE_SendMsg(_THIS, spu_data_t * spe_data, unsigned int msg);
71int SPE_WaitForMsg(_THIS, spu_data_t * spe_data, unsigned int msg);
72void SPE_RunContext(void *thread_argp);
73
74/* Helpers */
75void enable_cursor(int enable);
76
77/* Stores the SPE executable name of fb_writer_spu */
78extern spe_program_handle_t fb_writer_spu;
79
80/* SDL PS3 bootstrap function for checking availability */
81static int PS3_Available()
82{
83 return 1;
84}
85
86/* SDL PS3 bootstrap function for creating the device */
87static SDL_VideoDevice *PS3_CreateDevice(int devindex)
88{
89 SDL_VideoDevice *this;
90
91 /* Initialise SDL_VideoDevice */
92 this = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice));
93 if (this) {
94 memset(this, 0, sizeof *this);
95 this->hidden = (struct SDL_PrivateVideoData *)
96 SDL_malloc(sizeof(struct SDL_PrivateVideoData));
97 }
98 /* Error handling */
99 if ((this == NULL) || (this->hidden == NULL)) {
100 SDL_OutOfMemory();
101 if (this)
102 SDL_free(this);
103 return 0;
104 }
105 memset(this->hidden, 0, sizeof(struct SDL_PrivateVideoData));
106
107 /* Set the function pointers */
108 this->VideoInit = PS3_VideoInit;
109 this->ListModes = PS3_ListModes;
110 this->SetVideoMode = PS3_SetVideoMode;
111 this->SetColors = 0;
112 this->CreateYUVOverlay = PS3_CreateYUVOverlay;
113 this->UpdateRects = 0;
114 this->VideoQuit = PS3_VideoQuit;
115 this->AllocHWSurface = PS3_AllocHWSurface;
116 this->CheckHWBlit = 0;
117 this->FillHWRect = 0;
118 this->SetHWColorKey = 0;
119 this->SetHWAlpha = 0;
120 this->LockHWSurface = PS3_LockHWSurface;
121 this->UnlockHWSurface = PS3_UnlockHWSurface;
122 this->FlipHWSurface = PS3_FlipDoubleBuffer;
123 this->FreeHWSurface = PS3_FreeHWSurface;
124 this->SetCaption = 0;
125 this->SetIcon = 0;
126 this->IconifyWindow = 0;
127 this->GrabInput = 0;
128 this->GetWMInfo = 0;
129 this->InitOSKeymap = PS3_InitOSKeymap;
130 this->PumpEvents = PS3_PumpEvents;
131
132 this->free = PS3_DeleteDevice;
133
134 return this;
135}
136
137
138/* Bootstraping (see SDL_sysvideo.h) */
139VideoBootStrap PS3_bootstrap = {
140 "ps3", "PS3 Cell SPU Driver",
141 PS3_Available, PS3_CreateDevice
142};
143
144
145/* Delete the device */
146static void PS3_DeleteDevice(SDL_VideoDevice * device)
147{
148 free(device->hidden);
149 free(device);
150}
151
152
153/* Initialise the PS3 video device */
154static int PS3_VideoInit(_THIS, SDL_PixelFormat * vformat)
155{
156 /* Hide the cursor */
157 enable_cursor(0);
158
159 /* Create SPU fb_parms and thread structure */
160 fb_parms = (struct fb_writer_parms_t *)
161 memalign(16, sizeof(struct fb_writer_parms_t));
162 fb_thread_data = (spu_data_t *) malloc(sizeof(spu_data_t));
163 if (fb_parms == NULL || fb_thread_data == NULL) {
164 SDL_OutOfMemory();
165 return -1;
166 }
167 fb_thread_data->program = fb_writer_spu;
168 fb_thread_data->program_name = "fb_writer_spu";
169 fb_thread_data->argp = (void *)fb_parms;
170 fb_thread_data->keepalive = 1;
171 fb_thread_data->booted = 0;
172
173 SPE_Start(this, fb_thread_data);
174
175 /* Open the device */
176 fb_dev_fd = open(PS3_DEV_FB, O_RDWR);
177 if (fb_dev_fd < 0) {
178 SDL_SetError("[PS3] Unable to open device %s", PS3_DEV_FB);
179 return -1;
180 }
181
182 /* Get vscreeninfo */
183 if (ioctl(fb_dev_fd, FBIOGET_VSCREENINFO, &fb_vinfo)) {
184 SDL_SetError("[PS3] Can't get VSCREENINFO");
185 if (fb_dev_fd >= 0)
186 close(fb_dev_fd);
187 fb_dev_fd = -1;
188 return -1;
189 }
190
191 /* Fill in our hardware acceleration capabilities */
192 this->info.current_w = fb_vinfo.xres;
193 this->info.current_h = fb_vinfo.yres;
194 this->info.wm_available = 0;
195 this->info.hw_available = 1;
196
197 /* Backup the original vinfo to restore later */
198 fb_orig_vinfo = fb_vinfo;
199
200 /* 16 and 15 bpp is reported as 16 bpp */
201 fb_bits_per_pixel = fb_vinfo.bits_per_pixel;
202 if (fb_bits_per_pixel == 16)
203 fb_bits_per_pixel =
204 fb_vinfo.red.length + fb_vinfo.green.length +
205 fb_vinfo.blue.length;
206
207 /* Set SDL_PixelFormat */
208 vformat->BitsPerPixel = fb_vinfo.bits_per_pixel;
209
210 fb_vinfo.xres_virtual = fb_vinfo.xres;
211 fb_vinfo.yres_virtual = fb_vinfo.yres;
212
213 /* Put vscreeninfo */
214 if (ioctl(fb_dev_fd, FBIOPUT_VSCREENINFO, &fb_vinfo)) {
215 SDL_SetError("[PS3] Can't put VSCREENINFO");
216 if (fb_dev_fd >= 0)
217 close(fb_dev_fd);
218 fb_dev_fd = -1;
219 return -1;
220 }
221
222 s_fb_pixel_size = fb_vinfo.bits_per_pixel / 8;
223
224 s_writeable_width = fb_vinfo.xres;
225 s_writeable_height = fb_vinfo.yres;
226
227 /* Get ps3 screeninfo */
228 if (ioctl(fb_dev_fd, PS3FB_IOCTL_SCREENINFO, (unsigned long)&res) < 0) {
229 SDL_SetError("[PS3] PS3FB_IOCTL_SCREENINFO failed");
230 }
231 deprintf(1, "[PS3] xres:%d yres:%d xoff:%d yoff:%d\n", res.xres, res.yres, res.xoff, res.yoff);
232
233 /* Only use double buffering if enough fb memory is available */
234 if (res.num_frames < 2) {
235 double_buffering = 0;
236 } else {
237 double_buffering = 1;
238 }
239
240 real_width = res.xres;
241 real_height = res.yres;
242
243 /*
244 * Take control of frame buffer from kernel, for details see
245 * http://felter.org/wesley/files/ps3/linux-20061110-docs/ApplicationProgrammingEnvironment.html
246 * kernel will no longer flip the screen itself
247 */
248 ioctl(fb_dev_fd, PS3FB_IOCTL_ON, 0);
249
250 /* Unblank screen */
251 ioctl(fb_dev_fd, FBIOBLANK, 0);
252
253 return 0;
254}
255
256
257/* List available PS3 resolutions */
258static SDL_Rect **PS3_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags)
259{
260 /* A list of video resolutions that we query for (sorted largest to
261 * smallest)
262 */
263 static SDL_Rect PS3_resolutions[] = {
264 {0, 0, 1920, 1080}, // 1080p 16:9 HD
265 {0, 0, 1600, 1200}, // WUXGA
266 {0, 0, 1280, 1024}, // SXGA
267 {0, 0, 1280, 720}, // 720p 16:9 HD
268 {0, 0, 1024, 768}, // WXGA
269 {0, 0, 1024, 576}, // 576p 16:9
270 {0, 0, 853, 480}, // 480p 16:9
271 {0, 0, 720, 576}, // 576p 4:3 (PAL)
272 {0, 0, 720, 480}, // 480p 16:9 (NTSC)
273 };
274 static SDL_Rect *PS3_modes[] = {
275 &PS3_resolutions[0],
276 &PS3_resolutions[1],
277 &PS3_resolutions[2],
278 &PS3_resolutions[3],
279 &PS3_resolutions[4],
280 &PS3_resolutions[5],
281 &PS3_resolutions[6],
282 &PS3_resolutions[7],
283 &PS3_resolutions[8],
284 NULL
285 };
286 SDL_Rect **modes = PS3_modes;
287
288 return modes;
289}
290
291
292/* Get a list of the available display modes */
293static SDL_Surface *PS3_SetVideoMode(_THIS, SDL_Surface * current, int width, int height, int bpp, Uint32 flags)
294{
295 s_bounded_input_width = width < s_writeable_width ? width : s_writeable_width;
296 s_bounded_input_height = height < s_writeable_height ? height : s_writeable_height;
297 s_bounded_input_width_offset = (s_writeable_width - s_bounded_input_width) >> 1;
298 s_bounded_input_height_offset = (s_writeable_height - s_bounded_input_height) >> 1;
299 s_input_line_length = width * s_fb_pixel_size;
300
301 current->flags |= flags;
302
303 if (ioctl(fb_dev_fd, FBIOGET_FSCREENINFO, &fb_finfo)) {
304 SDL_SetError("[PS3] Can't get fixed screeninfo");
305 return NULL;
306 }
307
308 if (fb_finfo.type != FB_TYPE_PACKED_PIXELS) {
309 SDL_SetError("[PS3] type %s not supported",
310 fb_finfo.type);
311 return NULL;
312 }
313
314 /* Note: on PS3, fb_finfo.smem_len is enough for double buffering */
315 if ((frame_buffer =
316 (uint8_t *) mmap(0, fb_finfo.smem_len,
317 PROT_READ | PROT_WRITE, MAP_SHARED,
318 fb_dev_fd, 0)) == (uint8_t *) - 1) {
319 SDL_SetError("[PS3] Can't mmap for %s", PS3_DEV_FB);
320 return NULL;
321 } else {
322 current->flags |= SDL_DOUBLEBUF;
323 }
324 if (!SDL_ReallocFormat(current, fb_bits_per_pixel, 0, 0, 0, 0)) {
325 return (NULL);
326 }
327
328 /* Blank screen */
329 memset(frame_buffer, 0x00, fb_finfo.smem_len);
330
331 /* Centering */
332 s_center[0] =
333 frame_buffer + s_bounded_input_width_offset * s_fb_pixel_size +
334 s_bounded_input_height_offset * fb_finfo.line_length;
335 s_center[1] = s_center[0] + real_height * fb_finfo.line_length;
336 s_center_index = 0;
337
338 current->flags |= SDL_FULLSCREEN;
339 current->w = width;
340 current->h = height;
341 current->pitch = SDL_CalculatePitch(current);
342
343 /* Alloc aligned mem for current->pixels */
344 s_pixels = memalign(16, current->h * current->pitch);
345 current->pixels = (void *)s_pixels;
346 if (!current->pixels) {
347 SDL_OutOfMemory();
348 return NULL;
349 }
350
351 /* Set the update rectangle function */
352 this->UpdateRects = PS3_DoubleBufferUpdate;
353
354 return current;
355}
356
357
358/* Copy screen to framebuffer and flip */
359void PS3_DoubleBufferUpdate(_THIS, int numrects, SDL_Rect * rects)
360{
361 if (converter_thread_data && converter_thread_data->booted)
362 SPE_WaitForMsg(this, converter_thread_data, SPU_FIN);
363
364 /* Adjust centering */
365 s_bounded_input_width_offset = (s_writeable_width - s_bounded_input_width) >> 1;
366 s_bounded_input_height_offset = (s_writeable_height - s_bounded_input_height) >> 1;
367 s_center[0] = frame_buffer + s_bounded_input_width_offset * s_fb_pixel_size +
368 s_bounded_input_height_offset * fb_finfo.line_length;
369 s_center[1] = s_center[0] + real_height * fb_finfo.line_length;
370
371 /* Set SPU parms for copying the surface to framebuffer */
372 fb_parms->data = (unsigned char *)s_pixels;
373 fb_parms->center = s_center[s_center_index];
374 fb_parms->out_line_stride = fb_finfo.line_length;
375 fb_parms->in_line_stride = s_input_line_length;
376 fb_parms->bounded_input_height = s_bounded_input_height;
377 fb_parms->bounded_input_width = s_bounded_input_width;
378 fb_parms->fb_pixel_size = s_fb_pixel_size;
379
380 deprintf(3, "[PS3->SPU] fb_thread_data->argp = 0x%x\n", fb_thread_data->argp);
381
382 /* Copying.. */
383 SPE_SendMsg(this, fb_thread_data, SPU_START);
384 SPE_SendMsg(this, fb_thread_data, (unsigned int)fb_thread_data->argp);
385
386 SPE_WaitForMsg(this, fb_thread_data, SPU_FIN);
387
388 /* Flip the pages */
389 if (double_buffering)
390 s_center_index = s_center_index ^ 0x01;
391 PS3_FlipDoubleBuffer(this, this->screen);
392}
393
394
395/* Enable/Disable cursor */
396void enable_cursor(int enable)
397{
398 int fd = open("/dev/console", O_RDWR | O_NONBLOCK);
399 if (fd >= 0) {
400 ioctl(fd, KDSETMODE, enable ? KD_TEXT : KD_GRAPHICS);
401 close(fd);
402 }
403}
404
405
406static int PS3_AllocHWSurface(_THIS, SDL_Surface * surface)
407{
408 return -1;
409}
410
411
412static void PS3_FreeHWSurface(_THIS, SDL_Surface * surface)
413{
414 return;
415}
416
417
418static int PS3_LockHWSurface(_THIS, SDL_Surface * surface)
419{
420 return 0;
421}
422
423
424static void PS3_UnlockHWSurface(_THIS, SDL_Surface * surface)
425{
426 return;
427}
428
429
430/* Blit/Flip buffer to the screen. Must be called after each frame! */
431int PS3_FlipDoubleBuffer(_THIS, SDL_Surface * surface)
432{
433 unsigned long crt = 0;
434 /* Wait for vsync */
435 deprintf(1, "[PS3] Wait for vsync\n");
436 ioctl(fb_dev_fd, FBIO_WAITFORVSYNC, &crt);
437 /* Page flip */
438 deprintf(1, "[PS3] Page flip to buffer #%u 0x%x\n", s_center_index, s_center[s_center_index]);
439 ioctl(fb_dev_fd, PS3FB_IOCTL_FSEL, (unsigned long)&s_center_index);
440 return 1;
441}
442
443
444/* Start the SPE thread */
445int SPE_Start(_THIS, spu_data_t * spe_data)
446{
447 deprintf(2, "[PS3->SPU] Start SPE: %s\n", spe_data->program_name);
448 if (!(spe_data->booted))
449 SPE_Boot(this, spe_data);
450
451 /* To allow re-running of context, spe_ctx_entry has to be set before each call */
452 spe_data->entry = SPE_DEFAULT_ENTRY;
453 spe_data->error_code = 0;
454
455 /* Create SPE thread and run */
456 deprintf(2, "[PS3->SPU] Create Thread: %s\n", spe_data->program_name);
457 if (pthread_create
458 (&spe_data->thread, NULL, (void *)&SPE_RunContext, (void *)spe_data)) {
459 deprintf(2, "[PS3->SPU] Could not create pthread for spe: %s\n", spe_data->program_name);
460 SDL_SetError("[PS3->SPU] Could not create pthread for spe");
461 return -1;
462 }
463
464 if (spe_data->keepalive)
465 SPE_WaitForMsg(this, spe_data, SPU_READY);
466}
467
468
469/* Stop the SPE thread */
470int SPE_Stop(_THIS, spu_data_t * spe_data)
471{
472 deprintf(2, "[PS3->SPU] Stop SPE: %s\n", spe_data->program_name);
473 /* Wait for SPE thread to complete */
474 deprintf(2, "[PS3->SPU] Wait for SPE thread to complete: %s\n", spe_data->program_name);
475 if (pthread_join(spe_data->thread, NULL)) {
476 deprintf(2, "[PS3->SPU] Failed joining the thread: %s\n", spe_data->program_name);
477 SDL_SetError("[PS3->SPU] Failed joining the thread");
478 return -1;
479 }
480
481 return 0;
482}
483
484
485/* Create SPE context and load program */
486int SPE_Boot(_THIS, spu_data_t * spe_data)
487{
488 /* Create SPE context */
489 deprintf(2, "[PS3->SPU] Create SPE Context: %s\n", spe_data->program_name);
490 spe_data->ctx = spe_context_create(0, NULL);
491 if (spe_data->ctx == NULL) {
492 deprintf(2, "[PS3->SPU] Failed creating SPE context: %s\n", spe_data->program_name);
493 SDL_SetError("[PS3->SPU] Failed creating SPE context");
494 return -1;
495 }
496
497 /* Load SPE object into SPE local store */
498 deprintf(2, "[PS3->SPU] Load Program into SPE: %s\n", spe_data->program_name);
499 if (spe_program_load(spe_data->ctx, &spe_data->program)) {
500 deprintf(2, "[PS3->SPU] Failed loading program into SPE context: %s\n", spe_data->program_name);
501 SDL_SetError
502 ("[PS3->SPU] Failed loading program into SPE context");
503 return -1;
504 }
505 spe_data->booted = 1;
506 deprintf(2, "[PS3->SPU] SPE boot successful\n");
507
508 return 0;
509}
510
511/* (Stop and) shutdown the SPE */
512int SPE_Shutdown(_THIS, spu_data_t * spe_data)
513{
514 if (spe_data->keepalive && spe_data->booted) {
515 SPE_SendMsg(this, spe_data, SPU_EXIT);
516 SPE_Stop(this, spe_data);
517 }
518
519 /* Destroy SPE context */
520 deprintf(2, "[PS3->SPU] Destroy SPE context: %s\n", spe_data->program_name);
521 if (spe_context_destroy(spe_data->ctx)) {
522 deprintf(2, "[PS3->SPU] Failed destroying context: %s\n", spe_data->program_name);
523 SDL_SetError("[PS3->SPU] Failed destroying context");
524 return -1;
525 }
526 deprintf(2, "[PS3->SPU] SPE shutdown successful: %s\n", spe_data->program_name);
527 return 0;
528}
529
530
531/* Send message to the SPE via mailboxe */
532int SPE_SendMsg(_THIS, spu_data_t * spe_data, unsigned int msg)
533{
534 deprintf(2, "[PS3->SPU] Sending message %u to %s\n", msg, spe_data->program_name);
535 /* Send one message, block until message was sent */
536 unsigned int spe_in_mbox_msgs[1];
537 spe_in_mbox_msgs[0] = msg;
538 int in_mbox_write = spe_in_mbox_write(spe_data->ctx, spe_in_mbox_msgs, 1, SPE_MBOX_ALL_BLOCKING);
539
540 if (1 > in_mbox_write) {
541 deprintf(2, "[PS3->SPU] No message could be written to %s\n", spe_data->program_name);
542 SDL_SetError("[PS3->SPU] No message could be written");
543 return -1;
544 }
545 return 0;
546}
547
548
549/* Read 1 message from SPE, block until at least 1 message was received */
550int SPE_WaitForMsg(_THIS, spu_data_t * spe_data, unsigned int msg)
551{
552 deprintf(2, "[PS3->SPU] Waiting for message from %s\n", spe_data->program_name);
553 unsigned int out_messages[1];
554 while (!spe_out_mbox_status(spe_data->ctx));
555 int mbox_read = spe_out_mbox_read(spe_data->ctx, out_messages, 1);
556 deprintf(2, "[PS3->SPU] Got message from %s, message was %u\n", spe_data->program_name, out_messages[0]);
557 if (out_messages[0] == msg)
558 return 0;
559 else
560 return -1;
561}
562
563
564/* Re-runnable invocation of the spe_context_run call */
565void SPE_RunContext(void *thread_argp)
566{
567 /* argp is the pointer to argument to be passed to the SPE program */
568 spu_data_t *args = (spu_data_t *) thread_argp;
569 deprintf(3, "[PS3->SPU] void* argp=0x%x\n", (unsigned int)args->argp);
570
571 /* Run it.. */
572 deprintf(2, "[PS3->SPU] Run SPE program: %s\n", args->program_name);
573 if (spe_context_run
574 (args->ctx, &args->entry, 0, (void *)args->argp, NULL,
575 NULL) < 0) {
576 deprintf(2, "[PS3->SPU] Failed running SPE context: %s\n", args->program_name);
577 SDL_SetError("[PS3->SPU] Failed running SPE context: %s", args->program_name);
578 exit(1);
579 }
580
581 pthread_exit(NULL);
582}
583
584
585/* Quits the video driver */
586static void PS3_VideoQuit(_THIS)
587{
588 if (fb_dev_fd > 0) {
589 /* Restore the original video mode */
590 if (ioctl(fb_dev_fd, FBIOPUT_VSCREENINFO, &fb_orig_vinfo))
591 SDL_SetError("[PS3] Can't restore original fb_var_screeninfo");
592
593 /* Give control of frame buffer to kernel */
594 ioctl(fb_dev_fd, PS3FB_IOCTL_OFF, 0);
595 close(fb_dev_fd);
596 fb_dev_fd = -1;
597 }
598
599 if (frame_buffer) {
600 munmap(frame_buffer, fb_finfo.smem_len);
601 frame_buffer = 0;
602 }
603
604 if (fb_parms)
605 free((void *)fb_parms);
606 if (fb_thread_data) {
607 SPE_Shutdown(this, fb_thread_data);
608 free((void *)fb_thread_data);
609 }
610
611 if (this->screen) {
612 if (double_buffering && this->screen->pixels) {
613 free(this->screen->pixels);
614 }
615 this->screen->pixels = NULL;
616 }
617
618 enable_cursor(1);
619 deprintf(1, "[PS3] VideoQuit\n");
620}
621
diff --git a/apps/plugins/sdl/src/video/ps3/SDL_ps3video.h b/apps/plugins/sdl/src/video/ps3/SDL_ps3video.h
deleted file mode 100644
index 4fe5a2b42b..0000000000
--- a/apps/plugins/sdl/src/video/ps3/SDL_ps3video.h
+++ /dev/null
@@ -1,165 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28#include "SDL_config.h"
29#include "../SDL_sysvideo.h"
30#include "SDL_mouse.h"
31#include "SDL_mutex.h"
32#include "spulibs/spu_common.h"
33
34#include <libspe2.h>
35#include <pthread.h>
36#include <linux/types.h>
37#include <linux/fb.h>
38#include <asm/ps3fb.h>
39#include <linux/vt.h>
40#include <termios.h>
41
42#ifndef _SDL_ps3video_h
43#define _SDL_ps3video_h
44
45/* Debugging
46 * 0: No debug messages
47 * 1: Video debug messages
48 * 2: SPE debug messages
49 * 3: Memory adresses
50 */
51#define DEBUG_LEVEL 0
52
53#ifdef DEBUG_LEVEL
54#define deprintf( level, fmt, args... ) \
55 do \
56{ \
57 if ( (unsigned)(level) <= DEBUG_LEVEL ) \
58 { \
59 fprintf( stdout, fmt, ##args ); \
60 fflush( stdout ); \
61 } \
62} while ( 0 )
63#else
64#define deprintf( level, fmt, args... )
65#endif
66
67/* Framebuffer device */
68#define PS3_DEV_FB "/dev/fb0"
69
70/* Hidden "this" pointer for the video functions */
71#define _THIS SDL_VideoDevice * this
72
73/* SPU thread data */
74typedef struct spu_data {
75 spe_context_ptr_t ctx;
76 pthread_t thread;
77 spe_program_handle_t program;
78 char * program_name;
79 unsigned int booted;
80 unsigned int keepalive;
81 unsigned int entry;
82 int error_code;
83 void * argp;
84} spu_data_t;
85
86/* Private video driver data needed for Cell support */
87struct SDL_PrivateVideoData
88{
89 const char * const fb_dev_name; /* FB-device name */
90 int fb_dev_fd; /* Descriptor-handle for fb_dev_name */
91 uint8_t * frame_buffer; /* mmap'd access to fbdev */
92
93 /* SPE threading stuff */
94 spu_data_t * fb_thread_data;
95 spu_data_t * scaler_thread_data;
96 spu_data_t * converter_thread_data;
97
98 /* screeninfo (from linux/fb.h) */
99 struct fb_fix_screeninfo fb_finfo;
100 struct fb_var_screeninfo fb_vinfo;
101 struct fb_var_screeninfo fb_orig_vinfo;
102
103 /* screeninfo (from asm/ps3fb.h) */
104 struct ps3fb_ioctl_res res;
105
106 unsigned int double_buffering;
107 uint32_t real_width; // real width of screen
108 uint32_t real_height; // real height of screen
109
110 uint32_t s_fb_pixel_size; // 32: 4 24: 3 16: 2 15: 2
111 uint32_t fb_bits_per_pixel; // 32: 32 24: 24 16: 16 15: 15
112
113 uint32_t config_count;
114
115 uint32_t s_input_line_length; // precalculated: input_width * fb_pixel_size
116 uint32_t s_bounded_input_width; // width of input (bounded by writeable width)
117 uint32_t s_bounded_input_height;// height of input (bounded by writeable height)
118 uint32_t s_bounded_input_width_offset; // offset from the left side (used for centering)
119 uint32_t s_bounded_input_height_offset; // offset from the upper side (used for centering)
120 uint32_t s_writeable_width; // width of screen which is writeable
121 uint32_t s_writeable_height; // height of screen which is writeable
122
123 uint8_t * s_center[2]; // where to begin writing our image (centered?)
124 uint32_t s_center_index;
125
126 volatile void * s_pixels __attribute__((aligned(128)));
127
128 /* Framebuffer data */
129 volatile struct fb_writer_parms_t * fb_parms __attribute__((aligned(128)));
130};
131
132#define fb_dev_name (this->hidden->fb_dev_name)
133#define fb_dev_fd (this->hidden->fb_dev_fd)
134#define frame_buffer (this->hidden->frame_buffer)
135#define fb_thread_data (this->hidden->fb_thread_data)
136#define scaler_thread_data (this->hidden->scaler_thread_data)
137#define converter_thread_data (this->hidden->converter_thread_data)
138#define fb_parms (this->hidden->fb_parms)
139#define SDL_nummodes (this->hidden->SDL_nummodes)
140#define SDL_modelist (this->hidden->SDL_modelist)
141#define SDL_videomode (this->hidden->SDL_videomode)
142#define fb_finfo (this->hidden->fb_finfo)
143#define fb_vinfo (this->hidden->fb_vinfo)
144#define fb_orig_vinfo (this->hidden->fb_orig_vinfo)
145#define res (this->hidden->res)
146#define double_buffering (this->hidden->double_buffering)
147#define real_width (this->hidden->real_width)
148#define real_height (this->hidden->real_height)
149#define s_fb_pixel_size (this->hidden->s_fb_pixel_size)
150#define fb_bits_per_pixel (this->hidden->fb_bits_per_pixel)
151#define config_count (this->hidden->config_count)
152#define s_input_line_length (this->hidden->s_input_line_length)
153#define s_bounded_input_width (this->hidden->s_bounded_input_width)
154#define s_bounded_input_height (this->hidden->s_bounded_input_height)
155#define s_bounded_input_width_offset (this->hidden->s_bounded_input_width_offset)
156#define s_bounded_input_height_offset (this->hidden->s_bounded_input_height_offset)
157#define s_writeable_width (this->hidden->s_writeable_width)
158#define s_writeable_height (this->hidden->s_writeable_height)
159#define s_center (this->hidden->s_center)
160#define s_center_index (this->hidden->s_center_index)
161#define s_pixels (this->hidden->s_pixels)
162
163#endif /* _SDL_ps3video_h */
164
165
diff --git a/apps/plugins/sdl/src/video/ps3/SDL_ps3yuv.c b/apps/plugins/sdl/src/video/ps3/SDL_ps3yuv.c
deleted file mode 100644
index b1e17dae6d..0000000000
--- a/apps/plugins/sdl/src/video/ps3/SDL_ps3yuv.c
+++ /dev/null
@@ -1,340 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28#include "SDL_config.h"
29
30#include "SDL_video.h"
31#include "SDL_ps3video.h"
32#include "SDL_ps3yuv_c.h"
33#include "../SDL_yuvfuncs.h"
34#include "spulibs/spu_common.h"
35
36/* Stores the executable name */
37extern spe_program_handle_t yuv2rgb_spu;
38extern spe_program_handle_t bilin_scaler_spu;
39
40int SPE_Start(_THIS, spu_data_t * spe_data);
41int SPE_Stop(_THIS, spu_data_t * spe_data);
42int SPE_Boot(_THIS, spu_data_t * spe_data);
43int SPE_Shutdown(_THIS, spu_data_t * spe_data);
44int SPE_SendMsg(_THIS, spu_data_t * spe_data, unsigned int msg);
45int SPE_WaitForMsg(_THIS, spu_data_t * spe_data, unsigned int msg);
46void SPE_RunContext(void *thread_argp);
47
48
49/* The functions used to manipulate software video overlays */
50static struct private_yuvhwfuncs ps3_yuvfuncs = {
51 PS3_LockYUVOverlay,
52 PS3_UnlockYUVOverlay,
53 PS3_DisplayYUVOverlay,
54 PS3_FreeYUVOverlay
55};
56
57
58struct private_yuvhwdata {
59 SDL_Surface *display;
60 SDL_Surface *stretch;
61 volatile void * pixels __attribute__((aligned(128)));
62
63 /* These are just so we don't have to allocate them separately */
64 Uint16 pitches[3];
65 Uint8 * planes[3];
66
67 unsigned int scale;
68
69 /* Scaled YUV picture */
70 Uint8 * scaler_out __attribute__((aligned(128)));
71
72 /* YUV2RGB converter data */
73 volatile struct yuv2rgb_parms_t * converter_parms __attribute__((aligned(128)));
74
75 /* Scaler data */
76 volatile struct scale_parms_t * scaler_parms __attribute__((aligned(128)));
77
78 Uint8 locked;
79};
80
81
82SDL_Overlay *PS3_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display) {
83 /* Only RGB packed pixel conversion supported */
84 if ((display->format->BytesPerPixel != 2) &&
85 (display->format->BytesPerPixel != 3) &&
86 (display->format->BytesPerPixel != 4))
87 {
88 SDL_SetError ("Can't use YUV data on non 16/24/32 bit surfaces");
89 return NULL;
90 }
91
92 /* Double-check the requested format. We'll only support YV12 */
93 switch (format) {
94 case SDL_IYUV_OVERLAY:
95 case SDL_YV12_OVERLAY:
96 /* Supported YUV format */
97 break;
98 default:
99 SDL_SetError("Unsupported YUV format");
100 return NULL;
101 }
102
103 SDL_Overlay* overlay;
104 struct private_yuvhwdata* hwdata;
105
106 /* Create the overlay structure */
107 overlay = (SDL_Overlay *) SDL_calloc(1, sizeof(SDL_Overlay));
108 if (overlay == NULL) {
109 SDL_OutOfMemory();
110 return NULL;
111 }
112 SDL_memset(overlay, 0, (sizeof *overlay));
113
114 /* Set the basic attributes */
115 overlay->format = format;
116 overlay->w = width;
117 overlay->h = height;
118 overlay->hwdata = NULL;
119
120 /* Set up the PS3 YUV surface function structure */
121 overlay->hwfuncs = &ps3_yuvfuncs;
122
123 /* Create the pixel data and lookup tables */
124 hwdata = (struct private_yuvhwdata *) SDL_calloc(1, sizeof(struct private_yuvhwdata));
125 if (hwdata == NULL) {
126 SDL_OutOfMemory();
127 SDL_FreeYUVOverlay(overlay);
128 return NULL;
129 }
130 overlay->hwdata = hwdata;
131
132 hwdata->stretch = NULL;
133 hwdata->display = display;
134
135 /* Create SPU parms structure */
136 hwdata->converter_parms = (struct yuv2rgb_parms_t *) memalign(16, sizeof(struct yuv2rgb_parms_t));
137 hwdata->scaler_parms = (struct scale_parms_t *) memalign(16, sizeof(struct scale_parms_t));
138 if (hwdata->converter_parms == NULL || hwdata->scaler_parms == NULL) {
139 SDL_FreeYUVOverlay(overlay);
140 SDL_OutOfMemory();
141 return(NULL);
142 }
143
144 /* Set up the SPEs */
145 scaler_thread_data = (spu_data_t *) malloc(sizeof(spu_data_t));
146 converter_thread_data = (spu_data_t *) malloc(sizeof(spu_data_t));
147 if (converter_thread_data == NULL || scaler_thread_data == NULL) {
148 SDL_FreeYUVOverlay(overlay);
149 SDL_OutOfMemory();
150 return(NULL);
151 }
152
153 scaler_thread_data->program = bilin_scaler_spu;
154 scaler_thread_data->program_name = "bilin_scaler_spu";
155 scaler_thread_data->keepalive = 0;
156 scaler_thread_data->booted = 0;
157
158 converter_thread_data->program = yuv2rgb_spu;
159 converter_thread_data->program_name = "yuv2rgb_spu";
160 converter_thread_data->keepalive = 1;
161 converter_thread_data->booted = 0;
162
163 SPE_Start(this, converter_thread_data);
164
165 hwdata->pixels = (Uint8 *) memalign(16, width * height + ((width * height) >> 1));
166 if (hwdata->pixels == NULL) {
167 SDL_FreeYUVOverlay(overlay);
168 SDL_OutOfMemory();
169 return(NULL);
170 }
171
172 /* Find the pitch and offset values for the overlay */
173 overlay->pitches = hwdata->pitches;
174 overlay->pixels = hwdata->planes;
175 switch (format) {
176 case SDL_YV12_OVERLAY:
177 case SDL_IYUV_OVERLAY:
178 overlay->pitches[0] = overlay->w;
179 overlay->pitches[1] = overlay->pitches[0] / 2;
180 overlay->pitches[2] = overlay->pitches[0] / 2;
181 overlay->pixels[0] = (Uint8 *)hwdata->pixels;
182 overlay->pixels[1] = overlay->pixels[0] +
183 overlay->pitches[0] * overlay->h;
184 overlay->pixels[2] = overlay->pixels[1] +
185 overlay->pitches[1] * overlay->h / 2;
186 overlay->planes = 3;
187 break;
188 default:
189 /* We should never get here (caught above) */
190 break;
191 }
192
193 /* We're all done.. */
194 return overlay;
195}
196
197
198int PS3_LockYUVOverlay(_THIS, SDL_Overlay *overlay) {
199 if (overlay == NULL) {
200 return -1;
201 }
202 overlay->hwdata->locked = 1;
203
204 return 0;
205}
206
207
208void PS3_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay) {
209 if (overlay == NULL) {
210 return;
211 }
212 overlay->hwdata->locked = 0;
213
214 return;
215}
216
217
218int PS3_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst) {
219 if ((overlay == NULL) || (overlay->hwdata == NULL)) {
220 return -1;
221 }
222
223 Uint8 *lum, *Cr, *Cb;
224 struct private_yuvhwdata *hwdata;
225 SDL_Surface *display;
226
227 hwdata = overlay->hwdata;
228 display = hwdata->display;
229
230 /* Do we have to scale? */
231 if ((src->w != dst->w) || (src->h != dst->h) ) {
232 hwdata->scale = 1;
233 deprintf(1, "[PS3] We need to scale\n");
234 } else {
235 hwdata->scale = 0;
236 deprintf(1, "[PS3] No scaling\n");
237 }
238
239 /* Find out where the various portions of the image are */
240 switch (overlay->format) {
241 case SDL_YV12_OVERLAY:
242 lum = (Uint8 *)overlay->pixels[0];
243 Cr = (Uint8 *)overlay->pixels[1];
244 Cb = (Uint8 *)overlay->pixels[2];
245 break;
246 case SDL_IYUV_OVERLAY:
247 lum = (Uint8 *)overlay->pixels[0];
248 Cr = (Uint8 *)overlay->pixels[2];
249 Cb = (Uint8 *)overlay->pixels[1];
250 break;
251 default:
252 SDL_SetError("Unsupported YUV format in blit");
253 return -1;
254 }
255
256 if (hwdata->scale) {
257 /* Alloc mem for scaled YUV picture */
258 hwdata->scaler_out = (Uint8 *) memalign(16, dst->w * dst->h + ((dst->w * dst->h) >> 1));
259 if (hwdata->scaler_out == NULL) {
260 SDL_FreeYUVOverlay(overlay);
261 SDL_OutOfMemory();
262 return -1;
263 }
264
265 /* Set parms for scaling */
266 hwdata->scaler_parms->src_pixel_width = src->w;
267 hwdata->scaler_parms->src_pixel_height = src->h;
268 hwdata->scaler_parms->dst_pixel_width = dst->w;
269 hwdata->scaler_parms->dst_pixel_height = dst->h;
270 hwdata->scaler_parms->y_plane = lum;
271 hwdata->scaler_parms->v_plane = Cr;
272 hwdata->scaler_parms->u_plane = Cb;
273 hwdata->scaler_parms->dstBuffer = hwdata->scaler_out;
274 scaler_thread_data->argp = (void *)hwdata->scaler_parms;
275
276 /* Scale the YUV overlay to given size */
277 SPE_Start(this, scaler_thread_data);
278 SPE_Stop(this, scaler_thread_data);
279
280 /* Set parms for converting after scaling */
281 hwdata->converter_parms->y_plane = hwdata->scaler_out;
282 hwdata->converter_parms->v_plane = hwdata->scaler_out + dst->w * dst->h;
283 hwdata->converter_parms->u_plane = hwdata->scaler_out + dst->w * dst->h + ((dst->w * dst->h) >> 2);
284 } else {
285 /* Set parms for converting */
286 hwdata->converter_parms->y_plane = lum;
287 hwdata->converter_parms->v_plane = Cr;
288 hwdata->converter_parms->u_plane = Cb;
289 }
290
291 hwdata->converter_parms->src_pixel_width = dst->w;
292 hwdata->converter_parms->src_pixel_height = dst->h;
293 hwdata->converter_parms->dstBuffer = (Uint8 *) s_pixels;
294 converter_thread_data->argp = (void *)hwdata->converter_parms;
295
296 /* Convert YUV overlay to RGB */
297 SPE_SendMsg(this, converter_thread_data, SPU_START);
298 SPE_SendMsg(this, converter_thread_data, (unsigned int)converter_thread_data->argp);
299
300 /* Centering */
301 s_bounded_input_width = dst->w;
302 s_bounded_input_height = dst->h;
303
304 /* UpdateRects() will do the rest.. */
305 SDL_UpdateRects(display, 1, dst);
306
307 if (hwdata->scale)
308 SDL_free((void *)hwdata->scaler_out);
309
310 return 0;
311}
312
313
314void PS3_FreeYUVOverlay(_THIS, SDL_Overlay *overlay) {
315 if (overlay == NULL) {
316 return;
317 }
318
319 if (overlay->hwdata == NULL) {
320 return;
321 }
322
323 struct private_yuvhwdata * hwdata;
324 hwdata = overlay->hwdata;
325
326 if (scaler_thread_data)
327 SDL_free(scaler_thread_data);
328 if (converter_thread_data) {
329 SPE_Shutdown(this, converter_thread_data);
330 SDL_free(converter_thread_data);
331 }
332
333 if (hwdata) {
334 if (hwdata->pixels)
335 SDL_free((void *)hwdata->pixels);
336 SDL_free(hwdata);
337 }
338 return;
339}
340
diff --git a/apps/plugins/sdl/src/video/ps3/SDL_ps3yuv_c.h b/apps/plugins/sdl/src/video/ps3/SDL_ps3yuv_c.h
deleted file mode 100644
index 49f9d70953..0000000000
--- a/apps/plugins/sdl/src/video/ps3/SDL_ps3yuv_c.h
+++ /dev/null
@@ -1,44 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28#include "SDL_config.h"
29
30#ifndef _SDL_ps3yuv_h
31#define _SDL_ps3yuv_h
32
33/* This is the PS3 implementation of YUV video overlays */
34
35#include "SDL_video.h"
36
37extern SDL_Overlay *PS3_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display);
38extern int PS3_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst);
39extern int PS3_LockYUVOverlay(_THIS, SDL_Overlay *overlay);
40extern void PS3_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay);
41extern void PS3_FreeYUVOverlay(_THIS, SDL_Overlay *overlay);
42
43#endif /* _SDL_ps3yuv_h */
44
diff --git a/apps/plugins/sdl/src/video/ps3/spulibs/Makefile b/apps/plugins/sdl/src/video/ps3/spulibs/Makefile
deleted file mode 100644
index dc580d9436..0000000000
--- a/apps/plugins/sdl/src/video/ps3/spulibs/Makefile
+++ /dev/null
@@ -1,83 +0,0 @@
1# This Makefile is for building the CELL BE SPU libs
2# libfb_writer_spu.so, libyuv2rgb_spu.so, libbilin_scaler_spu.so
3
4# Toolchain
5SPU_GCC=/usr/bin/spu-gcc
6PPU_GCC=/usr/bin/gcc
7PPU_EMBEDSPU=/usr/bin/embedspu
8PPU_AR=/usr/bin/ar
9PPU_LD=/usr/bin/ld
10INSTALL=/usr/bin/install
11
12SPU_CFLAGS=-W -Wall -Winline -Wno-main -I. -I /usr/spu/include -I /opt/cell/sdk/usr/spu/include -finline-limit=10000 -Winline -ftree-vectorize -funroll-loops -fmodulo-sched -ffast-math -fPIC -O2
13
14# Usually /usr/lib, depending on your distribution
15PREFIX=/usr/lib
16
17
18all: libfb_writer_spu.a libfb_writer_spu.so \
19 libyuv2rgb_spu.so libyuv2rgb_spu.a \
20 libbilin_scaler_spu.so libbilin_scaler_spu.a
21
22
23# fb_writer
24fb_writer_spu-embed.o: fb_writer.c spu_common.h
25 $(SPU_GCC) $(SPU_CFLAGS) -o fb_writer_spu fb_writer.c -lm
26 $(PPU_EMBEDSPU) -m32 fb_writer_spu fb_writer_spu fb_writer_spu-embed.o
27
28libfb_writer_spu.so: fb_writer_spu-embed.o
29 $(PPU_LD) -o libfb_writer_spu.so -shared -soname=libfb_writer_spu.so fb_writer_spu-embed.o
30
31libfb_writer_spu.a: fb_writer_spu-embed.o
32 $(PPU_AR) -qcs libfb_writer_spu.a fb_writer_spu-embed.o
33
34
35# yuv2rgb_converter
36yuv2rgb_spu-embed.o: yuv2rgb_converter.c spu_common.h
37 $(SPU_GCC) $(SPU_CFLAGS) -o yuv2rgb_spu yuv2rgb_converter.c -lm
38 $(PPU_EMBEDSPU) -m32 yuv2rgb_spu yuv2rgb_spu yuv2rgb_spu-embed.o
39
40libyuv2rgb_spu.a: yuv2rgb_spu-embed.o
41 $(PPU_AR) -qcs libyuv2rgb_spu.a yuv2rgb_spu-embed.o
42
43libyuv2rgb_spu.so: yuv2rgb_spu-embed.o
44 $(PPU_LD) -o libyuv2rgb_spu.so -shared -soname=libyuv2rgb_spu.so yuv2rgb_spu-embed.o
45
46
47# bilin_scaler
48bilin_scaler_spu-embed.o: bilin_scaler.c spu_common.h
49 $(SPU_GCC) $(SPU_CFLAGS) -o bilin_scaler_spu bilin_scaler.c -lm
50 $(PPU_EMBEDSPU) -m32 bilin_scaler_spu bilin_scaler_spu bilin_scaler_spu-embed.o
51
52libbilin_scaler_spu.a: bilin_scaler_spu-embed.o
53 $(PPU_AR) -qcs libbilin_scaler_spu.a bilin_scaler_spu-embed.o
54
55libbilin_scaler_spu.so: bilin_scaler_spu-embed.o
56 $(PPU_LD) -o libbilin_scaler_spu.so -shared -soname=libbilin_scaler_spu.so bilin_scaler_spu-embed.o
57
58install: libfb_writer_spu.a libfb_writer_spu.so \
59 libyuv2rgb_spu.so libyuv2rgb_spu.a \
60 libbilin_scaler_spu.so libbilin_scaler_spu.a
61 $(INSTALL) -c -m 0755 libfb_writer_spu.so $(PREFIX)/.
62 $(INSTALL) -c -m 0655 libfb_writer_spu.a $(PREFIX)/.
63 $(INSTALL) -c -m 0755 libyuv2rgb_spu.so $(PREFIX)/.
64 $(INSTALL) -c -m 0655 libyuv2rgb_spu.a $(PREFIX)/.
65 $(INSTALL) -c -m 0755 libbilin_scaler_spu.so $(PREFIX)/.
66 $(INSTALL) -c -m 0655 libbilin_scaler_spu.a $(PREFIX)/.
67
68
69uninstall: $(PREFIX)/libfb_writer_spu.so $(PREFIX)/libfb_writer_spu.a \
70 $(PREFIX)/libyuv2rgb_spu.so $(PREFIX)/libyuv2rgb_spu.a \
71 $(PREFIX)/libbilin_scaler_spu.so $(PREFIX)/libbilin_scaler_spu.a
72 rm -f $(PREFIX)/libfb_writer_spu.a
73 rm -f $(PREFIX)/libfb_writer_spu.so
74 rm -f $(PREFIX)/libyuv2rgb_spu.so
75 rm -f $(PREFIX)/libyuv2rgb_spu.a
76 rm -f $(PREFIX)/libbilin_scaler_spu.so
77 rm -f $(PREFIX)/libbilin_scaler_spu.a
78
79
80clean:
81 rm -f bilin_scaler_spu-embed.o libbilin_scaler_spu.so libbilin_scaler_spu.a bilin_scaler_spu
82 rm -f yuv2rgb_spu-embed.o libyuv2rgb_spu.so libyuv2rgb_spu.a yuv2rgb_spu
83 rm -f fb_writer_spu-embed.o libfb_writer_spu.so libfb_writer_spu.a fb_writer_spu
diff --git a/apps/plugins/sdl/src/video/ps3/spulibs/bilin_scaler.c b/apps/plugins/sdl/src/video/ps3/spulibs/bilin_scaler.c
deleted file mode 100644
index be9b5c6e8d..0000000000
--- a/apps/plugins/sdl/src/video/ps3/spulibs/bilin_scaler.c
+++ /dev/null
@@ -1,2050 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28#include "spu_common.h"
29
30#include <spu_intrinsics.h>
31#include <spu_mfcio.h>
32
33// Debugging
34//#define DEBUG
35
36#ifdef DEBUG
37#define deprintf(fmt, args... ) \
38 fprintf( stdout, fmt, ##args ); \
39 fflush( stdout );
40#else
41#define deprintf( fmt, args... )
42#endif
43
44struct scale_parms_t parms __attribute__((aligned(128)));
45
46/* A maximum of 8 lines Y, therefore 4 lines V, 4 lines U are stored
47 * there might be the need to retrieve misaligned data, adjust
48 * incoming v and u plane to be able to handle this (add 128)
49 */
50unsigned char y_plane[2][(MAX_HDTV_WIDTH+128)*4] __attribute__((aligned(128)));
51unsigned char v_plane[2][(MAX_HDTV_WIDTH+128)*2] __attribute__((aligned(128)));
52unsigned char u_plane[2][(MAX_HDTV_WIDTH+128)*2] __attribute__((aligned(128)));
53
54/* temp-buffer for scaling: 4 lines Y, therefore 2 lines V, 2 lines U */
55unsigned char scaled_y_plane[2][MAX_HDTV_WIDTH*2] __attribute__((aligned(128)));
56unsigned char scaled_v_plane[2][MAX_HDTV_WIDTH/2] __attribute__((aligned(128)));
57unsigned char scaled_u_plane[2][MAX_HDTV_WIDTH/2] __attribute__((aligned(128)));
58
59/* some vectors needed by the float to int conversion */
60static const vector float vec_255 = { 255.0f, 255.0f, 255.0f, 255.0f };
61static const vector float vec_0_1 = { 0.1f, 0.1f, 0.1f, 0.1f };
62
63void bilinear_scale_line_w8(unsigned char* src, unsigned char* dst_, unsigned int dst_width, vector float vf_x_scale, vector float vf_NSweight, unsigned int src_linestride);
64void bilinear_scale_line_w16(unsigned char* src, unsigned char* dst_, unsigned int dst_width, vector float vf_x_scale, vector float vf_NSweight, unsigned int src_linestride);
65
66void scale_srcw16_dstw16();
67void scale_srcw16_dstw32();
68void scale_srcw32_dstw16();
69void scale_srcw32_dstw32();
70
71int main( unsigned long long spe_id __attribute__((unused)), unsigned long long argp )
72{
73 deprintf("[SPU] bilin_scaler_spu is up... (on SPE #%llu)\n", spe_id);
74 /* DMA transfer for the input parameters */
75 spu_mfcdma32(&parms, (unsigned int)argp, sizeof(struct scale_parms_t), TAG_INIT, MFC_GET_CMD);
76 DMA_WAIT_TAG(TAG_INIT);
77
78 deprintf("[SPU] Scale %ux%u to %ux%u\n", parms.src_pixel_width, parms.src_pixel_height,
79 parms.dst_pixel_width, parms.dst_pixel_height);
80
81 if(parms.src_pixel_width & 0x1f) {
82 if(parms.dst_pixel_width & 0x1F) {
83 deprintf("[SPU] Using scale_srcw16_dstw16\n");
84 scale_srcw16_dstw16();
85 } else {
86 deprintf("[SPU] Using scale_srcw16_dstw32\n");
87 scale_srcw16_dstw32();
88 }
89 } else {
90 if(parms.dst_pixel_width & 0x1F) {
91 deprintf("[SPU] Using scale_srcw32_dstw16\n");
92 scale_srcw32_dstw16();
93 } else {
94 deprintf("[SPU] Using scale_srcw32_dstw32\n");
95 scale_srcw32_dstw32();
96 }
97 }
98 deprintf("[SPU] bilin_scaler_spu... done!\n");
99
100 return 0;
101}
102
103
104/*
105 * vfloat_to_vuint()
106 *
107 * converts a float vector to an unsinged int vector using saturated
108 * arithmetic
109 *
110 * @param vec_s float vector for conversion
111 * @returns converted unsigned int vector
112 */
113inline static vector unsigned int vfloat_to_vuint(vector float vec_s) {
114 vector unsigned int select_1 = spu_cmpgt(vec_0_1, vec_s);
115 vec_s = spu_sel(vec_s, vec_0_1, select_1);
116
117 vector unsigned int select_2 = spu_cmpgt(vec_s, vec_255);
118 vec_s = spu_sel(vec_s, vec_255, select_2);
119 return spu_convtu(vec_s,0);
120}
121
122
123/*
124 * scale_srcw16_dstw16()
125 *
126 * processes an input image of width 16
127 * scaling is done to a width 16
128 * result stored in RAM
129 */
130void scale_srcw16_dstw16() {
131 // extract parameters
132 unsigned char* dst_addr = (unsigned char *)parms.dstBuffer;
133
134 unsigned int src_width = parms.src_pixel_width;
135 unsigned int src_height = parms.src_pixel_height;
136 unsigned int dst_width = parms.dst_pixel_width;
137 unsigned int dst_height = parms.dst_pixel_height;
138
139 // YVU
140 unsigned int src_linestride_y = src_width;
141 unsigned int src_dbl_linestride_y = src_width<<1;
142 unsigned int src_linestride_vu = src_width>>1;
143 unsigned int src_dbl_linestride_vu = src_width;
144
145 // scaled YVU
146 unsigned int scaled_src_linestride_y = dst_width;
147
148 // ram addresses
149 unsigned char* src_addr_y = parms.y_plane;
150 unsigned char* src_addr_v = parms.v_plane;
151 unsigned char* src_addr_u = parms.u_plane;
152
153 // for handling misalignment, addresses are precalculated
154 unsigned char* precalc_src_addr_v = src_addr_v;
155 unsigned char* precalc_src_addr_u = src_addr_u;
156
157 unsigned int dst_picture_size = dst_width*dst_height;
158
159 // Sizes for destination
160 unsigned int dst_dbl_linestride_y = dst_width<<1;
161 unsigned int dst_dbl_linestride_vu = dst_width>>1;
162
163 // Perform address calculation for Y, V and U in main memory with dst_addr as base
164 unsigned char* dst_addr_main_memory_y = dst_addr;
165 unsigned char* dst_addr_main_memory_v = dst_addr + dst_picture_size;
166 unsigned char* dst_addr_main_memory_u = dst_addr_main_memory_v +(dst_picture_size>>2);
167
168 // calculate scale factors
169 vector float vf_x_scale = spu_splats( (float)src_width/(float)dst_width );
170 float y_scale = (float)src_height/(float)dst_height;
171
172 // double buffered processing
173 // buffer switching
174 unsigned int curr_src_idx = 0;
175 unsigned int curr_dst_idx = 0;
176 unsigned int next_src_idx, next_dst_idx;
177
178 // 2 lines y as output, upper and lowerline
179 unsigned int curr_interpl_y_upper = 0;
180 unsigned int next_interpl_y_upper;
181 unsigned int curr_interpl_y_lower, next_interpl_y_lower;
182 // only 1 line v/u output, both planes have the same dimension
183 unsigned int curr_interpl_vu = 0;
184 unsigned int next_interpl_vu;
185
186 // weights, calculated in every loop iteration
187 vector float vf_curr_NSweight_y_upper = { 0.0f, 0.0f, 0.0f, 0.0f };
188 vector float vf_next_NSweight_y_upper;
189 vector float vf_curr_NSweight_y_lower, vf_next_NSweight_y_lower;
190 vector float vf_curr_NSweight_vu = { 0.0f, 0.0f, 0.0f, 0.0f };
191 vector float vf_next_NSweight_vu;
192
193 // line indices for the src picture
194 float curr_src_y_upper = 0.0f, next_src_y_upper;
195 float curr_src_y_lower, next_src_y_lower;
196 float curr_src_vu = 0.0f, next_src_vu;
197
198 // line indices for the dst picture
199 unsigned int dst_y=0, dst_vu=0;
200
201 // offset for the v and u plane to handle misalignement
202 unsigned int curr_lsoff_v = 0, next_lsoff_v;
203 unsigned int curr_lsoff_u = 0, next_lsoff_u;
204
205 // calculate lower line indices
206 curr_src_y_lower = ((float)curr_interpl_y_upper+1)*y_scale;
207 curr_interpl_y_lower = (unsigned int)curr_src_y_lower;
208 // lower line weight
209 vf_curr_NSweight_y_lower = spu_splats( curr_src_y_lower-(float)curr_interpl_y_lower );
210
211
212 // start partially double buffered processing
213 // get initial data, 2 sets of y, 1 set v, 1 set u
214 mfc_get( y_plane[curr_src_idx], (unsigned int) src_addr_y, src_dbl_linestride_y, RETR_BUF, 0, 0 );
215 mfc_get( y_plane[curr_src_idx]+src_dbl_linestride_y,
216 (unsigned int) src_addr_y+(curr_interpl_y_lower*src_linestride_y),
217 src_dbl_linestride_y,
218 RETR_BUF,
219 0, 0 );
220 mfc_get( v_plane[curr_src_idx], (unsigned int) src_addr_v, src_dbl_linestride_vu, RETR_BUF, 0, 0 );
221 mfc_get( u_plane[curr_src_idx], (unsigned int) src_addr_u, src_dbl_linestride_vu, RETR_BUF, 0, 0 );
222
223 /* iteration loop
224 * within each iteration 4 lines y, 2 lines v, 2 lines u are retrieved
225 * the scaled output is 2 lines y, 1 line v, 1 line u
226 * the yuv2rgb-converted output is stored to RAM
227 */
228 for( dst_vu=0; dst_vu<(dst_height>>1)-1; dst_vu++ ) {
229 dst_y = dst_vu<<1;
230
231 // calculate next indices
232 next_src_vu = ((float)dst_vu+1)*y_scale;
233 next_src_y_upper = ((float)dst_y+2)*y_scale;
234 next_src_y_lower = ((float)dst_y+3)*y_scale;
235
236 next_interpl_vu = (unsigned int) next_src_vu;
237 next_interpl_y_upper = (unsigned int) next_src_y_upper;
238 next_interpl_y_lower = (unsigned int) next_src_y_lower;
239
240 // calculate weight NORTH-SOUTH
241 vf_next_NSweight_vu = spu_splats( next_src_vu-(float)next_interpl_vu );
242 vf_next_NSweight_y_upper = spu_splats( next_src_y_upper-(float)next_interpl_y_upper );
243 vf_next_NSweight_y_lower = spu_splats( next_src_y_lower-(float)next_interpl_y_lower );
244
245 // get next lines
246 next_src_idx = curr_src_idx^1;
247 next_dst_idx = curr_dst_idx^1;
248
249 // 4 lines y
250 mfc_get( y_plane[next_src_idx],
251 (unsigned int) src_addr_y+(next_interpl_y_upper*src_linestride_y),
252 src_dbl_linestride_y,
253 RETR_BUF+next_src_idx,
254 0, 0 );
255 mfc_get( y_plane[next_src_idx]+src_dbl_linestride_y,
256 (unsigned int) src_addr_y+(next_interpl_y_lower*src_linestride_y),
257 src_dbl_linestride_y,
258 RETR_BUF+next_src_idx,
259 0, 0 );
260
261 // 2 lines v
262 precalc_src_addr_v = src_addr_v+(next_interpl_vu*src_linestride_vu);
263 next_lsoff_v = ((unsigned int)precalc_src_addr_v)&0x0F;
264 mfc_get( v_plane[next_src_idx],
265 ((unsigned int) precalc_src_addr_v)&0xFFFFFFF0,
266 src_dbl_linestride_vu+(next_lsoff_v<<1),
267 RETR_BUF+next_src_idx,
268 0, 0 );
269 // 2 lines u
270 precalc_src_addr_u = src_addr_u+(next_interpl_vu*src_linestride_vu);
271 next_lsoff_u = ((unsigned int)precalc_src_addr_u)&0x0F;
272 mfc_get( u_plane[next_src_idx],
273 ((unsigned int) precalc_src_addr_u)&0xFFFFFFF0,
274 src_dbl_linestride_vu+(next_lsoff_v<<1),
275 RETR_BUF+next_src_idx,
276 0, 0 );
277
278 DMA_WAIT_TAG( (RETR_BUF+curr_src_idx) );
279
280 // scaling
281 // work line y_upper
282 bilinear_scale_line_w16( y_plane[curr_src_idx],
283 scaled_y_plane[curr_src_idx],
284 dst_width,
285 vf_x_scale,
286 vf_curr_NSweight_y_upper,
287 src_linestride_y );
288 // work line y_lower
289 bilinear_scale_line_w16( y_plane[curr_src_idx]+src_dbl_linestride_y,
290 scaled_y_plane[curr_src_idx]+scaled_src_linestride_y,
291 dst_width,
292 vf_x_scale,
293 vf_curr_NSweight_y_lower,
294 src_linestride_y );
295 // work line v
296 bilinear_scale_line_w8( v_plane[curr_src_idx]+curr_lsoff_v,
297 scaled_v_plane[curr_src_idx],
298 dst_width>>1,
299 vf_x_scale,
300 vf_curr_NSweight_vu,
301 src_linestride_vu );
302 // work line u
303 bilinear_scale_line_w8( u_plane[curr_src_idx]+curr_lsoff_u,
304 scaled_u_plane[curr_src_idx],
305 dst_width>>1,
306 vf_x_scale,
307 vf_curr_NSweight_vu,
308 src_linestride_vu );
309
310
311 // Store the result back to main memory into a destination buffer in YUV format
312 //---------------------------------------------------------------------------------------------
313 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
314
315 // Perform three DMA transfers to 3 different locations in the main memory!
316 // dst_width: Pixel width of destination image
317 // dst_addr: Destination address in main memory
318 // dst_vu: Counter which is incremented one by one
319 // dst_y: Counter which is twice larger than dst_vu (dst_y = 2*dst_vu)
320 mfc_put( scaled_y_plane[curr_src_idx], // What from local store (addr)
321 (unsigned int)dst_addr_main_memory_y + (dst_vu*dst_dbl_linestride_y), // Destination in main memory (addr)
322 dst_dbl_linestride_y, // Two Y lines (depending on the widht of the destination resolution)
323 STR_BUF+curr_dst_idx, // Tag
324 0, 0 );
325
326 mfc_put( scaled_v_plane[curr_src_idx], // What from local store (addr)
327 (unsigned int)dst_addr_main_memory_v + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
328 dst_dbl_linestride_vu, // Two V lines (depending on the widht of the destination resolution)
329 STR_BUF+curr_dst_idx, // Tag
330 0, 0 );
331
332 mfc_put( scaled_u_plane[curr_src_idx], // What from local store (addr)
333 (unsigned int)dst_addr_main_memory_u + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
334 dst_dbl_linestride_vu, // Two U lines (depending on the widht of the destination resolution)
335 STR_BUF+curr_dst_idx, // Tag
336 0, 0 );
337 //---------------------------------------------------------------------------------------------
338
339
340 // update for next cycle
341 curr_src_idx = next_src_idx;
342 curr_dst_idx = next_dst_idx;
343
344 curr_interpl_y_upper = next_interpl_y_upper;
345 curr_interpl_y_lower = next_interpl_y_lower;
346 curr_interpl_vu = next_interpl_vu;
347
348 vf_curr_NSweight_y_upper = vf_curr_NSweight_y_upper;
349 vf_curr_NSweight_y_lower = vf_curr_NSweight_y_lower;
350 vf_curr_NSweight_vu = vf_next_NSweight_vu;
351
352 curr_src_y_upper = next_src_y_upper;
353 curr_src_y_lower = next_src_y_lower;
354 curr_src_vu = next_src_vu;
355
356 curr_lsoff_v = next_lsoff_v;
357 curr_lsoff_u = next_lsoff_u;
358 }
359
360
361
362 DMA_WAIT_TAG( (RETR_BUF+curr_src_idx) );
363
364 // scaling
365 // work line y_upper
366 bilinear_scale_line_w16( y_plane[curr_src_idx],
367 scaled_y_plane[curr_src_idx],
368 dst_width,
369 vf_x_scale,
370 vf_curr_NSweight_y_upper,
371 src_linestride_y );
372 // work line y_lower
373 bilinear_scale_line_w16( y_plane[curr_src_idx]+src_dbl_linestride_y,
374 scaled_y_plane[curr_src_idx]+scaled_src_linestride_y,
375 dst_width,
376 vf_x_scale,
377 vf_curr_NSweight_y_lower,
378 src_linestride_y );
379 // work line v
380 bilinear_scale_line_w8( v_plane[curr_src_idx]+curr_lsoff_v,
381 scaled_v_plane[curr_src_idx],
382 dst_width>>1,
383 vf_x_scale,
384 vf_curr_NSweight_vu,
385 src_linestride_vu );
386 // work line u
387 bilinear_scale_line_w8( u_plane[curr_src_idx]+curr_lsoff_u,
388 scaled_u_plane[curr_src_idx],
389 dst_width>>1,
390 vf_x_scale,
391 vf_curr_NSweight_vu,
392 src_linestride_vu );
393
394
395 // Store the result back to main memory into a destination buffer in YUV format
396 //---------------------------------------------------------------------------------------------
397 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
398
399 // Perform three DMA transfers to 3 different locations in the main memory!
400 // dst_width: Pixel width of destination image
401 // dst_addr: Destination address in main memory
402 // dst_vu: Counter which is incremented one by one
403 // dst_y: Counter which is twice larger than dst_vu (dst_y = 2*dst_vu)
404 mfc_put( scaled_y_plane[curr_src_idx], // What from local store (addr)
405 (unsigned int)dst_addr_main_memory_y + (dst_vu*dst_dbl_linestride_y), // Destination in main memory (addr)
406 dst_dbl_linestride_y, // Two Y lines (depending on the widht of the destination resolution)
407 STR_BUF+curr_dst_idx, // Tag
408 0, 0 );
409
410 mfc_put( scaled_v_plane[curr_src_idx], // What from local store (addr)
411 (unsigned int)dst_addr_main_memory_v + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
412 dst_dbl_linestride_vu, // Two V lines (depending on the widht of the destination resolution)
413 STR_BUF+curr_dst_idx, // Tag
414 0, 0 );
415
416 mfc_put( scaled_u_plane[curr_src_idx], // What from local store (addr)
417 (unsigned int)dst_addr_main_memory_u + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
418 dst_dbl_linestride_vu, // Two U lines (depending on the widht of the destination resolution)
419 STR_BUF+curr_dst_idx, // Tag
420 0, 0 );
421
422 // wait for completion
423 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
424 //---------------------------------------------------------------------------------------------
425}
426
427
428/*
429 * scale_srcw16_dstw32()
430 *
431 * processes an input image of width 16
432 * scaling is done to a width 32
433 * yuv2rgb conversion on a width of 32
434 * result stored in RAM
435 */
436void scale_srcw16_dstw32() {
437 // extract parameters
438 unsigned char* dst_addr = (unsigned char *)parms.dstBuffer;
439
440 unsigned int src_width = parms.src_pixel_width;
441 unsigned int src_height = parms.src_pixel_height;
442 unsigned int dst_width = parms.dst_pixel_width;
443 unsigned int dst_height = parms.dst_pixel_height;
444
445 // YVU
446 unsigned int src_linestride_y = src_width;
447 unsigned int src_dbl_linestride_y = src_width<<1;
448 unsigned int src_linestride_vu = src_width>>1;
449 unsigned int src_dbl_linestride_vu = src_width;
450 // scaled YVU
451 unsigned int scaled_src_linestride_y = dst_width;
452
453 // ram addresses
454 unsigned char* src_addr_y = parms.y_plane;
455 unsigned char* src_addr_v = parms.v_plane;
456 unsigned char* src_addr_u = parms.u_plane;
457
458 unsigned int dst_picture_size = dst_width*dst_height;
459
460 // Sizes for destination
461 unsigned int dst_dbl_linestride_y = dst_width<<1;
462 unsigned int dst_dbl_linestride_vu = dst_width>>1;
463
464 // Perform address calculation for Y, V and U in main memory with dst_addr as base
465 unsigned char* dst_addr_main_memory_y = dst_addr;
466 unsigned char* dst_addr_main_memory_v = dst_addr + dst_picture_size;
467 unsigned char* dst_addr_main_memory_u = dst_addr_main_memory_v +(dst_picture_size>>2);
468
469
470 // for handling misalignment, addresses are precalculated
471 unsigned char* precalc_src_addr_v = src_addr_v;
472 unsigned char* precalc_src_addr_u = src_addr_u;
473
474 // calculate scale factors
475 vector float vf_x_scale = spu_splats( (float)src_width/(float)dst_width );
476 float y_scale = (float)src_height/(float)dst_height;
477
478 // double buffered processing
479 // buffer switching
480 unsigned int curr_src_idx = 0;
481 unsigned int curr_dst_idx = 0;
482 unsigned int next_src_idx, next_dst_idx;
483
484 // 2 lines y as output, upper and lowerline
485 unsigned int curr_interpl_y_upper = 0;
486 unsigned int next_interpl_y_upper;
487 unsigned int curr_interpl_y_lower, next_interpl_y_lower;
488 // only 1 line v/u output, both planes have the same dimension
489 unsigned int curr_interpl_vu = 0;
490 unsigned int next_interpl_vu;
491
492 // weights, calculated in every loop iteration
493 vector float vf_curr_NSweight_y_upper = { 0.0f, 0.0f, 0.0f, 0.0f };
494 vector float vf_next_NSweight_y_upper;
495 vector float vf_curr_NSweight_y_lower, vf_next_NSweight_y_lower;
496 vector float vf_curr_NSweight_vu = { 0.0f, 0.0f, 0.0f, 0.0f };
497 vector float vf_next_NSweight_vu;
498
499 // line indices for the src picture
500 float curr_src_y_upper = 0.0f, next_src_y_upper;
501 float curr_src_y_lower, next_src_y_lower;
502 float curr_src_vu = 0.0f, next_src_vu;
503
504 // line indices for the dst picture
505 unsigned int dst_y=0, dst_vu=0;
506
507 // offset for the v and u plane to handle misalignement
508 unsigned int curr_lsoff_v = 0, next_lsoff_v;
509 unsigned int curr_lsoff_u = 0, next_lsoff_u;
510
511 // calculate lower line idices
512 curr_src_y_lower = ((float)curr_interpl_y_upper+1)*y_scale;
513 curr_interpl_y_lower = (unsigned int)curr_src_y_lower;
514 // lower line weight
515 vf_curr_NSweight_y_lower = spu_splats( curr_src_y_lower-(float)curr_interpl_y_lower );
516
517
518 // start partially double buffered processing
519 // get initial data, 2 sets of y, 1 set v, 1 set u
520 mfc_get( y_plane[curr_src_idx], (unsigned int) src_addr_y, src_dbl_linestride_y, RETR_BUF, 0, 0 );
521 mfc_get( y_plane[curr_src_idx]+src_dbl_linestride_y,
522 (unsigned int) src_addr_y+(curr_interpl_y_lower*src_linestride_y),
523 src_dbl_linestride_y,
524 RETR_BUF,
525 0, 0 );
526 mfc_get( v_plane[curr_src_idx], (unsigned int) src_addr_v, src_dbl_linestride_vu, RETR_BUF, 0, 0 );
527 mfc_get( u_plane[curr_src_idx], (unsigned int) src_addr_u, src_dbl_linestride_vu, RETR_BUF, 0, 0 );
528
529 // iteration loop
530 // within each iteration 4 lines y, 2 lines v, 2 lines u are retrieved
531 // the scaled output is 2 lines y, 1 line v, 1 line u
532 // the yuv2rgb-converted output is stored to RAM
533 for( dst_vu=0; dst_vu<(dst_height>>1)-1; dst_vu++ ) {
534 dst_y = dst_vu<<1;
535
536 // calculate next indices
537 next_src_vu = ((float)dst_vu+1)*y_scale;
538 next_src_y_upper = ((float)dst_y+2)*y_scale;
539 next_src_y_lower = ((float)dst_y+3)*y_scale;
540
541 next_interpl_vu = (unsigned int) next_src_vu;
542 next_interpl_y_upper = (unsigned int) next_src_y_upper;
543 next_interpl_y_lower = (unsigned int) next_src_y_lower;
544
545 // calculate weight NORTH-SOUTH
546 vf_next_NSweight_vu = spu_splats( next_src_vu-(float)next_interpl_vu );
547 vf_next_NSweight_y_upper = spu_splats( next_src_y_upper-(float)next_interpl_y_upper );
548 vf_next_NSweight_y_lower = spu_splats( next_src_y_lower-(float)next_interpl_y_lower );
549
550 // get next lines
551 next_src_idx = curr_src_idx^1;
552 next_dst_idx = curr_dst_idx^1;
553
554 // 4 lines y
555 mfc_get( y_plane[next_src_idx],
556 (unsigned int) src_addr_y+(next_interpl_y_upper*src_linestride_y),
557 src_dbl_linestride_y,
558 RETR_BUF+next_src_idx,
559 0, 0 );
560 mfc_get( y_plane[next_src_idx]+src_dbl_linestride_y,
561 (unsigned int) src_addr_y+(next_interpl_y_lower*src_linestride_y),
562 src_dbl_linestride_y,
563 RETR_BUF+next_src_idx,
564 0, 0 );
565
566 // 2 lines v
567 precalc_src_addr_v = src_addr_v+(next_interpl_vu*src_linestride_vu);
568 next_lsoff_v = ((unsigned int)precalc_src_addr_v)&0x0F;
569 mfc_get( v_plane[next_src_idx],
570 ((unsigned int) precalc_src_addr_v)&0xFFFFFFF0,
571 src_dbl_linestride_vu+(next_lsoff_v<<1),
572 RETR_BUF+next_src_idx,
573 0, 0 );
574 // 2 lines u
575 precalc_src_addr_u = src_addr_u+(next_interpl_vu*src_linestride_vu);
576 next_lsoff_u = ((unsigned int)precalc_src_addr_u)&0x0F;
577 mfc_get( u_plane[next_src_idx],
578 ((unsigned int) precalc_src_addr_u)&0xFFFFFFF0,
579 src_dbl_linestride_vu+(next_lsoff_v<<1),
580 RETR_BUF+next_src_idx,
581 0, 0 );
582
583 DMA_WAIT_TAG( (RETR_BUF+curr_src_idx) );
584
585 // scaling
586 // work line y_upper
587 bilinear_scale_line_w16( y_plane[curr_src_idx],
588 scaled_y_plane[curr_src_idx],
589 dst_width,
590 vf_x_scale,
591 vf_curr_NSweight_y_upper,
592 src_linestride_y );
593 // work line y_lower
594 bilinear_scale_line_w16( y_plane[curr_src_idx]+src_dbl_linestride_y,
595 scaled_y_plane[curr_src_idx]+scaled_src_linestride_y,
596 dst_width,
597 vf_x_scale,
598 vf_curr_NSweight_y_lower,
599 src_linestride_y );
600 // work line v
601 bilinear_scale_line_w8( v_plane[curr_src_idx]+curr_lsoff_v,
602 scaled_v_plane[curr_src_idx],
603 dst_width>>1,
604 vf_x_scale,
605 vf_curr_NSweight_vu,
606 src_linestride_vu );
607 // work line u
608 bilinear_scale_line_w8( u_plane[curr_src_idx]+curr_lsoff_u,
609 scaled_u_plane[curr_src_idx],
610 dst_width>>1,
611 vf_x_scale,
612 vf_curr_NSweight_vu,
613 src_linestride_vu );
614
615 //---------------------------------------------------------------------------------------------
616 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
617
618 // Perform three DMA transfers to 3 different locations in the main memory!
619 // dst_width: Pixel width of destination image
620 // dst_addr: Destination address in main memory
621 // dst_vu: Counter which is incremented one by one
622 // dst_y: Counter which is twice larger than dst_vu (dst_y = 2*dst_vu)
623
624 mfc_put( scaled_y_plane[curr_src_idx], // What from local store (addr)
625 (unsigned int) dst_addr_main_memory_y + (dst_vu*dst_dbl_linestride_y), // Destination in main memory (addr)
626 dst_dbl_linestride_y, // Two Y lines (depending on the widht of the destination resolution)
627 STR_BUF+curr_dst_idx, // Tag
628 0, 0 );
629
630 mfc_put( scaled_v_plane[curr_src_idx], // What from local store (addr)
631 (unsigned int) dst_addr_main_memory_v + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
632 dst_dbl_linestride_vu, // Two V lines (depending on the widht of the destination resolution)
633 STR_BUF+curr_dst_idx, // Tag
634 0, 0 );
635
636 mfc_put( scaled_u_plane[curr_src_idx], // What from local store (addr)
637 (unsigned int) dst_addr_main_memory_u + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
638 dst_dbl_linestride_vu, // Two U lines (depending on the widht of the destination resolution)
639 STR_BUF+curr_dst_idx, // Tag
640 0, 0 );
641 //---------------------------------------------------------------------------------------------
642
643
644 // update for next cycle
645 curr_src_idx = next_src_idx;
646 curr_dst_idx = next_dst_idx;
647
648 curr_interpl_y_upper = next_interpl_y_upper;
649 curr_interpl_y_lower = next_interpl_y_lower;
650 curr_interpl_vu = next_interpl_vu;
651
652 vf_curr_NSweight_y_upper = vf_curr_NSweight_y_upper;
653 vf_curr_NSweight_y_lower = vf_curr_NSweight_y_lower;
654 vf_curr_NSweight_vu = vf_next_NSweight_vu;
655
656 curr_src_y_upper = next_src_y_upper;
657 curr_src_y_lower = next_src_y_lower;
658 curr_src_vu = next_src_vu;
659
660 curr_lsoff_v = next_lsoff_v;
661 curr_lsoff_u = next_lsoff_u;
662 }
663
664
665
666 DMA_WAIT_TAG( (RETR_BUF+curr_src_idx) );
667
668 // scaling
669 // work line y_upper
670 bilinear_scale_line_w16( y_plane[curr_src_idx],
671 scaled_y_plane[curr_src_idx],
672 dst_width,
673 vf_x_scale,
674 vf_curr_NSweight_y_upper,
675 src_linestride_y );
676 // work line y_lower
677 bilinear_scale_line_w16( y_plane[curr_src_idx]+src_dbl_linestride_y,
678 scaled_y_plane[curr_src_idx]+scaled_src_linestride_y,
679 dst_width,
680 vf_x_scale,
681 vf_curr_NSweight_y_lower,
682 src_linestride_y );
683 // work line v
684 bilinear_scale_line_w8( v_plane[curr_src_idx]+curr_lsoff_v,
685 scaled_v_plane[curr_src_idx],
686 dst_width>>1,
687 vf_x_scale,
688 vf_curr_NSweight_vu,
689 src_linestride_vu );
690 // work line u
691 bilinear_scale_line_w8( u_plane[curr_src_idx]+curr_lsoff_u,
692 scaled_u_plane[curr_src_idx],
693 dst_width>>1,
694 vf_x_scale,
695 vf_curr_NSweight_vu,
696 src_linestride_vu );
697
698 //---------------------------------------------------------------------------------------------
699 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
700
701 // Perform three DMA transfers to 3 different locations in the main memory!
702 // dst_width: Pixel width of destination image
703 // dst_addr: Destination address in main memory
704 // dst_vu: Counter which is incremented one by one
705 // dst_y: Counter which is twice larger than dst_vu (dst_y = 2*dst_vu)
706
707 mfc_put( scaled_y_plane[curr_src_idx], // What from local store (addr)
708 (unsigned int) dst_addr_main_memory_y + (dst_vu*dst_dbl_linestride_y), // Destination in main memory (addr)
709 dst_dbl_linestride_y, // Two Y lines (depending on the widht of the destination resolution)
710 STR_BUF+curr_dst_idx, // Tag
711 0, 0 );
712
713 mfc_put( scaled_v_plane[curr_src_idx], // What from local store (addr)
714 (unsigned int) dst_addr_main_memory_v + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
715 dst_dbl_linestride_vu, // Two V lines (depending on the widht of the destination resolution)
716 STR_BUF+curr_dst_idx, // Tag
717 0, 0 );
718
719 mfc_put( scaled_u_plane[curr_src_idx], // What from local store (addr)
720 (unsigned int) dst_addr_main_memory_u + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
721 dst_dbl_linestride_vu, // Two U lines (depending on the widht of the destination resolution)
722 STR_BUF+curr_dst_idx, // Tag
723 0, 0 );
724
725 // wait for completion
726 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
727 //---------------------------------------------------------------------------------------------
728}
729
730
731/*
732 * scale_srcw32_dstw16()
733 *
734 * processes an input image of width 32
735 * scaling is done to a width 16
736 * yuv2rgb conversion on a width of 16
737 * result stored in RAM
738 */
739void scale_srcw32_dstw16() {
740 // extract parameters
741 unsigned char* dst_addr = (unsigned char *)parms.dstBuffer;
742
743 unsigned int src_width = parms.src_pixel_width;
744 unsigned int src_height = parms.src_pixel_height;
745 unsigned int dst_width = parms.dst_pixel_width;
746 unsigned int dst_height = parms.dst_pixel_height;
747
748 // YVU
749 unsigned int src_linestride_y = src_width;
750 unsigned int src_dbl_linestride_y = src_width<<1;
751 unsigned int src_linestride_vu = src_width>>1;
752 unsigned int src_dbl_linestride_vu = src_width;
753 // scaled YVU
754 unsigned int scaled_src_linestride_y = dst_width;
755
756 // ram addresses
757 unsigned char* src_addr_y = parms.y_plane;
758 unsigned char* src_addr_v = parms.v_plane;
759 unsigned char* src_addr_u = parms.u_plane;
760
761 unsigned int dst_picture_size = dst_width*dst_height;
762
763 // Sizes for destination
764 unsigned int dst_dbl_linestride_y = dst_width<<1;
765 unsigned int dst_dbl_linestride_vu = dst_width>>1;
766
767 // Perform address calculation for Y, V and U in main memory with dst_addr as base
768 unsigned char* dst_addr_main_memory_y = dst_addr;
769 unsigned char* dst_addr_main_memory_v = dst_addr + dst_picture_size;
770 unsigned char* dst_addr_main_memory_u = dst_addr_main_memory_v +(dst_picture_size>>2);
771
772 // calculate scale factors
773 vector float vf_x_scale = spu_splats( (float)src_width/(float)dst_width );
774 float y_scale = (float)src_height/(float)dst_height;
775
776 // double buffered processing
777 // buffer switching
778 unsigned int curr_src_idx = 0;
779 unsigned int curr_dst_idx = 0;
780 unsigned int next_src_idx, next_dst_idx;
781
782 // 2 lines y as output, upper and lowerline
783 unsigned int curr_interpl_y_upper = 0;
784 unsigned int next_interpl_y_upper;
785 unsigned int curr_interpl_y_lower, next_interpl_y_lower;
786 // only 1 line v/u output, both planes have the same dimension
787 unsigned int curr_interpl_vu = 0;
788 unsigned int next_interpl_vu;
789
790 // weights, calculated in every loop iteration
791 vector float vf_curr_NSweight_y_upper = { 0.0f, 0.0f, 0.0f, 0.0f };
792 vector float vf_next_NSweight_y_upper;
793 vector float vf_curr_NSweight_y_lower, vf_next_NSweight_y_lower;
794 vector float vf_curr_NSweight_vu = { 0.0f, 0.0f, 0.0f, 0.0f };
795 vector float vf_next_NSweight_vu;
796
797 // line indices for the src picture
798 float curr_src_y_upper = 0.0f, next_src_y_upper;
799 float curr_src_y_lower, next_src_y_lower;
800 float curr_src_vu = 0.0f, next_src_vu;
801
802 // line indices for the dst picture
803 unsigned int dst_y=0, dst_vu=0;
804
805 // calculate lower line idices
806 curr_src_y_lower = ((float)curr_interpl_y_upper+1)*y_scale;
807 curr_interpl_y_lower = (unsigned int)curr_src_y_lower;
808 // lower line weight
809 vf_curr_NSweight_y_lower = spu_splats( curr_src_y_lower-(float)curr_interpl_y_lower );
810
811
812 // start partially double buffered processing
813 // get initial data, 2 sets of y, 1 set v, 1 set u
814 mfc_get( y_plane[curr_src_idx], (unsigned int) src_addr_y, src_dbl_linestride_y, RETR_BUF, 0, 0 );
815 mfc_get( y_plane[curr_src_idx]+src_dbl_linestride_y,
816 (unsigned int) src_addr_y+(curr_interpl_y_lower*src_linestride_y),
817 src_dbl_linestride_y,
818 RETR_BUF,
819 0, 0 );
820 mfc_get( v_plane[curr_src_idx], (unsigned int) src_addr_v, src_dbl_linestride_vu, RETR_BUF, 0, 0 );
821 mfc_get( u_plane[curr_src_idx], (unsigned int) src_addr_u, src_dbl_linestride_vu, RETR_BUF, 0, 0 );
822
823 // iteration loop
824 // within each iteration 4 lines y, 2 lines v, 2 lines u are retrieved
825 // the scaled output is 2 lines y, 1 line v, 1 line u
826 // the yuv2rgb-converted output is stored to RAM
827 for( dst_vu=0; dst_vu<(dst_height>>1)-1; dst_vu++ ) {
828 dst_y = dst_vu<<1;
829
830 // calculate next indices
831 next_src_vu = ((float)dst_vu+1)*y_scale;
832 next_src_y_upper = ((float)dst_y+2)*y_scale;
833 next_src_y_lower = ((float)dst_y+3)*y_scale;
834
835 next_interpl_vu = (unsigned int) next_src_vu;
836 next_interpl_y_upper = (unsigned int) next_src_y_upper;
837 next_interpl_y_lower = (unsigned int) next_src_y_lower;
838
839 // calculate weight NORTH-SOUTH
840 vf_next_NSweight_vu = spu_splats( next_src_vu-(float)next_interpl_vu );
841 vf_next_NSweight_y_upper = spu_splats( next_src_y_upper-(float)next_interpl_y_upper );
842 vf_next_NSweight_y_lower = spu_splats( next_src_y_lower-(float)next_interpl_y_lower );
843
844 // get next lines
845 next_src_idx = curr_src_idx^1;
846 next_dst_idx = curr_dst_idx^1;
847
848 // 4 lines y
849 mfc_get( y_plane[next_src_idx],
850 (unsigned int) src_addr_y+(next_interpl_y_upper*src_linestride_y),
851 src_dbl_linestride_y,
852 RETR_BUF+next_src_idx,
853 0, 0 );
854 mfc_get( y_plane[next_src_idx]+src_dbl_linestride_y,
855 (unsigned int) src_addr_y+(next_interpl_y_lower*src_linestride_y),
856 src_dbl_linestride_y,
857 RETR_BUF+next_src_idx,
858 0, 0 );
859
860 // 2 lines v
861 mfc_get( v_plane[next_src_idx],
862 (unsigned int) src_addr_v+(next_interpl_vu*src_linestride_vu),
863 src_dbl_linestride_vu,
864 RETR_BUF+next_src_idx,
865 0, 0 );
866 // 2 lines u
867 mfc_get( u_plane[next_src_idx],
868 (unsigned int) src_addr_u+(next_interpl_vu*src_linestride_vu),
869 src_dbl_linestride_vu,
870 RETR_BUF+next_src_idx,
871 0, 0 );
872
873 DMA_WAIT_TAG( (RETR_BUF+curr_src_idx) );
874
875 // scaling
876 // work line y_upper
877 bilinear_scale_line_w16( y_plane[curr_src_idx],
878 scaled_y_plane[curr_src_idx],
879 dst_width,
880 vf_x_scale,
881 vf_curr_NSweight_y_upper,
882 src_linestride_y );
883 // work line y_lower
884 bilinear_scale_line_w16( y_plane[curr_src_idx]+src_dbl_linestride_y,
885 scaled_y_plane[curr_src_idx]+scaled_src_linestride_y,
886 dst_width,
887 vf_x_scale,
888 vf_curr_NSweight_y_lower,
889 src_linestride_y );
890 // work line v
891 bilinear_scale_line_w16( v_plane[curr_src_idx],
892 scaled_v_plane[curr_src_idx],
893 dst_width>>1,
894 vf_x_scale,
895 vf_curr_NSweight_vu,
896 src_linestride_vu );
897 // work line u
898 bilinear_scale_line_w16( u_plane[curr_src_idx],
899 scaled_u_plane[curr_src_idx],
900 dst_width>>1,
901 vf_x_scale,
902 vf_curr_NSweight_vu,
903 src_linestride_vu );
904
905 //---------------------------------------------------------------------------------------------
906 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
907
908 // Perform three DMA transfers to 3 different locations in the main memory!
909 // dst_width: Pixel width of destination image
910 // dst_addr: Destination address in main memory
911 // dst_vu: Counter which is incremented one by one
912 // dst_y: Counter which is twice larger than dst_vu (dst_y = 2*dst_vu)
913
914 mfc_put( scaled_y_plane[curr_src_idx], // What from local store (addr)
915 (unsigned int) dst_addr_main_memory_y + (dst_vu*dst_dbl_linestride_y), // Destination in main memory (addr)
916 dst_dbl_linestride_y, // Two Y lines (depending on the widht of the destination resolution)
917 STR_BUF+curr_dst_idx, // Tag
918 0, 0 );
919
920 mfc_put( scaled_v_plane[curr_src_idx], // What from local store (addr)
921 (unsigned int) dst_addr_main_memory_v + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
922 dst_dbl_linestride_vu, // Two V lines (depending on the widht of the destination resolution)
923 STR_BUF+curr_dst_idx, // Tag
924 0, 0 );
925
926 mfc_put( scaled_u_plane[curr_src_idx], // What from local store (addr)
927 (unsigned int) dst_addr_main_memory_u + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
928 dst_dbl_linestride_vu, // Two U lines (depending on the widht of the destination resolution)
929 STR_BUF+curr_dst_idx, // Tag
930 0, 0 );
931 //---------------------------------------------------------------------------------------------
932
933
934 // update for next cycle
935 curr_src_idx = next_src_idx;
936 curr_dst_idx = next_dst_idx;
937
938 curr_interpl_y_upper = next_interpl_y_upper;
939 curr_interpl_y_lower = next_interpl_y_lower;
940 curr_interpl_vu = next_interpl_vu;
941
942 vf_curr_NSweight_y_upper = vf_curr_NSweight_y_upper;
943 vf_curr_NSweight_y_lower = vf_curr_NSweight_y_lower;
944 vf_curr_NSweight_vu = vf_next_NSweight_vu;
945
946 curr_src_y_upper = next_src_y_upper;
947 curr_src_y_lower = next_src_y_lower;
948 curr_src_vu = next_src_vu;
949 }
950
951
952
953 DMA_WAIT_TAG( (RETR_BUF+curr_src_idx) );
954
955 // scaling
956 // work line y_upper
957 bilinear_scale_line_w16( y_plane[curr_src_idx],
958 scaled_y_plane[curr_src_idx],
959 dst_width,
960 vf_x_scale,
961 vf_curr_NSweight_y_upper,
962 src_linestride_y );
963 // work line y_lower
964 bilinear_scale_line_w16( y_plane[curr_src_idx]+src_dbl_linestride_y,
965 scaled_y_plane[curr_src_idx]+scaled_src_linestride_y,
966 dst_width,
967 vf_x_scale,
968 vf_curr_NSweight_y_lower,
969 src_linestride_y );
970 // work line v
971 bilinear_scale_line_w16( v_plane[curr_src_idx],
972 scaled_v_plane[curr_src_idx],
973 dst_width>>1,
974 vf_x_scale,
975 vf_curr_NSweight_vu,
976 src_linestride_vu );
977 // work line u
978 bilinear_scale_line_w16( u_plane[curr_src_idx],
979 scaled_u_plane[curr_src_idx],
980 dst_width>>1,
981 vf_x_scale,
982 vf_curr_NSweight_vu,
983 src_linestride_vu );
984
985
986 //---------------------------------------------------------------------------------------------
987 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
988
989 // Perform three DMA transfers to 3 different locations in the main memory!
990 // dst_width: Pixel width of destination image
991 // dst_addr: Destination address in main memory
992 // dst_vu: Counter which is incremented one by one
993 // dst_y: Counter which is twice larger than dst_vu (dst_y = 2*dst_vu)
994
995 mfc_put( scaled_y_plane[curr_src_idx], // What from local store (addr)
996 (unsigned int) dst_addr_main_memory_y + (dst_vu*dst_dbl_linestride_y), // Destination in main memory (addr)
997 dst_dbl_linestride_y, // Two Y lines (depending on the widht of the destination resolution)
998 STR_BUF+curr_dst_idx, // Tag
999 0, 0 );
1000
1001 mfc_put( scaled_v_plane[curr_src_idx], // What from local store (addr)
1002 (unsigned int) dst_addr_main_memory_v + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
1003 dst_dbl_linestride_vu, // Two V lines (depending on the widht of the destination resolution)
1004 STR_BUF+curr_dst_idx, // Tag
1005 0, 0 );
1006
1007 mfc_put( scaled_u_plane[curr_src_idx], // What from local store (addr)
1008 (unsigned int) dst_addr_main_memory_u + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
1009 dst_dbl_linestride_vu, // Two U lines (depending on the widht of the destination resolution)
1010 STR_BUF+curr_dst_idx, // Tag
1011 0, 0 );
1012
1013 // wait for completion
1014 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
1015 //---------------------------------------------------------------------------------------------
1016}
1017
1018
1019/**
1020 * scale_srcw32_dstw32()
1021 *
1022 * processes an input image of width 32
1023 * scaling is done to a width 32
1024 * yuv2rgb conversion on a width of 32
1025 * result stored in RAM
1026 */
1027void scale_srcw32_dstw32() {
1028 // extract parameters
1029 unsigned char* dst_addr = (unsigned char *)parms.dstBuffer;
1030
1031 unsigned int src_width = parms.src_pixel_width;
1032 unsigned int src_height = parms.src_pixel_height;
1033 unsigned int dst_width = parms.dst_pixel_width;
1034 unsigned int dst_height = parms.dst_pixel_height;
1035
1036 // YVU
1037 unsigned int src_linestride_y = src_width;
1038 unsigned int src_dbl_linestride_y = src_width<<1;
1039 unsigned int src_linestride_vu = src_width>>1;
1040 unsigned int src_dbl_linestride_vu = src_width;
1041
1042 // scaled YVU
1043 unsigned int scaled_src_linestride_y = dst_width;
1044
1045 // ram addresses
1046 unsigned char* src_addr_y = parms.y_plane;
1047 unsigned char* src_addr_v = parms.v_plane;
1048 unsigned char* src_addr_u = parms.u_plane;
1049
1050 unsigned int dst_picture_size = dst_width*dst_height;
1051
1052 // Sizes for destination
1053 unsigned int dst_dbl_linestride_y = dst_width<<1;
1054 unsigned int dst_dbl_linestride_vu = dst_width>>1;
1055
1056 // Perform address calculation for Y, V and U in main memory with dst_addr as base
1057 unsigned char* dst_addr_main_memory_y = dst_addr;
1058 unsigned char* dst_addr_main_memory_v = dst_addr + dst_picture_size;
1059 unsigned char* dst_addr_main_memory_u = dst_addr_main_memory_v +(dst_picture_size>>2);
1060
1061 // calculate scale factors
1062 vector float vf_x_scale = spu_splats( (float)src_width/(float)dst_width );
1063 float y_scale = (float)src_height/(float)dst_height;
1064
1065 // double buffered processing
1066 // buffer switching
1067 unsigned int curr_src_idx = 0;
1068 unsigned int curr_dst_idx = 0;
1069 unsigned int next_src_idx, next_dst_idx;
1070
1071 // 2 lines y as output, upper and lowerline
1072 unsigned int curr_interpl_y_upper = 0;
1073 unsigned int next_interpl_y_upper;
1074 unsigned int curr_interpl_y_lower, next_interpl_y_lower;
1075 // only 1 line v/u output, both planes have the same dimension
1076 unsigned int curr_interpl_vu = 0;
1077 unsigned int next_interpl_vu;
1078
1079 // weights, calculated in every loop iteration
1080 vector float vf_curr_NSweight_y_upper = { 0.0f, 0.0f, 0.0f, 0.0f };
1081 vector float vf_next_NSweight_y_upper;
1082 vector float vf_curr_NSweight_y_lower, vf_next_NSweight_y_lower;
1083 vector float vf_curr_NSweight_vu = { 0.0f, 0.0f, 0.0f, 0.0f };
1084 vector float vf_next_NSweight_vu;
1085
1086 // line indices for the src picture
1087 float curr_src_y_upper = 0.0f, next_src_y_upper;
1088 float curr_src_y_lower, next_src_y_lower;
1089 float curr_src_vu = 0.0f, next_src_vu;
1090
1091 // line indices for the dst picture
1092 unsigned int dst_y=0, dst_vu=0;
1093
1094 // calculate lower line idices
1095 curr_src_y_lower = ((float)curr_interpl_y_upper+1)*y_scale;
1096 curr_interpl_y_lower = (unsigned int)curr_src_y_lower;
1097 // lower line weight
1098 vf_curr_NSweight_y_lower = spu_splats( curr_src_y_lower-(float)curr_interpl_y_lower );
1099
1100
1101 // start partially double buffered processing
1102 // get initial data, 2 sets of y, 1 set v, 1 set u
1103 mfc_get( y_plane[curr_src_idx], (unsigned int) src_addr_y, src_dbl_linestride_y, RETR_BUF, 0, 0 );
1104 mfc_get( y_plane[curr_src_idx]+src_dbl_linestride_y,
1105 (unsigned int) src_addr_y+(curr_interpl_y_lower*src_linestride_y),
1106 src_dbl_linestride_y,
1107 RETR_BUF,
1108 0, 0 );
1109 mfc_get( v_plane[curr_src_idx], (unsigned int) src_addr_v, src_dbl_linestride_vu, RETR_BUF, 0, 0 );
1110 mfc_get( u_plane[curr_src_idx], (unsigned int) src_addr_u, src_dbl_linestride_vu, RETR_BUF, 0, 0 );
1111
1112 // iteration loop
1113 // within each iteration 4 lines y, 2 lines v, 2 lines u are retrieved
1114 // the scaled output is 2 lines y, 1 line v, 1 line u
1115 // the yuv2rgb-converted output is stored to RAM
1116 for( dst_vu=0; dst_vu<(dst_height>>1)-1; dst_vu++ ) {
1117 dst_y = dst_vu<<1;
1118
1119 // calculate next indices
1120 next_src_vu = ((float)dst_vu+1)*y_scale;
1121 next_src_y_upper = ((float)dst_y+2)*y_scale;
1122 next_src_y_lower = ((float)dst_y+3)*y_scale;
1123
1124 next_interpl_vu = (unsigned int) next_src_vu;
1125 next_interpl_y_upper = (unsigned int) next_src_y_upper;
1126 next_interpl_y_lower = (unsigned int) next_src_y_lower;
1127
1128 // calculate weight NORTH-SOUTH
1129 vf_next_NSweight_vu = spu_splats( next_src_vu-(float)next_interpl_vu );
1130 vf_next_NSweight_y_upper = spu_splats( next_src_y_upper-(float)next_interpl_y_upper );
1131 vf_next_NSweight_y_lower = spu_splats( next_src_y_lower-(float)next_interpl_y_lower );
1132
1133 // get next lines
1134 next_src_idx = curr_src_idx^1;
1135 next_dst_idx = curr_dst_idx^1;
1136
1137 // 4 lines y
1138 mfc_get( y_plane[next_src_idx],
1139 (unsigned int) src_addr_y+(next_interpl_y_upper*src_linestride_y),
1140 src_dbl_linestride_y,
1141 RETR_BUF+next_src_idx,
1142 0, 0 );
1143 mfc_get( y_plane[next_src_idx]+src_dbl_linestride_y,
1144 (unsigned int) src_addr_y+(next_interpl_y_lower*src_linestride_y),
1145 src_dbl_linestride_y,
1146 RETR_BUF+next_src_idx,
1147 0, 0 );
1148
1149 // 2 lines v
1150 mfc_get( v_plane[next_src_idx],
1151 (unsigned int) src_addr_v+(next_interpl_vu*src_linestride_vu),
1152 src_dbl_linestride_vu,
1153 RETR_BUF+next_src_idx,
1154 0, 0 );
1155 // 2 lines u
1156 mfc_get( u_plane[next_src_idx],
1157 (unsigned int) src_addr_u+(next_interpl_vu*src_linestride_vu),
1158 src_dbl_linestride_vu,
1159 RETR_BUF+next_src_idx,
1160 0, 0 );
1161
1162 DMA_WAIT_TAG( (RETR_BUF+curr_src_idx) );
1163
1164 // scaling
1165 // work line y_upper
1166 bilinear_scale_line_w16( y_plane[curr_src_idx],
1167 scaled_y_plane[curr_src_idx],
1168 dst_width,
1169 vf_x_scale,
1170 vf_curr_NSweight_y_upper,
1171 src_linestride_y );
1172 // work line y_lower
1173 bilinear_scale_line_w16( y_plane[curr_src_idx]+src_dbl_linestride_y,
1174 scaled_y_plane[curr_src_idx]+scaled_src_linestride_y,
1175 dst_width,
1176 vf_x_scale,
1177 vf_curr_NSweight_y_lower,
1178 src_linestride_y );
1179 // work line v
1180 bilinear_scale_line_w16( v_plane[curr_src_idx],
1181 scaled_v_plane[curr_src_idx],
1182 dst_width>>1,
1183 vf_x_scale,
1184 vf_curr_NSweight_vu,
1185 src_linestride_vu );
1186 // work line u
1187 bilinear_scale_line_w16( u_plane[curr_src_idx],
1188 scaled_u_plane[curr_src_idx],
1189 dst_width>>1,
1190 vf_x_scale,
1191 vf_curr_NSweight_vu,
1192 src_linestride_vu );
1193
1194
1195
1196 // Store the result back to main memory into a destination buffer in YUV format
1197 //---------------------------------------------------------------------------------------------
1198 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
1199
1200 // Perform three DMA transfers to 3 different locations in the main memory!
1201 // dst_width: Pixel width of destination image
1202 // dst_addr: Destination address in main memory
1203 // dst_vu: Counter which is incremented one by one
1204 // dst_y: Counter which is twice larger than dst_vu (dst_y = 2*dst_vu)
1205
1206 mfc_put( scaled_y_plane[curr_src_idx], // What from local store (addr)
1207 (unsigned int) dst_addr_main_memory_y + (dst_vu*dst_dbl_linestride_y), // Destination in main memory (addr)
1208 dst_dbl_linestride_y, // Two Y lines (depending on the widht of the destination resolution)
1209 STR_BUF+curr_dst_idx, // Tag
1210 0, 0 );
1211
1212 mfc_put( scaled_v_plane[curr_src_idx], // What from local store (addr)
1213 (unsigned int) dst_addr_main_memory_v + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
1214 dst_dbl_linestride_vu, // Two V lines (depending on the widht of the destination resolution)
1215 STR_BUF+curr_dst_idx, // Tag
1216 0, 0 );
1217
1218 mfc_put( scaled_u_plane[curr_src_idx], // What from local store (addr)
1219 (unsigned int) dst_addr_main_memory_u + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
1220 dst_dbl_linestride_vu, // Two U lines (depending on the widht of the destination resolution)
1221 STR_BUF+curr_dst_idx, // Tag
1222 0, 0 );
1223 //---------------------------------------------------------------------------------------------
1224
1225
1226 // update for next cycle
1227 curr_src_idx = next_src_idx;
1228 curr_dst_idx = next_dst_idx;
1229
1230 curr_interpl_y_upper = next_interpl_y_upper;
1231 curr_interpl_y_lower = next_interpl_y_lower;
1232 curr_interpl_vu = next_interpl_vu;
1233
1234 vf_curr_NSweight_y_upper = vf_curr_NSweight_y_upper;
1235 vf_curr_NSweight_y_lower = vf_curr_NSweight_y_lower;
1236 vf_curr_NSweight_vu = vf_next_NSweight_vu;
1237
1238 curr_src_y_upper = next_src_y_upper;
1239 curr_src_y_lower = next_src_y_lower;
1240 curr_src_vu = next_src_vu;
1241 }
1242
1243
1244
1245 DMA_WAIT_TAG( (RETR_BUF+curr_src_idx) );
1246
1247 // scaling
1248 // work line y_upper
1249 bilinear_scale_line_w16( y_plane[curr_src_idx],
1250 scaled_y_plane[curr_src_idx],
1251 dst_width,
1252 vf_x_scale,
1253 vf_curr_NSweight_y_upper,
1254 src_linestride_y );
1255 // work line y_lower
1256 bilinear_scale_line_w16( y_plane[curr_src_idx]+src_dbl_linestride_y,
1257 scaled_y_plane[curr_src_idx]+scaled_src_linestride_y,
1258 dst_width,
1259 vf_x_scale,
1260 vf_curr_NSweight_y_lower,
1261 src_linestride_y );
1262 // work line v
1263 bilinear_scale_line_w16( v_plane[curr_src_idx],
1264 scaled_v_plane[curr_src_idx],
1265 dst_width>>1,
1266 vf_x_scale,
1267 vf_curr_NSweight_vu,
1268 src_linestride_vu );
1269 // work line u
1270 bilinear_scale_line_w16( u_plane[curr_src_idx],
1271 scaled_u_plane[curr_src_idx],
1272 dst_width>>1,
1273 vf_x_scale,
1274 vf_curr_NSweight_vu,
1275 src_linestride_vu );
1276
1277
1278 // Store the result back to main memory into a destination buffer in YUV format
1279 //---------------------------------------------------------------------------------------------
1280 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
1281
1282 // Perform three DMA transfers to 3 different locations in the main memory!
1283 // dst_width: Pixel width of destination image
1284 // dst_addr: Destination address in main memory
1285 // dst_vu: Counter which is incremented one by one
1286 // dst_y: Counter which is twice larger than dst_vu (dst_y = 2*dst_vu)
1287
1288 mfc_put( scaled_y_plane[curr_src_idx], // What from local store (addr)
1289 (unsigned int) dst_addr_main_memory_y + (dst_vu*dst_dbl_linestride_y), // Destination in main memory (addr)
1290 dst_dbl_linestride_y, // Two Y lines (depending on the widht of the destination resolution)
1291 STR_BUF+curr_dst_idx, // Tag
1292 0, 0 );
1293
1294 mfc_put( scaled_v_plane[curr_src_idx], // What from local store (addr)
1295 (unsigned int) dst_addr_main_memory_v + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
1296 dst_dbl_linestride_vu, // Two V lines (depending on the widht of the destination resolution)
1297 STR_BUF+curr_dst_idx, // Tag
1298 0, 0 );
1299
1300 mfc_put( scaled_u_plane[curr_src_idx], // What from local store (addr)
1301 (unsigned int) dst_addr_main_memory_u + (dst_vu*dst_dbl_linestride_vu), // Destination in main memory (addr)
1302 dst_dbl_linestride_vu, // Two U lines (depending on the widht of the destination resolution)
1303 STR_BUF+curr_dst_idx, // Tag
1304 0, 0 );
1305
1306 // wait for completion
1307 DMA_WAIT_TAG( (STR_BUF+curr_dst_idx) );
1308 //---------------------------------------------------------------------------------------------
1309}
1310
1311
1312/*
1313 * bilinear_scale_line_w8()
1314 *
1315 * processes a line of yuv-input, width has to be a multiple of 8
1316 * scaled yuv-output is written to local store buffer
1317 *
1318 * @param src buffer for 2 lines input
1319 * @param dst_ buffer for 1 line output
1320 * @param dst_width the width of the destination line
1321 * @param vf_x_scale a float vector, at each entry is the x_scale-factor
1322 * @param vf_NSweight a float vector, at each position is the weight NORTH/SOUTH for the current line
1323 * @param src_linestride the stride of the srcline
1324 */
1325void bilinear_scale_line_w8( unsigned char* src, unsigned char* dst_, unsigned int dst_width, vector float vf_x_scale, vector float vf_NSweight, unsigned int src_linestride ) {
1326
1327 unsigned char* dst = dst_;
1328
1329 unsigned int dst_x;
1330 for( dst_x=0; dst_x<dst_width; dst_x+=8) {
1331 // address calculation for loading the 4 surrounding pixel of each calculated
1332 // destination pixel
1333 vector unsigned int vui_dst_x_tmp = spu_splats( dst_x );
1334 // lower range->first 4 pixel
1335 // upper range->next 4 pixel
1336 vector unsigned int vui_inc_dst_x_lower_range = { 0, 1, 2, 3 };
1337 vector unsigned int vui_inc_dst_x_upper_range = { 4, 5, 6, 7 };
1338 vector unsigned int vui_dst_x_lower_range = spu_add( vui_dst_x_tmp, vui_inc_dst_x_lower_range );
1339 vector unsigned int vui_dst_x_upper_range = spu_add( vui_dst_x_tmp, vui_inc_dst_x_upper_range );
1340
1341 // calculate weight EAST-WEST
1342 vector float vf_dst_x_lower_range = spu_convtf( vui_dst_x_lower_range, 0 );
1343 vector float vf_dst_x_upper_range = spu_convtf( vui_dst_x_upper_range, 0 );
1344 vector float vf_src_x_lower_range = spu_mul( vf_dst_x_lower_range, vf_x_scale );
1345 vector float vf_src_x_upper_range = spu_mul( vf_dst_x_upper_range, vf_x_scale );
1346 vector unsigned int vui_interpl_x_lower_range = spu_convtu( vf_src_x_lower_range, 0 );
1347 vector unsigned int vui_interpl_x_upper_range = spu_convtu( vf_src_x_upper_range, 0 );
1348 vector float vf_interpl_x_lower_range = spu_convtf( vui_interpl_x_lower_range, 0 );
1349 vector float vf_interpl_x_upper_range = spu_convtf( vui_interpl_x_upper_range, 0 );
1350 vector float vf_EWweight_lower_range = spu_sub( vf_src_x_lower_range, vf_interpl_x_lower_range );
1351 vector float vf_EWweight_upper_range = spu_sub( vf_src_x_upper_range, vf_interpl_x_upper_range );
1352
1353 // calculate address offset
1354 //
1355 // pixel NORTH WEST
1356 vector unsigned int vui_off_pixelNW_lower_range = vui_interpl_x_lower_range;
1357 vector unsigned int vui_off_pixelNW_upper_range = vui_interpl_x_upper_range;
1358
1359 // pixel NORTH EAST-->(offpixelNW+1)
1360 vector unsigned int vui_add_1 = { 1, 1, 1, 1 };
1361 vector unsigned int vui_off_pixelNE_lower_range = spu_add( vui_off_pixelNW_lower_range, vui_add_1 );
1362 vector unsigned int vui_off_pixelNE_upper_range = spu_add( vui_off_pixelNW_upper_range, vui_add_1 );
1363
1364 // SOUTH-WEST-->(offpixelNW+src_linestride)
1365 vector unsigned int vui_srclinestride = spu_splats( src_linestride );
1366 vector unsigned int vui_off_pixelSW_lower_range = spu_add( vui_srclinestride, vui_off_pixelNW_lower_range );
1367 vector unsigned int vui_off_pixelSW_upper_range = spu_add( vui_srclinestride, vui_off_pixelNW_upper_range );
1368
1369 // SOUTH-EAST-->(offpixelNW+src_linestride+1)
1370 vector unsigned int vui_off_pixelSE_lower_range = spu_add( vui_srclinestride, vui_off_pixelNE_lower_range );
1371 vector unsigned int vui_off_pixelSE_upper_range = spu_add( vui_srclinestride, vui_off_pixelNE_upper_range );
1372
1373 // calculate each address
1374 vector unsigned int vui_src_ls = spu_splats( (unsigned int) src );
1375 vector unsigned int vui_addr_pixelNW_lower_range = spu_add( vui_src_ls, vui_off_pixelNW_lower_range );
1376 vector unsigned int vui_addr_pixelNW_upper_range = spu_add( vui_src_ls, vui_off_pixelNW_upper_range );
1377 vector unsigned int vui_addr_pixelNE_lower_range = spu_add( vui_src_ls, vui_off_pixelNE_lower_range );
1378 vector unsigned int vui_addr_pixelNE_upper_range = spu_add( vui_src_ls, vui_off_pixelNE_upper_range );
1379
1380 vector unsigned int vui_addr_pixelSW_lower_range = spu_add( vui_src_ls, vui_off_pixelSW_lower_range );
1381 vector unsigned int vui_addr_pixelSW_upper_range = spu_add( vui_src_ls, vui_off_pixelSW_upper_range );
1382 vector unsigned int vui_addr_pixelSE_lower_range = spu_add( vui_src_ls, vui_off_pixelSE_lower_range );
1383 vector unsigned int vui_addr_pixelSE_upper_range = spu_add( vui_src_ls, vui_off_pixelSE_upper_range );
1384
1385 // get each pixel
1386 //
1387 // scalar load, afterwards insertion into the right position
1388 // NORTH WEST
1389 vector unsigned char null_vector = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1390 vector unsigned char vuc_pixel_NW_lower_range = spu_insert(
1391 *((unsigned char*) spu_extract( vui_addr_pixelNW_lower_range, 0 )), null_vector, 3 );
1392 vuc_pixel_NW_lower_range = spu_insert(
1393 *((unsigned char*) spu_extract( vui_addr_pixelNW_lower_range, 1 )),
1394 vuc_pixel_NW_lower_range, 7 );
1395 vuc_pixel_NW_lower_range = spu_insert(
1396 *((unsigned char*) spu_extract( vui_addr_pixelNW_lower_range, 2 )),
1397 vuc_pixel_NW_lower_range, 11 );
1398 vuc_pixel_NW_lower_range = spu_insert(
1399 *((unsigned char*) spu_extract( vui_addr_pixelNW_lower_range, 3 )),
1400 vuc_pixel_NW_lower_range, 15 );
1401
1402 vector unsigned char vuc_pixel_NW_upper_range = spu_insert(
1403 *((unsigned char*) spu_extract( vui_addr_pixelNW_upper_range, 0 )), null_vector, 3 );
1404 vuc_pixel_NW_upper_range = spu_insert(
1405 *((unsigned char*) spu_extract( vui_addr_pixelNW_upper_range, 1 )),
1406 vuc_pixel_NW_upper_range, 7 );
1407 vuc_pixel_NW_upper_range = spu_insert(
1408 *((unsigned char*) spu_extract( vui_addr_pixelNW_upper_range, 2 )),
1409 vuc_pixel_NW_upper_range, 11 );
1410 vuc_pixel_NW_upper_range = spu_insert(
1411 *((unsigned char*) spu_extract( vui_addr_pixelNW_upper_range, 3 )),
1412 vuc_pixel_NW_upper_range, 15 );
1413
1414 // NORTH EAST
1415 vector unsigned char vuc_pixel_NE_lower_range = spu_insert(
1416 *((unsigned char*) spu_extract( vui_addr_pixelNE_lower_range, 0 )), null_vector, 3 );
1417 vuc_pixel_NE_lower_range = spu_insert(
1418 *((unsigned char*) spu_extract( vui_addr_pixelNE_lower_range, 1 )),
1419 vuc_pixel_NE_lower_range, 7 );
1420 vuc_pixel_NE_lower_range = spu_insert(
1421 *((unsigned char*) spu_extract( vui_addr_pixelNE_lower_range, 2 )),
1422 vuc_pixel_NE_lower_range, 11 );
1423 vuc_pixel_NE_lower_range = spu_insert(
1424 *((unsigned char*) spu_extract( vui_addr_pixelNE_lower_range, 3 )),
1425 vuc_pixel_NE_lower_range, 15 );
1426
1427 vector unsigned char vuc_pixel_NE_upper_range = spu_insert(
1428 *((unsigned char*) spu_extract( vui_addr_pixelNE_upper_range, 0 )), null_vector, 3 );
1429 vuc_pixel_NE_upper_range = spu_insert(
1430 *((unsigned char*) spu_extract( vui_addr_pixelNE_upper_range, 1 )),
1431 vuc_pixel_NE_upper_range, 7 );
1432 vuc_pixel_NE_upper_range = spu_insert(
1433 *((unsigned char*) spu_extract( vui_addr_pixelNE_upper_range, 2 )),
1434 vuc_pixel_NE_upper_range, 11 );
1435 vuc_pixel_NE_upper_range = spu_insert(
1436 *((unsigned char*) spu_extract( vui_addr_pixelNE_upper_range, 3 )),
1437 vuc_pixel_NE_upper_range, 15 );
1438
1439
1440 // SOUTH WEST
1441 vector unsigned char vuc_pixel_SW_lower_range = spu_insert(
1442 *((unsigned char*) spu_extract( vui_addr_pixelSW_lower_range, 0 )), null_vector, 3 );
1443 vuc_pixel_SW_lower_range = spu_insert(
1444 *((unsigned char*) spu_extract( vui_addr_pixelSW_lower_range, 1 )),
1445 vuc_pixel_SW_lower_range, 7 );
1446 vuc_pixel_SW_lower_range = spu_insert(
1447 *((unsigned char*) spu_extract( vui_addr_pixelSW_lower_range, 2 )),
1448 vuc_pixel_SW_lower_range, 11 );
1449 vuc_pixel_SW_lower_range = spu_insert(
1450 *((unsigned char*) spu_extract( vui_addr_pixelSW_lower_range, 3 )),
1451 vuc_pixel_SW_lower_range, 15 );
1452
1453 vector unsigned char vuc_pixel_SW_upper_range = spu_insert(
1454 *((unsigned char*) spu_extract( vui_addr_pixelSW_upper_range, 0 )), null_vector, 3 );
1455 vuc_pixel_SW_upper_range = spu_insert(
1456 *((unsigned char*) spu_extract( vui_addr_pixelSW_upper_range, 1 )),
1457 vuc_pixel_SW_upper_range, 7 );
1458 vuc_pixel_SW_upper_range = spu_insert(
1459 *((unsigned char*) spu_extract( vui_addr_pixelSW_upper_range, 2 )),
1460 vuc_pixel_SW_upper_range, 11 );
1461 vuc_pixel_SW_upper_range = spu_insert(
1462 *((unsigned char*) spu_extract( vui_addr_pixelSW_upper_range, 3 )),
1463 vuc_pixel_SW_upper_range, 15 );
1464
1465 // SOUTH EAST
1466 vector unsigned char vuc_pixel_SE_lower_range = spu_insert(
1467 *((unsigned char*) spu_extract( vui_addr_pixelSE_lower_range, 0 )), null_vector, 3 );
1468 vuc_pixel_SE_lower_range = spu_insert(
1469 *((unsigned char*) spu_extract( vui_addr_pixelSE_lower_range, 1 )),
1470 vuc_pixel_SE_lower_range, 7 );
1471 vuc_pixel_SE_lower_range = spu_insert(
1472 *((unsigned char*) spu_extract( vui_addr_pixelSE_lower_range, 2 )),
1473 vuc_pixel_SE_lower_range, 11 );
1474 vuc_pixel_SE_lower_range = spu_insert(
1475 *((unsigned char*) spu_extract( vui_addr_pixelSE_lower_range, 3 )),
1476 vuc_pixel_SE_lower_range, 15 );
1477
1478 vector unsigned char vuc_pixel_SE_upper_range = spu_insert(
1479 *((unsigned char*) spu_extract( vui_addr_pixelSE_upper_range, 0 )), null_vector, 3 );
1480 vuc_pixel_SE_upper_range = spu_insert(
1481 *((unsigned char*) spu_extract( vui_addr_pixelSE_upper_range, 1 )),
1482 vuc_pixel_SE_upper_range, 7 );
1483 vuc_pixel_SE_upper_range = spu_insert(
1484 *((unsigned char*) spu_extract( vui_addr_pixelSE_upper_range, 2 )),
1485 vuc_pixel_SE_upper_range, 11 );
1486 vuc_pixel_SE_upper_range = spu_insert(
1487 *((unsigned char*) spu_extract( vui_addr_pixelSE_upper_range, 3 )),
1488 vuc_pixel_SE_upper_range, 15 );
1489
1490
1491 // convert to float
1492 vector float vf_pixel_NW_lower_range = spu_convtf( (vector unsigned int) vuc_pixel_NW_lower_range, 0 );
1493 vector float vf_pixel_NW_upper_range = spu_convtf( (vector unsigned int) vuc_pixel_NW_upper_range, 0 );
1494
1495 vector float vf_pixel_SW_lower_range = spu_convtf( (vector unsigned int) vuc_pixel_SW_lower_range, 0 );
1496 vector float vf_pixel_SW_upper_range = spu_convtf( (vector unsigned int) vuc_pixel_SW_upper_range, 0 );
1497
1498 vector float vf_pixel_NE_lower_range = spu_convtf( (vector unsigned int) vuc_pixel_NE_lower_range, 0 );
1499 vector float vf_pixel_NE_upper_range = spu_convtf( (vector unsigned int) vuc_pixel_NE_upper_range, 0 );
1500
1501 vector float vf_pixel_SE_lower_range = spu_convtf( (vector unsigned int) vuc_pixel_SE_lower_range, 0 );
1502 vector float vf_pixel_SE_upper_range = spu_convtf( (vector unsigned int) vuc_pixel_SE_upper_range, 0 );
1503
1504
1505
1506 // first linear interpolation: EWtop
1507 // EWtop = NW + EWweight*(NE-NW)
1508 //
1509 // lower range
1510 vector float vf_EWtop_lower_range_tmp = spu_sub( vf_pixel_NE_lower_range, vf_pixel_NW_lower_range );
1511 vector float vf_EWtop_lower_range = spu_madd( vf_EWweight_lower_range,
1512 vf_EWtop_lower_range_tmp,
1513 vf_pixel_NW_lower_range );
1514
1515 // upper range
1516 vector float vf_EWtop_upper_range_tmp = spu_sub( vf_pixel_NE_upper_range, vf_pixel_NW_upper_range );
1517 vector float vf_EWtop_upper_range = spu_madd( vf_EWweight_upper_range,
1518 vf_EWtop_upper_range_tmp,
1519 vf_pixel_NW_upper_range );
1520
1521
1522
1523 // second linear interpolation: EWbottom
1524 // EWbottom = SW + EWweight*(SE-SW)
1525 //
1526 // lower range
1527 vector float vf_EWbottom_lower_range_tmp = spu_sub( vf_pixel_SE_lower_range, vf_pixel_SW_lower_range );
1528 vector float vf_EWbottom_lower_range = spu_madd( vf_EWweight_lower_range,
1529 vf_EWbottom_lower_range_tmp,
1530 vf_pixel_SW_lower_range );
1531
1532 // upper range
1533 vector float vf_EWbottom_upper_range_tmp = spu_sub( vf_pixel_SE_upper_range, vf_pixel_SW_upper_range );
1534 vector float vf_EWbottom_upper_range = spu_madd( vf_EWweight_upper_range,
1535 vf_EWbottom_upper_range_tmp,
1536 vf_pixel_SW_upper_range );
1537
1538
1539
1540 // third linear interpolation: the bilinear interpolated value
1541 // result = EWtop + NSweight*(EWbottom-EWtop);
1542 //
1543 // lower range
1544 vector float vf_result_lower_range_tmp = spu_sub( vf_EWbottom_lower_range, vf_EWtop_lower_range );
1545 vector float vf_result_lower_range = spu_madd( vf_NSweight,
1546 vf_result_lower_range_tmp,
1547 vf_EWtop_lower_range );
1548
1549 // upper range
1550 vector float vf_result_upper_range_tmp = spu_sub( vf_EWbottom_upper_range, vf_EWtop_upper_range );
1551 vector float vf_result_upper_range = spu_madd( vf_NSweight,
1552 vf_result_upper_range_tmp,
1553 vf_EWtop_upper_range );
1554
1555
1556 // convert back: using saturated arithmetic
1557 vector unsigned int vui_result_lower_range = vfloat_to_vuint( vf_result_lower_range );
1558 vector unsigned int vui_result_upper_range = vfloat_to_vuint( vf_result_upper_range );
1559
1560 // merge results->lower,upper
1561 vector unsigned char vuc_mask_merge_result = { 0x03, 0x07, 0x0B, 0x0F,
1562 0x13, 0x17, 0x1B, 0x1F,
1563 0x00, 0x00, 0x00, 0x00,
1564 0x00, 0x00, 0x00, 0x00 };
1565
1566 vector unsigned char vuc_result = spu_shuffle( (vector unsigned char) vui_result_lower_range,
1567 (vector unsigned char) vui_result_upper_range,
1568 vuc_mask_merge_result );
1569
1570 // partial storing
1571 vector unsigned char vuc_mask_out = { 0x00, 0x00, 0x00, 0x00,
1572 0x00, 0x00, 0x00, 0x00,
1573 0xFF, 0xFF, 0xFF, 0xFF,
1574 0xFF, 0xFF, 0xFF, 0xFF };
1575
1576
1577 // get currently stored data
1578 vector unsigned char vuc_orig = *((vector unsigned char*)dst);
1579
1580 // clear currently stored data
1581 vuc_orig = spu_and( vuc_orig,
1582 spu_rlqwbyte( vuc_mask_out, ((unsigned int)dst)&0x0F) );
1583
1584 // rotate result according to storing address
1585 vuc_result = spu_rlqwbyte( vuc_result, ((unsigned int)dst)&0x0F );
1586
1587 // store result
1588 *((vector unsigned char*)dst) = spu_or( vuc_result,
1589 vuc_orig );
1590 dst += 8;
1591 }
1592}
1593
1594
1595/*
1596 * bilinear_scale_line_w16()
1597 *
1598 * processes a line of yuv-input, width has to be a multiple of 16
1599 * scaled yuv-output is written to local store buffer
1600 *
1601 * @param src buffer for 2 lines input
1602 * @param dst_ buffer for 1 line output
1603 * @param dst_width the width of the destination line
1604 * @param vf_x_scale a float vector, at each entry is the x_scale-factor
1605 * @param vf_NSweight a float vector, at each position is the weight NORTH/SOUTH for the current line
1606 * @param src_linestride the stride of the srcline
1607 */
1608void bilinear_scale_line_w16( unsigned char* src, unsigned char* dst_, unsigned int dst_width, vector float vf_x_scale, vector float vf_NSweight, unsigned int src_linestride ) {
1609
1610 unsigned char* dst = dst_;
1611
1612 unsigned int dst_x;
1613 for( dst_x=0; dst_x<dst_width; dst_x+=16) {
1614 // address calculation for loading the 4 surrounding pixel of each calculated
1615 // destination pixel
1616 vector unsigned int vui_dst_x_tmp = spu_splats( dst_x );
1617 // parallelised processing
1618 // first range->pixel 1 2 3 4
1619 // second range->pixel 5 6 7 8
1620 // third range->pixel 9 10 11 12
1621 // fourth range->pixel 13 14 15 16
1622 vector unsigned int vui_inc_dst_x_first_range = { 0, 1, 2, 3 };
1623 vector unsigned int vui_inc_dst_x_second_range = { 4, 5, 6, 7 };
1624 vector unsigned int vui_inc_dst_x_third_range = { 8, 9, 10, 11 };
1625 vector unsigned int vui_inc_dst_x_fourth_range = { 12, 13, 14, 15 };
1626 vector unsigned int vui_dst_x_first_range = spu_add( vui_dst_x_tmp, vui_inc_dst_x_first_range );
1627 vector unsigned int vui_dst_x_second_range = spu_add( vui_dst_x_tmp, vui_inc_dst_x_second_range );
1628 vector unsigned int vui_dst_x_third_range = spu_add( vui_dst_x_tmp, vui_inc_dst_x_third_range );
1629 vector unsigned int vui_dst_x_fourth_range = spu_add( vui_dst_x_tmp, vui_inc_dst_x_fourth_range );
1630
1631 // calculate weight EAST-WEST
1632 vector float vf_dst_x_first_range = spu_convtf( vui_dst_x_first_range, 0 );
1633 vector float vf_dst_x_second_range = spu_convtf( vui_dst_x_second_range, 0 );
1634 vector float vf_dst_x_third_range = spu_convtf( vui_dst_x_third_range, 0 );
1635 vector float vf_dst_x_fourth_range = spu_convtf( vui_dst_x_fourth_range, 0 );
1636 vector float vf_src_x_first_range = spu_mul( vf_dst_x_first_range, vf_x_scale );
1637 vector float vf_src_x_second_range = spu_mul( vf_dst_x_second_range, vf_x_scale );
1638 vector float vf_src_x_third_range = spu_mul( vf_dst_x_third_range, vf_x_scale );
1639 vector float vf_src_x_fourth_range = spu_mul( vf_dst_x_fourth_range, vf_x_scale );
1640 vector unsigned int vui_interpl_x_first_range = spu_convtu( vf_src_x_first_range, 0 );
1641 vector unsigned int vui_interpl_x_second_range = spu_convtu( vf_src_x_second_range, 0 );
1642 vector unsigned int vui_interpl_x_third_range = spu_convtu( vf_src_x_third_range, 0 );
1643 vector unsigned int vui_interpl_x_fourth_range = spu_convtu( vf_src_x_fourth_range, 0 );
1644 vector float vf_interpl_x_first_range = spu_convtf( vui_interpl_x_first_range, 0 );
1645 vector float vf_interpl_x_second_range = spu_convtf( vui_interpl_x_second_range, 0 );
1646 vector float vf_interpl_x_third_range = spu_convtf( vui_interpl_x_third_range, 0 );
1647 vector float vf_interpl_x_fourth_range = spu_convtf( vui_interpl_x_fourth_range, 0 );
1648 vector float vf_EWweight_first_range = spu_sub( vf_src_x_first_range, vf_interpl_x_first_range );
1649 vector float vf_EWweight_second_range = spu_sub( vf_src_x_second_range, vf_interpl_x_second_range );
1650 vector float vf_EWweight_third_range = spu_sub( vf_src_x_third_range, vf_interpl_x_third_range );
1651 vector float vf_EWweight_fourth_range = spu_sub( vf_src_x_fourth_range, vf_interpl_x_fourth_range );
1652
1653 // calculate address offset
1654 //
1655 // pixel NORTH WEST
1656 vector unsigned int vui_off_pixelNW_first_range = vui_interpl_x_first_range;
1657 vector unsigned int vui_off_pixelNW_second_range = vui_interpl_x_second_range;
1658 vector unsigned int vui_off_pixelNW_third_range = vui_interpl_x_third_range;
1659 vector unsigned int vui_off_pixelNW_fourth_range = vui_interpl_x_fourth_range;
1660
1661 // pixel NORTH EAST-->(offpixelNW+1)
1662 vector unsigned int vui_add_1 = { 1, 1, 1, 1 };
1663 vector unsigned int vui_off_pixelNE_first_range = spu_add( vui_off_pixelNW_first_range, vui_add_1 );
1664 vector unsigned int vui_off_pixelNE_second_range = spu_add( vui_off_pixelNW_second_range, vui_add_1 );
1665 vector unsigned int vui_off_pixelNE_third_range = spu_add( vui_off_pixelNW_third_range, vui_add_1 );
1666 vector unsigned int vui_off_pixelNE_fourth_range = spu_add( vui_off_pixelNW_fourth_range, vui_add_1 );
1667
1668 // SOUTH-WEST-->(offpixelNW+src_linestride)
1669 vector unsigned int vui_srclinestride = spu_splats( src_linestride );
1670 vector unsigned int vui_off_pixelSW_first_range = spu_add( vui_srclinestride, vui_off_pixelNW_first_range );
1671 vector unsigned int vui_off_pixelSW_second_range = spu_add( vui_srclinestride, vui_off_pixelNW_second_range );
1672 vector unsigned int vui_off_pixelSW_third_range = spu_add( vui_srclinestride, vui_off_pixelNW_third_range );
1673 vector unsigned int vui_off_pixelSW_fourth_range = spu_add( vui_srclinestride, vui_off_pixelNW_fourth_range );
1674
1675 // SOUTH-EAST-->(offpixelNW+src_linestride+1)
1676 vector unsigned int vui_off_pixelSE_first_range = spu_add( vui_srclinestride, vui_off_pixelNE_first_range );
1677 vector unsigned int vui_off_pixelSE_second_range = spu_add( vui_srclinestride, vui_off_pixelNE_second_range );
1678 vector unsigned int vui_off_pixelSE_third_range = spu_add( vui_srclinestride, vui_off_pixelNE_third_range );
1679 vector unsigned int vui_off_pixelSE_fourth_range = spu_add( vui_srclinestride, vui_off_pixelNE_fourth_range );
1680
1681 // calculate each address
1682 vector unsigned int vui_src_ls = spu_splats( (unsigned int) src );
1683 vector unsigned int vui_addr_pixelNW_first_range = spu_add( vui_src_ls, vui_off_pixelNW_first_range );
1684 vector unsigned int vui_addr_pixelNW_second_range = spu_add( vui_src_ls, vui_off_pixelNW_second_range );
1685 vector unsigned int vui_addr_pixelNW_third_range = spu_add( vui_src_ls, vui_off_pixelNW_third_range );
1686 vector unsigned int vui_addr_pixelNW_fourth_range = spu_add( vui_src_ls, vui_off_pixelNW_fourth_range );
1687
1688 vector unsigned int vui_addr_pixelNE_first_range = spu_add( vui_src_ls, vui_off_pixelNE_first_range );
1689 vector unsigned int vui_addr_pixelNE_second_range = spu_add( vui_src_ls, vui_off_pixelNE_second_range );
1690 vector unsigned int vui_addr_pixelNE_third_range = spu_add( vui_src_ls, vui_off_pixelNE_third_range );
1691 vector unsigned int vui_addr_pixelNE_fourth_range = spu_add( vui_src_ls, vui_off_pixelNE_fourth_range );
1692
1693 vector unsigned int vui_addr_pixelSW_first_range = spu_add( vui_src_ls, vui_off_pixelSW_first_range );
1694 vector unsigned int vui_addr_pixelSW_second_range = spu_add( vui_src_ls, vui_off_pixelSW_second_range );
1695 vector unsigned int vui_addr_pixelSW_third_range = spu_add( vui_src_ls, vui_off_pixelSW_third_range );
1696 vector unsigned int vui_addr_pixelSW_fourth_range = spu_add( vui_src_ls, vui_off_pixelSW_fourth_range );
1697
1698 vector unsigned int vui_addr_pixelSE_first_range = spu_add( vui_src_ls, vui_off_pixelSE_first_range );
1699 vector unsigned int vui_addr_pixelSE_second_range = spu_add( vui_src_ls, vui_off_pixelSE_second_range );
1700 vector unsigned int vui_addr_pixelSE_third_range = spu_add( vui_src_ls, vui_off_pixelSE_third_range );
1701 vector unsigned int vui_addr_pixelSE_fourth_range = spu_add( vui_src_ls, vui_off_pixelSE_fourth_range );
1702
1703
1704 // get each pixel
1705 //
1706 // scalar load, afterwards insertion into the right position
1707 // NORTH WEST
1708 // first range
1709 vector unsigned char null_vector = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1710 vector unsigned char vuc_pixel_NW_first_range = spu_insert(
1711 *((unsigned char*) spu_extract( vui_addr_pixelNW_first_range, 0 )), null_vector, 3 );
1712 vuc_pixel_NW_first_range = spu_insert(
1713 *((unsigned char*) spu_extract( vui_addr_pixelNW_first_range, 1 )),
1714 vuc_pixel_NW_first_range, 7 );
1715 vuc_pixel_NW_first_range = spu_insert(
1716 *((unsigned char*) spu_extract( vui_addr_pixelNW_first_range, 2 )),
1717 vuc_pixel_NW_first_range, 11 );
1718 vuc_pixel_NW_first_range = spu_insert(
1719 *((unsigned char*) spu_extract( vui_addr_pixelNW_first_range, 3 )),
1720 vuc_pixel_NW_first_range, 15 );
1721 // second range
1722 vector unsigned char vuc_pixel_NW_second_range = spu_insert(
1723 *((unsigned char*) spu_extract( vui_addr_pixelNW_second_range, 0 )), null_vector, 3 );
1724 vuc_pixel_NW_second_range = spu_insert(
1725 *((unsigned char*) spu_extract( vui_addr_pixelNW_second_range, 1 )),
1726 vuc_pixel_NW_second_range, 7 );
1727 vuc_pixel_NW_second_range = spu_insert(
1728 *((unsigned char*) spu_extract( vui_addr_pixelNW_second_range, 2 )),
1729 vuc_pixel_NW_second_range, 11 );
1730 vuc_pixel_NW_second_range = spu_insert(
1731 *((unsigned char*) spu_extract( vui_addr_pixelNW_second_range, 3 )),
1732 vuc_pixel_NW_second_range, 15 );
1733 // third range
1734 vector unsigned char vuc_pixel_NW_third_range = spu_insert(
1735 *((unsigned char*) spu_extract( vui_addr_pixelNW_third_range, 0 )), null_vector, 3 );
1736 vuc_pixel_NW_third_range = spu_insert(
1737 *((unsigned char*) spu_extract( vui_addr_pixelNW_third_range, 1 )),
1738 vuc_pixel_NW_third_range, 7 );
1739 vuc_pixel_NW_third_range = spu_insert(
1740 *((unsigned char*) spu_extract( vui_addr_pixelNW_third_range, 2 )),
1741 vuc_pixel_NW_third_range, 11 );
1742 vuc_pixel_NW_third_range = spu_insert(
1743 *((unsigned char*) spu_extract( vui_addr_pixelNW_third_range, 3 )),
1744 vuc_pixel_NW_third_range, 15 );
1745 // fourth range
1746 vector unsigned char vuc_pixel_NW_fourth_range = spu_insert(
1747 *((unsigned char*) spu_extract( vui_addr_pixelNW_fourth_range, 0 )), null_vector, 3 );
1748 vuc_pixel_NW_fourth_range = spu_insert(
1749 *((unsigned char*) spu_extract( vui_addr_pixelNW_fourth_range, 1 )),
1750 vuc_pixel_NW_fourth_range, 7 );
1751 vuc_pixel_NW_fourth_range = spu_insert(
1752 *((unsigned char*) spu_extract( vui_addr_pixelNW_fourth_range, 2 )),
1753 vuc_pixel_NW_fourth_range, 11 );
1754 vuc_pixel_NW_fourth_range = spu_insert(
1755 *((unsigned char*) spu_extract( vui_addr_pixelNW_fourth_range, 3 )),
1756 vuc_pixel_NW_fourth_range, 15 );
1757
1758 // NORTH EAST
1759 // first range
1760 vector unsigned char vuc_pixel_NE_first_range = spu_insert(
1761 *((unsigned char*) spu_extract( vui_addr_pixelNE_first_range, 0 )), null_vector, 3 );
1762 vuc_pixel_NE_first_range = spu_insert(
1763 *((unsigned char*) spu_extract( vui_addr_pixelNE_first_range, 1 )),
1764 vuc_pixel_NE_first_range, 7 );
1765 vuc_pixel_NE_first_range = spu_insert(
1766 *((unsigned char*) spu_extract( vui_addr_pixelNE_first_range, 2 )),
1767 vuc_pixel_NE_first_range, 11 );
1768 vuc_pixel_NE_first_range = spu_insert(
1769 *((unsigned char*) spu_extract( vui_addr_pixelNE_first_range, 3 )),
1770 vuc_pixel_NE_first_range, 15 );
1771 // second range
1772 vector unsigned char vuc_pixel_NE_second_range = spu_insert(
1773 *((unsigned char*) spu_extract( vui_addr_pixelNE_second_range, 0 )), null_vector, 3 );
1774 vuc_pixel_NE_second_range = spu_insert(
1775 *((unsigned char*) spu_extract( vui_addr_pixelNE_second_range, 1 )),
1776 vuc_pixel_NE_second_range, 7 );
1777 vuc_pixel_NE_second_range = spu_insert(
1778 *((unsigned char*) spu_extract( vui_addr_pixelNE_second_range, 2 )),
1779 vuc_pixel_NE_second_range, 11 );
1780 vuc_pixel_NE_second_range = spu_insert(
1781 *((unsigned char*) spu_extract( vui_addr_pixelNE_second_range, 3 )),
1782 vuc_pixel_NE_second_range, 15 );
1783 // third range
1784 vector unsigned char vuc_pixel_NE_third_range = spu_insert(
1785 *((unsigned char*) spu_extract( vui_addr_pixelNE_third_range, 0 )), null_vector, 3 );
1786 vuc_pixel_NE_third_range = spu_insert(
1787 *((unsigned char*) spu_extract( vui_addr_pixelNE_third_range, 1 )),
1788 vuc_pixel_NE_third_range, 7 );
1789 vuc_pixel_NE_third_range = spu_insert(
1790 *((unsigned char*) spu_extract( vui_addr_pixelNE_third_range, 2 )),
1791 vuc_pixel_NE_third_range, 11 );
1792 vuc_pixel_NE_third_range = spu_insert(
1793 *((unsigned char*) spu_extract( vui_addr_pixelNE_third_range, 3 )),
1794 vuc_pixel_NE_third_range, 15 );
1795 // fourth range
1796 vector unsigned char vuc_pixel_NE_fourth_range = spu_insert(
1797 *((unsigned char*) spu_extract( vui_addr_pixelNE_fourth_range, 0 )), null_vector, 3 );
1798 vuc_pixel_NE_fourth_range = spu_insert(
1799 *((unsigned char*) spu_extract( vui_addr_pixelNE_fourth_range, 1 )),
1800 vuc_pixel_NE_fourth_range, 7 );
1801 vuc_pixel_NE_fourth_range = spu_insert(
1802 *((unsigned char*) spu_extract( vui_addr_pixelNE_fourth_range, 2 )),
1803 vuc_pixel_NE_fourth_range, 11 );
1804 vuc_pixel_NE_fourth_range = spu_insert(
1805 *((unsigned char*) spu_extract( vui_addr_pixelNE_fourth_range, 3 )),
1806 vuc_pixel_NE_fourth_range, 15 );
1807
1808 // SOUTH WEST
1809 // first range
1810 vector unsigned char vuc_pixel_SW_first_range = spu_insert(
1811 *((unsigned char*) spu_extract( vui_addr_pixelSW_first_range, 0 )), null_vector, 3 );
1812 vuc_pixel_SW_first_range = spu_insert(
1813 *((unsigned char*) spu_extract( vui_addr_pixelSW_first_range, 1 )),
1814 vuc_pixel_SW_first_range, 7 );
1815 vuc_pixel_SW_first_range = spu_insert(
1816 *((unsigned char*) spu_extract( vui_addr_pixelSW_first_range, 2 )),
1817 vuc_pixel_SW_first_range, 11 );
1818 vuc_pixel_SW_first_range = spu_insert(
1819 *((unsigned char*) spu_extract( vui_addr_pixelSW_first_range, 3 )),
1820 vuc_pixel_SW_first_range, 15 );
1821 // second range
1822 vector unsigned char vuc_pixel_SW_second_range = spu_insert(
1823 *((unsigned char*) spu_extract( vui_addr_pixelSW_second_range, 0 )), null_vector, 3 );
1824 vuc_pixel_SW_second_range = spu_insert(
1825 *((unsigned char*) spu_extract( vui_addr_pixelSW_second_range, 1 )),
1826 vuc_pixel_SW_second_range, 7 );
1827 vuc_pixel_SW_second_range = spu_insert(
1828 *((unsigned char*) spu_extract( vui_addr_pixelSW_second_range, 2 )),
1829 vuc_pixel_SW_second_range, 11 );
1830 vuc_pixel_SW_second_range = spu_insert(
1831 *((unsigned char*) spu_extract( vui_addr_pixelSW_second_range, 3 )),
1832 vuc_pixel_SW_second_range, 15 );
1833 // third range
1834 vector unsigned char vuc_pixel_SW_third_range = spu_insert(
1835 *((unsigned char*) spu_extract( vui_addr_pixelSW_third_range, 0 )), null_vector, 3 );
1836 vuc_pixel_SW_third_range = spu_insert(
1837 *((unsigned char*) spu_extract( vui_addr_pixelSW_third_range, 1 )),
1838 vuc_pixel_SW_third_range, 7 );
1839 vuc_pixel_SW_third_range = spu_insert(
1840 *((unsigned char*) spu_extract( vui_addr_pixelSW_third_range, 2 )),
1841 vuc_pixel_SW_third_range, 11 );
1842 vuc_pixel_SW_third_range = spu_insert(
1843 *((unsigned char*) spu_extract( vui_addr_pixelSW_third_range, 3 )),
1844 vuc_pixel_SW_third_range, 15 );
1845 // fourth range
1846 vector unsigned char vuc_pixel_SW_fourth_range = spu_insert(
1847 *((unsigned char*) spu_extract( vui_addr_pixelSW_fourth_range, 0 )), null_vector, 3 );
1848 vuc_pixel_SW_fourth_range = spu_insert(
1849 *((unsigned char*) spu_extract( vui_addr_pixelSW_fourth_range, 1 )),
1850 vuc_pixel_SW_fourth_range, 7 );
1851 vuc_pixel_SW_fourth_range = spu_insert(
1852 *((unsigned char*) spu_extract( vui_addr_pixelSW_fourth_range, 2 )),
1853 vuc_pixel_SW_fourth_range, 11 );
1854 vuc_pixel_SW_fourth_range = spu_insert(
1855 *((unsigned char*) spu_extract( vui_addr_pixelSW_fourth_range, 3 )),
1856 vuc_pixel_SW_fourth_range, 15 );
1857
1858 // NORTH EAST
1859 // first range
1860 vector unsigned char vuc_pixel_SE_first_range = spu_insert(
1861 *((unsigned char*) spu_extract( vui_addr_pixelSE_first_range, 0 )), null_vector, 3 );
1862 vuc_pixel_SE_first_range = spu_insert(
1863 *((unsigned char*) spu_extract( vui_addr_pixelSE_first_range, 1 )),
1864 vuc_pixel_SE_first_range, 7 );
1865 vuc_pixel_SE_first_range = spu_insert(
1866 *((unsigned char*) spu_extract( vui_addr_pixelSE_first_range, 2 )),
1867 vuc_pixel_SE_first_range, 11 );
1868 vuc_pixel_SE_first_range = spu_insert(
1869 *((unsigned char*) spu_extract( vui_addr_pixelSE_first_range, 3 )),
1870 vuc_pixel_SE_first_range, 15 );
1871 // second range
1872 vector unsigned char vuc_pixel_SE_second_range = spu_insert(
1873 *((unsigned char*) spu_extract( vui_addr_pixelSE_second_range, 0 )), null_vector, 3 );
1874 vuc_pixel_SE_second_range = spu_insert(
1875 *((unsigned char*) spu_extract( vui_addr_pixelSE_second_range, 1 )),
1876 vuc_pixel_SE_second_range, 7 );
1877 vuc_pixel_SE_second_range = spu_insert(
1878 *((unsigned char*) spu_extract( vui_addr_pixelSE_second_range, 2 )),
1879 vuc_pixel_SE_second_range, 11 );
1880 vuc_pixel_SE_second_range = spu_insert(
1881 *((unsigned char*) spu_extract( vui_addr_pixelSE_second_range, 3 )),
1882 vuc_pixel_SE_second_range, 15 );
1883 // third range
1884 vector unsigned char vuc_pixel_SE_third_range = spu_insert(
1885 *((unsigned char*) spu_extract( vui_addr_pixelSE_third_range, 0 )), null_vector, 3 );
1886 vuc_pixel_SE_third_range = spu_insert(
1887 *((unsigned char*) spu_extract( vui_addr_pixelSE_third_range, 1 )),
1888 vuc_pixel_SE_third_range, 7 );
1889 vuc_pixel_SE_third_range = spu_insert(
1890 *((unsigned char*) spu_extract( vui_addr_pixelSE_third_range, 2 )),
1891 vuc_pixel_SE_third_range, 11 );
1892 vuc_pixel_SE_third_range = spu_insert(
1893 *((unsigned char*) spu_extract( vui_addr_pixelSE_third_range, 3 )),
1894 vuc_pixel_SE_third_range, 15 );
1895 // fourth range
1896 vector unsigned char vuc_pixel_SE_fourth_range = spu_insert(
1897 *((unsigned char*) spu_extract( vui_addr_pixelSE_fourth_range, 0 )), null_vector, 3 );
1898 vuc_pixel_SE_fourth_range = spu_insert(
1899 *((unsigned char*) spu_extract( vui_addr_pixelSE_fourth_range, 1 )),
1900 vuc_pixel_SE_fourth_range, 7 );
1901 vuc_pixel_SE_fourth_range = spu_insert(
1902 *((unsigned char*) spu_extract( vui_addr_pixelSE_fourth_range, 2 )),
1903 vuc_pixel_SE_fourth_range, 11 );
1904 vuc_pixel_SE_fourth_range = spu_insert(
1905 *((unsigned char*) spu_extract( vui_addr_pixelSE_fourth_range, 3 )),
1906 vuc_pixel_SE_fourth_range, 15 );
1907
1908
1909
1910 // convert to float
1911 vector float vf_pixel_NW_first_range = spu_convtf( (vector unsigned int) vuc_pixel_NW_first_range, 0 );
1912 vector float vf_pixel_NW_second_range = spu_convtf( (vector unsigned int) vuc_pixel_NW_second_range, 0 );
1913 vector float vf_pixel_NW_third_range = spu_convtf( (vector unsigned int) vuc_pixel_NW_third_range, 0 );
1914 vector float vf_pixel_NW_fourth_range = spu_convtf( (vector unsigned int) vuc_pixel_NW_fourth_range, 0 );
1915
1916 vector float vf_pixel_NE_first_range = spu_convtf( (vector unsigned int) vuc_pixel_NE_first_range, 0 );
1917 vector float vf_pixel_NE_second_range = spu_convtf( (vector unsigned int) vuc_pixel_NE_second_range, 0 );
1918 vector float vf_pixel_NE_third_range = spu_convtf( (vector unsigned int) vuc_pixel_NE_third_range, 0 );
1919 vector float vf_pixel_NE_fourth_range = spu_convtf( (vector unsigned int) vuc_pixel_NE_fourth_range, 0 );
1920
1921 vector float vf_pixel_SW_first_range = spu_convtf( (vector unsigned int) vuc_pixel_SW_first_range, 0 );
1922 vector float vf_pixel_SW_second_range = spu_convtf( (vector unsigned int) vuc_pixel_SW_second_range, 0 );
1923 vector float vf_pixel_SW_third_range = spu_convtf( (vector unsigned int) vuc_pixel_SW_third_range, 0 );
1924 vector float vf_pixel_SW_fourth_range = spu_convtf( (vector unsigned int) vuc_pixel_SW_fourth_range, 0 );
1925
1926 vector float vf_pixel_SE_first_range = spu_convtf( (vector unsigned int) vuc_pixel_SE_first_range, 0 );
1927 vector float vf_pixel_SE_second_range = spu_convtf( (vector unsigned int) vuc_pixel_SE_second_range, 0 );
1928 vector float vf_pixel_SE_third_range = spu_convtf( (vector unsigned int) vuc_pixel_SE_third_range, 0 );
1929 vector float vf_pixel_SE_fourth_range = spu_convtf( (vector unsigned int) vuc_pixel_SE_fourth_range, 0 );
1930
1931 // first linear interpolation: EWtop
1932 // EWtop = NW + EWweight*(NE-NW)
1933 //
1934 // first range
1935 vector float vf_EWtop_first_range_tmp = spu_sub( vf_pixel_NE_first_range, vf_pixel_NW_first_range );
1936 vector float vf_EWtop_first_range = spu_madd( vf_EWweight_first_range,
1937 vf_EWtop_first_range_tmp,
1938 vf_pixel_NW_first_range );
1939
1940 // second range
1941 vector float vf_EWtop_second_range_tmp = spu_sub( vf_pixel_NE_second_range, vf_pixel_NW_second_range );
1942 vector float vf_EWtop_second_range = spu_madd( vf_EWweight_second_range,
1943 vf_EWtop_second_range_tmp,
1944 vf_pixel_NW_second_range );
1945
1946 // third range
1947 vector float vf_EWtop_third_range_tmp = spu_sub( vf_pixel_NE_third_range, vf_pixel_NW_third_range );
1948 vector float vf_EWtop_third_range = spu_madd( vf_EWweight_third_range,
1949 vf_EWtop_third_range_tmp,
1950 vf_pixel_NW_third_range );
1951
1952 // fourth range
1953 vector float vf_EWtop_fourth_range_tmp = spu_sub( vf_pixel_NE_fourth_range, vf_pixel_NW_fourth_range );
1954 vector float vf_EWtop_fourth_range = spu_madd( vf_EWweight_fourth_range,
1955 vf_EWtop_fourth_range_tmp,
1956 vf_pixel_NW_fourth_range );
1957
1958
1959
1960 // second linear interpolation: EWbottom
1961 // EWbottom = SW + EWweight*(SE-SW)
1962 //
1963 // first range
1964 vector float vf_EWbottom_first_range_tmp = spu_sub( vf_pixel_SE_first_range, vf_pixel_SW_first_range );
1965 vector float vf_EWbottom_first_range = spu_madd( vf_EWweight_first_range,
1966 vf_EWbottom_first_range_tmp,
1967 vf_pixel_SW_first_range );
1968
1969 // second range
1970 vector float vf_EWbottom_second_range_tmp = spu_sub( vf_pixel_SE_second_range, vf_pixel_SW_second_range );
1971 vector float vf_EWbottom_second_range = spu_madd( vf_EWweight_second_range,
1972 vf_EWbottom_second_range_tmp,
1973 vf_pixel_SW_second_range );
1974 // first range
1975 vector float vf_EWbottom_third_range_tmp = spu_sub( vf_pixel_SE_third_range, vf_pixel_SW_third_range );
1976 vector float vf_EWbottom_third_range = spu_madd( vf_EWweight_third_range,
1977 vf_EWbottom_third_range_tmp,
1978 vf_pixel_SW_third_range );
1979
1980 // first range
1981 vector float vf_EWbottom_fourth_range_tmp = spu_sub( vf_pixel_SE_fourth_range, vf_pixel_SW_fourth_range );
1982 vector float vf_EWbottom_fourth_range = spu_madd( vf_EWweight_fourth_range,
1983 vf_EWbottom_fourth_range_tmp,
1984 vf_pixel_SW_fourth_range );
1985
1986
1987
1988 // third linear interpolation: the bilinear interpolated value
1989 // result = EWtop + NSweight*(EWbottom-EWtop);
1990 //
1991 // first range
1992 vector float vf_result_first_range_tmp = spu_sub( vf_EWbottom_first_range, vf_EWtop_first_range );
1993 vector float vf_result_first_range = spu_madd( vf_NSweight,
1994 vf_result_first_range_tmp,
1995 vf_EWtop_first_range );
1996
1997 // second range
1998 vector float vf_result_second_range_tmp = spu_sub( vf_EWbottom_second_range, vf_EWtop_second_range );
1999 vector float vf_result_second_range = spu_madd( vf_NSweight,
2000 vf_result_second_range_tmp,
2001 vf_EWtop_second_range );
2002
2003 // third range
2004 vector float vf_result_third_range_tmp = spu_sub( vf_EWbottom_third_range, vf_EWtop_third_range );
2005 vector float vf_result_third_range = spu_madd( vf_NSweight,
2006 vf_result_third_range_tmp,
2007 vf_EWtop_third_range );
2008
2009 // fourth range
2010 vector float vf_result_fourth_range_tmp = spu_sub( vf_EWbottom_fourth_range, vf_EWtop_fourth_range );
2011 vector float vf_result_fourth_range = spu_madd( vf_NSweight,
2012 vf_result_fourth_range_tmp,
2013 vf_EWtop_fourth_range );
2014
2015
2016
2017 // convert back: using saturated arithmetic
2018 vector unsigned int vui_result_first_range = vfloat_to_vuint( vf_result_first_range );
2019 vector unsigned int vui_result_second_range = vfloat_to_vuint( vf_result_second_range );
2020 vector unsigned int vui_result_third_range = vfloat_to_vuint( vf_result_third_range );
2021 vector unsigned int vui_result_fourth_range = vfloat_to_vuint( vf_result_fourth_range );
2022
2023 // merge results->lower,upper
2024 vector unsigned char vuc_mask_merge_result_first_second = { 0x03, 0x07, 0x0B, 0x0F,
2025 0x13, 0x17, 0x1B, 0x1F,
2026 0x00, 0x00, 0x00, 0x00,
2027 0x00, 0x00, 0x00, 0x00 };
2028
2029 vector unsigned char vuc_mask_merge_result_third_fourth = { 0x00, 0x00, 0x00, 0x00,
2030 0x00, 0x00, 0x00, 0x00,
2031 0x03, 0x07, 0x0B, 0x0F,
2032 0x13, 0x17, 0x1B, 0x1F };
2033
2034 vector unsigned char vuc_result_first_second =
2035 spu_shuffle( (vector unsigned char) vui_result_first_range,
2036 (vector unsigned char) vui_result_second_range,
2037 vuc_mask_merge_result_first_second );
2038
2039 vector unsigned char vuc_result_third_fourth =
2040 spu_shuffle( (vector unsigned char) vui_result_third_range,
2041 (vector unsigned char) vui_result_fourth_range,
2042 vuc_mask_merge_result_third_fourth );
2043
2044 // store result
2045 *((vector unsigned char*)dst) = spu_or( vuc_result_first_second,
2046 vuc_result_third_fourth );
2047 dst += 16;
2048 }
2049}
2050
diff --git a/apps/plugins/sdl/src/video/ps3/spulibs/fb_writer.c b/apps/plugins/sdl/src/video/ps3/spulibs/fb_writer.c
deleted file mode 100644
index 0eb51cc682..0000000000
--- a/apps/plugins/sdl/src/video/ps3/spulibs/fb_writer.c
+++ /dev/null
@@ -1,193 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28#include "spu_common.h"
29
30#include <spu_intrinsics.h>
31#include <spu_mfcio.h>
32#include <stdio.h>
33#include <string.h>
34
35// Debugging
36//#define DEBUG
37
38#ifdef DEBUG
39#define deprintf(fmt, args... ) \
40 fprintf( stdout, fmt, ##args ); \
41 fflush( stdout );
42#else
43#define deprintf( fmt, args... )
44#endif
45
46void cpy_to_fb(unsigned int);
47
48/* fb_writer_spu parms */
49static volatile struct fb_writer_parms_t parms __attribute__ ((aligned(128)));
50
51/* Code running on SPU */
52int main(unsigned long long spe_id __attribute__ ((unused)), unsigned long long argp __attribute__ ((unused)))
53{
54 deprintf("[SPU] fb_writer_spu is up... (on SPE #%llu)\n", spe_id);
55 uint32_t ea_mfc, mbox;
56 // send ready message
57 spu_write_out_mbox(SPU_READY);
58
59 while (1) {
60 /* Check mailbox */
61 mbox = spu_read_in_mbox();
62 deprintf("[SPU] Message is %u\n", mbox);
63 switch (mbox) {
64 case SPU_EXIT:
65 deprintf("[SPU] fb_writer goes down...\n");
66 return 0;
67 case SPU_START:
68 break;
69 default:
70 deprintf("[SPU] Cannot handle message\n");
71 continue;
72 }
73
74 /* Tag Manager setup */
75 unsigned int tags;
76 tags = mfc_multi_tag_reserve(5);
77 if (tags == MFC_TAG_INVALID) {
78 deprintf("[SPU] Failed to reserve mfc tags on fb_writer\n");
79 return 0;
80 }
81
82 /* Framebuffer parms */
83 ea_mfc = spu_read_in_mbox();
84 deprintf("[SPU] Message on fb_writer is %u\n", ea_mfc);
85 spu_mfcdma32(&parms, (unsigned int)ea_mfc,
86 sizeof(struct fb_writer_parms_t), tags,
87 MFC_GET_CMD);
88 deprintf("[SPU] argp = %u\n", (unsigned int)argp);
89 DMA_WAIT_TAG(tags);
90
91 /* Copy parms->data to framebuffer */
92 deprintf("[SPU] Copying to framebuffer started\n");
93 cpy_to_fb(tags);
94 deprintf("[SPU] Copying to framebuffer done!\n");
95
96 mfc_multi_tag_release(tags, 5);
97 deprintf("[SPU] fb_writer_spu... done!\n");
98 /* Send FIN msg */
99 spu_write_out_mbox(SPU_FIN);
100 }
101
102 return 0;
103}
104
105void cpy_to_fb(unsigned int tag_id_base)
106{
107 unsigned int i;
108 unsigned char current_buf;
109 uint8_t *in = parms.data;
110
111 /* Align fb pointer which was centered before */
112 uint8_t *fb =
113 (unsigned char *)((unsigned int)parms.center & 0xFFFFFFF0);
114
115 uint32_t bounded_input_height = parms.bounded_input_height;
116 uint32_t bounded_input_width = parms.bounded_input_width;
117 uint32_t fb_pixel_size = parms.fb_pixel_size;
118
119 uint32_t out_line_stride = parms.out_line_stride;
120 uint32_t in_line_stride = parms.in_line_stride;
121 uint32_t in_line_size = bounded_input_width * fb_pixel_size;
122
123 current_buf = 0;
124
125 /* Local store buffer */
126 static volatile uint8_t buf[4][BUFFER_SIZE]
127 __attribute__ ((aligned(128)));
128 /* do 4-times multibuffering using DMA list, process in two steps */
129 for (i = 0; i < bounded_input_height >> 2; i++) {
130 /* first buffer */
131 DMA_WAIT_TAG(tag_id_base + 1);
132 // retrieve buffer
133 spu_mfcdma32(buf[0], (unsigned int)in, in_line_size,
134 tag_id_base + 1, MFC_GETB_CMD);
135 DMA_WAIT_TAG(tag_id_base + 1);
136 // store buffer
137 spu_mfcdma32(buf[0], (unsigned int)fb, in_line_size,
138 tag_id_base + 1, MFC_PUTB_CMD);
139 in += in_line_stride;
140 fb += out_line_stride;
141 deprintf("[SPU] 1st buffer copied in=0x%x, fb=0x%x\n", in,
142 fb);
143
144 /* second buffer */
145 DMA_WAIT_TAG(tag_id_base + 2);
146 // retrieve buffer
147 spu_mfcdma32(buf[1], (unsigned int)in, in_line_size,
148 tag_id_base + 2, MFC_GETB_CMD);
149 DMA_WAIT_TAG(tag_id_base + 2);
150 // store buffer
151 spu_mfcdma32(buf[1], (unsigned int)fb, in_line_size,
152 tag_id_base + 2, MFC_PUTB_CMD);
153 in += in_line_stride;
154 fb += out_line_stride;
155 deprintf("[SPU] 2nd buffer copied in=0x%x, fb=0x%x\n", in,
156 fb);
157
158 /* third buffer */
159 DMA_WAIT_TAG(tag_id_base + 3);
160 // retrieve buffer
161 spu_mfcdma32(buf[2], (unsigned int)in, in_line_size,
162 tag_id_base + 3, MFC_GETB_CMD);
163 DMA_WAIT_TAG(tag_id_base + 3);
164 // store buffer
165 spu_mfcdma32(buf[2], (unsigned int)fb, in_line_size,
166 tag_id_base + 3, MFC_PUTB_CMD);
167 in += in_line_stride;
168 fb += out_line_stride;
169 deprintf("[SPU] 3rd buffer copied in=0x%x, fb=0x%x\n", in,
170 fb);
171
172 /* fourth buffer */
173 DMA_WAIT_TAG(tag_id_base + 4);
174 // retrieve buffer
175 spu_mfcdma32(buf[3], (unsigned int)in, in_line_size,
176 tag_id_base + 4, MFC_GETB_CMD);
177 DMA_WAIT_TAG(tag_id_base + 4);
178 // store buffer
179 spu_mfcdma32(buf[3], (unsigned int)fb, in_line_size,
180 tag_id_base + 4, MFC_PUTB_CMD);
181 in += in_line_stride;
182 fb += out_line_stride;
183 deprintf("[SPU] 4th buffer copied in=0x%x, fb=0x%x\n", in,
184 fb);
185 deprintf("[SPU] Loop #%i, bounded_input_height=%i\n", i,
186 bounded_input_height >> 2);
187 }
188 DMA_WAIT_TAG(tag_id_base + 2);
189 DMA_WAIT_TAG(tag_id_base + 3);
190 DMA_WAIT_TAG(tag_id_base + 4);
191}
192
193
diff --git a/apps/plugins/sdl/src/video/ps3/spulibs/spu_common.h b/apps/plugins/sdl/src/video/ps3/spulibs/spu_common.h
deleted file mode 100644
index 42c328c83d..0000000000
--- a/apps/plugins/sdl/src/video/ps3/spulibs/spu_common.h
+++ /dev/null
@@ -1,108 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28/* Common definitions/makros for SPUs */
29
30#ifndef _SPU_COMMON_H
31#define _SPU_COMMON_H
32
33#include <stdio.h>
34#include <stdint.h>
35#include <string.h>
36
37/* Tag management */
38#define DMA_WAIT_TAG(_tag) \
39 mfc_write_tag_mask(1<<(_tag)); \
40 mfc_read_tag_status_all();
41
42/* SPU mailbox messages */
43#define SPU_READY 0
44#define SPU_START 1
45#define SPU_FIN 2
46#define SPU_EXIT 3
47
48/* Tags */
49#define RETR_BUF 0
50#define STR_BUF 1
51#define TAG_INIT 2
52
53/* Buffersizes */
54#define MAX_HDTV_WIDTH 1920
55#define MAX_HDTV_HEIGHT 1080
56/* One stride of HDTV */
57#define BUFFER_SIZE 7680
58
59/* fb_writer ppu/spu exchange parms */
60struct fb_writer_parms_t {
61 uint8_t *data;
62 uint8_t *center;
63 uint32_t out_line_stride;
64 uint32_t in_line_stride;
65 uint32_t bounded_input_height;
66 uint32_t bounded_input_width;
67 uint32_t fb_pixel_size;
68
69 /* This padding is to fulfill the need for 16 byte alignment. On parm change, update! */
70 char padding[4];
71} __attribute__((aligned(128)));
72
73/* yuv2rgb ppu/spu exchange parms */
74struct yuv2rgb_parms_t {
75 uint8_t* y_plane;
76 uint8_t* v_plane;
77 uint8_t* u_plane;
78
79 uint8_t* dstBuffer;
80
81 unsigned int src_pixel_width;
82 unsigned int src_pixel_height;
83
84 /* This padding is to fulfill the need for 16 byte alignment. On parm change, update! */
85 char padding[128 - ((4 * sizeof(uint8_t *) + 2 * sizeof(unsigned int)) & 0x7F)];
86} __attribute__((aligned(128)));
87
88/* bilin_scaler ppu/spu exchange parms */
89struct scale_parms_t {
90 uint8_t* y_plane;
91 uint8_t* v_plane;
92 uint8_t* u_plane;
93
94 uint8_t* dstBuffer;
95
96 unsigned int src_pixel_width;
97 unsigned int src_pixel_height;
98
99 unsigned int dst_pixel_width;
100 unsigned int dst_pixel_height;
101
102 /* This padding is to fulfill the need for 16 byte alignment. On parm change, update! */
103 char padding[128 - ((4 * sizeof(uint8_t *) + 4 * sizeof(unsigned int)) & 0x7F)];
104} __attribute__((aligned(128)));
105
106#endif /* _SPU_COMMON_H */
107
108
diff --git a/apps/plugins/sdl/src/video/ps3/spulibs/yuv2rgb_converter.c b/apps/plugins/sdl/src/video/ps3/spulibs/yuv2rgb_converter.c
deleted file mode 100644
index 5e166914c5..0000000000
--- a/apps/plugins/sdl/src/video/ps3/spulibs/yuv2rgb_converter.c
+++ /dev/null
@@ -1,629 +0,0 @@
1/*
2 * SDL - Simple DirectMedia Layer
3 * CELL BE Support for PS3 Framebuffer
4 * Copyright (C) 2008, 2009 International Business Machines Corporation
5 *
6 * This library is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 *
21 * Martin Lowinski <lowinski [at] de [dot] ibm [ibm] com>
22 * Dirk Herrendoerfer <d.herrendoerfer [at] de [dot] ibm [dot] com>
23 * SPE code based on research by:
24 * Rene Becker
25 * Thimo Emmerich
26 */
27
28#include "spu_common.h"
29
30#include <spu_intrinsics.h>
31#include <spu_mfcio.h>
32
33// Debugging
34//#define DEBUG
35
36#ifdef DEBUG
37#define deprintf(fmt, args... ) \
38 fprintf( stdout, fmt, ##args ); \
39 fflush( stdout );
40#else
41#define deprintf( fmt, args... )
42#endif
43
44struct yuv2rgb_parms_t parms_converter __attribute__((aligned(128)));
45
46/* A maximum of 8 lines Y, therefore 4 lines V, 4 lines U are stored
47 * there might be the need to retrieve misaligned data, adjust
48 * incoming v and u plane to be able to handle this (add 128)
49 */
50unsigned char y_plane[2][(MAX_HDTV_WIDTH + 128) * 4] __attribute__((aligned(128)));
51unsigned char v_plane[2][(MAX_HDTV_WIDTH + 128) * 2] __attribute__((aligned(128)));
52unsigned char u_plane[2][(MAX_HDTV_WIDTH + 128) * 2] __attribute__((aligned(128)));
53
54/* A maximum of 4 lines BGRA are stored, 4 byte per pixel */
55unsigned char bgra[4 * MAX_HDTV_WIDTH * 4] __attribute__((aligned(128)));
56
57/* some vectors needed by the float to int conversion */
58static const vector float vec_255 = { 255.0f, 255.0f, 255.0f, 255.0f };
59static const vector float vec_0_1 = { 0.1f, 0.1f, 0.1f, 0.1f };
60
61void yuv_to_rgb_w16();
62void yuv_to_rgb_w32();
63
64void yuv_to_rgb_w16_line(unsigned char* y_addr, unsigned char* v_addr, unsigned char* u_addr, unsigned char* bgra_addr, unsigned int width);
65void yuv_to_rgb_w32_line(unsigned char* y_addr, unsigned char* v_addr, unsigned char* u_addr, unsigned char* bgra_addr_, unsigned int width);
66
67
68int main(unsigned long long spe_id __attribute__((unused)), unsigned long long argp __attribute__ ((unused)))
69{
70 deprintf("[SPU] yuv2rgb_spu is up... (on SPE #%llu)\n", spe_id);
71 uint32_t ea_mfc, mbox;
72 // send ready message
73 spu_write_out_mbox(SPU_READY);
74
75 while (1) {
76 /* Check mailbox */
77 mbox = spu_read_in_mbox();
78 deprintf("[SPU] Message is %u\n", mbox);
79 switch (mbox) {
80 case SPU_EXIT:
81 deprintf("[SPU] fb_writer goes down...\n");
82 return 0;
83 case SPU_START:
84 break;
85 default:
86 deprintf("[SPU] Cannot handle message\n");
87 continue;
88 }
89
90 /* Tag Manager setup */
91 unsigned int tag_id;
92 tag_id = mfc_multi_tag_reserve(1);
93 if (tag_id == MFC_TAG_INVALID) {
94 deprintf("[SPU] Failed to reserve mfc tags on yuv2rgb_converter\n");
95 return 0;
96 }
97
98 /* DMA transfer for the input parameters */
99 ea_mfc = spu_read_in_mbox();
100 deprintf("[SPU] Message on yuv2rgb_converter is %u\n", ea_mfc);
101 spu_mfcdma32(&parms_converter, (unsigned int)ea_mfc, sizeof(struct yuv2rgb_parms_t), tag_id, MFC_GET_CMD);
102 DMA_WAIT_TAG(tag_id);
103
104 /* There are alignment issues that involve handling of special cases
105 * a width of 32 results in a width of 16 in the chrominance
106 * --> choose the proper handling to optimize the performance
107 */
108 deprintf("[SPU] Convert %ix%i from YUV to RGB\n", parms_converter.src_pixel_width, parms_converter.src_pixel_height);
109 if (parms_converter.src_pixel_width & 0x1f) {
110 deprintf("[SPU] Using yuv_to_rgb_w16\n");
111 yuv_to_rgb_w16();
112 } else {
113 deprintf("[SPU] Using yuv_to_rgb_w32\n");
114 yuv_to_rgb_w32();
115 }
116
117 mfc_multi_tag_release(tag_id, 1);
118 deprintf("[SPU] yuv2rgb_spu... done!\n");
119 /* Send FIN message */
120 spu_write_out_mbox(SPU_FIN);
121 }
122
123 return 0;
124}
125
126
127/*
128 * float_to_char()
129 *
130 * converts a float to a character using saturated
131 * arithmetic
132 *
133 * @param s float for conversion
134 * @returns converted character
135 */
136inline static unsigned char float_to_char(float s) {
137 vector float vec_s = spu_splats(s);
138 vector unsigned int select_1 = spu_cmpgt(vec_0_1, vec_s);
139 vec_s = spu_sel(vec_s, vec_0_1, select_1);
140
141 vector unsigned int select_2 = spu_cmpgt(vec_s, vec_255);
142 vec_s = spu_sel(vec_s, vec_255, select_2);
143 return (unsigned char) spu_extract(vec_s,0);
144}
145
146
147/*
148 * vfloat_to_vuint()
149 *
150 * converts a float vector to an unsinged int vector using saturated
151 * arithmetic
152 *
153 * @param vec_s float vector for conversion
154 * @returns converted unsigned int vector
155 */
156inline static vector unsigned int vfloat_to_vuint(vector float vec_s) {
157 vector unsigned int select_1 = spu_cmpgt(vec_0_1, vec_s);
158 vec_s = spu_sel(vec_s, vec_0_1, select_1);
159
160 vector unsigned int select_2 = spu_cmpgt(vec_s, vec_255);
161 vec_s = spu_sel(vec_s, vec_255, select_2);
162 return spu_convtu(vec_s,0);
163}
164
165
166void yuv_to_rgb_w16() {
167 // Pixel dimensions of the picture
168 uint32_t width, height;
169
170 // Extract parameters
171 width = parms_converter.src_pixel_width;
172 height = parms_converter.src_pixel_height;
173
174 // Plane data management
175 // Y
176 unsigned char* ram_addr_y = parms_converter.y_plane;
177 // V
178 unsigned char* ram_addr_v = parms_converter.v_plane;
179 // U
180 unsigned char* ram_addr_u = parms_converter.u_plane;
181
182 // BGRA
183 unsigned char* ram_addr_bgra = parms_converter.dstBuffer;
184
185 // Strides
186 unsigned int stride_y = width;
187 unsigned int stride_vu = width>>1;
188
189 // Buffer management
190 unsigned int buf_idx = 0;
191 unsigned int size_4lines_y = stride_y<<2;
192 unsigned int size_2lines_y = stride_y<<1;
193 unsigned int size_2lines_vu = stride_vu<<1;
194
195 // 2*width*4byte_per_pixel
196 unsigned int size_2lines_bgra = width<<3;
197
198
199 // start double-buffered processing
200 // 4 lines y
201 spu_mfcdma32(y_plane[buf_idx], (unsigned int) ram_addr_y, size_4lines_y, RETR_BUF+buf_idx, MFC_GET_CMD);
202
203 // 2 lines v
204 spu_mfcdma32(v_plane[buf_idx], (unsigned int) ram_addr_v, size_2lines_vu, RETR_BUF+buf_idx, MFC_GET_CMD);
205
206 // 2 lines u
207 spu_mfcdma32(u_plane[buf_idx], (unsigned int) ram_addr_u, size_2lines_vu, RETR_BUF+buf_idx, MFC_GET_CMD);
208
209 // Wait for these transfers to be completed
210 DMA_WAIT_TAG((RETR_BUF + buf_idx));
211
212 unsigned int i;
213 for(i=0; i<(height>>2)-1; i++) {
214
215 buf_idx^=1;
216
217 // 4 lines y
218 spu_mfcdma32(y_plane[buf_idx], (unsigned int) ram_addr_y+size_4lines_y, size_4lines_y, RETR_BUF+buf_idx, MFC_GET_CMD);
219
220 // 2 lines v
221 spu_mfcdma32(v_plane[buf_idx], (unsigned int) ram_addr_v+size_2lines_vu, size_2lines_vu, RETR_BUF+buf_idx, MFC_GET_CMD);
222
223 // 2 lines u
224 spu_mfcdma32(u_plane[buf_idx], (unsigned int) ram_addr_u+size_2lines_vu, size_2lines_vu, RETR_BUF+buf_idx, MFC_GET_CMD);
225
226 DMA_WAIT_TAG((RETR_BUF + buf_idx));
227
228 buf_idx^=1;
229
230
231 // Convert YUV to BGRA, store it back (first two lines)
232 yuv_to_rgb_w16_line(y_plane[buf_idx], v_plane[buf_idx], u_plane[buf_idx], bgra, width);
233
234 // Next two lines
235 yuv_to_rgb_w16_line(y_plane[buf_idx] + size_2lines_y,
236 v_plane[buf_idx] + stride_vu,
237 u_plane[buf_idx] + stride_vu,
238 bgra + size_2lines_bgra,
239 width);
240
241 // Wait for previous storing transfer to be completed
242 DMA_WAIT_TAG(STR_BUF);
243
244 // Store converted lines in two steps->max transfer size 16384
245 spu_mfcdma32(bgra, (unsigned int) ram_addr_bgra, size_2lines_bgra, STR_BUF, MFC_PUT_CMD);
246 ram_addr_bgra += size_2lines_bgra;
247 spu_mfcdma32(bgra+size_2lines_bgra, (unsigned int) ram_addr_bgra, size_2lines_bgra, STR_BUF, MFC_PUT_CMD);
248 ram_addr_bgra += size_2lines_bgra;
249
250 // Move 4 lines
251 ram_addr_y += size_4lines_y;
252 ram_addr_v += size_2lines_vu;
253 ram_addr_u += size_2lines_vu;
254
255 buf_idx^=1;
256 }
257
258 // Convert YUV to BGRA, store it back (first two lines)
259 yuv_to_rgb_w16_line(y_plane[buf_idx], v_plane[buf_idx], u_plane[buf_idx], bgra, width);
260
261 // Next two lines
262 yuv_to_rgb_w16_line(y_plane[buf_idx] + size_2lines_y,
263 v_plane[buf_idx] + stride_vu,
264 u_plane[buf_idx] + stride_vu,
265 bgra + size_2lines_bgra,
266 width);
267
268 // Wait for previous storing transfer to be completed
269 DMA_WAIT_TAG(STR_BUF);
270 spu_mfcdma32(bgra, (unsigned int) ram_addr_bgra, size_2lines_bgra, STR_BUF, MFC_PUT_CMD);
271 ram_addr_bgra += size_2lines_bgra;
272 spu_mfcdma32(bgra+size_2lines_bgra, (unsigned int) ram_addr_bgra, size_2lines_bgra, STR_BUF, MFC_PUT_CMD);
273
274 // wait for previous storing transfer to be completed
275 DMA_WAIT_TAG(STR_BUF);
276
277}
278
279
280void yuv_to_rgb_w32() {
281 // Pixel dimensions of the picture
282 uint32_t width, height;
283
284 // Extract parameters
285 width = parms_converter.src_pixel_width;
286 height = parms_converter.src_pixel_height;
287
288 // Plane data management
289 // Y
290 unsigned char* ram_addr_y = parms_converter.y_plane;
291 // V
292 unsigned char* ram_addr_v = parms_converter.v_plane;
293 // U
294 unsigned char* ram_addr_u = parms_converter.u_plane;
295
296 // BGRA
297 unsigned char* ram_addr_bgra = parms_converter.dstBuffer;
298
299 // Strides
300 unsigned int stride_y = width;
301 unsigned int stride_vu = width>>1;
302
303 // Buffer management
304 unsigned int buf_idx = 0;
305 unsigned int size_4lines_y = stride_y<<2;
306 unsigned int size_2lines_y = stride_y<<1;
307 unsigned int size_2lines_vu = stride_vu<<1;
308
309 // 2*width*4byte_per_pixel
310 unsigned int size_2lines_bgra = width<<3;
311
312 // start double-buffered processing
313 // 4 lines y
314 spu_mfcdma32(y_plane[buf_idx], (unsigned int) ram_addr_y, size_4lines_y, RETR_BUF + buf_idx, MFC_GET_CMD);
315 // 2 lines v
316 spu_mfcdma32(v_plane[buf_idx], (unsigned int) ram_addr_v, size_2lines_vu, RETR_BUF + buf_idx, MFC_GET_CMD);
317 // 2 lines u
318 spu_mfcdma32(u_plane[buf_idx], (unsigned int) ram_addr_u, size_2lines_vu, RETR_BUF + buf_idx, MFC_GET_CMD);
319
320 // Wait for these transfers to be completed
321 DMA_WAIT_TAG((RETR_BUF + buf_idx));
322
323 unsigned int i;
324 for(i=0; i < (height>>2)-1; i++) {
325 buf_idx^=1;
326 // 4 lines y
327 spu_mfcdma32(y_plane[buf_idx], (unsigned int) ram_addr_y+size_4lines_y, size_4lines_y, RETR_BUF + buf_idx, MFC_GET_CMD);
328 deprintf("4lines = %d\n", size_4lines_y);
329 // 2 lines v
330 spu_mfcdma32(v_plane[buf_idx], (unsigned int) ram_addr_v+size_2lines_vu, size_2lines_vu, RETR_BUF + buf_idx, MFC_GET_CMD);
331 deprintf("2lines = %d\n", size_2lines_vu);
332 // 2 lines u
333 spu_mfcdma32(u_plane[buf_idx], (unsigned int) ram_addr_u+size_2lines_vu, size_2lines_vu, RETR_BUF + buf_idx, MFC_GET_CMD);
334 deprintf("2lines = %d\n", size_2lines_vu);
335
336 DMA_WAIT_TAG((RETR_BUF + buf_idx));
337
338 buf_idx^=1;
339
340 // Convert YUV to BGRA, store it back (first two lines)
341 yuv_to_rgb_w32_line(y_plane[buf_idx], v_plane[buf_idx], u_plane[buf_idx], bgra, width);
342
343 // Next two lines
344 yuv_to_rgb_w32_line(y_plane[buf_idx] + size_2lines_y,
345 v_plane[buf_idx] + stride_vu,
346 u_plane[buf_idx] + stride_vu,
347 bgra + size_2lines_bgra,
348 width);
349
350 // Wait for previous storing transfer to be completed
351 DMA_WAIT_TAG(STR_BUF);
352
353 // Store converted lines in two steps->max transfer size 16384
354 spu_mfcdma32(bgra, (unsigned int)ram_addr_bgra, size_2lines_bgra, STR_BUF, MFC_PUT_CMD);
355 ram_addr_bgra += size_2lines_bgra;
356 spu_mfcdma32(bgra + size_2lines_bgra, (unsigned int)ram_addr_bgra, size_2lines_bgra, STR_BUF, MFC_PUT_CMD);
357 ram_addr_bgra += size_2lines_bgra;
358
359 // Move 4 lines
360 ram_addr_y += size_4lines_y;
361 ram_addr_v += size_2lines_vu;
362 ram_addr_u += size_2lines_vu;
363
364 buf_idx^=1;
365 }
366
367 // Convert YUV to BGRA, store it back (first two lines)
368 yuv_to_rgb_w32_line(y_plane[buf_idx], v_plane[buf_idx], u_plane[buf_idx], bgra, width);
369
370 // Next two lines
371 yuv_to_rgb_w32_line(y_plane[buf_idx] + size_2lines_y,
372 v_plane[buf_idx] + stride_vu,
373 u_plane[buf_idx] + stride_vu,
374 bgra + size_2lines_bgra,
375 width);
376
377 // Wait for previous storing transfer to be completed
378 DMA_WAIT_TAG(STR_BUF);
379 spu_mfcdma32(bgra, (unsigned int) ram_addr_bgra, size_2lines_bgra, STR_BUF, MFC_PUT_CMD);
380 ram_addr_bgra += size_2lines_bgra;
381 spu_mfcdma32(bgra + size_2lines_bgra, (unsigned int) ram_addr_bgra, size_2lines_bgra, STR_BUF, MFC_PUT_CMD);
382
383 // Wait for previous storing transfer to be completed
384 DMA_WAIT_TAG(STR_BUF);
385}
386
387
388/* Some vectors needed by the yuv 2 rgb conversion algorithm */
389const vector float vec_minus_128 = { -128.0f, -128.0f, -128.0f, -128.0f };
390const vector unsigned char vec_null = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
391const vector unsigned char vec_char2int_first = { 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x13 };
392const vector unsigned char vec_char2int_second = { 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17 };
393const vector unsigned char vec_char2int_third = { 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0x1A, 0x00, 0x00, 0x00, 0x1B };
394const vector unsigned char vec_char2int_fourth = { 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x1F };
395
396const vector float vec_R_precalc_coeff = {1.403f, 1.403f, 1.403f, 1.403f};
397const vector float vec_Gu_precalc_coeff = {-0.344f, -0.344f, -0.344f, -0.344f};
398const vector float vec_Gv_precalc_coeff = {-0.714f, -0.714f, -0.714f, -0.714f};
399const vector float vec_B_precalc_coeff = {1.773f, 1.773f, 1.773f, 1.773f};
400
401const vector unsigned int vec_alpha = { 255 << 24, 255 << 24, 255 << 24, 255 << 24 };
402
403const vector unsigned char vec_select_floats_upper = { 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x04, 0x05, 0x06, 0x07 };
404const vector unsigned char vec_select_floats_lower = { 0x08, 0x09, 0x0A, 0x0B, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x0C, 0x0D, 0x0E, 0x0F };
405
406
407/*
408 * yuv_to_rgb_w16()
409 *
410 * processes to line of yuv-input, width has to be a multiple of 16
411 * two lines of yuv are taken as input
412 *
413 * @param y_addr address of the y plane in local store
414 * @param v_addr address of the v plane in local store
415 * @param u_addr address of the u plane in local store
416 * @param bgra_addr_ address of the bgra output buffer
417 * @param width the width in pixel
418 */
419void yuv_to_rgb_w16_line(unsigned char* y_addr, unsigned char* v_addr, unsigned char* u_addr, unsigned char* bgra_addr_, unsigned int width) {
420 // each pixel is stored as an integer
421 unsigned int* bgra_addr = (unsigned int*) bgra_addr_;
422
423 unsigned int x;
424 for(x = 0; x < width; x+=2) {
425 // Gehe zweischrittig durch die zeile, da jeder u und v wert fuer 4 pixel(zwei hoch, zwei breit) gilt
426 const unsigned char Y_1 = *(y_addr + x);
427 const unsigned char Y_2 = *(y_addr + x + 1);
428 const unsigned char Y_3 = *(y_addr + x + width);
429 const unsigned char Y_4 = *(y_addr + x + width + 1);
430 const unsigned char U = *(u_addr + (x >> 1));
431 const unsigned char V = *(v_addr + (x >> 1));
432
433 float V_minus_128 = (float)((float)V - 128.0f);
434 float U_minus_128 = (float)((float)U - 128.0f);
435
436 float R_precalculate = 1.403f * V_minus_128;
437 float G_precalculate = -(0.344f * U_minus_128 + 0.714f * V_minus_128);
438 float B_precalculate = 1.773f * U_minus_128;
439
440 const unsigned char R_1 = float_to_char((Y_1 + R_precalculate));
441 const unsigned char R_2 = float_to_char((Y_2 + R_precalculate));
442 const unsigned char R_3 = float_to_char((Y_3 + R_precalculate));
443 const unsigned char R_4 = float_to_char((Y_4 + R_precalculate));
444 const unsigned char G_1 = float_to_char((Y_1 + G_precalculate));
445 const unsigned char G_2 = float_to_char((Y_2 + G_precalculate));
446 const unsigned char G_3 = float_to_char((Y_3 + G_precalculate));
447 const unsigned char G_4 = float_to_char((Y_4 + G_precalculate));
448 const unsigned char B_1 = float_to_char((Y_1 + B_precalculate));
449 const unsigned char B_2 = float_to_char((Y_2 + B_precalculate));
450 const unsigned char B_3 = float_to_char((Y_3 + B_precalculate));
451 const unsigned char B_4 = float_to_char((Y_4 + B_precalculate));
452
453 *(bgra_addr + x) = (B_1 << 0)| (G_1 << 8) | (R_1 << 16) | (255 << 24);
454 *(bgra_addr + x + 1) = (B_2 << 0)| (G_2 << 8) | (R_2 << 16) | (255 << 24);
455 *(bgra_addr + x + width) = (B_3 << 0)| (G_3 << 8) | (R_3 << 16) | (255 << 24);
456 *(bgra_addr + x + width + 1) = (B_4 << 0)| (G_4 << 8) | (R_4 << 16) | (255 << 24);
457 }
458}
459
460
461/*
462 * yuv_to_rgb_w32()
463 *
464 * processes to line of yuv-input, width has to be a multiple of 32
465 * two lines of yuv are taken as input
466 *
467 * @param y_addr address of the y plane in local store
468 * @param v_addr address of the v plane in local store
469 * @param u_addr address of the u plane in local store
470 * @param bgra_addr_ address of the bgra output buffer
471 * @param width the width in pixel
472 */
473void yuv_to_rgb_w32_line(unsigned char* y_addr, unsigned char* v_addr, unsigned char* u_addr, unsigned char* bgra_addr_, unsigned int width) {
474 // each pixel is stored as an integer
475 unsigned int* bgra_addr = (unsigned int*) bgra_addr_;
476
477 unsigned int x;
478 for(x = 0; x < width; x+=32) {
479 // Gehe zweischrittig durch die zeile, da jeder u und v wert fuer 4 pixel(zwei hoch, zwei breit) gilt
480
481 const vector unsigned char vchar_Y_1 = *((vector unsigned char*)(y_addr + x));
482 const vector unsigned char vchar_Y_2 = *((vector unsigned char*)(y_addr + x + 16));
483 const vector unsigned char vchar_Y_3 = *((vector unsigned char*)(y_addr + x + width));
484 const vector unsigned char vchar_Y_4 = *((vector unsigned char*)(y_addr + x + width + 16));
485 const vector unsigned char vchar_U = *((vector unsigned char*)(u_addr + (x >> 1)));
486 const vector unsigned char vchar_V = *((vector unsigned char*)(v_addr + (x >> 1)));
487
488 const vector float vfloat_U_1 = spu_add(spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_U, vec_char2int_first), 0),vec_minus_128);
489 const vector float vfloat_U_2 = spu_add(spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_U, vec_char2int_second), 0),vec_minus_128);
490 const vector float vfloat_U_3 = spu_add(spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_U, vec_char2int_third), 0),vec_minus_128);
491 const vector float vfloat_U_4 = spu_add(spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_U, vec_char2int_fourth), 0),vec_minus_128);
492
493 const vector float vfloat_V_1 = spu_add(spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_V, vec_char2int_first), 0),vec_minus_128);
494 const vector float vfloat_V_2 = spu_add(spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_V, vec_char2int_second), 0),vec_minus_128);
495 const vector float vfloat_V_3 = spu_add(spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_V, vec_char2int_third), 0),vec_minus_128);
496 const vector float vfloat_V_4 = spu_add(spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_V, vec_char2int_fourth), 0),vec_minus_128);
497
498 vector float Y_1 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_1, vec_char2int_first), 0);
499 vector float Y_2 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_1, vec_char2int_second), 0);
500 vector float Y_3 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_1, vec_char2int_third), 0);
501 vector float Y_4 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_1, vec_char2int_fourth), 0);
502 vector float Y_5 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_2, vec_char2int_first), 0);
503 vector float Y_6 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_2, vec_char2int_second), 0);
504 vector float Y_7 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_2, vec_char2int_third), 0);
505 vector float Y_8 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_2, vec_char2int_fourth), 0);
506 vector float Y_9 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_3, vec_char2int_first), 0);
507 vector float Y_10 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_3, vec_char2int_second), 0);
508 vector float Y_11 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_3, vec_char2int_third), 0);
509 vector float Y_12 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_3, vec_char2int_fourth), 0);
510 vector float Y_13 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_4, vec_char2int_first), 0);
511 vector float Y_14 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_4, vec_char2int_second), 0);
512 vector float Y_15 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_4, vec_char2int_third), 0);
513 vector float Y_16 = spu_convtf((vector unsigned int)spu_shuffle(vec_null, vchar_Y_4, vec_char2int_fourth), 0);
514
515 const vector float R1a_precalculate = spu_mul(vec_R_precalc_coeff, vfloat_V_1);
516 const vector float R2a_precalculate = spu_mul(vec_R_precalc_coeff, vfloat_V_2);
517 const vector float R3a_precalculate = spu_mul(vec_R_precalc_coeff, vfloat_V_3);
518 const vector float R4a_precalculate = spu_mul(vec_R_precalc_coeff, vfloat_V_4);
519
520 const vector float R1_precalculate = spu_shuffle(R1a_precalculate, R1a_precalculate, vec_select_floats_upper);
521 const vector float R2_precalculate = spu_shuffle(R1a_precalculate, R1a_precalculate, vec_select_floats_lower);
522 const vector float R3_precalculate = spu_shuffle(R2a_precalculate, R2a_precalculate, vec_select_floats_upper);
523 const vector float R4_precalculate = spu_shuffle(R2a_precalculate, R2a_precalculate, vec_select_floats_lower);
524 const vector float R5_precalculate = spu_shuffle(R3a_precalculate, R3a_precalculate, vec_select_floats_upper);
525 const vector float R6_precalculate = spu_shuffle(R3a_precalculate, R3a_precalculate, vec_select_floats_lower);
526 const vector float R7_precalculate = spu_shuffle(R4a_precalculate, R4a_precalculate, vec_select_floats_upper);
527 const vector float R8_precalculate = spu_shuffle(R4a_precalculate, R4a_precalculate, vec_select_floats_lower);
528
529
530 const vector float G1a_precalculate = spu_madd(vec_Gu_precalc_coeff, vfloat_U_1, spu_mul(vfloat_V_1, vec_Gv_precalc_coeff));
531 const vector float G2a_precalculate = spu_madd(vec_Gu_precalc_coeff, vfloat_U_2, spu_mul(vfloat_V_2, vec_Gv_precalc_coeff));
532 const vector float G3a_precalculate = spu_madd(vec_Gu_precalc_coeff, vfloat_U_3, spu_mul(vfloat_V_3, vec_Gv_precalc_coeff));
533 const vector float G4a_precalculate = spu_madd(vec_Gu_precalc_coeff, vfloat_U_4, spu_mul(vfloat_V_4, vec_Gv_precalc_coeff));
534
535 const vector float G1_precalculate = spu_shuffle(G1a_precalculate, G1a_precalculate, vec_select_floats_upper);
536 const vector float G2_precalculate = spu_shuffle(G1a_precalculate, G1a_precalculate, vec_select_floats_lower);
537 const vector float G3_precalculate = spu_shuffle(G2a_precalculate, G2a_precalculate, vec_select_floats_upper);
538 const vector float G4_precalculate = spu_shuffle(G2a_precalculate, G2a_precalculate, vec_select_floats_lower);
539 const vector float G5_precalculate = spu_shuffle(G3a_precalculate, G3a_precalculate, vec_select_floats_upper);
540 const vector float G6_precalculate = spu_shuffle(G3a_precalculate, G3a_precalculate, vec_select_floats_lower);
541 const vector float G7_precalculate = spu_shuffle(G4a_precalculate, G4a_precalculate, vec_select_floats_upper);
542 const vector float G8_precalculate = spu_shuffle(G4a_precalculate, G4a_precalculate, vec_select_floats_lower);
543
544
545 const vector float B1a_precalculate = spu_mul(vec_B_precalc_coeff, vfloat_U_1);
546 const vector float B2a_precalculate = spu_mul(vec_B_precalc_coeff, vfloat_U_2);
547 const vector float B3a_precalculate = spu_mul(vec_B_precalc_coeff, vfloat_U_3);
548 const vector float B4a_precalculate = spu_mul(vec_B_precalc_coeff, vfloat_U_4);
549
550 const vector float B1_precalculate = spu_shuffle(B1a_precalculate, B1a_precalculate, vec_select_floats_upper);
551 const vector float B2_precalculate = spu_shuffle(B1a_precalculate, B1a_precalculate, vec_select_floats_lower);
552 const vector float B3_precalculate = spu_shuffle(B2a_precalculate, B2a_precalculate, vec_select_floats_upper);
553 const vector float B4_precalculate = spu_shuffle(B2a_precalculate, B2a_precalculate, vec_select_floats_lower);
554 const vector float B5_precalculate = spu_shuffle(B3a_precalculate, B3a_precalculate, vec_select_floats_upper);
555 const vector float B6_precalculate = spu_shuffle(B3a_precalculate, B3a_precalculate, vec_select_floats_lower);
556 const vector float B7_precalculate = spu_shuffle(B4a_precalculate, B4a_precalculate, vec_select_floats_upper);
557 const vector float B8_precalculate = spu_shuffle(B4a_precalculate, B4a_precalculate, vec_select_floats_lower);
558
559
560 const vector unsigned int R_1 = vfloat_to_vuint(spu_add( Y_1, R1_precalculate));
561 const vector unsigned int R_2 = vfloat_to_vuint(spu_add( Y_2, R2_precalculate));
562 const vector unsigned int R_3 = vfloat_to_vuint(spu_add( Y_3, R3_precalculate));
563 const vector unsigned int R_4 = vfloat_to_vuint(spu_add( Y_4, R4_precalculate));
564 const vector unsigned int R_5 = vfloat_to_vuint(spu_add( Y_5, R5_precalculate));
565 const vector unsigned int R_6 = vfloat_to_vuint(spu_add( Y_6, R6_precalculate));
566 const vector unsigned int R_7 = vfloat_to_vuint(spu_add( Y_7, R7_precalculate));
567 const vector unsigned int R_8 = vfloat_to_vuint(spu_add( Y_8, R8_precalculate));
568 const vector unsigned int R_9 = vfloat_to_vuint(spu_add( Y_9, R1_precalculate));
569 const vector unsigned int R_10 = vfloat_to_vuint(spu_add(Y_10, R2_precalculate));
570 const vector unsigned int R_11 = vfloat_to_vuint(spu_add(Y_11, R3_precalculate));
571 const vector unsigned int R_12 = vfloat_to_vuint(spu_add(Y_12, R4_precalculate));
572 const vector unsigned int R_13 = vfloat_to_vuint(spu_add(Y_13, R5_precalculate));
573 const vector unsigned int R_14 = vfloat_to_vuint(spu_add(Y_14, R6_precalculate));
574 const vector unsigned int R_15 = vfloat_to_vuint(spu_add(Y_15, R7_precalculate));
575 const vector unsigned int R_16 = vfloat_to_vuint(spu_add(Y_16, R8_precalculate));
576
577 const vector unsigned int G_1 = vfloat_to_vuint(spu_add( Y_1, G1_precalculate));
578 const vector unsigned int G_2 = vfloat_to_vuint(spu_add( Y_2, G2_precalculate));
579 const vector unsigned int G_3 = vfloat_to_vuint(spu_add( Y_3, G3_precalculate));
580 const vector unsigned int G_4 = vfloat_to_vuint(spu_add( Y_4, G4_precalculate));
581 const vector unsigned int G_5 = vfloat_to_vuint(spu_add( Y_5, G5_precalculate));
582 const vector unsigned int G_6 = vfloat_to_vuint(spu_add( Y_6, G6_precalculate));
583 const vector unsigned int G_7 = vfloat_to_vuint(spu_add( Y_7, G7_precalculate));
584 const vector unsigned int G_8 = vfloat_to_vuint(spu_add( Y_8, G8_precalculate));
585 const vector unsigned int G_9 = vfloat_to_vuint(spu_add( Y_9, G1_precalculate));
586 const vector unsigned int G_10 = vfloat_to_vuint(spu_add(Y_10, G2_precalculate));
587 const vector unsigned int G_11 = vfloat_to_vuint(spu_add(Y_11, G3_precalculate));
588 const vector unsigned int G_12 = vfloat_to_vuint(spu_add(Y_12, G4_precalculate));
589 const vector unsigned int G_13 = vfloat_to_vuint(spu_add(Y_13, G5_precalculate));
590 const vector unsigned int G_14 = vfloat_to_vuint(spu_add(Y_14, G6_precalculate));
591 const vector unsigned int G_15 = vfloat_to_vuint(spu_add(Y_15, G7_precalculate));
592 const vector unsigned int G_16 = vfloat_to_vuint(spu_add(Y_16, G8_precalculate));
593
594 const vector unsigned int B_1 = vfloat_to_vuint(spu_add( Y_1, B1_precalculate));
595 const vector unsigned int B_2 = vfloat_to_vuint(spu_add( Y_2, B2_precalculate));
596 const vector unsigned int B_3 = vfloat_to_vuint(spu_add( Y_3, B3_precalculate));
597 const vector unsigned int B_4 = vfloat_to_vuint(spu_add( Y_4, B4_precalculate));
598 const vector unsigned int B_5 = vfloat_to_vuint(spu_add( Y_5, B5_precalculate));
599 const vector unsigned int B_6 = vfloat_to_vuint(spu_add( Y_6, B6_precalculate));
600 const vector unsigned int B_7 = vfloat_to_vuint(spu_add( Y_7, B7_precalculate));
601 const vector unsigned int B_8 = vfloat_to_vuint(spu_add( Y_8, B8_precalculate));
602 const vector unsigned int B_9 = vfloat_to_vuint(spu_add( Y_9, B1_precalculate));
603 const vector unsigned int B_10 = vfloat_to_vuint(spu_add(Y_10, B2_precalculate));
604 const vector unsigned int B_11 = vfloat_to_vuint(spu_add(Y_11, B3_precalculate));
605 const vector unsigned int B_12 = vfloat_to_vuint(spu_add(Y_12, B4_precalculate));
606 const vector unsigned int B_13 = vfloat_to_vuint(spu_add(Y_13, B5_precalculate));
607 const vector unsigned int B_14 = vfloat_to_vuint(spu_add(Y_14, B6_precalculate));
608 const vector unsigned int B_15 = vfloat_to_vuint(spu_add(Y_15, B7_precalculate));
609 const vector unsigned int B_16 = vfloat_to_vuint(spu_add(Y_16, B8_precalculate));
610
611 *((vector unsigned int*)(bgra_addr + x)) = spu_or(spu_or(vec_alpha, B_1), spu_or(spu_slqwbyte( R_1, 2),spu_slqwbyte(G_1, 1)));
612 *((vector unsigned int*)(bgra_addr + x + 4)) = spu_or(spu_or(vec_alpha, B_2), spu_or(spu_slqwbyte( R_2, 2),spu_slqwbyte(G_2, 1)));
613 *((vector unsigned int*)(bgra_addr + x + 8)) = spu_or(spu_or(vec_alpha, B_3), spu_or(spu_slqwbyte( R_3, 2),spu_slqwbyte(G_3, 1)));
614 *((vector unsigned int*)(bgra_addr + x + 12)) = spu_or(spu_or(vec_alpha, B_4), spu_or(spu_slqwbyte( R_4, 2),spu_slqwbyte(G_4, 1)));
615 *((vector unsigned int*)(bgra_addr + x + 16)) = spu_or(spu_or(vec_alpha, B_5), spu_or(spu_slqwbyte( R_5, 2),spu_slqwbyte(G_5, 1)));
616 *((vector unsigned int*)(bgra_addr + x + 20)) = spu_or(spu_or(vec_alpha, B_6), spu_or(spu_slqwbyte( R_6, 2),spu_slqwbyte(G_6, 1)));
617 *((vector unsigned int*)(bgra_addr + x + 24)) = spu_or(spu_or(vec_alpha, B_7), spu_or(spu_slqwbyte( R_7, 2),spu_slqwbyte(G_7, 1)));
618 *((vector unsigned int*)(bgra_addr + x + 28)) = spu_or(spu_or(vec_alpha, B_8), spu_or(spu_slqwbyte( R_8, 2),spu_slqwbyte(G_8, 1)));
619 *((vector unsigned int*)(bgra_addr + x + width)) = spu_or(spu_or(vec_alpha, B_9), spu_or(spu_slqwbyte( R_9, 2),spu_slqwbyte(G_9, 1)));
620 *((vector unsigned int*)(bgra_addr + x + width + 4)) = spu_or(spu_or(vec_alpha, B_10), spu_or(spu_slqwbyte(R_10, 2),spu_slqwbyte(G_10, 1)));
621 *((vector unsigned int*)(bgra_addr + x + width + 8)) = spu_or(spu_or(vec_alpha, B_11), spu_or(spu_slqwbyte(R_11, 2),spu_slqwbyte(G_11, 1)));
622 *((vector unsigned int*)(bgra_addr + x + width + 12)) = spu_or(spu_or(vec_alpha, B_12), spu_or(spu_slqwbyte(R_12, 2),spu_slqwbyte(G_12, 1)));
623 *((vector unsigned int*)(bgra_addr + x + width + 16)) = spu_or(spu_or(vec_alpha, B_13), spu_or(spu_slqwbyte(R_13, 2),spu_slqwbyte(G_13, 1)));
624 *((vector unsigned int*)(bgra_addr + x + width + 20)) = spu_or(spu_or(vec_alpha, B_14), spu_or(spu_slqwbyte(R_14, 2),spu_slqwbyte(G_14, 1)));
625 *((vector unsigned int*)(bgra_addr + x + width + 24)) = spu_or(spu_or(vec_alpha, B_15), spu_or(spu_slqwbyte(R_15, 2),spu_slqwbyte(G_15, 1)));
626 *((vector unsigned int*)(bgra_addr + x + width + 28)) = spu_or(spu_or(vec_alpha, B_16), spu_or(spu_slqwbyte(R_16, 2),spu_slqwbyte(G_16, 1)));
627 }
628}
629
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_QPEApp.cc b/apps/plugins/sdl/src/video/qtopia/SDL_QPEApp.cc
deleted file mode 100644
index 8daf1c524c..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_QPEApp.cc
+++ /dev/null
@@ -1,63 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <qpe/qpeapplication.h>
25#include <qapplication.h>
26#include <qevent.h>
27
28#include "SDL_thread.h"
29#include "SDL_timer.h"
30#include "SDL_error.h"
31
32/* Flag to tell whether or not the Be application is active or not */
33int SDL_QPEAppActive = 0;
34static QPEApplication *app;
35
36int SDL_InitQPEApp() {
37 if(SDL_QPEAppActive <= 0) {
38 if(!qApp) {
39 int argc = 1;
40 char *argv[] = { { "SDLApp" } };
41 app = new QPEApplication(argc, argv);
42 QWidget dummy;
43 app->showMainWidget(&dummy);
44 } else {
45 app = (QPEApplication*)qApp;
46 }
47 SDL_QPEAppActive++;
48 }
49 return 0;
50}
51
52/* Quit the QPE Application, if there's nothing left to do */
53void SDL_QuitQPEApp(void)
54{
55 /* Decrement the application reference count */
56 SDL_QPEAppActive--;
57 /* If the reference count reached zero, clean up the app */
58 if ( SDL_QPEAppActive == 0 && app) {
59 delete app;
60 app = 0;
61 qApp = 0;
62 }
63}
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_QPEApp.h b/apps/plugins/sdl/src/video/qtopia/SDL_QPEApp.h
deleted file mode 100644
index 8a9ab77d88..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_QPEApp.h
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the QPE application loop */
25
26/* Initialize the QPE Application, if it's not already started */
27extern int SDL_InitQPEApp(void);
28
29/* Quit the QPE Application, if there's nothing left to do */
30extern void SDL_QuitQPEApp(void);
31
32/* Flag to tell whether the app is active or not */
33extern int SDL_QPEAppActive;
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_QWin.cc b/apps/plugins/sdl/src/video/qtopia/SDL_QWin.cc
deleted file mode 100644
index 04474ed9be..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_QWin.cc
+++ /dev/null
@@ -1,527 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_QWin.h"
25#include <qapplication.h>
26#include <qdirectpainter_qws.h>
27
28screenRotationT screenRotation = SDL_QT_NO_ROTATION;
29
30SDL_QWin::SDL_QWin(const QSize& size)
31 : QWidget(0, "SDL_main"), my_painter(0), my_image(0),
32 my_inhibit_resize(false), my_mouse_pos(-1,-1), my_flags(0),
33 my_has_fullscreen(false), my_locked(0)
34{
35 setBackgroundMode(NoBackground);
36}
37
38SDL_QWin::~SDL_QWin() {
39 // Nothing to do yet.
40 if(my_image) {
41 delete my_image;
42 }
43}
44
45void SDL_QWin::setImage(QImage *image) {
46 if ( my_image ) {
47 delete my_image;
48 }
49 my_image = image;
50 // setFixedSize(image->size());
51}
52
53void SDL_QWin::resizeEvent(QResizeEvent *e) {
54 if(size() != qApp->desktop()->size()) {
55 // Widget is not the correct size, so do the fullscreen magic
56 my_has_fullscreen = false;
57 enableFullscreen();
58 }
59 if(my_inhibit_resize) {
60 my_inhibit_resize = false;
61 } else {
62 SDL_PrivateResize(e->size().width(), e->size().height());
63 }
64}
65
66void SDL_QWin::focusInEvent(QFocusEvent *) {
67 // Always do it here, no matter the size.
68 enableFullscreen();
69 SDL_PrivateAppActive(true, SDL_APPINPUTFOCUS);
70}
71
72void SDL_QWin::focusOutEvent(QFocusEvent *) {
73 my_has_fullscreen = false;
74 SDL_PrivateAppActive(false, SDL_APPINPUTFOCUS);
75}
76
77void SDL_QWin::closeEvent(QCloseEvent *e) {
78 SDL_PrivateQuit();
79 e->ignore();
80}
81
82void SDL_QWin::setMousePos(const QPoint &pos) {
83 if(my_image->width() == height()) {
84 if (screenRotation == SDL_QT_ROTATION_90)
85 my_mouse_pos = QPoint(height()-pos.y(), pos.x());
86 else if (screenRotation == SDL_QT_ROTATION_270)
87 my_mouse_pos = QPoint(pos.y(), width()-pos.x());
88 } else {
89 my_mouse_pos = pos;
90 }
91}
92
93void SDL_QWin::mouseMoveEvent(QMouseEvent *e) {
94 Qt::ButtonState button = e->button();
95 int sdlstate = 0;
96 if( (button & Qt::LeftButton)) {
97 sdlstate |= SDL_BUTTON_LMASK;
98 }
99 if( (button & Qt::RightButton)) {
100 sdlstate |= SDL_BUTTON_RMASK;
101 }
102 if( (button & Qt::MidButton)) {
103 sdlstate |= SDL_BUTTON_MMASK;
104 }
105 setMousePos(e->pos());
106 SDL_PrivateMouseMotion(sdlstate, 0, my_mouse_pos.x(), my_mouse_pos.y());
107}
108
109void SDL_QWin::mousePressEvent(QMouseEvent *e) {
110 mouseMoveEvent(e);
111 Qt::ButtonState button = e->button();
112 SDL_PrivateMouseButton(SDL_PRESSED,
113 (button & Qt::LeftButton) ? 1 :
114 ((button & Qt::RightButton) ? 2 : 3),
115 my_mouse_pos.x(), my_mouse_pos.y());
116}
117
118void SDL_QWin::mouseReleaseEvent(QMouseEvent *e) {
119 setMousePos(e->pos());
120 Qt::ButtonState button = e->button();
121 SDL_PrivateMouseButton(SDL_RELEASED,
122 (button & Qt::LeftButton) ? 1 :
123 ((button & Qt::RightButton) ? 2 : 3),
124 my_mouse_pos.x(), my_mouse_pos.y());
125 my_mouse_pos = QPoint(-1, -1);
126}
127
128static inline void
129gs_fastRotateBlit_3 ( unsigned short *fb,
130 unsigned short *bits,
131 const QRect& rect )
132{
133 // FIXME: this only works correctly for 240x320 displays
134 int startx, starty;
135 int width, height;
136
137 startx = rect.left() >> 1;
138 starty = rect.top() >> 1;
139 width = ((rect.right() - rect.left()) >> 1) + 2;
140 height = ((rect.bottom() - rect.top()) >> 1) + 2;
141
142 if((startx+width) > 120) {
143 width = 120 - startx; // avoid horizontal overflow
144 }
145 if((starty+height) > 160) {
146 height = 160 - starty; // avoid vertical overflow
147 }
148
149 ulong *sp1, *sp2, *dp1, *dp2;
150 ulong stop, sbot, dtop, dbot;
151
152 sp1 = (ulong*)bits + startx + starty*240;
153 sp2 = sp1 + 120;
154 dp1 = (ulong *)fb + (159 - starty) + startx*320;
155 dp2 = dp1 + 160;
156 int rowadd = (-320*width) - 1;
157 int rowadd2 = 240 - width;
158 // transfer in cells of 2x2 pixels in words
159 for (int y=0; y<height; y++) {
160 for (int x=0; x<width; x++) {
161 // read source pixels
162 stop = *sp1;
163 sbot = *sp2;
164 // rotate pixels
165 dtop = (sbot & 0xffff) + ((stop & 0xffff)<<16);
166 dbot = ((sbot & 0xffff0000)>>16) + (stop & 0xffff0000);
167 // write to framebuffer
168 *dp1 = dtop;
169 *dp2 = dbot;
170 // update source ptrs
171 sp1++; sp2++;
172 // update dest ptrs - 2 pix at a time
173 dp1 += 320;
174 dp2 += 320;
175 }
176 // adjust src ptrs - skip a row as we work in pairs
177 sp1 += rowadd2;
178 sp2 += rowadd2;
179 // adjust dest ptrs for rotation
180 dp1 += rowadd;
181 dp2 += rowadd;
182 }
183}
184
185static inline void
186gs_fastRotateBlit_1 ( unsigned short *fb,
187 unsigned short *bits,
188 const QRect& rect ) {
189 // FIXME: this only works correctly for 240x320 displays
190 int startx, starty;
191 int width, height;
192
193 startx = rect.left() >> 1;
194 starty = rect.top() >> 1;
195 width = ((rect.right() - rect.left()) >> 1) + 2;
196 height = ((rect.bottom() - rect.top()) >> 1) + 2;
197
198 if((startx+width) > 120) {
199 width = 120 - startx; // avoid horizontal overflow
200 }
201 if((starty+height) > 160) {
202 height = 160 - starty; // avoid vertical overflow
203 }
204
205 ulong *sp1, *sp2, *dp1, *dp2;
206 ulong stop, sbot, dtop, dbot;
207 fb += 320*239; // Move "fb" to top left corner
208 sp1 = (ulong*)bits + startx + starty*240;
209 sp2 = sp1 + 120;
210 dp1 = (ulong*)fb - startx * 320 - starty;
211 dp2 = dp1 - 160;
212 int rowadd = (320*width) + 1;
213 int rowadd2 = 240 - width;
214 // transfer in cells of 2x2 pixels in words
215 for (int y=0; y<height; y++) {
216 for (int x=0; x<width; x++) {
217 // read
218 stop = *sp1;
219 sbot = *sp2;
220 // rotate
221 dtop = (stop & 0xffff) + ((sbot & 0xffff)<<16);
222 dbot = ((stop & 0xffff0000)>>16) + (sbot & 0xffff0000);
223 // write
224 *dp1 = dtop;
225 *dp2 = dbot;
226 // update source ptrs
227 sp1++; sp2++;
228 // update dest ptrs - 2 pix at a time
229 dp1 -= 320;
230 dp2 -= 320;
231 }
232 // adjust src ptrs - skip a row as we work in pairs
233 sp1 += rowadd2;
234 sp2 += rowadd2;
235 // adjust dest ptrs for rotation
236 dp1 += rowadd;
237 dp2 += rowadd;
238 }
239}
240
241// desktop, SL-A300 etc
242bool SDL_QWin::repaintRotation0(const QRect& rect) {
243 if(my_image->width() == width()) {
244 uchar *fb = (uchar*)my_painter->frameBuffer();
245 uchar *buf = (uchar*)my_image->bits();
246 if(rect == my_image->rect()) {
247 SDL_memcpy(fb, buf, width()*height()*2);
248 } else {
249 int h = rect.height();
250 int wd = rect.width()<<1;
251 int fblineadd = my_painter->lineStep();
252 int buflineadd = my_image->bytesPerLine();
253 fb += (rect.left()<<1) + rect.top() * my_painter->lineStep();
254 buf += (rect.left()<<1) + rect.top() * my_image->bytesPerLine();
255 while(h--) {
256 SDL_memcpy(fb, buf, wd);
257 fb += fblineadd;
258 buf += buflineadd;
259 }
260 }
261 } else {
262 return false; // FIXME: Landscape
263 }
264#ifdef __i386__
265 my_painter->fillRect( rect, QBrush( Qt::NoBrush ) );
266#endif
267 return true;
268}
269
270
271// Sharp Zaurus SL-5500 etc
272bool SDL_QWin::repaintRotation3(const QRect& rect) {
273 if(my_image->width() == width()) {
274 ushort *fb = (ushort*)my_painter->frameBuffer();
275 ushort *buf = (ushort*)my_image->bits();
276 gs_fastRotateBlit_3(fb, buf, rect);
277 } else {
278 // landscape mode
279 if (screenRotation == SDL_QT_ROTATION_90) {
280 uchar *fb = (uchar*)my_painter->frameBuffer();
281 uchar *buf = (uchar*)my_image->bits();
282 if(rect == my_image->rect()) {
283 SDL_memcpy(fb, buf, width()*height()*2);
284 } else {
285 int h = rect.height();
286 int wd = rect.width()<<1;
287 int fblineadd = my_painter->lineStep();
288 int buflineadd = my_image->bytesPerLine();
289 fb += (rect.left()<<1) + rect.top() * my_painter->lineStep();
290 buf += (rect.left()<<1) + rect.top() * my_image->bytesPerLine();
291 while(h--) {
292 SDL_memcpy(fb, buf, wd);
293 fb += fblineadd;
294 buf += buflineadd;
295 }
296 }
297 } else if (screenRotation == SDL_QT_ROTATION_270) {
298 int h = rect.height();
299 int wd = rect.width();
300 int fblineadd = my_painter->lineStep() - (rect.width() << 1);
301 int buflineadd = my_image->bytesPerLine() - (rect.width() << 1);
302 int w;
303
304 uchar *fb = (uchar*)my_painter->frameBuffer();
305 uchar *buf = (uchar*)my_image->bits();
306
307 fb += ((my_painter->width() - (rect.top() + rect.height())) *
308 my_painter->lineStep()) + ((my_painter->height() - ((rect.left() +
309 rect.width()))) << 1);
310
311 buf += my_image->bytesPerLine() * (rect.top() + rect.height()) -
312 (((my_image->width() - (rect.left() + rect.width())) << 1) + 2);
313
314 while(h--) {
315 w = wd;
316 while(w--) *((unsigned short*)fb)++ = *((unsigned short*)buf)--;
317 fb += fblineadd;
318 buf -= buflineadd;
319 }
320 }
321 }
322 return true;
323}
324
325// ipaq 3800...
326bool SDL_QWin::repaintRotation1(const QRect& rect) {
327 if(my_image->width() == width()) {
328 ushort *fb = (ushort*)my_painter->frameBuffer();
329 ushort *buf = (ushort*)my_image->bits();
330 gs_fastRotateBlit_1(fb, buf, rect);
331 } else {
332 return false; // FIXME: landscape mode
333 }
334 return true;
335}
336
337void SDL_QWin::repaintRect(const QRect& rect) {
338 if(!my_painter || !rect.width() || !rect.height()) {
339 return;
340 }
341
342 if(QPixmap::defaultDepth() == 16) {
343 switch(my_painter->transformOrientation()) {
344 case 3:
345 if(repaintRotation3(rect)) { return; }
346 break;
347 case 1:
348 if(repaintRotation1(rect)) { return; }
349 break;
350 case 0:
351 if(repaintRotation0(rect)) { return; }
352 break;
353 }
354 }
355 my_painter->drawImage(rect.topLeft(), *my_image, rect);
356}
357
358// This paints the current buffer to the screen, when desired.
359void SDL_QWin::paintEvent(QPaintEvent *ev) {
360 if(my_image) {
361 lockScreen(true);
362 repaintRect(ev->rect());
363 unlockScreen();
364 }
365}
366
367/* Function to translate a keyboard transition and queue the key event
368 * This should probably be a table although this method isn't exactly
369 * slow.
370 */
371void SDL_QWin::QueueKey(QKeyEvent *e, int pressed)
372{
373 SDL_keysym keysym;
374 int scancode = e->key();
375 /* Set the keysym information */
376 if(scancode >= 'A' && scancode <= 'Z') {
377 // Qt sends uppercase, SDL wants lowercase
378 keysym.sym = static_cast<SDLKey>(scancode + 32);
379 } else if(scancode >= 0x1000) {
380 // Special keys
381 switch(scancode) {
382 case Qt::Key_Escape: scancode = SDLK_ESCAPE; break;
383 case Qt::Key_Tab: scancode = SDLK_TAB; break;
384 case Qt::Key_Backspace: scancode = SDLK_BACKSPACE; break;
385 case Qt::Key_Return: scancode = SDLK_RETURN; break;
386 case Qt::Key_Enter: scancode = SDLK_KP_ENTER; break;
387 case Qt::Key_Insert: scancode = SDLK_INSERT; break;
388 case Qt::Key_Delete: scancode = SDLK_DELETE; break;
389 case Qt::Key_Pause: scancode = SDLK_PAUSE; break;
390 case Qt::Key_Print: scancode = SDLK_PRINT; break;
391 case Qt::Key_SysReq: scancode = SDLK_SYSREQ; break;
392 case Qt::Key_Home: scancode = SDLK_HOME; break;
393 case Qt::Key_End: scancode = SDLK_END; break;
394 // We want the control keys to rotate with the screen
395 case Qt::Key_Left:
396 if (screenRotation == SDL_QT_ROTATION_90) scancode = SDLK_UP;
397 else if (screenRotation == SDL_QT_ROTATION_270) scancode = SDLK_DOWN;
398 else scancode = SDLK_LEFT;
399 break;
400 case Qt::Key_Up:
401 if (screenRotation == SDL_QT_ROTATION_90) scancode = SDLK_RIGHT;
402 else if (screenRotation == SDL_QT_ROTATION_270) scancode = SDLK_LEFT;
403 else scancode = SDLK_UP;
404 break;
405 case Qt::Key_Right:
406 if (screenRotation == SDL_QT_ROTATION_90) scancode = SDLK_DOWN;
407 else if (screenRotation == SDL_QT_ROTATION_270) scancode = SDLK_UP;
408 else scancode = SDLK_RIGHT;
409 break;
410 case Qt::Key_Down:
411 if (screenRotation == SDL_QT_ROTATION_90) scancode = SDLK_LEFT;
412 else if (screenRotation == SDL_QT_ROTATION_270) scancode = SDLK_RIGHT;
413 else scancode = SDLK_DOWN;
414 break;
415 case Qt::Key_Prior: scancode = SDLK_PAGEUP; break;
416 case Qt::Key_Next: scancode = SDLK_PAGEDOWN; break;
417 case Qt::Key_Shift: scancode = SDLK_LSHIFT; break;
418 case Qt::Key_Control: scancode = SDLK_LCTRL; break;
419 case Qt::Key_Meta: scancode = SDLK_LMETA; break;
420 case Qt::Key_Alt: scancode = SDLK_LALT; break;
421 case Qt::Key_CapsLock: scancode = SDLK_CAPSLOCK; break;
422 case Qt::Key_NumLock: scancode = SDLK_NUMLOCK; break;
423 case Qt::Key_ScrollLock: scancode = SDLK_SCROLLOCK; break;
424 case Qt::Key_F1: scancode = SDLK_F1; break;
425 case Qt::Key_F2: scancode = SDLK_F2; break;
426 case Qt::Key_F3: scancode = SDLK_F3; break;
427 case Qt::Key_F4: scancode = SDLK_F4; break;
428 case Qt::Key_F5: scancode = SDLK_F5; break;
429 case Qt::Key_F6: scancode = SDLK_F6; break;
430 case Qt::Key_F7: scancode = SDLK_F7; break;
431 case Qt::Key_F8: scancode = SDLK_F8; break;
432 case Qt::Key_F9: scancode = SDLK_F9; break;
433 case Qt::Key_F10: scancode = SDLK_F10; break;
434 case Qt::Key_F11: scancode = SDLK_F11; break;
435 case Qt::Key_F12: scancode = SDLK_F12; break;
436 case Qt::Key_F13: scancode = SDLK_F13; break;
437 case Qt::Key_F14: scancode = SDLK_F14; break;
438 case Qt::Key_F15: scancode = SDLK_F15; break;
439 case Qt::Key_Super_L: scancode = SDLK_LSUPER; break;
440 case Qt::Key_Super_R: scancode = SDLK_RSUPER; break;
441 case Qt::Key_Menu: scancode = SDLK_MENU; break;
442 case Qt::Key_Help: scancode = SDLK_HELP; break;
443
444 case Qt::Key_F33:
445 // FIXME: This is a hack to enable the OK key on
446 // Zaurii devices. SDLK_RETURN is a suitable key to use
447 // since it often is used as such.
448 // david@hedbor.org
449 scancode = SDLK_RETURN;
450 break;
451 default:
452 scancode = SDLK_UNKNOWN;
453 break;
454 }
455 keysym.sym = static_cast<SDLKey>(scancode);
456 } else {
457 keysym.sym = static_cast<SDLKey>(scancode);
458 }
459 keysym.scancode = scancode;
460 keysym.mod = KMOD_NONE;
461 ButtonState st = e->state();
462 if( (st & ShiftButton) ) { keysym.mod = static_cast<SDLMod>(keysym.mod | KMOD_LSHIFT); }
463 if( (st & ControlButton) ) { keysym.mod = static_cast<SDLMod>(keysym.mod | KMOD_LCTRL); }
464 if( (st & AltButton) ) { keysym.mod = static_cast<SDLMod>(keysym.mod | KMOD_LALT); }
465 if ( SDL_TranslateUNICODE ) {
466 QChar qchar = e->text()[0];
467 keysym.unicode = qchar.unicode();
468 } else {
469 keysym.unicode = 0;
470 }
471
472 /* NUMLOCK and CAPSLOCK are implemented as double-presses in reality */
473 // if ( (keysym.sym == SDLK_NUMLOCK) || (keysym.sym == SDLK_CAPSLOCK) ) {
474 // pressed = 1;
475 // }
476
477 /* Queue the key event */
478 if ( pressed ) {
479 SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
480 } else {
481 SDL_PrivateKeyboard(SDL_RELEASED, &keysym);
482 }
483}
484
485void SDL_QWin::setFullscreen(bool fs_on) {
486 my_has_fullscreen = false;
487 enableFullscreen();
488}
489
490void SDL_QWin::enableFullscreen() {
491 // Make sure size is correct
492 if(!my_has_fullscreen) {
493 setFixedSize(qApp->desktop()->size());
494 // This call is needed because showFullScreen won't work
495 // correctly if the widget already considers itself to be fullscreen.
496 showNormal();
497 // This is needed because showNormal() forcefully changes the window
498 // style to WSTyle_TopLevel.
499 setWFlags(WStyle_Customize | WStyle_NoBorder);
500 // Enable fullscreen.
501 showFullScreen();
502 my_has_fullscreen = true;
503 }
504}
505
506bool SDL_QWin::lockScreen(bool force) {
507 if(!my_painter) {
508 if(force || (isVisible() && isActiveWindow())) {
509 my_painter = new QDirectPainter(this);
510 } else {
511 return false;
512 }
513 }
514 my_locked++; // Increate lock refcount
515 return true;
516}
517
518void SDL_QWin::unlockScreen() {
519 if(my_locked > 0) {
520 my_locked--; // decrease lock refcount;
521 }
522 if(!my_locked && my_painter) {
523 my_painter->end();
524 delete my_painter;
525 my_painter = 0;
526 }
527}
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_QWin.h b/apps/plugins/sdl/src/video/qtopia/SDL_QWin.h
deleted file mode 100644
index 2531834a91..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_QWin.h
+++ /dev/null
@@ -1,110 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_QWin_h
25#define _SDL_QWin_h
26
27#include <stdio.h>
28
29#include <qimage.h>
30#include <qpixmap.h>
31#include <qwidget.h>
32#include <qpainter.h>
33#include <qdirectpainter_qws.h>
34
35#include "SDL_events.h"
36
37extern "C" {
38#include "../../events/SDL_events_c.h"
39};
40
41typedef enum {
42 SDL_QT_NO_ROTATION = 0,
43 SDL_QT_ROTATION_90,
44 SDL_QT_ROTATION_270
45} screenRotationT;
46
47extern screenRotationT screenRotation;
48
49class SDL_QWin : public QWidget
50{
51 void QueueKey(QKeyEvent *e, int pressed);
52 public:
53 SDL_QWin(const QSize& size);
54 virtual ~SDL_QWin();
55 virtual bool shown(void) {
56 return isVisible();
57 }
58 /* If called, the next resize event will not be forwarded to SDL. */
59 virtual void inhibitResize(void) {
60 my_inhibit_resize = true;
61 }
62 void setImage(QImage *image);
63 void setOffset(int x, int y) {
64 my_offset = QPoint(x, y);
65 }
66 void GetXYOffset(int &x, int &y) {
67 x = my_offset.x();
68 y = my_offset.y();
69 }
70 QImage *image(void) { return my_image; }
71
72 void setWFlags(WFlags flags) {
73 QWidget::setWFlags(flags);
74 my_flags = flags;
75 }
76 const QPoint& mousePos() const { return my_mouse_pos; }
77 void setMousePos(const QPoint& newpos);
78 void setFullscreen(bool);
79
80 bool lockScreen(bool force=false);
81 void unlockScreen();
82 void repaintRect(const QRect& rect);
83 protected:
84 /* Handle resizing of the window */
85 virtual void resizeEvent(QResizeEvent *e);
86 void focusInEvent(QFocusEvent *);
87 void focusOutEvent(QFocusEvent *);
88 void closeEvent(QCloseEvent *e);
89 void mouseMoveEvent(QMouseEvent *e);
90 void mousePressEvent(QMouseEvent *e);
91 void mouseReleaseEvent(QMouseEvent *e);
92 void paintEvent(QPaintEvent *ev);
93 void keyPressEvent(QKeyEvent *e) { QueueKey(e, 1); }
94 void keyReleaseEvent(QKeyEvent *e) { QueueKey(e, 0); }
95 private:
96 bool repaintRotation0(const QRect& rect);
97 bool repaintRotation1(const QRect& rect);
98 bool repaintRotation3(const QRect& rect);
99 void enableFullscreen();
100 QDirectPainter *my_painter;
101 QImage *my_image;
102 bool my_inhibit_resize;
103 QPoint my_offset;
104 QPoint my_mouse_pos;
105 WFlags my_flags;
106 WFlags my_has_fullscreen;
107 unsigned int my_locked;
108};
109
110#endif /* _SDL_QWin_h */
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_lowvideo.h b/apps/plugins/sdl/src/video/qtopia/SDL_lowvideo.h
deleted file mode 100644
index 1d05c72b14..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_lowvideo.h
+++ /dev/null
@@ -1,65 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowvideo_h
25#define _SDL_lowvideo_h
26
27#include "SDL_mouse.h"
28#include "../SDL_sysvideo.h"
29
30/* Hidden "this" pointer for the video functions */
31#define _THIS SDL_VideoDevice *_this
32
33/* Private display data */
34struct SDL_PrivateVideoData {
35 /* The main window */
36 SDL_QWin *SDL_Win;
37
38 /* The fullscreen mode list */
39#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
40 int SDL_nummodes[NUM_MODELISTS];
41 SDL_Rect **SDL_modelist[NUM_MODELISTS];
42
43 /* A completely clear cursor */
44 WMcursor *BlankCursor;
45
46 /* Mouse state variables */
47 Uint32 last_buttons;
48 QPoint last_point;
49
50 /* Keyboard state variables */
51 int key_flip;
52 //struct key_info keyinfo[2];
53};
54/* Old variable names */
55#define SDL_Win (_this->hidden->SDL_Win)
56#define saved_mode (_this->hidden->saved_mode)
57#define SDL_nummodes (_this->hidden->SDL_nummodes)
58#define SDL_modelist (_this->hidden->SDL_modelist)
59#define SDL_BlankCursor (_this->hidden->BlankCursor)
60#define last_buttons (_this->hidden->last_buttons)
61#define last_point (_this->hidden->last_point)
62#define key_flip (_this->hidden->key_flip)
63#define keyinfo (_this->hidden->keyinfo)
64
65#endif /* _SDL_lowvideo_h */
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_sysevents.cc b/apps/plugins/sdl/src/video/qtopia/SDL_sysevents.cc
deleted file mode 100644
index 4aaf81437c..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_sysevents.cc
+++ /dev/null
@@ -1,269 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <qpe/qpeapplication.h>
25
26#include <stdio.h>
27#include <string.h>
28#include "SDL_error.h"
29#include "SDL_events.h"
30#include "SDL_QWin.h"
31#include "SDL_lowvideo.h"
32#include "SDL_timer.h"
33
34extern "C" {
35#include "../../events/SDL_sysevents.h"
36#include "../../events/SDL_events_c.h"
37#include "SDL_sysevents_c.h"
38
39 // static SDLKey keymap[128];
40/* This is special because we know it will be run in a loop in a separate
41 thread. Normally this function should loop as long as there are input
42 states changing, i.e. new events arriving.
43*/
44void QT_PumpEvents(_THIS)
45{
46 if(!qApp) {
47 return;
48 }
49 // printf("processing events: %p\n", qApp);
50 //qApp->processOneEvent(); // wait for a event
51 qApp->processEvents(); // and process all outstanding ones
52#if 0
53 BView *view;
54 BRect bounds;
55 BPoint point;
56 uint32 buttons;
57 const uint32 button_masks[3] = {
58 B_PRIMARY_MOUSE_BUTTON,
59 B_TERTIARY_MOUSE_BUTTON,
60 B_SECONDARY_MOUSE_BUTTON,
61 };
62 unsigned int i, j;
63
64 /* Check out the mouse buttons and position (slight race condition) */
65 if ( SDL_Win->Lock() ) {
66 /* Don't do anything if we have no view */
67 view = SDL_Win->View();
68 if ( ! view ) {
69 SDL_Win->Unlock();
70 return;
71 }
72 bounds = view->Bounds();
73 /* Get new input state, if still active */
74 if ( SDL_Win->IsActive() ) {
75 key_flip = !key_flip;
76 get_key_info(&keyinfo[key_flip]);
77 view->GetMouse(&point, &buttons, true);
78 } else {
79 key_flip = key_flip;
80 point = last_point;
81 buttons = last_buttons;
82 }
83 SDL_Win->Unlock();
84 } else {
85 return;
86 }
87
88 /* If our view is active, we'll find key changes here */
89 if ( SDL_memcmp(keyinfo[0].key_states, keyinfo[1].key_states, 16) != 0 ) {
90 for ( i=0; i<16; ++i ) {
91 Uint8 new_state, transition;
92
93 new_state = keyinfo[key_flip].key_states[i];
94 transition = keyinfo[!key_flip].key_states[i] ^
95 keyinfo[ key_flip].key_states[i];
96 for ( j=0; j<8; ++j ) {
97 if ( transition&0x80 )
98 QueueKey(i*8+j, new_state&0x80);
99 transition <<= 1;
100 new_state <<= 1;
101 }
102 }
103 }
104
105 /* We check keyboard, but not mouse if mouse isn't in window */
106 if ( ! bounds.Contains(point) ) {
107 /* Mouse moved outside our view? */
108 if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) {
109 SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
110 be_app->SetCursor(B_HAND_CURSOR);
111 }
112 return;
113 }
114 /* Has the mouse moved back into our view? */
115 if ( ! (SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) {
116 /* Reset the B_HAND_CURSOR to our own */
117 SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
118 SDL_SetCursor(NULL);
119 }
120
121 /* Check for mouse motion */
122 if ( point != last_point ) {
123 int x, y;
124
125 SDL_Win->GetXYOffset(x, y);
126 x = (int)point.x - x;
127 y = (int)point.y - y;
128 SDL_PrivateMouseMotion(0, 0, x, y);
129 }
130 last_point = point;
131
132 /* Add any mouse button events */
133 for ( i=0; i<SDL_TABLESIZE(button_masks); ++i ) {
134 if ( (buttons ^ last_buttons) & button_masks[i] ) {
135 if ( buttons & button_masks[i] ) {
136 SDL_PrivateMouseButton(SDL_PRESSED, 1+i, 0, 0);
137 } else {
138 SDL_PrivateMouseButton(SDL_RELEASED, 1+i, 0, 0);
139 }
140 }
141 }
142 last_buttons = buttons;
143#endif
144}
145
146void QT_InitOSKeymap(_THIS)
147{
148#if 0
149 unsigned int i;
150
151 /* Initialize all the key states as "up" */
152 key_flip = 0;
153 SDL_memset(keyinfo[key_flip].key_states, 0, 16);
154
155 /* Initialize the key translation table */
156 for ( i=0; i<SDL_TABLESIZE(keymap); ++i )
157 keymap[i] = SDLK_UNKNOWN;
158
159 // keymap[0x01] = SDLK_ESCAPE;
160 // keymap[B_F1_KEY] = SDLK_F1;
161 // keymap[B_F2_KEY] = SDLK_F2;
162 // keymap[B_F3_KEY] = SDLK_F3;
163 // keymap[B_F4_KEY] = SDLK_F4;
164 // keymap[B_F5_KEY] = SDLK_F5;
165 // keymap[B_F6_KEY] = SDLK_F6;
166 // keymap[B_F7_KEY] = SDLK_F7;
167 // keymap[B_F8_KEY] = SDLK_F8;
168 // keymap[B_F9_KEY] = SDLK_F9;
169 // keymap[B_F10_KEY] = SDLK_F10;
170 // keymap[B_F11_KEY] = SDLK_F11;
171 // keymap[B_F12_KEY] = SDLK_F12;
172 // keymap[B_PRINT_KEY] = SDLK_PRINT;
173 //keymap[B_SCROLL_KEY] = SDLK_SCROLLOCK;
174 // keymap[B_PAUSE_KEY] = SDLK_PAUSE;
175 keymap[0x11] = SDLK_BACKQUOTE;
176 keymap[0x12] = SDLK_1;
177 keymap[0x13] = SDLK_2;
178 keymap[0x14] = SDLK_3;
179 keymap[0x15] = SDLK_4;
180 keymap[0x16] = SDLK_5;
181 keymap[0x17] = SDLK_6;
182 keymap[0x18] = SDLK_7;
183 keymap[0x19] = SDLK_8;
184 keymap[0x1a] = SDLK_9;
185 keymap[0x1b] = SDLK_0;
186 keymap[0x1c] = SDLK_MINUS;
187 keymap[0x1d] = SDLK_EQUALS;
188 keymap[0x1e] = SDLK_BACKSPACE;
189 keymap[0x1f] = SDLK_INSERT;
190 keymap[0x20] = SDLK_HOME;
191 keymap[0x21] = SDLK_PAGEUP;
192 //keymap[0x22] = SDLK_NUMLOCK;
193 keymap[0x23] = SDLK_KP_DIVIDE;
194 keymap[0x24] = SDLK_KP_MULTIPLY;
195 keymap[0x25] = SDLK_KP_MINUS;
196 keymap[0x26] = SDLK_TAB;
197 keymap[0x27] = SDLK_q;
198 keymap[0x28] = SDLK_w;
199 keymap[0x29] = SDLK_e;
200 keymap[0x2a] = SDLK_r;
201 keymap[0x2b] = SDLK_t;
202 keymap[0x2c] = SDLK_y;
203 keymap[0x2d] = SDLK_u;
204 keymap[0x2e] = SDLK_i;
205 keymap[0x2f] = SDLK_o;
206 keymap[0x30] = SDLK_p;
207 keymap[0x31] = SDLK_LEFTBRACKET;
208 keymap[0x32] = SDLK_RIGHTBRACKET;
209 keymap[0x33] = SDLK_BACKSLASH;
210 keymap[0x34] = SDLK_DELETE;
211 keymap[0x35] = SDLK_END;
212 keymap[0x36] = SDLK_PAGEDOWN;
213 keymap[0x37] = SDLK_KP7;
214 keymap[0x38] = SDLK_KP8;
215 keymap[0x39] = SDLK_KP9;
216 keymap[0x3a] = SDLK_KP_PLUS;
217 //keymap[0x3b] = SDLK_CAPSLOCK;
218 keymap[0x3c] = SDLK_a;
219 keymap[0x3d] = SDLK_s;
220 keymap[0x3e] = SDLK_d;
221 keymap[0x3f] = SDLK_f;
222 keymap[0x40] = SDLK_g;
223 keymap[0x41] = SDLK_h;
224 keymap[0x42] = SDLK_j;
225 keymap[0x43] = SDLK_k;
226 keymap[0x44] = SDLK_l;
227 keymap[0x45] = SDLK_SEMICOLON;
228 keymap[0x46] = SDLK_QUOTE;
229 keymap[0x47] = SDLK_RETURN;
230 keymap[0x48] = SDLK_KP4;
231 keymap[0x49] = SDLK_KP5;
232 keymap[0x4a] = SDLK_KP6;
233 keymap[0x4b] = SDLK_LSHIFT;
234 keymap[0x4c] = SDLK_z;
235 keymap[0x4d] = SDLK_x;
236 keymap[0x4e] = SDLK_c;
237 keymap[0x4f] = SDLK_v;
238 keymap[0x50] = SDLK_b;
239 keymap[0x51] = SDLK_n;
240 keymap[0x52] = SDLK_m;
241 keymap[0x53] = SDLK_COMMA;
242 keymap[0x54] = SDLK_PERIOD;
243 keymap[0x55] = SDLK_SLASH;
244 keymap[0x56] = SDLK_RSHIFT;
245 keymap[0x57] = SDLK_UP;
246 keymap[0x58] = SDLK_KP1;
247 keymap[0x59] = SDLK_KP2;
248 keymap[0x5a] = SDLK_KP3;
249 keymap[0x5b] = SDLK_KP_ENTER;
250 //keymap[0x5c] = SDLK_LCTRL;
251 //keymap[0x5d] = SDLK_LALT;
252 keymap[0x5e] = SDLK_SPACE;
253 //keymap[0x5f] = SDLK_RALT;
254 //keymap[0x60] = SDLK_RCTRL;
255 keymap[0x61] = SDLK_LEFT;
256 keymap[0x62] = SDLK_DOWN;
257 keymap[0x63] = SDLK_RIGHT;
258 keymap[0x64] = SDLK_KP0;
259 keymap[0x65] = SDLK_KP_PERIOD;
260 //keymap[0x66] = SDLK_LMETA;
261 //keymap[0x67] = SDLK_RMETA;
262 //keymap[0x68] = SDLK_MENU;
263 keymap[0x69] = SDLK_EURO;
264 keymap[0x6a] = SDLK_KP_EQUALS;
265 keymap[0x6b] = SDLK_POWER;
266#endif
267}
268
269}; /* Extern C */
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_sysevents_c.h b/apps/plugins/sdl/src/video/qtopia/SDL_sysevents_c.h
deleted file mode 100644
index 5e267592de..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_sysevents_c.h
+++ /dev/null
@@ -1,31 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_lowvideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29
30extern void QT_InitOSKeymap(_THIS);
31extern void QT_PumpEvents(_THIS);
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_sysmouse.cc b/apps/plugins/sdl/src/video/qtopia/SDL_sysmouse.cc
deleted file mode 100644
index 1a655b6f3d..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_sysmouse.cc
+++ /dev/null
@@ -1,56 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_QWin.h"
25
26extern "C" {
27
28#include "SDL_sysmouse_c.h"
29
30/* The implementation dependent data for the window manager cursor */
31struct WMcursor {
32 char *bits;
33};
34WMcursor *QT_CreateWMCursor(_THIS,
35 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
36{
37 static WMcursor dummy;
38 dummy.bits = 0;
39 return &dummy;
40}
41
42int QT_ShowWMCursor(_THIS, WMcursor *cursor)
43{
44 return 1;
45}
46
47void QT_FreeWMCursor(_THIS, WMcursor *cursor)
48{
49}
50
51void QT_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
52{
53 SDL_Win->setMousePos(QPoint(x, y));
54}
55
56}; /* Extern C */
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_sysmouse_c.h b/apps/plugins/sdl/src/video/qtopia/SDL_sysmouse_c.h
deleted file mode 100644
index 98e4cf5f36..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_sysmouse_c.h
+++ /dev/null
@@ -1,32 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_lowvideo.h"
25
26/* Functions to be exported */
27extern void QT_FreeWMCursor(_THIS, WMcursor *cursor);
28extern WMcursor *QT_CreateWMCursor(_THIS,
29 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
30extern int QT_ShowWMCursor(_THIS, WMcursor *cursor);
31extern void QT_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
32
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_sysvideo.cc b/apps/plugins/sdl/src/video/qtopia/SDL_sysvideo.cc
deleted file mode 100644
index 0e07874c7a..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_sysvideo.cc
+++ /dev/null
@@ -1,403 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Qtopia based framebuffer implementation */
25
26#include <unistd.h>
27
28#include <qapplication.h>
29#include <qpe/qpeapplication.h>
30
31#include "SDL_timer.h"
32
33#include "SDL_QWin.h"
34
35extern "C" {
36
37#include "../SDL_sysvideo.h"
38#include "../../events/SDL_events_c.h"
39#include "SDL_sysevents_c.h"
40#include "SDL_sysmouse_c.h"
41#include "SDL_syswm_c.h"
42#include "SDL_lowvideo.h"
43
44 //#define QTOPIA_DEBUG
45#define QT_HIDDEN_SIZE 32 /* starting hidden window size */
46
47 /* Name of the environment variable used to invert the screen rotation or not:
48 Possible values:
49 !=0 : Screen is 270° rotated
50 0: Screen is 90° rotated*/
51#define SDL_QT_ROTATION_ENV_NAME "SDL_QT_INVERT_ROTATION"
52
53 /* Initialization/Query functions */
54 static int QT_VideoInit(_THIS, SDL_PixelFormat *vformat);
55 static SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
56 static SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
57 static void QT_UpdateMouse(_THIS);
58 static int QT_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
59 static void QT_VideoQuit(_THIS);
60
61 /* Hardware surface functions */
62 static int QT_AllocHWSurface(_THIS, SDL_Surface *surface);
63 static int QT_LockHWSurface(_THIS, SDL_Surface *surface);
64 static void QT_UnlockHWSurface(_THIS, SDL_Surface *surface);
65 static void QT_FreeHWSurface(_THIS, SDL_Surface *surface);
66
67 static int QT_ToggleFullScreen(_THIS, int fullscreen);
68
69 static int QT_IconifyWindow(_THIS);
70 static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode);
71
72 /* FB driver bootstrap functions */
73
74 static int QT_Available(void)
75 {
76 return(1);
77 }
78
79 static void QT_DeleteDevice(SDL_VideoDevice *device)
80 {
81 SDL_free(device->hidden);
82 SDL_free(device);
83 }
84
85 static SDL_VideoDevice *QT_CreateDevice(int devindex)
86 {
87 SDL_VideoDevice *device;
88
89 /* Initialize all variables that we clean on shutdown */
90 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
91 if ( device ) {
92 SDL_memset(device, 0, (sizeof *device));
93 device->hidden = (struct SDL_PrivateVideoData *)
94 SDL_malloc((sizeof *device->hidden));
95 }
96 if ( (device == NULL) || (device->hidden == NULL) ) {
97 SDL_OutOfMemory();
98 if ( device ) {
99 SDL_free(device);
100 }
101 return(0);
102 }
103 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
104
105 /* Set the function pointers */
106 device->VideoInit = QT_VideoInit;
107 device->ListModes = QT_ListModes;
108 device->SetVideoMode = QT_SetVideoMode;
109 device->UpdateMouse = QT_UpdateMouse;
110 device->SetColors = QT_SetColors;
111 device->UpdateRects = NULL;
112 device->VideoQuit = QT_VideoQuit;
113 device->AllocHWSurface = QT_AllocHWSurface;
114 device->CheckHWBlit = NULL;
115 device->FillHWRect = NULL;
116 device->SetHWColorKey = NULL;
117 device->SetHWAlpha = NULL;
118 device->LockHWSurface = QT_LockHWSurface;
119 device->UnlockHWSurface = QT_UnlockHWSurface;
120 device->FlipHWSurface = NULL;
121 device->FreeHWSurface = QT_FreeHWSurface;
122 device->SetIcon = NULL;
123 device->SetCaption = QT_SetWMCaption;
124 device->IconifyWindow = QT_IconifyWindow;
125 device->GrabInput = QT_GrabInput;
126 device->GetWMInfo = NULL;
127 device->FreeWMCursor = QT_FreeWMCursor;
128 device->CreateWMCursor = QT_CreateWMCursor;
129 device->ShowWMCursor = QT_ShowWMCursor;
130 device->WarpWMCursor = QT_WarpWMCursor;
131 device->InitOSKeymap = QT_InitOSKeymap;
132 device->PumpEvents = QT_PumpEvents;
133
134 device->free = QT_DeleteDevice;
135 device->ToggleFullScreen = QT_ToggleFullScreen;
136
137 /* Set the driver flags */
138 device->handles_any_size = 0;
139
140 return device;
141 }
142
143 VideoBootStrap Qtopia_bootstrap = {
144 "qtopia", "Qtopia / QPE graphics",
145 QT_Available, QT_CreateDevice
146 };
147
148 /* Function to sort the display_list */
149 static int CompareModes(const void *A, const void *B)
150 {
151#if 0
152 const display_mode *a = (display_mode *)A;
153 const display_mode *b = (display_mode *)B;
154
155 if ( a->space == b->space ) {
156 return((b->virtual_width*b->virtual_height)-
157 (a->virtual_width*a->virtual_height));
158 } else {
159 return(ColorSpaceToBitsPerPixel(b->space)-
160 ColorSpaceToBitsPerPixel(a->space));
161 }
162#endif
163 return 0;
164 }
165
166 /* Yes, this isn't the fastest it could be, but it works nicely */
167 static int QT_AddMode(_THIS, int index, unsigned int w, unsigned int h)
168 {
169 SDL_Rect *mode;
170 int i;
171 int next_mode;
172
173 /* Check to see if we already have this mode */
174 if ( SDL_nummodes[index] > 0 ) {
175 for ( i=SDL_nummodes[index]-1; i >= 0; --i ) {
176 mode = SDL_modelist[index][i];
177 if ( (mode->w == w) && (mode->h == h) ) {
178 return(0);
179 }
180 }
181 }
182
183 /* Set up the new video mode rectangle */
184 mode = (SDL_Rect *)SDL_malloc(sizeof *mode);
185 if ( mode == NULL ) {
186 SDL_OutOfMemory();
187 return(-1);
188 }
189 mode->x = 0;
190 mode->y = 0;
191 mode->w = w;
192 mode->h = h;
193#ifdef QTOPIA_DEBUG
194 fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h, index+1);
195#endif
196
197 /* Allocate the new list of modes, and fill in the new mode */
198 next_mode = SDL_nummodes[index];
199 SDL_modelist[index] = (SDL_Rect **)
200 SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *));
201 if ( SDL_modelist[index] == NULL ) {
202 SDL_OutOfMemory();
203 SDL_nummodes[index] = 0;
204 SDL_free(mode);
205 return(-1);
206 }
207 SDL_modelist[index][next_mode] = mode;
208 SDL_modelist[index][next_mode+1] = NULL;
209 SDL_nummodes[index]++;
210
211 return(0);
212 }
213
214 int QT_VideoInit(_THIS, SDL_PixelFormat *vformat)
215 {
216 /* Initialize the QPE Application */
217 /* Determine the screen depth */
218 vformat->BitsPerPixel = QPixmap::defaultDepth();
219
220 // For now we hardcode the current depth because anything else
221 // might as well be emulated by SDL rather than by Qtopia.
222
223 QSize desktop_size = qApp->desktop()->size();
224 QT_AddMode(_this, ((vformat->BitsPerPixel+7)/8)-1,
225 desktop_size.width(), desktop_size.height());
226 QT_AddMode(_this, ((vformat->BitsPerPixel+7)/8)-1,
227 desktop_size.height(), desktop_size.width());
228
229 /* Determine the current screen size */
230 _this->info.current_w = desktop_size.width();
231 _this->info.current_h = desktop_size.height();
232
233 /* Create the window / widget */
234 SDL_Win = new SDL_QWin(QSize(QT_HIDDEN_SIZE, QT_HIDDEN_SIZE));
235 ((QPEApplication*)qApp)->showMainWidget(SDL_Win);
236 /* Fill in some window manager capabilities */
237 _this->info.wm_available = 0;
238
239 /* We're done! */
240 return(0);
241 }
242
243 /* We support any dimension at our bit-depth */
244 SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
245 {
246 SDL_Rect **modes;
247
248 modes = ((SDL_Rect **)0);
249 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
250 modes = SDL_modelist[((format->BitsPerPixel+7)/8)-1];
251 } else {
252 if ( format->BitsPerPixel ==
253 _this->screen->format->BitsPerPixel ) {
254 modes = ((SDL_Rect **)-1);
255 }
256 }
257 return(modes);
258 }
259
260 /* Various screen update functions available */
261 static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect *rects);
262
263
264 static int QT_SetFullScreen(_THIS, SDL_Surface *screen, int fullscreen)
265 {
266 return -1;
267 }
268
269 static int QT_ToggleFullScreen(_THIS, int fullscreen)
270 {
271 return -1;
272 }
273
274 /* FIXME: check return values and cleanup here */
275 SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface *current,
276 int width, int height, int bpp, Uint32 flags)
277 {
278
279 QImage *qimage;
280 QSize desktop_size = qApp->desktop()->size();
281
282
283 current->flags = 0; //SDL_FULLSCREEN; // We always run fullscreen.
284
285 if(width <= desktop_size.width()
286 && height <= desktop_size.height()) {
287 current->w = desktop_size.width();
288 current->h = desktop_size.height();
289 } else if(width <= desktop_size.height() && height <= desktop_size.width()) {
290 // Landscape mode
291 char * envString = SDL_getenv(SDL_QT_ROTATION_ENV_NAME);
292 int envValue = envString ? atoi(envString) : 0;
293 screenRotation = envValue ? SDL_QT_ROTATION_270 : SDL_QT_ROTATION_90;
294 current->h = desktop_size.width();
295 current->w = desktop_size.height();
296 } else {
297 SDL_SetError("Unsupported resolution, %dx%d\n", width, height);
298 }
299 if ( flags & SDL_OPENGL ) {
300 SDL_SetError("OpenGL not supported");
301 return(NULL);
302 }
303 /* Create the QImage framebuffer */
304 qimage = new QImage(current->w, current->h, bpp);
305 if (qimage->isNull()) {
306 SDL_SetError("Couldn't create screen bitmap");
307 delete qimage;
308 return(NULL);
309 }
310 current->pitch = qimage->bytesPerLine();
311 current->pixels = (void *)qimage->bits();
312 SDL_Win->setImage(qimage);
313 _this->UpdateRects = QT_NormalUpdate;
314 SDL_Win->setFullscreen(true);
315 /* We're done */
316 return(current);
317 }
318
319 /* Update the current mouse state and position */
320 void QT_UpdateMouse(_THIS)
321 {
322 QPoint point(-1, -1);
323 if ( SDL_Win->isActiveWindow() ) {
324 point = SDL_Win->mousePos();
325 }
326
327 if ( (point.x() >= 0) && (point.x() < SDL_VideoSurface->w) &&
328 (point.y() >= 0) && (point.y() < SDL_VideoSurface->h) ) {
329 SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
330 SDL_PrivateMouseMotion(0, 0,
331 (Sint16)point.x(), (Sint16)point.y());
332 } else {
333 SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
334 }
335 }
336
337 /* We don't actually allow hardware surfaces other than the main one */
338 static int QT_AllocHWSurface(_THIS, SDL_Surface *surface)
339 {
340 return(-1);
341 }
342 static void QT_FreeHWSurface(_THIS, SDL_Surface *surface)
343 {
344 return;
345 }
346 static int QT_LockHWSurface(_THIS, SDL_Surface *surface)
347 {
348 return(0);
349 }
350 static void QT_UnlockHWSurface(_THIS, SDL_Surface *surface)
351 {
352 return;
353 }
354
355 static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect *rects)
356 {
357 if(SDL_Win->lockScreen()) {
358 for(int i=0; i<numrects; ++i ) {
359 QRect rect(rects[i].x, rects[i].y,
360 rects[i].w, rects[i].h);
361 SDL_Win->repaintRect(rect);
362 }
363 SDL_Win->unlockScreen();
364 }
365 }
366 /* Is the system palette settable? */
367 int QT_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
368 {
369 return -1;
370 }
371
372 void QT_VideoQuit(_THIS)
373 {
374 // This is dumb, but if I free this, the app doesn't exit correctly.
375 // Of course, this will leak memory if init video is done more than once.
376 // Sucks but such is life.
377
378 // -- David Hedbor
379 // delete SDL_Win;
380 // SDL_Win = 0;
381 _this->screen->pixels = NULL;
382 QT_GrabInput(_this, SDL_GRAB_OFF);
383 }
384
385 static int QT_IconifyWindow(_THIS) {
386 SDL_Win->hide();
387
388 return true;
389 }
390
391 static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode) {
392 if(mode == SDL_GRAB_OFF) {
393 QPEApplication::grabKeyboard();
394 qApp->processEvents();
395 QPEApplication::ungrabKeyboard();
396 } else {
397 QPEApplication::grabKeyboard();
398 }
399 qApp->processEvents();
400 return mode;
401 }
402
403}; /* Extern C */
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_syswm.cc b/apps/plugins/sdl/src/video/qtopia/SDL_syswm.cc
deleted file mode 100644
index 47f988f4bd..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_syswm.cc
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_QWin.h"
25
26extern "C" {
27
28#include "SDL_syswm_c.h"
29
30void QT_SetWMCaption(_THIS, const char *title, const char *icon)
31{
32 SDL_Win->setCaption(title);
33}
34
35}; /* Extern C */
diff --git a/apps/plugins/sdl/src/video/qtopia/SDL_syswm_c.h b/apps/plugins/sdl/src/video/qtopia/SDL_syswm_c.h
deleted file mode 100644
index 4e4326b5a1..0000000000
--- a/apps/plugins/sdl/src/video/qtopia/SDL_syswm_c.h
+++ /dev/null
@@ -1,28 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_lowvideo.h"
25
26/* Functions to be exported */
27extern void QT_SetWMCaption(_THIS, const char *title, const char *icon);
28
diff --git a/apps/plugins/sdl/src/video/quartz/CGS.h b/apps/plugins/sdl/src/video/quartz/CGS.h
deleted file mode 100644
index abe47f7320..0000000000
--- a/apps/plugins/sdl/src/video/quartz/CGS.h
+++ /dev/null
@@ -1,84 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Obscuring code: maximum number of windows above ours (inclusive)
26
27 Note: this doesn't work too well in practice and should be
28 phased out when we add OpenGL 2D acceleration. It was never
29 enabled in the first place, so this shouldn't be a problem ;-)
30*/
31#define kMaxWindows 256
32
33/* Some of the Core Graphics Server API for obscuring code */
34#define kCGSWindowLevelTop 2147483632
35#define kCGSWindowLevelDockIconDrag 500
36#define kCGSWindowLevelDockMenu 101
37#define kCGSWindowLevelMenuIgnore 21
38#define kCGSWindowLevelMenu 20
39#define kCGSWindowLevelDockLabel 12
40#define kCGSWindowLevelDockIcon 11
41#define kCGSWindowLevelDock 10
42#define kCGSWindowLevelUtility 3
43#define kCGSWindowLevelNormal 0
44
45/*
46 For completeness; We never use these window levels, they are always below us
47 #define kCGSWindowLevelMBarShadow -20
48 #define kCGSWindowLevelDesktopPicture -2147483647
49 #define kCGSWindowLevelDesktop -2147483648
50*/
51
52typedef CGError CGSError;
53typedef long CGSWindowCount;
54typedef void * CGSConnectionID;
55typedef int CGSWindowID;
56typedef CGSWindowID* CGSWindowIDList;
57typedef CGWindowLevel CGSWindowLevel;
58typedef NSRect CGSRect;
59
60extern CGSConnectionID _CGSDefaultConnection ();
61
62extern CGSError CGSGetOnScreenWindowList (CGSConnectionID cid,
63 CGSConnectionID owner,
64 CGSWindowCount listCapacity,
65 CGSWindowIDList list,
66 CGSWindowCount *listCount);
67
68extern CGSError CGSGetScreenRectForWindow (CGSConnectionID cid,
69 CGSWindowID wid,
70 CGSRect *rect);
71
72extern CGWindowLevel CGSGetWindowLevel (CGSConnectionID cid,
73 CGSWindowID wid,
74 CGSWindowLevel *level);
75
76extern CGSError CGSDisplayHWFill (CGDirectDisplayID id, unsigned int x, unsigned int y,
77 unsigned int w, unsigned int h, unsigned int color);
78
79extern CGSError CGSDisplayCanHWFill (CGDirectDisplayID id);
80
81extern CGSError CGSGetMouseEnabledFlags (CGSConnectionID cid, CGSWindowID wid, int *flags);
82
83int CGSDisplayHWSync (CGDirectDisplayID id);
84
diff --git a/apps/plugins/sdl/src/video/quartz/SDL_QuartzEvents.m b/apps/plugins/sdl/src/video/quartz/SDL_QuartzEvents.m
deleted file mode 100644
index 773eb010be..0000000000
--- a/apps/plugins/sdl/src/video/quartz/SDL_QuartzEvents.m
+++ /dev/null
@@ -1,1063 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_QuartzVideo.h"
25#include "SDL_QuartzWM.h"
26
27#include <IOKit/IOMessage.h> /* For wake from sleep detection */
28#include <IOKit/pwr_mgt/IOPMLib.h> /* For wake from sleep detection */
29#include "SDL_QuartzKeys.h"
30
31/*
32 * On Leopard, this is missing from the 64-bit headers
33 */
34#if defined(__LP64__) && !defined(__POWER__)
35/*
36 * Workaround for a bug in the 10.5 SDK: By accident, OSService.h does
37 * not include Power.h at all when compiling in 64bit mode. This has
38 * been fixed in 10.6, but for 10.5, we manually define UsrActivity
39 * to ensure compilation works.
40 */
41#define UsrActivity 1
42#endif
43
44/*
45 * In Panther, this header defines device dependent masks for
46 * right side keys. These definitions only exist in Panther, but
47 * the header seems to exist at least in Jaguar and probably earlier
48 * versions of the OS, so this should't break anything.
49 */
50#include <IOKit/hidsystem/IOLLEvent.h>
51/*
52 * These are not defined before Panther. To keep the code compiling
53 * on systems without these, I will define if they don't exist.
54 */
55#ifndef NX_DEVICERCTLKEYMASK
56 #define NX_DEVICELCTLKEYMASK 0x00000001
57#endif
58#ifndef NX_DEVICELSHIFTKEYMASK
59 #define NX_DEVICELSHIFTKEYMASK 0x00000002
60#endif
61#ifndef NX_DEVICERSHIFTKEYMASK
62 #define NX_DEVICERSHIFTKEYMASK 0x00000004
63#endif
64#ifndef NX_DEVICELCMDKEYMASK
65 #define NX_DEVICELCMDKEYMASK 0x00000008
66#endif
67#ifndef NX_DEVICERCMDKEYMASK
68 #define NX_DEVICERCMDKEYMASK 0x00000010
69#endif
70#ifndef NX_DEVICELALTKEYMASK
71 #define NX_DEVICELALTKEYMASK 0x00000020
72#endif
73#ifndef NX_DEVICERALTKEYMASK
74 #define NX_DEVICERALTKEYMASK 0x00000040
75#endif
76#ifndef NX_DEVICERCTLKEYMASK
77 #define NX_DEVICERCTLKEYMASK 0x00002000
78#endif
79
80void QZ_InitOSKeymap (_THIS) {
81 BOOL saw_layout = NO;
82 UInt32 state;
83 UInt32 value;
84 Uint16 i;
85 int world = SDLK_WORLD_0;
86
87 for ( i=0; i<SDL_TABLESIZE(keymap); ++i )
88 keymap[i] = SDLK_UNKNOWN;
89
90 /* This keymap is almost exactly the same as the OS 9 one */
91 keymap[QZ_ESCAPE] = SDLK_ESCAPE;
92 keymap[QZ_F1] = SDLK_F1;
93 keymap[QZ_F2] = SDLK_F2;
94 keymap[QZ_F3] = SDLK_F3;
95 keymap[QZ_F4] = SDLK_F4;
96 keymap[QZ_F5] = SDLK_F5;
97 keymap[QZ_F6] = SDLK_F6;
98 keymap[QZ_F7] = SDLK_F7;
99 keymap[QZ_F8] = SDLK_F8;
100 keymap[QZ_F9] = SDLK_F9;
101 keymap[QZ_F10] = SDLK_F10;
102 keymap[QZ_F11] = SDLK_F11;
103 keymap[QZ_F12] = SDLK_F12;
104 keymap[QZ_F13] = SDLK_F13;
105 keymap[QZ_F14] = SDLK_F14;
106 keymap[QZ_F15] = SDLK_F15;
107/*
108 keymap[QZ_PRINT] = SDLK_PRINT;
109 keymap[QZ_SCROLLOCK] = SDLK_SCROLLOCK;
110 keymap[QZ_PAUSE] = SDLK_PAUSE;
111*/
112 keymap[QZ_POWER] = SDLK_POWER;
113 keymap[QZ_BACKQUOTE] = SDLK_BACKQUOTE;
114 keymap[QZ_1] = SDLK_1;
115 keymap[QZ_2] = SDLK_2;
116 keymap[QZ_3] = SDLK_3;
117 keymap[QZ_4] = SDLK_4;
118 keymap[QZ_5] = SDLK_5;
119 keymap[QZ_6] = SDLK_6;
120 keymap[QZ_7] = SDLK_7;
121 keymap[QZ_8] = SDLK_8;
122 keymap[QZ_9] = SDLK_9;
123 keymap[QZ_0] = SDLK_0;
124 keymap[QZ_MINUS] = SDLK_MINUS;
125 keymap[QZ_EQUALS] = SDLK_EQUALS;
126 keymap[QZ_BACKSPACE] = SDLK_BACKSPACE;
127 keymap[QZ_INSERT] = SDLK_INSERT;
128 keymap[QZ_HOME] = SDLK_HOME;
129 keymap[QZ_PAGEUP] = SDLK_PAGEUP;
130 keymap[QZ_NUMLOCK] = SDLK_NUMLOCK;
131 keymap[QZ_KP_EQUALS] = SDLK_KP_EQUALS;
132 keymap[QZ_KP_DIVIDE] = SDLK_KP_DIVIDE;
133 keymap[QZ_KP_MULTIPLY] = SDLK_KP_MULTIPLY;
134 keymap[QZ_TAB] = SDLK_TAB;
135 keymap[QZ_q] = SDLK_q;
136 keymap[QZ_w] = SDLK_w;
137 keymap[QZ_e] = SDLK_e;
138 keymap[QZ_r] = SDLK_r;
139 keymap[QZ_t] = SDLK_t;
140 keymap[QZ_y] = SDLK_y;
141 keymap[QZ_u] = SDLK_u;
142 keymap[QZ_i] = SDLK_i;
143 keymap[QZ_o] = SDLK_o;
144 keymap[QZ_p] = SDLK_p;
145 keymap[QZ_LEFTBRACKET] = SDLK_LEFTBRACKET;
146 keymap[QZ_RIGHTBRACKET] = SDLK_RIGHTBRACKET;
147 keymap[QZ_BACKSLASH] = SDLK_BACKSLASH;
148 keymap[QZ_DELETE] = SDLK_DELETE;
149 keymap[QZ_END] = SDLK_END;
150 keymap[QZ_PAGEDOWN] = SDLK_PAGEDOWN;
151 keymap[QZ_KP7] = SDLK_KP7;
152 keymap[QZ_KP8] = SDLK_KP8;
153 keymap[QZ_KP9] = SDLK_KP9;
154 keymap[QZ_KP_MINUS] = SDLK_KP_MINUS;
155 keymap[QZ_CAPSLOCK] = SDLK_CAPSLOCK;
156 keymap[QZ_a] = SDLK_a;
157 keymap[QZ_s] = SDLK_s;
158 keymap[QZ_d] = SDLK_d;
159 keymap[QZ_f] = SDLK_f;
160 keymap[QZ_g] = SDLK_g;
161 keymap[QZ_h] = SDLK_h;
162 keymap[QZ_j] = SDLK_j;
163 keymap[QZ_k] = SDLK_k;
164 keymap[QZ_l] = SDLK_l;
165 keymap[QZ_SEMICOLON] = SDLK_SEMICOLON;
166 keymap[QZ_QUOTE] = SDLK_QUOTE;
167 keymap[QZ_RETURN] = SDLK_RETURN;
168 keymap[QZ_KP4] = SDLK_KP4;
169 keymap[QZ_KP5] = SDLK_KP5;
170 keymap[QZ_KP6] = SDLK_KP6;
171 keymap[QZ_KP_PLUS] = SDLK_KP_PLUS;
172 keymap[QZ_LSHIFT] = SDLK_LSHIFT;
173 keymap[QZ_RSHIFT] = SDLK_RSHIFT;
174 keymap[QZ_z] = SDLK_z;
175 keymap[QZ_x] = SDLK_x;
176 keymap[QZ_c] = SDLK_c;
177 keymap[QZ_v] = SDLK_v;
178 keymap[QZ_b] = SDLK_b;
179 keymap[QZ_n] = SDLK_n;
180 keymap[QZ_m] = SDLK_m;
181 keymap[QZ_COMMA] = SDLK_COMMA;
182 keymap[QZ_PERIOD] = SDLK_PERIOD;
183 keymap[QZ_SLASH] = SDLK_SLASH;
184 keymap[QZ_UP] = SDLK_UP;
185 keymap[QZ_KP1] = SDLK_KP1;
186 keymap[QZ_KP2] = SDLK_KP2;
187 keymap[QZ_KP3] = SDLK_KP3;
188 keymap[QZ_KP_ENTER] = SDLK_KP_ENTER;
189 keymap[QZ_LCTRL] = SDLK_LCTRL;
190 keymap[QZ_LALT] = SDLK_LALT;
191 keymap[QZ_LMETA] = SDLK_LMETA;
192 keymap[QZ_RCTRL] = SDLK_RCTRL;
193 keymap[QZ_RALT] = SDLK_RALT;
194 keymap[QZ_RMETA] = SDLK_RMETA;
195 keymap[QZ_SPACE] = SDLK_SPACE;
196 keymap[QZ_LEFT] = SDLK_LEFT;
197 keymap[QZ_DOWN] = SDLK_DOWN;
198 keymap[QZ_RIGHT] = SDLK_RIGHT;
199 keymap[QZ_KP0] = SDLK_KP0;
200 keymap[QZ_KP_PERIOD] = SDLK_KP_PERIOD;
201 keymap[QZ_IBOOK_ENTER] = SDLK_KP_ENTER;
202 keymap[QZ_IBOOK_RIGHT] = SDLK_RIGHT;
203 keymap[QZ_IBOOK_DOWN] = SDLK_DOWN;
204 keymap[QZ_IBOOK_UP] = SDLK_UP;
205 keymap[QZ_IBOOK_LEFT] = SDLK_LEFT;
206
207 /*
208 Up there we setup a static scancode->keysym map. However, it will not
209 work very well on international keyboard. Hence we now query MacOS
210 for its own keymap to adjust our own mapping table. However, this is
211 basically only useful for ascii char keys. This is also the reason
212 why we keep the static table, too.
213 */
214
215#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1050)
216 if (TISCopyCurrentKeyboardLayoutInputSource != NULL) {
217 TISInputSourceRef src = TISCopyCurrentKeyboardLayoutInputSource();
218 if (src != NULL) {
219 CFDataRef data = (CFDataRef)
220 TISGetInputSourceProperty(src,
221 kTISPropertyUnicodeKeyLayoutData);
222 if (data != NULL) {
223 const UCKeyboardLayout *layout = (const UCKeyboardLayout *)
224 CFDataGetBytePtr(data);
225 if (layout != NULL) {
226 const UInt32 kbdtype = LMGetKbdType();
227 saw_layout = YES;
228
229 /* Loop over all 127 possible scan codes */
230 for (i = 0; i < 0x7F; i++) {
231 UniChar buf[16];
232 UniCharCount count = 0;
233
234 /* We pretend a clean start to begin with (i.e. no dead keys active */
235 state = 0;
236
237 if (UCKeyTranslate(layout, i, kUCKeyActionDown, 0, kbdtype,
238 0, &state, 16, &count, buf) != noErr) {
239 continue;
240 }
241
242 /* If the state become 0, it was a dead key. We need to
243 translate again, passing in the new state, to get
244 the actual key value */
245 if (state != 0) {
246 if (UCKeyTranslate(layout, i, kUCKeyActionDown, 0, kbdtype,
247 0, &state, 16, &count, buf) != noErr) {
248 continue;
249 }
250 }
251
252 if (count != 1) {
253 continue; /* no multi-char. Use SDL 1.3 instead. :) */
254 }
255
256 value = (UInt32) buf[0];
257 if (value >= 128) {
258 /* Some non-ASCII char, map it to SDLK_WORLD_* */
259 if (world < 0xFF) {
260 keymap[i] = world++;
261 }
262 } else if (value >= 32) { /* non-control ASCII char */
263 keymap[i] = value;
264 }
265 }
266 }
267 }
268 CFRelease(src);
269 }
270 }
271#endif
272
273#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1050)
274 if (!saw_layout) {
275 /* Get a pointer to the systems cached KCHR */
276 const void *KCHRPtr = (const void *)GetScriptManagerVariable(smKCHRCache);
277 if (KCHRPtr)
278 {
279 /* Loop over all 127 possible scan codes */
280 for (i = 0; i < 0x7F; i++)
281 {
282 /* We pretend a clean start to begin with (i.e. no dead keys active */
283 state = 0;
284
285 /* Now translate the key code to a key value */
286 value = KeyTranslate(KCHRPtr, i, &state) & 0xff;
287
288 /* If the state become 0, it was a dead key. We need to translate again,
289 passing in the new state, to get the actual key value */
290 if (state != 0)
291 value = KeyTranslate(KCHRPtr, i, &state) & 0xff;
292
293 /* Now we should have an ascii value, or 0. Try to figure out to which SDL symbol it maps */
294 if (value >= 128) { /* Some non-ASCII char, map it to SDLK_WORLD_* */
295 if (world < 0xFF) {
296 keymap[i] = world++;
297 }
298 } else if (value >= 32) { /* non-control ASCII char */
299 keymap[i] = value;
300 }
301 }
302 }
303 }
304#endif
305
306 /*
307 The keypad codes are re-setup here, because the loop above cannot
308 distinguish between a key on the keypad and a regular key. We maybe
309 could get around this problem in another fashion: NSEvent's flags
310 include a "NSNumericPadKeyMask" bit; we could check that and modify
311 the symbol we return on the fly. However, this flag seems to exhibit
312 some weird behaviour related to the num lock key
313 */
314 keymap[QZ_KP0] = SDLK_KP0;
315 keymap[QZ_KP1] = SDLK_KP1;
316 keymap[QZ_KP2] = SDLK_KP2;
317 keymap[QZ_KP3] = SDLK_KP3;
318 keymap[QZ_KP4] = SDLK_KP4;
319 keymap[QZ_KP5] = SDLK_KP5;
320 keymap[QZ_KP6] = SDLK_KP6;
321 keymap[QZ_KP7] = SDLK_KP7;
322 keymap[QZ_KP8] = SDLK_KP8;
323 keymap[QZ_KP9] = SDLK_KP9;
324 keymap[QZ_KP_MINUS] = SDLK_KP_MINUS;
325 keymap[QZ_KP_PLUS] = SDLK_KP_PLUS;
326 keymap[QZ_KP_PERIOD] = SDLK_KP_PERIOD;
327 keymap[QZ_KP_EQUALS] = SDLK_KP_EQUALS;
328 keymap[QZ_KP_DIVIDE] = SDLK_KP_DIVIDE;
329 keymap[QZ_KP_MULTIPLY] = SDLK_KP_MULTIPLY;
330 keymap[QZ_KP_ENTER] = SDLK_KP_ENTER;
331}
332
333static void QZ_DoKey (_THIS, int state, NSEvent *event) {
334
335 NSString *chars = NULL;
336 unsigned int i, numChars;
337 SDL_keysym key;
338
339 /*
340 A key event can contain multiple characters,
341 or no characters at all. In most cases, it
342 will contain a single character. If it contains
343 0 characters, we'll use 0 as the unicode. If it
344 contains multiple characters, we'll use 0 as
345 the scancode/keysym.
346 */
347 if (SDL_TranslateUNICODE && state == SDL_PRESSED) {
348 [field_edit interpretKeyEvents:[NSArray arrayWithObject:event]];
349 chars = [ event characters ];
350 numChars = [ chars length ];
351 if (numChars > 0)
352 [field_edit setString:@""];
353 } else {
354 numChars = 0;
355 }
356
357 if (numChars == 0) {
358
359 key.scancode = [ event keyCode ];
360 key.sym = keymap [ key.scancode ];
361 key.unicode = 0;
362 key.mod = KMOD_NONE;
363
364 SDL_PrivateKeyboard (state, &key);
365 }
366 else if (numChars >= 1) {
367
368 key.scancode = [ event keyCode ];
369 key.sym = keymap [ key.scancode ];
370 key.unicode = [ chars characterAtIndex:0 ];
371 key.mod = KMOD_NONE;
372
373 SDL_PrivateKeyboard (state, &key);
374
375 for (i = 1; i < numChars; i++) {
376
377 key.scancode = 0;
378 key.sym = 0;
379 key.unicode = [ chars characterAtIndex:i];
380 key.mod = KMOD_NONE;
381
382 SDL_PrivateKeyboard (state, &key);
383 }
384 }
385
386 if (SDL_getenv ("SDL_ENABLEAPPEVENTS"))
387 [ NSApp sendEvent:event ];
388}
389
390/* This is the original behavior, before support was added for
391 * differentiating between left and right versions of the keys.
392 */
393static void QZ_DoUnsidedModifiers (_THIS, unsigned int newMods) {
394
395 const int mapping[] = { SDLK_CAPSLOCK, SDLK_LSHIFT, SDLK_LCTRL, SDLK_LALT, SDLK_LMETA };
396
397 int i;
398 int bit;
399 SDL_keysym key;
400
401 key.scancode = 0;
402 key.sym = SDLK_UNKNOWN;
403 key.unicode = 0;
404 key.mod = KMOD_NONE;
405
406 /* Iterate through the bits, testing each against the current modifiers */
407 for (i = 0, bit = NSAlphaShiftKeyMask; bit <= NSCommandKeyMask; bit <<= 1, ++i) {
408
409 unsigned int currentMask, newMask;
410
411 currentMask = current_mods & bit;
412 newMask = newMods & bit;
413
414 if ( currentMask &&
415 currentMask != newMask ) { /* modifier up event */
416
417 key.sym = mapping[i];
418 /* If this was Caps Lock, we need some additional voodoo to make SDL happy */
419 if (bit == NSAlphaShiftKeyMask)
420 SDL_PrivateKeyboard (SDL_PRESSED, &key);
421 SDL_PrivateKeyboard (SDL_RELEASED, &key);
422 }
423 else if ( newMask &&
424 currentMask != newMask ) { /* modifier down event */
425
426 key.sym = mapping[i];
427 SDL_PrivateKeyboard (SDL_PRESSED, &key);
428 /* If this was Caps Lock, we need some additional voodoo to make SDL happy */
429 if (bit == NSAlphaShiftKeyMask)
430 SDL_PrivateKeyboard (SDL_RELEASED, &key);
431 }
432 }
433}
434
435/* This is a helper function for QZ_HandleModifierSide. This
436 * function reverts back to behavior before the distinction between
437 * sides was made.
438 */
439static void QZ_HandleNonDeviceModifier ( _THIS, unsigned int device_independent_mask, unsigned int newMods, unsigned int key_sym) {
440 unsigned int currentMask, newMask;
441 SDL_keysym key;
442
443 key.scancode = 0;
444 key.sym = key_sym;
445 key.unicode = 0;
446 key.mod = KMOD_NONE;
447
448 /* Isolate just the bits we care about in the depedent bits so we can
449 * figure out what changed
450 */
451 currentMask = current_mods & device_independent_mask;
452 newMask = newMods & device_independent_mask;
453
454 if ( currentMask &&
455 currentMask != newMask ) { /* modifier up event */
456 SDL_PrivateKeyboard (SDL_RELEASED, &key);
457 }
458 else if ( newMask &&
459 currentMask != newMask ) { /* modifier down event */
460 SDL_PrivateKeyboard (SDL_PRESSED, &key);
461 }
462}
463
464/* This is a helper function for QZ_HandleModifierSide.
465 * This function sets the actual SDL_PrivateKeyboard event.
466 */
467static void QZ_HandleModifierOneSide ( _THIS, unsigned int newMods,
468 unsigned int key_sym,
469 unsigned int sided_device_dependent_mask ) {
470
471 SDL_keysym key;
472 unsigned int current_dep_mask, new_dep_mask;
473
474 key.scancode = 0;
475 key.sym = key_sym;
476 key.unicode = 0;
477 key.mod = KMOD_NONE;
478
479 /* Isolate just the bits we care about in the depedent bits so we can
480 * figure out what changed
481 */
482 current_dep_mask = current_mods & sided_device_dependent_mask;
483 new_dep_mask = newMods & sided_device_dependent_mask;
484
485 /* We now know that this side bit flipped. But we don't know if
486 * it went pressed to released or released to pressed, so we must
487 * find out which it is.
488 */
489 if( new_dep_mask &&
490 current_dep_mask != new_dep_mask ) {
491 /* Modifier down event */
492 SDL_PrivateKeyboard (SDL_PRESSED, &key);
493 }
494 else /* Modifier up event */ {
495 SDL_PrivateKeyboard (SDL_RELEASED, &key);
496 }
497}
498
499/* This is a helper function for QZ_DoSidedModifiers.
500 * This function will figure out if the modifier key is the left or right side,
501 * e.g. left-shift vs right-shift.
502 */
503static void QZ_HandleModifierSide ( _THIS, int device_independent_mask,
504 unsigned int newMods,
505 unsigned int left_key_sym,
506 unsigned int right_key_sym,
507 unsigned int left_device_dependent_mask,
508 unsigned int right_device_dependent_mask ) {
509 unsigned int device_dependent_mask = 0;
510 unsigned int diff_mod = 0;
511
512 device_dependent_mask = left_device_dependent_mask | right_device_dependent_mask;
513 /* On the basis that the device independent mask is set, but there are
514 * no device dependent flags set, we'll assume that we can't detect this
515 * keyboard and revert to the unsided behavior.
516 */
517 if ( (device_dependent_mask & newMods) == 0 ) {
518 /* Revert to the old behavior */
519 QZ_HandleNonDeviceModifier ( this, device_independent_mask, newMods, left_key_sym );
520 return;
521 }
522
523 /* XOR the previous state against the new state to see if there's a change */
524 diff_mod = (device_dependent_mask & current_mods)
525 ^ (device_dependent_mask & newMods);
526
527 if ( diff_mod ) {
528 /* A change in state was found. Isolate the left and right bits
529 * to handle them separately just in case the values can simulataneously
530 * change or if the bits don't both exist.
531 */
532 if ( left_device_dependent_mask & diff_mod ) {
533 QZ_HandleModifierOneSide ( this, newMods, left_key_sym, left_device_dependent_mask );
534 }
535 if ( right_device_dependent_mask & diff_mod ) {
536 QZ_HandleModifierOneSide ( this, newMods, right_key_sym, right_device_dependent_mask );
537 }
538 }
539}
540
541/* This is a helper function for QZ_DoSidedModifiers.
542 * This function will release a key press in the case that
543 * it is clear that the modifier has been released (i.e. one side
544 * can't still be down).
545 */
546static void QZ_ReleaseModifierSide ( _THIS,
547 unsigned int device_independent_mask,
548 unsigned int newMods,
549 unsigned int left_key_sym,
550 unsigned int right_key_sym,
551 unsigned int left_device_dependent_mask,
552 unsigned int right_device_dependent_mask ) {
553 unsigned int device_dependent_mask = 0;
554 SDL_keysym key;
555
556 key.scancode = 0;
557 key.sym = SDLK_UNKNOWN;
558 key.unicode = 0;
559 key.mod = KMOD_NONE;
560
561 device_dependent_mask = left_device_dependent_mask | right_device_dependent_mask;
562 /* On the basis that the device independent mask is set, but there are
563 * no device dependent flags set, we'll assume that we can't detect this
564 * keyboard and revert to the unsided behavior.
565 */
566 if ( (device_dependent_mask & current_mods) == 0 ) {
567 /* In this case, we can't detect the keyboard, so use the left side
568 * to represent both, and release it.
569 */
570 key.sym = left_key_sym;
571 SDL_PrivateKeyboard (SDL_RELEASED, &key);
572
573 return;
574 }
575
576
577 /*
578 * This could have been done in an if-else case because at this point,
579 * we know that all keys have been released when calling this function.
580 * But I'm being paranoid so I want to handle each separately,
581 * so I hope this doesn't cause other problems.
582 */
583 if ( left_device_dependent_mask & current_mods ) {
584 key.sym = left_key_sym;
585 SDL_PrivateKeyboard (SDL_RELEASED, &key);
586 }
587 if ( right_device_dependent_mask & current_mods ) {
588 key.sym = right_key_sym;
589 SDL_PrivateKeyboard (SDL_RELEASED, &key);
590 }
591}
592
593/* This is a helper function for QZ_DoSidedModifiers.
594 * This function handles the CapsLock case.
595 */
596static void QZ_HandleCapsLock (_THIS, unsigned int newMods) {
597 unsigned int currentMask, newMask;
598 SDL_keysym key;
599
600 key.scancode = 0;
601 key.sym = SDLK_CAPSLOCK;
602 key.unicode = 0;
603 key.mod = KMOD_NONE;
604
605 currentMask = current_mods & NSAlphaShiftKeyMask;
606 newMask = newMods & NSAlphaShiftKeyMask;
607
608 if ( currentMask &&
609 currentMask != newMask ) { /* modifier up event */
610 /* If this was Caps Lock, we need some additional voodoo to make SDL happy */
611 SDL_PrivateKeyboard (SDL_PRESSED, &key);
612 SDL_PrivateKeyboard (SDL_RELEASED, &key);
613 }
614 else if ( newMask &&
615 currentMask != newMask ) { /* modifier down event */
616 /* If this was Caps Lock, we need some additional voodoo to make SDL happy */
617 SDL_PrivateKeyboard (SDL_PRESSED, &key);
618 SDL_PrivateKeyboard (SDL_RELEASED, &key);
619 }
620}
621
622/* This function will handle the modifier keys and also determine the
623 * correct side of the key.
624 */
625static void QZ_DoSidedModifiers (_THIS, unsigned int newMods) {
626 /* Set up arrays for the key syms for the left and right side. */
627 const unsigned int left_mapping[] = { SDLK_LSHIFT, SDLK_LCTRL, SDLK_LALT, SDLK_LMETA };
628 const unsigned int right_mapping[] = { SDLK_RSHIFT, SDLK_RCTRL, SDLK_RALT, SDLK_RMETA };
629 /* Set up arrays for the device dependent masks with indices that
630 * correspond to the _mapping arrays
631 */
632 const unsigned int left_device_mapping[] = { NX_DEVICELSHIFTKEYMASK, NX_DEVICELCTLKEYMASK, NX_DEVICELALTKEYMASK, NX_DEVICELCMDKEYMASK };
633 const unsigned int right_device_mapping[] = { NX_DEVICERSHIFTKEYMASK, NX_DEVICERCTLKEYMASK, NX_DEVICERALTKEYMASK, NX_DEVICERCMDKEYMASK };
634
635 unsigned int i;
636 unsigned int bit;
637
638 /* Handle CAPSLOCK separately because it doesn't have a left/right side */
639 QZ_HandleCapsLock ( this, newMods );
640
641 /* Iterate through the bits, testing each against the current modifiers */
642 for (i = 0, bit = NSShiftKeyMask; bit <= NSCommandKeyMask; bit <<= 1, ++i) {
643
644 unsigned int currentMask, newMask;
645
646 currentMask = current_mods & bit;
647 newMask = newMods & bit;
648
649 /* If the bit is set, we must always examine it because the left
650 * and right side keys may alternate or both may be pressed.
651 */
652 if ( newMask ) {
653 QZ_HandleModifierSide ( this, bit, newMods,
654 left_mapping[i],
655 right_mapping[i],
656 left_device_mapping[i],
657 right_device_mapping[i] );
658 }
659 /* If the state changed from pressed to unpressed, we must examine
660 * the device dependent bits to release the correct keys.
661 */
662 else if ( currentMask &&
663 currentMask != newMask ) { /* modifier up event */
664 QZ_ReleaseModifierSide ( this, bit, newMods,
665 left_mapping[i],
666 right_mapping[i],
667 left_device_mapping[i],
668 right_device_mapping[i] );
669 }
670 }
671}
672
673/* This function is called to handle the modifiers.
674 * It will try to distinguish between the left side and right side
675 * of the keyboard for those modifiers that qualify if the
676 * operating system version supports it. Otherwise, the code
677 * will not try to make the distinction.
678 */
679static void QZ_DoModifiers (_THIS, unsigned int newMods) {
680
681 if (current_mods == newMods)
682 return;
683
684 /*
685 * Starting with Panther (10.3.0), the ability to distinguish between
686 * left side and right side modifiers is available.
687 */
688 if( system_version >= 0x1030 ) {
689 QZ_DoSidedModifiers (this, newMods);
690 }
691 else {
692 QZ_DoUnsidedModifiers (this, newMods);
693 }
694
695 current_mods = newMods;
696}
697
698static void QZ_GetMouseLocation (_THIS, NSPoint *p) {
699 *p = [ NSEvent mouseLocation ]; /* global coordinates */
700 if (qz_window)
701 QZ_PrivateGlobalToLocal (this, p);
702 QZ_PrivateCocoaToSDL (this, p);
703}
704
705void QZ_DoActivate (_THIS) {
706
707 SDL_PrivateAppActive (1, SDL_APPINPUTFOCUS | (QZ_IsMouseInWindow (this) ? SDL_APPMOUSEFOCUS : 0));
708
709 QZ_UpdateCursor(this);
710
711 /* Regrab input, only if it was previously grabbed */
712 if ( current_grab_mode == SDL_GRAB_ON ) {
713
714 /* Restore cursor location if input was grabbed */
715 QZ_PrivateWarpCursor (this, cursor_loc.x, cursor_loc.y);
716 QZ_ChangeGrabState (this, QZ_ENABLE_GRAB);
717 }
718 else {
719 /* Update SDL's mouse location */
720 NSPoint p;
721 QZ_GetMouseLocation (this, &p);
722 SDL_PrivateMouseMotion (0, 0, p.x, p.y);
723 }
724
725 QZ_UpdateCursor(this);
726}
727
728void QZ_DoDeactivate (_THIS) {
729
730 SDL_PrivateAppActive (0, SDL_APPINPUTFOCUS | SDL_APPMOUSEFOCUS);
731
732 /* Get the current cursor location, for restore on activate */
733 QZ_GetMouseLocation (this, &cursor_loc);
734
735 /* Reassociate mouse and cursor */
736 CGAssociateMouseAndMouseCursorPosition (1);
737
738 QZ_UpdateCursor(this);
739}
740
741void QZ_SleepNotificationHandler (void * refcon,
742 io_service_t service,
743 natural_t messageType,
744 void * messageArgument )
745{
746 SDL_VideoDevice *this = (SDL_VideoDevice*)refcon;
747
748 switch(messageType)
749 {
750 case kIOMessageSystemWillSleep:
751 IOAllowPowerChange(power_connection, (long) messageArgument);
752 break;
753 case kIOMessageCanSystemSleep:
754 IOAllowPowerChange(power_connection, (long) messageArgument);
755 break;
756 case kIOMessageSystemHasPoweredOn:
757 /* awake */
758 SDL_PrivateExpose();
759 break;
760 }
761}
762
763void QZ_RegisterForSleepNotifications (_THIS)
764{
765 CFRunLoopSourceRef rls;
766 IONotificationPortRef thePortRef;
767 io_object_t notifier;
768
769 power_connection = IORegisterForSystemPower (this, &thePortRef, QZ_SleepNotificationHandler, &notifier);
770
771 if (power_connection == 0)
772 NSLog(@"SDL: QZ_SleepNotificationHandler() IORegisterForSystemPower failed.");
773
774 rls = IONotificationPortGetRunLoopSource (thePortRef);
775 CFRunLoopAddSource (CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
776 CFRelease (rls);
777}
778
779
780/* Try to map Quartz mouse buttons to SDL's lingo... */
781static int QZ_OtherMouseButtonToSDL(int button)
782{
783 switch (button)
784 {
785 case 0:
786 return(SDL_BUTTON_LEFT); /* 1 */
787 case 1:
788 return(SDL_BUTTON_RIGHT); /* 3 */
789 case 2:
790 return(SDL_BUTTON_MIDDLE); /* 2 */
791 }
792
793 /* >= 3: skip 4 & 5, since those are the SDL mousewheel buttons. */
794 return(button + 3);
795}
796
797
798void QZ_PumpEvents (_THIS)
799{
800 int32_t dx, dy;
801
802 NSDate *distantPast;
803 NSEvent *event;
804 NSRect winRect;
805 NSAutoreleasePool *pool;
806
807 if (!SDL_VideoSurface)
808 return; /* don't do anything if there's no screen surface. */
809
810 /* Update activity every five seconds to prevent screensaver. --ryan. */
811 if (!allow_screensaver) {
812 static Uint32 screensaverTicks;
813 Uint32 nowTicks = SDL_GetTicks();
814 if ((nowTicks - screensaverTicks) > 5000)
815 {
816 UpdateSystemActivity(UsrActivity);
817 screensaverTicks = nowTicks;
818 }
819 }
820
821 pool = [ [ NSAutoreleasePool alloc ] init ];
822 distantPast = [ NSDate distantPast ];
823
824 winRect = NSMakeRect (0, 0, SDL_VideoSurface->w, SDL_VideoSurface->h);
825
826 /* while grabbed, accumulate all mouse moved events into one SDL mouse event */
827 dx = 0;
828 dy = 0;
829
830 do {
831
832 /* Poll for an event. This will not block */
833 event = [ NSApp nextEventMatchingMask:NSAnyEventMask
834 untilDate:distantPast
835 inMode: NSDefaultRunLoopMode dequeue:YES ];
836 if (event != nil) {
837
838 int button;
839 unsigned int type;
840 BOOL isInGameWin;
841
842 #define DO_MOUSE_DOWN(button) do { \
843 if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) { \
844 SDL_PrivateMouseButton (SDL_PRESSED, button, 0, 0); \
845 expect_mouse_up |= 1<<button; \
846 } \
847 [ NSApp sendEvent:event ]; \
848 } while(0)
849
850 #define DO_MOUSE_UP(button) do { \
851 if ( expect_mouse_up & (1<<button) ) { \
852 SDL_PrivateMouseButton (SDL_RELEASED, button, 0, 0); \
853 expect_mouse_up &= ~(1<<button); \
854 } \
855 [ NSApp sendEvent:event ]; \
856 } while(0)
857
858 type = [ event type ];
859 isInGameWin = QZ_IsMouseInWindow (this);
860
861 QZ_DoModifiers(this, [ event modifierFlags ] );
862
863 switch (type) {
864 case NSLeftMouseDown:
865 if ( SDL_getenv("SDL_HAS3BUTTONMOUSE") ) {
866 DO_MOUSE_DOWN (SDL_BUTTON_LEFT);
867 } else {
868 if ( NSCommandKeyMask & current_mods ) {
869 last_virtual_button = SDL_BUTTON_RIGHT;
870 DO_MOUSE_DOWN (SDL_BUTTON_RIGHT);
871 }
872 else if ( NSAlternateKeyMask & current_mods ) {
873 last_virtual_button = SDL_BUTTON_MIDDLE;
874 DO_MOUSE_DOWN (SDL_BUTTON_MIDDLE);
875 }
876 else {
877 DO_MOUSE_DOWN (SDL_BUTTON_LEFT);
878 }
879 }
880 break;
881
882 case NSLeftMouseUp:
883 if ( last_virtual_button != 0 ) {
884 DO_MOUSE_UP (last_virtual_button);
885 last_virtual_button = 0;
886 }
887 else {
888 DO_MOUSE_UP (SDL_BUTTON_LEFT);
889 }
890 break;
891
892 case NSOtherMouseDown:
893 case NSRightMouseDown:
894 button = QZ_OtherMouseButtonToSDL([ event buttonNumber ]);
895 DO_MOUSE_DOWN (button);
896 break;
897
898 case NSOtherMouseUp:
899 case NSRightMouseUp:
900 button = QZ_OtherMouseButtonToSDL([ event buttonNumber ]);
901 DO_MOUSE_UP (button);
902 break;
903
904 case NSSystemDefined:
905 /*
906 Future: up to 32 "mouse" buttons can be handled.
907 if ([event subtype] == 7) {
908 unsigned int buttons;
909 buttons = [ event data2 ];
910 */
911 break;
912 case NSLeftMouseDragged:
913 case NSRightMouseDragged:
914 case NSOtherMouseDragged: /* usually middle mouse dragged */
915 case NSMouseMoved:
916 if ( grab_state == QZ_INVISIBLE_GRAB ) {
917
918 /*
919 If input is grabbed+hidden, the cursor doesn't move,
920 so we have to call the lowlevel window server
921 function. This is less accurate but works OK.
922 */
923 int32_t dx1, dy1;
924 CGGetLastMouseDelta (&dx1, &dy1);
925 dx += dx1;
926 dy += dy1;
927 }
928 else {
929
930 /*
931 Get the absolute mouse location. This is not the
932 mouse location after the currently processed event,
933 but the *current* mouse location, i.e. after all
934 pending events. This means that if there are
935 multiple mouse moved events in the queue, we make
936 multiple identical calls to SDL_PrivateMouseMotion(),
937 but that's no problem since the latter only
938 generates SDL events for nonzero movements. In my
939 experience on PBG4/10.4.8, this rarely happens anyway.
940 */
941 NSPoint p;
942 QZ_GetMouseLocation (this, &p);
943 SDL_PrivateMouseMotion (0, 0, p.x, p.y);
944 }
945
946 /*
947 Handle grab input+cursor visible by warping the cursor back
948 into the game window. This still generates a mouse moved event,
949 but not as a result of the warp (so it's in the right direction).
950 */
951 if ( grab_state == QZ_VISIBLE_GRAB && !isInGameWin ) {
952
953 NSPoint p;
954 QZ_GetMouseLocation (this, &p);
955
956 if ( p.x < 0.0 )
957 p.x = 0.0;
958
959 if ( p.y < 0.0 )
960 p.y = 0.0;
961
962 if ( p.x >= winRect.size.width )
963 p.x = winRect.size.width-1;
964
965 if ( p.y >= winRect.size.height )
966 p.y = winRect.size.height-1;
967
968 QZ_PrivateWarpCursor (this, p.x, p.y);
969 }
970 else
971 if ( !isInGameWin && (SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) {
972
973 SDL_PrivateAppActive (0, SDL_APPMOUSEFOCUS);
974
975 if (grab_state == QZ_INVISIBLE_GRAB)
976 /*The cursor has left the window even though it is
977 disassociated from the mouse (and therefore
978 shouldn't move): this can happen with Wacom
979 tablets, and it effectively breaks the grab, since
980 mouse down events now go to background
981 applications. The only possibility to avoid this
982 seems to be talking to the tablet driver
983 (AppleEvents) to constrain its mapped area to the
984 window, which may not be worth the effort. For
985 now, handle the condition more gracefully than
986 before by reassociating cursor and mouse until the
987 cursor enters the window again, making it obvious
988 to the user that the grab is broken.*/
989 CGAssociateMouseAndMouseCursorPosition (1);
990
991 QZ_UpdateCursor(this);
992 }
993 else
994 if ( isInGameWin && (SDL_GetAppState() & (SDL_APPMOUSEFOCUS | SDL_APPINPUTFOCUS)) == SDL_APPINPUTFOCUS ) {
995
996 SDL_PrivateAppActive (1, SDL_APPMOUSEFOCUS);
997
998 QZ_UpdateCursor(this);
999
1000 if (grab_state == QZ_INVISIBLE_GRAB) { /*see comment above*/
1001 QZ_PrivateWarpCursor (this, SDL_VideoSurface->w / 2, SDL_VideoSurface->h / 2);
1002 CGAssociateMouseAndMouseCursorPosition (0);
1003 }
1004 }
1005 break;
1006 case NSScrollWheel:
1007 if ( isInGameWin ) {
1008 float dy, dx;
1009 Uint8 button;
1010 dy = [ event deltaY ];
1011 dx = [ event deltaX ];
1012 if ( dy > 0.0 ) /* Scroll up */
1013 button = SDL_BUTTON_WHEELUP;
1014 else if ( dy < 0.0 ) /* Scroll down */
1015 button = SDL_BUTTON_WHEELDOWN;
1016 else
1017 break; /* Horizontal scroll */
1018 /* For now, wheel is sent as a quick down+up */
1019 SDL_PrivateMouseButton (SDL_PRESSED, button, 0, 0);
1020 SDL_PrivateMouseButton (SDL_RELEASED, button, 0, 0);
1021 }
1022 break;
1023 case NSKeyUp:
1024 QZ_DoKey (this, SDL_RELEASED, event);
1025 break;
1026 case NSKeyDown:
1027 QZ_DoKey (this, SDL_PRESSED, event);
1028 break;
1029 case NSFlagsChanged:
1030 break;
1031 case NSAppKitDefined:
1032 [ NSApp sendEvent:event ];
1033 if ([ event subtype ] == NSApplicationActivatedEventType && (mode_flags & SDL_FULLSCREEN)) {
1034 /* the default handling of this event seems to reset any cursor set by [NSCursor set] (used by SDL_SetCursor() in fullscreen mode) to the default system arrow cursor */
1035 SDL_Cursor *sdlc = SDL_GetCursor();
1036 if (sdlc != NULL && sdlc->wm_cursor != NULL) {
1037 [ sdlc->wm_cursor->nscursor set ];
1038 }
1039 }
1040 break;
1041 /* case NSApplicationDefined: break; */
1042 /* case NSPeriodic: break; */
1043 /* case NSCursorUpdate: break; */
1044 default:
1045 [ NSApp sendEvent:event ];
1046 }
1047 }
1048 } while (event != nil);
1049
1050 /* handle accumulated mouse moved events */
1051 if (dx != 0 || dy != 0)
1052 SDL_PrivateMouseMotion (0, 1, dx, dy);
1053
1054 [ pool release ];
1055}
1056
1057void QZ_UpdateMouse (_THIS)
1058{
1059 NSPoint p;
1060 QZ_GetMouseLocation (this, &p);
1061 SDL_PrivateAppActive (QZ_IsMouseInWindow (this), SDL_APPMOUSEFOCUS);
1062 SDL_PrivateMouseMotion (0, 0, p.x, p.y);
1063}
diff --git a/apps/plugins/sdl/src/video/quartz/SDL_QuartzGL.m b/apps/plugins/sdl/src/video/quartz/SDL_QuartzGL.m
deleted file mode 100644
index d38dceb56b..0000000000
--- a/apps/plugins/sdl/src/video/quartz/SDL_QuartzGL.m
+++ /dev/null
@@ -1,292 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_QuartzVideo.h"
25
26/*
27 * GL_ARB_Multisample is supposed to be available in 10.1, according to Apple:
28 *
29 * http://developer.apple.com/graphicsimaging/opengl/extensions.html#GL_ARB_multisample
30 *
31 * ...but it isn't in the system headers, according to Sam:
32 *
33 * http://lists.libsdl.org/pipermail/sdl-libsdl.org/2003-December/039794.html
34 *
35 * These are normally enums and not #defines in the system headers.
36 *
37 * --ryan.
38 */
39#if (MAC_OS_X_VERSION_MAX_ALLOWED < 1020)
40#define NSOpenGLPFASampleBuffers ((NSOpenGLPixelFormatAttribute) 55)
41#define NSOpenGLPFASamples ((NSOpenGLPixelFormatAttribute) 56)
42#endif
43
44#ifdef __powerpc__ /* we lost this in 10.6, which has no PPC support. */
45@implementation NSOpenGLContext (CGLContextAccess)
46- (CGLContextObj) cglContext;
47{
48 return _contextAuxiliary;
49}
50@end
51CGLContextObj QZ_GetCGLContextObj(NSOpenGLContext *nsctx)
52{
53 return [nsctx cglContext];
54}
55#else
56CGLContextObj QZ_GetCGLContextObj(NSOpenGLContext *nsctx)
57{
58 return (CGLContextObj) [nsctx CGLContextObj];
59}
60#endif
61
62
63/* OpenGL helper functions (used internally) */
64
65int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags) {
66
67 NSOpenGLPixelFormatAttribute attr[32];
68 NSOpenGLPixelFormat *fmt;
69 int i = 0;
70 int colorBits = bpp;
71
72 /* if a GL library hasn't been loaded at this point, load the default. */
73 if (!this->gl_config.driver_loaded) {
74 if (QZ_GL_LoadLibrary(this, NULL) == -1)
75 return 0;
76 }
77
78 if ( flags & SDL_FULLSCREEN ) {
79
80 attr[i++] = NSOpenGLPFAFullScreen;
81 }
82 /* In windowed mode, the OpenGL pixel depth must match device pixel depth */
83 else if ( colorBits != device_bpp ) {
84
85 colorBits = device_bpp;
86 }
87
88 attr[i++] = NSOpenGLPFAColorSize;
89 attr[i++] = colorBits;
90
91 attr[i++] = NSOpenGLPFADepthSize;
92 attr[i++] = this->gl_config.depth_size;
93
94 if ( this->gl_config.double_buffer ) {
95 attr[i++] = NSOpenGLPFADoubleBuffer;
96 }
97
98 if ( this->gl_config.stereo ) {
99 attr[i++] = NSOpenGLPFAStereo;
100 }
101
102 if ( this->gl_config.stencil_size != 0 ) {
103 attr[i++] = NSOpenGLPFAStencilSize;
104 attr[i++] = this->gl_config.stencil_size;
105 }
106
107 if ( (this->gl_config.accum_red_size +
108 this->gl_config.accum_green_size +
109 this->gl_config.accum_blue_size +
110 this->gl_config.accum_alpha_size) > 0 ) {
111 attr[i++] = NSOpenGLPFAAccumSize;
112 attr[i++] = this->gl_config.accum_red_size + this->gl_config.accum_green_size + this->gl_config.accum_blue_size + this->gl_config.accum_alpha_size;
113 }
114
115 if ( this->gl_config.multisamplebuffers != 0 ) {
116 attr[i++] = NSOpenGLPFASampleBuffers;
117 attr[i++] = this->gl_config.multisamplebuffers;
118 }
119
120 if ( this->gl_config.multisamplesamples != 0 ) {
121 attr[i++] = NSOpenGLPFASamples;
122 attr[i++] = this->gl_config.multisamplesamples;
123 attr[i++] = NSOpenGLPFANoRecovery;
124 }
125
126 if ( this->gl_config.accelerated > 0 ) {
127 attr[i++] = NSOpenGLPFAAccelerated;
128 }
129
130 attr[i++] = NSOpenGLPFAScreenMask;
131 attr[i++] = CGDisplayIDToOpenGLDisplayMask (display_id);
132 attr[i] = 0;
133
134 fmt = [ [ NSOpenGLPixelFormat alloc ] initWithAttributes:attr ];
135 if (fmt == nil) {
136 SDL_SetError ("Failed creating OpenGL pixel format");
137 return 0;
138 }
139
140 gl_context = [ [ NSOpenGLContext alloc ] initWithFormat:fmt
141 shareContext:nil];
142
143 [ fmt release ];
144
145 if (gl_context == nil) {
146 SDL_SetError ("Failed creating OpenGL context");
147 return 0;
148 }
149
150 /* Synchronize QZ_GL_SwapBuffers() to vertical retrace.
151 * (Apple's documentation is not completely clear about what this setting
152 * exactly does, IMHO - for a detailed explanation see
153 * http://lists.apple.com/archives/mac-opengl/2006/Jan/msg00080.html )
154 */
155 if ( this->gl_config.swap_control >= 0 ) {
156 GLint value;
157 value = this->gl_config.swap_control;
158 [ gl_context setValues: &value forParameter: NSOpenGLCPSwapInterval ];
159 }
160
161 /*
162 * Wisdom from Apple engineer in reference to UT2003's OpenGL performance:
163 * "You are blowing a couple of the internal OpenGL function caches. This
164 * appears to be happening in the VAO case. You can tell OpenGL to up
165 * the cache size by issuing the following calls right after you create
166 * the OpenGL context. The default cache size is 16." --ryan.
167 */
168
169 #ifndef GLI_ARRAY_FUNC_CACHE_MAX
170 #define GLI_ARRAY_FUNC_CACHE_MAX 284
171 #endif
172
173 #ifndef GLI_SUBMIT_FUNC_CACHE_MAX
174 #define GLI_SUBMIT_FUNC_CACHE_MAX 280
175 #endif
176
177 {
178 GLint cache_max = 64;
179 CGLContextObj ctx = QZ_GetCGLContextObj(gl_context);
180 CGLSetParameter (ctx, GLI_SUBMIT_FUNC_CACHE_MAX, &cache_max);
181 CGLSetParameter (ctx, GLI_ARRAY_FUNC_CACHE_MAX, &cache_max);
182 }
183
184 /* End Wisdom from Apple Engineer section. --ryan. */
185
186 return 1;
187}
188
189void QZ_TearDownOpenGL (_THIS) {
190
191 [ NSOpenGLContext clearCurrentContext ];
192 [ gl_context clearDrawable ];
193 [ gl_context release ];
194}
195
196
197/* SDL OpenGL functions */
198static const char *DEFAULT_OPENGL_LIB_NAME =
199 "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib";
200
201int QZ_GL_LoadLibrary (_THIS, const char *location) {
202 if ( gl_context != NULL ) {
203 SDL_SetError("OpenGL context already created");
204 return -1;
205 }
206
207 if (opengl_library != NULL)
208 SDL_UnloadObject(opengl_library);
209
210 if (location == NULL)
211 location = DEFAULT_OPENGL_LIB_NAME;
212
213 opengl_library = SDL_LoadObject(location);
214 if (opengl_library != NULL) {
215 this->gl_config.driver_loaded = 1;
216 return 0;
217 }
218
219 this->gl_config.driver_loaded = 0;
220 return -1;
221}
222
223void* QZ_GL_GetProcAddress (_THIS, const char *proc) {
224 return SDL_LoadFunction(opengl_library, proc);
225}
226
227int QZ_GL_GetAttribute (_THIS, SDL_GLattr attrib, int* value) {
228
229 GLenum attr = 0;
230
231 QZ_GL_MakeCurrent (this);
232
233 switch (attrib) {
234 case SDL_GL_RED_SIZE: attr = GL_RED_BITS; break;
235 case SDL_GL_BLUE_SIZE: attr = GL_BLUE_BITS; break;
236 case SDL_GL_GREEN_SIZE: attr = GL_GREEN_BITS; break;
237 case SDL_GL_ALPHA_SIZE: attr = GL_ALPHA_BITS; break;
238 case SDL_GL_DOUBLEBUFFER: attr = GL_DOUBLEBUFFER; break;
239 case SDL_GL_DEPTH_SIZE: attr = GL_DEPTH_BITS; break;
240 case SDL_GL_STENCIL_SIZE: attr = GL_STENCIL_BITS; break;
241 case SDL_GL_ACCUM_RED_SIZE: attr = GL_ACCUM_RED_BITS; break;
242 case SDL_GL_ACCUM_GREEN_SIZE: attr = GL_ACCUM_GREEN_BITS; break;
243 case SDL_GL_ACCUM_BLUE_SIZE: attr = GL_ACCUM_BLUE_BITS; break;
244 case SDL_GL_ACCUM_ALPHA_SIZE: attr = GL_ACCUM_ALPHA_BITS; break;
245 case SDL_GL_STEREO: attr = GL_STEREO; break;
246 case SDL_GL_MULTISAMPLEBUFFERS: attr = GL_SAMPLE_BUFFERS_ARB; break;
247 case SDL_GL_MULTISAMPLESAMPLES: attr = GL_SAMPLES_ARB; break;
248 case SDL_GL_BUFFER_SIZE:
249 {
250 GLint bits = 0;
251 GLint component;
252
253 /* there doesn't seem to be a single flag in OpenGL for this! */
254 glGetIntegerv (GL_RED_BITS, &component); bits += component;
255 glGetIntegerv (GL_GREEN_BITS,&component); bits += component;
256 glGetIntegerv (GL_BLUE_BITS, &component); bits += component;
257 glGetIntegerv (GL_ALPHA_BITS, &component); bits += component;
258
259 *value = bits;
260 return 0;
261 }
262 case SDL_GL_ACCELERATED_VISUAL:
263 {
264 GLint val;
265 /* FIXME: How do we get this information here?
266 [fmt getValues: &val forAttribute: NSOpenGLPFAAccelerated attr forVirtualScreen: 0];
267 */
268 val = (this->gl_config.accelerated != 0);;
269 *value = val;
270 return 0;
271 }
272 case SDL_GL_SWAP_CONTROL:
273 {
274 GLint val;
275 [ gl_context getValues: &val forParameter: NSOpenGLCPSwapInterval ];
276 *value = val;
277 return 0;
278 }
279 }
280
281 glGetIntegerv (attr, (GLint *)value);
282 return 0;
283}
284
285int QZ_GL_MakeCurrent (_THIS) {
286 [ gl_context makeCurrentContext ];
287 return 0;
288}
289
290void QZ_GL_SwapBuffers (_THIS) {
291 [ gl_context flushBuffer ];
292}
diff --git a/apps/plugins/sdl/src/video/quartz/SDL_QuartzKeys.h b/apps/plugins/sdl/src/video/quartz/SDL_QuartzKeys.h
deleted file mode 100644
index 82b78595e3..0000000000
--- a/apps/plugins/sdl/src/video/quartz/SDL_QuartzKeys.h
+++ /dev/null
@@ -1,146 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* These are the Macintosh key scancode constants -- from Inside Macintosh */
25
26#define QZ_ESCAPE 0x35
27#define QZ_F1 0x7A
28#define QZ_F2 0x78
29#define QZ_F3 0x63
30#define QZ_F4 0x76
31#define QZ_F5 0x60
32#define QZ_F6 0x61
33#define QZ_F7 0x62
34#define QZ_F8 0x64
35#define QZ_F9 0x65
36#define QZ_F10 0x6D
37#define QZ_F11 0x67
38#define QZ_F12 0x6F
39#define QZ_F13 0x69
40#define QZ_F14 0x6B
41#define QZ_F15 0x71
42/*
43#define QZ_PRINT 0x69
44#define QZ_SCROLLOCK 0x6B
45#define QZ_PAUSE 0x71
46*/
47#define QZ_POWER 0x7F
48#define QZ_BACKQUOTE 0x32
49#define QZ_1 0x12
50#define QZ_2 0x13
51#define QZ_3 0x14
52#define QZ_4 0x15
53#define QZ_5 0x17
54#define QZ_6 0x16
55#define QZ_7 0x1A
56#define QZ_8 0x1C
57#define QZ_9 0x19
58#define QZ_0 0x1D
59#define QZ_MINUS 0x1B
60#define QZ_EQUALS 0x18
61#define QZ_BACKSPACE 0x33
62#define QZ_INSERT 0x72
63#define QZ_HOME 0x73
64#define QZ_PAGEUP 0x74
65#define QZ_NUMLOCK 0x47
66#define QZ_KP_EQUALS 0x51
67#define QZ_KP_DIVIDE 0x4B
68#define QZ_KP_MULTIPLY 0x43
69#define QZ_TAB 0x30
70#define QZ_q 0x0C
71#define QZ_w 0x0D
72#define QZ_e 0x0E
73#define QZ_r 0x0F
74#define QZ_t 0x11
75#define QZ_y 0x10
76#define QZ_u 0x20
77#define QZ_i 0x22
78#define QZ_o 0x1F
79#define QZ_p 0x23
80#define QZ_LEFTBRACKET 0x21
81#define QZ_RIGHTBRACKET 0x1E
82#define QZ_BACKSLASH 0x2A
83#define QZ_DELETE 0x75
84#define QZ_END 0x77
85#define QZ_PAGEDOWN 0x79
86#define QZ_KP7 0x59
87#define QZ_KP8 0x5B
88#define QZ_KP9 0x5C
89#define QZ_KP_MINUS 0x4E
90#define QZ_CAPSLOCK 0x39
91#define QZ_a 0x00
92#define QZ_s 0x01
93#define QZ_d 0x02
94#define QZ_f 0x03
95#define QZ_g 0x05
96#define QZ_h 0x04
97#define QZ_j 0x26
98#define QZ_k 0x28
99#define QZ_l 0x25
100#define QZ_SEMICOLON 0x29
101#define QZ_QUOTE 0x27
102#define QZ_RETURN 0x24
103#define QZ_KP4 0x56
104#define QZ_KP5 0x57
105#define QZ_KP6 0x58
106#define QZ_KP_PLUS 0x45
107#define QZ_LSHIFT 0x38
108#define QZ_z 0x06
109#define QZ_x 0x07
110#define QZ_c 0x08
111#define QZ_v 0x09
112#define QZ_b 0x0B
113#define QZ_n 0x2D
114#define QZ_m 0x2E
115#define QZ_COMMA 0x2B
116#define QZ_PERIOD 0x2F
117#define QZ_SLASH 0x2C
118#if 1 /* Panther now defines right side keys */
119#define QZ_RSHIFT 0x3C
120#endif
121#define QZ_UP 0x7E
122#define QZ_KP1 0x53
123#define QZ_KP2 0x54
124#define QZ_KP3 0x55
125#define QZ_KP_ENTER 0x4C
126#define QZ_LCTRL 0x3B
127#define QZ_LALT 0x3A
128#define QZ_LMETA 0x37
129#define QZ_SPACE 0x31
130#if 1 /* Panther now defines right side keys */
131#define QZ_RMETA 0x36
132#define QZ_RALT 0x3D
133#define QZ_RCTRL 0x3E
134#endif
135#define QZ_LEFT 0x7B
136#define QZ_DOWN 0x7D
137#define QZ_RIGHT 0x7C
138#define QZ_KP0 0x52
139#define QZ_KP_PERIOD 0x41
140
141/* Wierd, these keys are on my iBook under Mac OS X */
142#define QZ_IBOOK_ENTER 0x34
143#define QZ_IBOOK_LEFT 0x3B
144#define QZ_IBOOK_RIGHT 0x3C
145#define QZ_IBOOK_DOWN 0x3D
146#define QZ_IBOOK_UP 0x3E
diff --git a/apps/plugins/sdl/src/video/quartz/SDL_QuartzVideo.h b/apps/plugins/sdl/src/video/quartz/SDL_QuartzVideo.h
deleted file mode 100644
index 7506e0cd10..0000000000
--- a/apps/plugins/sdl/src/video/quartz/SDL_QuartzVideo.h
+++ /dev/null
@@ -1,229 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 @file SDL_QuartzVideo.h
26 @author Darrell Walisser, Max Horn, et al.
27
28 @abstract SDL video driver for Mac OS X.
29
30 @discussion
31
32 TODO
33 - Hardware Cursor support with NSCursor instead of Carbon
34 - Keyboard repeat/mouse speed adjust (if needed)
35 - Multiple monitor support (currently only main display)
36 - Accelerated blitting support
37 - Fix white OpenGL window on minimize (fixed) (update: broken again on 10.2)
38 - Find out what events should be sent/ignored if window is minimized
39 - Find a way to deal with external resolution/depth switch while app is running
40 - Check accuracy of QZ_SetGamma()
41 Problems:
42 - OGL not working in full screen with software renderer
43 - SetColors sets palette correctly but clears framebuffer
44 - Crash in CG after several mode switches (I think this has been fixed)
45 - Retained windows don't draw their title bar quite right (OS Bug) (not using retained windows)
46 - Cursor in 8 bit modes is screwy (might just be Radeon PCI bug) (update: not just Radeon)
47 - Warping cursor delays mouse events for a fraction of a second,
48 there is a hack around this that helps a bit
49*/
50
51/* Needs to be first, so QuickTime.h doesn't include glext.h (10.4) */
52#include "SDL_opengl.h"
53
54#include <Cocoa/Cocoa.h>
55#include <Carbon/Carbon.h>
56#include <OpenGL/OpenGL.h> /* For CGL functions and types */
57#include <IOKit/IOKitLib.h> /* For powersave handling */
58#include <pthread.h>
59
60#include "SDL_thread.h"
61#include "SDL_video.h"
62#include "SDL_error.h"
63#include "SDL_timer.h"
64#include "SDL_loadso.h"
65#include "SDL_syswm.h"
66#include "../SDL_sysvideo.h"
67#include "../SDL_pixels_c.h"
68#include "../../events/SDL_events_c.h"
69
70
71#ifdef __powerpc__
72/*
73 This is a workaround to directly access NSOpenGLContext's CGL context
74 We need this to check for errors NSOpenGLContext doesn't support
75 Please note this is only used on PowerPC (Intel Macs are guaranteed to
76 have a better API for this, since it showed up in Mac OS X 10.3).
77*/
78@interface NSOpenGLContext (CGLContextAccess)
79- (CGLContextObj) cglContext;
80@end
81#endif
82
83/* use this to get the CGLContext; it handles Cocoa interface changes. */
84CGLContextObj QZ_GetCGLContextObj(NSOpenGLContext *nsctx);
85
86
87/* Main driver structure to store required state information */
88typedef struct SDL_PrivateVideoData {
89 BOOL use_new_mode_apis; /* 1 == >= 10.6 APIs available */
90 BOOL allow_screensaver; /* 0 == disable screensaver */
91 CGDirectDisplayID display; /* 0 == main display (only support single display) */
92 const void *mode; /* current mode of the display */
93 const void *save_mode; /* original mode of the display */
94 CGDirectPaletteRef palette; /* palette of an 8-bit display */
95 NSOpenGLContext *gl_context; /* OpenGL rendering context */
96 NSGraphicsContext *nsgfx_context; /* Cocoa graphics context */
97 Uint32 width, height, bpp; /* frequently used data about the display */
98 Uint32 flags; /* flags for current mode, for teardown purposes */
99 Uint32 video_set; /* boolean; indicates if video was set correctly */
100 Uint32 warp_flag; /* boolean; notify to event loop that a warp just occured */
101 Uint32 warp_ticks; /* timestamp when the warp occured */
102 NSWindow *window; /* Cocoa window to implement the SDL window */
103 NSView *view; /* the window's view; draw 2D and OpenGL into this view */
104 CGContextRef cg_context; /* CoreGraphics rendering context */
105 SDL_Surface *resize_icon; /* icon for the resize badge, we have to draw it by hand */
106 SDL_GrabMode current_grab_mode; /* default value is SDL_GRAB_OFF */
107 SDL_Rect **client_mode_list; /* resolution list to pass back to client */
108 SDLKey keymap[256]; /* Mac OS X to SDL key mapping */
109 Uint32 current_mods; /* current keyboard modifiers, to track modifier state */
110 NSText *field_edit; /* a field editor for keyboard composition processing */
111 Uint32 last_virtual_button;/* last virtual mouse button pressed */
112 io_connect_t power_connection; /* used with IOKit to detect wake from sleep */
113 Uint8 expect_mouse_up; /* used to determine when to send mouse up events */
114 Uint8 grab_state; /* used to manage grab behavior */
115 NSPoint cursor_loc; /* saved cursor coords, for activate/deactivate when grabbed */
116 BOOL cursor_should_be_visible; /* tells if cursor is supposed to be visible (SDL_ShowCursor) */
117 BOOL cursor_visible; /* tells if cursor is *actually* visible or not */
118 Uint8* sw_buffers[2]; /* pointers to the two software buffers for double-buffer emulation */
119 SDL_Thread *thread; /* thread for async updates to the screen */
120 SDL_sem *sem1, *sem2; /* synchronization for async screen updates */
121 Uint8 *current_buffer; /* the buffer being copied to the screen */
122 BOOL quit_thread; /* used to quit the async blitting thread */
123 SInt32 system_version; /* used to dis-/enable workarounds depending on the system version */
124
125 void *opengl_library; /* dynamically loaded OpenGL library. */
126} SDL_PrivateVideoData;
127
128#define _THIS SDL_VideoDevice *this
129#define display_id (this->hidden->display)
130#define mode (this->hidden->mode)
131#define save_mode (this->hidden->save_mode)
132#define use_new_mode_apis (this->hidden->use_new_mode_apis)
133#define allow_screensaver (this->hidden->allow_screensaver)
134#define palette (this->hidden->palette)
135#define gl_context (this->hidden->gl_context)
136#define nsgfx_context (this->hidden->nsgfx_context)
137#define device_width (this->hidden->width)
138#define device_height (this->hidden->height)
139#define device_bpp (this->hidden->bpp)
140#define mode_flags (this->hidden->flags)
141#define qz_window (this->hidden->window)
142#define window_view (this->hidden->view)
143#define cg_context (this->hidden->cg_context)
144#define video_set (this->hidden->video_set)
145#define warp_ticks (this->hidden->warp_ticks)
146#define warp_flag (this->hidden->warp_flag)
147#define resize_icon (this->hidden->resize_icon)
148#define current_grab_mode (this->hidden->current_grab_mode)
149#define client_mode_list (this->hidden->client_mode_list)
150#define keymap (this->hidden->keymap)
151#define current_mods (this->hidden->current_mods)
152#define field_edit (this->hidden->field_edit)
153#define last_virtual_button (this->hidden->last_virtual_button)
154#define power_connection (this->hidden->power_connection)
155#define expect_mouse_up (this->hidden->expect_mouse_up)
156#define grab_state (this->hidden->grab_state)
157#define cursor_loc (this->hidden->cursor_loc)
158#define cursor_should_be_visible (this->hidden->cursor_should_be_visible)
159#define cursor_visible (this->hidden->cursor_visible)
160#define sw_buffers (this->hidden->sw_buffers)
161#define sw_contexts (this->hidden->sw_contexts)
162#define thread (this->hidden->thread)
163#define sem1 (this->hidden->sem1)
164#define sem2 (this->hidden->sem2)
165#define current_buffer (this->hidden->current_buffer)
166#define quit_thread (this->hidden->quit_thread)
167#define system_version (this->hidden->system_version)
168#define opengl_library (this->hidden->opengl_library)
169
170/* grab states - the input is in one of these states */
171enum {
172 QZ_UNGRABBED = 0,
173 QZ_VISIBLE_GRAB,
174 QZ_INVISIBLE_GRAB
175};
176
177/* grab actions - these can change the grabbed state */
178enum {
179 QZ_ENABLE_GRAB = 0,
180 QZ_DISABLE_GRAB,
181 QZ_HIDECURSOR,
182 QZ_SHOWCURSOR
183};
184
185/* Gamma Functions */
186int QZ_SetGamma (_THIS, float red, float green, float blue);
187int QZ_GetGamma (_THIS, float *red, float *green, float *blue);
188int QZ_SetGammaRamp (_THIS, Uint16 *ramp);
189int QZ_GetGammaRamp (_THIS, Uint16 *ramp);
190
191/* OpenGL functions */
192int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags);
193void QZ_TearDownOpenGL (_THIS);
194void* QZ_GL_GetProcAddress (_THIS, const char *proc);
195int QZ_GL_GetAttribute (_THIS, SDL_GLattr attrib, int* value);
196int QZ_GL_MakeCurrent (_THIS);
197void QZ_GL_SwapBuffers (_THIS);
198int QZ_GL_LoadLibrary (_THIS, const char *location);
199
200/* Cursor and Mouse functions */
201void QZ_FreeWMCursor (_THIS, WMcursor *cursor);
202WMcursor* QZ_CreateWMCursor (_THIS, Uint8 *data, Uint8 *mask,
203 int w, int h, int hot_x, int hot_y);
204int QZ_ShowWMCursor (_THIS, WMcursor *cursor);
205void QZ_WarpWMCursor (_THIS, Uint16 x, Uint16 y);
206void QZ_MoveWMCursor (_THIS, int x, int y);
207void QZ_CheckMouseMode (_THIS);
208void QZ_UpdateMouse (_THIS);
209
210/* Event functions */
211void QZ_InitOSKeymap (_THIS);
212void QZ_PumpEvents (_THIS);
213
214/* Window Manager functions */
215void QZ_SetCaption (_THIS, const char *title, const char *icon);
216void QZ_SetIcon (_THIS, SDL_Surface *icon, Uint8 *mask);
217int QZ_IconifyWindow (_THIS);
218SDL_GrabMode QZ_GrabInput (_THIS, SDL_GrabMode grab_mode);
219/*int QZ_GetWMInfo (_THIS, SDL_SysWMinfo *info);*/
220
221/* Private functions (used internally) */
222void QZ_PrivateWarpCursor (_THIS, int x, int y);
223void QZ_ChangeGrabState (_THIS, int action);
224void QZ_RegisterForSleepNotifications (_THIS);
225void QZ_PrivateGlobalToLocal (_THIS, NSPoint *p);
226void QZ_PrivateCocoaToSDL (_THIS, NSPoint *p);
227BOOL QZ_IsMouseInWindow (_THIS);
228void QZ_DoActivate (_THIS);
229void QZ_DoDeactivate (_THIS);
diff --git a/apps/plugins/sdl/src/video/quartz/SDL_QuartzVideo.m b/apps/plugins/sdl/src/video/quartz/SDL_QuartzVideo.m
deleted file mode 100644
index fa04e9d107..0000000000
--- a/apps/plugins/sdl/src/video/quartz/SDL_QuartzVideo.m
+++ /dev/null
@@ -1,1689 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_QuartzVideo.h"
25#include "SDL_QuartzWindow.h"
26
27/* These APIs aren't just deprecated; they're gone from the headers in the
28 10.7 SDK. If we're using a >= 10.7 SDK, but targeting < 10.7, then we
29 force these function declarations. */
30#if ((MAC_OS_X_VERSION_MIN_REQUIRED < 1070) && (MAC_OS_X_VERSION_MAX_ALLOWED >= 1070))
31CG_EXTERN void *CGDisplayBaseAddress(CGDirectDisplayID display)
32 CG_AVAILABLE_BUT_DEPRECATED(__MAC_10_0, __MAC_10_6,
33 __IPHONE_NA, __IPHONE_NA);
34CG_EXTERN size_t CGDisplayBytesPerRow(CGDirectDisplayID display)
35 CG_AVAILABLE_BUT_DEPRECATED(__MAC_10_0, __MAC_10_6,
36 __IPHONE_NA, __IPHONE_NA);
37#endif
38
39
40static inline BOOL IS_LION_OR_LATER(_THIS)
41{
42 return (system_version >= 0x1070);
43}
44
45static inline BOOL IS_SNOW_LEOPARD_OR_LATER(_THIS)
46{
47 return (system_version >= 0x1060);
48}
49
50#if (MAC_OS_X_VERSION_MAX_ALLOWED < 1060) && !defined(__LP64__) /* Fixed in Snow Leopard */
51/*
52 Add methods to get at private members of NSScreen.
53 Since there is a bug in Apple's screen switching code
54 that does not update this variable when switching
55 to fullscreen, we'll set it manually (but only for the
56 main screen).
57*/
58@interface NSScreen (NSScreenAccess)
59- (void) setFrame:(NSRect)frame;
60@end
61
62@implementation NSScreen (NSScreenAccess)
63- (void) setFrame:(NSRect)frame;
64{
65 _frame = frame;
66}
67@end
68static inline void QZ_SetFrame(_THIS, NSScreen *nsscreen, NSRect frame)
69{
70 if (!IS_SNOW_LEOPARD_OR_LATER(this)) {
71 [nsscreen setFrame:frame];
72 }
73}
74#else
75static inline void QZ_SetFrame(_THIS, NSScreen *nsscreen, NSRect frame)
76{
77}
78#endif
79
80@interface SDLTranslatorResponder : NSTextView
81{
82}
83- (void) doCommandBySelector:(SEL)myselector;
84@end
85
86@implementation SDLTranslatorResponder
87- (void) doCommandBySelector:(SEL) myselector {}
88@end
89
90/* absent in 10.3.9. */
91CG_EXTERN CGImageRef CGBitmapContextCreateImage (CGContextRef);
92
93/* Bootstrap functions */
94static int QZ_Available ();
95static SDL_VideoDevice* QZ_CreateDevice (int device_index);
96static void QZ_DeleteDevice (SDL_VideoDevice *device);
97
98/* Initialization, Query, Setup, and Redrawing functions */
99static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format);
100
101static SDL_Rect** QZ_ListModes (_THIS, SDL_PixelFormat *format,
102 Uint32 flags);
103static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop, BOOL save_gl);
104
105static SDL_Surface* QZ_SetVideoMode (_THIS, SDL_Surface *current,
106 int width, int height, int bpp,
107 Uint32 flags);
108static int QZ_ToggleFullScreen (_THIS, int on);
109static int QZ_SetColors (_THIS, int first_color,
110 int num_colors, SDL_Color *colors);
111
112#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070)
113static int QZ_LockDoubleBuffer (_THIS, SDL_Surface *surface);
114static void QZ_UnlockDoubleBuffer (_THIS, SDL_Surface *surface);
115static int QZ_ThreadFlip (_THIS);
116static int QZ_FlipDoubleBuffer (_THIS, SDL_Surface *surface);
117static void QZ_DoubleBufferUpdate (_THIS, int num_rects, SDL_Rect *rects);
118static void QZ_DirectUpdate (_THIS, int num_rects, SDL_Rect *rects);
119#endif
120
121static void QZ_UpdateRects (_THIS, int num_rects, SDL_Rect *rects);
122static void QZ_VideoQuit (_THIS);
123
124static int QZ_LockHWSurface(_THIS, SDL_Surface *surface);
125static void QZ_UnlockHWSurface(_THIS, SDL_Surface *surface);
126static int QZ_AllocHWSurface(_THIS, SDL_Surface *surface);
127static void QZ_FreeHWSurface (_THIS, SDL_Surface *surface);
128
129/* Bootstrap binding, enables entry point into the driver */
130VideoBootStrap QZ_bootstrap = {
131 "Quartz", "Mac OS X CoreGraphics", QZ_Available, QZ_CreateDevice
132};
133
134/* Disable compiler warnings we can't avoid. */
135#if (defined(__GNUC__) && (__GNUC__ >= 4))
136# if (MAC_OS_X_VERSION_MAX_ALLOWED <= 1070)
137# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
138# endif
139#endif
140
141static void QZ_ReleaseDisplayMode(_THIS, const void *moderef)
142{
143 /* we only own these references in the 10.6+ API. */
144#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)
145 if (use_new_mode_apis) {
146 CGDisplayModeRelease((CGDisplayModeRef) moderef);
147 }
148#endif
149}
150
151static void QZ_ReleaseDisplayModeList(_THIS, CFArrayRef mode_list)
152{
153 /* we only own these references in the 10.6+ API. */
154#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)
155 if (use_new_mode_apis) {
156 CFRelease(mode_list);
157 }
158#endif
159}
160
161
162/* Bootstrap functions */
163static int QZ_Available ()
164{
165 return 1;
166}
167
168static SDL_VideoDevice* QZ_CreateDevice (int device_index)
169{
170#pragma unused (device_index)
171
172 SDL_VideoDevice *device;
173 SDL_PrivateVideoData *hidden;
174
175 device = (SDL_VideoDevice*) SDL_malloc (sizeof (*device) );
176 hidden = (SDL_PrivateVideoData*) SDL_malloc (sizeof (*hidden) );
177
178 if (device == NULL || hidden == NULL)
179 SDL_OutOfMemory ();
180
181 SDL_memset (device, 0, sizeof (*device) );
182 SDL_memset (hidden, 0, sizeof (*hidden) );
183
184 device->hidden = hidden;
185
186 device->VideoInit = QZ_VideoInit;
187 device->ListModes = QZ_ListModes;
188 device->SetVideoMode = QZ_SetVideoMode;
189 device->ToggleFullScreen = QZ_ToggleFullScreen;
190 device->UpdateMouse = QZ_UpdateMouse;
191 device->SetColors = QZ_SetColors;
192 /* device->UpdateRects = QZ_UpdateRects; this is determined by SetVideoMode() */
193 device->VideoQuit = QZ_VideoQuit;
194
195 device->LockHWSurface = QZ_LockHWSurface;
196 device->UnlockHWSurface = QZ_UnlockHWSurface;
197 device->AllocHWSurface = QZ_AllocHWSurface;
198 device->FreeHWSurface = QZ_FreeHWSurface;
199
200 device->SetGamma = QZ_SetGamma;
201 device->GetGamma = QZ_GetGamma;
202 device->SetGammaRamp = QZ_SetGammaRamp;
203 device->GetGammaRamp = QZ_GetGammaRamp;
204
205 device->GL_GetProcAddress = QZ_GL_GetProcAddress;
206 device->GL_GetAttribute = QZ_GL_GetAttribute;
207 device->GL_MakeCurrent = QZ_GL_MakeCurrent;
208 device->GL_SwapBuffers = QZ_GL_SwapBuffers;
209 device->GL_LoadLibrary = QZ_GL_LoadLibrary;
210
211 device->FreeWMCursor = QZ_FreeWMCursor;
212 device->CreateWMCursor = QZ_CreateWMCursor;
213 device->ShowWMCursor = QZ_ShowWMCursor;
214 device->WarpWMCursor = QZ_WarpWMCursor;
215 device->MoveWMCursor = QZ_MoveWMCursor;
216 device->CheckMouseMode = QZ_CheckMouseMode;
217 device->InitOSKeymap = QZ_InitOSKeymap;
218 device->PumpEvents = QZ_PumpEvents;
219
220 device->SetCaption = QZ_SetCaption;
221 device->SetIcon = QZ_SetIcon;
222 device->IconifyWindow = QZ_IconifyWindow;
223 /*device->GetWMInfo = QZ_GetWMInfo;*/
224 device->GrabInput = QZ_GrabInput;
225
226 /*
227 * This is a big hassle, needing QuickDraw and QuickTime on older
228 * systems, and god knows what on 10.6, so we immediately fail here,
229 * which causes SDL to make an RGB surface and manage the YUV overlay
230 * in software. Sorry. Use SDL 1.3 if you want YUV rendering in a pixel
231 * shader. :)
232 */
233 /*device->CreateYUVOverlay = QZ_CreateYUVOverlay;*/
234
235 device->free = QZ_DeleteDevice;
236
237 return device;
238}
239
240static void QZ_DeleteDevice (SDL_VideoDevice *device)
241{
242 _THIS = device;
243 QZ_ReleaseDisplayMode(this, save_mode);
244 QZ_ReleaseDisplayMode(this, mode);
245 SDL_free (device->hidden);
246 SDL_free (device);
247}
248
249static void QZ_GetModeInfo(_THIS, const void *_mode, Uint32 *w, Uint32 *h, Uint32 *bpp)
250{
251 *w = *h = *bpp = 0;
252 if (_mode == NULL) {
253 return;
254 }
255
256#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)
257 if (use_new_mode_apis) {
258 CGDisplayModeRef vidmode = (CGDisplayModeRef) _mode;
259 CFStringRef fmt = CGDisplayModeCopyPixelEncoding(vidmode);
260
261 *w = (Uint32) CGDisplayModeGetWidth(vidmode);
262 *h = (Uint32) CGDisplayModeGetHeight(vidmode);
263
264 /* we only care about the 32-bit modes... */
265 if (CFStringCompare(fmt, CFSTR(IO32BitDirectPixels),
266 kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
267 *bpp = 32;
268 }
269
270 CFRelease(fmt);
271 }
272#endif
273
274#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1060)
275 if (!use_new_mode_apis) {
276 CFDictionaryRef vidmode = (CFDictionaryRef) _mode;
277 CFNumberGetValue (
278 CFDictionaryGetValue (vidmode, kCGDisplayBitsPerPixel),
279 kCFNumberSInt32Type, bpp);
280
281 CFNumberGetValue (
282 CFDictionaryGetValue (vidmode, kCGDisplayWidth),
283 kCFNumberSInt32Type, w);
284
285 CFNumberGetValue (
286 CFDictionaryGetValue (vidmode, kCGDisplayHeight),
287 kCFNumberSInt32Type, h);
288 }
289#endif
290
291 /* we only care about the 32-bit modes... */
292 if (*bpp != 32) {
293 *bpp = 0;
294 }
295}
296
297static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format)
298{
299 NSRect r = NSMakeRect(0.0, 0.0, 0.0, 0.0);
300 const char *env = NULL;
301
302 if ( Gestalt(gestaltSystemVersion, &system_version) != noErr )
303 system_version = 0;
304
305 use_new_mode_apis = NO;
306
307#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)
308 use_new_mode_apis = IS_SNOW_LEOPARD_OR_LATER(this);
309#endif
310
311 /* Initialize the video settings; this data persists between mode switches */
312 display_id = kCGDirectMainDisplay;
313
314#if 0 /* The mouse event code needs to take this into account... */
315 env = getenv("SDL_VIDEO_FULLSCREEN_DISPLAY");
316 if ( env ) {
317 int monitor = SDL_atoi(env);
318 CGDirectDisplayID activeDspys [3];
319 CGDisplayCount dspyCnt;
320 CGGetActiveDisplayList (3, activeDspys, &dspyCnt);
321 if ( monitor >= 0 && monitor < dspyCnt ) {
322 display_id = activeDspys[monitor];
323 }
324 }
325#endif
326
327#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)
328 if (use_new_mode_apis) {
329 save_mode = CGDisplayCopyDisplayMode(display_id);
330 }
331#endif
332
333#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1060)
334 if (!use_new_mode_apis) {
335 save_mode = CGDisplayCurrentMode(display_id);
336 }
337#endif
338
339#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070)
340 if (!IS_LION_OR_LATER(this)) {
341 palette = CGPaletteCreateDefaultColorPalette();
342 }
343#endif
344
345 if (save_mode == NULL) {
346 SDL_SetError("Couldn't figure out current display mode.");
347 return -1;
348 }
349
350 /* Allow environment override of screensaver disable. */
351 env = SDL_getenv("SDL_VIDEO_ALLOW_SCREENSAVER");
352 if ( env ) {
353 allow_screensaver = SDL_atoi(env);
354 } else {
355#ifdef SDL_VIDEO_DISABLE_SCREENSAVER
356 allow_screensaver = 0;
357#else
358 allow_screensaver = 1;
359#endif
360 }
361
362 /* Gather some information that is useful to know about the display */
363 QZ_GetModeInfo(this, save_mode, &device_width, &device_height, &device_bpp);
364 if (device_bpp == 0) {
365 QZ_ReleaseDisplayMode(this, save_mode);
366 save_mode = NULL;
367 SDL_SetError("Unsupported display mode");
368 return -1;
369 }
370
371 /* Determine the current screen size */
372 this->info.current_w = device_width;
373 this->info.current_h = device_height;
374
375 /* Determine the default screen depth */
376 video_format->BitsPerPixel = device_bpp;
377
378 /* Set misc globals */
379 current_grab_mode = SDL_GRAB_OFF;
380 cursor_should_be_visible = YES;
381 cursor_visible = YES;
382 current_mods = 0;
383 field_edit = [[SDLTranslatorResponder alloc] initWithFrame:r];
384
385 /* register for sleep notifications so wake from sleep generates SDL_VIDEOEXPOSE */
386 QZ_RegisterForSleepNotifications (this);
387
388 /* Fill in some window manager capabilities */
389 this->info.wm_available = 1;
390
391 return 0;
392}
393
394static SDL_Rect** QZ_ListModes (_THIS, SDL_PixelFormat *format, Uint32 flags)
395{
396 CFArrayRef mode_list = NULL; /* list of available fullscreen modes */
397 CFIndex num_modes;
398 CFIndex i;
399
400 int list_size = 0;
401
402 /* Any windowed mode is acceptable */
403 if ( (flags & SDL_FULLSCREEN) == 0 )
404 return (SDL_Rect**)-1;
405
406 /* Free memory from previous call, if any */
407 if ( client_mode_list != NULL ) {
408 int i;
409
410 for (i = 0; client_mode_list[i] != NULL; i++)
411 SDL_free (client_mode_list[i]);
412
413 SDL_free (client_mode_list);
414 client_mode_list = NULL;
415 }
416
417#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)
418 if (use_new_mode_apis) {
419 mode_list = CGDisplayCopyAllDisplayModes(display_id, NULL);
420 }
421#endif
422
423#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1060)
424 if (!use_new_mode_apis) {
425 mode_list = CGDisplayAvailableModes(display_id);
426 }
427#endif
428
429 num_modes = CFArrayGetCount (mode_list);
430
431 /* Build list of modes with the requested bpp */
432 for (i = 0; i < num_modes; i++) {
433 Uint32 width, height, bpp;
434 const void *onemode = CFArrayGetValueAtIndex(mode_list, i);
435
436 QZ_GetModeInfo(this, onemode, &width, &height, &bpp);
437
438 if (bpp && (bpp == format->BitsPerPixel)) {
439 int hasMode = SDL_FALSE;
440 int i;
441
442 /* Check if mode is already in the list */
443 for (i = 0; i < list_size; i++) {
444 if (client_mode_list[i]->w == width &&
445 client_mode_list[i]->h == height) {
446 hasMode = SDL_TRUE;
447 break;
448 }
449 }
450
451 /* Grow the list and add mode to the list */
452 if ( ! hasMode ) {
453 SDL_Rect *rect;
454
455 list_size++;
456
457 if (client_mode_list == NULL)
458 client_mode_list = (SDL_Rect**)
459 SDL_malloc (sizeof(*client_mode_list) * (list_size+1) );
460 else {
461 /* !!! FIXME: this leaks memory if SDL_realloc() fails! */
462 client_mode_list = (SDL_Rect**)
463 SDL_realloc (client_mode_list, sizeof(*client_mode_list) * (list_size+1));
464 }
465
466 rect = (SDL_Rect*) SDL_malloc (sizeof(**client_mode_list));
467
468 if (client_mode_list == NULL || rect == NULL) {
469 QZ_ReleaseDisplayModeList(this, mode_list);
470 SDL_OutOfMemory ();
471 return NULL;
472 }
473
474 rect->x = rect->y = 0;
475 rect->w = width;
476 rect->h = height;
477
478 client_mode_list[list_size-1] = rect;
479 client_mode_list[list_size] = NULL;
480 }
481 }
482 }
483
484 QZ_ReleaseDisplayModeList(this, mode_list);
485
486 /* Sort list largest to smallest (by area) */
487 {
488 int i, j;
489 for (i = 0; i < list_size; i++) {
490 for (j = 0; j < list_size-1; j++) {
491
492 int area1, area2;
493 area1 = client_mode_list[j]->w * client_mode_list[j]->h;
494 area2 = client_mode_list[j+1]->w * client_mode_list[j+1]->h;
495
496 if (area1 < area2) {
497 SDL_Rect *tmp = client_mode_list[j];
498 client_mode_list[j] = client_mode_list[j+1];
499 client_mode_list[j+1] = tmp;
500 }
501 }
502 }
503 }
504
505 return client_mode_list;
506}
507
508static SDL_bool QZ_WindowPosition(_THIS, int *x, int *y)
509{
510 const char *window = getenv("SDL_VIDEO_WINDOW_POS");
511 if ( window ) {
512 if ( sscanf(window, "%d,%d", x, y) == 2 ) {
513 return SDL_TRUE;
514 }
515 }
516 return SDL_FALSE;
517}
518
519static CGError QZ_SetDisplayMode(_THIS, const void *vidmode)
520{
521#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)
522 if (use_new_mode_apis) {
523 return CGDisplaySetDisplayMode(display_id, (CGDisplayModeRef) vidmode, NULL);
524 }
525#endif
526
527#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1060)
528 if (!use_new_mode_apis) {
529 return CGDisplaySwitchToMode(display_id, (CFDictionaryRef) vidmode);
530 }
531#endif
532
533 return kCGErrorFailure;
534}
535
536static inline CGError QZ_RestoreDisplayMode(_THIS)
537{
538 return QZ_SetDisplayMode(this, save_mode);
539}
540
541static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop, BOOL save_gl)
542{
543 /* Reset values that may change between switches */
544 this->info.blit_fill = 0;
545 this->FillHWRect = NULL;
546 this->UpdateRects = NULL;
547 this->LockHWSurface = NULL;
548 this->UnlockHWSurface = NULL;
549
550 if (cg_context) {
551 CGContextFlush (cg_context);
552 CGContextRelease (cg_context);
553 cg_context = nil;
554 }
555
556 /* Release fullscreen resources */
557 if ( mode_flags & SDL_FULLSCREEN ) {
558
559 NSRect screen_rect;
560
561 /* Release double buffer stuff */
562#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070)
563 if ( !IS_LION_OR_LATER(this) && (mode_flags & SDL_DOUBLEBUF) ) {
564 quit_thread = YES;
565 SDL_SemPost (sem1);
566 SDL_WaitThread (thread, NULL);
567 SDL_DestroySemaphore (sem1);
568 SDL_DestroySemaphore (sem2);
569 SDL_free (sw_buffers[0]);
570 }
571#endif
572
573 /* If we still have a valid window, close it. */
574 if ( qz_window ) {
575 NSCAssert([ qz_window delegate ] == nil, @"full screen window shouldn't have a delegate"); /* if that should ever change, we'd have to release it here */
576 [ qz_window close ]; /* includes release because [qz_window isReleasedWhenClosed] */
577 qz_window = nil;
578 window_view = nil;
579 }
580 /*
581 Release the OpenGL context
582 Do this first to avoid trash on the display before fade
583 */
584 if ( mode_flags & SDL_OPENGL ) {
585 if (!save_gl) {
586 QZ_TearDownOpenGL (this);
587 }
588
589 #ifdef __powerpc__ /* we only use this for pre-10.3 compatibility. */
590 CGLSetFullScreen (NULL);
591 #endif
592 }
593 if (to_desktop) {
594 /* !!! FIXME: keep an eye on this.
595 * This API is officially unavailable for 64-bit binaries.
596 * It happens to work, as of 10.7, but we're going to see if
597 * we can just simply do without it on newer OSes...
598 */
599 #if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070) && !defined(__LP64__)
600 if ( !IS_LION_OR_LATER(this) ) {
601 ShowMenuBar ();
602 }
603 #endif
604
605 /* Restore original screen resolution/bpp */
606 QZ_RestoreDisplayMode (this);
607 CGReleaseAllDisplays ();
608 /*
609 Reset the main screen's rectangle
610 See comment in QZ_SetVideoFullscreen for why we do this
611 */
612 screen_rect = NSMakeRect(0,0,device_width,device_height);
613 QZ_SetFrame(this, [ NSScreen mainScreen ], screen_rect);
614 }
615 }
616 /* Release window mode resources */
617 else {
618 id delegate = [ qz_window delegate ];
619 [ qz_window close ]; /* includes release because [qz_window isReleasedWhenClosed] */
620 if (delegate != nil) [ delegate release ];
621 qz_window = nil;
622 window_view = nil;
623
624 /* Release the OpenGL context */
625 if ( mode_flags & SDL_OPENGL ) {
626 if (!save_gl) {
627 QZ_TearDownOpenGL (this);
628 }
629 }
630 }
631
632 /* Signal successful teardown */
633 video_set = SDL_FALSE;
634}
635
636static const void *QZ_BestMode(_THIS, const int bpp, const int w, const int h)
637{
638 const void *best = NULL;
639
640 if (bpp == 0) {
641 return NULL;
642 }
643
644#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)
645 if (use_new_mode_apis) {
646 /* apparently, we have to roll our own now. :/ */
647 CFArrayRef mode_list = CGDisplayCopyAllDisplayModes(display_id, NULL);
648 if (mode_list != NULL) {
649 const CFIndex num_modes = CFArrayGetCount(mode_list);
650 CFIndex i;
651 for (i = 0; i < num_modes; i++) {
652 const void *vidmode = CFArrayGetValueAtIndex(mode_list, i);
653 Uint32 thisw, thish, thisbpp;
654 QZ_GetModeInfo(this, vidmode, &thisw, &thish, &thisbpp);
655
656 /* We only care about exact matches, apparently. */
657 if ((thisbpp == bpp) && (thisw == w) && (thish == h)) {
658 best = vidmode;
659 break; /* got it! */
660 }
661 }
662 CGDisplayModeRetain((CGDisplayModeRef) best); /* NULL is ok */
663 CFRelease(mode_list);
664 }
665 }
666#endif
667
668#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1060)
669 if (!use_new_mode_apis) {
670 boolean_t exact = 0;
671 best = CGDisplayBestModeForParameters(display_id, bpp, w, h, &exact);
672 if (!exact) {
673 best = NULL;
674 }
675 }
676#endif
677
678 return best;
679}
680
681static SDL_Surface* QZ_SetVideoFullScreen (_THIS, SDL_Surface *current, int width,
682 int height, int bpp, Uint32 flags,
683 const BOOL save_gl)
684{
685 const BOOL isLion = IS_LION_OR_LATER(this);
686 NSRect screen_rect;
687 CGError error;
688 NSRect contentRect;
689 CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken;
690
691 current->flags = SDL_FULLSCREEN;
692 current->w = width;
693 current->h = height;
694
695 contentRect = NSMakeRect (0, 0, width, height);
696
697 /* Fade to black to hide resolution-switching flicker (and garbage
698 that is displayed by a destroyed OpenGL context, if applicable) */
699 if ( CGAcquireDisplayFadeReservation (5, &fade_token) == kCGErrorSuccess ) {
700 CGDisplayFade (fade_token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE);
701 }
702
703 /* Destroy any previous mode */
704 if (video_set == SDL_TRUE)
705 QZ_UnsetVideoMode (this, FALSE, save_gl);
706
707 /* Sorry, QuickDraw was ripped out. */
708 if (getenv("SDL_NSWindowPointer") || getenv("SDL_NSQuickDrawViewPointer")) {
709 SDL_SetError ("Embedded QuickDraw windows are no longer supported");
710 goto ERR_NO_MATCH;
711 }
712
713 QZ_ReleaseDisplayMode(this, mode); /* NULL is okay. */
714
715 /* See if requested mode exists */
716 mode = QZ_BestMode(this, bpp, width, height);
717
718 /* Require an exact match to the requested mode */
719 if ( mode == NULL ) {
720 SDL_SetError ("Failed to find display resolution: %dx%dx%d", width, height, bpp);
721 goto ERR_NO_MATCH;
722 }
723
724 /* Put up the blanking window (a window above all other windows) */
725 if (getenv ("SDL_SINGLEDISPLAY"))
726 error = CGDisplayCapture (display_id);
727 else
728 error = CGCaptureAllDisplays ();
729
730 if ( CGDisplayNoErr != error ) {
731 SDL_SetError ("Failed capturing display");
732 goto ERR_NO_CAPTURE;
733 }
734
735 /* Do the physical switch */
736 if ( CGDisplayNoErr != QZ_SetDisplayMode(this, mode) ) {
737 SDL_SetError ("Failed switching display resolution");
738 goto ERR_NO_SWITCH;
739 }
740
741#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070)
742 if ( !isLion ) {
743 current->pixels = (Uint32*) CGDisplayBaseAddress (display_id);
744 current->pitch = CGDisplayBytesPerRow (display_id);
745
746 current->flags |= SDL_HWSURFACE;
747 current->flags |= SDL_PREALLOC;
748 /* current->hwdata = (void *) CGDisplayGetDrawingContext (display_id); */
749
750 this->UpdateRects = QZ_DirectUpdate;
751 this->LockHWSurface = QZ_LockHWSurface;
752 this->UnlockHWSurface = QZ_UnlockHWSurface;
753
754 /* Setup double-buffer emulation */
755 if ( flags & SDL_DOUBLEBUF ) {
756
757 /*
758 Setup a software backing store for reasonable results when
759 double buffering is requested (since a single-buffered hardware
760 surface looks hideous).
761
762 The actual screen blit occurs in a separate thread to allow
763 other blitting while waiting on the VBL (and hence results in higher framerates).
764 */
765 this->LockHWSurface = NULL;
766 this->UnlockHWSurface = NULL;
767 this->UpdateRects = NULL;
768
769 current->flags |= (SDL_HWSURFACE|SDL_DOUBLEBUF);
770 this->UpdateRects = QZ_DoubleBufferUpdate;
771 this->LockHWSurface = QZ_LockDoubleBuffer;
772 this->UnlockHWSurface = QZ_UnlockDoubleBuffer;
773 this->FlipHWSurface = QZ_FlipDoubleBuffer;
774
775 current->pixels = SDL_malloc (current->pitch * current->h * 2);
776 if (current->pixels == NULL) {
777 SDL_OutOfMemory ();
778 goto ERR_DOUBLEBUF;
779 }
780
781 sw_buffers[0] = current->pixels;
782 sw_buffers[1] = (Uint8*)current->pixels + current->pitch * current->h;
783
784 quit_thread = NO;
785 sem1 = SDL_CreateSemaphore (0);
786 sem2 = SDL_CreateSemaphore (1);
787 thread = SDL_CreateThread ((int (*)(void *))QZ_ThreadFlip, this);
788 }
789
790 if ( CGDisplayCanSetPalette (display_id) )
791 current->flags |= SDL_HWPALETTE;
792 }
793#endif
794
795 /* Check if we should recreate the window */
796 if (qz_window == nil) {
797 /* Manually create a window, avoids having a nib file resource */
798 qz_window = [ [ SDL_QuartzWindow alloc ]
799 initWithContentRect:contentRect
800 styleMask:(isLion ? NSBorderlessWindowMask : 0)
801 backing:NSBackingStoreBuffered
802 defer:NO ];
803
804 if (qz_window != nil) {
805 [ qz_window setAcceptsMouseMovedEvents:YES ];
806 [ qz_window setViewsNeedDisplay:NO ];
807 if (isLion) {
808 [ qz_window setContentView: [ [ [ SDL_QuartzView alloc ] init ] autorelease ] ];
809 }
810 }
811 }
812 /* We already have a window, just change its size */
813 else {
814 [ qz_window setContentSize:contentRect.size ];
815 current->flags |= (SDL_NOFRAME|SDL_RESIZABLE) & mode_flags;
816 [ window_view setFrameSize:contentRect.size ];
817 }
818
819 /* Setup OpenGL for a fullscreen context */
820 if (flags & SDL_OPENGL) {
821
822 if ( ! save_gl ) {
823 if ( ! QZ_SetupOpenGL (this, bpp, flags) ) {
824 goto ERR_NO_GL;
825 }
826 }
827
828 /* Initialize the NSView and add it to our window. The presence of a valid window and
829 view allow the cursor to be changed whilst in fullscreen.*/
830 window_view = [ [ NSView alloc ] initWithFrame:contentRect ];
831
832 if ( isLion ) {
833 [ window_view setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable ];
834 }
835
836 [ [ qz_window contentView ] addSubview:window_view ];
837
838 /* Apparently Lion checks some version flag set by the linker
839 and changes API behavior. Annoying. */
840 if ( isLion ) {
841 [ qz_window setLevel:CGShieldingWindowLevel() ];
842 [ gl_context setView: window_view ];
843 //[ gl_context setFullScreen ];
844 [ gl_context update ];
845 }
846
847#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070)
848 if ( !isLion ) {
849 CGLError err;
850 CGLContextObj ctx;
851
852 [ qz_window setLevel:NSNormalWindowLevel ];
853 ctx = QZ_GetCGLContextObj (gl_context);
854 err = CGLSetFullScreen (ctx);
855
856 if (err) {
857 SDL_SetError ("Error setting OpenGL fullscreen: %s", CGLErrorString(err));
858 goto ERR_NO_GL;
859 }
860 }
861#endif
862
863 [ window_view release ];
864 [ gl_context makeCurrentContext];
865
866 glClear (GL_COLOR_BUFFER_BIT);
867
868 [ gl_context flushBuffer ];
869
870 current->flags |= SDL_OPENGL;
871 } else if (isLion) { /* For 2D, we build a CGBitmapContext */
872 CGColorSpaceRef cgColorspace;
873
874 /* Only recreate the view if it doesn't already exist */
875 if (window_view == nil) {
876 window_view = [ [ NSView alloc ] initWithFrame:contentRect ];
877 [ window_view setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable ];
878 [ [ qz_window contentView ] addSubview:window_view ];
879 [ window_view release ];
880 }
881
882 cgColorspace = CGColorSpaceCreateDeviceRGB();
883 current->pitch = 4 * current->w;
884 current->pixels = SDL_malloc (current->h * current->pitch);
885
886 cg_context = CGBitmapContextCreate (current->pixels, current->w, current->h,
887 8, current->pitch, cgColorspace,
888 kCGImageAlphaNoneSkipFirst);
889 CGColorSpaceRelease (cgColorspace);
890
891 current->flags |= SDL_SWSURFACE;
892 current->flags |= SDL_ASYNCBLIT;
893 current->hwdata = (void *) cg_context;
894
895 /* Force this window to draw above _everything_. */
896 [ qz_window setLevel:CGShieldingWindowLevel() ];
897
898 this->UpdateRects = QZ_UpdateRects;
899 this->LockHWSurface = QZ_LockHWSurface;
900 this->UnlockHWSurface = QZ_UnlockHWSurface;
901 }
902
903 if (isLion) {
904 [ qz_window setHasShadow:NO];
905 [ qz_window setOpaque:YES];
906 [ qz_window makeKeyAndOrderFront:nil ];
907 }
908
909 /* !!! FIXME: keep an eye on this.
910 * This API is officially unavailable for 64-bit binaries.
911 * It happens to work, as of 10.7, but we're going to see if
912 * we can just simply do without it on newer OSes...
913 */
914 #if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070) && !defined(__LP64__)
915 if ( !isLion ) {
916 /* If we don't hide menu bar, it will get events and interrupt the program */
917 HideMenuBar ();
918 }
919 #endif
920
921 /* Fade in again (asynchronously) */
922 if ( fade_token != kCGDisplayFadeReservationInvalidToken ) {
923 CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
924 CGReleaseDisplayFadeReservation(fade_token);
925 }
926
927 /*
928 There is a bug in Cocoa where NSScreen doesn't synchronize
929 with CGDirectDisplay, so the main screen's frame is wrong.
930 As a result, coordinate translation produces incorrect results.
931 We can hack around this bug by setting the screen rect
932 ourselves. This hack should be removed if/when the bug is fixed.
933 */
934 screen_rect = NSMakeRect(0,0,width,height);
935 QZ_SetFrame(this, [ NSScreen mainScreen ], screen_rect);
936
937 /* Save the flags to ensure correct tear-down */
938 mode_flags = current->flags;
939
940 /* Set app state, hide cursor if necessary, ... */
941 QZ_DoActivate(this);
942
943 return current;
944
945 /* Since the blanking window covers *all* windows (even force quit) correct recovery is crucial */
946ERR_NO_GL: goto ERR_DOUBLEBUF; /* this goto is to stop a compiler warning on newer SDKs. */
947ERR_DOUBLEBUF: QZ_RestoreDisplayMode(this);
948ERR_NO_SWITCH: CGReleaseAllDisplays ();
949ERR_NO_CAPTURE:
950ERR_NO_MATCH: if ( fade_token != kCGDisplayFadeReservationInvalidToken ) {
951 CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
952 CGReleaseDisplayFadeReservation (fade_token);
953 }
954 return NULL;
955}
956
957static SDL_Surface* QZ_SetVideoWindowed (_THIS, SDL_Surface *current, int width,
958 int height, int *bpp, Uint32 flags,
959 const BOOL save_gl)
960{
961 unsigned int style;
962 NSRect contentRect;
963 int center_window = 1;
964 int origin_x, origin_y;
965 CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken;
966
967 current->flags = 0;
968 current->w = width;
969 current->h = height;
970
971 contentRect = NSMakeRect (0, 0, width, height);
972
973 /*
974 Check if we should completely destroy the previous mode
975 - If it is fullscreen
976 - If it has different noframe or resizable attribute
977 - If it is OpenGL (since gl attributes could be different)
978 - If new mode is OpenGL, but previous mode wasn't
979 */
980 if (video_set == SDL_TRUE) {
981 if (mode_flags & SDL_FULLSCREEN) {
982 /* Fade to black to hide resolution-switching flicker (and garbage
983 that is displayed by a destroyed OpenGL context, if applicable) */
984 if (CGAcquireDisplayFadeReservation (5, &fade_token) == kCGErrorSuccess) {
985 CGDisplayFade (fade_token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE);
986 }
987 QZ_UnsetVideoMode (this, TRUE, save_gl);
988 }
989 else if ( ((mode_flags ^ flags) & (SDL_NOFRAME|SDL_RESIZABLE)) ||
990 (mode_flags & SDL_OPENGL) ||
991 (flags & SDL_OPENGL) ) {
992 QZ_UnsetVideoMode (this, TRUE, save_gl);
993 }
994 }
995
996 /* Sorry, QuickDraw was ripped out. */
997 if (getenv("SDL_NSWindowPointer") || getenv("SDL_NSQuickDrawViewPointer")) {
998 SDL_SetError ("Embedded QuickDraw windows are no longer supported");
999 if (fade_token != kCGDisplayFadeReservationInvalidToken) {
1000 CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
1001 CGReleaseDisplayFadeReservation (fade_token);
1002 }
1003 return NULL;
1004 }
1005
1006 /* Check if we should recreate the window */
1007 if (qz_window == nil) {
1008
1009 /* Set the window style based on input flags */
1010 if ( flags & SDL_NOFRAME ) {
1011 style = NSBorderlessWindowMask;
1012 current->flags |= SDL_NOFRAME;
1013 } else {
1014 style = NSTitledWindowMask;
1015 style |= (NSMiniaturizableWindowMask | NSClosableWindowMask);
1016 if ( flags & SDL_RESIZABLE ) {
1017 style |= NSResizableWindowMask;
1018 current->flags |= SDL_RESIZABLE;
1019 }
1020 }
1021
1022 /* Manually create a window, avoids having a nib file resource */
1023 qz_window = [ [ SDL_QuartzWindow alloc ]
1024 initWithContentRect:contentRect
1025 styleMask:style
1026 backing:NSBackingStoreBuffered
1027 defer:NO ];
1028
1029 if (qz_window == nil) {
1030 SDL_SetError ("Could not create the Cocoa window");
1031 if (fade_token != kCGDisplayFadeReservationInvalidToken) {
1032 CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
1033 CGReleaseDisplayFadeReservation (fade_token);
1034 }
1035 return NULL;
1036 }
1037
1038 /*[ qz_window setReleasedWhenClosed:YES ];*/ /* no need to set this as it's the default for NSWindows */
1039 QZ_SetCaption(this, this->wm_title, this->wm_icon);
1040 [ qz_window setAcceptsMouseMovedEvents:YES ];
1041 [ qz_window setViewsNeedDisplay:NO ];
1042
1043 if ( QZ_WindowPosition(this, &origin_x, &origin_y) ) {
1044 /* have to flip the Y value (NSPoint is lower left corner origin) */
1045 [ qz_window setFrameTopLeftPoint:NSMakePoint((float) origin_x, (float) (this->info.current_h - origin_y))];
1046 center_window = 0;
1047 } else if ( center_window ) {
1048 [ qz_window center ];
1049 }
1050
1051 [ qz_window setDelegate:
1052 [ [ SDL_QuartzWindowDelegate alloc ] init ] ];
1053 [ qz_window setContentView: [ [ [ SDL_QuartzView alloc ] init ] autorelease ] ];
1054 }
1055 /* We already have a window, just change its size */
1056 else {
1057 [ qz_window setContentSize:contentRect.size ];
1058 current->flags |= (SDL_NOFRAME|SDL_RESIZABLE) & mode_flags;
1059 [ window_view setFrameSize:contentRect.size ];
1060 }
1061
1062 /* For OpenGL, we bind the context to a subview */
1063 if ( flags & SDL_OPENGL ) {
1064
1065 if ( ! save_gl ) {
1066 if ( ! QZ_SetupOpenGL (this, *bpp, flags) ) {
1067 if (fade_token != kCGDisplayFadeReservationInvalidToken) {
1068 CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
1069 CGReleaseDisplayFadeReservation (fade_token);
1070 }
1071 return NULL;
1072 }
1073 }
1074
1075 window_view = [ [ NSView alloc ] initWithFrame:contentRect ];
1076 [ window_view setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable ];
1077 [ [ qz_window contentView ] addSubview:window_view ];
1078 [ gl_context setView: window_view ];
1079 [ window_view release ];
1080 [ gl_context makeCurrentContext];
1081 [ qz_window makeKeyAndOrderFront:nil ];
1082 current->flags |= SDL_OPENGL;
1083 }
1084 /* For 2D, we build a CGBitmapContext */
1085 else {
1086 CGColorSpaceRef cgColorspace;
1087
1088 /* Only recreate the view if it doesn't already exist */
1089 if (window_view == nil) {
1090
1091 window_view = [ [ NSView alloc ] initWithFrame:contentRect ];
1092 [ window_view setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable ];
1093 [ [ qz_window contentView ] addSubview:window_view ];
1094 [ window_view release ];
1095 [ qz_window makeKeyAndOrderFront:nil ];
1096 }
1097
1098 cgColorspace = CGColorSpaceCreateDeviceRGB();
1099 current->pitch = 4 * current->w;
1100 current->pixels = SDL_malloc (current->h * current->pitch);
1101
1102 cg_context = CGBitmapContextCreate (current->pixels, current->w, current->h,
1103 8, current->pitch, cgColorspace,
1104 kCGImageAlphaNoneSkipFirst);
1105 CGColorSpaceRelease (cgColorspace);
1106
1107 current->flags |= SDL_SWSURFACE;
1108 current->flags |= SDL_ASYNCBLIT;
1109 current->hwdata = (void *) cg_context;
1110
1111 this->UpdateRects = QZ_UpdateRects;
1112 this->LockHWSurface = QZ_LockHWSurface;
1113 this->UnlockHWSurface = QZ_UnlockHWSurface;
1114 }
1115
1116 /* Save flags to ensure correct teardown */
1117 mode_flags = current->flags;
1118
1119 /* Fade in again (asynchronously) if we came from a fullscreen mode and faded to black */
1120 if (fade_token != kCGDisplayFadeReservationInvalidToken) {
1121 CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
1122 CGReleaseDisplayFadeReservation (fade_token);
1123 }
1124
1125 return current;
1126}
1127
1128
1129static SDL_Surface* QZ_SetVideoModeInternal (_THIS, SDL_Surface *current,
1130 int width, int height, int bpp,
1131 Uint32 flags, BOOL save_gl)
1132{
1133 const BOOL isLion = IS_LION_OR_LATER(this);
1134
1135 current->flags = 0;
1136 current->pixels = NULL;
1137
1138 /* Setup full screen video */
1139 if ( flags & SDL_FULLSCREEN ) {
1140 if ( isLion ) {
1141 bpp = 32;
1142 }
1143 current = QZ_SetVideoFullScreen (this, current, width, height, bpp, flags, save_gl );
1144 if (current == NULL)
1145 return NULL;
1146 }
1147 /* Setup windowed video */
1148 else {
1149 /* Force bpp to 32 */
1150 bpp = 32;
1151 current = QZ_SetVideoWindowed (this, current, width, height, &bpp, flags, save_gl );
1152 if (current == NULL)
1153 return NULL;
1154 }
1155
1156 if (qz_window != nil) {
1157 nsgfx_context = [NSGraphicsContext graphicsContextWithWindow:qz_window];
1158 [NSGraphicsContext setCurrentContext:nsgfx_context];
1159 }
1160
1161 /* Setup the new pixel format */
1162 {
1163 int amask = 0,
1164 rmask = 0,
1165 gmask = 0,
1166 bmask = 0;
1167
1168 switch (bpp) {
1169 case 16: /* (1)-5-5-5 RGB */
1170 amask = 0;
1171 rmask = 0x7C00;
1172 gmask = 0x03E0;
1173 bmask = 0x001F;
1174 break;
1175 case 24:
1176 SDL_SetError ("24bpp is not available");
1177 return NULL;
1178 case 32: /* (8)-8-8-8 ARGB */
1179 amask = 0x00000000;
1180 if ( (!isLion) && (flags & SDL_FULLSCREEN) ) {
1181 rmask = 0x00FF0000;
1182 gmask = 0x0000FF00;
1183 bmask = 0x000000FF;
1184 } else {
1185#if SDL_BYTEORDER == SDL_LIL_ENDIAN
1186 rmask = 0x0000FF00;
1187 gmask = 0x00FF0000;
1188 bmask = 0xFF000000;
1189#else
1190 rmask = 0x00FF0000;
1191 gmask = 0x0000FF00;
1192 bmask = 0x000000FF;
1193#endif
1194 break;
1195 }
1196 }
1197
1198 if ( ! SDL_ReallocFormat (current, bpp,
1199 rmask, gmask, bmask, amask ) ) {
1200 SDL_SetError ("Couldn't reallocate pixel format");
1201 return NULL;
1202 }
1203 }
1204
1205 /* Signal successful completion (used internally) */
1206 video_set = SDL_TRUE;
1207
1208 return current;
1209}
1210
1211static SDL_Surface* QZ_SetVideoMode(_THIS, SDL_Surface *current,
1212 int width, int height, int bpp,
1213 Uint32 flags)
1214{
1215 /* Don't throw away the GL context if we can just resize the current one. */
1216#if 0 /* !!! FIXME: half-finished side project. Reenable this if you ever debug the corner cases. */
1217 const BOOL save_gl = ( (video_set == SDL_TRUE) && ((flags & SDL_OPENGL) == (current->flags & SDL_OPENGL)) && (bpp == current->format->BitsPerPixel) );
1218#else
1219 const BOOL save_gl = NO;
1220#endif
1221
1222 NSOpenGLContext *glctx = gl_context;
1223 SDL_Surface* retval = NULL;
1224
1225 if (save_gl) {
1226 [glctx retain]; /* just so we don't lose this when killing old views, etc */
1227 }
1228
1229 retval = QZ_SetVideoModeInternal (this, current, width, height, bpp, flags, save_gl);
1230
1231 if (save_gl) {
1232 [glctx release]; /* something else should own this now, or we legitimately release it. */
1233 }
1234
1235 return retval;
1236}
1237
1238
1239static int QZ_ToggleFullScreen (_THIS, int on)
1240{
1241 return 0;
1242}
1243
1244static int QZ_SetColors (_THIS, int first_color, int num_colors,
1245 SDL_Color *colors)
1246{
1247#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070)
1248 /* we shouldn't have an 8-bit mode on Lion! */
1249 if (!IS_LION_OR_LATER(this)) {
1250 CGTableCount index;
1251 CGDeviceColor color;
1252
1253 for (index = first_color; index < first_color+num_colors; index++) {
1254
1255 /* Clamp colors between 0.0 and 1.0 */
1256 color.red = colors->r / 255.0;
1257 color.blue = colors->b / 255.0;
1258 color.green = colors->g / 255.0;
1259
1260 colors++;
1261
1262 CGPaletteSetColorAtIndex (palette, color, index);
1263 }
1264
1265 return ( CGDisplayNoErr == CGDisplaySetPalette (display_id, palette) );
1266 }
1267#endif
1268
1269 return 0;
1270}
1271
1272#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070)
1273static int QZ_LockDoubleBuffer (_THIS, SDL_Surface *surface)
1274{
1275 return 1;
1276}
1277
1278static void QZ_UnlockDoubleBuffer (_THIS, SDL_Surface *surface)
1279{
1280}
1281
1282/* The VBL delay is based on code by Ian R Ollmann's RezLib <iano@cco.caltech.edu> */
1283static AbsoluteTime QZ_SecondsToAbsolute ( double seconds )
1284{
1285 union
1286 {
1287 UInt64 i;
1288 Nanoseconds ns;
1289 } temp;
1290
1291 temp.i = seconds * 1000000000.0;
1292
1293 return NanosecondsToAbsolute ( temp.ns );
1294}
1295
1296static int QZ_ThreadFlip (_THIS)
1297{
1298 Uint8 *src, *dst;
1299 int skip, len, h;
1300
1301 /*
1302 Give this thread the highest scheduling priority possible,
1303 in the hopes that it will immediately run after the VBL delay
1304 */
1305 {
1306 pthread_t current_thread;
1307 int policy;
1308 struct sched_param param;
1309
1310 current_thread = pthread_self ();
1311 pthread_getschedparam (current_thread, &policy, &param);
1312 policy = SCHED_RR;
1313 param.sched_priority = sched_get_priority_max (policy);
1314 pthread_setschedparam (current_thread, policy, &param);
1315 }
1316
1317 while (1) {
1318
1319 SDL_SemWait (sem1);
1320 if (quit_thread)
1321 return 0;
1322
1323 /*
1324 * We have to add SDL_VideoSurface->offset here, since we might be a
1325 * smaller surface in the center of the framebuffer (you asked for
1326 * a fullscreen resolution smaller than the hardware could supply
1327 * so SDL is centering it in a bigger resolution)...
1328 */
1329 dst = ((Uint8 *)((size_t)CGDisplayBaseAddress (display_id))) + SDL_VideoSurface->offset;
1330 src = current_buffer + SDL_VideoSurface->offset;
1331 len = SDL_VideoSurface->w * SDL_VideoSurface->format->BytesPerPixel;
1332 h = SDL_VideoSurface->h;
1333 skip = SDL_VideoSurface->pitch;
1334
1335 /* Wait for the VBL to occur (estimated since we don't have a hardware interrupt) */
1336 {
1337
1338 /* The VBL delay is based on Ian Ollmann's RezLib <iano@cco.caltech.edu> */
1339 double refreshRate;
1340 double linesPerSecond;
1341 double target;
1342 double position;
1343 double adjustment;
1344 AbsoluteTime nextTime;
1345 CFNumberRef refreshRateCFNumber;
1346
1347 refreshRateCFNumber = CFDictionaryGetValue (mode, kCGDisplayRefreshRate);
1348 if ( NULL == refreshRateCFNumber ) {
1349 SDL_SetError ("Mode has no refresh rate");
1350 goto ERROR;
1351 }
1352
1353 if ( 0 == CFNumberGetValue (refreshRateCFNumber, kCFNumberDoubleType, &refreshRate) ) {
1354 SDL_SetError ("Error getting refresh rate");
1355 goto ERROR;
1356 }
1357
1358 if ( 0 == refreshRate ) {
1359
1360 SDL_SetError ("Display has no refresh rate, using 60hz");
1361
1362 /* ok, for LCD's we'll emulate a 60hz refresh, which may or may not look right */
1363 refreshRate = 60.0;
1364 }
1365
1366 linesPerSecond = refreshRate * h;
1367 target = h;
1368
1369 /* Figure out the first delay so we start off about right */
1370 position = CGDisplayBeamPosition (display_id);
1371 if (position > target)
1372 position = 0;
1373
1374 adjustment = (target - position) / linesPerSecond;
1375
1376 nextTime = AddAbsoluteToAbsolute (UpTime (), QZ_SecondsToAbsolute (adjustment));
1377
1378 MPDelayUntil (&nextTime);
1379 }
1380
1381
1382 /* On error, skip VBL delay */
1383 ERROR:
1384
1385 /* TODO: use CGContextDrawImage here too! Create two CGContextRefs the same way we
1386 create two buffers, replace current_buffer with current_context and set it
1387 appropriately in QZ_FlipDoubleBuffer. */
1388 while ( h-- ) {
1389
1390 SDL_memcpy (dst, src, len);
1391 src += skip;
1392 dst += skip;
1393 }
1394
1395 /* signal flip completion */
1396 SDL_SemPost (sem2);
1397 }
1398
1399 return 0;
1400}
1401
1402static int QZ_FlipDoubleBuffer (_THIS, SDL_Surface *surface)
1403{
1404 /* wait for previous flip to complete */
1405 SDL_SemWait (sem2);
1406
1407 current_buffer = surface->pixels;
1408
1409 if (surface->pixels == sw_buffers[0])
1410 surface->pixels = sw_buffers[1];
1411 else
1412 surface->pixels = sw_buffers[0];
1413
1414 /* signal worker thread to do the flip */
1415 SDL_SemPost (sem1);
1416
1417 return 0;
1418}
1419
1420static void QZ_DoubleBufferUpdate (_THIS, int num_rects, SDL_Rect *rects)
1421{
1422 /* perform a flip if someone calls updaterects on a doublebuferred surface */
1423 this->FlipHWSurface (this, SDL_VideoSurface);
1424}
1425
1426static void QZ_DirectUpdate (_THIS, int num_rects, SDL_Rect *rects)
1427{
1428#pragma unused(this,num_rects,rects)
1429}
1430#endif
1431
1432/* Resize icon, BMP format */
1433static const unsigned char QZ_ResizeIcon[] = {
1434 0x42,0x4d,0x31,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x36,0x00,0x00,0x00,0x28,0x00,
1435 0x00,0x00,0x0d,0x00,0x00,0x00,0x0d,0x00,0x00,0x00,0x01,0x00,0x18,0x00,0x00,0x00,
1436 0x00,0x00,0xfb,0x01,0x00,0x00,0x13,0x0b,0x00,0x00,0x13,0x0b,0x00,0x00,0x00,0x00,
1437 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1438 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1439 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0b,0xff,0xff,
1440 0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda,0xda,
1441 0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8,
1442 0xe8,0xe8,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xda,0xda,0xda,0x87,
1443 0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8,0xe8,
1444 0xe8,0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xff,0xff,0xff,0x0b,0xff,0xff,
1445 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd5,0xd5,0xd5,0x87,0x87,0x87,0xe8,0xe8,0xe8,
1446 0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,
1447 0xda,0xda,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1448 0xff,0xff,0xd7,0xd7,0xd7,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda,
1449 0xda,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xff,0xff,0xff,0x0b,0xff,0xff,
1450 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd7,0xd7,0xd7,
1451 0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8,
1452 0xe8,0xe8,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1453 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd7,0xd7,0xd7,0x87,0x87,0x87,0xe8,0xe8,
1454 0xe8,0xff,0xff,0xff,0xdc,0xdc,0xdc,0x87,0x87,0x87,0xff,0xff,0xff,0x0b,0xff,0xff,
1455 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1456 0xff,0xff,0xff,0xd9,0xd9,0xd9,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xdc,
1457 0xdc,0xdc,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1458 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xdb,0xdb,
1459 0xdb,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xff,0xff,0xff,0x0b,0xff,0xff,
1460 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1461 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xdb,0xdb,0xdb,0x87,0x87,0x87,0xe8,
1462 0xe8,0xe8,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1463 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1464 0xff,0xff,0xff,0xff,0xdc,0xdc,0xdc,0x87,0x87,0x87,0xff,0xff,0xff,0x0b,0xff,0xff,
1465 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1466 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xdc,
1467 0xdc,0xdc,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1468 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
1469 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0b
1470};
1471
1472static void QZ_DrawResizeIcon (_THIS)
1473{
1474 /* Check if we should draw the resize icon */
1475 if (SDL_VideoSurface->flags & SDL_RESIZABLE) {
1476
1477 SDL_Rect icon_rect;
1478
1479 /* Create the icon image */
1480 if (resize_icon == NULL) {
1481
1482 SDL_RWops *rw;
1483 SDL_Surface *tmp;
1484
1485 rw = SDL_RWFromConstMem (QZ_ResizeIcon, sizeof(QZ_ResizeIcon));
1486 tmp = SDL_LoadBMP_RW (rw, SDL_TRUE);
1487
1488 resize_icon = SDL_ConvertSurface (tmp, SDL_VideoSurface->format, SDL_SRCCOLORKEY);
1489 SDL_SetColorKey (resize_icon, SDL_SRCCOLORKEY, 0xFFFFFF);
1490
1491 SDL_FreeSurface (tmp);
1492 }
1493
1494 icon_rect.x = SDL_VideoSurface->w - 13;
1495 icon_rect.y = SDL_VideoSurface->h - 13;
1496 icon_rect.w = 13;
1497 icon_rect.h = 13;
1498
1499 SDL_BlitSurface (resize_icon, NULL, SDL_VideoSurface, &icon_rect);
1500 }
1501}
1502
1503static void QZ_UpdateRects (_THIS, int numRects, SDL_Rect *rects)
1504{
1505 if (SDL_VideoSurface->flags & SDL_OPENGLBLIT) {
1506 QZ_GL_SwapBuffers (this);
1507 }
1508 else if ( [ qz_window isMiniaturized ] ) {
1509
1510 /* Do nothing if miniaturized */
1511 }
1512
1513 else {
1514 NSGraphicsContext *ctx = [NSGraphicsContext currentContext];
1515 if (ctx != nsgfx_context) { /* uhoh, you might be rendering from another thread... */
1516 [NSGraphicsContext setCurrentContext:nsgfx_context];
1517 ctx = nsgfx_context;
1518 }
1519 CGContextRef cgc = (CGContextRef) [ctx graphicsPort];
1520 QZ_DrawResizeIcon (this);
1521 CGContextFlush (cg_context);
1522 CGImageRef image = CGBitmapContextCreateImage (cg_context);
1523 CGRect rectangle = CGRectMake (0,0,[window_view frame].size.width,[window_view frame].size.height);
1524
1525 CGContextDrawImage (cgc, rectangle, image);
1526 CGImageRelease(image);
1527 CGContextFlush (cgc);
1528 }
1529}
1530
1531static void QZ_VideoQuit (_THIS)
1532{
1533 CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken;
1534
1535 /* Restore gamma settings */
1536 CGDisplayRestoreColorSyncSettings ();
1537
1538 /* Ensure the cursor will be visible and working when we quit */
1539 CGDisplayShowCursor (display_id);
1540 CGAssociateMouseAndMouseCursorPosition (1);
1541
1542 if (mode_flags & SDL_FULLSCREEN) {
1543 /* Fade to black to hide resolution-switching flicker (and garbage
1544 that is displayed by a destroyed OpenGL context, if applicable) */
1545 if (CGAcquireDisplayFadeReservation (5, &fade_token) == kCGErrorSuccess) {
1546 CGDisplayFade (fade_token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE);
1547 }
1548 QZ_UnsetVideoMode (this, TRUE, FALSE);
1549 if (fade_token != kCGDisplayFadeReservationInvalidToken) {
1550 CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
1551 CGReleaseDisplayFadeReservation (fade_token);
1552 }
1553 }
1554 else
1555 QZ_UnsetVideoMode (this, TRUE, FALSE);
1556
1557#if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070)
1558 if (!IS_LION_OR_LATER(this)) {
1559 CGPaletteRelease(palette);
1560 }
1561#endif
1562
1563 if (opengl_library) {
1564 SDL_UnloadObject(opengl_library);
1565 opengl_library = NULL;
1566 }
1567 this->gl_config.driver_loaded = 0;
1568
1569 if (field_edit) {
1570 [field_edit release];
1571 field_edit = NULL;
1572 }
1573}
1574
1575static int QZ_LockHWSurface(_THIS, SDL_Surface *surface)
1576{
1577 return 1;
1578}
1579
1580static void QZ_UnlockHWSurface(_THIS, SDL_Surface *surface)
1581{
1582}
1583
1584static int QZ_AllocHWSurface(_THIS, SDL_Surface *surface)
1585{
1586 return(-1); /* unallowed (no HWSURFACE support here). */
1587}
1588
1589static void QZ_FreeHWSurface (_THIS, SDL_Surface *surface)
1590{
1591}
1592
1593/* Gamma functions */
1594int QZ_SetGamma (_THIS, float red, float green, float blue)
1595{
1596 const CGGammaValue min = 0.0, max = 1.0;
1597
1598 if (red == 0.0)
1599 red = FLT_MAX;
1600 else
1601 red = 1.0 / red;
1602
1603 if (green == 0.0)
1604 green = FLT_MAX;
1605 else
1606 green = 1.0 / green;
1607
1608 if (blue == 0.0)
1609 blue = FLT_MAX;
1610 else
1611 blue = 1.0 / blue;
1612
1613 if ( CGDisplayNoErr == CGSetDisplayTransferByFormula
1614 (display_id, min, max, red, min, max, green, min, max, blue) ) {
1615
1616 return 0;
1617 }
1618 else {
1619
1620 return -1;
1621 }
1622}
1623
1624int QZ_GetGamma (_THIS, float *red, float *green, float *blue)
1625{
1626 CGGammaValue dummy;
1627 if ( CGDisplayNoErr == CGGetDisplayTransferByFormula
1628 (display_id, &dummy, &dummy, red,
1629 &dummy, &dummy, green, &dummy, &dummy, blue) )
1630
1631 return 0;
1632 else
1633 return -1;
1634}
1635
1636int QZ_SetGammaRamp (_THIS, Uint16 *ramp)
1637{
1638 const uint32_t tableSize = 255;
1639 CGGammaValue redTable[tableSize];
1640 CGGammaValue greenTable[tableSize];
1641 CGGammaValue blueTable[tableSize];
1642
1643 int i;
1644
1645 /* Extract gamma values into separate tables, convert to floats between 0.0 and 1.0 */
1646 for (i = 0; i < 256; i++)
1647 redTable[i % 256] = ramp[i] / 65535.0;
1648
1649 for (i=256; i < 512; i++)
1650 greenTable[i % 256] = ramp[i] / 65535.0;
1651
1652 for (i=512; i < 768; i++)
1653 blueTable[i % 256] = ramp[i] / 65535.0;
1654
1655 if ( CGDisplayNoErr == CGSetDisplayTransferByTable
1656 (display_id, tableSize, redTable, greenTable, blueTable) )
1657 return 0;
1658 else
1659 return -1;
1660}
1661
1662int QZ_GetGammaRamp (_THIS, Uint16 *ramp)
1663{
1664 const uint32_t tableSize = 255;
1665 CGGammaValue redTable[tableSize];
1666 CGGammaValue greenTable[tableSize];
1667 CGGammaValue blueTable[tableSize];
1668 uint32_t actual;
1669 int i;
1670
1671 if ( CGDisplayNoErr != CGGetDisplayTransferByTable
1672 (display_id, tableSize, redTable, greenTable, blueTable, &actual) ||
1673 actual != tableSize)
1674
1675 return -1;
1676
1677 /* Pack tables into one array, with values from 0 to 65535 */
1678 for (i = 0; i < 256; i++)
1679 ramp[i] = redTable[i % 256] * 65535.0;
1680
1681 for (i=256; i < 512; i++)
1682 ramp[i] = greenTable[i % 256] * 65535.0;
1683
1684 for (i=512; i < 768; i++)
1685 ramp[i] = blueTable[i % 256] * 65535.0;
1686
1687 return 0;
1688}
1689
diff --git a/apps/plugins/sdl/src/video/quartz/SDL_QuartzWM.h b/apps/plugins/sdl/src/video/quartz/SDL_QuartzWM.h
deleted file mode 100644
index 0b0767e8e2..0000000000
--- a/apps/plugins/sdl/src/video/quartz/SDL_QuartzWM.h
+++ /dev/null
@@ -1,27 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23struct WMcursor {
24 NSCursor *nscursor;
25};
26
27void QZ_UpdateCursor(_THIS);
diff --git a/apps/plugins/sdl/src/video/quartz/SDL_QuartzWM.m b/apps/plugins/sdl/src/video/quartz/SDL_QuartzWM.m
deleted file mode 100644
index d526424d4c..0000000000
--- a/apps/plugins/sdl/src/video/quartz/SDL_QuartzWM.m
+++ /dev/null
@@ -1,444 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_QuartzVideo.h"
25#include "SDL_QuartzWM.h"
26
27
28void QZ_FreeWMCursor (_THIS, WMcursor *cursor) {
29
30 if ( cursor != NULL ) {
31 [ cursor->nscursor release ];
32 free (cursor);
33 }
34}
35
36WMcursor* QZ_CreateWMCursor (_THIS, Uint8 *data, Uint8 *mask,
37 int w, int h, int hot_x, int hot_y) {
38 WMcursor *cursor;
39 NSBitmapImageRep *imgrep;
40 NSImage *img;
41 unsigned char *planes[5];
42 int i;
43 NSAutoreleasePool *pool;
44
45 pool = [ [ NSAutoreleasePool alloc ] init ];
46
47 /* Allocate the cursor memory */
48 cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor));
49 if (cursor == NULL) goto outOfMemory;
50
51 /* create the image representation and get the pointers to its storage */
52 imgrep = [ [ [ NSBitmapImageRep alloc ] initWithBitmapDataPlanes: NULL pixelsWide: w pixelsHigh: h bitsPerSample: 1 samplesPerPixel: 2 hasAlpha: YES isPlanar: YES colorSpaceName: NSDeviceWhiteColorSpace bytesPerRow: (w+7)/8 bitsPerPixel: 0 ] autorelease ];
53 if (imgrep == nil) goto outOfMemory;
54 [ imgrep getBitmapDataPlanes: planes ];
55
56 /* copy data and mask, extending the mask to all black pixels because the inversion effect doesn't work with Cocoa's alpha-blended cursors */
57 for (i = 0; i < (w+7)/8*h; i++) {
58 planes[0][i] = data[i] ^ 0xFF;
59 planes[1][i] = mask[i] | data[i];
60 }
61
62 /* create image and cursor */
63 img = [ [ [ NSImage alloc ] initWithSize: NSMakeSize(w, h) ] autorelease ];
64 if (img == nil) goto outOfMemory;
65 [ img addRepresentation: imgrep ];
66 if (system_version < 0x1030) { /* on 10.2, cursors must be 16*16 */
67 if (w > 16 || h > 16) { /* too big: scale it down */
68 [ img setScalesWhenResized: YES ];
69 hot_x = hot_x*16/w;
70 hot_y = hot_y*16/h;
71 }
72 else { /* too small (or just right): extend it (from the bottom left corner, so hot_y must be adjusted) */
73 hot_y += 16 - h;
74 }
75 [ img setSize: NSMakeSize(16, 16) ];
76 }
77 cursor->nscursor = [ [ NSCursor alloc ] initWithImage: img hotSpot: NSMakePoint(hot_x, hot_y) ];
78 if (cursor->nscursor == nil) goto outOfMemory;
79
80 [ pool release ];
81 return(cursor);
82
83outOfMemory:
84 [ pool release ];
85 if (cursor != NULL) SDL_free(cursor);
86 SDL_OutOfMemory();
87 return(NULL);
88}
89
90void QZ_UpdateCursor (_THIS) {
91 BOOL state;
92
93 if (cursor_should_be_visible || !(SDL_GetAppState() & SDL_APPMOUSEFOCUS)) {
94 state = YES;
95 } else {
96 state = NO;
97 }
98 if (state != cursor_visible) {
99 if (state) {
100 [ NSCursor unhide ];
101 } else {
102 [ NSCursor hide ];
103 }
104 cursor_visible = state;
105 }
106}
107
108BOOL QZ_IsMouseInWindow (_THIS) {
109 if (qz_window == nil || (mode_flags & SDL_FULLSCREEN)) return YES; /*fullscreen*/
110 else {
111 NSPoint p = [ qz_window mouseLocationOutsideOfEventStream ];
112 p.y -= 1.0f; /* Apparently y goes from 1 to h, not from 0 to h-1 (i.e. the "location of the mouse" seems to be defined as "the location of the top left corner of the mouse pointer's hot pixel" */
113 return NSPointInRect(p, [ window_view frame ]);
114 }
115}
116
117int QZ_ShowWMCursor (_THIS, WMcursor *cursor) {
118
119 if ( cursor == NULL) {
120 if ( cursor_should_be_visible ) {
121 cursor_should_be_visible = NO;
122 QZ_ChangeGrabState (this, QZ_HIDECURSOR);
123 }
124 QZ_UpdateCursor(this);
125 }
126 else {
127 if ( qz_window != nil && !(mode_flags & SDL_FULLSCREEN) ) {
128 [ qz_window invalidateCursorRectsForView: [ qz_window contentView ] ];
129 }
130 if ( ! cursor_should_be_visible ) {
131 cursor_should_be_visible = YES;
132 QZ_ChangeGrabState (this, QZ_SHOWCURSOR);
133 }
134 [ cursor->nscursor performSelectorOnMainThread:@selector(set) withObject:nil waitUntilDone:NO ];
135 QZ_UpdateCursor(this);
136 }
137
138 return 1;
139}
140
141/*
142 Coordinate conversion functions, for convenience
143 Cocoa sets the origin at the lower left corner of the window/screen
144 SDL, CoreGraphics/WindowServer, and QuickDraw use the origin at the upper left corner
145 The routines were written so they could be called before SetVideoMode() has finished;
146 this might have limited usefulness at the moment, but the extra cost is trivial.
147*/
148
149/* Convert Cocoa screen coordinate to Cocoa window coordinate */
150void QZ_PrivateGlobalToLocal (_THIS, NSPoint *p) {
151
152 if ( ! CGDisplayIsCaptured (display_id) )
153 *p = [ qz_window convertScreenToBase:*p ];
154}
155
156
157/* Convert Cocoa window coordinate to Cocoa screen coordinate */
158void QZ_PrivateLocalToGlobal (_THIS, NSPoint *p) {
159
160 if ( ! CGDisplayIsCaptured (display_id) )
161 *p = [ qz_window convertBaseToScreen:*p ];
162}
163
164/* Convert SDL coordinate to Cocoa coordinate */
165void QZ_PrivateSDLToCocoa (_THIS, NSPoint *p) {
166
167 if ( CGDisplayIsCaptured (display_id) ) { /* capture signals fullscreen */
168
169 p->y = CGDisplayPixelsHigh (display_id) - p->y;
170 }
171 else {
172
173 *p = [ window_view convertPoint:*p toView: nil ];
174 p->y = [window_view frame].size.height - p->y;
175 }
176}
177
178/* Convert Cocoa coordinate to SDL coordinate */
179void QZ_PrivateCocoaToSDL (_THIS, NSPoint *p) {
180
181 if ( CGDisplayIsCaptured (display_id) ) { /* capture signals fullscreen */
182
183 p->y = CGDisplayPixelsHigh (display_id) - p->y;
184 }
185 else {
186
187 *p = [ window_view convertPoint:*p fromView: nil ];
188 p->y = [window_view frame].size.height - p->y;
189 }
190}
191
192/* Convert SDL coordinate to window server (CoreGraphics) coordinate */
193CGPoint QZ_PrivateSDLToCG (_THIS, NSPoint *p) {
194
195 CGPoint cgp;
196
197 if ( ! CGDisplayIsCaptured (display_id) ) { /* not captured => not fullscreen => local coord */
198
199 int height;
200
201 QZ_PrivateSDLToCocoa (this, p);
202 QZ_PrivateLocalToGlobal (this, p);
203
204 height = CGDisplayPixelsHigh (display_id);
205 p->y = height - p->y;
206 }
207
208 cgp.x = p->x;
209 cgp.y = p->y;
210
211 return cgp;
212}
213
214#if 0 /* Dead code */
215/* Convert window server (CoreGraphics) coordinate to SDL coordinate */
216void QZ_PrivateCGToSDL (_THIS, NSPoint *p) {
217
218 if ( ! CGDisplayIsCaptured (display_id) ) { /* not captured => not fullscreen => local coord */
219
220 int height;
221
222 /* Convert CG Global to Cocoa Global */
223 height = CGDisplayPixelsHigh (display_id);
224 p->y = height - p->y;
225
226 QZ_PrivateGlobalToLocal (this, p);
227 QZ_PrivateCocoaToSDL (this, p);
228 }
229}
230#endif /* Dead code */
231
232void QZ_PrivateWarpCursor (_THIS, int x, int y) {
233 NSPoint p;
234 CGPoint cgp;
235
236 p = NSMakePoint (x, y);
237 cgp = QZ_PrivateSDLToCG (this, &p);
238
239 /* this is the magic call that fixes cursor "freezing" after warp */
240 CGAssociateMouseAndMouseCursorPosition (0);
241 CGWarpMouseCursorPosition (cgp);
242 if (grab_state != QZ_INVISIBLE_GRAB) { /* can't leave it disassociated? */
243 CGAssociateMouseAndMouseCursorPosition (1);
244 }
245 SDL_PrivateAppActive (QZ_IsMouseInWindow (this), SDL_APPMOUSEFOCUS);
246}
247
248void QZ_WarpWMCursor (_THIS, Uint16 x, Uint16 y) {
249
250 /* Only allow warping when in foreground */
251 if ( ! [ NSApp isActive ] )
252 return;
253
254 /* Do the actual warp */
255 if (grab_state != QZ_INVISIBLE_GRAB) QZ_PrivateWarpCursor (this, x, y);
256
257 /* Generate the mouse moved event */
258 SDL_PrivateMouseMotion (0, 0, x, y);
259}
260
261void QZ_MoveWMCursor (_THIS, int x, int y) { }
262void QZ_CheckMouseMode (_THIS) { }
263
264void QZ_SetCaption (_THIS, const char *title, const char *icon) {
265
266 if ( qz_window != nil ) {
267 NSString *string;
268 if ( title != NULL ) {
269 string = [ [ NSString alloc ] initWithUTF8String:title ];
270 [ qz_window setTitle:string ];
271 [ string release ];
272 }
273 if ( icon != NULL ) {
274 string = [ [ NSString alloc ] initWithUTF8String:icon ];
275 [ qz_window setMiniwindowTitle:string ];
276 [ string release ];
277 }
278 }
279}
280
281void QZ_SetIcon (_THIS, SDL_Surface *icon, Uint8 *mask)
282{
283 NSBitmapImageRep *imgrep;
284 NSImage *img;
285 SDL_Surface *mergedSurface;
286 NSAutoreleasePool *pool;
287 Uint8 *pixels;
288 SDL_bool iconSrcAlpha;
289 Uint8 iconAlphaValue;
290 int i, j, maskPitch, index;
291
292 pool = [ [ NSAutoreleasePool alloc ] init ];
293
294 imgrep = [ [ [ NSBitmapImageRep alloc ] initWithBitmapDataPlanes: NULL pixelsWide: icon->w pixelsHigh: icon->h bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES isPlanar: NO colorSpaceName: NSDeviceRGBColorSpace bytesPerRow: 4*icon->w bitsPerPixel: 32 ] autorelease ];
295 if (imgrep == nil) goto freePool;
296 pixels = [ imgrep bitmapData ];
297 SDL_memset(pixels, 0, 4*icon->w*icon->h); /* make the background, which will survive in colorkeyed areas, completely transparent */
298
299#if SDL_BYTEORDER == SDL_BIG_ENDIAN
300#define BYTEORDER_DEPENDENT_RGBA_MASKS 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF
301#else
302#define BYTEORDER_DEPENDENT_RGBA_MASKS 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000
303#endif
304 mergedSurface = SDL_CreateRGBSurfaceFrom(pixels, icon->w, icon->h, 32, 4*icon->w, BYTEORDER_DEPENDENT_RGBA_MASKS);
305 if (mergedSurface == NULL) goto freePool;
306
307 /* blit, with temporarily cleared SRCALPHA flag because we want to copy, not alpha-blend */
308 iconSrcAlpha = ((icon->flags & SDL_SRCALPHA) != 0);
309 iconAlphaValue = icon->format->alpha;
310 SDL_SetAlpha(icon, 0, 255);
311 SDL_BlitSurface(icon, NULL, mergedSurface, NULL);
312 if (iconSrcAlpha) SDL_SetAlpha(icon, SDL_SRCALPHA, iconAlphaValue);
313
314 SDL_FreeSurface(mergedSurface);
315
316 /* apply mask, source alpha, and premultiply color values by alpha */
317 maskPitch = (icon->w+7)/8;
318 for (i = 0; i < icon->h; i++) {
319 for (j = 0; j < icon->w; j++) {
320 index = i*4*icon->w + j*4;
321 if (!(mask[i*maskPitch + j/8] & (128 >> j%8))) {
322 pixels[index + 3] = 0;
323 }
324 else {
325 if (iconSrcAlpha) {
326 if (icon->format->Amask == 0) pixels[index + 3] = icon->format->alpha;
327 }
328 else {
329 pixels[index + 3] = 255;
330 }
331 }
332 if (pixels[index + 3] < 255) {
333 pixels[index + 0] = (Uint16)pixels[index + 0]*pixels[index + 3]/255;
334 pixels[index + 1] = (Uint16)pixels[index + 1]*pixels[index + 3]/255;
335 pixels[index + 2] = (Uint16)pixels[index + 2]*pixels[index + 3]/255;
336 }
337 }
338 }
339
340 img = [ [ [ NSImage alloc ] initWithSize: NSMakeSize(icon->w, icon->h) ] autorelease ];
341 if (img == nil) goto freePool;
342 [ img addRepresentation: imgrep ];
343 [ NSApp setApplicationIconImage:img ];
344
345freePool:
346 [ pool release ];
347}
348
349int QZ_IconifyWindow (_THIS) {
350
351 if ( ! [ qz_window isMiniaturized ] ) {
352 [ qz_window miniaturize:nil ];
353 if ( ! [ qz_window isMiniaturized ] ) {
354 SDL_SetError ("window iconification failed");
355 return 0;
356 }
357 return 1;
358 }
359 else {
360 SDL_SetError ("window already iconified");
361 return 0;
362 }
363}
364
365/*
366int QZ_GetWMInfo (_THIS, SDL_SysWMinfo *info) {
367 info->nsWindowPtr = qz_window;
368 return 0;
369}*/
370
371void QZ_ChangeGrabState (_THIS, int action) {
372
373 /*
374 Figure out what the next state should be based on the action.
375 Ignore actions that can't change the current state.
376 */
377 if ( grab_state == QZ_UNGRABBED ) {
378 if ( action == QZ_ENABLE_GRAB ) {
379 if ( cursor_should_be_visible )
380 grab_state = QZ_VISIBLE_GRAB;
381 else
382 grab_state = QZ_INVISIBLE_GRAB;
383 }
384 }
385 else if ( grab_state == QZ_VISIBLE_GRAB ) {
386 if ( action == QZ_DISABLE_GRAB )
387 grab_state = QZ_UNGRABBED;
388 else if ( action == QZ_HIDECURSOR )
389 grab_state = QZ_INVISIBLE_GRAB;
390 }
391 else {
392 assert( grab_state == QZ_INVISIBLE_GRAB );
393
394 if ( action == QZ_DISABLE_GRAB )
395 grab_state = QZ_UNGRABBED;
396 else if ( action == QZ_SHOWCURSOR )
397 grab_state = QZ_VISIBLE_GRAB;
398 }
399
400 /* now apply the new state */
401 if (grab_state == QZ_UNGRABBED) {
402
403 CGAssociateMouseAndMouseCursorPosition (1);
404 }
405 else if (grab_state == QZ_VISIBLE_GRAB) {
406
407 CGAssociateMouseAndMouseCursorPosition (1);
408 }
409 else {
410 assert( grab_state == QZ_INVISIBLE_GRAB );
411
412 QZ_PrivateWarpCursor (this, SDL_VideoSurface->w / 2, SDL_VideoSurface->h / 2);
413 CGAssociateMouseAndMouseCursorPosition (0);
414 }
415}
416
417SDL_GrabMode QZ_GrabInput (_THIS, SDL_GrabMode grab_mode) {
418
419 int doGrab = grab_mode & SDL_GRAB_ON;
420 /*int fullscreen = grab_mode & SDL_GRAB_FULLSCREEN;*/
421
422 if ( this->screen == NULL ) {
423 SDL_SetError ("QZ_GrabInput: screen is NULL");
424 return SDL_GRAB_OFF;
425 }
426
427 if ( ! video_set ) {
428 /*SDL_SetError ("QZ_GrabInput: video is not set, grab will take effect on mode switch"); */
429 current_grab_mode = grab_mode;
430 return grab_mode; /* Will be set later on mode switch */
431 }
432
433 if ( grab_mode != SDL_GRAB_QUERY ) {
434 if ( doGrab )
435 QZ_ChangeGrabState (this, QZ_ENABLE_GRAB);
436 else
437 QZ_ChangeGrabState (this, QZ_DISABLE_GRAB);
438
439 current_grab_mode = doGrab ? SDL_GRAB_ON : SDL_GRAB_OFF;
440 QZ_UpdateCursor(this);
441 }
442
443 return current_grab_mode;
444}
diff --git a/apps/plugins/sdl/src/video/quartz/SDL_QuartzWindow.h b/apps/plugins/sdl/src/video/quartz/SDL_QuartzWindow.h
deleted file mode 100644
index d19375b747..0000000000
--- a/apps/plugins/sdl/src/video/quartz/SDL_QuartzWindow.h
+++ /dev/null
@@ -1,51 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#if (MAC_OS_X_VERSION_MAX_ALLOWED < 1050)
25typedef unsigned int NSUInteger;
26#endif
27
28/* Subclass of NSWindow to fix genie effect and support resize events */
29@interface SDL_QuartzWindow : NSWindow
30{
31 BOOL watchForMouseUp;
32}
33
34- (void)miniaturize:(id)sender;
35- (void)display;
36- (void)setFrame:(NSRect)frameRect display:(BOOL)flag;
37- (void)appDidHide:(NSNotification*)note;
38- (void)appWillUnhide:(NSNotification*)note;
39- (void)appDidUnhide:(NSNotification*)note;
40- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)styleMask backing:(NSBackingStoreType)backingType defer:(BOOL)flag;
41@end
42
43/* Delegate for our NSWindow to send SDLQuit() on close */
44@interface SDL_QuartzWindowDelegate : NSObject
45- (BOOL)windowShouldClose:(id)sender;
46@end
47
48/* Subclass of NSView to set cursor rectangle */
49@interface SDL_QuartzView : NSView
50- (void)resetCursorRects;
51@end
diff --git a/apps/plugins/sdl/src/video/quartz/SDL_QuartzWindow.m b/apps/plugins/sdl/src/video/quartz/SDL_QuartzWindow.m
deleted file mode 100644
index 375833fb7b..0000000000
--- a/apps/plugins/sdl/src/video/quartz/SDL_QuartzWindow.m
+++ /dev/null
@@ -1,231 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_QuartzVideo.h"
25#include "SDL_QuartzWM.h"
26#include "SDL_QuartzWindow.h"
27
28/*
29 This function makes the *SDL region* of the window 100% opaque.
30 The genie effect uses the alpha component. Otherwise,
31 it doesn't seem to matter what value it has.
32*/
33static void QZ_SetPortAlphaOpaque () {
34
35 SDL_Surface *surface = current_video->screen;
36 int bpp;
37
38 bpp = surface->format->BitsPerPixel;
39
40 if (bpp == 32) {
41
42 Uint32 *pixels = (Uint32*) surface->pixels;
43 Uint32 rowPixels = surface->pitch / 4;
44 Uint32 i, j;
45
46 for (i = 0; i < surface->h; i++)
47 for (j = 0; j < surface->w; j++) {
48
49 pixels[ (i * rowPixels) + j ] |= 0xFF000000;
50 }
51 }
52}
53
54@implementation SDL_QuartzWindow
55
56/* we override these methods to fix the miniaturize animation/dock icon bug */
57- (void)miniaturize:(id)sender
58{
59 if (SDL_VideoSurface->flags & SDL_OPENGL) {
60
61 /*
62 Future: Grab framebuffer and put into NSImage
63 [ qz_window setMiniwindowImage:image ];
64 */
65 }
66 else {
67
68 /* make the alpha channel opaque so anim won't have holes in it */
69 QZ_SetPortAlphaOpaque ();
70 }
71
72 /* window is hidden now */
73 SDL_PrivateAppActive (0, SDL_APPACTIVE);
74
75 [ super miniaturize:sender ];
76}
77
78- (void)display
79{
80 /*
81 This method fires just before the window deminaturizes from the Dock.
82
83 We'll save the current visible surface, let the window manager redraw any
84 UI elements, and restore the SDL surface. This way, no expose event
85 is required, and the deminiaturize works perfectly.
86 */
87 SDL_VideoDevice *this = (SDL_VideoDevice*)current_video;
88
89 /* make sure pixels are fully opaque */
90 if (! ( SDL_VideoSurface->flags & SDL_OPENGL ) )
91 QZ_SetPortAlphaOpaque ();
92
93 /* save current visible SDL surface */
94 [ self cacheImageInRect:[ window_view frame ] ];
95
96 /* let the window manager redraw controls, border, etc */
97 [ super display ];
98
99 /* restore visible SDL surface */
100 [ self restoreCachedImage ];
101
102 /* window is visible again */
103 SDL_PrivateAppActive (1, SDL_APPACTIVE);
104}
105
106- (void)setFrame:(NSRect)frameRect display:(BOOL)flag
107{
108
109 /*
110 If the video surface is NULL, this originated from QZ_SetVideoMode,
111 so don't send the resize event.
112 */
113 SDL_VideoDevice *this = (SDL_VideoDevice*)current_video;
114
115 if (this && SDL_VideoSurface == NULL) {
116
117 [ super setFrame:frameRect display:flag ];
118 }
119 else if (this && qz_window) {
120
121 NSRect newViewFrame;
122
123 [ super setFrame:frameRect display:flag ];
124
125 newViewFrame = [ window_view frame ];
126
127 SDL_PrivateResize (newViewFrame.size.width, newViewFrame.size.height);
128 }
129}
130
131/* QZ_DoActivate() calls a low-level CoreGraphics routine to adjust
132 the cursor position, if input is being grabbed. If app activation is
133 triggered by a mouse click in the title bar, then the window manager
134 gets confused and thinks we're dragging the window. The solution
135 below postpones the activate event to avoid this scenario. */
136- (void)becomeKeyWindow
137{
138 NSEvent *event = [self currentEvent];
139 if ([event type] == NSLeftMouseDown && [event window] == self)
140 watchForMouseUp = YES;
141 else
142 [super becomeKeyWindow];
143}
144
145- (void)sendEvent:(NSEvent *)event
146{
147 [super sendEvent:event];
148 if (watchForMouseUp && [event type] == NSLeftMouseUp)
149 {
150 watchForMouseUp = NO;
151 [super becomeKeyWindow];
152 }
153}
154
155- (void)appDidHide:(NSNotification*)note
156{
157 SDL_PrivateAppActive (0, SDL_APPACTIVE);
158}
159
160- (void)appWillUnhide:(NSNotification*)note
161{
162 SDL_VideoDevice *this = (SDL_VideoDevice*)current_video;
163
164 if ( this ) {
165
166 /* make sure pixels are fully opaque */
167 if (! ( SDL_VideoSurface->flags & SDL_OPENGL ) )
168 QZ_SetPortAlphaOpaque ();
169
170 /* save current visible SDL surface */
171 [ self cacheImageInRect:[ window_view frame ] ];
172 }
173}
174
175- (void)appDidUnhide:(NSNotification*)note
176{
177 /* restore cached image, since it may not be current, post expose event too */
178 [ self restoreCachedImage ];
179
180 /*SDL_PrivateExpose ();*/
181
182 SDL_PrivateAppActive (1, SDL_APPACTIVE);
183}
184
185- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)styleMask backing:(NSBackingStoreType)backingType defer:(BOOL)flag
186{
187 /* Make our window subclass receive these application notifications */
188 [ [ NSNotificationCenter defaultCenter ] addObserver:self
189 selector:@selector(appDidHide:) name:NSApplicationDidHideNotification object:NSApp ];
190
191 [ [ NSNotificationCenter defaultCenter ] addObserver:self
192 selector:@selector(appDidUnhide:) name:NSApplicationDidUnhideNotification object:NSApp ];
193
194 [ [ NSNotificationCenter defaultCenter ] addObserver:self
195 selector:@selector(appWillUnhide:) name:NSApplicationWillUnhideNotification object:NSApp ];
196
197 return [ super initWithContentRect:contentRect styleMask:styleMask backing:backingType defer:flag ];
198}
199
200@end
201
202@implementation SDL_QuartzWindowDelegate
203- (BOOL)windowShouldClose:(id)sender
204{
205 SDL_PrivateQuit();
206 return NO;
207}
208
209- (void)windowDidBecomeKey:(NSNotification *)aNotification
210{
211 QZ_DoActivate (current_video);
212}
213
214- (void)windowDidResignKey:(NSNotification *)aNotification
215{
216 QZ_DoDeactivate (current_video);
217}
218
219@end
220
221@implementation SDL_QuartzView
222
223- (void)resetCursorRects
224{
225 SDL_Cursor *sdlc = SDL_GetCursor();
226 if (sdlc != NULL && sdlc->wm_cursor != NULL) {
227 [self addCursorRect: [self visibleRect] cursor: sdlc->wm_cursor->nscursor];
228 }
229}
230
231@end
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscosASM.S b/apps/plugins/sdl/src/video/riscos/SDL_riscosASM.S
deleted file mode 100644
index fae32f84d6..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscosASM.S
+++ /dev/null
@@ -1,116 +0,0 @@
1;
2; SDL - Simple DirectMedia Layer
3; Copyright (C) 1997-2012 Sam Lantinga
4;
5; This library is free software; you can redistribute it and/or
6; modify it under the terms of the GNU Library General Public
7; License as published by the Free Software Foundation; either
8; version 2 of the License, or (at your option) any later version.
9;
10; This library is distributed in the hope that it will be useful,
11; but WITHOUT ANY WARRANTY; without even the implied warranty of
12; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13; Library General Public License for more details.
14;
15; You should have received a copy of the GNU Library General Public
16; License along with this library; if not, write to the Free
17; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18;
19; Sam Lantinga
20; slouken@libsdl.org
21;
22; Assembler routines for RISC OS display
23;
24
25 AREA |C$$CODE|
26
27 EXPORT |RISCOS_Put32|
28
29; Display 32bpp to 32bpp, 1:1
30;
31; Code provided by Adrain Lees
32;
33; entry a1 -> destination
34; a2 = dest width in pixels
35; a3 = dest line length in bytes
36; a4 = dest height in scanlines
37; arg5 -> source
38; arg6 = byte offset from end of source line to start of next
39
40Arg5 * 10*4
41Arg6 * Arg5+4
42
43RISCOS_Put32 ROUT
44 STMFD sp!,{a2,v1-v6,sl,fp,lr}
45 LDR ip,[sp,#Arg5]
46 MOV lr,a1
47 B ucp64lp
48
4900 ;tail strip of 1-15 pixels
50
51 LDR v1,[ip],#4
5201 SUBS a2,a2,#1
53 STR v1,[lr],#4
54 LDRHI v1,[ip],#4
55 BHI %01
56 B %02
57
58ucp64end ADDS a2,a2,#16
59 BNE %00
60
6102 SUBS a4,a4,#1 ;height--
62 LDRHI v1,[sp,#Arg6]
63 LDRHI a2,[sp] ;reload width
64 BLS %03
65
66 ;move to start of next scanline
67
68 ADD lr,a1,a3
69 ADD a1,a1,a3
70 ADD ip,ip,v1
71
72ucp64lp SUBS a2,a2,#16
73 BLO ucp64end
74
75 PLD [ip,#64]
76
77 LDR v1,[ip],#4
78 LDR v2,[ip],#4
79 LDR v3,[ip],#4
80 LDR v4,[ip],#4
81 LDR v5,[ip],#4
82 LDR v6,[ip],#4
83 LDR sl,[ip],#4
84 LDR fp,[ip],#4
85 STR v1,[lr],#4
86 STR v2,[lr],#4
87 STR v3,[lr],#4
88 STR v4,[lr],#4
89 STR v5,[lr],#4
90 STR v6,[lr],#4
91 STR sl,[lr],#4
92 STR fp,[lr],#4
93
94 PLD [ip,#64]
95
96 LDR v1,[ip],#4
97 LDR v2,[ip],#4
98 LDR v3,[ip],#4
99 LDR v4,[ip],#4
100 LDR v5,[ip],#4
101 LDR v6,[ip],#4
102 LDR sl,[ip],#4
103 LDR fp,[ip],#4
104 STR v1,[lr],#4
105 STR v2,[lr],#4
106 STR v3,[lr],#4
107 STR v4,[lr],#4
108 STR v5,[lr],#4
109 STR v6,[lr],#4
110 STR sl,[lr],#4
111 STR fp,[lr],#4
112
113 B ucp64lp
114
11503 LDMFD sp!,{a2,v1-v6,sl,fp,pc}
116
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscosFullScreenVideo.c b/apps/plugins/sdl/src/video/riscos/SDL_riscosFullScreenVideo.c
deleted file mode 100644
index b8c3cf786b..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscosFullScreenVideo.c
+++ /dev/null
@@ -1,777 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 File added by Alan Buckley (alan_baa@hotmail.com) for RISC OS compatability
26 27 March 2003
27
28 Implements RISC OS full screen display.
29*/
30
31#include "SDL_video.h"
32#include "SDL_mouse.h"
33#include "../SDL_sysvideo.h"
34#include "../SDL_pixels_c.h"
35#include "../../events/SDL_events_c.h"
36
37#include "SDL_riscostask.h"
38#include "SDL_riscosvideo.h"
39#include "SDL_riscosevents_c.h"
40#include "SDL_riscosmouse_c.h"
41
42#include "kernel.h"
43#include "swis.h"
44#include "unixlib/os.h"
45#include "unixlib/local.h"
46
47/* Private structures */
48typedef struct tagScreenModeBlock
49{
50 int flags; // mode selector flags, bit 0 = 1, bit 1-7 format specifier, 8-31 reserved
51 int x_pixels;
52 int y_pixels;
53 int pixel_depth; // 2^pixel_depth = bpp,i.e. 0 = 1, 1 = 2, 4 = 16, 5 = 32
54 int frame_rate; // -1 use first match
55 int mode_vars[5]; // array of index, value pairs terminated by -1
56} SCREENMODEBLOCK;
57
58
59/* Helper functions */
60void FULLSCREEN_SetDeviceMode(_THIS);
61int FULLSCREEN_SetMode(int width, int height, int bpp);
62void FULLSCREEN_SetupBanks(_THIS);
63
64/* SDL video device functions for fullscreen mode */
65static int FULLSCREEN_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
66static int FULLSCREEN_FlipHWSurface(_THIS, SDL_Surface *surface);
67void FULLSCREEN_SetWMCaption(_THIS, const char *title, const char *icon);
68extern int RISCOS_GetWmInfo(_THIS, SDL_SysWMinfo *info);
69
70/* UpdateRects variants */
71static void FULLSCREEN_UpdateRects(_THIS, int numrects, SDL_Rect *rects);
72static void FULLSCREEN_UpdateRectsMemCpy(_THIS, int numrects, SDL_Rect *rects);
73static void FULLSCREEN_UpdateRects8bpp(_THIS, int numrects, SDL_Rect *rects);
74static void FULLSCREEN_UpdateRects16bpp(_THIS, int numrects, SDL_Rect *rects);
75static void FULLSCREEN_UpdateRects32bpp(_THIS, int numrects, SDL_Rect *rects);
76static void FULLSCREEN_UpdateRectsOS(_THIS, int numrects, SDL_Rect *rects);
77
78/* Local helper functions */
79static int cmpmodes(const void *va, const void *vb);
80static int FULLSCREEN_AddMode(_THIS, int bpp, int w, int h);
81void FULLSCREEN_SetWriteBank(int bank);
82void FULLSCREEN_SetDisplayBank(int bank);
83static void FULLSCREEN_DisableEscape();
84static void FULLSCREEN_EnableEscape();
85void FULLSCREEN_BuildModeList(_THIS);
86
87/* Following variable is set up in riskosTask.c */
88extern int riscos_backbuffer; /* Create a back buffer in system memory for full screen mode */
89
90/* Following is used to create a sprite back buffer */
91extern unsigned char *WIMP_CreateBuffer(int width, int height, int bpp);
92
93/* Fast assembler copy */
94extern void RISCOS_Put32(void *to, int pixels, int pitch, int rows, void *from, int src_skip_bytes);
95
96SDL_Surface *FULLSCREEN_SetVideoMode(_THIS, SDL_Surface *current,
97 int width, int height, int bpp, Uint32 flags)
98{
99 _kernel_swi_regs regs;
100 Uint32 Rmask = 0;
101 Uint32 Gmask = 0;
102 Uint32 Bmask = 0;
103 int create_back_buffer = riscos_backbuffer;
104
105 switch(bpp)
106 {
107 case 8:
108 flags |= SDL_HWPALETTE;
109 break;
110
111 case 15:
112 case 16:
113 Bmask = 0x00007c00;
114 Gmask = 0x000003e0;
115 Rmask = 0x0000001f;
116 break;
117
118 case 32:
119 Bmask = 0x00ff0000;
120 Gmask = 0x0000ff00;
121 Rmask = 0x000000ff;
122 break;
123
124 default:
125 SDL_SetError("Pixel depth not supported");
126 return NULL;
127 break;
128 }
129
130 if (FULLSCREEN_SetMode(width, height, bpp) == 0)
131 {
132 SDL_SetError("Couldn't set requested mode");
133 return (NULL);
134 }
135
136/* printf("Setting mode %dx%d\n", width, height); */
137
138 /* Allocate the new pixel format for the screen */
139 if ( ! SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, 0) ) {
140 RISCOS_RestoreWimpMode();
141 SDL_SetError("Couldn't allocate new pixel format for requested mode");
142 return(NULL);
143 }
144
145 /* Set up the new mode framebuffer */
146 current->w = width;
147 this->hidden->height = current->h = height;
148
149 regs.r[0] = -1; /* -1 for current screen mode */
150
151 /* Get screen width in bytes */
152 regs.r[1] = 6; // Screen Width in bytes
153 _kernel_swi(OS_ReadModeVariable, &regs, &regs);
154
155 current->pitch = regs.r[2];
156
157 if (flags & SDL_DOUBLEBUF)
158 {
159 regs.r[0] = 2; /* Screen area */
160 _kernel_swi(OS_ReadDynamicArea, &regs, &regs);
161
162 /* Reg 1 has amount of memory currently used for display */
163 regs.r[0] = 2; /* Screen area */
164 regs.r[1] = (current->pitch * height * 2) - regs.r[1];
165 if (_kernel_swi(OS_ChangeDynamicArea, &regs, &regs) != NULL)
166 {
167 /* Can't allocate enough screen memory for double buffer */
168 flags &= ~SDL_DOUBLEBUF;
169 }
170 }
171
172 current->flags = flags | SDL_FULLSCREEN | SDL_HWSURFACE | SDL_PREALLOC;
173
174
175 /* Need to set display banks here for double buffering */
176 if (flags & SDL_DOUBLEBUF)
177 {
178 FULLSCREEN_SetWriteBank(0);
179 FULLSCREEN_SetDisplayBank(1);
180
181 create_back_buffer = 0; /* Don't need a back buffer for a double buffered display */
182 }
183
184 FULLSCREEN_SetupBanks(this);
185
186 if (create_back_buffer)
187 {
188 /* If not double buffered we may need to create a memory
189 ** back buffer to simulate processing on other OSes.
190 ** This is turned on by setting the enviromental variable
191 ** SDL$<name>$BackBuffer >= 1
192 */
193 if (riscos_backbuffer == 3)
194 this->hidden->bank[0] = WIMP_CreateBuffer(width, height, bpp);
195 else
196 this->hidden->bank[0] = SDL_malloc(height * current->pitch);
197 if (this->hidden->bank[0] == 0)
198 {
199 RISCOS_RestoreWimpMode();
200 SDL_SetError("Couldnt allocate memory for back buffer");
201 return (NULL);
202 }
203 /* Surface updated in programs is now a software surface */
204 current->flags &= ~SDL_HWSURFACE;
205 }
206
207 /* Store address of allocated screen bank to be freed later */
208 if (this->hidden->alloc_bank) SDL_free(this->hidden->alloc_bank);
209 if (create_back_buffer)
210 {
211 this->hidden->alloc_bank = this->hidden->bank[0];
212 if (riscos_backbuffer == 3)
213 {
214 this->hidden->bank[0] += 60; /* Start of sprite data */
215 if (bpp == 8) this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */
216 }
217 } else
218 this->hidden->alloc_bank = 0;
219
220 // Clear both banks to black
221 SDL_memset(this->hidden->bank[0], 0, height * current->pitch);
222 SDL_memset(this->hidden->bank[1], 0, height * current->pitch);
223
224 this->hidden->current_bank = 0;
225 current->pixels = this->hidden->bank[0];
226
227 /* Have to set the screen here, so SetDeviceMode will pick it up */
228 this->screen = current;
229
230 /* Reset device functions for the wimp */
231 FULLSCREEN_SetDeviceMode(this);
232
233/* FULLSCREEN_DisableEscape(); */
234
235 /* We're done */
236 return(current);
237}
238
239/* Reset any device functions that have been changed because we have run in WIMP mode */
240void FULLSCREEN_SetDeviceMode(_THIS)
241{
242 /* Update rects is different if we have a backbuffer */
243
244 if (riscos_backbuffer && (this->screen->flags & SDL_DOUBLEBUF) == 0)
245 {
246 switch(riscos_backbuffer)
247 {
248 case 2: /* ARM code full word copy */
249 switch(this->screen->format->BytesPerPixel)
250 {
251 case 1: /* 8bpp modes */
252 this->UpdateRects = FULLSCREEN_UpdateRects8bpp;
253 break;
254 case 2: /* 15/16bpp modes */
255 this->UpdateRects = FULLSCREEN_UpdateRects16bpp;
256 break;
257 case 4: /* 32 bpp modes */
258 this->UpdateRects = FULLSCREEN_UpdateRects32bpp;
259 break;
260
261 default: /* Just default to the memcpy routine */
262 this->UpdateRects = FULLSCREEN_UpdateRectsMemCpy;
263 break;
264 }
265 break;
266
267 case 3: /* Use OS sprite plot routine */
268 this->UpdateRects = FULLSCREEN_UpdateRectsOS;
269 break;
270
271 default: /* Old but safe memcpy */
272 this->UpdateRects = FULLSCREEN_UpdateRectsMemCpy;
273 break;
274 }
275 } else
276 this->UpdateRects = FULLSCREEN_UpdateRects; /* Default do nothing implementation */
277
278 this->SetColors = FULLSCREEN_SetColors;
279
280 this->FlipHWSurface = FULLSCREEN_FlipHWSurface;
281
282 this->SetCaption = FULLSCREEN_SetWMCaption;
283 this->SetIcon = NULL;
284 this->IconifyWindow = NULL;
285
286 this->ShowWMCursor = RISCOS_ShowWMCursor;
287 this->WarpWMCursor = FULLSCREEN_WarpWMCursor;
288
289 this->PumpEvents = FULLSCREEN_PumpEvents;
290}
291
292/* Query for the list of available video modes */
293void FULLSCREEN_BuildModeList(_THIS)
294{
295 _kernel_swi_regs regs;
296 char *enumInfo = NULL;
297 char *enum_ptr;
298 int *blockInfo;
299 int j;
300 int num_modes;
301
302 /* Find out how much space we need */
303 regs.r[0] = 2; /* Reason code */
304 regs.r[2] = 0; /* Number of modes to skip */
305 regs.r[6] = 0; /* pointer to block or 0 for count */
306 regs.r[7] = 0; /* Size of block in bytes */
307 _kernel_swi(OS_ScreenMode, &regs, &regs);
308
309 num_modes = -regs.r[2];
310
311 /* Video memory should be in r[5] */
312 this->info.video_mem = regs.r[5]/1024;
313
314 enumInfo = (unsigned char *)SDL_malloc(-regs.r[7]);
315 if (enumInfo == NULL)
316 {
317 SDL_OutOfMemory();
318 return;
319 }
320 /* Read mode information into block */
321 regs.r[2] = 0;
322 regs.r[6] = (int)enumInfo;
323 regs.r[7] = -regs.r[7];
324 _kernel_swi(OS_ScreenMode, &regs, &regs);
325
326 enum_ptr = enumInfo;
327
328 for (j =0; j < num_modes;j++)
329 {
330 blockInfo = (int *)enum_ptr;
331 if ((blockInfo[1] & 255) == 1) /* We understand this format */
332 {
333 switch(blockInfo[4])
334 {
335 case 3: /* 8 bits per pixel */
336 FULLSCREEN_AddMode(this, 8, blockInfo[2], blockInfo[3]);
337 break;
338 case 4: /* 15 bits per pixel */
339 FULLSCREEN_AddMode(this, 15, blockInfo[2], blockInfo[3]);
340 break;
341 case 5: /* 32 bits per pixel */
342 FULLSCREEN_AddMode(this, 32, blockInfo[2], blockInfo[3]);
343 break;
344 }
345 }
346
347 enum_ptr += blockInfo[0];
348 }
349
350 SDL_free(enumInfo);
351
352 /* Sort the mode lists */
353 for ( j=0; j<NUM_MODELISTS; ++j ) {
354 if ( SDL_nummodes[j] > 0 ) {
355 SDL_qsort(SDL_modelist[j], SDL_nummodes[j], sizeof *SDL_modelist[j], cmpmodes);
356 }
357 }
358}
359
360static int FULLSCREEN_FlipHWSurface(_THIS, SDL_Surface *surface)
361{
362 _kernel_swi_regs regs;
363 regs.r[0] = 19;
364
365 FULLSCREEN_SetDisplayBank(this->hidden->current_bank);
366 this->hidden->current_bank ^= 1;
367 FULLSCREEN_SetWriteBank(this->hidden->current_bank);
368 surface->pixels = this->hidden->bank[this->hidden->current_bank];
369
370 /* Wait for Vsync */
371 _kernel_swi(OS_Byte, &regs, &regs);
372
373 return(0);
374}
375
376/* Nothing to do if we are writing direct to hardware */
377static void FULLSCREEN_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
378{
379}
380
381/* Safe but slower Memory copy from our allocated back buffer */
382static void FULLSCREEN_UpdateRectsMemCpy(_THIS, int numrects, SDL_Rect *rects)
383{
384 int j;
385 char *to, *from;
386 int pitch = this->screen->pitch;
387 int row;
388 int xmult = this->screen->format->BytesPerPixel;
389 for (j = 0; j < numrects; j++)
390 {
391 from = this->hidden->bank[0] + rects->x * xmult + rects->y * pitch;
392 to = this->hidden->bank[1] + rects->x * xmult + rects->y * pitch;
393 for (row = 0; row < rects->h; row++)
394 {
395 SDL_memcpy(to, from, rects->w * xmult);
396 from += pitch;
397 to += pitch;
398 }
399 rects++;
400 }
401}
402
403/* Use optimized assembler memory copy. Deliberately copies extra columns if
404 necessary to ensure the rectangle is word aligned. */
405static void FULLSCREEN_UpdateRects8bpp(_THIS, int numrects, SDL_Rect *rects)
406{
407 int j;
408 char *to, *from;
409 int pitch = this->screen->pitch;
410 int width_bytes;
411 int src_skip_bytes;
412
413 for (j = 0; j < numrects; j++)
414 {
415 from = this->hidden->bank[0] + rects->x + rects->y * pitch;
416 to = this->hidden->bank[1] + rects->x + rects->y * pitch;
417 width_bytes = rects->w;
418 if ((int)from & 3)
419 {
420 int extra = ((int)from & 3);
421 from -= extra;
422 to -= extra;
423 width_bytes += extra;
424 }
425 if (width_bytes & 3) width_bytes += 4 - (width_bytes & 3);
426 src_skip_bytes = pitch - width_bytes;
427
428 RISCOS_Put32(to, (width_bytes >> 2), pitch, (int)rects->h, from, src_skip_bytes);
429 rects++;
430 }
431}
432
433/* Use optimized assembler memory copy. Deliberately copies extra columns if
434 necessary to ensure the rectangle is word aligned. */
435static void FULLSCREEN_UpdateRects16bpp(_THIS, int numrects, SDL_Rect *rects)
436{
437 int j;
438 char *to, *from;
439 int pitch = this->screen->pitch;
440 int width_bytes;
441 int src_skip_bytes;
442
443 for (j = 0; j < numrects; j++)
444 {
445 from = this->hidden->bank[0] + (rects->x << 1) + rects->y * pitch;
446 to = this->hidden->bank[1] + (rects->x << 1) + rects->y * pitch;
447 width_bytes = (((int)rects->w) << 1);
448 if ((int)from & 3)
449 {
450 from -= 2;
451 to -= 2;
452 width_bytes += 2;
453 }
454 if (width_bytes & 3) width_bytes += 2;
455 src_skip_bytes = pitch - width_bytes;
456
457 RISCOS_Put32(to, (width_bytes >> 2), pitch, (int)rects->h, from, src_skip_bytes);
458 rects++;
459 }
460}
461
462/* Use optimized assembler memory copy. 32 bpp modes are always word aligned */
463static void FULLSCREEN_UpdateRects32bpp(_THIS, int numrects, SDL_Rect *rects)
464{
465 int j;
466 char *to, *from;
467 int pitch = this->screen->pitch;
468 int width;
469
470 for (j = 0; j < numrects; j++)
471 {
472 from = this->hidden->bank[0] + (rects->x << 2) + rects->y * pitch;
473 to = this->hidden->bank[1] + (rects->x << 2) + rects->y * pitch;
474 width = (int)rects->w ;
475
476 RISCOS_Put32(to, width, pitch, (int)rects->h, from, pitch - (width << 2));
477 rects++;
478 }
479}
480
481/* Use operating system sprite plots. Currently this is much slower than the
482 other variants however accelerated sprite plotting can be seen on the horizon
483 so this prepares for it. */
484static void FULLSCREEN_UpdateRectsOS(_THIS, int numrects, SDL_Rect *rects)
485{
486 _kernel_swi_regs regs;
487 _kernel_oserror *err;
488 int j;
489 int y;
490
491 regs.r[0] = 28 + 512;
492 regs.r[1] = (unsigned int)this->hidden->alloc_bank;
493 regs.r[2] = (unsigned int)this->hidden->alloc_bank+16;
494 regs.r[5] = 0;
495
496 for (j = 0; j < numrects; j++)
497 {
498 y = this->screen->h - rects->y; /* top of clipping region */
499 _kernel_oswrch(24); /* Set graphics clip region */
500 _kernel_oswrch((rects->x << this->hidden->xeig) & 0xFF); /* left */
501 _kernel_oswrch(((rects->x << this->hidden->xeig) >> 8) & 0xFF);
502 _kernel_oswrch(((y - rects->h) << this->hidden->yeig) & 0xFF); /* bottom */
503 _kernel_oswrch((((y - rects->h) << this->hidden->yeig)>> 8) & 0xFF);
504 _kernel_oswrch(((rects->x + rects->w - 1) << this->hidden->xeig) & 0xFF); /* right */
505 _kernel_oswrch((((rects->x + rects->w - 1)<< this->hidden->xeig) >> 8) & 0xFF);
506 _kernel_oswrch(((y-1) << this->hidden->yeig) & 0xFF); /* top */
507 _kernel_oswrch((((y-1) << this->hidden->yeig) >> 8) & 0xFF);
508
509 regs.r[3] = 0;
510 regs.r[4] = 0;
511
512 if ((err = _kernel_swi(OS_SpriteOp, &regs, &regs)) != 0)
513 {
514 printf("OS_SpriteOp failed \n%s\n",err->errmess);
515 }
516
517 rects++;
518
519 /* Reset to full screen clipping */
520 _kernel_oswrch(24); /* Set graphics clip region */
521 _kernel_oswrch(0); /* left */
522 _kernel_oswrch(0);
523 _kernel_oswrch(0); /* bottom */
524 _kernel_oswrch(0);
525 _kernel_oswrch(((this->screen->w-1) << this->hidden->xeig) & 0xFF); /* right */
526 _kernel_oswrch((((this->screen->w-1) << this->hidden->xeig) >> 8) & 0xFF);
527 _kernel_oswrch(((this->screen->h-1) << this->hidden->yeig) & 0xFF); /* top */
528 _kernel_oswrch((((this->screen->h-1) << this->hidden->yeig) >> 8) & 0xFF);
529 }
530}
531
532
533int FULLSCREEN_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
534{
535 _kernel_swi_regs regs;
536 int palette[256];
537
538 regs.r[0] = -1;
539 regs.r[1] = -1;
540 regs.r[2] = (int)palette;
541 regs.r[3] = 1024;
542 regs.r[4] = 0;
543 _kernel_swi(ColourTrans_ReadPalette, &regs, &regs);
544
545 while(ncolors--)
546 {
547 palette[firstcolor] = ((colors->b) << 24) | ((colors->g) << 16) | ((colors->r) << 8);
548 firstcolor++;
549 colors++;
550 }
551
552 regs.r[0] = -1;
553 regs.r[1] = -1;
554 regs.r[2] = (int)palette;
555 regs.r[3] = 0;
556 regs.r[4] = 0;
557 _kernel_swi(ColourTrans_WritePalette, &regs, &regs);
558
559 return(1);
560}
561
562
563static int cmpmodes(const void *va, const void *vb)
564{
565 SDL_Rect *a = *(SDL_Rect **)va;
566 SDL_Rect *b = *(SDL_Rect **)vb;
567 if(a->w == b->w)
568 return b->h - a->h;
569 else
570 return b->w - a->w;
571}
572
573static int FULLSCREEN_AddMode(_THIS, int bpp, int w, int h)
574{
575 SDL_Rect *mode;
576 int i, index;
577 int next_mode;
578
579 /* Check to see if we already have this mode */
580 if ( bpp < 8 ) { /* Not supported */
581 return(0);
582 }
583 index = ((bpp+7)/8)-1;
584 for ( i=0; i<SDL_nummodes[index]; ++i ) {
585 mode = SDL_modelist[index][i];
586 if ( (mode->w == w) && (mode->h == h) ) {
587 return(0);
588 }
589 }
590
591 /* Set up the new video mode rectangle */
592 mode = (SDL_Rect *)SDL_malloc(sizeof *mode);
593 if ( mode == NULL ) {
594 SDL_OutOfMemory();
595 return(-1);
596 }
597 mode->x = 0;
598 mode->y = 0;
599 mode->w = w;
600 mode->h = h;
601
602 /* Allocate the new list of modes, and fill in the new mode */
603 next_mode = SDL_nummodes[index];
604 SDL_modelist[index] = (SDL_Rect **)
605 SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *));
606 if ( SDL_modelist[index] == NULL ) {
607 SDL_OutOfMemory();
608 SDL_nummodes[index] = 0;
609 SDL_free(mode);
610 return(-1);
611 }
612 SDL_modelist[index][next_mode] = mode;
613 SDL_modelist[index][next_mode+1] = NULL;
614 SDL_nummodes[index]++;
615
616 return(0);
617}
618
619void FULLSCREEN_SetWriteBank(int bank)
620{
621 _kernel_swi_regs regs;
622 regs.r[0] = 112;
623 regs.r[1] = bank+1;
624 _kernel_swi(OS_Byte, &regs, &regs);
625}
626
627void FULLSCREEN_SetDisplayBank(int bank)
628{
629 _kernel_swi_regs regs;
630 regs.r[0] = 113;
631 regs.r[1] = bank+1;
632 _kernel_swi(OS_Byte, &regs, &regs);
633}
634
635
636/** Disable special escape key processing */
637static void FULLSCREEN_DisableEscape()
638{
639 _kernel_swi_regs regs;
640 regs.r[0] = 229;
641 regs.r[1] = 1;
642 regs.r[2] = 0;
643 _kernel_swi(OS_Byte, &regs, &regs);
644
645}
646
647/** Enable special escape key processing */
648static void FULLSCREEN_EnableEscape()
649{
650 _kernel_swi_regs regs;
651 regs.r[0] = 229;
652 regs.r[1] = 0;
653 regs.r[2] = 0;
654 _kernel_swi(OS_Byte, &regs, &regs);
655
656}
657
658/** Store caption in case this is called before we create a window */
659void FULLSCREEN_SetWMCaption(_THIS, const char *title, const char *icon)
660{
661 SDL_strlcpy(this->hidden->title, title, SDL_arraysize(this->hidden->title));
662}
663
664/* Set screen mode
665*
666* Returns 1 if mode is set ok, otherwise 0
667*/
668
669int FULLSCREEN_SetMode(int width, int height, int bpp)
670{
671 SCREENMODEBLOCK smb;
672 _kernel_swi_regs regs;
673
674 smb.flags = 1;
675 smb.x_pixels = width;
676 smb.y_pixels = height;
677 smb.mode_vars[0] = -1;
678
679 switch(bpp)
680 {
681 case 8:
682 smb.pixel_depth = 3;
683 /* Note: Need to set ModeFlags to 128 and NColour variables to 255 get full 8 bit palette */
684 smb.mode_vars[0] = 0; smb.mode_vars[1] = 128; /* Mode flags */
685 smb.mode_vars[2] = 3; smb.mode_vars[3] = 255; /* NColour (number of colours -1) */
686 smb.mode_vars[4] = -1; /* End of list */
687 break;
688
689 case 15:
690 case 16:
691 smb.pixel_depth = 4;
692 break;
693
694 case 32:
695 smb.pixel_depth = 5;
696 break;
697
698 default:
699 SDL_SetError("Pixel depth not supported");
700 return 0;
701 break;
702 }
703
704 smb.frame_rate = -1;
705
706 regs.r[0] = 0;
707 regs.r[1] = (int)&smb;
708
709 if (_kernel_swi(OS_ScreenMode, &regs, &regs) != 0)
710 {
711 SDL_SetError("Couldn't set requested mode");
712 return 0;
713 }
714
715 /* Turn cursor off*/
716 _kernel_oswrch(23);_kernel_oswrch(1);_kernel_oswrch(0);
717 _kernel_oswrch(0);_kernel_oswrch(0);_kernel_oswrch(0);
718 _kernel_oswrch(0);_kernel_oswrch(0);_kernel_oswrch(0);
719 _kernel_oswrch(0);_kernel_oswrch(0);
720
721 return 1;
722}
723
724/* Get Start addresses for the screen banks */
725void FULLSCREEN_SetupBanks(_THIS)
726{
727 _kernel_swi_regs regs;
728 int block[5];
729 block[0] = 148; /* Write screen start */
730 block[1] = 149; /* Display screen start */
731 block[2] = 4; /* X eig factor */
732 block[3] = 5; /* Y eig factor */
733 block[4] = -1; /* End of list of variables to request */
734
735 regs.r[0] = (int)block;
736 regs.r[1] = (int)block;
737 _kernel_swi(OS_ReadVduVariables, &regs, &regs);
738
739 this->hidden->bank[0] = (void *)block[0];
740 this->hidden->bank[1] = (void *)block[1];
741 this->hidden->xeig = block[2];
742 this->hidden->yeig = block[3];
743}
744
745/* Toggle to full screen mode from the WIMP */
746
747int FULLSCREEN_ToggleFromWimp(_THIS)
748{
749 int width = this->screen->w;
750 int height = this->screen->h;
751 int bpp = this->screen->format->BitsPerPixel;
752
753 RISCOS_StoreWimpMode();
754 if (FULLSCREEN_SetMode(width, height, bpp))
755 {
756 char *buffer = this->hidden->alloc_bank; /* This is start of sprite data */
757 /* Support back buffer mode only */
758 if (riscos_backbuffer == 0) riscos_backbuffer = 1;
759
760 FULLSCREEN_SetupBanks(this);
761
762 this->hidden->bank[0] = buffer + 60; /* Start of sprite data */
763 if (bpp == 8) this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */
764
765 this->hidden->current_bank = 0;
766 this->screen->pixels = this->hidden->bank[0];
767
768 /* Copy back buffer to screen memory */
769 SDL_memcpy(this->hidden->bank[1], this->hidden->bank[0], width * height * this->screen->format->BytesPerPixel);
770
771 FULLSCREEN_SetDeviceMode(this);
772 return 1;
773 } else
774 RISCOS_RestoreWimpMode();
775
776 return 0;
777}
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscosevents.c b/apps/plugins/sdl/src/video/riscos/SDL_riscosevents.c
deleted file mode 100644
index 54875076ab..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscosevents.c
+++ /dev/null
@@ -1,549 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 File added by Alan Buckley (alan_baa@hotmail.com) for RISC OS compatability
26 27 March 2003
27
28 Implements keyboard setup, event pump and keyboard and mouse polling
29*/
30
31
32#include "SDL.h"
33#include "../../timer/SDL_timer_c.h"
34#include "../../events/SDL_sysevents.h"
35#include "../../events/SDL_events_c.h"
36#include "../SDL_cursor_c.h"
37#include "SDL_riscosvideo.h"
38#include "SDL_riscosevents_c.h"
39
40#include "memory.h"
41#include "stdlib.h"
42#include "ctype.h"
43
44#include "kernel.h"
45#include "swis.h"
46
47/* The translation table from a RISC OS internal key numbers to a SDL keysym */
48static SDLKey RO_keymap[SDLK_LAST];
49
50/* RISC OS Key codes */
51#define ROKEY_SHIFT 0
52#define ROKEY_CTRL 1
53#define ROKEY_ALT 2
54/* Left shift is first key we will check for */
55#define ROKEY_LEFT_SHIFT 3
56
57/* Need to ignore mouse buttons as they are processed separately */
58#define ROKEY_LEFT_MOUSE 9
59#define ROKEY_CENTRE_MOUSE 10
60#define ROKEY_RIGHT_MOUSE 11
61
62/* No key has been pressed return value*/
63#define ROKEY_NONE 255
64
65/* Id of last key in keyboard */
66#define ROKEY_LAST_KEY 124
67
68/* Size of array for all keys */
69#define ROKEYBD_ARRAYSIZE 125
70
71static char RO_pressed[ROKEYBD_ARRAYSIZE];
72
73static SDL_keysym *TranslateKey(int intkey, SDL_keysym *keysym, int pressed);
74
75void RISCOS_PollMouse(_THIS);
76void RISCOS_PollKeyboard();
77
78void RISCOS_PollMouseHelper(_THIS, int fullscreen);
79
80#if SDL_THREADS_DISABLED
81extern void DRenderer_FillBuffers();
82
83/* Timer running function */
84extern void RISCOS_CheckTimer();
85
86#endif
87
88void FULLSCREEN_PumpEvents(_THIS)
89{
90 /* Current implementation requires keyboard and mouse polling */
91 RISCOS_PollKeyboard();
92 RISCOS_PollMouse(this);
93#if SDL_THREADS_DISABLED
94// DRenderer_FillBuffers();
95 if (SDL_timer_running) RISCOS_CheckTimer();
96#endif
97}
98
99
100void RISCOS_InitOSKeymap(_THIS)
101{
102 int i;
103
104 /* Map the VK keysyms */
105 for ( i=0; i<SDL_arraysize(RO_keymap); ++i )
106 RO_keymap[i] = SDLK_UNKNOWN;
107
108 RO_keymap[3] = SDLK_LSHIFT;
109 RO_keymap[4] = SDLK_LCTRL;
110 RO_keymap[5] = SDLK_LALT;
111 RO_keymap[6] = SDLK_RSHIFT;
112 RO_keymap[7] = SDLK_RCTRL;
113 RO_keymap[8] = SDLK_RALT;
114 RO_keymap[16] = SDLK_q;
115 RO_keymap[17] = SDLK_3;
116 RO_keymap[18] = SDLK_4;
117 RO_keymap[19] = SDLK_5;
118 RO_keymap[20] = SDLK_F4;
119 RO_keymap[21] = SDLK_8;
120 RO_keymap[22] = SDLK_F7;
121 RO_keymap[23] = SDLK_MINUS,
122 RO_keymap[25] = SDLK_LEFT;
123 RO_keymap[26] = SDLK_KP6;
124 RO_keymap[27] = SDLK_KP7;
125 RO_keymap[28] = SDLK_F11;
126 RO_keymap[29] = SDLK_F12;
127 RO_keymap[30] = SDLK_F10;
128 RO_keymap[31] = SDLK_SCROLLOCK;
129 RO_keymap[32] = SDLK_PRINT;
130 RO_keymap[33] = SDLK_w;
131 RO_keymap[34] = SDLK_e;
132 RO_keymap[35] = SDLK_t;
133 RO_keymap[36] = SDLK_7;
134 RO_keymap[37] = SDLK_i;
135 RO_keymap[38] = SDLK_9;
136 RO_keymap[39] = SDLK_0;
137 RO_keymap[41] = SDLK_DOWN;
138 RO_keymap[42] = SDLK_KP8;
139 RO_keymap[43] = SDLK_KP9;
140 RO_keymap[44] = SDLK_BREAK;
141 RO_keymap[45] = SDLK_BACKQUOTE;
142/* RO_keymap[46] = SDLK_currency; TODO: Figure out if this has a value */
143 RO_keymap[47] = SDLK_BACKSPACE;
144 RO_keymap[48] = SDLK_1;
145 RO_keymap[49] = SDLK_2;
146 RO_keymap[50] = SDLK_d;
147 RO_keymap[51] = SDLK_r;
148 RO_keymap[52] = SDLK_6;
149 RO_keymap[53] = SDLK_u;
150 RO_keymap[54] = SDLK_o;
151 RO_keymap[55] = SDLK_p;
152 RO_keymap[56] = SDLK_LEFTBRACKET;
153 RO_keymap[57] = SDLK_UP;
154 RO_keymap[58] = SDLK_KP_PLUS;
155 RO_keymap[59] = SDLK_KP_MINUS;
156 RO_keymap[60] = SDLK_KP_ENTER;
157 RO_keymap[61] = SDLK_INSERT;
158 RO_keymap[62] = SDLK_HOME;
159 RO_keymap[63] = SDLK_PAGEUP;
160 RO_keymap[64] = SDLK_CAPSLOCK;
161 RO_keymap[65] = SDLK_a;
162 RO_keymap[66] = SDLK_x;
163 RO_keymap[67] = SDLK_f;
164 RO_keymap[68] = SDLK_y;
165 RO_keymap[69] = SDLK_j;
166 RO_keymap[70] = SDLK_k;
167 RO_keymap[72] = SDLK_SEMICOLON;
168 RO_keymap[73] = SDLK_RETURN;
169 RO_keymap[74] = SDLK_KP_DIVIDE;
170 RO_keymap[76] = SDLK_KP_PERIOD;
171 RO_keymap[77] = SDLK_NUMLOCK;
172 RO_keymap[78] = SDLK_PAGEDOWN;
173 RO_keymap[79] = SDLK_QUOTE;
174 RO_keymap[81] = SDLK_s;
175 RO_keymap[82] = SDLK_c;
176 RO_keymap[83] = SDLK_g;
177 RO_keymap[84] = SDLK_h;
178 RO_keymap[85] = SDLK_n;
179 RO_keymap[86] = SDLK_l;
180 RO_keymap[87] = SDLK_SEMICOLON;
181 RO_keymap[88] = SDLK_RIGHTBRACKET;
182 RO_keymap[89] = SDLK_DELETE;
183 RO_keymap[90] = SDLK_KP_MINUS;
184 RO_keymap[91] = SDLK_KP_MULTIPLY;
185 RO_keymap[93] = SDLK_EQUALS;
186 RO_keymap[94] = SDLK_BACKSLASH;
187 RO_keymap[96] = SDLK_TAB;
188 RO_keymap[97] = SDLK_z;
189 RO_keymap[98] = SDLK_SPACE;
190 RO_keymap[99] = SDLK_v;
191 RO_keymap[100] = SDLK_b;
192 RO_keymap[101] = SDLK_m;
193 RO_keymap[102] = SDLK_COMMA;
194 RO_keymap[103] = SDLK_PERIOD;
195 RO_keymap[104] = SDLK_SLASH;
196 RO_keymap[105] = SDLK_END;
197 RO_keymap[106] = SDLK_KP0;
198 RO_keymap[107] = SDLK_KP1;
199 RO_keymap[108] = SDLK_KP3;
200 RO_keymap[112] = SDLK_ESCAPE;
201 RO_keymap[113] = SDLK_F1;
202 RO_keymap[114] = SDLK_F2;
203 RO_keymap[115] = SDLK_F3;
204 RO_keymap[116] = SDLK_F5;
205 RO_keymap[117] = SDLK_F6;
206 RO_keymap[118] = SDLK_F8;
207 RO_keymap[119] = SDLK_F9;
208 RO_keymap[120] = SDLK_HASH;
209 RO_keymap[121] = SDLK_RIGHT;
210 RO_keymap[122] = SDLK_KP4;
211 RO_keymap[123] = SDLK_KP5;
212 RO_keymap[124] = SDLK_KP2;
213
214 SDL_memset(RO_pressed, 0, ROKEYBD_ARRAYSIZE);
215}
216
217
218/* Variable for mouse relative processing */
219int mouse_relative = 0;
220
221/* Check to see if we need to enter or leave mouse relative mode */
222
223void RISCOS_CheckMouseMode(_THIS)
224{
225 /* If the mouse is hidden and input is grabbed, we use relative mode */
226 if ( !(SDL_cursorstate & CURSOR_VISIBLE) &&
227 (this->input_grab != SDL_GRAB_OFF) ) {
228 mouse_relative = 1;
229 } else {
230 mouse_relative = 0;
231 }
232}
233
234
235void RISCOS_PollMouse(_THIS)
236{
237 RISCOS_PollMouseHelper(this, 1);
238}
239
240extern int mouseInWindow;
241
242void WIMP_PollMouse(_THIS)
243{
244 /* Only poll when mouse is over the window */
245 if (!mouseInWindow) return;
246
247 RISCOS_PollMouseHelper(this, 0);
248}
249
250/* Static variables so only changes are reported */
251static Sint16 last_x = -1, last_y = -1;
252static int last_buttons = 0;
253
254/* Share routine between WIMP and FULLSCREEN for polling mouse and
255 passing on events */
256void RISCOS_PollMouseHelper(_THIS, int fullscreen)
257{
258 _kernel_swi_regs regs;
259 static int starting = 1;
260
261 if (_kernel_swi(OS_Mouse, &regs, &regs) == NULL)
262 {
263 Sint16 new_x = regs.r[0]; /* Initialy get as OS units */
264 Sint16 new_y = regs.r[1];
265
266 /* Discard mouse events until they let go of the mouse after starting */
267 if (starting && regs.r[2] != 0)
268 return;
269 else
270 starting = 0;
271
272 if (new_x != last_x || new_y != last_y || last_buttons != regs.r[2])
273 {
274 /* Something changed so generate appropriate events */
275 int topLeftX, topLeftY; /* Top left OS units */
276 int x, y; /* Mouse position in SDL pixels */
277
278 if (fullscreen)
279 {
280 topLeftX = 0;
281 topLeftY = (this->hidden->height << this->hidden->yeig) - 1;
282 } else
283 {
284 int window_state[9];
285
286 /* Get current window state */
287 window_state[0] = this->hidden->window_handle;
288 regs.r[1] = (unsigned int)window_state;
289 _kernel_swi(Wimp_GetWindowState, &regs, &regs);
290
291 topLeftX = window_state[1];
292 topLeftY = window_state[4];
293 }
294
295 /* Convert co-ordinates to workspace */
296 x = new_x - topLeftX;
297 y = topLeftY - new_y; /* Y goes from top of window/screen */
298
299 /* Convert OS units to pixels */
300 x >>= this->hidden->xeig;
301 y >>= this->hidden->yeig;
302
303 if (last_x != new_x || last_y != new_y)
304 {
305 if (mouse_relative)
306 {
307 int centre_x = SDL_VideoSurface->w/2;
308 int centre_y = SDL_VideoSurface->h/2;
309
310 if (centre_x != x || centre_y != y)
311 {
312 if (SDL_VideoSurface) SDL_PrivateMouseMotion(0,1,x - centre_x, y - centre_y);
313 last_x = topLeftX + (centre_x << this->hidden->xeig);
314 last_y = topLeftY - (centre_y << this->hidden->yeig);
315
316 /* Re-centre the mouse pointer, so we still get relative
317 movement when the mouse is at the edge of the window
318 or screen.
319 */
320 {
321 unsigned char block[5];
322
323 block[0] = 3; /* OSWORD move pointer sub-reason code */
324 block[1] = last_x & 0xFF;
325 block[2] = (last_x >> 8) & 0xFF;
326 block[3] = last_y & 0xFF;
327 block[4] = (last_y >> 8) & 0xFF;
328
329 regs.r[0] = 21; /* OSWORD pointer stuff code */
330 regs.r[1] = (int)block;
331 _kernel_swi(OS_Word, &regs, &regs);
332 }
333 }
334 } else
335 {
336 last_x = new_x;
337 last_y = new_y;
338 SDL_PrivateMouseMotion(0,0,x,y);
339 }
340 }
341
342 if (last_buttons != regs.r[2])
343 {
344 int changed = last_buttons ^ regs.r[2];
345 last_buttons = regs.r[2];
346 if (changed & 4) SDL_PrivateMouseButton((last_buttons & 4) ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_LEFT, 0, 0);
347 if (changed & 2) SDL_PrivateMouseButton((last_buttons & 2) ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_MIDDLE, 0, 0);
348 if (changed & 1) SDL_PrivateMouseButton((last_buttons & 1) ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_RIGHT, 0, 0);
349 }
350 }
351 }
352}
353
354void RISCOS_PollKeyboard()
355{
356 int which_key = ROKEY_LEFT_SHIFT;
357 int j;
358 int min_key, max_key;
359 SDL_keysym key;
360
361 /* Scan the keyboard to see what is pressed */
362 while (which_key <= ROKEY_LAST_KEY)
363 {
364 which_key = (_kernel_osbyte(121, which_key, 0) & 0xFF);
365 if (which_key != ROKEY_NONE)
366 {
367 switch(which_key)
368 {
369 /* Skip over mouse keys */
370 case ROKEY_LEFT_MOUSE:
371 case ROKEY_CENTRE_MOUSE:
372 case ROKEY_RIGHT_MOUSE:
373 which_key = ROKEY_RIGHT_MOUSE;
374 break;
375
376 /* Ignore keys that cause 2 internal number to be generated */
377 case 71: case 24: case 87: case 40:
378 break;
379
380 /* Ignore break as it can be latched on */
381 case 44:
382 break;
383
384 default:
385 RO_pressed[which_key] += 2;
386 break;
387 }
388 which_key++;
389 }
390 }
391
392 /* Generate key released messages */
393 min_key = ROKEY_LAST_KEY+1;
394 max_key = ROKEY_LEFT_SHIFT;
395
396 for (j = ROKEY_LEFT_SHIFT; j <= ROKEY_LAST_KEY; j++)
397 {
398 if (RO_pressed[j])
399 {
400 if (RO_pressed[j] == 1)
401 {
402 RO_pressed[j] = 0;
403 SDL_PrivateKeyboard(SDL_RELEASED, TranslateKey(j,&key,0));
404 } else
405 {
406 if (j < min_key) min_key = j;
407 if (j > max_key) max_key = j;
408 }
409 }
410 }
411
412 /* Generate key pressed messages */
413 for (j = min_key; j <= max_key; j++)
414 {
415 if (RO_pressed[j])
416 {
417 if (RO_pressed[j] == 2)
418 {
419 SDL_PrivateKeyboard(SDL_PRESSED,TranslateKey(j,&key,1));
420 }
421 RO_pressed[j] = 1;
422 }
423 }
424}
425
426static SDL_keysym *TranslateKey(int intkey, SDL_keysym *keysym, int pressed)
427{
428 /* Set the keysym information */
429 keysym->scancode = (unsigned char) intkey;
430 keysym->sym = RO_keymap[intkey];
431 keysym->mod = KMOD_NONE;
432 keysym->unicode = 0;
433 if ( pressed && SDL_TranslateUNICODE )
434 {
435 int state;
436 int ch;
437
438 state = (_kernel_osbyte(202, 0, 255) & 0xFF);
439
440 /*TODO: Take into account other keyboard layouts */
441
442 ch = keysym->sym; /* This should handle most unshifted keys */
443
444 if (intkey < 9 || ch == SDLK_UNKNOWN)
445 {
446 ch = 0;
447
448 } else if (state & 64) /* Control on */
449 {
450 ch = ch & 31;
451
452 } else
453 {
454 int topOfKey = 0;
455 if (state & 8) /* Shift on */
456 {
457 topOfKey = 1;
458 }
459
460 if ((state & 16) == 0) /* Caps lock is on */
461 {
462 if (ch >= SDLK_a && ch <= SDLK_z)
463 {
464 if ((state & 128) == 0) /* Shift Enable off */
465 {
466 /* All letter become upper case */
467 topOfKey = 1;
468 } else
469 {
470 /* Shift+Letters gives lower case */
471 topOfKey = 1 - topOfKey;
472 }
473 }
474 }
475
476 if (topOfKey)
477 {
478 /* Key produced with shift held down */
479
480 /* Letters just give upper case version */
481 if (ch >= SDLK_a && ch <= SDLK_z) ch = toupper(ch);
482 else
483 {
484 switch(ch)
485 {
486 case SDLK_HASH: ch = '~'; break;
487 case SDLK_QUOTE: ch = '@'; break;
488 case SDLK_COMMA: ch = '<'; break;
489 case SDLK_MINUS: ch = '_'; break;
490 case SDLK_PERIOD: ch = '>'; break;
491 case SDLK_SLASH: ch = '?'; break;
492
493 case SDLK_0: ch = ')'; break;
494 case SDLK_1: ch = '!'; break;
495 case SDLK_2: ch = '"'; break;
496 case SDLK_3: ch = '£'; break;
497 case SDLK_4: ch = '$'; break;
498 case SDLK_5: ch = '%'; break;
499 case SDLK_6: ch = '^'; break;
500 case SDLK_7: ch = '&'; break;
501 case SDLK_8: ch = '*'; break;
502 case SDLK_9: ch = '('; break;
503
504 case SDLK_SEMICOLON: ch = ':'; break;
505 case SDLK_EQUALS: ch = '+'; break;
506 case SDLK_LEFTBRACKET: ch = '{'; break;
507 case SDLK_BACKSLASH: ch = '|'; break;
508 case SDLK_RIGHTBRACKET: ch = '}'; break;
509 case SDLK_BACKQUOTE: ch = '¬'; break;
510
511 default:
512 ch = 0; /* Map to zero character if we don't understand it */
513 break;
514 }
515 }
516
517 } else if (ch > 126)
518 {
519 /* SDL key code < 126 map directly onto their Unicode equivalents */
520 /* Keypad 0 to 9 maps to numeric equivalent */
521 if (ch >= SDLK_KP0 && ch <= SDLK_KP9) ch = ch - SDLK_KP0 + '0';
522 else
523 {
524 /* Following switch maps other keys that produce an Ascii value */
525 switch(ch)
526 {
527 case SDLK_KP_PERIOD: ch = '.'; break;
528 case SDLK_KP_DIVIDE: ch = '/'; break;
529 case SDLK_KP_MULTIPLY: ch = '*'; break;
530 case SDLK_KP_MINUS: ch = '-'; break;
531 case SDLK_KP_PLUS: ch = '+'; break;
532 case SDLK_KP_EQUALS: ch = '='; break;
533
534 default:
535 /* If we don't know what it is set the Unicode to 0 */
536 ch = 0;
537 break;
538 }
539 }
540 }
541 }
542
543 keysym->unicode = ch;
544 }
545 return(keysym);
546}
547
548/* end of SDL_riscosevents.c ... */
549
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscosevents_c.h b/apps/plugins/sdl/src/video/riscos/SDL_riscosevents_c.h
deleted file mode 100644
index 189b3c0cfe..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscosevents_c.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_riscosvideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29extern void RISCOS_InitOSKeymap(_THIS);
30extern void FULLSCREEN_PumpEvents(_THIS);
31extern void WIMP_PumpEvents(_THIS);
32
33/* end of SDL_nullevents_c.h ... */
34
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscosmouse.c b/apps/plugins/sdl/src/video/riscos/SDL_riscosmouse.c
deleted file mode 100644
index b4a0bffc94..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscosmouse.c
+++ /dev/null
@@ -1,371 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 File added by Alan Buckley (alan_baa@hotmail.com) for RISC OS compatability
26 27 March 2003
27
28 Implements mouse cursor shape definitions and positioning
29*/
30
31#include "SDL_mouse.h"
32#include "../../events/SDL_events_c.h"
33
34#include "SDL_riscosmouse_c.h"
35
36#include "kernel.h"
37#include "swis.h"
38
39static WMcursor *current_cursor = NULL;
40static WMcursor *defined_cursor = NULL;
41
42extern int mouseInWindow;
43
44/* Area to save cursor palette colours changed by SDL.
45 Actual values will be read before we change to the SDL cursor */
46static Uint8 wimp_cursor_palette[2][5] = {
47 {1, 25, 255, 255, 255},
48 {3, 25, 255, 255, 255}
49};
50
51static int cursor_palette_saved = 0;
52
53void WIMP_SaveCursorPalette();
54void WIMP_RestoreWimpCursor();
55void WIMP_SetSDLCursorPalette();
56
57
58void RISCOS_FreeWMCursor(_THIS, WMcursor *cursor)
59{
60 SDL_free(cursor->data);
61 SDL_free(cursor);
62}
63
64WMcursor *RISCOS_CreateWMCursor(_THIS,
65 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
66{
67 WMcursor *cursor;
68 Uint8 *cursor_data;
69 Uint8 *ptr;
70 int i,j,k;
71 int data_byte, mask_byte;
72
73 /* Check to make sure the cursor size is okay */
74 if ( (w > 32) || (h > 32) ) {
75 SDL_SetError("Only with width and height <= 32 pixels are allowed");
76 return(NULL);
77 }
78
79 /* Allocate the cursor */
80 cursor = (WMcursor *)SDL_malloc(sizeof(*cursor));
81 if ( cursor == NULL ) {
82 SDL_SetError("Out of memory");
83 return(NULL);
84 }
85
86 /* Note: SDL says width must be a multiple of 8 */
87 cursor_data = SDL_malloc(w/4 * h);
88 if (cursor_data == NULL)
89 {
90 SDL_free(cursor);
91 SDL_SetError("Out of memory");
92 return(NULL);
93 }
94
95 cursor->w = w;
96 cursor->h = h;
97 cursor->hot_x = hot_x;
98 cursor->hot_y = hot_y;
99 cursor->data = cursor_data;
100
101
102/* Data / Mask Resulting pixel on screen
103 0 / 1 White
104 1 / 1 Black
105 0 / 0 Transparent
106 1 / 0 Inverted color if possible, black if not.
107*/
108 ptr = cursor_data;
109
110 for ( i=0; i<h; ++i )
111 {
112 for (j = 0; j < w/8; ++j)
113 {
114 data_byte = *data;
115 mask_byte = *mask;
116 *ptr++ = 0; /* Sets whole byte transparent */
117 *ptr = 0;
118 for (k = 0; k < 8; k++)
119 {
120 (*ptr) <<= 2;
121 if (data_byte & 1) *ptr |= 3; /* Black or inverted */
122 else if(mask_byte & 1) *ptr |= 1; /* White */
123 if ((k&3) == 3) ptr--;
124 data_byte >>= 1;
125 mask_byte >>= 1;
126 }
127
128 ptr+=3;
129 data++;
130 mask++;
131 }
132 }
133
134 return(cursor);
135}
136
137int RISCOS_ShowWMCursor(_THIS, WMcursor *cursor)
138{
139 current_cursor = cursor;
140
141 if (cursor == NULL)
142 {
143 _kernel_osbyte(106,0,0);
144 defined_cursor = NULL;
145 } else
146 {
147 WMcursor *old_cursor = defined_cursor;
148
149 if (cursor != defined_cursor)
150 {
151 Uint8 cursor_def[10];
152
153 cursor_def[0] = 0;
154 cursor_def[1] = 2; /* Use shape number 2 */
155 cursor_def[2] = cursor->w/4; /* Width in bytes */
156 cursor_def[3] = cursor->h; /* Height (h) in pixels */
157 cursor_def[4] = cursor->hot_x; /* ActiveX in pixels from left */
158 cursor_def[5] = cursor->hot_y; /* ActiveY in pixels from top */
159 cursor_def[6] = ((int)(cursor->data) & 0xFF); /* Least significant byte of pointer to data */
160 cursor_def[7] = ((int)(cursor->data) >> 8) & 0xFF; /* ... */
161 cursor_def[8] = ((int)(cursor->data) >> 16) & 0xFF; /* ... */
162 cursor_def[9] = ((int)(cursor->data) >> 24) & 0xFF; /* Most significant byte of pointer to data */
163
164 if (_kernel_osword(21, (int *)cursor_def) != 0)
165 {
166 SDL_SetError("RISCOS couldn't create the cursor to show");
167 return(0);
168 }
169 defined_cursor = cursor;
170 }
171
172 if (old_cursor == NULL)
173 {
174 /* First time or reshow in window, so save/setup palette */
175 if (!cursor_palette_saved)
176 {
177 WIMP_SaveCursorPalette();
178 }
179 WIMP_SetSDLCursorPalette();
180 }
181
182 _kernel_osbyte(106, 2, 0);
183 }
184
185 return(1);
186}
187
188void FULLSCREEN_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
189{
190 Uint8 move_block[5];
191 int eig_block[3];
192 _kernel_swi_regs regs;
193 int os_x, os_y;
194
195 eig_block[0] = 4; /* X eig factor */
196 eig_block[1] = 5; /* Y eig factor */
197 eig_block[2] = -1; /* End of list of variables to request */
198
199 regs.r[0] = (int)eig_block;
200 regs.r[1] = (int)eig_block;
201 _kernel_swi(OS_ReadVduVariables, &regs, &regs);
202
203 os_x = x << eig_block[0];
204 os_y = y << eig_block[1];
205
206 move_block[0] = 3; /* Move cursor */
207 move_block[1] = os_x & 0xFF;
208 move_block[2] = (os_x >> 8) & 0xFF;
209 move_block[3] = os_y & 0xFF;
210 move_block[4] = (os_y >> 8) & 0xFF;
211
212 _kernel_osword(21, (int *)move_block);
213 SDL_PrivateMouseMotion(0, 0, x, y);
214}
215
216
217/* Reshow cursor when mouse re-enters the window */
218void WIMP_ReshowCursor(_THIS)
219{
220 defined_cursor = NULL;
221 cursor_palette_saved = 0;
222 RISCOS_ShowWMCursor(this, current_cursor);
223}
224
225void WIMP_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
226{
227 _kernel_swi_regs regs;
228 int window_state[9];
229 char block[5];
230 int osX, osY;
231
232 window_state[0] = this->hidden->window_handle;
233 regs.r[1] = (unsigned int)window_state;
234 _kernel_swi(Wimp_GetWindowState, &regs, &regs);
235
236 osX = (x << this->hidden->xeig) + window_state[1];
237 osY = window_state[4] - (y << this->hidden->yeig);
238
239 block[0] = 3;
240 block[1] = osX & 0xFF;
241 block[2] = (osX >> 8) & 0xFF;
242 block[3] = osY & 0xFF;
243 block[4] = (osY >> 8) & 0xFF;
244
245 regs.r[0] = 21;
246 regs.r[1] = (int)block;
247 _kernel_swi(OS_Word, &regs, &regs);
248 SDL_PrivateMouseMotion(0, 0, x, y);
249}
250
251int WIMP_ShowWMCursor(_THIS, WMcursor *cursor)
252{
253 if (mouseInWindow) return RISCOS_ShowWMCursor(this, cursor);
254 else current_cursor = cursor;
255
256 return 1;
257}
258
259SDL_GrabMode RISCOS_GrabInput(_THIS, SDL_GrabMode mode)
260{
261 /* In fullscreen mode we don't need to do anything */
262 if (mode < SDL_GRAB_FULLSCREEN)
263 {
264 _kernel_swi_regs regs;
265 unsigned char block[9];
266 block[0] = 1; /* Define mouse cursor bounding block */
267
268 if ( mode == SDL_GRAB_OFF )
269 {
270 /* Clip to whole screen */
271
272 int r = (this->hidden->screen_width << this->hidden->xeig) - 1;
273 int t = (this->hidden->screen_height << this->hidden->yeig) - 1;
274
275 block[1] = 0; block[2] = 0; /* Left*/
276 block[3] = 0; block[4] = 0; /* Bottom */
277 block[5] = r & 0xFF; block[6] = (r >> 8) & 0xFF; /* Right */
278 block[7] = t & 0xFF; block[8] = (t >> 8) & 0xFF; /* Top */
279 } else
280 {
281 /* Clip to window */
282 unsigned char window_state[36];
283
284 *((int *)window_state) = this->hidden->window_handle;
285 regs.r[1] = (unsigned int)window_state;
286 _kernel_swi(Wimp_GetWindowState, &regs, &regs);
287
288 block[1] = window_state[4];
289 block[2] = window_state[5];
290 block[3] = window_state[8];
291 block[4] = window_state[9];
292 block[5] = window_state[12];
293 block[6] = window_state[13];
294 block[7] = window_state[16];
295 block[8] = window_state[17];
296
297 }
298
299 regs.r[0] = 21; /* OS word code */
300 regs.r[1] = (int)block;
301 _kernel_swi(OS_Word, &regs, &regs);
302 }
303
304 return mode;
305}
306
307/* Save mouse cursor palette to be restore when we are no longer
308 defining a cursor */
309
310void WIMP_SaveCursorPalette()
311{
312 _kernel_swi_regs regs;
313 int colour;
314
315 for (colour = 0; colour < 2; colour++)
316 {
317 regs.r[0] = (int)wimp_cursor_palette[colour][0];
318 regs.r[1] = 25;
319 /* Read settings with OS_ReadPalette */
320 if (_kernel_swi(0x2f, &regs, &regs) == NULL)
321 {
322 wimp_cursor_palette[colour][2] = (unsigned char)((regs.r[2] >> 8) & 0xFF);
323 wimp_cursor_palette[colour][3] = (unsigned char)((regs.r[2] >> 16) & 0xFF);
324 wimp_cursor_palette[colour][4] = (unsigned char)((regs.r[2] >> 24) & 0xFF);
325 }
326 }
327
328 cursor_palette_saved = 1;
329}
330
331/* Restore the WIMP's cursor when we leave the SDL window */
332void WIMP_RestoreWimpCursor()
333{
334 int colour;
335
336 /* Reset to pointer shape 1 */
337 _kernel_osbyte(106, 1, 0);
338
339 /* Reset pointer colours */
340 if (cursor_palette_saved)
341 {
342 for (colour = 0; colour < 2; colour++)
343 {
344 _kernel_osword(12, (int *)wimp_cursor_palette[colour]);
345 }
346 }
347 cursor_palette_saved = 0;
348}
349
350/* Set palette used for SDL mouse cursors */
351void WIMP_SetSDLCursorPalette()
352{
353 /* First time set up the mouse colours */
354 Uint8 block[5];
355
356 /* Set up colour 1 as white */
357 block[0] = 1; /* Colour to change 1 - 3 */
358 block[1] = 25; /* Set pointer colour */
359 block[2] = 255; /* red component*/
360 block[3] = 255; /* green component */
361 block[4] = 255; /* blue component*/
362 _kernel_osword(12, (int *)block);
363
364 /* Set colour 3 to back */
365 block[0] = 3; /* Colour to change 1 - 3 */
366 block[1] = 25; /* Set pointer colour*/
367 block[2] = 0; /* red component*/
368 block[3] = 0; /* green component */
369 block[4] = 0; /* blue component*/
370 _kernel_osword(12, (int *)block);
371}
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscosmouse_c.h b/apps/plugins/sdl/src/video/riscos/SDL_riscosmouse_c.h
deleted file mode 100644
index 9019cb43ca..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscosmouse_c.h
+++ /dev/null
@@ -1,44 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_riscosvideo.h"
25
26/* The implementation dependent data for the window manager cursor */
27struct WMcursor {
28 int w;
29 int h;
30 int hot_x;
31 int hot_y;
32 Uint8 *data;
33};
34
35/* Functions to be exported */
36void RISCOS_FreeWMCursor(_THIS, WMcursor *cursor);
37WMcursor *RISCOS_CreateWMCursor(_THIS, Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
38
39int RISCOS_ShowWMCursor(_THIS, WMcursor *cursor);
40void FULLSCREEN_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
41
42int WIMP_ShowWMCursor(_THIS, WMcursor *cursor);
43void WIMP_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
44
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscossprite.c b/apps/plugins/sdl/src/video/riscos/SDL_riscossprite.c
deleted file mode 100644
index 70b2f919db..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscossprite.c
+++ /dev/null
@@ -1,265 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 File added by Alan Buckley (alan_baa@hotmail.com) for RISC OS compatability
26 27 March 2003
27
28 Implements Sprite plotting code for wimp display.window
29*/
30
31#include "kernel.h"
32#include "swis.h"
33
34#include "SDL_stdinc.h"
35#include "SDL_riscosvideo.h"
36
37extern void WIMP_ReadModeInfo(_THIS);
38
39void WIMP_PaletteChanged(_THIS);
40
41
42/* Create sprite buffer for screen */
43
44unsigned char *WIMP_CreateBuffer(int width, int height, int bpp)
45{
46 int size;
47 char sprite_name[12] = "display";
48 unsigned char *buffer;
49 _kernel_swi_regs regs;
50 int bytesPerPixel;
51 int bytesPerRow;
52 int offsetToSpriteData = 60;
53
54 switch(bpp)
55 {
56 case 32: bytesPerPixel = 4; break;
57 case 16: bytesPerPixel = 2; break;
58 case 8:
59 bytesPerPixel = 1;
60 offsetToSpriteData += 2048; /* Add in size of palette */
61 break;
62 default:
63 return NULL;
64 break;
65 }
66
67 bytesPerRow = bytesPerPixel * width;
68
69 if ((bytesPerRow & 3) != 0)
70 {
71 bytesPerRow += 4 - (bytesPerRow & 3);
72 }
73 size = bytesPerRow * height;
74
75 buffer = SDL_malloc( (size_t) size + offsetToSpriteData );
76 if (!buffer) return NULL;
77
78 /* Initialise a sprite area */
79
80 *(unsigned int *)buffer = size + offsetToSpriteData;
81 *(unsigned int *)(buffer + 8) = 16;
82
83 regs.r[0] = 256+9;
84 regs.r[1] = (unsigned int)buffer;
85 _kernel_swi(OS_SpriteOp, &regs, &regs);
86
87 regs.r[0] = 256+15;
88 regs.r[1] = (unsigned int)buffer;
89 regs.r[2] = (unsigned int)&sprite_name;
90 regs.r[3] = 0; /* Palette flag: 0 = no palette */
91 regs.r[4] = width;
92 regs.r[5] = height;
93 if (bpp == 8)
94 {
95 /* Use old style mode number */
96 regs.r[6] = 28; /* 8bpp 90x90dpi */
97 } else
98 {
99 regs.r[6] = (((bpp == 16) ? 5 : 6) << 27) /* Type 6 = 32bpp sprite, 5 = 16bpp sprite */
100 | (90 << 14) /* Vertical dpi */
101 | (90 << 1) /* Horizontal dpi */
102 | 1; /* Marker to distinguish between mode selectors and sprite modes */
103 }
104 if (_kernel_swi(OS_SpriteOp, &regs, &regs) == NULL)
105 {
106 if (bpp == 8)
107 {
108 /* Modify sprite to take into account 256 colour palette */
109 int *sprite = (int *)(buffer + 16);
110 /* Adjust sprite offsets */
111 sprite[0] += 2048;
112 sprite[8] += 2048;
113 sprite[9] += 2048;
114 /* Adjust sprite area next free pointer */
115 (*(int *)(buffer+12)) += 2048;
116
117 /* Don't need to set up palette as SDL sets up the default
118 256 colour palette */
119/* {
120 int *pal = sprite + 11;
121 unsigned int j;
122 unsigned int entry;
123 for (j = 0; j < 255; j++)
124 {
125 entry = (j << 24) | (j << 16) | (j << 8);
126 *pal++ = entry;
127 *pal++ = entry;
128 }
129 }
130*/
131 }
132 } else
133 {
134 SDL_free(buffer);
135 buffer = NULL;
136 }
137
138 return buffer;
139}
140
141
142/* Setup translation buffers for the sprite plotting */
143
144void WIMP_SetupPlotInfo(_THIS)
145{
146 _kernel_swi_regs regs;
147 int *sprite = ((int *)this->hidden->bank[1])+4;
148
149 regs.r[0] = (unsigned int)this->hidden->bank[1];
150 regs.r[1] = (unsigned int)sprite;
151 regs.r[2] = -1; /* Current mode */
152 regs.r[3] = -1; /* Current palette */
153 regs.r[4] = 0; /* Get size of buffer */
154 regs.r[5] = 1|2|16; /* R1 - pointer to sprite and can use full palette words */
155 regs.r[6] = 0;
156 regs.r[7] = 0;
157
158 if (this->hidden->pixtrans) SDL_free(this->hidden->pixtrans);
159 this->hidden->pixtrans = 0;
160
161 /* Get the size required for the buffer */
162 _kernel_swi(ColourTrans_GenerateTable, &regs, &regs);
163 if (regs.r[4])
164 {
165 this->hidden->pixtrans = SDL_malloc(regs.r[4]);
166
167 regs.r[4] = (unsigned int)this->hidden->pixtrans;
168 /* Actually read the buffer */
169 _kernel_swi(ColourTrans_GenerateTable, &regs, &regs);
170 }
171}
172
173/* Plot the sprite in the given context */
174void WIMP_PlotSprite(_THIS, int x, int y)
175{
176 _kernel_swi_regs regs;
177 _kernel_oserror *err;
178
179 regs.r[0] = 52 + 512;
180 regs.r[1] = (unsigned int)this->hidden->bank[1];
181 regs.r[2] = (unsigned int)this->hidden->bank[1]+16;
182 regs.r[3] = x;
183 regs.r[4] = y;
184 regs.r[5] = 0|32; /* Overwrite screen and pixtrans contains wide colour entries */
185 regs.r[6] = 0; /* No scale factors i.e. 1:1 */
186 regs.r[7] = (int)this->hidden->pixtrans;
187
188 if ((err = _kernel_swi(OS_SpriteOp, &regs, &regs)) != 0)
189 {
190 int *p = (int *)this->hidden->pixtrans;
191 printf("OS_SpriteOp failed \n%s\n",err->errmess);
192 printf("pixtrans %d\n", (int)this->hidden->pixtrans);
193 printf("%x %x %x\n", p[0], p[1], p[2]);
194 }
195}
196
197
198/* Wimp mode has changes so update colour mapping and pixel sizes
199 of windows and the sprites they plot */
200
201void WIMP_ModeChanged(_THIS)
202{
203 int oldXeig = this->hidden->xeig;
204 int oldYeig = this->hidden->yeig;
205
206 WIMP_ReadModeInfo(this);
207
208 if (oldXeig == this->hidden->xeig && oldYeig == this->hidden->yeig)
209 {
210 /* Only need to update the palette */
211 WIMP_PaletteChanged(this);
212 } else
213 {
214 _kernel_swi_regs regs;
215 int window_state[9];
216 int extent[4];
217 int currWidth, currHeight;
218 int newWidth, newHeight;
219
220 /* Need to resize windows and update the palette */
221 WIMP_SetupPlotInfo(this);
222
223
224 window_state[0] = this->hidden->window_handle;
225 regs.r[1] = (unsigned int)window_state;
226 _kernel_swi(Wimp_GetWindowState, &regs, &regs);
227
228 currWidth = window_state[3] - window_state[1];
229 currHeight = window_state[4] - window_state[2];
230
231 newWidth = (currWidth >> oldXeig) << this->hidden->xeig;
232 newHeight = (currHeight >> oldYeig) << this->hidden->yeig;
233 /* Need to avoid extent getting too small for visible part
234 of window */
235 extent[0] = 0;
236 if (currHeight <= newHeight)
237 {
238 extent[1] = -newHeight;
239 } else
240 {
241 extent[1] = -currHeight;
242 }
243 if (currWidth <= newWidth)
244 {
245 extent[2] = newWidth;
246 } else
247 {
248 extent[2] = currWidth;
249 }
250 extent[3] = 0;
251
252 regs.r[0] = this->hidden->window_handle;
253 regs.r[1] = (int)extent;
254 _kernel_swi(Wimp_SetExtent, &regs, &regs);
255
256 /*TODO: May need to set flag to resize window on next open */
257 }
258}
259
260/* Palette has changed so update palettes used for windows sprites */
261
262void WIMP_PaletteChanged(_THIS)
263{
264 WIMP_SetupPlotInfo(this);
265}
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscostask.c b/apps/plugins/sdl/src/video/riscos/SDL_riscostask.c
deleted file mode 100644
index 67dc3e2fec..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscostask.c
+++ /dev/null
@@ -1,350 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 This file added by Alan Buckley (alan_baa@hotmail.com) to support RISC OS
26 26 March 2003
27
28 File includes routines for:
29 Setting up as a WIMP Task
30 Reading information about the current desktop
31 Storing information before a switch to full screen
32 Restoring desktop after switching to full screen
33*/
34
35#include "kernel.h"
36#include "swis.h"
37
38#include "SDL_stdinc.h"
39#include "SDL_riscostask.h"
40
41#if !SDL_THREADS_DISABLED
42#include <pthread.h>
43pthread_t main_thread;
44#endif
45
46/* RISC OS variables */
47
48static int task_handle = 0;
49static int wimp_version = 0;
50
51/* RISC OS variables to help compatability with certain programs */
52int riscos_backbuffer = 0; /* Create a back buffer in system memory for full screen mode */
53int riscos_closeaction = 1; /* Close icon action */
54
55static int stored_mode = -1; /* -1 when in desktop, mode number or pointer when full screen */
56
57extern int mouseInWindow; /* Mouse is in WIMP window */
58
59/* Local function */
60
61static int RISCOS_GetTaskName(char *task_name, size_t maxlen);
62
63/* Uncomment next line to copy mode changes/restores to stderr */
64/* #define DUMP_MODE */
65#ifdef DUMP_MODE
66#include "stdio.h"
67static void dump_mode()
68{
69 fprintf(stderr, "mode %d\n", stored_mode);
70 if (stored_mode < -1 || stored_mode >= 256)
71 {
72 int blockSize = 0;
73 int *storeBlock = (int *)stored_mode;
74
75 while(blockSize < 5 || storeBlock[blockSize] != -1)
76 {
77 fprintf(stderr, " %d\n", storeBlock[blockSize++]);
78 }
79 }
80}
81#endif
82
83/******************************************************************
84
85 Initialise as RISC OS Wimp task
86
87*******************************************************************/
88
89int RISCOS_InitTask()
90{
91 char task_name[32];
92 _kernel_swi_regs regs;
93 int messages[4];
94
95 if (RISCOS_GetTaskName(task_name, SDL_arraysize(task_name)) == 0) return 0;
96
97 messages[0] = 9; /* Palette changed */
98 messages[1] = 0x400c1; /* Mode changed */
99 messages[2] = 8; /* Pre quit */
100 messages[2] = 0;
101
102 regs.r[0] = (unsigned int)360; /* Minimum version 3.6 */
103 regs.r[1] = (unsigned int)0x4b534154;
104 regs.r[2] = (unsigned int)task_name;
105 regs.r[3] = (unsigned int)messages;
106
107 if (_kernel_swi(Wimp_Initialise, &regs, &regs) == 0)
108 {
109 wimp_version = regs.r[0];
110 task_handle = regs.r[1];
111 return 1;
112 }
113
114#if !SDL_THREADS_DISABLED
115 main_thread = pthread_self();
116#endif
117
118 return 0;
119}
120
121/*********************************************************************
122
123 Close down application on exit.
124
125**********************************************************************/
126
127void RISCOS_ExitTask()
128{
129 _kernel_swi_regs regs;
130
131 if (stored_mode == -1)
132 {
133 /* Ensure cursor is put back to standard pointer shape if
134 we have been running in a window */
135 _kernel_osbyte(106,1,0);
136 }
137
138 /* Ensure we end up back in the wimp */
139 RISCOS_RestoreWimpMode();
140
141 /* Neatly exit the task */
142 regs.r[0] = task_handle;
143 regs.r[1] = (unsigned int)0x4b534154;
144 _kernel_swi(Wimp_CloseDown, &regs, &regs);
145 task_handle = 0;
146}
147
148/**************************************************************************
149
150 Get the name of the task for the desktop.
151
152 Param: task_name - name of task 32 characters.
153
154 Returns: 1 is successful, otherwise 0
155
156 Notes: Works by getting using OS_GetEnv to get the command line
157 used to run the program and then parsing a name from it
158 as follows.
159
160 1. Use name after final period if not !RunImage
161 2. If name is !RunImage then process item before the period
162 in front of !RunImage.
163 3. If directory name use that
164 4. if in form <XXX$Dir> use the XXX.
165
166 Finally once this value has been retrieved use it unless
167 there is a variable set up in the form SDL$<name>$TaskName
168 in which case the value of this variable will be used.
169
170 Now also gets other RISC OS configuration varibles
171 SDL$<name>$BackBuffer - set to 1 to use a system memory backbuffer in fullscreen mode
172 so updates wait until a call to SDL_UpdateRects. (default 0)
173 This is required for programmes where they have assumed this is
174 always the case which is contrary to the documentation.
175 SDL$<name>$CloseAction
176 0 Don't show close icon
177 1 Show close icon
178
179***************************************************************************/
180
181int RISCOS_GetTaskName(char *task_name, size_t maxlen)
182{
183 _kernel_swi_regs regs;
184
185 task_name[0] = 0;
186
187 /* Figure out a sensible task name */
188 if (_kernel_swi(OS_GetEnv, &regs, &regs) == 0)
189 {
190 char *command_line = (char *)regs.r[0];
191 size_t len = SDL_strlen(command_line)+1;
192 char *buffer = SDL_stack_alloc(char, len);
193 char *env_var;
194 char *p;
195
196 SDL_strlcpy(buffer, command_line, len);
197 p = SDL_strchr(buffer, ' ');
198 if (p) *p = 0;
199 p = SDL_strrchr(buffer, '.');
200 if (p == 0) p = buffer;
201 if (stricmp(p+1,"!RunImage") == 0)
202 {
203 *p = 0;
204 p = SDL_strrchr(buffer, '.');
205 if (p == 0) p = buffer;
206 }
207 if (*p == '.') p++;
208 if (*p == '!') p++; /* Skip "!" at beginning of application directories */
209
210 if (*p == '<')
211 {
212 // Probably in the form <appname$Dir>
213 char *q = SDL_strchr(p, '$');
214 if (q == 0) q = SDL_strchr(p,'>'); /* Use variable name if not */
215 if (q) *q = 0;
216 p++; /* Move over the < */
217 }
218
219 if (*p)
220 {
221 /* Read variables that effect the RISC OS SDL engine for this task */
222 len = SDL_strlen(p) + 18; /* 18 is larger than the biggest variable name */
223 env_var = SDL_stack_alloc(char, len);
224 if (env_var)
225 {
226 char *env_val;
227
228 /* See if a variable of form SDL$<dirname>$TaskName exists */
229
230 SDL_strlcpy(env_var, "SDL$", len);
231 SDL_strlcat(env_var, p, len);
232 SDL_strlcat(env_var, "$TaskName", len);
233
234 env_val = SDL_getenv(env_var);
235 if (env_val) SDL_strlcpy(task_name, env_val, maxlen);
236
237 SDL_strlcpy(env_var, "SDL$", len);
238 SDL_strlcat(env_var, p, len);
239 SDL_strlcat(env_var, "$BackBuffer", len);
240
241 env_val = SDL_getenv(env_var);
242 if (env_val) riscos_backbuffer = atoi(env_val);
243
244 SDL_strlcpy(env_var, "SDL$", len);
245 SDL_strlcat(env_var, p, len);
246 SDL_strlcat(env_var, "$CloseAction", len);
247
248 env_val = SDL_getenv(env_var);
249 if (env_val && SDL_strcmp(env_val,"0") == 0) riscos_closeaction = 0;
250
251 SDL_stack_free(env_var);
252 }
253
254 if (!*task_name) SDL_strlcpy(task_name, p, maxlen);
255 }
256
257 SDL_stack_free(buffer);
258 }
259
260 if (task_name[0] == 0) SDL_strlcpy(task_name, "SDL Task", maxlen);
261
262 return 1;
263}
264
265/*****************************************************************
266
267 Store the current desktop screen mode if we are in the desktop.
268
269******************************************************************/
270
271void RISCOS_StoreWimpMode()
272{
273 _kernel_swi_regs regs;
274
275 /* Don't store if in full screen mode */
276 if (stored_mode != -1) return;
277
278 regs.r[0] = 1;
279 _kernel_swi(OS_ScreenMode, &regs, &regs);
280 if (regs.r[1] >= 0 && regs.r[1] < 256) stored_mode = regs.r[1];
281 else
282 {
283 int blockSize = 0;
284 int *retBlock = (int *)regs.r[1];
285 int *storeBlock;
286 int j;
287
288 while(blockSize < 5 || retBlock[blockSize] != -1) blockSize++;
289 blockSize++;
290 storeBlock = (int *)SDL_malloc(blockSize * sizeof(int));
291 retBlock = (int *)regs.r[1];
292 for ( j = 0; j < blockSize; j++)
293 storeBlock[j] = retBlock[j];
294
295 stored_mode = (int)storeBlock;
296 }
297#if DUMP_MODE
298 fprintf(stderr, "Stored "); dump_mode();
299#endif
300}
301
302/*****************************************************************
303
304 Restore desktop screen mode if we are in full screen mode.
305
306*****************************************************************/
307
308void RISCOS_RestoreWimpMode()
309{
310 _kernel_swi_regs regs;
311
312 /* Only need to restore if we are in full screen mode */
313 if (stored_mode == -1) return;
314
315#if DUMP_MODE
316 fprintf(stderr, "Restored"); dump_mode();
317#endif
318
319 regs.r[0] = stored_mode;
320 _kernel_swi(Wimp_SetMode, &regs, &regs);
321 if (stored_mode < 0 || stored_mode > 256)
322 {
323 SDL_free((int *)stored_mode);
324 }
325 stored_mode = -1;
326
327 /* Flush keyboard buffer to dump the keystrokes we've already polled */
328 regs.r[0] = 21;
329 regs.r[1] = 0; /* Keyboard buffer number */
330 _kernel_swi(OS_Byte, &regs, &regs);
331
332 mouseInWindow = 0;
333
334}
335
336/*********************************************************************
337
338 Get version of Wimp running when task was initialised.
339
340*********************************************************************/
341
342int RISCOS_GetWimpVersion()
343{
344 return wimp_version;
345}
346
347int RISCOS_GetTaskHandle()
348{
349 return task_handle;
350}
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscostask.h b/apps/plugins/sdl/src/video/riscos/SDL_riscostask.h
deleted file mode 100644
index 5744afa9db..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscostask.h
+++ /dev/null
@@ -1,39 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 This file added by Alan Buckley (alan_baa@hotmail.com) to support RISC OS
26 26 March 2003
27*/
28
29/* Task initialisation/Clean up */
30
31extern int RISCOS_InitTask();
32extern void RISCOS_ExitTask();
33extern int RISCOS_GetWimpVersion();
34extern int RISCOS_GetTaskHandle();
35
36
37/* Wimp mode saveing/restoring */
38extern void RISCOS_StoreWimpMode();
39extern void RISCOS_RestoreWimpMode();
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscosvideo.c b/apps/plugins/sdl/src/video/riscos/SDL_riscosvideo.c
deleted file mode 100644
index bae5e374d9..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscosvideo.c
+++ /dev/null
@@ -1,316 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 File added by Alan Buckley (alan_baa@hotmail.com) for RISC OS compatability
26 23 March 2003
27
28 Implements RISC OS display device management.
29 Routines for full screen and wimp modes are split
30 into other source files.
31*/
32
33#include "SDL_video.h"
34#include "SDL_mouse.h"
35#include "SDL_syswm.h"
36#include "../SDL_sysvideo.h"
37#include "../SDL_pixels_c.h"
38#include "../../events/SDL_events_c.h"
39
40#include "SDL_riscostask.h"
41#include "SDL_riscosvideo.h"
42#include "SDL_riscosevents_c.h"
43#include "SDL_riscosmouse_c.h"
44
45#include "kernel.h"
46#include "swis.h"
47
48#define RISCOSVID_DRIVER_NAME "riscos"
49
50/* Initialization/Query functions */
51static int RISCOS_VideoInit(_THIS, SDL_PixelFormat *vformat);
52static void RISCOS_VideoQuit(_THIS);
53
54static SDL_Rect **RISCOS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
55static SDL_Surface *RISCOS_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
56
57int RISCOS_GetWmInfo(_THIS, SDL_SysWMinfo *info);
58
59int RISCOS_ToggleFullScreen(_THIS, int fullscreen);
60/* Mouse checking */
61void RISCOS_CheckMouseMode(_THIS);
62extern SDL_GrabMode RISCOS_GrabInput(_THIS, SDL_GrabMode mode);
63
64/* Fullscreen mode functions */
65extern SDL_Surface *FULLSCREEN_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
66extern void FULLSCREEN_BuildModeList(_THIS);
67extern void FULLSCREEN_SetDeviceMode(_THIS);
68extern int FULLSCREEN_ToggleFromWimp(_THIS);
69
70/* Wimp mode functions */
71extern SDL_Surface *WIMP_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
72extern void WIMP_DeleteWindow(_THIS);
73extern int WIMP_ToggleFromFullScreen(_THIS);
74
75/* Hardware surface functions - common to WIMP and FULLSCREEN */
76static int RISCOS_AllocHWSurface(_THIS, SDL_Surface *surface);
77static int RISCOS_LockHWSurface(_THIS, SDL_Surface *surface);
78static void RISCOS_UnlockHWSurface(_THIS, SDL_Surface *surface);
79static void RISCOS_FreeHWSurface(_THIS, SDL_Surface *surface);
80
81/* RISC OS driver bootstrap functions */
82
83static int RISCOS_Available(void)
84{
85 return(1);
86}
87
88static void RISCOS_DeleteDevice(SDL_VideoDevice *device)
89{
90 SDL_free(device->hidden);
91 SDL_free(device);
92}
93
94static SDL_VideoDevice *RISCOS_CreateDevice(int devindex)
95{
96 SDL_VideoDevice *device;
97
98 /* Initialize all variables that we clean on shutdown */
99 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
100 if ( device ) {
101 SDL_memset(device, 0, (sizeof *device));
102 device->hidden = (struct SDL_PrivateVideoData *)
103 SDL_malloc((sizeof *device->hidden));
104 }
105 if ( (device == NULL) || (device->hidden == NULL) ) {
106 SDL_OutOfMemory();
107 if ( device ) {
108 SDL_free(device);
109 }
110 return(0);
111 }
112 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
113
114 /* Set the function pointers */
115 device->VideoInit = RISCOS_VideoInit;
116 device->VideoQuit = RISCOS_VideoQuit;
117
118 device->ListModes = RISCOS_ListModes;
119 device->SetVideoMode = RISCOS_SetVideoMode;
120 device->CreateYUVOverlay = NULL;
121 device->AllocHWSurface = RISCOS_AllocHWSurface;
122 device->CheckHWBlit = NULL;
123 device->FillHWRect = NULL;
124 device->SetHWColorKey = NULL;
125 device->SetHWAlpha = NULL;
126 device->LockHWSurface = RISCOS_LockHWSurface;
127 device->UnlockHWSurface = RISCOS_UnlockHWSurface;
128 device->FreeHWSurface = RISCOS_FreeHWSurface;
129
130 device->FreeWMCursor = RISCOS_FreeWMCursor;
131 device->CreateWMCursor = RISCOS_CreateWMCursor;
132 device->CheckMouseMode = RISCOS_CheckMouseMode;
133 device->GrabInput = RISCOS_GrabInput;
134
135 device->InitOSKeymap = RISCOS_InitOSKeymap;
136
137 device->GetWMInfo = RISCOS_GetWmInfo;
138
139 device->free = RISCOS_DeleteDevice;
140
141/* Can't get Toggle screen to work if program starts up in Full screen mode so
142 disable it here and re-enable it when a wimp screen is chosen */
143 device->ToggleFullScreen = NULL; /*RISCOS_ToggleFullScreen;*/
144
145 /* Set other entries for fullscreen mode */
146 FULLSCREEN_SetDeviceMode(device);
147
148 /* Mouse pointer needs to use the WIMP ShowCursor version so
149 that it doesn't modify the pointer until the SDL Window is
150 entered or the application goes full screen */
151 device->ShowWMCursor = WIMP_ShowWMCursor;
152
153 return device;
154}
155
156VideoBootStrap RISCOS_bootstrap = {
157 RISCOSVID_DRIVER_NAME, "RISC OS video driver",
158 RISCOS_Available, RISCOS_CreateDevice
159};
160
161
162int RISCOS_VideoInit(_THIS, SDL_PixelFormat *vformat)
163{
164 _kernel_swi_regs regs;
165 int vars[4], vals[3];
166
167 if (RISCOS_InitTask() == 0)
168 {
169 SDL_SetError("Unable to start task");
170 return 0;
171 }
172
173 vars[0] = 9; /* Log base 2 bpp */
174 vars[1] = 11; /* XWndLimit - num x pixels -1 */
175 vars[2] = 12; /* YWndLimit - num y pixels -1 */
176 vars[3] = -1; /* Terminate list */
177 regs.r[0] = (int)vars;
178 regs.r[1] = (int)vals;
179
180 _kernel_swi(OS_ReadVduVariables, &regs, &regs);
181 vformat->BitsPerPixel = (1 << vals[0]);
182
183 /* Determine the current screen size */
184 this->info.current_w = vals[1] + 1;
185 this->info.current_h = vals[2] + 1;
186
187 /* Minimum bpp for SDL is 8 */
188 if (vformat->BitsPerPixel < 8) vformat->BitsPerPixel = 8;
189
190
191 switch (vformat->BitsPerPixel)
192 {
193 case 15:
194 case 16:
195 vformat->Bmask = 0x00007c00;
196 vformat->Gmask = 0x000003e0;
197 vformat->Rmask = 0x0000001f;
198 vformat->BitsPerPixel = 16; /* SDL wants actual number of bits used */
199 vformat->BytesPerPixel = 2;
200 break;
201
202 case 24:
203 case 32:
204 vformat->Bmask = 0x00ff0000;
205 vformat->Gmask = 0x0000ff00;
206 vformat->Rmask = 0x000000ff;
207 vformat->BytesPerPixel = 4;
208 break;
209
210 default:
211 vformat->Bmask = 0;
212 vformat->Gmask = 0;
213 vformat->Rmask = 0;
214 vformat->BytesPerPixel = 1;
215 break;
216 }
217
218 /* Fill in some window manager capabilities */
219 this->info.wm_available = 1;
220
221 /* We're done! */
222 return(0);
223}
224
225/* Note: If we are terminated, this could be called in the middle of
226 another SDL video routine -- notably UpdateRects.
227*/
228void RISCOS_VideoQuit(_THIS)
229{
230 RISCOS_ExitTask();
231
232 if (this->hidden->alloc_bank) SDL_free(this->hidden->alloc_bank);
233 this->hidden->alloc_bank = 0;
234}
235
236
237SDL_Rect **RISCOS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
238{
239 if (flags & SDL_FULLSCREEN)
240 {
241 /* Build mode list when first required. */
242 if (SDL_nummodes[0] == 0) FULLSCREEN_BuildModeList(this);
243
244 return(SDL_modelist[((format->BitsPerPixel+7)/8)-1]);
245 } else
246 return (SDL_Rect **)-1;
247}
248
249
250/* Set up video mode */
251SDL_Surface *RISCOS_SetVideoMode(_THIS, SDL_Surface *current,
252 int width, int height, int bpp, Uint32 flags)
253{
254 if (flags & SDL_FULLSCREEN)
255 {
256 RISCOS_StoreWimpMode();
257 /* Dump wimp window on switch to full screen */
258 if (this->hidden->window_handle) WIMP_DeleteWindow(this);
259
260 return FULLSCREEN_SetVideoMode(this, current, width, height, bpp, flags);
261 } else
262 {
263 RISCOS_RestoreWimpMode();
264 return WIMP_SetVideoMode(this, current, width, height, bpp, flags);
265 }
266}
267
268
269/* We don't actually allow hardware surfaces other than the main one */
270static int RISCOS_AllocHWSurface(_THIS, SDL_Surface *surface)
271{
272 return(-1);
273}
274static void RISCOS_FreeHWSurface(_THIS, SDL_Surface *surface)
275{
276 return;
277}
278
279/* We need to wait for vertical retrace on page flipped displays */
280static int RISCOS_LockHWSurface(_THIS, SDL_Surface *surface)
281{
282 return(0);
283}
284
285static void RISCOS_UnlockHWSurface(_THIS, SDL_Surface *surface)
286{
287 return;
288}
289
290
291int RISCOS_GetWmInfo(_THIS, SDL_SysWMinfo *info)
292{
293 SDL_VERSION(&(info->version));
294 info->wimpVersion = RISCOS_GetWimpVersion();
295 info->taskHandle = RISCOS_GetTaskHandle();
296 info->window = this->hidden->window_handle;
297
298 return 1;
299}
300/* Toggle full screen mode.
301 Returns 1 if successful otherwise 0
302*/
303
304int RISCOS_ToggleFullScreen(_THIS, int fullscreen)
305{
306 if (fullscreen)
307 {
308 return FULLSCREEN_ToggleFromWimp(this);
309 } else
310 {
311 return WIMP_ToggleFromFullScreen(this);
312 }
313
314 return 0;
315}
316
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_riscosvideo.h b/apps/plugins/sdl/src/video/riscos/SDL_riscosvideo.h
deleted file mode 100644
index 7c717ad667..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_riscosvideo.h
+++ /dev/null
@@ -1,62 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_riscosvideo_h
25#define _SDL_riscosvideo_h
26
27#include "SDL_mouse.h"
28#include "SDL_mutex.h"
29#include "../SDL_sysvideo.h"
30
31/* Hidden "this" pointer for the video functions */
32#define _THIS SDL_VideoDevice *this
33
34
35/* Private display data */
36
37struct SDL_PrivateVideoData {
38 unsigned char *bank[2];
39 int current_bank;
40 unsigned char *alloc_bank;
41 int height;
42 int xeig;
43 int yeig;
44 int screen_bpp;
45 int screen_width;
46 int screen_height;
47 char *pixtrans;
48
49 /* Wimp variables */
50 unsigned int window_handle;
51 char title[256];
52
53#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
54 int SDL_nummodes[NUM_MODELISTS];
55 SDL_Rect **SDL_modelist[NUM_MODELISTS];
56};
57
58/* Old variable names */
59#define SDL_nummodes (this->hidden->SDL_nummodes)
60#define SDL_modelist (this->hidden->SDL_modelist)
61
62#endif /* _SDL_risosvideo_h */
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_wimppoll.c b/apps/plugins/sdl/src/video/riscos/SDL_wimppoll.c
deleted file mode 100644
index 4999664536..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_wimppoll.c
+++ /dev/null
@@ -1,330 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 File added by Alan Buckley (alan_baa@hotmail.com) for RISC OS compatability
26 27 March 2003
27
28 Implements Pumping of events and WIMP polling
29*/
30
31#include "SDL.h"
32#include "SDL_syswm.h"
33#include "../../events/SDL_sysevents.h"
34#include "../../events/SDL_events_c.h"
35#include "SDL_riscosvideo.h"
36#include "SDL_riscosevents_c.h"
37#include "SDL_riscosmouse_c.h"
38#include "../../timer/SDL_timer_c.h"
39
40#include "memory.h"
41#include "stdlib.h"
42#include "ctype.h"
43
44#include "kernel.h"
45#include "swis.h"
46#include "unixlib/os.h"
47
48#if !SDL_THREADS_DISABLED
49#include <pthread.h>
50#endif
51
52/* Local functions */
53void WIMP_Poll(_THIS, int waitTime);
54void WIMP_SetFocus(int win);
55
56/* SDL_riscossprite functions */
57void WIMP_PlotSprite(_THIS, int x, int y);
58void WIMP_ModeChanged(_THIS);
59void WIMP_PaletteChanged(_THIS);
60
61
62extern void WIMP_PollMouse(_THIS);
63extern void RISCOS_PollKeyboard();
64
65#if SDL_THREADS_DISABLED
66/* Timer running function */
67extern void RISCOS_CheckTimer();
68#else
69extern int riscos_using_threads;
70#endif
71
72/* Mouse cursor handling */
73extern void WIMP_ReshowCursor(_THIS);
74extern void WIMP_RestoreWimpCursor();
75
76int hasFocus = 0;
77int mouseInWindow = 0;
78
79/* Flag to ensure window is correct size after a mode change */
80static int resizeOnOpen = 0;
81
82void WIMP_PumpEvents(_THIS)
83{
84 WIMP_Poll(this, 0);
85 if (hasFocus) RISCOS_PollKeyboard();
86 if (mouseInWindow) WIMP_PollMouse(this);
87#if SDL_THREADS_DISABLED
88 if (SDL_timer_running) RISCOS_CheckTimer();
89#endif
90}
91
92
93void WIMP_Poll(_THIS, int waitTime)
94{
95 _kernel_swi_regs regs;
96 int message[64];
97 unsigned int code;
98 int pollMask = 0;
99 int doPoll = 1;
100 int sysEvent;
101 int sdlWindow = this->hidden->window_handle;
102
103 if (this->PumpEvents != WIMP_PumpEvents) return;
104
105 if (waitTime > 0)
106 {
107 _kernel_swi(OS_ReadMonotonicTime, &regs, &regs);
108 waitTime += regs.r[0];
109 }
110
111 while (doPoll)
112 {
113#if !SDL_THREADS_DISABLED
114 /* Stop thread callbacks while program is paged out */
115 if (riscos_using_threads) __pthread_stop_ticker();
116#endif
117
118 if (waitTime <= 0)
119 {
120 regs.r[0] = pollMask; /* Poll Mask */
121 /* For no wait time mask out null event so we wait until something happens */
122 if (waitTime < 0) regs.r[0] |= 1;
123 regs.r[1] = (int)message;
124 _kernel_swi(Wimp_Poll, &regs, &regs);
125 } else
126 {
127 regs.r[0] = pollMask;
128 regs.r[1] = (int)message;
129 regs.r[2] = waitTime;
130 _kernel_swi(Wimp_PollIdle, &regs, &regs);
131 }
132
133 /* Flag to specify if we post a SDL_SysWMEvent */
134 sysEvent = 0;
135
136 code = (unsigned int)regs.r[0];
137
138 switch(code)
139 {
140 case 0: /* Null Event - drop out for standard processing*/
141 doPoll = 0;
142 break;
143
144 case 1: /* Redraw window */
145 _kernel_swi(Wimp_RedrawWindow, &regs,&regs);
146 if (message[0] == sdlWindow)
147 {
148 while (regs.r[0])
149 {
150 WIMP_PlotSprite(this, message[1], message[2]);
151 _kernel_swi(Wimp_GetRectangle, &regs, &regs);
152 }
153 } else
154 {
155 /* TODO: Currently we just eat them - we may need to pass them on */
156 while (regs.r[0])
157 {
158 _kernel_swi(Wimp_GetRectangle, &regs, &regs);
159 }
160 }
161 break;
162
163 case 2: /* Open window */
164 if ( resizeOnOpen && message[0] == sdlWindow)
165 {
166 /* Ensure window is correct size */
167 resizeOnOpen = 0;
168 message[3] = message[1] + (this->screen->w << this->hidden->xeig);
169 message[4] = message[2] + (this->screen->h << this->hidden->yeig);
170 }
171 _kernel_swi(Wimp_OpenWindow, &regs, &regs);
172 break;
173
174 case 3: /* Close window */
175 if (message[0] == sdlWindow)
176 {
177 /* Documentation makes it looks as if the following line is correct:
178 ** if (SDL_PrivateQuit() == 1) _kernel_swi(Wimp_CloseWindow, &regs, &regs);
179 ** However some programs don't process this message and so sit there invisibly
180 ** in the background so I just post the quit message and hope the application
181 ** does the correct thing.
182 */
183 SDL_PrivateQuit();
184 } else
185 sysEvent = 1;
186 doPoll = 0;
187 break;
188
189 case 4: /* Pointer_Leaving_Window */
190 if (message[0] == sdlWindow)
191 {
192 mouseInWindow = 0;
193 //TODO: Lose buttons / dragging
194 /* Reset to default pointer */
195 WIMP_RestoreWimpCursor();
196 SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
197 } else
198 sysEvent = 1;
199 break;
200
201 case 5: /* Pointer_Entering_Window */
202 if (message[0] == sdlWindow)
203 {
204 mouseInWindow = 1;
205 WIMP_ReshowCursor(this);
206 SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
207 } else sysEvent = 1;
208 break;
209
210 case 6: /* Mouse_Click */
211 if (hasFocus == 0)
212 {
213 /* First click gives focus if it's not a menu */
214 /* we only count non-menu clicks on a window that has the focus */
215 WIMP_SetFocus(message[3]);
216 } else
217 doPoll = 0; // So PollMouse gets a chance to pick it up
218 break;
219
220 case 7: /* User_Drag_Box - Used for mouse release */
221 //TODO: May need to implement this in the future
222 sysEvent = 1;
223 break;
224
225 case 8: /* Keypressed */
226 doPoll = 0; /* PollKeyboard should pick it up */
227 if (message[0] != sdlWindow) sysEvent = 1;
228 /*TODO: May want to always pass F12 etc to the wimp
229 {
230 regs.r[0] = message[6];
231 _kernel_swi(Wimp_ProcessKey, &regs, &regs);
232 }
233 */
234 break;
235
236 case 11: /* Lose Caret */
237 hasFocus = 0;
238 if (message[0] == sdlWindow) SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS);
239 else sysEvent = 1;
240 break;
241
242 case 12: /* Gain Caret */
243 hasFocus = 1;
244 if (message[0] == sdlWindow) SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS);
245 else sysEvent = 1;
246 break;
247
248 case 17:
249 case 18:
250 sysEvent = 1; /* All messages are passed on */
251
252 switch(message[4])
253 {
254 case 0: /* Quit Event */
255 /* No choice - have to quit */
256 SDL_Quit();
257 exit(0);
258 break;
259
260 case 8: /* Pre Quit */
261 SDL_PrivateQuit();
262 break;
263
264 case 0x400c1: /* Mode change */
265 WIMP_ModeChanged(this);
266 resizeOnOpen = 1;
267 break;
268
269 case 9: /* Palette changed */
270 WIMP_PaletteChanged(this);
271 break;
272 }
273 break;
274
275 default:
276 /* Pass unknown events on */
277 sysEvent = 1;
278 break;
279 }
280
281 if (sysEvent)
282 {
283 SDL_SysWMmsg wmmsg;
284
285 SDL_VERSION(&wmmsg.version);
286 wmmsg.eventCode = code;
287 SDL_memcpy(wmmsg.pollBlock, message, 64 * sizeof(int));
288
289 /* Fall out of polling loop if message is successfully posted */
290 if (SDL_PrivateSysWMEvent(&wmmsg)) doPoll = 0;
291 }
292#if !SDL_THREADS_DISABLED
293 if (riscos_using_threads)
294 {
295 /* Restart ticker here so other thread can not interfere
296 with the Redraw processing */
297 if (riscos_using_threads) __pthread_start_ticker();
298 /* Give other threads a better chance of running */
299 pthread_yield();
300 }
301#endif
302 }
303}
304
305/* Set focus to specified window */
306void WIMP_SetFocus(int win)
307{
308 _kernel_swi_regs regs;
309
310 regs.r[0] = win;
311 regs.r[1] = -1; /* Icon handle */
312 regs.r[2] = 0; /* X-offset we just put it at position 0 */
313 regs.r[3] = 0; /* Y-offset as above */
314 regs.r[4] = 1 << 25; /* Caret is invisible */
315 regs.r[5] = 0; /* index into string */
316
317 _kernel_swi(Wimp_SetCaretPosition, &regs, &regs);
318}
319
320/** Run background task while in a sleep command */
321void RISCOS_BackgroundTasks(void)
322{
323 if (current_video && current_video->hidden->window_handle)
324 {
325 WIMP_Poll(current_video, 0);
326 }
327#if SDL_THREADS_DISABLED
328 if (SDL_timer_running) RISCOS_CheckTimer();
329#endif
330}
diff --git a/apps/plugins/sdl/src/video/riscos/SDL_wimpvideo.c b/apps/plugins/sdl/src/video/riscos/SDL_wimpvideo.c
deleted file mode 100644
index 0f9c5451d7..0000000000
--- a/apps/plugins/sdl/src/video/riscos/SDL_wimpvideo.c
+++ /dev/null
@@ -1,501 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 File added by Alan Buckley (alan_baa@hotmail.com) for RISC OS compatability
26 27 March 2003
27
28 Implements RISC OS Wimp display.
29*/
30
31#include "SDL_video.h"
32#include "SDL_mouse.h"
33#include "../SDL_sysvideo.h"
34#include "../SDL_pixels_c.h"
35#include "../../events/SDL_events_c.h"
36
37#include "SDL_riscostask.h"
38#include "SDL_riscosvideo.h"
39#include "SDL_riscosevents_c.h"
40#include "SDL_riscosmouse_c.h"
41
42#include "kernel.h"
43#include "swis.h"
44
45/* Initialization/Query functions */
46SDL_Rect **WIMP_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
47SDL_Surface *WIMP_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
48int WIMP_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
49void WIMP_SetWMCaption(_THIS, const char *title, const char *icon);
50
51
52extern unsigned char *WIMP_CreateBuffer(int width, int height, int bpp);
53extern void WIMP_PumpEvents(_THIS);
54extern void WIMP_PlotSprite(_THIS, int x, int y);
55extern void WIMP_SetupPlotInfo(_THIS);
56extern void WIMP_SetFocus(int win);
57
58/* etc. */
59static void WIMP_UpdateRects(_THIS, int numrects, SDL_Rect *rects);
60
61/* RISC OS Wimp handling helpers */
62void WIMP_ReadModeInfo(_THIS);
63unsigned int WIMP_SetupWindow(_THIS, SDL_Surface *surface);
64void WIMP_SetDeviceMode(_THIS);
65void WIMP_DeleteWindow(_THIS);
66
67/* FULLSCREEN function required for wimp/fullscreen toggling */
68extern int FULLSCREEN_SetMode(int width, int height, int bpp);
69
70/* Currently need to set this up here as it only works if you
71 start up in a Wimp mode */
72extern int RISCOS_ToggleFullScreen(_THIS, int fullscreen);
73
74extern int riscos_backbuffer;
75extern int mouseInWindow;
76extern int riscos_closeaction;
77
78/* Following needed to ensure window is shown immediately */
79extern int hasFocus;
80extern void WIMP_Poll(_THIS, int waitTime);
81
82SDL_Surface *WIMP_SetVideoMode(_THIS, SDL_Surface *current,
83 int width, int height, int bpp, Uint32 flags)
84{
85 Uint32 Rmask = 0;
86 Uint32 Gmask = 0;
87 Uint32 Bmask = 0;
88 char *buffer = NULL;
89 int bytesPerPixel = 1;
90
91 /* Don't support double buffering in Wimp mode */
92 flags &= ~SDL_DOUBLEBUF;
93 flags &= ~SDL_HWSURFACE;
94
95 switch(bpp)
96 {
97 case 8:
98 /* Emulated palette using ColourTrans */
99 flags |= SDL_HWPALETTE;
100 break;
101
102 case 15:
103 case 16:
104 Bmask = 0x00007c00;
105 Gmask = 0x000003e0;
106 Rmask = 0x0000001f;
107 bytesPerPixel = 2;
108 break;
109
110 case 32:
111 Bmask = 0x00ff0000;
112 Gmask = 0x0000ff00;
113 Rmask = 0x000000ff;
114 bytesPerPixel = 4;
115 break;
116
117 default:
118 SDL_SetError("Pixel depth not supported");
119 return NULL;
120 break;
121 }
122
123/* printf("Setting mode %dx%d\n", width, height);*/
124
125 /* Allocate the new pixel format for the screen */
126 if ( ! SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, 0) ) {
127 SDL_SetError("Couldn't allocate new pixel format for requested mode");
128 return(NULL);
129 }
130
131 /* Set up the new mode framebuffer */
132 current->w = width;
133 this->hidden->height = current->h = height;
134
135 if (bpp == 15) bpp = 16;
136 buffer = WIMP_CreateBuffer(width, height, bpp);
137 if (buffer == NULL)
138 {
139 SDL_SetError("Couldn't create sprite for video memory");
140 return (NULL);
141 }
142
143 this->hidden->bank[0] = buffer + 60; /* Start of sprite data */
144 if (bpp == 8) this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */
145
146 this->hidden->bank[1] = buffer; /* Start of buffer */
147
148 /* Remember sprite buffer so it can be freed later */
149 if (this->hidden->alloc_bank) SDL_free(this->hidden->alloc_bank);
150 this->hidden->alloc_bank = buffer;
151
152 current->pitch = width * bytesPerPixel;
153 if ((current->pitch & 3))
154 {
155 /* Sprites are 32bit word aligned */
156 current->pitch += (4 - (current->pitch & 3));
157 }
158
159 current->flags = flags | SDL_PREALLOC;
160
161 WIMP_ReadModeInfo(this);
162
163 SDL_memset(this->hidden->bank[0], 0, height * current->pitch);
164
165 this->hidden->current_bank = 0;
166 current->pixels = this->hidden->bank[0];
167
168
169 if (WIMP_SetupWindow(this, current) == 0)
170 {
171 SDL_SetError("Unable to create window to display surface");
172 return NULL;
173 }
174
175 /* Reset device functions for the wimp */
176 WIMP_SetDeviceMode(this);
177
178 /* Needs to set up plot info after window has been created */
179 /* Not sure why, but plots don't work if I do it earlier */
180 WIMP_SetupPlotInfo(this);
181
182 /* Poll until window is shown */
183 {
184 /* We wait until it gets the focus, but give up after 5 seconds
185 in case the focus is prevented in any way.
186 */
187 Uint32 now = SDL_GetTicks();
188 while (!hasFocus && SDL_GetTicks() - now < 5000)
189 {
190 WIMP_Poll(this, 0);
191 }
192 }
193
194 /* We're done */
195 return(current);
196}
197
198
199void WIMP_ReadModeInfo(_THIS)
200{
201 _kernel_swi_regs regs;
202 int vars[6];
203 int vals[5];
204
205 vars[0] = 4; /* XEig */
206 vars[1] = 5; /* YEig */
207 vars[2] = 9; /* Log base 2 bpp */
208 vars[3] = 11; /* Screen Width - 1 */
209 vars[4] = 12; /* Screen Depth - 1 */
210 vars[5] = -1; /* Terminate list */
211
212 regs.r[0] = (int)vars;
213 regs.r[1] = (int)vals;
214 _kernel_swi(OS_ReadVduVariables, &regs, &regs);
215 this->hidden->xeig = vals[0];
216 this->hidden->yeig = vals[1];
217 this->hidden->screen_bpp = 1 << vals[2];
218 this->hidden->screen_width = vals[3] + 1;
219 this->hidden->screen_height = vals[4] + 1;
220}
221
222/* Set device function to call the correct versions for running
223 in a wimp window */
224
225void WIMP_SetDeviceMode(_THIS)
226{
227 if (this->UpdateRects == WIMP_UpdateRects) return; /* Already set up */
228
229 this->SetColors = WIMP_SetColors;
230 this->UpdateRects = WIMP_UpdateRects;
231
232 this->FlipHWSurface = NULL;
233
234 this->SetCaption = WIMP_SetWMCaption;
235 this->SetIcon = NULL;
236 this->IconifyWindow = NULL;
237
238 this->ShowWMCursor = WIMP_ShowWMCursor;
239 this->WarpWMCursor = WIMP_WarpWMCursor;
240
241 this->ToggleFullScreen = RISCOS_ToggleFullScreen;
242
243 this->PumpEvents = WIMP_PumpEvents;
244}
245
246/* Setup the Window to display the surface */
247unsigned int WIMP_SetupWindow(_THIS, SDL_Surface *surface)
248{
249 _kernel_swi_regs regs;
250 int window_data[23];
251 int *window_block = window_data+1;
252 int x = (this->hidden->screen_width - surface->w) / 2;
253 int y = (this->hidden->screen_height - surface->h) / 2;
254 int xeig = this->hidden->xeig;
255 int yeig = this->hidden->yeig;
256
257 mouseInWindow = 0;
258
259 /* Always delete the window and recreate on a change */
260 if (this->hidden->window_handle) WIMP_DeleteWindow(this);
261
262 /* Setup window co-ordinates */
263 window_block[0] = x << xeig;
264 window_block[1] = y << yeig;
265 window_block[2] = window_block[0] + (surface->w << xeig);
266 window_block[3] = window_block[1] + (surface->h << yeig);
267
268
269 window_block[4] = 0; /* Scroll offsets */
270 window_block[5] = 0;
271 window_block[6] = -1; /* Open on top of window stack */
272
273 window_block[7] = 0x85040042; /* Window flags */
274 if (riscos_closeaction != 0) window_block[7] |= 0x2000000;
275
276 /* TODO: Take into account surface->flags */
277
278 window_block[8] = 0xff070207; /* Window colours */
279 window_block[9] = 0x000c0103;
280 window_block[10] = 0; /* Work area minimum */
281 window_block[11] = -surface->h << yeig;
282 window_block[12] = surface->w << xeig; /* Work area maximum */
283 window_block[13] = 0;
284 window_block[14] = 0x2700013d; /* Title icon flags */
285 window_block[15] = 0x00003000; /* Work area flags - Mouse click down reported */
286 window_block[16] = 1; /* Sprite area control block pointer */
287 window_block[17] = 0x00100010; /* Minimum window size (width & height) (16x16)*/
288 window_block[18] = (int)this->hidden->title; /* Title data */
289 window_block[19] = -1;
290 window_block[20] = 256;
291 window_block[21] = 0; /* Number of icons */
292
293 regs.r[1] = (unsigned int)(window_block);
294
295 /* Create the window */
296 if (_kernel_swi(Wimp_CreateWindow, &regs, &regs) == NULL)
297 {
298 this->hidden->window_handle = window_data[0] = regs.r[0];
299
300 /* Show the window on the screen */
301 regs.r[1] = (unsigned int)window_data;
302 if (_kernel_swi(Wimp_OpenWindow, &regs, &regs) == NULL)
303 {
304 WIMP_SetFocus(this->hidden->window_handle);
305 } else
306 {
307 WIMP_DeleteWindow(this);
308 }
309 }
310
311 return this->hidden->window_handle;
312}
313
314/* Destroy the Window */
315
316void WIMP_DeleteWindow(_THIS)
317{
318 _kernel_swi_regs regs;
319 regs.r[1] = (unsigned int)&(this->hidden->window_handle);
320 _kernel_swi(Wimp_DeleteWindow, &regs, &regs);
321 this->hidden->window_handle = 0;
322}
323
324
325void WIMP_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
326{
327 _kernel_swi_regs regs;
328 int update_block[12];
329 int xeig = this->hidden->xeig;
330 int yeig = this->hidden->yeig;
331 int j;
332 update_block[0] = this->hidden->window_handle;
333
334 for (j = 0; j < numrects; j++)
335 {
336 update_block[1] = rects[j].x << xeig; /* Min X */
337 update_block[4] = -(rects[j].y << yeig);
338 update_block[3] = update_block[1] + (rects[j].w << xeig);
339 update_block[2] = update_block[4] - (rects[j].h << yeig);
340
341 regs.r[1] = (int)update_block;
342 /* Update window can fail if called before first poll */
343 if (_kernel_swi(Wimp_UpdateWindow, &regs, &regs) == 0)
344 {
345 while (regs.r[0])
346 {
347 WIMP_PlotSprite(this, update_block[1], update_block[2]);
348 _kernel_swi(Wimp_GetRectangle, &regs, &regs);
349 }
350 }
351 }
352}
353
354
355int WIMP_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
356{
357 unsigned int *pal = (unsigned int *)(this->hidden->bank[1]+60);
358 int j;
359 SDL_Rect update;
360
361 pal += firstcolor*2;
362 for (j = 0; j < ncolors; j++)
363 {
364 *pal = (((unsigned int)colors->r) << 8)
365 + (((unsigned int)colors->g) << 16)
366 + (((unsigned int)colors->b) << 24);
367 pal[1] = *pal;
368 pal += 2;
369 colors++;
370 }
371
372 WIMP_SetupPlotInfo(this);
373
374 /* Need to refresh the window */
375 update.x = 0;
376 update.y = 0;
377 update.w = SDL_VideoSurface->w;
378 update.h = SDL_VideoSurface->h;
379 WIMP_UpdateRects(this, 1, &update);
380
381 return 1;
382}
383
384void WIMP_SetWMCaption(_THIS, const char *title, const char *icon)
385{
386 _kernel_swi_regs regs;
387
388 SDL_strlcpy(this->hidden->title, title, SDL_arraysize(this->hidden->title));
389
390 if (RISCOS_GetWimpVersion() < 380)
391 {
392 int block[6];
393
394 regs.r[1] = (int)block;
395 _kernel_swi(Wimp_GetCaretPosition, &regs, &regs);
396 if (block[0] == (int)this->hidden->window_handle)
397 {
398 regs.r[0] = -1;
399 _kernel_swi(Wimp_SetCaretPosition, &regs,&regs);
400 } else
401 {
402 regs.r[0] = this->hidden->window_handle;
403 regs.r[1] = -1;
404 regs.r[2] = -1;
405 regs.r[3] = -1;
406 _kernel_swi(Wimp_SetCaretPosition, &regs,&regs);
407 }
408 regs.r[0] = block[0];
409 regs.r[1] = block[1];
410 regs.r[2] = block[2];
411 regs.r[3] = block[3];
412 regs.r[4] = block[4];
413 regs.r[5] = block[5];
414 _kernel_swi(Wimp_SetCaretPosition, &regs,&regs);
415 } else
416 {
417 regs.r[0] = this->hidden->window_handle;
418 regs.r[1] = 0x4b534154; /* "TASK" */
419 regs.r[2] = 3; /* Redraw title */
420 _kernel_swi(Wimp_ForceRedraw, &regs, &regs);
421 }
422}
423
424void WIMP_RefreshDesktop(_THIS)
425{
426 int width = this->hidden->screen_width << this->hidden->xeig;
427 int height = this->hidden->screen_height << this->hidden->yeig;
428 _kernel_swi_regs regs;
429 regs.r[0] = -1; /* Whole screen */
430 regs.r[1] = 0;
431 regs.r[2] = 0;
432 regs.r[3] = width;
433 regs.r[4] = height;
434 _kernel_swi(Wimp_ForceRedraw, &regs, &regs);
435}
436
437/* Toggle to window from full screen */
438int WIMP_ToggleFromFullScreen(_THIS)
439{
440 int width = this->screen->w;
441 int height = this->screen->h;
442 int bpp = this->screen->format->BitsPerPixel;
443 char *buffer = NULL;
444 char *old_bank[2];
445 char *old_alloc_bank;
446
447 /* Ensure flags are OK */
448 this->screen->flags &= ~(SDL_DOUBLEBUF|SDL_HWSURFACE);
449
450 if (this->hidden->bank[0] == this->hidden->alloc_bank || riscos_backbuffer == 0)
451 {
452 /* Need to create a sprite for the screen and copy the data to it */
453 char *data;
454 buffer = WIMP_CreateBuffer(width, height, bpp);
455 data = buffer + 60; /* Start of sprite data */
456 if (bpp == 8) data += 2048; /* 8bpp sprite have palette first */
457
458 if (buffer == NULL) return 0;
459 SDL_memcpy(data, this->hidden->bank[0], width * height * this->screen->format->BytesPerPixel);
460 }
461 /* else We've switch to full screen before so we already have a sprite */
462
463 old_bank[0] = this->hidden->bank[0];
464 old_bank[1] = this->hidden->bank[1];
465 old_alloc_bank = this->hidden->alloc_bank;
466
467 if (buffer != NULL) this->hidden->alloc_bank = buffer;
468
469 this->hidden->bank[1] = this->hidden->alloc_bank;
470 this->hidden->bank[0] = this->hidden->bank[1] + 60; /* Start of sprite data */
471 if (bpp == 8) this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */
472
473 this->hidden->current_bank = 0;
474 this->screen->pixels = this->hidden->bank[0];
475
476 RISCOS_RestoreWimpMode();
477 WIMP_ReadModeInfo(this);
478 if (WIMP_SetupWindow(this, this->screen))
479 {
480 WIMP_SetDeviceMode(this);
481 WIMP_SetupPlotInfo(this);
482
483 if (riscos_backbuffer == 0) riscos_backbuffer = 1;
484
485 if (buffer && old_alloc_bank) SDL_free(old_alloc_bank);
486
487 return 1;
488 } else
489 {
490 /* Drop back to full screen mode on failure */
491 this->hidden->bank[0] = old_bank[0];
492 this->hidden->bank[1] = old_bank[1];
493 this->hidden->alloc_bank = old_alloc_bank;
494 if (buffer) SDL_free(buffer);
495
496 RISCOS_StoreWimpMode();
497 FULLSCREEN_SetMode(width, height, bpp);
498 }
499
500 return 0;
501}
diff --git a/apps/plugins/sdl/src/video/svga/SDL_svgaevents.c b/apps/plugins/sdl/src/video/svga/SDL_svgaevents.c
deleted file mode 100644
index 107a702cf3..0000000000
--- a/apps/plugins/sdl/src/video/svga/SDL_svgaevents.c
+++ /dev/null
@@ -1,412 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting X11 events into SDL events */
25
26#include <vga.h>
27#include <vgamouse.h>
28#include <vgakeyboard.h>
29#if defined(__LINUX__)
30#include <linux/kd.h>
31#include <linux/keyboard.h>
32#elif defined(__FREEBSD__)
33#include <sys/kbio.h>
34#else
35#error You must choose your operating system here
36#endif
37
38#include "../../events/SDL_sysevents.h"
39#include "../../events/SDL_events_c.h"
40#include "SDL_svgavideo.h"
41#include "SDL_svgaevents_c.h"
42
43/* The translation tables from a console scancode to a SDL keysym */
44#if defined(linux)
45#define NUM_VGAKEYMAPS (1<<KG_CAPSSHIFT)
46static Uint16 vga_keymap[NUM_VGAKEYMAPS][NR_KEYS];
47#elif defined(__FREEBSD__)
48/* FIXME: Free the keymap when we shut down the video mode */
49static keymap_t *vga_keymap = NULL;
50#else
51#error You must choose your operating system here
52#endif
53static SDLKey keymap[128];
54static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym);
55
56/* Ugh, we have to duplicate the kernel's keysym mapping code...
57 Oh, it's not so bad. :-)
58
59 FIXME: Add keyboard LED handling code
60 */
61#if defined(linux)
62int SVGA_initkeymaps(int fd)
63{
64 struct kbentry entry;
65 int map, i;
66
67 /* Load all the keysym mappings */
68 for ( map=0; map<NUM_VGAKEYMAPS; ++map ) {
69 SDL_memset(vga_keymap[map], 0, NR_KEYS*sizeof(Uint16));
70 for ( i=0; i<NR_KEYS; ++i ) {
71 entry.kb_table = map;
72 entry.kb_index = i;
73 if ( ioctl(fd, KDGKBENT, &entry) == 0 ) {
74 /* The "Enter" key is a special case */
75 if ( entry.kb_value == K_ENTER ) {
76 entry.kb_value = K(KT_ASCII,13);
77 }
78 /* Handle numpad specially as well */
79 if ( KTYP(entry.kb_value) == KT_PAD ) {
80 switch ( entry.kb_value ) {
81 case K_P0:
82 case K_P1:
83 case K_P2:
84 case K_P3:
85 case K_P4:
86 case K_P5:
87 case K_P6:
88 case K_P7:
89 case K_P8:
90 case K_P9:
91 vga_keymap[map][i]=entry.kb_value;
92 vga_keymap[map][i]+= '0';
93 break;
94 case K_PPLUS:
95 vga_keymap[map][i]=K(KT_ASCII,'+');
96 break;
97 case K_PMINUS:
98 vga_keymap[map][i]=K(KT_ASCII,'-');
99 break;
100 case K_PSTAR:
101 vga_keymap[map][i]=K(KT_ASCII,'*');
102 break;
103 case K_PSLASH:
104 vga_keymap[map][i]=K(KT_ASCII,'/');
105 break;
106 case K_PENTER:
107 vga_keymap[map][i]=K(KT_ASCII,'\r');
108 break;
109 case K_PCOMMA:
110 vga_keymap[map][i]=K(KT_ASCII,',');
111 break;
112 case K_PDOT:
113 vga_keymap[map][i]=K(KT_ASCII,'.');
114 break;
115 default:
116 break;
117 }
118 }
119 /* Do the normal key translation */
120 if ( (KTYP(entry.kb_value) == KT_LATIN) ||
121 (KTYP(entry.kb_value) == KT_ASCII) ||
122 (KTYP(entry.kb_value) == KT_LETTER) ) {
123 vga_keymap[map][i] = entry.kb_value;
124 }
125 }
126 }
127 }
128 return(0);
129}
130#elif defined(__FREEBSD__)
131int SVGA_initkeymaps(int fd)
132{
133 vga_keymap = SDL_malloc(sizeof(keymap_t));
134 if ( ! vga_keymap ) {
135 SDL_OutOfMemory();
136 return(-1);
137 }
138 if (ioctl(fd, GIO_KEYMAP, vga_keymap) == -1) {
139 SDL_free(vga_keymap);
140 vga_keymap = NULL;
141 SDL_SetError("Unable to get keyboard map");
142 return(-1);
143 }
144 return(0);
145}
146#else
147#error You must choose your operating system here
148#endif
149
150int posted = 0;
151
152void SVGA_mousecallback(int button, int dx, int dy,
153 int u1,int u2,int u3, int u4)
154{
155 if ( dx || dy ) {
156 posted += SDL_PrivateMouseMotion(0, 1, dx, dy);
157 }
158 if ( button & MOUSE_LEFTBUTTON ) {
159 if ( !(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(1)) ) {
160 posted += SDL_PrivateMouseButton(SDL_PRESSED, 1, 0, 0);
161 }
162 } else {
163 if ( (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(1)) ) {
164 posted += SDL_PrivateMouseButton(SDL_RELEASED, 1, 0, 0);
165 }
166 }
167 if ( button & MOUSE_MIDDLEBUTTON ) {
168 if ( !(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(2)) ) {
169 posted += SDL_PrivateMouseButton(SDL_PRESSED, 2, 0, 0);
170 }
171 } else {
172 if ( (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(2)) ) {
173 posted += SDL_PrivateMouseButton(SDL_RELEASED, 2, 0, 0);
174 }
175 }
176 if ( button & MOUSE_RIGHTBUTTON ) {
177 if ( !(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(3)) ) {
178 posted += SDL_PrivateMouseButton(SDL_PRESSED, 3, 0, 0);
179 }
180 } else {
181 if ( (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(3)) ) {
182 posted += SDL_PrivateMouseButton(SDL_RELEASED, 3, 0, 0);
183 }
184 }
185}
186
187void SVGA_keyboardcallback(int scancode, int pressed)
188{
189 SDL_keysym keysym;
190
191 if ( pressed ) {
192 posted += SDL_PrivateKeyboard(SDL_PRESSED,
193 TranslateKey(scancode, &keysym));
194 } else {
195 posted += SDL_PrivateKeyboard(SDL_RELEASED,
196 TranslateKey(scancode, &keysym));
197 }
198}
199
200void SVGA_PumpEvents(_THIS)
201{
202 do {
203 posted = 0;
204 mouse_update();
205 keyboard_update();
206 } while ( posted );
207}
208
209void SVGA_InitOSKeymap(_THIS)
210{
211 int i;
212
213 /* Initialize the BeOS key translation table */
214 for ( i=0; i<SDL_arraysize(keymap); ++i )
215 keymap[i] = SDLK_UNKNOWN;
216
217 keymap[SCANCODE_ESCAPE] = SDLK_ESCAPE;
218 keymap[SCANCODE_1] = SDLK_1;
219 keymap[SCANCODE_2] = SDLK_2;
220 keymap[SCANCODE_3] = SDLK_3;
221 keymap[SCANCODE_4] = SDLK_4;
222 keymap[SCANCODE_5] = SDLK_5;
223 keymap[SCANCODE_6] = SDLK_6;
224 keymap[SCANCODE_7] = SDLK_7;
225 keymap[SCANCODE_8] = SDLK_8;
226 keymap[SCANCODE_9] = SDLK_9;
227 keymap[SCANCODE_0] = SDLK_0;
228 keymap[SCANCODE_MINUS] = SDLK_MINUS;
229 keymap[SCANCODE_EQUAL] = SDLK_EQUALS;
230 keymap[SCANCODE_BACKSPACE] = SDLK_BACKSPACE;
231 keymap[SCANCODE_TAB] = SDLK_TAB;
232 keymap[SCANCODE_Q] = SDLK_q;
233 keymap[SCANCODE_W] = SDLK_w;
234 keymap[SCANCODE_E] = SDLK_e;
235 keymap[SCANCODE_R] = SDLK_r;
236 keymap[SCANCODE_T] = SDLK_t;
237 keymap[SCANCODE_Y] = SDLK_y;
238 keymap[SCANCODE_U] = SDLK_u;
239 keymap[SCANCODE_I] = SDLK_i;
240 keymap[SCANCODE_O] = SDLK_o;
241 keymap[SCANCODE_P] = SDLK_p;
242 keymap[SCANCODE_BRACKET_LEFT] = SDLK_LEFTBRACKET;
243 keymap[SCANCODE_BRACKET_RIGHT] = SDLK_RIGHTBRACKET;
244 keymap[SCANCODE_ENTER] = SDLK_RETURN;
245 keymap[SCANCODE_LEFTCONTROL] = SDLK_LCTRL;
246 keymap[SCANCODE_A] = SDLK_a;
247 keymap[SCANCODE_S] = SDLK_s;
248 keymap[SCANCODE_D] = SDLK_d;
249 keymap[SCANCODE_F] = SDLK_f;
250 keymap[SCANCODE_G] = SDLK_g;
251 keymap[SCANCODE_H] = SDLK_h;
252 keymap[SCANCODE_J] = SDLK_j;
253 keymap[SCANCODE_K] = SDLK_k;
254 keymap[SCANCODE_L] = SDLK_l;
255 keymap[SCANCODE_SEMICOLON] = SDLK_SEMICOLON;
256 keymap[SCANCODE_APOSTROPHE] = SDLK_QUOTE;
257 keymap[SCANCODE_GRAVE] = SDLK_BACKQUOTE;
258 keymap[SCANCODE_LEFTSHIFT] = SDLK_LSHIFT;
259 keymap[SCANCODE_BACKSLASH] = SDLK_BACKSLASH;
260 keymap[SCANCODE_Z] = SDLK_z;
261 keymap[SCANCODE_X] = SDLK_x;
262 keymap[SCANCODE_C] = SDLK_c;
263 keymap[SCANCODE_V] = SDLK_v;
264 keymap[SCANCODE_B] = SDLK_b;
265 keymap[SCANCODE_N] = SDLK_n;
266 keymap[SCANCODE_M] = SDLK_m;
267 keymap[SCANCODE_COMMA] = SDLK_COMMA;
268 keymap[SCANCODE_PERIOD] = SDLK_PERIOD;
269 keymap[SCANCODE_SLASH] = SDLK_SLASH;
270 keymap[SCANCODE_RIGHTSHIFT] = SDLK_RSHIFT;
271 keymap[SCANCODE_KEYPADMULTIPLY] = SDLK_KP_MULTIPLY;
272 keymap[SCANCODE_LEFTALT] = SDLK_LALT;
273 keymap[SCANCODE_SPACE] = SDLK_SPACE;
274 keymap[SCANCODE_CAPSLOCK] = SDLK_CAPSLOCK;
275 keymap[SCANCODE_F1] = SDLK_F1;
276 keymap[SCANCODE_F2] = SDLK_F2;
277 keymap[SCANCODE_F3] = SDLK_F3;
278 keymap[SCANCODE_F4] = SDLK_F4;
279 keymap[SCANCODE_F5] = SDLK_F5;
280 keymap[SCANCODE_F6] = SDLK_F6;
281 keymap[SCANCODE_F7] = SDLK_F7;
282 keymap[SCANCODE_F8] = SDLK_F8;
283 keymap[SCANCODE_F9] = SDLK_F9;
284 keymap[SCANCODE_F10] = SDLK_F10;
285 keymap[SCANCODE_NUMLOCK] = SDLK_NUMLOCK;
286 keymap[SCANCODE_SCROLLLOCK] = SDLK_SCROLLOCK;
287 keymap[SCANCODE_KEYPAD7] = SDLK_KP7;
288 keymap[SCANCODE_CURSORUPLEFT] = SDLK_KP7;
289 keymap[SCANCODE_KEYPAD8] = SDLK_KP8;
290 keymap[SCANCODE_CURSORUP] = SDLK_KP8;
291 keymap[SCANCODE_KEYPAD9] = SDLK_KP9;
292 keymap[SCANCODE_CURSORUPRIGHT] = SDLK_KP9;
293 keymap[SCANCODE_KEYPADMINUS] = SDLK_KP_MINUS;
294 keymap[SCANCODE_KEYPAD4] = SDLK_KP4;
295 keymap[SCANCODE_CURSORLEFT] = SDLK_KP4;
296 keymap[SCANCODE_KEYPAD5] = SDLK_KP5;
297 keymap[SCANCODE_KEYPAD6] = SDLK_KP6;
298 keymap[SCANCODE_CURSORRIGHT] = SDLK_KP6;
299 keymap[SCANCODE_KEYPADPLUS] = SDLK_KP_PLUS;
300 keymap[SCANCODE_KEYPAD1] = SDLK_KP1;
301 keymap[SCANCODE_CURSORDOWNLEFT] = SDLK_KP1;
302 keymap[SCANCODE_KEYPAD2] = SDLK_KP2;
303 keymap[SCANCODE_CURSORDOWN] = SDLK_KP2;
304 keymap[SCANCODE_KEYPAD3] = SDLK_KP3;
305 keymap[SCANCODE_CURSORDOWNRIGHT] = SDLK_KP3;
306 keymap[SCANCODE_KEYPAD0] = SDLK_KP0;
307 keymap[SCANCODE_KEYPADPERIOD] = SDLK_KP_PERIOD;
308 keymap[SCANCODE_LESS] = SDLK_LESS;
309 keymap[SCANCODE_F11] = SDLK_F11;
310 keymap[SCANCODE_F12] = SDLK_F12;
311 keymap[SCANCODE_KEYPADENTER] = SDLK_KP_ENTER;
312 keymap[SCANCODE_RIGHTCONTROL] = SDLK_RCTRL;
313 keymap[SCANCODE_CONTROL] = SDLK_RCTRL;
314 keymap[SCANCODE_KEYPADDIVIDE] = SDLK_KP_DIVIDE;
315 keymap[SCANCODE_PRINTSCREEN] = SDLK_PRINT;
316 keymap[SCANCODE_RIGHTALT] = SDLK_RALT;
317 keymap[SCANCODE_BREAK] = SDLK_BREAK;
318 keymap[SCANCODE_BREAK_ALTERNATIVE] = SDLK_UNKNOWN;
319 keymap[SCANCODE_HOME] = SDLK_HOME;
320 keymap[SCANCODE_CURSORBLOCKUP] = SDLK_UP;
321 keymap[SCANCODE_PAGEUP] = SDLK_PAGEUP;
322 keymap[SCANCODE_CURSORBLOCKLEFT] = SDLK_LEFT;
323 keymap[SCANCODE_CURSORBLOCKRIGHT] = SDLK_RIGHT;
324 keymap[SCANCODE_END] = SDLK_END;
325 keymap[SCANCODE_CURSORBLOCKDOWN] = SDLK_DOWN;
326 keymap[SCANCODE_PAGEDOWN] = SDLK_PAGEDOWN;
327 keymap[SCANCODE_INSERT] = SDLK_INSERT;
328 keymap[SCANCODE_REMOVE] = SDLK_DELETE;
329 keymap[119] = SDLK_PAUSE;
330 keymap[SCANCODE_RIGHTWIN] = SDLK_RSUPER;
331 keymap[SCANCODE_LEFTWIN] = SDLK_LSUPER;
332 keymap[127] = SDLK_MENU;
333}
334
335#if defined(linux)
336static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym)
337{
338 /* Set the keysym information */
339 keysym->scancode = scancode;
340 keysym->sym = keymap[scancode];
341 keysym->mod = KMOD_NONE;
342
343 /* If UNICODE is on, get the UNICODE value for the key */
344 keysym->unicode = 0;
345 if ( SDL_TranslateUNICODE ) {
346 int map;
347 SDLMod modstate;
348
349 modstate = SDL_GetModState();
350 map = 0;
351 if ( modstate & KMOD_SHIFT ) {
352 map |= (1<<KG_SHIFT);
353 }
354 if ( modstate & KMOD_CTRL ) {
355 map |= (1<<KG_CTRL);
356 }
357 if ( modstate & KMOD_ALT ) {
358 map |= (1<<KG_ALT);
359 }
360 if ( modstate & KMOD_MODE ) {
361 map |= (1<<KG_ALTGR);
362 }
363 if ( KTYP(vga_keymap[map][scancode]) == KT_LETTER ) {
364 if ( modstate & KMOD_CAPS ) {
365 map ^= (1<<KG_SHIFT);
366 }
367 }
368 if ( KTYP(vga_keymap[map][scancode]) == KT_PAD ) {
369 if ( modstate & KMOD_NUM ) {
370 keysym->unicode=KVAL(vga_keymap[map][scancode]);
371 }
372 } else {
373 keysym->unicode = KVAL(vga_keymap[map][scancode]);
374 }
375 }
376 return(keysym);
377}
378#elif defined(__FREEBSD__)
379static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym)
380{
381 /* Set the keysym information */
382 keysym->scancode = scancode;
383 keysym->sym = keymap[scancode];
384 keysym->mod = KMOD_NONE;
385
386 /* If UNICODE is on, get the UNICODE value for the key */
387 keysym->unicode = 0;
388 if ( SDL_TranslateUNICODE && vga_keymap ) {
389 int map;
390 SDLMod modstate;
391
392 modstate = SDL_GetModState();
393 map = 0;
394 if ( modstate & KMOD_SHIFT ) {
395 map += 1;
396 }
397 if ( modstate & KMOD_CTRL ) {
398 map += 2;
399 }
400 if ( modstate & KMOD_ALT ) {
401 map += 4;
402 }
403 if ( !(vga_keymap->key[scancode].spcl & (0x80 >> map)) ) {
404 keysym->unicode = vga_keymap->key[scancode].map[map];
405 }
406
407 }
408 return(keysym);
409}
410#else
411#error You must choose your operating system here
412#endif
diff --git a/apps/plugins/sdl/src/video/svga/SDL_svgaevents_c.h b/apps/plugins/sdl/src/video/svga/SDL_svgaevents_c.h
deleted file mode 100644
index cd9f888904..0000000000
--- a/apps/plugins/sdl/src/video/svga/SDL_svgaevents_c.h
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_svgavideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29extern int SVGA_initkeymaps(int fd);
30extern void SVGA_mousecallback(int button, int dx, int dy,
31 int u1,int u2,int u3, int u4);
32extern void SVGA_keyboardcallback(int scancode, int pressed);
33
34extern void SVGA_InitOSKeymap(_THIS);
35extern void SVGA_PumpEvents(_THIS);
diff --git a/apps/plugins/sdl/src/video/svga/SDL_svgamouse.c b/apps/plugins/sdl/src/video/svga/SDL_svgamouse.c
deleted file mode 100644
index a82dbfd7c7..0000000000
--- a/apps/plugins/sdl/src/video/svga/SDL_svgamouse.c
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_mouse.h"
25#include "../../events/SDL_events_c.h"
26#include "SDL_svgavideo.h"
27#include "SDL_svgamouse_c.h"
28
29
30/* The implementation dependent data for the window manager cursor */
31struct WMcursor {
32 int unused;
33};
diff --git a/apps/plugins/sdl/src/video/svga/SDL_svgamouse_c.h b/apps/plugins/sdl/src/video/svga/SDL_svgamouse_c.h
deleted file mode 100644
index 78fe8abcb2..0000000000
--- a/apps/plugins/sdl/src/video/svga/SDL_svgamouse_c.h
+++ /dev/null
@@ -1,26 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_svgavideo.h"
25
26/* Functions to be exported */
diff --git a/apps/plugins/sdl/src/video/svga/SDL_svgavideo.c b/apps/plugins/sdl/src/video/svga/SDL_svgavideo.c
deleted file mode 100644
index 58ea800f24..0000000000
--- a/apps/plugins/sdl/src/video/svga/SDL_svgavideo.c
+++ /dev/null
@@ -1,584 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* SVGAlib based SDL video driver implementation.
25*/
26
27#include <unistd.h>
28#include <sys/stat.h>
29#include <sys/types.h>
30#include <sys/ioctl.h>
31#include <fcntl.h>
32
33#if defined(__LINUX__)
34#include <linux/vt.h>
35#elif defined(__FREEBSD__)
36#include <sys/consio.h>
37#else
38#error You must choose your operating system here
39#endif
40#include <vga.h>
41#include <vgamouse.h>
42#include <vgakeyboard.h>
43
44#include "SDL_video.h"
45#include "SDL_mouse.h"
46#include "../SDL_sysvideo.h"
47#include "../SDL_pixels_c.h"
48#include "../../events/SDL_events_c.h"
49#include "SDL_svgavideo.h"
50#include "SDL_svgaevents_c.h"
51#include "SDL_svgamouse_c.h"
52
53/* Initialization/Query functions */
54static int SVGA_VideoInit(_THIS, SDL_PixelFormat *vformat);
55static SDL_Rect **SVGA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
56static SDL_Surface *SVGA_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
57static int SVGA_SetColors(_THIS, int firstcolor, int ncolors,
58 SDL_Color *colors);
59static void SVGA_VideoQuit(_THIS);
60
61/* Hardware surface functions */
62static int SVGA_AllocHWSurface(_THIS, SDL_Surface *surface);
63static int SVGA_LockHWSurface(_THIS, SDL_Surface *surface);
64static int SVGA_FlipHWSurface(_THIS, SDL_Surface *surface);
65static void SVGA_UnlockHWSurface(_THIS, SDL_Surface *surface);
66static void SVGA_FreeHWSurface(_THIS, SDL_Surface *surface);
67
68/* SVGAlib driver bootstrap functions */
69
70static int SVGA_Available(void)
71{
72 /* Check to see if we are root and stdin is a virtual console */
73 int console;
74
75 /* SVGALib 1.9.x+ doesn't require root (via /dev/svga) */
76 int svgalib2 = -1;
77
78 /* See if we are connected to a virtual terminal */
79 console = STDIN_FILENO;
80#if 0 /* This is no longer needed, SVGAlib can switch consoles for us */
81 if ( console >= 0 ) {
82 struct stat sb;
83 struct vt_mode dummy;
84
85 if ( (fstat(console, &sb) < 0) ||
86 (ioctl(console, VT_GETMODE, &dummy) < 0) ) {
87 console = -1;
88 }
89 }
90#endif /* 0 */
91
92 /* See if SVGAlib 2.0 is available */
93 svgalib2 = open("/dev/svga", O_RDONLY);
94 if (svgalib2 != -1) {
95 close(svgalib2);
96 }
97
98 return(((svgalib2 != -1) || (geteuid() == 0)) && (console >= 0));
99}
100
101static void SVGA_DeleteDevice(SDL_VideoDevice *device)
102{
103 SDL_free(device->hidden);
104 SDL_free(device);
105}
106
107static SDL_VideoDevice *SVGA_CreateDevice(int devindex)
108{
109 SDL_VideoDevice *device;
110
111 /* Initialize all variables that we clean on shutdown */
112 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
113 if ( device ) {
114 SDL_memset(device, 0, (sizeof *device));
115 device->hidden = (struct SDL_PrivateVideoData *)
116 SDL_malloc((sizeof *device->hidden));
117 }
118 if ( (device == NULL) || (device->hidden == NULL) ) {
119 SDL_OutOfMemory();
120 if ( device ) {
121 SDL_free(device);
122 }
123 return(0);
124 }
125 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
126
127 /* Set the function pointers */
128 device->VideoInit = SVGA_VideoInit;
129 device->ListModes = SVGA_ListModes;
130 device->SetVideoMode = SVGA_SetVideoMode;
131 device->SetColors = SVGA_SetColors;
132 device->UpdateRects = NULL;
133 device->VideoQuit = SVGA_VideoQuit;
134 device->AllocHWSurface = SVGA_AllocHWSurface;
135 device->CheckHWBlit = NULL;
136 device->FillHWRect = NULL;
137 device->SetHWColorKey = NULL;
138 device->SetHWAlpha = NULL;
139 device->LockHWSurface = SVGA_LockHWSurface;
140 device->UnlockHWSurface = SVGA_UnlockHWSurface;
141 device->FlipHWSurface = SVGA_FlipHWSurface;
142 device->FreeHWSurface = SVGA_FreeHWSurface;
143 device->SetCaption = NULL;
144 device->SetIcon = NULL;
145 device->IconifyWindow = NULL;
146 device->GrabInput = NULL;
147 device->GetWMInfo = NULL;
148 device->InitOSKeymap = SVGA_InitOSKeymap;
149 device->PumpEvents = SVGA_PumpEvents;
150
151 device->free = SVGA_DeleteDevice;
152
153 return device;
154}
155
156VideoBootStrap SVGALIB_bootstrap = {
157 "svgalib", "SVGAlib",
158 SVGA_Available, SVGA_CreateDevice
159};
160
161static int SVGA_AddMode(_THIS, int mode, int actually_add)
162{
163 int i, j;
164 vga_modeinfo *modeinfo;
165
166 modeinfo = vga_getmodeinfo(mode);
167
168 i = modeinfo->bytesperpixel-1;
169 if ( i < 0 ) {
170 return 0;
171 }
172 if ( actually_add ) {
173 SDL_Rect saved_rect[2];
174 int saved_mode[2];
175 int b;
176
177 /* Add the mode, sorted largest to smallest */
178 b = 0;
179 j = 0;
180 while ( (SDL_modelist[i][j]->w > modeinfo->width) ||
181 (SDL_modelist[i][j]->h > modeinfo->height) ) {
182 ++j;
183 }
184 /* Skip modes that are already in our list */
185 if ( (SDL_modelist[i][j]->w == modeinfo->width) &&
186 (SDL_modelist[i][j]->h == modeinfo->height) ) {
187 return(0);
188 }
189 /* Insert the new mode */
190 saved_rect[b] = *SDL_modelist[i][j];
191 saved_mode[b] = SDL_vgamode[i][j];
192 SDL_modelist[i][j]->w = modeinfo->width;
193 SDL_modelist[i][j]->h = modeinfo->height;
194 SDL_vgamode[i][j] = mode;
195 /* Everybody scoot down! */
196 if ( saved_rect[b].w && saved_rect[b].h ) {
197 for ( ++j; SDL_modelist[i][j]->w; ++j ) {
198 saved_rect[!b] = *SDL_modelist[i][j];
199 saved_mode[!b] = SDL_vgamode[i][j];
200 *SDL_modelist[i][j] = saved_rect[b];
201 SDL_vgamode[i][j] = saved_mode[b];
202 b = !b;
203 }
204 *SDL_modelist[i][j] = saved_rect[b];
205 SDL_vgamode[i][j] = saved_mode[b];
206 }
207 } else {
208 ++SDL_nummodes[i];
209 }
210 return(1);
211}
212
213static void SVGA_UpdateVideoInfo(_THIS)
214{
215 vga_modeinfo *modeinfo;
216
217 this->info.wm_available = 0;
218 this->info.hw_available = (banked ? 0 : 1);
219 modeinfo = vga_getmodeinfo(vga_getcurrentmode());
220 this->info.video_mem = modeinfo->memory;
221 /* FIXME: Add hardware accelerated blit information */
222#ifdef SVGALIB_DEBUG
223 printf("Hardware accelerated blit: %savailable\n", modeinfo->haveblit ? "" : "not ");
224#endif
225}
226
227int SVGA_VideoInit(_THIS, SDL_PixelFormat *vformat)
228{
229 int keyboard;
230 int i, j;
231 int mode, total_modes;
232
233 /* Initialize all variables that we clean on shutdown */
234 for ( i=0; i<NUM_MODELISTS; ++i ) {
235 SDL_nummodes[i] = 0;
236 SDL_modelist[i] = NULL;
237 SDL_vgamode[i] = NULL;
238 }
239
240 /* Initialize the library */
241 vga_disabledriverreport();
242 if ( vga_init() < 0 ) {
243 SDL_SetError("Unable to initialize SVGAlib");
244 return(-1);
245 }
246 vga_setmode(TEXT);
247
248 /* Enable mouse and keyboard support */
249 vga_setmousesupport(1);
250 keyboard = keyboard_init_return_fd();
251 if ( keyboard < 0 ) {
252 SDL_SetError("Unable to initialize keyboard");
253 return(-1);
254 }
255 if ( SVGA_initkeymaps(keyboard) < 0 ) {
256 return(-1);
257 }
258 keyboard_seteventhandler(SVGA_keyboardcallback);
259
260 /* Determine the current screen size */
261 this->info.current_w = 0;
262 this->info.current_h = 0;
263
264 /* Determine the screen depth (use default 8-bit depth) */
265 vformat->BitsPerPixel = 8;
266
267 /* Enumerate the available fullscreen modes */
268 total_modes = 0;
269 for ( mode=vga_lastmodenumber(); mode; --mode ) {
270 if ( vga_hasmode(mode) ) {
271 if ( SVGA_AddMode(this, mode, 0) ) {
272 ++total_modes;
273 }
274 }
275 }
276 if ( SVGA_AddMode(this, G320x200x256, 0) ) ++total_modes;
277 if ( total_modes == 0 ) {
278 SDL_SetError("No linear video modes available");
279 return(-1);
280 }
281 for ( i=0; i<NUM_MODELISTS; ++i ) {
282 SDL_vgamode[i] = (int *)SDL_malloc(SDL_nummodes[i]*sizeof(int));
283 if ( SDL_vgamode[i] == NULL ) {
284 SDL_OutOfMemory();
285 return(-1);
286 }
287 SDL_modelist[i] = (SDL_Rect **)
288 SDL_malloc((SDL_nummodes[i]+1)*sizeof(SDL_Rect *));
289 if ( SDL_modelist[i] == NULL ) {
290 SDL_OutOfMemory();
291 return(-1);
292 }
293 for ( j=0; j<SDL_nummodes[i]; ++j ) {
294 SDL_modelist[i][j]=(SDL_Rect *)SDL_malloc(sizeof(SDL_Rect));
295 if ( SDL_modelist[i][j] == NULL ) {
296 SDL_OutOfMemory();
297 return(-1);
298 }
299 SDL_memset(SDL_modelist[i][j], 0, sizeof(SDL_Rect));
300 }
301 SDL_modelist[i][j] = NULL;
302 }
303 for ( mode=vga_lastmodenumber(); mode; --mode ) {
304 if ( vga_hasmode(mode) ) {
305 SVGA_AddMode(this, mode, 1);
306 }
307 }
308 SVGA_AddMode(this, G320x200x256, 1);
309
310 /* Free extra (duplicated) modes */
311 for ( i=0; i<NUM_MODELISTS; ++i ) {
312 j = 0;
313 while ( SDL_modelist[i][j] && SDL_modelist[i][j]->w ) {
314 j++;
315 }
316 while ( SDL_modelist[i][j] ) {
317 SDL_free(SDL_modelist[i][j]);
318 SDL_modelist[i][j] = NULL;
319 j++;
320 }
321 }
322
323 /* Fill in our hardware acceleration capabilities */
324 SVGA_UpdateVideoInfo(this);
325
326 /* We're done! */
327 return(0);
328}
329
330SDL_Rect **SVGA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
331{
332 return(SDL_modelist[((format->BitsPerPixel+7)/8)-1]);
333}
334
335/* Various screen update functions available */
336static void SVGA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
337static void SVGA_BankedUpdate(_THIS, int numrects, SDL_Rect *rects);
338
339SDL_Surface *SVGA_SetVideoMode(_THIS, SDL_Surface *current,
340 int width, int height, int bpp, Uint32 flags)
341{
342 int mode;
343 int vgamode;
344 vga_modeinfo *modeinfo;
345 int screenpage_len;
346
347 /* Free old pixels if we were in banked mode */
348 if ( banked && current->pixels ) {
349 free(current->pixels);
350 current->pixels = NULL;
351 }
352
353 /* Try to set the requested linear video mode */
354 bpp = (bpp+7)/8-1;
355 for ( mode=0; SDL_modelist[bpp][mode]; ++mode ) {
356 if ( (SDL_modelist[bpp][mode]->w == width) &&
357 (SDL_modelist[bpp][mode]->h == height) ) {
358 break;
359 }
360 }
361 if ( SDL_modelist[bpp][mode] == NULL ) {
362 SDL_SetError("Couldn't find requested mode in list");
363 return(NULL);
364 }
365 vgamode = SDL_vgamode[bpp][mode];
366 vga_setmode(vgamode);
367 vga_setpage(0);
368
369 if ( (vga_setlinearaddressing() < 0) && (vgamode != G320x200x256) ) {
370 banked = 1;
371 } else {
372 banked = 0;
373 }
374
375 modeinfo = vga_getmodeinfo(SDL_vgamode[bpp][mode]);
376
377 /* Update hardware acceleration info */
378 SVGA_UpdateVideoInfo(this);
379
380 /* Allocate the new pixel format for the screen */
381 bpp = (bpp+1)*8;
382 if ( (bpp == 16) && (modeinfo->colors == 32768) ) {
383 bpp = 15;
384 }
385 if ( ! SDL_ReallocFormat(current, bpp, 0, 0, 0, 0) ) {
386 return(NULL);
387 }
388
389 /* Set up the new mode framebuffer */
390 current->flags = SDL_FULLSCREEN;
391 if ( !banked ) {
392 current->flags |= SDL_HWSURFACE;
393 }
394 if ( bpp == 8 ) {
395 /* FIXME: What about DirectColor? */
396 current->flags |= SDL_HWPALETTE;
397 }
398 current->w = width;
399 current->h = height;
400 current->pitch = modeinfo->linewidth;
401 if ( banked ) {
402 current->pixels = SDL_malloc(current->h * current->pitch);
403 if ( !current->pixels ) {
404 SDL_OutOfMemory();
405 return(NULL);
406 }
407 } else {
408 current->pixels = vga_getgraphmem();
409 }
410
411 /* set double-buffering */
412 if ( (flags & SDL_DOUBLEBUF) && !banked )
413 {
414 /* length of one screen page in bytes */
415 screenpage_len=current->h*modeinfo->linewidth;
416
417 /* if start address should be aligned */
418 if ( modeinfo->linewidth_unit )
419 {
420 if ( screenpage_len % modeinfo->linewidth_unit )
421 {
422 screenpage_len += modeinfo->linewidth_unit - ( screenpage_len % modeinfo->linewidth_unit );
423 }
424 }
425
426 /* if we heve enough videomemory = ak je dost videopamete */
427 if ( modeinfo->memory > ( screenpage_len * 2 / 1024 ) )
428 {
429 current->flags |= SDL_DOUBLEBUF;
430 flip_page = 0;
431 flip_offset[0] = 0;
432 flip_offset[1] = screenpage_len;
433 flip_address[0] = vga_getgraphmem();
434 flip_address[1] = flip_address[0]+screenpage_len;
435 SVGA_FlipHWSurface(this,current);
436 }
437 }
438
439 /* Set the blit function */
440 if ( banked ) {
441 this->UpdateRects = SVGA_BankedUpdate;
442 } else {
443 this->UpdateRects = SVGA_DirectUpdate;
444 }
445
446 /* Set up the mouse handler again (buggy SVGAlib 1.40) */
447 mouse_seteventhandler(SVGA_mousecallback);
448
449 /* We're done */
450 return(current);
451}
452
453/* We don't actually allow hardware surfaces other than the main one */
454static int SVGA_AllocHWSurface(_THIS, SDL_Surface *surface)
455{
456 return(-1);
457}
458static void SVGA_FreeHWSurface(_THIS, SDL_Surface *surface)
459{
460 return;
461}
462
463/* We need to wait for vertical retrace on page flipped displays */
464static int SVGA_LockHWSurface(_THIS, SDL_Surface *surface)
465{
466 /* The waiting is done in SVGA_FlipHWSurface() */
467 return(0);
468}
469static void SVGA_UnlockHWSurface(_THIS, SDL_Surface *surface)
470{
471 return;
472}
473
474static int SVGA_FlipHWSurface(_THIS, SDL_Surface *surface)
475{
476 if ( !banked ) {
477 vga_setdisplaystart(flip_offset[flip_page]);
478 flip_page=!flip_page;
479 surface->pixels=flip_address[flip_page];
480 vga_waitretrace();
481 }
482 return(0);
483}
484
485static void SVGA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
486{
487 return;
488}
489
490static void SVGA_BankedUpdate(_THIS, int numrects, SDL_Rect *rects)
491{
492 int i, j;
493 SDL_Rect *rect;
494 int page, vp;
495 int x, y, w, h;
496 unsigned char *src;
497 unsigned char *dst;
498 int bpp = this->screen->format->BytesPerPixel;
499 int pitch = this->screen->pitch;
500
501 dst = vga_getgraphmem();
502 for ( i=0; i < numrects; ++i ) {
503 rect = &rects[i];
504 x = rect->x;
505 y = rect->y;
506 w = rect->w * bpp;
507 h = rect->h;
508
509 vp = y * pitch + x * bpp;
510 src = (unsigned char *)this->screen->pixels + vp;
511 page = vp >> 16;
512 vp &= 0xffff;
513 vga_setpage(page);
514 for (j = 0; j < h; j++) {
515 if (vp + w > 0x10000) {
516 if (vp >= 0x10000) {
517 page++;
518 vga_setpage(page);
519 vp &= 0xffff;
520 } else {
521 SDL_memcpy(dst + vp, src, 0x10000 - vp);
522 page++;
523 vga_setpage(page);
524 SDL_memcpy(dst, src + 0x10000 - vp,
525 (vp + w) & 0xffff);
526 vp = (vp + pitch) & 0xffff;
527 src += pitch;
528 continue;
529 }
530 }
531 SDL_memcpy(dst + vp, src, w);
532 src += pitch;
533 vp += pitch;
534 }
535 }
536}
537
538int SVGA_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
539{
540 int i;
541
542 for(i = 0; i < ncolors; i++) {
543 vga_setpalette(firstcolor + i,
544 colors[i].r>>2,
545 colors[i].g>>2,
546 colors[i].b>>2);
547 }
548 return(1);
549}
550
551/* Note: If we are terminated, this could be called in the middle of
552 another SDL video routine -- notably UpdateRects.
553*/
554void SVGA_VideoQuit(_THIS)
555{
556 int i, j;
557
558 /* Reset the console video mode */
559 if ( this->screen && (this->screen->w && this->screen->h) ) {
560 vga_setmode(TEXT);
561 }
562 keyboard_close();
563
564 /* Free video mode lists */
565 for ( i=0; i<NUM_MODELISTS; ++i ) {
566 if ( SDL_modelist[i] != NULL ) {
567 for ( j=0; SDL_modelist[i][j]; ++j )
568 SDL_free(SDL_modelist[i][j]);
569 SDL_free(SDL_modelist[i]);
570 SDL_modelist[i] = NULL;
571 }
572 if ( SDL_vgamode[i] != NULL ) {
573 SDL_free(SDL_vgamode[i]);
574 SDL_vgamode[i] = NULL;
575 }
576 }
577 if ( this->screen ) {
578 if ( banked && this->screen->pixels ) {
579 SDL_free(this->screen->pixels);
580 }
581 this->screen->pixels = NULL;
582 }
583}
584
diff --git a/apps/plugins/sdl/src/video/svga/SDL_svgavideo.h b/apps/plugins/sdl/src/video/svga/SDL_svgavideo.h
deleted file mode 100644
index 7fb86cbbbe..0000000000
--- a/apps/plugins/sdl/src/video/svga/SDL_svgavideo.h
+++ /dev/null
@@ -1,58 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_svgavideo_h
25#define _SDL_svgavideo_h
26
27#include "SDL_mouse.h"
28#include "../SDL_sysvideo.h"
29
30/* Hidden "this" pointer for the video functions */
31#define _THIS SDL_VideoDevice *this
32
33/* Private display data */
34struct SDL_PrivateVideoData {
35#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
36 int SDL_nummodes[NUM_MODELISTS];
37 SDL_Rect **SDL_modelist[NUM_MODELISTS];
38 int *SDL_vgamode[NUM_MODELISTS];
39
40 /* information for double-buffering */
41 int flip_page;
42 int flip_offset[2];
43 Uint8 *flip_address[2];
44
45 /* Set to 1 if we're in banked video mode */
46 int banked;
47};
48/* Old variable names */
49#define SDL_nummodes (this->hidden->SDL_nummodes)
50#define SDL_modelist (this->hidden->SDL_modelist)
51#define SDL_vgamode (this->hidden->SDL_vgamode)
52#define flip_page (this->hidden->flip_page)
53#define flip_offset (this->hidden->flip_offset)
54#define flip_address (this->hidden->flip_address)
55#define banked (this->hidden->banked)
56
57#endif /* _SDL_svgavideo_h */
58
diff --git a/apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocevents.cpp b/apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocevents.cpp
deleted file mode 100644
index 5ceed5fe3b..0000000000
--- a/apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocevents.cpp
+++ /dev/null
@@ -1,626 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_epocevents.cpp
25 Handle the event stream, converting Epoc events into SDL events
26
27 Epoc version by Hannu Viitala (hannu.j.viitala@mbnet.fi)
28*/
29
30
31#include <stdio.h>
32#undef NULL
33extern "C" {
34//#define DEBUG_TRACE_ENABLED
35#include "SDL_error.h"
36#include "SDL_video.h"
37#include "SDL_keysym.h"
38#include "SDL_keyboard.h"
39#include "SDL_events_c.h"
40#include "SDL_timer.h"
41}; /* extern "C" */
42
43#include "SDL_epocvideo.h"
44#include "SDL_epocevents_c.h"
45
46#include<linereader.h>
47#include<bautils.h>
48
49
50#include <hal.h>
51
52extern "C" {
53/* The translation tables from a console scancode to a SDL keysym */
54static SDLKey keymap[MAX_SCANCODE];
55static SDL_keysym *TranslateKey(_THIS, int scancode, SDL_keysym *keysym);
56void DisableKeyBlocking(_THIS);
57}; /* extern "C" */
58
59TBool isCursorVisible = EFalse;
60
61int EPOC_HandleWsEvent(_THIS, const TWsEvent& aWsEvent)
62{
63 int posted = 0;
64 SDL_keysym keysym;
65
66// SDL_TRACE1("hws %d", aWsEvent.Type());
67
68 switch (aWsEvent.Type())
69 {
70 case EEventPointer: /* Mouse pointer events */
71 {
72
73 const TPointerCursorMode mode = Private->EPOC_WsSession.PointerCursorMode();
74
75 if(mode == EPointerCursorNone)
76 {
77 return 0; //TODO: Find out why events are get despite of cursor should be off
78 }
79
80 const TPointerEvent* pointerEvent = aWsEvent.Pointer();
81 TPoint mousePos = pointerEvent->iPosition;
82
83 /*!! TODO Pointer do not yet work properly
84 //SDL_TRACE1("SDL: EPOC_HandleWsEvent, pointerEvent->iType=%d", pointerEvent->iType); //!!
85
86 if (Private->EPOC_ShrinkedHeight) {
87 mousePos.iY <<= 1; // Scale y coordinate to shrinked screen height
88 }
89 if (Private->EPOC_ShrinkedWidth) {
90 mousePos.iX <<= 1; // Scale x coordinate to shrinked screen width
91 }
92 */
93
94 posted += SDL_PrivateMouseMotion(0, 0, mousePos.iX, mousePos.iY); /* Absolute position on screen */
95
96 switch (pointerEvent->iType)
97 {
98 case TPointerEvent::EButton1Down:
99 posted += SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_LEFT, 0, 0);
100 break;
101 case TPointerEvent::EButton1Up:
102 posted += SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_LEFT, 0, 0);
103 break;
104 case TPointerEvent::EButton2Down:
105 posted += SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_RIGHT, 0, 0);
106 break;
107 case TPointerEvent::EButton2Up:
108 posted += SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_RIGHT, 0, 0);
109 break;
110 case TPointerEvent::EButton3Down:
111 posted += SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_MIDDLE, 0, 0);
112 break;
113 case TPointerEvent::EButton3Up:
114 posted += SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_MIDDLE, 0, 0);
115 break;
116 } // switch
117 break;
118 }
119
120 case EEventKeyDown: /* Key events */
121 {
122#ifdef SYMBIAN_CRYSTAL
123 // special case: 9300/9500 rocker down, simulate left mouse button
124 if (aWsEvent.Key()->iScanCode == EStdKeyDeviceA)
125 {
126 const TPointerCursorMode mode = Private->EPOC_WsSession.PointerCursorMode();
127 if(mode != EPointerCursorNone)
128 posted += SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_LEFT, 0, 0);
129 }
130#endif
131 (void*)TranslateKey(_this, aWsEvent.Key()->iScanCode, &keysym);
132
133#ifndef DISABLE_JOYSTICK
134 /* Special handling */
135 switch((int)keysym.sym) {
136 case SDLK_CAPSLOCK:
137 if (!isCursorVisible) {
138 /* Enable virtual cursor */
139 HAL::Set(HAL::EMouseState, HAL::EMouseState_Visible);
140 }
141 else {
142 /* Disable virtual cursor */
143 HAL::Set(HAL::EMouseState, HAL::EMouseState_Invisible);
144 }
145 isCursorVisible = !isCursorVisible;
146 break;
147 }
148#endif
149 posted += SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
150 break;
151 }
152
153 case EEventKeyUp: /* Key events */
154 {
155#ifdef SYMBIAN_CRYSTAL
156 // special case: 9300/9500 rocker up, simulate left mouse button
157 if (aWsEvent.Key()->iScanCode == EStdKeyDeviceA)
158 {
159 posted += SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_LEFT, 0, 0);
160 }
161#endif
162 posted += SDL_PrivateKeyboard(SDL_RELEASED, TranslateKey(_this, aWsEvent.Key()->iScanCode, &keysym));
163 break;
164 }
165
166 case EEventFocusGained: /* SDL window got focus */
167 {
168 Private->EPOC_IsWindowFocused = ETrue;
169 posted += SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS);
170 /* Draw window background and screen buffer */
171 DisableKeyBlocking(_this); //Markus: guess why:-)
172
173 RedrawWindowL(_this);
174 break;
175 }
176
177 case EEventFocusLost: /* SDL window lost focus */
178 {
179/*
180 CFbsBitmap* bmp = new (ELeave) CFbsBitmap();
181 bmp->Create(Private->EPOC_ScreenSize, Private->EPOC_DisplayMode);
182 Private->EPOC_WsScreen->CopyScreenToBitmap(bmp);
183 Private->EPOC_WindowGc->Activate(Private->EPOC_WsWindow);
184 Private->EPOC_WsWindow.BeginRedraw(TRect(Private->EPOC_WsWindow.Size()));
185 Private->EPOC_WindowGc->BitBlt(TPoint(0, 0), bmp);
186 Private->EPOC_WsWindow.EndRedraw();
187 Private->EPOC_WindowGc->Deactivate();
188 bmp->Save(_L("C:\\scr.mbm"));
189 delete bmp;
190*/
191
192 Private->EPOC_IsWindowFocused = EFalse;
193
194 posted += SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS);
195
196 RWsSession s;
197 s.Connect();
198 RWindowGroup g(s);
199 g.Construct(TUint32(&g), EFalse);
200 g.EnableReceiptOfFocus(EFalse);
201 RWindow w(s);
202 w.Construct(g, TUint32(&w));
203 w.SetExtent(TPoint(0, 0), Private->EPOC_WsWindow.Size());
204 w.SetOrdinalPosition(0);
205 w.Activate();
206 w.Close();
207 g.Close();
208 s.Close();
209
210/*
211 Private->EPOC_WsSession.SetWindowGroupOrdinalPosition(Private->EPOC_WsWindowGroupID, -1);
212
213
214 SDL_Delay(500);
215 TInt focus = -1;
216 while(focus < 0)
217 {
218 const TInt curr = Private->EPOC_WsSession.GetFocusWindowGroup();
219 if(curr != Private->EPOC_WsWindowGroupID)
220 focus = curr;
221 else
222 SDL_Delay(500);
223 }
224
225 if(1 < Private->EPOC_WsSession.GetWindowGroupOrdinalPriority(Private->EPOC_WsWindowGroupID))
226 {
227 Private->EPOC_WsSession.SetWindowGroupOrdinalPosition(focus, -1);
228 SDL_Delay(500);
229 Private->EPOC_WsSession.SetWindowGroupOrdinalPosition(focus, 0);
230 }
231*/
232 /*//and the request redraw
233 TRawEvent redrawEvent;
234 redrawEvent.Set(TRawEvent::ERedraw);
235 Private->EPOC_WsSession.SimulateRawEvent(redrawEvent);
236 Private->EPOC_WsSession.Flush();*/
237#if 0
238 //!! Not used
239 // Wait and eat events until focus is gained again
240 while (ETrue) {
241 Private->EPOC_WsSession.EventReady(&Private->EPOC_WsEventStatus);
242 User::WaitForRequest(Private->EPOC_WsEventStatus);
243 Private->EPOC_WsSession.GetEvent(Private->EPOC_WsEvent);
244 TInt eventType = Private->EPOC_WsEvent.Type();
245 Private->EPOC_WsEventStatus = KRequestPending;
246 //Private->EPOC_WsSession.EventReady(&Private->EPOC_WsEventStatus);
247 if (eventType == EEventFocusGained) {
248 RedrawWindowL(_this);
249 break;
250 }
251 }
252#endif
253 break;
254 }
255
256 case EEventModifiersChanged:
257 {
258 TModifiersChangedEvent* modEvent = aWsEvent.ModifiersChanged();
259 TUint modstate = KMOD_NONE;
260 if (modEvent->iModifiers == EModifierLeftShift)
261 modstate |= KMOD_LSHIFT;
262 if (modEvent->iModifiers == EModifierRightShift)
263 modstate |= KMOD_RSHIFT;
264 if (modEvent->iModifiers == EModifierLeftCtrl)
265 modstate |= KMOD_LCTRL;
266 if (modEvent->iModifiers == EModifierRightCtrl)
267 modstate |= KMOD_RCTRL;
268 if (modEvent->iModifiers == EModifierLeftAlt)
269 modstate |= KMOD_LALT;
270 if (modEvent->iModifiers == EModifierRightAlt)
271 modstate |= KMOD_RALT;
272 if (modEvent->iModifiers == EModifierLeftFunc)
273 modstate |= KMOD_LMETA;
274 if (modEvent->iModifiers == EModifierRightFunc)
275 modstate |= KMOD_RMETA;
276 if (modEvent->iModifiers == EModifierCapsLock)
277 modstate |= KMOD_CAPS;
278 SDL_SetModState(STATIC_CAST(SDLMod,(modstate | KMOD_LSHIFT)));
279 break;
280 }
281 default:
282 break;
283 }
284
285 return posted;
286}
287
288extern "C" {
289
290void EPOC_PumpEvents(_THIS)
291{
292 int posted = 0; // !! Do we need this?
293 //Private->EPOC_WsSession.EventReady(&Private->EPOC_WsEventStatus);
294 while (Private->EPOC_WsEventStatus != KRequestPending) {
295
296 Private->EPOC_WsSession.GetEvent(Private->EPOC_WsEvent);
297 posted = EPOC_HandleWsEvent(_this, Private->EPOC_WsEvent);
298 Private->EPOC_WsEventStatus = KRequestPending;
299 Private->EPOC_WsSession.EventReady(&Private->EPOC_WsEventStatus);
300 }
301}
302
303
304_LIT(KMapFileName, "C:\\sdl_info\\sdlkeymap.cfg");
305LOCAL_C void ReadL(RFs& aFs, RArray<TInt>& aArray)
306 {
307 TInt drive = -1;
308 TFileName name(KMapFileName);
309 for(TInt i = 'z'; drive < 0 && i >= 'a'; i--)
310 {
311 name[0] = (TUint16)i;
312 if(BaflUtils::FileExists(aFs, name))
313 drive = i;
314 }
315 if(drive < 0)
316 return;
317 CLineReader* reader = CLineReader::NewLC(aFs, name);
318 while(reader->NextL())
319 {
320 TPtrC ln = reader->Current();
321 TLex line(ln);
322 TInt n = 0;
323 for(;;)
324 {
325 const TPtrC token = line.NextToken();
326 if(token.Length() == 0)
327 break;
328 if((n & 1) != 0)
329 {
330 TInt value;
331 TLex lex(token);
332 User::LeaveIfError(lex.Val(value));
333 User::LeaveIfError(aArray.Append(value));
334 }
335 n++;
336 }
337 }
338 CleanupStack::PopAndDestroy();
339 }
340
341
342void EPOC_InitOSKeymap(_THIS)
343{
344 int i;
345
346 /* Initialize the key translation table */
347 for ( i=0; i<SDL_TABLESIZE(keymap); ++i )
348 keymap[i] = SDLK_UNKNOWN;
349
350
351 /* Numbers */
352 for ( i = 0; i<32; ++i ){
353 keymap[' ' + i] = (SDLKey)(SDLK_SPACE+i);
354 }
355 /* e.g. Alphabet keys */
356 for ( i = 0; i<32; ++i ){
357 keymap['A' + i] = (SDLKey)(SDLK_a+i);
358 }
359
360 keymap[EStdKeyBackspace] = SDLK_BACKSPACE;
361 keymap[EStdKeyTab] = SDLK_TAB;
362 keymap[EStdKeyEnter] = SDLK_RETURN;
363 keymap[EStdKeyEscape] = SDLK_ESCAPE;
364 keymap[EStdKeySpace] = SDLK_SPACE;
365 keymap[EStdKeyPause] = SDLK_PAUSE;
366 keymap[EStdKeyHome] = SDLK_HOME;
367 keymap[EStdKeyEnd] = SDLK_END;
368 keymap[EStdKeyPageUp] = SDLK_PAGEUP;
369 keymap[EStdKeyPageDown] = SDLK_PAGEDOWN;
370 keymap[EStdKeyDelete] = SDLK_DELETE;
371 keymap[EStdKeyUpArrow] = SDLK_UP;
372 keymap[EStdKeyDownArrow] = SDLK_DOWN;
373 keymap[EStdKeyLeftArrow] = SDLK_LEFT;
374 keymap[EStdKeyRightArrow] = SDLK_RIGHT;
375 keymap[EStdKeyCapsLock] = SDLK_CAPSLOCK;
376 keymap[EStdKeyLeftShift] = SDLK_LSHIFT;
377 keymap[EStdKeyRightShift] = SDLK_RSHIFT;
378 keymap[EStdKeyLeftAlt] = SDLK_LALT;
379 keymap[EStdKeyRightAlt] = SDLK_RALT;
380 keymap[EStdKeyLeftCtrl] = SDLK_LCTRL;
381 keymap[EStdKeyRightCtrl] = SDLK_RCTRL;
382 keymap[EStdKeyLeftFunc] = SDLK_LMETA;
383 keymap[EStdKeyRightFunc] = SDLK_RMETA;
384 keymap[EStdKeyInsert] = SDLK_INSERT;
385 keymap[EStdKeyComma] = SDLK_COMMA;
386 keymap[EStdKeyFullStop] = SDLK_PERIOD;
387 keymap[EStdKeyForwardSlash] = SDLK_SLASH;
388 keymap[EStdKeyBackSlash] = SDLK_BACKSLASH;
389 keymap[EStdKeySemiColon] = SDLK_SEMICOLON;
390 keymap[EStdKeySingleQuote] = SDLK_QUOTE;
391 keymap[EStdKeyHash] = SDLK_HASH;
392 keymap[EStdKeySquareBracketLeft] = SDLK_LEFTBRACKET;
393 keymap[EStdKeySquareBracketRight] = SDLK_RIGHTBRACKET;
394 keymap[EStdKeyMinus] = SDLK_MINUS;
395 keymap[EStdKeyEquals] = SDLK_EQUALS;
396
397 keymap[EStdKeyF1] = SDLK_F1; /* chr + q */
398 keymap[EStdKeyF2] = SDLK_F2; /* chr + w */
399 keymap[EStdKeyF3] = SDLK_F3; /* chr + e */
400 keymap[EStdKeyF4] = SDLK_F4; /* chr + r */
401 keymap[EStdKeyF5] = SDLK_F5; /* chr + t */
402 keymap[EStdKeyF6] = SDLK_F6; /* chr + y */
403 keymap[EStdKeyF7] = SDLK_F7; /* chr + i */
404 keymap[EStdKeyF8] = SDLK_F8; /* chr + o */
405
406 keymap[EStdKeyF9] = SDLK_F9; /* chr + a */
407 keymap[EStdKeyF10] = SDLK_F10; /* chr + s */
408 keymap[EStdKeyF11] = SDLK_F11; /* chr + d */
409 keymap[EStdKeyF12] = SDLK_F12; /* chr + f */
410
411 #ifndef SYMBIAN_CRYSTAL
412 //!!7650 additions
413 #ifdef __WINS__
414 keymap[EStdKeyXXX] = SDLK_RETURN; /* "fire" key */
415 #else
416 keymap[EStdKeyDevice3] = SDLK_RETURN; /* "fire" key */
417 #endif
418 keymap[EStdKeyNkpAsterisk] = SDLK_ASTERISK;
419 keymap[EStdKeyYes] = SDLK_HOME; /* "call" key */
420 keymap[EStdKeyNo] = SDLK_END; /* "end call" key */
421 keymap[EStdKeyDevice0] = SDLK_SPACE; /* right menu key */
422 keymap[EStdKeyDevice1] = SDLK_ESCAPE; /* left menu key */
423 keymap[EStdKeyDevice2] = SDLK_POWER; /* power key */
424 #endif
425
426 #ifdef SYMBIAN_CRYSTAL
427 keymap[EStdKeyMenu] = SDLK_ESCAPE; // menu key
428 keymap[EStdKeyDevice6] = SDLK_LEFT; // Rocker (joystick) left
429 keymap[EStdKeyDevice7] = SDLK_RIGHT; // Rocker (joystick) right
430 keymap[EStdKeyDevice8] = SDLK_UP; // Rocker (joystick) up
431 keymap[EStdKeyDevice9] = SDLK_DOWN; // Rocker (joystick) down
432 keymap[EStdKeyLeftFunc] = SDLK_LALT; //chr?
433 keymap[EStdKeyRightFunc] = SDLK_RALT;
434 keymap[EStdKeyDeviceA] = SDLK_RETURN; /* "fire" key */
435#endif
436
437 ///////////////////////////////////////////////////////////
438
439 RFs fs;
440 if(KErrNone == fs.Connect())
441 {
442 RArray<TInt> array;
443 TRAPD(err, ReadL(fs, array));
444 if(err == KErrNone && array.Count() > 0)
445 {
446
447 SDLKey temp[MAX_SCANCODE];
448 Mem::Copy(temp, keymap, MAX_SCANCODE * sizeof(SDLKey));
449
450 for(TInt k = 0; k < array.Count(); k+= 2)
451 {
452 const TInt oldval = array[k];
453 const TInt newval = array[k + 1];
454 if(oldval >= 0 && oldval < MAX_SCANCODE && newval >= 0 && newval < MAX_SCANCODE)
455 {
456 keymap[oldval] = temp[newval];
457 }
458 }
459 }
460 array.Close();
461 }
462
463 fs.Close();
464 ///////////////////////////////////////////////////////////
465
466 /* !!TODO
467 EStdKeyNumLock=0x1b,
468 EStdKeyScrollLock=0x1c,
469
470 EStdKeyNkpForwardSlash=0x84,
471 EStdKeyNkpAsterisk=0x85,
472 EStdKeyNkpMinus=0x86,
473 EStdKeyNkpPlus=0x87,
474 EStdKeyNkpEnter=0x88,
475 EStdKeyNkp1=0x89,
476 EStdKeyNkp2=0x8a,
477 EStdKeyNkp3=0x8b,
478 EStdKeyNkp4=0x8c,
479 EStdKeyNkp5=0x8d,
480 EStdKeyNkp6=0x8e,
481 EStdKeyNkp7=0x8f,
482 EStdKeyNkp8=0x90,
483 EStdKeyNkp9=0x91,
484 EStdKeyNkp0=0x92,
485 EStdKeyNkpFullStop=0x93,
486 EStdKeyMenu=0x94,
487 EStdKeyBacklightOn=0x95,
488 EStdKeyBacklightOff=0x96,
489 EStdKeyBacklightToggle=0x97,
490 EStdKeyIncContrast=0x98,
491 EStdKeyDecContrast=0x99,
492 EStdKeySliderDown=0x9a,
493 EStdKeySliderUp=0x9b,
494 EStdKeyDictaphonePlay=0x9c,
495 EStdKeyDictaphoneStop=0x9d,
496 EStdKeyDictaphoneRecord=0x9e,
497 EStdKeyHelp=0x9f,
498 EStdKeyOff=0xa0,
499 EStdKeyDial=0xa1,
500 EStdKeyIncVolume=0xa2,
501 EStdKeyDecVolume=0xa3,
502 EStdKeyDevice0=0xa4,
503 EStdKeyDevice1=0xa5,
504 EStdKeyDevice2=0xa6,
505 EStdKeyDevice3=0xa7,
506 EStdKeyDevice4=0xa8,
507 EStdKeyDevice5=0xa9,
508 EStdKeyDevice6=0xaa,
509 EStdKeyDevice7=0xab,
510 EStdKeyDevice8=0xac,
511 EStdKeyDevice9=0xad,
512 EStdKeyDeviceA=0xae,
513 EStdKeyDeviceB=0xaf,
514 EStdKeyDeviceC=0xb0,
515 EStdKeyDeviceD=0xb1,
516 EStdKeyDeviceE=0xb2,
517 EStdKeyDeviceF=0xb3,
518 EStdKeyApplication0=0xb4,
519 EStdKeyApplication1=0xb5,
520 EStdKeyApplication2=0xb6,
521 EStdKeyApplication3=0xb7,
522 EStdKeyApplication4=0xb8,
523 EStdKeyApplication5=0xb9,
524 EStdKeyApplication6=0xba,
525 EStdKeyApplication7=0xbb,
526 EStdKeyApplication8=0xbc,
527 EStdKeyApplication9=0xbd,
528 EStdKeyApplicationA=0xbe,
529 EStdKeyApplicationB=0xbf,
530 EStdKeyApplicationC=0xc0,
531 EStdKeyApplicationD=0xc1,
532 EStdKeyApplicationE=0xc2,
533 EStdKeyApplicationF=0xc3,
534 EStdKeyYes=0xc4,
535 EStdKeyNo=0xc5,
536 EStdKeyIncBrightness=0xc6,
537 EStdKeyDecBrightness=0xc7,
538 EStdKeyCaseOpen=0xc8,
539 EStdKeyCaseClose=0xc9
540 */
541
542}
543
544
545
546static SDL_keysym *TranslateKey(_THIS, int scancode, SDL_keysym *keysym)
547{
548// char debug[256];
549 //SDL_TRACE1("SDL: TranslateKey, scancode=%d", scancode); //!!
550
551 /* Set the keysym information */
552
553 keysym->scancode = scancode;
554
555 if ((scancode >= MAX_SCANCODE) &&
556 ((scancode - ENonCharacterKeyBase + 0x0081) >= MAX_SCANCODE)) {
557 SDL_SetError("Too big scancode");
558 keysym->scancode = SDLK_UNKNOWN;
559 keysym->mod = KMOD_NONE;
560 return keysym;
561 }
562
563 keysym->mod = SDL_GetModState();
564
565 /* Handle function keys: F1, F2, F3 ... */
566 if (keysym->mod & KMOD_META) {
567 if (scancode >= 'A' && scancode < ('A' + 24)) { /* first 32 alphabet keys */
568 switch(scancode) {
569 case 'Q': scancode = EStdKeyF1; break;
570 case 'W': scancode = EStdKeyF2; break;
571 case 'E': scancode = EStdKeyF3; break;
572 case 'R': scancode = EStdKeyF4; break;
573 case 'T': scancode = EStdKeyF5; break;
574 case 'Y': scancode = EStdKeyF6; break;
575 case 'U': scancode = EStdKeyF7; break;
576 case 'I': scancode = EStdKeyF8; break;
577 case 'A': scancode = EStdKeyF9; break;
578 case 'S': scancode = EStdKeyF10; break;
579 case 'D': scancode = EStdKeyF11; break;
580 case 'F': scancode = EStdKeyF12; break;
581 }
582 keysym->sym = keymap[scancode];
583 }
584 }
585
586 if (scancode >= ENonCharacterKeyBase) {
587 // Non character keys
588 keysym->sym = keymap[scancode -
589 ENonCharacterKeyBase + 0x0081]; // !!hard coded
590 } else {
591 keysym->sym = keymap[scancode];
592 }
593
594 /* Remap the arrow keys if the device is rotated */
595 if (Private->EPOC_ScreenOrientation == CFbsBitGc::EGraphicsOrientationRotated270) {
596 switch(keysym->sym) {
597 case SDLK_UP: keysym->sym = SDLK_LEFT; break;
598 case SDLK_DOWN: keysym->sym = SDLK_RIGHT; break;
599 case SDLK_LEFT: keysym->sym = SDLK_DOWN; break;
600 case SDLK_RIGHT:keysym->sym = SDLK_UP; break;
601 }
602 }
603
604 /* If UNICODE is on, get the UNICODE value for the key */
605 keysym->unicode = 0;
606
607#if 0 // !!TODO:unicode
608
609 if ( SDL_TranslateUNICODE )
610 {
611 /* Populate the unicode field with the ASCII value */
612 keysym->unicode = scancode;
613 }
614#endif
615
616 //!!
617 //sprintf(debug, "SDL: TranslateKey: keysym->scancode=%d, keysym->sym=%d, keysym->mod=%d",
618 // keysym->scancode, keysym->sym, keysym->mod);
619 //SDL_TRACE(debug); //!!
620
621 return(keysym);
622}
623
624}; /* extern "C" */
625
626
diff --git a/apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocvideo.cpp b/apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocvideo.cpp
deleted file mode 100644
index 06874d546c..0000000000
--- a/apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocvideo.cpp
+++ /dev/null
@@ -1,1356 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_epocvideo.cpp
25 Epoc based SDL video driver implementation
26
27 Thanks to Peter van Sebille, the author of EMame. It is a great example of
28 low level graphics coding in Epoc.
29
30 Epoc version by Hannu Viitala (hannu.j.viitala@mbnet.fi)
31 Assembler routines by Kimmo Kinnunen
32*/
33
34
35
36#include <stdlib.h>
37#include <stdio.h>
38#include <string.h>
39
40extern "C" {
41#include "SDL_error.h"
42#include "SDL_timer.h"
43#include "SDL_video.h"
44#undef NULL
45#include "SDL_pixels_c.h"
46#include "SDL.h"
47};
48
49#include "SDL_epocvideo.h"
50#include "SDL_epocevents_c.h"
51
52#include "sdl_epocruntime.h"
53
54#include <hal.h>
55#include <coedef.h>
56#include <flogger.h>
57
58#ifdef SYMBIAN_QUARTZ
59SDL_VideoDevice* _thisDevice;
60#endif
61
62_LIT(KLibName, "SDL");
63
64/* For debugging */
65
66//if old SOS, from 7.x this is public!
67class CLockable : public CFbsBitmap
68 {
69 public:
70 static CLockable* Lockable(CFbsBitmap* aBmp) {return static_cast<CLockable*>(aBmp);}
71 void Lock() {LockHeap();}
72 void Unlock() {UnlockHeap();}
73 };
74#define LockHeap(x) CLockable::Lockable(x)->Lock()
75#define UnlockHeap(x) CLockable::Lockable(x)->Unlock()
76
77void RDebug_Print_b(char* error_str, void* param)
78 {
79 TBuf8<128> error8((TUint8*)error_str);
80 TBuf<128> error;
81 error.Copy(error8);
82
83#ifndef TRACE_TO_FILE
84 if (param) //!! Do not work if the parameter is really 0!!
85 RDebug::Print(error, param);
86 else
87 RDebug::Print(error);
88#else
89 if (param) //!! Do not work if the parameter is really 0!!
90 RFileLogger::WriteFormat(KLibName, _L("SDL.txt"), EFileLoggingModeAppend, error, param);
91 else
92 RFileLogger::Write(KLibName, _L("SDL.txt"), EFileLoggingModeAppend, error);
93#endif
94
95 }
96
97extern "C" void RDebug_Print(char* error_str, void* param)
98 {
99 RDebug_Print_b(error_str, param);
100 }
101
102
103int Debug_AvailMem2()
104 {
105 //User::CompressAllHeaps();
106 TMemoryInfoV1Buf membuf;
107 User::LeaveIfError(UserHal::MemoryInfo(membuf));
108 TMemoryInfoV1 minfo = membuf();
109 return(minfo.iFreeRamInBytes);
110 }
111
112extern "C" int Debug_AvailMem()
113 {
114 return(Debug_AvailMem2());
115 }
116
117
118extern "C" {
119
120/* Initialization/Query functions */
121
122static int EPOC_VideoInit(_THIS, SDL_PixelFormat *vformat);
123static SDL_Rect **EPOC_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
124static SDL_Surface *EPOC_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
125static int EPOC_SetColors(_THIS, int firstcolor, int ncolors,
126 SDL_Color *colors);
127static void EPOC_VideoQuit(_THIS);
128
129/* Hardware surface functions */
130
131static int EPOC_AllocHWSurface(_THIS, SDL_Surface *surface);
132static int EPOC_LockHWSurface(_THIS, SDL_Surface *surface);
133static int EPOC_FlipHWSurface(_THIS, SDL_Surface *surface);
134static void EPOC_UnlockHWSurface(_THIS, SDL_Surface *surface);
135static void EPOC_FreeHWSurface(_THIS, SDL_Surface *surface);
136static void EPOC_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
137
138static int EPOC_Available(void);
139static SDL_VideoDevice *EPOC_CreateDevice(int devindex);
140
141void DrawBackground(_THIS);
142void DirectDraw(_THIS, int numrects, SDL_Rect *rects, TUint16* screenBuffer);
143void DirectDrawRotated(_THIS, int numrects, SDL_Rect *rects, TUint16* screenBuffer);
144
145/* Mouse functions */
146
147static WMcursor *EPOC_CreateWMCursor(_THIS, Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
148static void EPOC_FreeWMCursor(_THIS, WMcursor *cursor);
149static int EPOC_ShowWMCursor(_THIS, WMcursor *cursor);
150
151
152
153/* !!For 12 bit screen HW. Table for fast conversion from 8 bit to 12 bit */
154// TUint16 is enough, but using TUint32 so we can use better instruction selection on ARMI
155static TUint32 EPOC_HWPalette_256_to_Screen[256];
156
157VideoBootStrap EPOC_bootstrap = {
158 "epoc", "EPOC system",
159 EPOC_Available, EPOC_CreateDevice
160};
161
162const TUint32 WindowClientHandle = 9210; //!! const
163
164/* Epoc video driver bootstrap functions */
165
166static int EPOC_Available(void)
167{
168 return 1; /* Always available */
169}
170
171static void EPOC_DeleteDevice(SDL_VideoDevice *device)
172{
173 free(device->hidden);
174 free(device);
175}
176
177static SDL_VideoDevice *EPOC_CreateDevice(int /*devindex*/)
178{
179 SDL_VideoDevice *device;
180
181 SDL_TRACE("SDL:EPOC_CreateDevice");
182
183 /* Allocate all variables that we free on delete */
184 device = (SDL_VideoDevice *)malloc(sizeof(SDL_VideoDevice));
185 if ( device ) {
186 memset(device, 0, (sizeof *device));
187 device->hidden = (struct SDL_PrivateVideoData *)
188 malloc((sizeof *device->hidden));
189 }
190 if ( (device == NULL) || (device->hidden == NULL) ) {
191 SDL_OutOfMemory();
192 if ( device ) {
193 free(device);
194 }
195 return(0);
196 }
197 memset(device->hidden, 0, (sizeof *device->hidden));
198
199 /* Set the function pointers */
200 device->VideoInit = EPOC_VideoInit;
201 device->ListModes = EPOC_ListModes;
202 device->SetVideoMode = EPOC_SetVideoMode;
203 device->SetColors = EPOC_SetColors;
204 device->UpdateRects = NULL;
205 device->VideoQuit = EPOC_VideoQuit;
206 device->AllocHWSurface = EPOC_AllocHWSurface;
207 device->CheckHWBlit = NULL;
208 device->FillHWRect = NULL;
209 device->SetHWColorKey = NULL;
210 device->SetHWAlpha = NULL;
211 device->LockHWSurface = EPOC_LockHWSurface;
212 device->UnlockHWSurface = EPOC_UnlockHWSurface;
213 device->FlipHWSurface = EPOC_FlipHWSurface;
214 device->FreeHWSurface = EPOC_FreeHWSurface;
215 device->SetIcon = NULL;
216 device->SetCaption = NULL;
217 device->GetWMInfo = NULL;
218 device->FreeWMCursor = EPOC_FreeWMCursor;
219 device->CreateWMCursor = EPOC_CreateWMCursor;
220 device->ShowWMCursor = EPOC_ShowWMCursor;
221 device->WarpWMCursor = NULL;
222 device->InitOSKeymap = EPOC_InitOSKeymap;
223 device->PumpEvents = EPOC_PumpEvents;
224 device->free = EPOC_DeleteDevice;
225
226 return device;
227}
228
229
230int GetBpp(TDisplayMode displaymode)
231{
232 /*TInt numColors = TDisplayModeUtils::NumDisplayModeColors(displaymode);
233 TInt bitsPerPixel = 1;
234 for (TInt32 i = 2; i < numColors; i <<= 1, bitsPerPixel++);
235 return bitsPerPixel;*/
236 return TDisplayModeUtils::NumDisplayModeBitsPerPixel(displaymode);
237}
238
239
240void DisableKeyBlocking(_THIS)
241 {
242 // Disable key blocking
243 TRawEvent event;
244 event.Set((TRawEvent::TType)/*EDisableKeyBlock*/51); // !!EDisableKeyBlock not found in epoc32\include!
245 Private->EPOC_WsSession.SimulateRawEvent(event);
246 }
247
248void ConstructWindowL(_THIS)
249{
250 TInt error;
251
252 SDL_TRACE("SDL:ConstructWindowL");
253 error = Private->EPOC_WsSession.Connect();
254 User::LeaveIfError(error);
255 Private->EPOC_WsScreen=new(ELeave) CWsScreenDevice(Private->EPOC_WsSession);
256 User::LeaveIfError(Private->EPOC_WsScreen->Construct());
257 User::LeaveIfError(Private->EPOC_WsScreen->CreateContext(Private->EPOC_WindowGc));
258
259 Private->EPOC_WsWindowGroup=RWindowGroup(Private->EPOC_WsSession);
260 User::LeaveIfError(Private->EPOC_WsWindowGroup.Construct(WindowClientHandle));
261 Private->EPOC_WsWindowGroup.SetOrdinalPosition(0);
262
263 // Set window group name (the same as process name)) !!Gives always "EPOC" in WINS
264 RProcess thisProcess;
265 TParse exeName;
266 exeName.Set(thisProcess.FileName(), NULL, NULL);
267 TBuf<32> winGroupName;
268 winGroupName.Append(0);
269 winGroupName.Append(0);
270 winGroupName.Append(0);// uid
271 winGroupName.Append(0);
272 winGroupName.Append(exeName.Name()); // caption
273 winGroupName.Append(0);
274 winGroupName.Append(0); //doc name
275 Private->EPOC_WsWindowGroup.SetName(winGroupName);
276
277 Private->EPOC_WsWindow=RWindow(Private->EPOC_WsSession);
278 // Markus, it was:
279 // User::LeaveIfError(Private->EPOC_WsWindow.Construct(Private->EPOC_WsWindowGroup,WindowClientHandle ));
280 // but SOS 7.0s debug does not accept same window handle twice
281 User::LeaveIfError(Private->EPOC_WsWindow.Construct(Private->EPOC_WsWindowGroup,WindowClientHandle - 1));
282 Private->EPOC_WsWindow.SetBackgroundColor(KRgbWhite);
283 Private->EPOC_WsWindow.Activate();
284 Private->EPOC_WsWindow.SetSize(Private->EPOC_WsScreen->SizeInPixels());
285 Private->EPOC_WsWindow.SetVisible(ETrue);
286
287 Private->EPOC_WsWindowGroupID = Private->EPOC_WsWindowGroup.Identifier();
288 Private->EPOC_IsWindowFocused = EFalse;
289
290 DisableKeyBlocking(_this); //disable key blocking
291}
292
293int EPOC_VideoInit(_THIS, SDL_PixelFormat *vformat)
294{
295 // !!TODO:handle leave functions!
296
297 int i;
298
299 SDL_TRACE("SDL:EPOC_VideoInit");
300
301 /* Initialize all variables that we clean on shutdown */
302
303 for ( i=0; i<SDL_NUMMODES; ++i ) {
304 Private->SDL_modelist[i] = (SDL_Rect *)malloc(sizeof(SDL_Rect));
305 Private->SDL_modelist[i]->x = Private->SDL_modelist[i]->y = 0;
306 }
307
308 /* Modes sorted largest to smallest */
309 Private->SDL_modelist[0]->w = 800; Private->SDL_modelist[0]->h = 250;
310 Private->SDL_modelist[1]->w = 640; Private->SDL_modelist[1]->h = 480;
311 Private->SDL_modelist[2]->w = 480; Private->SDL_modelist[2]->h = 600;
312 Private->SDL_modelist[3]->w = 640; Private->SDL_modelist[3]->h = 400;
313 Private->SDL_modelist[4]->w = 352; Private->SDL_modelist[4]->h = 416;
314 Private->SDL_modelist[5]->w = 416; Private->SDL_modelist[5]->h = 352;
315 Private->SDL_modelist[6]->w = 416; Private->SDL_modelist[6]->h = 312;
316 Private->SDL_modelist[7]->w = 352; Private->SDL_modelist[7]->h = 264;
317 Private->SDL_modelist[8]->w = 800; Private->SDL_modelist[8]->h = 240; //for doom all these..
318 Private->SDL_modelist[9]->w = 640; Private->SDL_modelist[9]->h = 240;
319 Private->SDL_modelist[10]->w = 480; Private->SDL_modelist[10]->h = 240;
320 Private->SDL_modelist[11]->w = 640; Private->SDL_modelist[11]->h = 240;
321 Private->SDL_modelist[12]->w = 352; Private->SDL_modelist[12]->h = 240;
322 Private->SDL_modelist[13]->w = 416; Private->SDL_modelist[13]->h = 240;
323 Private->SDL_modelist[14]->w = 416; Private->SDL_modelist[14]->h = 240;
324 Private->SDL_modelist[15]->w = 352; Private->SDL_modelist[15]->h = 240;
325 Private->SDL_modelist[16]->w = 640; Private->SDL_modelist[16]->h = 200;
326 Private->SDL_modelist[17]->w = 320; Private->SDL_modelist[17]->h = 240; //...for doom, currently engine renders no-higher windows :-(, propably should get fixed
327 Private->SDL_modelist[18]->w = 320; Private->SDL_modelist[18]->h = 200;
328 Private->SDL_modelist[19]->w = 256; Private->SDL_modelist[19]->h = 192;
329 Private->SDL_modelist[20]->w = 176; Private->SDL_modelist[20]->h = 208;
330 Private->SDL_modelist[21]->w = 208; Private->SDL_modelist[21]->h = 176; // Rotated
331 Private->SDL_modelist[22]->w = 160; Private->SDL_modelist[22]->h = 144;
332
333 Private->SDL_modelist[23]->w = 640; Private->SDL_modelist[2]->h = 200; //s80 some new modes
334 Private->SDL_modelist[24]->w = 640; Private->SDL_modelist[2]->h = 320; //s90 modes are added
335 Private->SDL_modelist[25]->w = 640; Private->SDL_modelist[2]->h = 240; //here
336 Private->SDL_modelist[26]->w = 640; Private->SDL_modelist[4]->h = 200; //now
337
338 Private->SDL_modelist[27] = NULL;
339
340 /* Construct Epoc window */
341
342 ConstructWindowL(_this);
343
344 /* Initialise Epoc frame buffer */
345
346 TDisplayMode displayMode = Private->EPOC_WsScreen->DisplayMode();
347
348#if !defined(__WINS__) && !defined(TEST_BM_DRAW)
349
350 TScreenInfoV01 screenInfo;
351 TPckg<TScreenInfoV01> sInfo(screenInfo);
352 UserSvr::ScreenInfo(sInfo);
353
354 Private->EPOC_ScreenSize = screenInfo.iScreenSize;
355 Private->EPOC_DisplayMode = displayMode;
356 Private->EPOC_HasFrameBuffer = screenInfo.iScreenAddressValid;
357 Private->EPOC_FrameBuffer = Private->EPOC_HasFrameBuffer ? (TUint8*) screenInfo.iScreenAddress : NULL;
358 Private->EPOC_BytesPerPixel = ((GetBpp(displayMode)-1) / 8) + 1;
359
360 Private->EPOC_BytesPerScanLine = screenInfo.iScreenSize.iWidth * Private->EPOC_BytesPerPixel;
361 Private->EPOC_BytesPerScreen = Private->EPOC_BytesPerScanLine * Private->EPOC_ScreenSize.iHeight;
362
363 SDL_TRACE1("Screen width %d", screenInfo.iScreenSize.iWidth);
364 SDL_TRACE1("Screen height %d", screenInfo.iScreenSize.iHeight);
365 SDL_TRACE1("Screen dmode %d", displayMode);
366 SDL_TRACE1("Screen valid %d", screenInfo.iScreenAddressValid);
367
368 SDL_TRACE1("bpp %d", Private->EPOC_BytesPerPixel);
369 SDL_TRACE1("bpsl %d", Private->EPOC_BytesPerScanLine);
370 SDL_TRACE1("bps %d", Private->EPOC_BytesPerScreen);
371
372
373 /* It seems that in SA1100 machines for 8bpp displays there is a 512 palette table at the
374 * beginning of the frame buffer. E.g. Series 7 and Netbook.
375 * In 12 bpp machines the table has 16 entries.
376 */
377 if (Private->EPOC_HasFrameBuffer && GetBpp(displayMode) == 8)
378 {
379 Private->EPOC_FrameBuffer += 512;
380 }
381 else
382 {
383 Private->EPOC_FrameBuffer += 32;
384 }
385 /*if (Private->EPOC_HasFrameBuffer && GetBpp(displayMode) == 12)
386 Private->EPOC_FrameBuffer += 16 * 2;
387 if (Private->EPOC_HasFrameBuffer && GetBpp(displayMode) == 16)
388 Private->EPOC_FrameBuffer += 16 * 2;
389 */
390#else /* defined __WINS__ */
391
392 /* Create bitmap, device and context for screen drawing */
393 Private->EPOC_ScreenSize = Private->EPOC_WsScreen->SizeInPixels();
394
395 Private->EPOC_Bitmap = new (ELeave) CWsBitmap(Private->EPOC_WsSession);
396 Private->EPOC_Bitmap->Create(Private->EPOC_ScreenSize, displayMode);
397
398 Private->EPOC_DisplayMode = displayMode;
399 Private->EPOC_HasFrameBuffer = ETrue;
400 Private->EPOC_FrameBuffer = NULL; /* Private->EPOC_Bitmap->DataAddress() can change any time */
401 Private->EPOC_BytesPerPixel = ((GetBpp(displayMode)-1) / 8) + 1;
402 Private->EPOC_BytesPerScanLine = Private->EPOC_WsScreen->SizeInPixels().iWidth * Private->EPOC_BytesPerPixel;
403
404#endif /* __WINS__ */
405
406#ifndef SYMBIAN_CRYSTAL
407 // Get draw device for updating the screen
408 TScreenInfoV01 screenInfo2;
409
410 Epoc_Runtime::GetScreenInfo(screenInfo2);
411
412 TRAPD(status, Private->EPOC_DrawDevice = CFbsDrawDevice::NewScreenDeviceL(screenInfo2, displayMode));
413 User::LeaveIfError(status);
414#endif
415
416 /* The "best" video format should be returned to caller. */
417
418 vformat->BitsPerPixel = /*!!GetBpp(displayMode) */ 8;
419 vformat->BytesPerPixel = /*!!Private->EPOC_BytesPerPixel*/ 1;
420
421 /* Activate events for me */
422
423 Private->EPOC_WsEventStatus = KRequestPending;
424 Private->EPOC_WsSession.EventReady(&Private->EPOC_WsEventStatus);
425
426 SDL_TRACE("SDL:WsEventStatus");
427 User::WaitForRequest(Private->EPOC_WsEventStatus); //Markus: I added this and ...
428
429 Private->EPOC_RedrawEventStatus = KRequestPending;
430 Private->EPOC_WsSession.RedrawReady(&Private->EPOC_RedrawEventStatus);
431
432 SDL_TRACE("SDL:RedrawEventStatus");
433 User::WaitForRequest(Private->EPOC_RedrawEventStatus); //...this, if not catches a stray event is risen
434 //if there are active objects used, or confucing
435 //actions with User::WaitForAnyRequest
436 Private->EPOC_WsWindow.PointerFilter(EPointerFilterDrag, 0);
437
438 Private->EPOC_ScreenOffset = TPoint(0, 0);
439
440#if defined(__WINS__) || defined(TEST_BM_DRAW)
441 LockHeap(Private->EPOC_Bitmap); // Lock bitmap heap
442#endif
443
444 SDL_TRACE("SDL:DrawBackground");
445 DrawBackground(_this); // Clear screen
446
447#if defined(__WINS__) || defined(TEST_BM_DRAW)
448 UnlockHeap(Private->EPOC_Bitmap); // Unlock bitmap heap
449#endif
450 //!! TODO: error handling
451 //if (ret != KErrNone)
452 // return(-1);
453 //else
454 return(0);
455}
456
457
458SDL_Rect **EPOC_ListModes(_THIS, SDL_PixelFormat *format, Uint32 /*flags*/)
459{
460 if (format->BitsPerPixel == 12 || format->BitsPerPixel == 8)
461 return Private->SDL_modelist;
462 return NULL;
463}
464
465int EPOC_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
466{
467 if ((firstcolor+ncolors) > 256)
468 return -1;
469// SDL_TRACE1("colors %d", (TDisplayModeUtils::NumDisplayModeColors(Private->EPOC_DisplayMode)));
470 if(TDisplayModeUtils::NumDisplayModeColors(Private->EPOC_DisplayMode) == 4096)
471 {
472 // Set 12 bit palette
473 for(int i = firstcolor; i < ncolors; i++)
474 {
475 // 4k value: 0000 rrrr gggg bbbb
476 TUint32 color4K = (colors[i].r & 0x0000f0) << 4;
477 color4K |= (colors[i].g & 0x0000f0);
478 color4K |= (colors[i].b & 0x0000f0) >> 4;
479 EPOC_HWPalette_256_to_Screen[i] = color4K;
480 }
481 }
482 else if(TDisplayModeUtils::NumDisplayModeColors(Private->EPOC_DisplayMode) == 65536)
483 {
484 for(int i = firstcolor; i < ncolors; i++)
485 {
486 // 64k-colour displays effectively support RGB values
487 // with 5 bits allocated to red, 6 to green and 5 to blue
488 // 64k value: rrrr rggg gggb bbbb
489 TUint32 color64K = (colors[i].r & 0x0000f8) << 8;
490 color64K |= (colors[i].g & 0x0000fc) << 3;
491 color64K |= (colors[i].b & 0x0000f8) >> 3;
492 EPOC_HWPalette_256_to_Screen[i] = color64K;
493 }
494 }
495 else if(TDisplayModeUtils::NumDisplayModeColors(Private->EPOC_DisplayMode) == 16777216)
496 {
497 for(int i = firstcolor; i < ncolors; i++)
498 {
499 // 16M-colour
500 //0000 0000 rrrr rrrr gggg gggg bbbb bbbb
501 TUint32 color16M = colors[i].r << 16;
502 color16M |= colors[i].g << 8;
503 color16M |= colors[i].b;
504 EPOC_HWPalette_256_to_Screen[i] = color16M;
505 }
506 }
507 else
508 {
509 return -2;
510 }
511 return(0);
512}
513
514
515SDL_Surface *EPOC_SetVideoMode(_THIS, SDL_Surface *current,
516 int width, int height, int bpp, Uint32 /*flags*/)
517{
518 SDL_TRACE("SDL:EPOC_SetVideoMode");
519 /* Check parameters */
520#ifdef SYMBIAN_CRYSTAL
521 if (! (bpp == 8 || bpp == 12 || bpp == 16) &&
522 (
523 (width == 640 && height == 200) ||
524 (width == 640 && height == 400) ||
525 (width == 640 && height == 480) ||
526 (width == 320 && height == 200) ||
527 (width == 320 && height == 240)
528 )) {
529 SDL_SetError("Requested video mode is not supported");
530 return NULL;
531 }
532#else // SYMBIAN_SERIES60
533 if (! (bpp == 8 || bpp == 12 || bpp == 16) &&
534 (
535 (width == 320 && height == 200) ||
536 (width == 320 && height == 240) ||
537 (width == 256 && height == 192) ||
538 (width == 176 && height == 208) ||
539 (width == 208 && height == 176) || // Rotated
540 (width == 160 && height == 144)
541 )) {
542 SDL_SetError("Requested video mode is not supported");
543 return NULL;
544 }
545#endif
546
547 if (current && current->pixels) {
548 free(current->pixels);
549 current->pixels = NULL;
550 }
551 if ( ! SDL_ReallocFormat(current, bpp, 0, 0, 0, 0) ) {
552 return(NULL);
553 }
554
555 /* Set up the new mode framebuffer */
556 if (bpp == 8)
557 current->flags = (SDL_FULLSCREEN|SDL_SWSURFACE|SDL_PREALLOC|SDL_HWPALETTE);
558 else // 12 bpp, 16 bpp
559 current->flags = (SDL_FULLSCREEN|SDL_SWSURFACE|SDL_PREALLOC);
560 current->w = width;
561 current->h = height;
562 int numBytesPerPixel = ((bpp-1)>>3) + 1;
563 current->pitch = numBytesPerPixel * width; // Number of bytes in scanline
564 current->pixels = malloc(width * height * numBytesPerPixel);
565 memset(current->pixels, 0, width * height * numBytesPerPixel);
566
567 /* Set the blit function */
568 _this->UpdateRects = EPOC_DirectUpdate;
569
570 /*
571 * Logic for getting suitable screen dimensions, offset, scaling and orientation
572 */
573
574 int w = current->w;
575 int h = current->h;
576
577 // Rotate, if the screen does not fit horizontally and it is landscape screen
578/*
579 if ((width>Private->EPOC_ScreenSize.iWidth) && (width>height)) {
580 Private->EPOC_ScreenOrientation = CFbsBitGc::EGraphicsOrientationRotated270;
581 w = current->h;
582 h = current->w;
583 }
584*/
585 // Get nearest stepwise scale values for width and height. The smallest supported scaled screen is 1/2.
586 TInt scaleValue = 0;
587 Private->EPOC_ScreenXScaleValue = 1;
588 Private->EPOC_ScreenYScaleValue = 1;
589 if (w > Private->EPOC_ScreenSize.iWidth) {
590 // Find the biggest scale value that result the width that fits in the screen HW
591 for (scaleValue = 2; scaleValue++;) {
592 TInt scaledWidth = (w * (scaleValue-1))/scaleValue;
593 if (scaledWidth > Private->EPOC_ScreenSize.iWidth)
594 break;
595 }
596 Private->EPOC_ScreenXScaleValue = Max(2, scaleValue - 1);
597 w = (w * (Private->EPOC_ScreenXScaleValue-1))/Private->EPOC_ScreenXScaleValue;
598 }
599 if (h > Private->EPOC_ScreenSize.iHeight) {
600 // Find the biggest scale value that result the height that fits in the screen HW
601 for (scaleValue = 2; scaleValue++;) {
602 TInt scaledHeight = (h * (scaleValue-1))/scaleValue;
603 if (scaledHeight > Private->EPOC_ScreenSize.iHeight)
604 break;
605 }
606 Private->EPOC_ScreenYScaleValue = Max(2, scaleValue - 1);
607 h = (h * (Private->EPOC_ScreenYScaleValue-1))/Private->EPOC_ScreenYScaleValue;
608 }
609
610 /* Centralize game window on device screen */
611 Private->EPOC_ScreenOffset.iX = (Private->EPOC_ScreenSize.iWidth - w) / 2;
612 if (Private->EPOC_ScreenOffset.iX < 0)
613 Private->EPOC_ScreenOffset.iX = 0;
614 Private->EPOC_ScreenOffset.iY = (Private->EPOC_ScreenSize.iHeight - h) / 2;
615 if (Private->EPOC_ScreenOffset.iY < 0)
616 Private->EPOC_ScreenOffset.iY = 0;
617
618
619 SDL_TRACE1("View width %d", w);
620 SDL_TRACE1("View height %d", h);
621 SDL_TRACE1("View bmode %d", bpp);
622 SDL_TRACE1("View s %d", scaleValue);
623 SDL_TRACE1("View x %d", Private->EPOC_ScreenOffset.iX);
624 SDL_TRACE1("View y %d", Private->EPOC_ScreenOffset.iY);
625
626 /* We're done */
627 return(current);
628}
629
630
631void RedrawWindowL(_THIS)
632{
633
634#if defined(__WINS__) || defined(TEST_BM_DRAW)
635 LockHeap(Private->EPOC_Bitmap); // Lock bitmap heap
636 Private->EPOC_WindowGc->Activate(Private->EPOC_WsWindow);
637#endif
638
639 int w = _this->screen->w;
640 int h = _this->screen->h;
641 if (Private->EPOC_ScreenOrientation == CFbsBitGc::EGraphicsOrientationRotated270) {
642 w = _this->screen->h;
643 h = _this->screen->w;
644 }
645 if ((w < Private->EPOC_ScreenSize.iWidth)
646 || (h < Private->EPOC_ScreenSize.iHeight)) {
647 DrawBackground(_this);
648 }
649
650 /* Tell the system that something has been drawn */
651 TRect rect = TRect(Private->EPOC_WsWindow.Size());
652 Private->EPOC_WsWindow.Invalidate(rect);
653
654#if defined(__WINS__) || defined(TEST_BM_DRAW)
655 Private->EPOC_WsWindow.BeginRedraw(rect);
656 Private->EPOC_WindowGc->BitBlt(TPoint(), Private->EPOC_Bitmap);
657 Private->EPOC_WsWindow.EndRedraw();
658 Private->EPOC_WindowGc->Deactivate();
659 UnlockHeap(Private->EPOC_Bitmap);; // Unlock bitmap heap
660 Private->EPOC_WsSession.Flush();
661#endif
662
663 /* Draw current buffer */
664 SDL_Rect fullScreen;
665 fullScreen.x = 0;
666 fullScreen.y = 0;
667 fullScreen.w = _this->screen->w;
668 fullScreen.h = _this->screen->h;
669 EPOC_DirectUpdate(_this, 1, &fullScreen);
670}
671
672
673void DrawBackground(_THIS)
674{
675 /* Draw background */
676#if defined(__WINS__) || defined(TEST_BM_DRAW)
677 //warning heap is not locked! - a function calling must ensure that it's ok
678 TUint16* screenBuffer = (TUint16*)Private->EPOC_Bitmap->DataAddress();
679#else
680 TUint16* screenBuffer = (TUint16*)Private->EPOC_FrameBuffer;
681#endif
682 // Draw black background
683 Mem::FillZ(screenBuffer, Private->EPOC_BytesPerScreen);
684
685#if 0
686 for (int y = 0; y < Private->EPOC_ScreenSize.iHeight; y++) {
687 for (int x = 0; x < Private->EPOC_ScreenSize.iWidth; x++) {
688#ifdef SYMBIAN_CRYSTAL
689 const TUint16 color = 0; // ((x+y)>>1) & 0xf; /* Draw blue stripes pattern, because in e.g. 320x200 mode there is a big background area*/
690#else // SYMBIAN_SERIES60
691 const TUint16 color = 0; /* Draw black background */
692#endif
693 *screenBuffer++ = color;
694 }
695 }
696#endif
697}
698
699
700/* We don't actually allow hardware surfaces other than the main one */
701static int EPOC_AllocHWSurface(_THIS, SDL_Surface* /*surface*/)
702{
703 return(-1);
704}
705static void EPOC_FreeHWSurface(_THIS, SDL_Surface* /*surface*/)
706{
707 return;
708}
709
710static int EPOC_LockHWSurface(_THIS, SDL_Surface* /*surface*/)
711{
712 return(0);
713}
714static void EPOC_UnlockHWSurface(_THIS, SDL_Surface* /*surface*/)
715{
716 return;
717}
718
719static int EPOC_FlipHWSurface(_THIS, SDL_Surface* /*surface*/)
720{
721 return(0);
722}
723
724static void EPOC_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
725{
726 //TInt focusWindowGroupId = Private->EPOC_WsSession.GetFocusWindowGroup();//these are async services
727 // if (focusWindowGroupId != Private->EPOC_WsWindowGroupID) { //for that cannot be called from
728 //SDL threads ???
729 if (!Private->EPOC_IsWindowFocused)
730 {
731 /* Force focus window to redraw again for cleaning away SDL screen graphics */
732/*
733 TInt pos = Private->EPOC_WsWindowGroup.OrdinalPosition();
734 Private->EPOC_WsWindowGroup.SetOrdinalPosition(0, KMaxTInt);
735 TRect rect = TRect(Private->EPOC_WsWindow.Size());
736 Private->EPOC_WsWindow.Invalidate(rect);
737 Private->EPOC_WsWindowGroup.SetOrdinalPosition(pos, ECoeWinPriorityNormal);
738 */ /* If this is not the topmost window, wait here! Sleep for 1 second to give cpu time to
739 multitasking and poll for being the topmost window.
740 */
741 // if (Private->EPOC_WsSession.GetFocusWindowGroup() != Private->EPOC_WsWindowGroupID) {
742
743 /* !!TODO: Could call GetRedraw() etc. for WsSession and redraw the screen if needed. That might be
744 needed if a small dialog comes in front of Game screen.
745 */
746 // while (Private->EPOC_WsSession.GetFocusWindowGroup() != Private->EPOC_WsWindowGroupID)
747
748 SDL_PauseAudio(1);
749 SDL_Delay(1000);
750 return;
751 // }
752
753 // RedrawWindowL(_this);
754 }
755
756 SDL_PauseAudio(0);
757
758 // if we are not focused, do not draw
759// if (!Private->EPOC_IsWindowFocused)
760// return;
761#if defined(__WINS__) || defined(TEST_BM_DRAW)
762 TBitmapUtil lock(Private->EPOC_Bitmap);
763 lock.Begin(TPoint(0,0)); // Lock bitmap heap
764 Private->EPOC_WindowGc->Activate(Private->EPOC_WsWindow);
765 TUint16* screenBuffer = (TUint16*)Private->EPOC_Bitmap->DataAddress();
766#else
767 TUint16* screenBuffer = (TUint16*)Private->EPOC_FrameBuffer;
768#endif
769
770 if (Private->EPOC_ScreenOrientation == CFbsBitGc::EGraphicsOrientationRotated270)
771 DirectDrawRotated(_this, numrects, rects, screenBuffer);
772 else
773 DirectDraw(_this, numrects, rects, screenBuffer);
774
775
776#if defined(__WINS__) || defined(TEST_BM_DRAW)
777
778 TRect rect = TRect(Private->EPOC_WsWindow.Size());
779 Private->EPOC_WsWindow.Invalidate(rect);
780 Private->EPOC_WsWindow.BeginRedraw(rect);
781 Private->EPOC_WindowGc->BitBlt(TPoint(), Private->EPOC_Bitmap);
782 Private->EPOC_WsWindow.EndRedraw();
783 Private->EPOC_WindowGc->Deactivate();
784 lock.End(); // Unlock bitmap heap
785 Private->EPOC_WsSession.Flush();
786#else
787#ifndef SYMBIAN_CRYSTAL
788 // This is not needed in Crystal. What is the performance penalty in SERIES60?
789 TRect rect2 = TRect(Private->EPOC_WsWindow.Size());
790
791 Private->EPOC_DrawDevice->UpdateRegion(rect2); // Should we update rects parameter area only??
792 Private->EPOC_DrawDevice->Update();
793#endif
794#endif
795
796 /* Update virtual cursor. !!Do not yet work properly
797 Private->EPOC_WsSession.SetPointerCursorPosition(Private->EPOC_WsSession.PointerCursorPosition());
798 */
799
800 /*static int foo = 1;
801
802 for ( int i=0; i < numrects; ++i ) {
803 const SDL_Rect& currentRect = rects[i];
804 SDL_Rect rect2;
805 rect2.x = currentRect.x;
806 rect2.y = currentRect.y;
807 rect2.w = currentRect.w;
808 rect2.h = currentRect.h;
809
810 if (rect2.w <= 0 || rect2.h <= 0)
811 continue;
812
813
814 foo++;
815 if((foo % 200) == 0)
816 {
817 SDL_TRACE1("foo %d", foo);
818 CFbsBitmap* b = new (ELeave) CFbsBitmap;
819 SDL_TRACE1("bee %d", (int)b);
820 int e = b->Create(TSize(currentRect.w, currentRect.h), Private->EPOC_DisplayMode);
821
822 SDL_TRACE1("err %d", e);
823 if(e != KErrNone)
824 User::Panic(_L("damn"), e);
825
826 TBitmapUtil u(b);
827 u.Begin(TPoint(0, 0));
828 TUint32* d = b->DataAddress();
829
830 SDL_TRACE1("addr %d", (int)d);
831
832 for(TInt o = 0; o < currentRect.h; o++)
833 for(TInt p = 0; p < currentRect.w; p++)
834 {
835 u.SetPos(TPoint(p, o));
836 u.SetPixel(0xFFFF);
837 }
838
839 SDL_TRACE1("w %d", (int)currentRect.w);
840 SDL_TRACE1("h %d", (int)currentRect.h);
841
842 SDL_TRACE1("addr %d", (int)Private->EPOC_DisplayMode);
843
844
845 const TUint f = (TUint)Private->EPOC_FrameBuffer;
846 const TUint y = (TUint)Private->EPOC_BytesPerScreen;
847
848
849 SDL_TRACE1("frame %u", f);
850 SDL_TRACE1("bytes %u", y);
851
852 Mem::Copy(d, Private->EPOC_FrameBuffer, Private->EPOC_BytesPerScreen);
853
854 SDL_TRACE("kopied");
855
856 u.End();
857 TBuf<32> name;
858 name.Format(_L("C:\\nokia\\images\\doom%d.mbm"), (foo / 200));
859 e= b->Save(name);
860 if(e != KErrNone)
861 User::Panic(_L("damned"), e);
862 delete b;
863 }}*/
864}
865
866
867void DirectDraw(_THIS, int numrects, SDL_Rect *rects, TUint16* screenBuffer)
868{
869 TInt i;
870
871 const TInt sourceNumBytesPerPixel = ((_this->screen->format->BitsPerPixel-1)>>3) + 1;
872 const TPoint fixedOffset = Private->EPOC_ScreenOffset;
873 const TInt screenW = _this->screen->w;
874 const TInt screenH = _this->screen->h;
875 const TInt sourceScanlineLength = screenW;
876 const TInt targetScanlineLength = Private->EPOC_ScreenSize.iWidth;
877
878 /* Render the rectangles in the list */
879
880 for ( i=0; i < numrects; ++i ) {
881 const SDL_Rect& currentRect = rects[i];
882 SDL_Rect rect2;
883 rect2.x = currentRect.x;
884 rect2.y = currentRect.y;
885 rect2.w = currentRect.w;
886 rect2.h = currentRect.h;
887
888 if (rect2.w <= 0 || rect2.h <= 0) /* sanity check */
889 continue;
890
891 /* All variables are measured in pixels */
892
893 /* Check rects validity, i.e. upper and lower bounds */
894 TInt maxX = Min(screenW - 1, rect2.x + rect2.w - 1);
895 TInt maxY = Min(screenH - 1, rect2.y + rect2.h - 1);
896 if (maxX < 0 || maxY < 0) /* sanity check */
897 continue;
898 /* Clip from bottom */
899 maxY = Min(maxY, Private->EPOC_ScreenSize.iHeight-1);
900 /* TODO: Clip from the right side */
901
902 const TInt sourceRectWidth = maxX - rect2.x + 1;
903 const TInt sourceRectWidthInBytes = sourceRectWidth * sourceNumBytesPerPixel;
904 const TInt sourceRectHeight = maxY - rect2.y + 1;
905 const TInt sourceStartOffset = rect2.x + rect2.y * sourceScanlineLength;
906 const TUint skipValue = 1; // no skip
907
908 TInt targetStartOffset = fixedOffset.iX + rect2.x + (fixedOffset.iY +rect2.y) * targetScanlineLength;
909
910 // Nokia7650 native mode: 12 bpp --> 12 bpp
911 //
912
913 switch (_this->screen->format->BitsPerPixel)
914 {
915 case 12:
916 {
917 TUint16* bitmapLine = (TUint16*)_this->screen->pixels + sourceStartOffset;
918 TUint16* screenMemory = screenBuffer + targetStartOffset;
919 if (skipValue == 1)
920 {
921 for(TInt y = 0 ; y < sourceRectHeight ; y++)
922 {
923 Mem::Copy(screenMemory, bitmapLine, sourceRectWidthInBytes);
924 }
925 bitmapLine += sourceScanlineLength;
926 screenMemory += targetScanlineLength;
927 }
928 else
929 {
930 for(TInt y = 0 ; y < sourceRectHeight ; y++)
931 {
932 //TODO: optimize: separate loops for 1, 2 and n skip. Mem::Copy() can be used in unscaled case.
933 TUint16* bitmapPos = bitmapLine; /* 2 bytes per pixel */
934 TUint16* screenMemoryLinePos = screenMemory; /* 2 bytes per pixel */
935 for(TInt x = 0 ; x < sourceRectWidth ; x++)
936 {
937 __ASSERT_DEBUG(screenMemory < (screenBuffer + Private->EPOC_ScreenSize.iWidth * Private->EPOC_ScreenSize.iHeight), User::Panic(_L("SDL"), KErrCorrupt));
938 __ASSERT_DEBUG(screenMemory >= screenBuffer, User::Panic(_L("SDL"), KErrCorrupt));
939 __ASSERT_DEBUG(bitmapLine < ((TUint16*)_this->screen->pixels + (_this->screen->w * _this->screen->h)), User::Panic(_L("SDL"), KErrCorrupt));
940 __ASSERT_DEBUG(bitmapLine >= (TUint16*)_this->screen->pixels, User::Panic(_L("SDL"), KErrCorrupt));
941
942 *screenMemoryLinePos++ = *bitmapPos;
943 bitmapPos+=skipValue;
944 }
945 bitmapLine += sourceScanlineLength;
946 screenMemory += targetScanlineLength;
947 }
948 }
949 }
950 break;
951 // 256 color paletted mode: 8 bpp --> 12 bpp
952 //
953 default:
954 {
955 if(Private->EPOC_BytesPerPixel <= 2)
956 {
957 TUint8* bitmapLine = (TUint8*)_this->screen->pixels + sourceStartOffset;
958 TUint16* screenMemory = screenBuffer + targetStartOffset;
959 for(TInt y = 0 ; y < sourceRectHeight ; y++)
960 {
961 TUint8* bitmapPos = bitmapLine; /* 1 byte per pixel */
962 TUint16* screenMemoryLinePos = screenMemory; /* 2 bytes per pixel */
963 /* Convert each pixel from 256 palette to 4k color values */
964 for(TInt x = 0 ; x < sourceRectWidth ; x++)
965 {
966 __ASSERT_DEBUG(screenMemoryLinePos < (screenBuffer + (Private->EPOC_ScreenSize.iWidth * Private->EPOC_ScreenSize.iHeight)), User::Panic(_L("SDL"), KErrCorrupt));
967 __ASSERT_DEBUG(screenMemoryLinePos >= screenBuffer, User::Panic(_L("SDL"), KErrCorrupt));
968 __ASSERT_DEBUG(bitmapPos < ((TUint8*)_this->screen->pixels + (_this->screen->w * _this->screen->h)), User::Panic(_L("SDL"), KErrCorrupt));
969 __ASSERT_DEBUG(bitmapPos >= (TUint8*)_this->screen->pixels, User::Panic(_L("SDL"), KErrCorrupt));
970 *screenMemoryLinePos++ = EPOC_HWPalette_256_to_Screen[*bitmapPos++];
971 // bitmapPos+=skipValue; //TODO: optimize: separate loops for 1, 2 and n skip
972 }
973 bitmapLine += sourceScanlineLength;
974 screenMemory += targetScanlineLength;
975 }
976 }
977 else
978 {
979 TUint8* bitmapLine = (TUint8*)_this->screen->pixels + sourceStartOffset;
980 TUint32* screenMemory = reinterpret_cast<TUint32*>(screenBuffer + targetStartOffset);
981 for(TInt y = 0 ; y < sourceRectHeight ; y++)
982 {
983 TUint8* bitmapPos = bitmapLine; /* 1 byte per pixel */
984 TUint32* screenMemoryLinePos = screenMemory; /* 2 bytes per pixel */
985 /* Convert each pixel from 256 palette to 4k color values */
986 for(TInt x = 0 ; x < sourceRectWidth ; x++)
987 {
988 __ASSERT_DEBUG(screenMemoryLinePos < (reinterpret_cast<TUint32*>(screenBuffer) + (Private->EPOC_ScreenSize.iWidth * Private->EPOC_ScreenSize.iHeight)), User::Panic(_L("SDL"), KErrCorrupt));
989 __ASSERT_DEBUG(screenMemoryLinePos >= reinterpret_cast<TUint32*>(screenBuffer), User::Panic(_L("SDL"), KErrCorrupt));
990 __ASSERT_DEBUG(bitmapPos < ((TUint8*)_this->screen->pixels + (_this->screen->w * _this->screen->h)), User::Panic(_L("SDL"), KErrCorrupt));
991 __ASSERT_DEBUG(bitmapPos >= (TUint8*)_this->screen->pixels, User::Panic(_L("SDL"), KErrCorrupt));
992 *screenMemoryLinePos++ = EPOC_HWPalette_256_to_Screen[*bitmapPos++];
993 // bitmapPos+=skipValue; //TODO: optimize: separate loops for 1, 2 and n skip
994 }
995 bitmapLine += sourceScanlineLength;
996 screenMemory += targetScanlineLength;
997 }
998 }
999 }
1000 } // switch
1001 } // for
1002}
1003
1004/*
1005void DirectDraw(_THIS, int numrects, SDL_Rect *rects, TUint16* screenBuffer)
1006{
1007 TInt i;
1008 const TInt sourceNumBytesPerPixel = ((_this->screen->format->BitsPerPixel-1)>>3) + 1;
1009 const TPoint fixedOffset = Private->EPOC_ScreenOffset;
1010 const TInt screenW = _this->screen->w;
1011 const TInt screenH = _this->screen->h;
1012 const TInt sourceScanlineLength = screenW;
1013 const TInt targetScanlineLength = Private->EPOC_ScreenSize.iWidth;
1014
1015 /* Render the rectangles in the list */
1016
1017/* for ( i=0; i < numrects; ++i ) {
1018 const SDL_Rect& currentRect = rects[i];
1019 SDL_Rect rect2;
1020 rect2.x = currentRect.x;
1021 rect2.y = currentRect.y;
1022 rect2.w = currentRect.w;
1023 rect2.h = currentRect.h;
1024
1025 if (rect2.w <= 0 || rect2.h <= 0) /* sanity check */
1026/* continue;
1027
1028 /* All variables are measured in pixels */
1029
1030 /* Check rects validity, i.e. upper and lower bounds */
1031/* TInt maxX = Min(screenW - 1, rect2.x + rect2.w - 1);
1032 TInt maxY = Min(screenH - 1, rect2.y + rect2.h - 1);
1033 if (maxX < 0 || maxY < 0) /* sanity check */
1034/* continue;
1035 /* Clip from bottom */
1036/* maxY = Min(maxY, Private->EPOC_ScreenSize.iHeight-1);
1037 /* TODO: Clip from the right side */
1038
1039/* TInt sourceRectWidth = maxX - rect2.x + 1;
1040 const TInt sourceRectWidthInBytes = sourceRectWidth * sourceNumBytesPerPixel;
1041 const TInt sourceRectHeight = maxY - rect2.y + 1;
1042 const TInt sourceStartOffset = rect2.x + rect2.y * sourceScanlineLength;
1043 const TUint skipValue = Private->EPOC_ScreenXScaleValue; //1; // no skip
1044
1045 const TInt targetStartOffset = // = (fixedOffset.iX + (rect2.x / skipValue) + (fixedOffset.iY + rect2.y) * targetScanlineLength ) ;
1046 (skipValue > 1 ?
1047 (fixedOffset.iX + (rect2.x / skipValue) + (fixedOffset.iY + rect2.y) * targetScanlineLength ) :
1048 (fixedOffset.iX + rect2.x + (fixedOffset.iY + rect2.y) * targetScanlineLength ));
1049
1050 __ASSERT_DEBUG(skipValue >= 1, User::Panic(KLibName, KErrArgument));
1051
1052 // Nokia7650 native mode: 12 bpp --> 12 bpp
1053 //
1054 switch (_this->screen->format->BitsPerPixel)
1055 {
1056 case 12:
1057 {
1058 TUint16* bitmapLine = (TUint16*)_this->screen->pixels + sourceStartOffset;
1059 TUint16* screenMemory = screenBuffer + targetStartOffset;
1060 if (skipValue == 1)
1061 {
1062 for(TInt y = 0 ; y < sourceRectHeight ; y++)
1063 {
1064 Mem::Copy(screenMemory, bitmapLine, sourceRectWidthInBytes);
1065 }
1066 bitmapLine += sourceScanlineLength;
1067 screenMemory += targetScanlineLength;
1068 }
1069 else
1070 {
1071 for(TInt y = 0 ; y < sourceRectHeight ; y++)
1072 {
1073 //TODO: optimize: separate loops for 1, 2 and n skip. Mem::Copy() can be used in unscaled case.
1074 TUint16* bitmapPos = bitmapLine; /* 2 bytes per pixel */
1075/* TUint16* screenMemoryLinePos = screenMemory; /* 2 bytes per pixel */
1076/* for(TInt x = 0 ; x < sourceRectWidth ; x++)
1077 {
1078 __ASSERT_DEBUG(screenMemory < (screenBuffer + Private->EPOC_ScreenSize.iWidth * Private->EPOC_ScreenSize.iHeight), User::Panic(KLibName, KErrCorrupt));
1079 __ASSERT_DEBUG(screenMemory >= screenBuffer, User::Panic(KLibName, KErrCorrupt));
1080 __ASSERT_DEBUG(bitmapLine < ((TUint16*)_this->screen->pixels + (_this->screen->w * _this->screen->h)), User::Panic(KLibName, KErrCorrupt));
1081 __ASSERT_DEBUG(bitmapLine >= (TUint16*)_this->screen->pixels, User::Panic(KLibName, KErrCorrupt));
1082
1083 *screenMemoryLinePos++ = *bitmapPos;
1084 bitmapPos+=skipValue;
1085 }
1086 bitmapLine += sourceScanlineLength;
1087 screenMemory += targetScanlineLength;
1088 }
1089 }
1090 }
1091 break;
1092 // 256 color paletted mode: 8 bpp --> 12 bpp
1093 //
1094 default:
1095 {
1096 TUint8* bitmapLine = (TUint8*)_this->screen->pixels + sourceStartOffset;
1097 TUint16* screenMemory = screenBuffer + targetStartOffset;
1098 if (skipValue > 1)
1099 sourceRectWidth /= skipValue;
1100#if defined __MARM_ARMI__
1101 __asm volatile("
1102 mov %4, %4, lsl #1 @ targetScanLineLength is in pixels, we need it in bytes
1103 1:
1104 mov r6, %0 @ bitmapLine
1105 mov r7, %2 @ screenMemory
1106 mov r8, %6 @ sourceRectWidth
1107 2:
1108 ldrb r4, [%0], %7 @ r4 = *bitmapPos; bitmapPos += skipValue
1109 ldr r5, [%1, r4, lsl #2] @ only 16 lower bits actually used
1110 subs r8, r8, #1 @ x--
1111 strh r5, [%2], #2 @ *screenMemoryLinePos++ = r4
1112 bne 2b
1113
1114 add %0, r6, %3 @ bitmapLine += sourceScanlineLength
1115 add %2, r7, %4 @ screenMemory += targetScanlineLength
1116 subs %5, %5, #1 @ sourceRectHeight--
1117 bne 1b
1118 "
1119 : // no output
1120 // %0 %1 %2 %3 %4 %5 %6 %7
1121 : "r" (bitmapLine), "r" (&EPOC_HWPalette_256_to_Screen[0]), "r" (screenMemory), "r" (sourceScanlineLength), "r" (targetScanlineLength), "r" (sourceRectHeight), "r" (sourceRectWidth), "r" (skipValue)
1122 : "r4", "r5", "r6", "r7", "r8"
1123 );
1124#else
1125 for(TInt y = 0 ; y < sourceRectHeight ; y++)
1126 {
1127 TUint8* bitmapPos = bitmapLine; /* 1 byte per pixel */
1128/* TUint16* screenMemoryLinePos = screenMemory; /* 2 bytes per pixel */
1129 /* Convert each pixel from 256 palette to 4k color values */
1130/* for (TInt x = 0 ; x < sourceRectWidth ; x++)
1131 {
1132 //__ASSERT_DEBUG(screenMemoryLinePos < (screenBuffer + (Private->EPOC_ScreenSize.iWidth * Private->EPOC_ScreenSize.iHeight)), User::Panic(KLibName, KErrCorrupt));
1133 //__ASSERT_DEBUG(screenMemoryLinePos >= screenBuffer, User::Panic(KLibName, KErrCorrupt));
1134 //__ASSERT_DEBUG(bitmapPos < ((TUint8*)_this->screen->pixels + (_this->screen->w * _this->screen->h)), User::Panic(KLibName, KErrCorrupt));
1135 //__ASSERT_DEBUG(bitmapPos >= (TUint8*)_this->screen->pixels, User::Panic(KLibName, KErrCorrupt));
1136
1137 *screenMemoryLinePos++ = EPOC_HWPalette_256_to_Screen[*bitmapPos];
1138 bitmapPos += skipValue;
1139 }
1140 bitmapLine += sourceScanlineLength;
1141 screenMemory += targetScanlineLength;
1142 }
1143//#endif
1144 }
1145 } // switch
1146 } // for
1147}
1148*/
1149
1150void DirectDrawRotated(_THIS, int numrects, SDL_Rect *rects, TUint16* screenBuffer)
1151{
1152 TInt i;
1153// TInt sourceNumBytesPerPixel = ((_this->screen->format->BitsPerPixel-1)>>3) + 1;
1154 TPoint fixedScreenOffset = Private->EPOC_ScreenOffset;
1155 TInt bufferW = _this->screen->w;
1156 TInt bufferH = _this->screen->h;
1157 TInt ScreenW = Private->EPOC_ScreenSize.iWidth;
1158// TInt ScreenH = Private->EPOC_ScreenSize.iWidth;
1159 TInt sourceW = bufferW;
1160 TInt sourceH = bufferH;
1161 TInt targetW = ScreenW - fixedScreenOffset.iX * 2;
1162// TInt targetH = ScreenH - fixedScreenOffset.iY * 2;
1163 TInt sourceScanlineLength = bufferW;
1164 TInt targetScanlineLength = Private->EPOC_ScreenSize.iWidth;
1165
1166 /* Render the rectangles in the list */
1167
1168 for ( i=0; i < numrects; ++i ) {
1169 SDL_Rect rect2;
1170 const SDL_Rect& currentRect = rects[i];
1171 rect2.x = currentRect.x;
1172 rect2.y = currentRect.y;
1173 rect2.w = currentRect.w;
1174 rect2.h = currentRect.h;
1175
1176 if (rect2.w <= 0 || rect2.h <= 0) /* sanity check */
1177 continue;
1178
1179 /* All variables are measured in pixels */
1180
1181 /* Check rects validity, i.e. upper and lower bounds */
1182 TInt maxX = Min(sourceW - 1, rect2.x + rect2.w - 1);
1183 TInt maxY = Min(sourceH - 1, rect2.y + rect2.h - 1);
1184 if (maxX < 0 || maxY < 0) /* sanity check */
1185 continue;
1186 /* Clip from bottom */
1187 //maxX = Min(maxX, Private->EPOC_ScreenSize.iHeight-1);
1188 /* TODO: Clip from the right side */
1189
1190 TInt sourceRectWidth = maxX - rect2.x + 1;
1191// TInt sourceRectWidthInBytes = sourceRectWidth * sourceNumBytesPerPixel;
1192 TInt sourceRectHeight = maxY - rect2.y + 1;
1193 TInt sourceStartOffset = rect2.x + rect2.y * sourceScanlineLength;
1194 TInt targetStartOffset = fixedScreenOffset.iX + (targetW-1 - rect2.y) + (fixedScreenOffset.iY +rect2.x) * targetScanlineLength;
1195
1196 // Nokia7650 native mode: 12 bpp --> 12 bpp
1197 if (_this->screen->format->BitsPerPixel == 12) {
1198
1199 /* !!TODO: not yet implemented
1200
1201 TUint16* bitmapLine = (TUint16*)_this->screen->pixels + sourceStartOffset;
1202 TUint16* screenMemory = screenBuffer + targetStartOffset;
1203 for(TInt y = 0 ; y < sourceRectHeight ; y++) {
1204 //TODO: optimize: separate loops for 1, 2 and n skip
1205 //Mem::Copy(screenMemory, bitmapLine, sourceRectWidthInBytes);
1206 TUint16* bitmapPos = bitmapLine; // 2 bytes per pixel
1207 TUint16* screenMemoryLinePos = screenMemory; // 2 bytes per pixel
1208 for(TInt x = 0 ; x < sourceRectWidth ; x++) {
1209
1210 __ASSERT_DEBUG(screenMemory < (screenBuffer + Private->EPOC_ScreenSize.iWidth * Private->EPOC_ScreenSize.iHeight), User::Panic(KLibName, KErrCorrupt));
1211 __ASSERT_DEBUG(screenMemory >= screenBuffer, User::Panic(KLibName, KErrCorrupt));
1212 __ASSERT_DEBUG(bitmapLine < ((TUint16*)_this->screen->pixels + (_this->screen->w * _this->screen->h)), User::Panic(KLibName, KErrCorrupt));
1213 __ASSERT_DEBUG(bitmapLine >= (TUint16*)_this->screen->pixels, User::Panic(KLibName, KErrCorrupt));
1214
1215 *screenMemoryLinePos = *bitmapPos;
1216 bitmapPos++;
1217 screenMemoryLinePos += targetScanlineLength;
1218 }
1219 bitmapLine += sourceScanlineLength;
1220 screenMemory--;
1221 }
1222
1223 */
1224 }
1225 // 256 color paletted mode: 8 bpp --> 12 bpp
1226 else {
1227 TUint8* bitmapLine = (TUint8*)_this->screen->pixels + sourceStartOffset;
1228 TUint16* screenMemory = screenBuffer + targetStartOffset;
1229 TInt screenXScaleValue = Private->EPOC_ScreenXScaleValue;
1230 TInt debug_ycount=0;
1231 for(TInt y = 0 ; y < sourceRectHeight ; y++) {
1232 if(--screenXScaleValue) {
1233 TUint8* bitmapPos = bitmapLine; /* 1 byte per pixel */
1234 TUint16* screenMemoryLinePos = screenMemory; /* 2 bytes per pixel */
1235 TInt screenYScaleValue = Private->EPOC_ScreenYScaleValue;
1236 TInt debug_xcount=0;
1237 /* Convert each pixel from 256 palette to 4k color values */
1238 for(TInt x = 0 ; x < sourceRectWidth ; x++) {
1239 if(--screenYScaleValue) {
1240
1241 __ASSERT_DEBUG(screenMemoryLinePos < (screenBuffer + (Private->EPOC_ScreenSize.iWidth * Private->EPOC_ScreenSize.iHeight)), User::Panic(KLibName, KErrCorrupt));
1242 __ASSERT_DEBUG(screenMemoryLinePos >= screenBuffer, User::Panic(KLibName, KErrCorrupt));
1243 __ASSERT_DEBUG(bitmapPos < ((TUint8*)_this->screen->pixels + (_this->screen->w * _this->screen->h)), User::Panic(KLibName, KErrCorrupt));
1244 __ASSERT_DEBUG(bitmapPos >= (TUint8*)_this->screen->pixels, User::Panic(KLibName, KErrCorrupt));
1245
1246 *screenMemoryLinePos = TUint16(EPOC_HWPalette_256_to_Screen[*bitmapPos]);
1247 screenMemoryLinePos += targetScanlineLength; debug_xcount++;
1248 }
1249 else
1250 screenYScaleValue = Private->EPOC_ScreenYScaleValue;
1251 bitmapPos++;
1252 }
1253 screenMemory--; debug_ycount++;
1254 } // endif
1255 else
1256 screenXScaleValue = Private->EPOC_ScreenXScaleValue;
1257 bitmapLine += sourceScanlineLength;
1258 }
1259 }
1260 }
1261}
1262
1263
1264/* Note: If we are terminated, this could be called in the middle of
1265 another SDL video routine -- notably UpdateRects.
1266*/
1267void EPOC_VideoQuit(_THIS)
1268{
1269 int i;
1270
1271 /* Free video mode lists */
1272 for ( i=0; i<SDL_NUMMODES; ++i ) {
1273 if ( Private->SDL_modelist[i] != NULL ) {
1274 free(Private->SDL_modelist[i]);
1275 Private->SDL_modelist[i] = NULL;
1276 }
1277 }
1278
1279 if ( _this->screen && (_this->screen->flags & SDL_HWSURFACE) ) {
1280 /* Direct screen access, no memory buffer */
1281 _this->screen->pixels = NULL;
1282 }
1283
1284 if (_this->screen && _this->screen->pixels) {
1285 free(_this->screen->pixels);
1286 _this->screen->pixels = NULL;
1287 }
1288
1289 /* Free Epoc resources */
1290
1291 /* Disable events for me */
1292 if (Private->EPOC_WsEventStatus != KRequestPending)
1293 Private->EPOC_WsSession.EventReadyCancel();
1294 if (Private->EPOC_RedrawEventStatus != KRequestPending)
1295 Private->EPOC_WsSession.RedrawReadyCancel();
1296
1297 #if defined(__WINS__) || defined(TEST_BM_DRAW)
1298 delete Private->EPOC_Bitmap;
1299 Private->EPOC_Bitmap = NULL;
1300 #else
1301 #endif
1302
1303#ifndef SYMBIAN_CRYSTAL
1304 free(Private->EPOC_DrawDevice);
1305#endif
1306
1307 if (Private->EPOC_WsWindow.WsHandle())
1308 Private->EPOC_WsWindow.Close();
1309
1310 if (Private->EPOC_WsWindowGroup.WsHandle())
1311 Private->EPOC_WsWindowGroup.Close();
1312
1313 delete Private->EPOC_WindowGc;
1314 Private->EPOC_WindowGc = NULL;
1315
1316 delete Private->EPOC_WsScreen;
1317 Private->EPOC_WsScreen = NULL;
1318
1319 if (Private->EPOC_WsSession.WsHandle())
1320 Private->EPOC_WsSession.Close();
1321}
1322
1323
1324WMcursor *EPOC_CreateWMCursor(_THIS, Uint8* /*data*/, Uint8* /*mask*/, int /*w*/, int /*h*/, int /*hot_x*/, int /*hot_y*/)
1325{
1326 return (WMcursor *) 9210; // it's ok to return something unuseful but true
1327}
1328
1329void EPOC_FreeWMCursor(_THIS, WMcursor* /*cursor*/)
1330{
1331 /* Disable virtual cursor */
1332 HAL::Set(HAL::EMouseState, HAL::EMouseState_Invisible);
1333 Private->EPOC_WsSession.SetPointerCursorMode(EPointerCursorNone);
1334}
1335
1336int EPOC_ShowWMCursor(_THIS, WMcursor *cursor)
1337{
1338
1339 if (cursor == (WMcursor *)9210) {
1340 /* Enable virtual cursor */
1341 Private->EPOC_WsSession.SetPointerCursorMode(EPointerCursorNormal);
1342 if (isCursorVisible)
1343 HAL::Set(HAL::EMouseState, HAL::EMouseState_Visible);
1344 else
1345 Private->EPOC_WsSession.SetPointerCursorMode(EPointerCursorNone);
1346 }
1347 else {
1348 /* Disable virtual cursor */
1349 HAL::Set(HAL::EMouseState, HAL::EMouseState_Invisible);
1350 Private->EPOC_WsSession.SetPointerCursorMode(EPointerCursorNone);
1351 }
1352
1353 return(1);
1354}
1355
1356}; // extern "C"
diff --git a/apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocvideo.h b/apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocvideo.h
deleted file mode 100644
index bd0b0e29c5..0000000000
--- a/apps/plugins/sdl/src/video/symbian/EKA1/SDL_epocvideo.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23#ifndef _SDL_epocvideo_h
24#define _SDL_epocvideo_h
25
26#ifndef EKA2
27#include"SDL_epocvideo_org.h"
28#else
29#include"SDL_epocvideo2.h"
30#endif
31
32
33#endif
34
diff --git a/apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocevents.cpp b/apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocevents.cpp
deleted file mode 100644
index 2452daed6f..0000000000
--- a/apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocevents.cpp
+++ /dev/null
@@ -1,521 +0,0 @@
1#include "epoc_sdl.h"
2
3#include <stdio.h>
4#undef NULL
5extern "C" {
6//#define DEBUG_TRACE_ENABLED
7#include "SDL_error.h"
8#include "SDL_video.h"
9#include "SDL_keysym.h"
10#include "SDL_keyboard.h"
11#include "SDL_events_c.h"
12#include "SDL_timer.h"
13} /* extern "C" */
14
15#include "SDL_epocvideo.h"
16#include "SDL_epocevents_c.h"
17
18#include "sdlepocapi.h"
19
20#include <eikenv.h>
21
22#include<bautils.h>
23
24
25extern "C"
26 {
27 static SDL_keysym *TranslateKey(_THIS, int scancode, SDL_keysym *keysym);
28 }
29
30//extern "C" {
31/* The translation tables from a console scancode to a SDL keysym */
32static SDLKey keymap[MAX_SCANCODE];
33static SDL_keysym *TranslateKey(_THIS, int scancode, SDL_keysym *keysym);
34void DisableKeyBlocking(_THIS);
35//} /* extern "C" */
36
37SDLKey* KeyMap()
38 {
39 return keymap;
40 }
41
42TBool isCursorVisible = EFalse;
43
44void ResetKeyMap()
45 {
46 int i;
47
48 /* Initialize the key translation table */
49 for ( i=0; i<SDL_TABLESIZE(keymap); ++i )
50 keymap[i] = SDLK_UNKNOWN;
51
52
53 /* Numbers */
54 for ( i = 0; i<32; ++i ){
55 keymap[' ' + i] = (SDLKey)(SDLK_SPACE+i);
56 }
57 /* e.g. Alphabet keys */
58 for ( i = 0; i<32; ++i ){
59 keymap['A' + i] = (SDLKey)(SDLK_a+i);
60 }
61
62 keymap[EStdKeyBackspace] = SDLK_BACKSPACE;
63 keymap[EStdKeyTab] = SDLK_TAB;
64 keymap[EStdKeyEnter] = SDLK_RETURN;
65 keymap[EStdKeyEscape] = SDLK_ESCAPE;
66 keymap[EStdKeySpace] = SDLK_SPACE;
67 keymap[EStdKeyPause] = SDLK_PAUSE;
68 keymap[EStdKeyHome] = SDLK_HOME;
69 keymap[EStdKeyEnd] = SDLK_END;
70 keymap[EStdKeyPageUp] = SDLK_PAGEUP;
71 keymap[EStdKeyPageDown] = SDLK_PAGEDOWN;
72 keymap[EStdKeyDelete] = SDLK_DELETE;
73 keymap[EStdKeyUpArrow] = SDLK_UP;
74 keymap[EStdKeyDownArrow] = SDLK_DOWN;
75 keymap[EStdKeyLeftArrow] = SDLK_LEFT;
76 keymap[EStdKeyRightArrow] = SDLK_RIGHT;
77 keymap[EStdKeyCapsLock] = SDLK_CAPSLOCK;
78 keymap[EStdKeyLeftShift] = SDLK_LSHIFT;
79 keymap[EStdKeyRightShift] = SDLK_RSHIFT;
80 keymap[EStdKeyLeftAlt] = SDLK_LALT;
81 keymap[EStdKeyRightAlt] = SDLK_RALT;
82 keymap[EStdKeyLeftCtrl] = SDLK_LCTRL;
83 keymap[EStdKeyRightCtrl] = SDLK_RCTRL;
84 keymap[EStdKeyLeftFunc] = SDLK_LMETA;
85 keymap[EStdKeyRightFunc] = SDLK_RMETA;
86 keymap[EStdKeyInsert] = SDLK_INSERT;
87 keymap[EStdKeyComma] = SDLK_COMMA;
88 keymap[EStdKeyFullStop] = SDLK_PERIOD;
89 keymap[EStdKeyForwardSlash] = SDLK_SLASH;
90 keymap[EStdKeyBackSlash] = SDLK_BACKSLASH;
91 keymap[EStdKeySemiColon] = SDLK_SEMICOLON;
92 keymap[EStdKeySingleQuote] = SDLK_QUOTE;
93 keymap[EStdKeyHash] = SDLK_HASH;
94 keymap[EStdKeySquareBracketLeft] = SDLK_LEFTBRACKET;
95 keymap[EStdKeySquareBracketRight] = SDLK_RIGHTBRACKET;
96 keymap[EStdKeyMinus] = SDLK_MINUS;
97 keymap[EStdKeyEquals] = SDLK_EQUALS;
98
99 keymap[EStdKeyF1] = SDLK_F1;
100 keymap[EStdKeyF2] = SDLK_F2;
101 keymap[EStdKeyF3] = SDLK_F3;
102 keymap[EStdKeyF4] = SDLK_F4;
103 keymap[EStdKeyF5] = SDLK_F5;
104 keymap[EStdKeyF6] = SDLK_F6;
105 keymap[EStdKeyF7] = SDLK_F7;
106 keymap[EStdKeyF8] = SDLK_F8;
107
108 keymap[EStdKeyF9] = SDLK_F9;
109 keymap[EStdKeyF10] = SDLK_F10;
110 keymap[EStdKeyF11] = SDLK_F11;
111 keymap[EStdKeyF12] = SDLK_F12;
112
113
114 keymap[EStdKeyXXX] = SDLK_RETURN; /* "fire" key */
115
116 keymap[EStdKeyDevice3] = SDLK_RETURN; /* "fire" key */
117 keymap[EStdKeyNkpAsterisk] = SDLK_ASTERISK;
118 keymap[EStdKeyYes] = SDLK_HOME; /* "call" key */
119 keymap[EStdKeyNo] = SDLK_END; /* "end call" key */
120 keymap[EStdKeyDevice0] = SDLK_SPACE; /* right menu key */
121 keymap[EStdKeyDevice1] = SDLK_ESCAPE; /* left menu key */
122 keymap[EStdKeyDevice2] = SDLK_POWER; /* power key */
123
124 keymap[EStdKeyMenu] = SDLK_MENU; // menu key
125 keymap[EStdKeyDevice6] = SDLK_LEFT; // Rocker (joystick) left
126 keymap[EStdKeyDevice7] = SDLK_RIGHT; // Rocker (joystick) right
127 keymap[EStdKeyDevice8] = SDLK_UP; // Rocker (joystick) up
128 keymap[EStdKeyDevice9] = SDLK_DOWN; // Rocker (joystick) down
129 keymap[EStdKeyLeftFunc] = SDLK_LALT; //chr?
130 keymap[EStdKeyRightFunc] = SDLK_RALT;
131 keymap[EStdKeyDeviceA] = SDLK_RETURN; /* "fire" key */
132
133
134
135
136
137 ///////////////////////////////////////////////////////////
138 /*
139 RFs fs;
140 if(KErrNone == fs.Connect())
141 {
142 RArray<TInt> array;
143 TRAPD(err, ReadL(fs, array));
144 if(err == KErrNone && array.Count() > 0)
145 {
146
147 SDLKey temp[MAX_SCANCODE];
148 Mem::Copy(temp, keymap, MAX_SCANCODE * sizeof(SDLKey));
149
150 for(TInt k = 0; k < array.Count(); k+= 2)
151 {
152 const TInt oldval = array[k];
153 const TInt newval = array[k + 1];
154 if(oldval >= 0 && oldval < MAX_SCANCODE && newval >= 0 && newval < MAX_SCANCODE)
155 {
156 keymap[oldval] = temp[newval];
157 }
158 }
159 }
160 array.Close();
161 }
162
163 fs.Close();*/
164 ///////////////////////////////////////////////////////////
165
166
167 keymap[EStdKeyNumLock] = SDLK_NUMLOCK;
168 keymap[EStdKeyScrollLock] = SDLK_SCROLLOCK;
169
170 keymap[EStdKeyNkpForwardSlash] = SDLK_KP_DIVIDE;
171 keymap[EStdKeyNkpAsterisk] = SDLK_KP_MULTIPLY;
172 keymap[EStdKeyNkpMinus] = SDLK_KP_MINUS;
173 keymap[EStdKeyNkpPlus] = SDLK_KP_PLUS;
174 keymap[EStdKeyNkpEnter] = SDLK_KP_ENTER;
175 keymap[EStdKeyNkp1] = SDLK_KP1;
176 keymap[EStdKeyNkp2] = SDLK_KP2;
177 keymap[EStdKeyNkp3] = SDLK_KP3;
178 keymap[EStdKeyNkp4] = SDLK_KP4;
179 keymap[EStdKeyNkp5] = SDLK_KP5;
180 keymap[EStdKeyNkp6] = SDLK_KP6;
181 keymap[EStdKeyNkp7] = SDLK_KP7;
182 keymap[EStdKeyNkp8] = SDLK_KP8;
183 keymap[EStdKeyNkp9] = SDLK_KP9;
184 keymap[EStdKeyNkp0] = SDLK_KP0;
185 keymap[EStdKeyNkpFullStop] = SDLK_KP_PERIOD;
186 /*
187 keymap[EStdKeyMenu] = SDLK_MENU; should be, but not yet
188 keymap[EStdKeyBacklightOn] =
189 keymap[EStdKeyBacklightOff] =
190 keymap[EStdKeyBacklightToggle] =
191 keymap[EStdKeyIncContrast] =
192 keymap[EStdKeyDecContrast] =
193 keymap[EStdKeySliderDown] =
194 keymap[EStdKeySliderUp] =
195 keymap[EStdKeyDictaphonePlay] =
196 keymap[EStdKeyDictaphoneStop] =
197 keymap[EStdKeyDictaphoneRecord] =
198 keymap[EStdKeyHelp] =
199 keymap[EStdKeyOff] =
200 keymap[EStdKeyDial] =
201 keymap[EStdKeyIncVolume] =
202 keymap[EStdKeyDecVolume] =
203 keymap[EStdKeyDevice0] =
204 keymap[EStdKeyDevice1] =
205 keymap[EStdKeyDevice2] =
206 keymap[EStdKeyDevice3] =
207 keymap[EStdKeyDevice4] =
208 keymap[EStdKeyDevice5] =
209 keymap[EStdKeyDevice6] =
210 keymap[EStdKeyDevice7] =
211 keymap[EStdKeyDevice8] =
212 keymap[EStdKeyDevice9] =
213 keymap[EStdKeyDeviceA] =
214 keymap[EStdKeyDeviceB] =
215 keymap[EStdKeyDeviceC] =
216 keymap[EStdKeyDeviceD] =
217 keymap[EStdKeyDeviceE] =
218 keymap[EStdKeyDeviceF] =
219 keymap[EStdKeyApplication0] =
220 keymap[EStdKeyApplication1] =
221 keymap[EStdKeyApplication2] =
222 keymap[EStdKeyApplication3] =
223 keymap[EStdKeyApplication4] =
224 keymap[EStdKeyApplication5] =
225 keymap[EStdKeyApplication6] =
226 keymap[EStdKeyApplication7] =
227 keymap[EStdKeyApplication8] =
228 keymap[EStdKeyApplication9] =
229 keymap[EStdKeyApplicationA] =
230 keymap[EStdKeyApplicationB] =
231 keymap[EStdKeyApplicationC] =
232 keymap[EStdKeyApplicationD] =
233 keymap[EStdKeyApplicationE] =
234 keymap[EStdKeyApplicationF] =
235 keymap[EStdKeyYes] =
236 keymap[EStdKeyNo] =
237 keymap[EStdKeyIncBrightness] =
238 keymap[EStdKeyDecBrightness] =
239 keymap[EStdKeyCaseOpen] =
240 keymap[EStdKeyCaseClose] = */
241
242
243
244}
245
246
247int EPOC_HandleWsEvent(_THIS, const TWsEvent& aWsEvent)
248{
249 int posted = 0;
250 SDL_keysym keysym;
251
252// SDL_TRACE1("hws %d", aWsEvent.Type());
253
254 switch (aWsEvent.Type())
255 {
256 case EEventPointer: /* Mouse pointer events */
257 {
258/* const TPointerCursorMode mode = EpocSdlEnv::PointerMode();
259
260
261 if(mode == EPointerCursorNone)
262 {
263 return 0; //TODO: Find out why events are get despite of cursor should be off
264 }
265*/
266 const TPointerEvent* pointerEvent = aWsEvent.Pointer();
267 const TPoint mousePos = EpocSdlEnv::WindowCoordinates(pointerEvent->iPosition);
268
269 /*!! TODO Pointer do not yet work properly
270 //SDL_TRACE1("SDL: EPOC_HandleWsEvent, pointerEvent->iType=%d", pointerEvent->iType); //!!
271
272 if (Private->EPOC_ShrinkedHeight) {
273 mousePos.iY <<= 1; // Scale y coordinate to shrinked screen height
274 }
275 if (Private->EPOC_ShrinkedWidth) {
276 mousePos.iX <<= 1; // Scale x coordinate to shrinked screen width
277 }
278 */
279
280 posted += SDL_PrivateMouseMotion(0, 0, mousePos.iX, mousePos.iY); /* Absolute position on screen */
281
282 switch (pointerEvent->iType)
283 {
284 case TPointerEvent::EButton1Down:
285 posted += SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_LEFT, 0, 0);
286 break;
287 case TPointerEvent::EButton1Up:
288 posted += SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_LEFT, 0, 0);
289 break;
290 case TPointerEvent::EButton2Down:
291 posted += SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_RIGHT, 0, 0);
292 break;
293 case TPointerEvent::EButton2Up:
294 posted += SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_RIGHT, 0, 0);
295 break;
296 case TPointerEvent::EButton3Down:
297 posted += SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_MIDDLE, 0, 0);
298 break;
299 case TPointerEvent::EButton3Up:
300 posted += SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_MIDDLE, 0, 0);
301 break;
302 } // switch
303 break;
304 }
305
306 case EEventKeyDown: /* Key events */
307 {
308#ifdef SYMBIAN_CRYSTAL
309 // special case: 9300/9500 rocker down, simulate left mouse button
310 if (aWsEvent.Key()->iScanCode == EStdKeyDeviceA)
311 {
312 const TPointerCursorMode mode = Private->EPOC_WsSession.PointerCursorMode();
313 if(mode != EPointerCursorNone)
314 posted += SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_LEFT, 0, 0);
315 }
316#endif
317 (void*)TranslateKey(_this, aWsEvent.Key()->iScanCode, &keysym);
318
319#ifndef DISABLE_JOYSTICK
320 /* Special handling */
321 switch((int)keysym.sym) {
322 case SDLK_CAPSLOCK:
323 if (!isCursorVisible) {
324 /* Enable virtual cursor */
325 HAL::Set(HAL::EMouseState, HAL::EMouseState_Visible);
326 }
327 else {
328 /* Disable virtual cursor */
329 HAL::Set(HAL::EMouseState, HAL::EMouseState_Invisible);
330 }
331 isCursorVisible = !isCursorVisible;
332 break;
333 }
334#endif
335 posted += SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
336 break;
337 }
338
339 case EEventKeyUp: /* Key events */
340 {
341#ifdef SYMBIAN_CRYSTAL
342 // special case: 9300/9500 rocker up, simulate left mouse button
343 if (aWsEvent.Key()->iScanCode == EStdKeyDeviceA)
344 {
345 posted += SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_LEFT, 0, 0);
346 }
347#endif
348 posted += SDL_PrivateKeyboard(SDL_RELEASED, TranslateKey(_this, aWsEvent.Key()->iScanCode, &keysym));
349 break;
350 }
351
352 case EEventFocusGained: /* SDL window got focus */
353 {
354 Private->iIsWindowFocused = ETrue;
355 posted += SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS);
356 /* Draw window background and screen buffer */
357 DisableKeyBlocking(_this); //Markus: guess why:-)
358
359 //RedrawWindowL(_this);
360 break;
361 }
362
363 case EEventFocusLost: /* SDL window lost focus */
364 {
365
366 Private->iIsWindowFocused = EFalse;
367
368 posted += SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS);
369
370
371 break;
372 }
373
374 case EEventModifiersChanged:
375 {
376 TModifiersChangedEvent* modEvent = aWsEvent.ModifiersChanged();
377 TUint modstate = KMOD_NONE;
378 if (modEvent->iModifiers == EModifierLeftShift)
379 modstate |= KMOD_LSHIFT;
380 if (modEvent->iModifiers == EModifierRightShift)
381 modstate |= KMOD_RSHIFT;
382 if (modEvent->iModifiers == EModifierLeftCtrl)
383 modstate |= KMOD_LCTRL;
384 if (modEvent->iModifiers == EModifierRightCtrl)
385 modstate |= KMOD_RCTRL;
386 if (modEvent->iModifiers == EModifierLeftAlt)
387 modstate |= KMOD_LALT;
388 if (modEvent->iModifiers == EModifierRightAlt)
389 modstate |= KMOD_RALT;
390 if (modEvent->iModifiers == EModifierLeftFunc)
391 modstate |= KMOD_LMETA;
392 if (modEvent->iModifiers == EModifierRightFunc)
393 modstate |= KMOD_RMETA;
394 if (modEvent->iModifiers == EModifierCapsLock)
395 modstate |= KMOD_CAPS;
396 SDL_SetModState(STATIC_CAST(SDLMod,(modstate | KMOD_LSHIFT)));
397 break;
398 }
399 case EEventScreenDeviceChanged:
400 {
401 EpocSdlEnv::WaitDeviceChange();
402 }
403 break;
404 default:
405 break;
406 }
407
408 return posted;
409}
410
411extern "C" {
412
413void EPOC_PumpEvents(_THIS)
414 {
415 MEventQueue& events = EpocSdlEnv::EventQueue();
416 while(events.HasData())
417 {
418 events.Lock();
419
420 //there have to be a copy, so we can release
421 //lock immediately. HandleWsEvent may cause
422 //deadlock otherwise.
423
424 const TWsEvent event = events.Shift();
425 events.Unlock();
426// const TWsEvent& event = events.Top();
427 EPOC_HandleWsEvent(_this, event);
428// events.Shift();
429 }
430 }
431
432
433
434void EPOC_InitOSKeymap(_THIS)
435 {
436 ResetKeyMap();
437 EpocSdlEnv::ObserverEvent(MSDLObserver::EEventKeyMapInit ,0);
438 }
439
440static SDL_keysym *TranslateKey(_THIS, int scancode, SDL_keysym *keysym)
441{
442// char debug[256];
443 //SDL_TRACE1("SDL: TranslateKey, scancode=%d", scancode); //!!
444
445 /* Set the keysym information */
446
447 keysym->scancode = scancode;
448
449 if ((scancode >= MAX_SCANCODE) &&
450 ((scancode - ENonCharacterKeyBase + 0x0081) >= MAX_SCANCODE)) {
451 SDL_SetError("Too big scancode");
452 keysym->scancode = SDLK_UNKNOWN;
453 keysym->mod = KMOD_NONE;
454 return keysym;
455 }
456
457 keysym->mod = SDL_GetModState();
458
459 /* Handle function keys: F1, F2, F3 ... */
460 if (keysym->mod & KMOD_META) {
461 if (scancode >= 'A' && scancode < ('A' + 24)) { /* first 32 alphabet keys */
462 switch(scancode) {
463 case 'Q': scancode = EStdKeyF1; break;
464 case 'W': scancode = EStdKeyF2; break;
465 case 'E': scancode = EStdKeyF3; break;
466 case 'R': scancode = EStdKeyF4; break;
467 case 'T': scancode = EStdKeyF5; break;
468 case 'Y': scancode = EStdKeyF6; break;
469 case 'U': scancode = EStdKeyF7; break;
470 case 'I': scancode = EStdKeyF8; break;
471 case 'A': scancode = EStdKeyF9; break;
472 case 'S': scancode = EStdKeyF10; break;
473 case 'D': scancode = EStdKeyF11; break;
474 case 'F': scancode = EStdKeyF12; break;
475 }
476 keysym->sym = keymap[scancode];
477 }
478 }
479
480 if (scancode >= ENonCharacterKeyBase) {
481 // Non character keys
482 keysym->sym = keymap[scancode -
483 ENonCharacterKeyBase + 0x0081]; // !!hard coded
484 } else {
485 keysym->sym = keymap[scancode];
486 }
487
488 /* Remap the arrow keys if the device is rotated */
489/*
490 if (Private->EPOC_ScreenOrientation == CFbsBitGc::EGraphicsOrientationRotated270) {
491 switch(keysym->sym) {
492 case SDLK_UP: keysym->sym = SDLK_LEFT; break;
493 case SDLK_DOWN: keysym->sym = SDLK_RIGHT; break;
494 case SDLK_LEFT: keysym->sym = SDLK_DOWN; break;
495 case SDLK_RIGHT:keysym->sym = SDLK_UP; break;
496 }
497 }
498*/
499 /* If UNICODE is on, get the UNICODE value for the key */
500 keysym->unicode = 0;
501
502#if 0 // !!TODO:unicode
503
504 if ( SDL_TranslateUNICODE )
505 {
506 /* Populate the unicode field with the ASCII value */
507 keysym->unicode = scancode;
508 }
509#endif
510
511 //!!
512 //sprintf(debug, "SDL: TranslateKey: keysym->scancode=%d, keysym->sym=%d, keysym->mod=%d",
513 // keysym->scancode, keysym->sym, keysym->mod);
514 //SDL_TRACE(debug); //!!
515
516 return(keysym);
517}
518
519} /* extern "C" */
520
521
diff --git a/apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocvideo.cpp b/apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocvideo.cpp
deleted file mode 100644
index c15506ddc0..0000000000
--- a/apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocvideo.cpp
+++ /dev/null
@@ -1,594 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_epocvideo.cpp
25 Epoc based SDL video driver implementation
26
27 Markus Mertama
28*/
29
30
31
32#include "epoc_sdl.h"
33
34#include <stdlib.h>
35#include <stdio.h>
36#include <string.h>
37
38extern "C" {
39#include "SDL_error.h"
40#include "SDL_timer.h"
41#include "SDL_video.h"
42#undef NULL
43#include "SDL_pixels_c.h"
44#include "SDL.h"
45#include "SDL_mouse.h"
46}
47
48#include "SDL_epocvideo.h"
49#include "SDL_epocevents_c.h"
50
51
52
53#include <coedef.h>
54#include <flogger.h>
55
56#include <eikenv.h>
57#include <eikappui.h>
58#include <eikapp.h>
59#include "sdlepocapi.h"
60
61
62////////////////////////////////////////////////////////////////
63
64
65
66
67_LIT(KLibName, "SDL");
68
69void RDebug_Print_b(char* error_str, void* param)
70 {
71 TBuf8<128> error8((TUint8*)error_str);
72 TBuf<128> error;
73 error.Copy(error8);
74
75#ifndef TRACE_TO_FILE
76 if (param) //!! Do not work if the parameter is really 0!!
77 RDebug::Print(error, param);
78 else
79 RDebug::Print(error);
80#else
81 if (param) //!! Do not work if the parameter is really 0!!
82 RFileLogger::WriteFormat(KLibName, _L("SDL.txt"), EFileLoggingModeAppend, error, param);
83 else
84 RFileLogger::Write(KLibName, _L("SDL.txt"), EFileLoggingModeAppend, error);
85#endif
86
87 }
88
89extern "C" void RDebug_Print(char* error_str, void* param)
90 {
91 RDebug_Print_b(error_str, param);
92 }
93
94/*
95int Debug_AvailMem2()
96 {
97 //User::CompressAllHeaps();
98 TMemoryInfoV1Buf membuf;
99 User::LeaveIfError(UserHal::MemoryInfo(membuf));
100 TMemoryInfoV1 minfo = membuf();
101 return(minfo.iFreeRamInBytes);
102 }
103
104extern "C" int Debug_AvailMem()
105 {
106 return(Debug_AvailMem2());
107 }
108
109*/
110
111extern "C" {
112
113/* Initialization/Query functions */
114
115static int EPOC_VideoInit(_THIS, SDL_PixelFormat *vformat);
116static SDL_Rect **EPOC_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
117static SDL_Surface *EPOC_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
118static int EPOC_SetColors(_THIS, int firstcolor, int ncolors,
119 SDL_Color *colors);
120static void EPOC_VideoQuit(_THIS);
121
122/* Hardware surface functions */
123
124static int EPOC_AllocHWSurface(_THIS, SDL_Surface *surface);
125static int EPOC_LockHWSurface(_THIS, SDL_Surface *surface);
126static int EPOC_FlipHWSurface(_THIS, SDL_Surface *surface);
127static void EPOC_UnlockHWSurface(_THIS, SDL_Surface *surface);
128static void EPOC_FreeHWSurface(_THIS, SDL_Surface *surface);
129static void EPOC_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
130
131static int EPOC_Available(void);
132static SDL_VideoDevice *EPOC_CreateDevice(int devindex);
133
134void DrawBackground(_THIS);
135void DirectDraw(_THIS, int numrects, SDL_Rect *rects, TUint16* screenBuffer);
136void DirectDrawRotated(_THIS, int numrects, SDL_Rect *rects, TUint16* screenBuffer);
137
138/* Mouse functions */
139
140static WMcursor *EPOC_CreateWMCursor(_THIS, Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
141static void EPOC_FreeWMCursor(_THIS, WMcursor *cursor);
142static int EPOC_ShowWMCursor(_THIS, WMcursor *cursor);
143}
144
145
146extern "C"
147 {
148 struct WMcursor
149 {
150 };
151 }
152
153/* Epoc video driver bootstrap functions */
154
155
156static int EPOC_Available(void)
157 {
158 return 1; /* Always available */
159 }
160
161static void EPOC_DeleteDevice(SDL_VideoDevice *device)
162 {
163 User::Free(device->hidden);
164 User::Free(device);
165 }
166
167static SDL_VideoDevice *EPOC_CreateDevice(int /*devindex*/)
168 {
169 SDL_VideoDevice *device;
170
171 SDL_TRACE("SDL:EPOC_CreateDevice");
172
173 /* Allocate all variables that we free on delete */
174 device = static_cast<SDL_VideoDevice*>(User::Alloc(sizeof(SDL_VideoDevice)));
175 if ( device )
176 {
177 Mem::FillZ(device, (sizeof *device));
178 device->hidden = static_cast<struct SDL_PrivateVideoData*>
179 (User::Alloc((sizeof *device->hidden)));
180 }
181 if ( (device == NULL) || (device->hidden == NULL) )
182 {
183 SDL_OutOfMemory();
184 if ( device ) {
185 User::Free(device);
186 }
187 return(0);
188 }
189 Mem::FillZ(device->hidden, (sizeof *device->hidden));
190
191 /* Set the function pointers */
192 device->VideoInit = EPOC_VideoInit;
193 device->ListModes = EPOC_ListModes;
194 device->SetVideoMode = EPOC_SetVideoMode;
195 device->SetColors = EPOC_SetColors;
196 device->UpdateRects = NULL;
197 device->VideoQuit = EPOC_VideoQuit;
198 device->AllocHWSurface = EPOC_AllocHWSurface;
199 device->CheckHWBlit = NULL;
200 device->FillHWRect = NULL;
201 device->SetHWColorKey = NULL;
202 device->SetHWAlpha = NULL;
203 device->LockHWSurface = EPOC_LockHWSurface;
204 device->UnlockHWSurface = EPOC_UnlockHWSurface;
205 device->FlipHWSurface = EPOC_FlipHWSurface;
206 device->FreeHWSurface = EPOC_FreeHWSurface;
207 device->SetIcon = NULL;
208 device->SetCaption = NULL;
209 device->GetWMInfo = NULL;
210 device->FreeWMCursor = EPOC_FreeWMCursor;
211 device->CreateWMCursor = EPOC_CreateWMCursor;
212 device->ShowWMCursor = EPOC_ShowWMCursor;
213 device->WarpWMCursor = NULL;
214 device->InitOSKeymap = EPOC_InitOSKeymap;
215 device->PumpEvents = EPOC_PumpEvents;
216 device->free = EPOC_DeleteDevice;
217
218 return device;
219}
220
221
222VideoBootStrap EPOC_bootstrap = {
223 "epoc\0\0\0", "EPOC system",
224 EPOC_Available, EPOC_CreateDevice
225};
226
227
228
229void DisableKeyBlocking(_THIS)
230 {
231 EpocSdlEnv::Request(EpocSdlEnv::EDisableKeyBlocking);
232 }
233
234void ConstructWindowL(_THIS)
235 {
236 SDL_TRACE("SDL:ConstructWindowL");
237 DisableKeyBlocking(_this); //disable key blocking
238 }
239
240
241int EPOC_VideoInit(_THIS, SDL_PixelFormat *vformat)
242 {
243 /* Construct Epoc window */
244
245 ConstructWindowL(_this);
246
247 /* Initialise Epoc frame buffer */
248
249
250 const TDisplayMode displayMode = EpocSdlEnv::DisplayMode();
251
252 /* The "best" video format should be returned to caller. */
253
254 vformat->BitsPerPixel = TDisplayModeUtils::NumDisplayModeBitsPerPixel(displayMode);
255 vformat->BytesPerPixel = TDisplayModeUtils::NumDisplayModeBitsPerPixel(displayMode) / 8;
256
257
258 //?? Private->iWindow->PointerFilter(EPointerFilterDrag, 0);
259
260 Private->iScreenPos = TPoint(0, 0);
261
262 Private->iRect.x = Private->iScreenPos.iX;
263 Private->iRect.y = Private->iScreenPos.iY;
264
265 const TSize sz = EpocSdlEnv::WindowSize();
266
267 Private->iRect.w = sz.iWidth;
268 Private->iRect.h = sz.iHeight;
269 Private->iRectPtr = &Private->iRect;
270
271 return(0);
272 }
273
274
275SDL_Rect **EPOC_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
276 {
277 if(flags & SDL_HWSURFACE)
278 {
279 if(format->BytesPerPixel != 4) //in HW only full color is supported
280 return NULL;
281 }
282 if(flags & SDL_FULLSCREEN)
283 {
284 return &Private->iRectPtr;
285 }
286 return (SDL_Rect **)(-1); //everythingisok, unless too small shoes
287 }
288
289
290int EPOC_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
291 {
292 if ((firstcolor+ncolors) > 256)
293 return -1;
294 TUint32 palette[256];
295 const TDisplayMode mode = EpocSdlEnv::DisplayMode();
296 if(TDisplayModeUtils::NumDisplayModeColors(mode) == 4096)
297 {
298 // Set 12 bit palette
299 for(int i = firstcolor; i < ncolors; i++)
300 {
301 // 4k value: 0000 rrrr gggg bbbb
302 TUint32 color4K = (colors[i].r & 0x0000f0) << 4;
303 color4K |= (colors[i].g & 0x0000f0);
304 color4K |= (colors[i].b & 0x0000f0) >> 4;
305 palette[i] = color4K;
306 }
307 }
308 else if(TDisplayModeUtils::NumDisplayModeColors(mode) == 65536)
309 {
310 for(int i = firstcolor; i < ncolors; i++)
311 {
312 // 64k-colour displays effectively support RGB values
313 // with 5 bits allocated to red, 6 to green and 5 to blue
314 // 64k value: rrrr rggg gggb bbbb
315 TUint32 color64K = (colors[i].r & 0x0000f8) << 8;
316 color64K |= (colors[i].g & 0x0000fc) << 3;
317 color64K |= (colors[i].b & 0x0000f8) >> 3;
318 palette[i] = color64K;
319 }
320 }
321 else if(TDisplayModeUtils::NumDisplayModeColors(mode) == 16777216)
322 {
323 for(int i = firstcolor; i < ncolors; i++)
324 {
325 // 16M-colour
326 //0000 0000 rrrr rrrr gggg gggg bbbb bbbb
327 TUint32 color16M = colors[i].r << 16;
328 color16M |= colors[i].g << 8;
329 color16M |= colors[i].b;
330 palette[i] = color16M;
331 }
332 }
333 else
334 {
335 return -2;
336 }
337 if(EpocSdlEnv::SetPalette(firstcolor, ncolors, palette) == KErrNone)
338 return 0;
339 return -1;
340 }
341
342
343/*
344void AllocHWSurfaceL(CFbsBitmap*& aBitmap, const TDisplayMode& aMode, const TSize& aSize)
345 {
346 aBitmap = new (ELeave) CFbsBitmap();
347 if(KErrNone != aBitmap->CreateHardwareBitmap(aSize, aMode,
348 EpocSdlEnv::EikonEnv().EikAppUi()->Application()->AppDllUid()))
349 //...if it fails - should we use wsbitmaps???
350 {//the good reason to use hw bitmaps is that they wont need lock heap
351 PANIC_IF_ERROR(aBitmap->Create(aSize, aMode));
352 }
353 }
354
355int CreateSurfaceL(_THIS, SDL_Surface* surface)
356 {
357 __ASSERT_ALWAYS(Private->iFrame == NULL, PANIC(KErrAlreadyExists));
358;
359 TInt dmode = EColorLast;
360
361 TDisplayMode displayMode;
362 EpocSdlEnv::GetDiplayMode(displayMode);
363
364 if(
365 TDisplayModeUtils::NumDisplayModeBitsPerPixel(displayMode)
366 == surface->format->BitsPerPixel)
367 {
368 dmode = displayMode;
369 }
370 else
371 {
372 --dmode;
373 while(TDisplayModeUtils::IsDisplayModeColor(TDisplayMode(dmode)) &&
374 TDisplayModeUtils::NumDisplayModeBitsPerPixel(TDisplayMode(dmode)) !=
375 surface->format->BitsPerPixel)
376 --dmode;
377 }
378
379 __ASSERT_ALWAYS(TDisplayModeUtils::IsDisplayModeColor(TDisplayMode(dmode)), PANIC(KErrNotSupported));
380 TRAPD(err, AllocHWSurfaceL(Private->iFrame, TDisplayMode(dmode), TSize(surface->w, surface->h)));
381 return err == KErrNone ? 0 : -1;
382 }
383*/
384
385TDisplayMode GetDisplayMode(TInt aBitsPerPixel)
386 {
387 const TDisplayMode displayMode = EpocSdlEnv::DisplayMode();
388 TInt dmode = EColorLast;
389 if(
390 TDisplayModeUtils::NumDisplayModeBitsPerPixel(displayMode)
391 == aBitsPerPixel)
392 {
393 dmode = displayMode;
394 }
395 else
396 {
397 --dmode;
398 while(TDisplayModeUtils::IsDisplayModeColor(TDisplayMode(dmode)) &&
399 TDisplayModeUtils::NumDisplayModeBitsPerPixel(TDisplayMode(dmode)) !=
400 aBitsPerPixel)
401 --dmode;
402 }
403 return TDisplayMode(dmode);
404 }
405
406SDL_Surface *EPOC_SetVideoMode(_THIS, SDL_Surface *current,
407 int width, int height, int bpp, Uint32 flags)
408 {
409 const TSize screenSize = EpocSdlEnv::WindowSize(TSize(width, height));
410 if(width > screenSize.iWidth || height > screenSize.iHeight)
411 {
412 if(flags & SDL_FULLSCREEN)
413 {
414 width = screenSize.iWidth;
415 height = screenSize.iHeight;
416 }
417 else
418 return NULL;
419 }
420
421 if(current && current->pixels)
422 {
423 // free(current->pixels);
424 current->pixels = NULL;
425 }
426
427 if(!SDL_ReallocFormat(current, bpp, 0, 0, 0, 0))
428 {
429 return(NULL);
430 }
431
432 current->flags = 0;
433 if(width == screenSize.iWidth && height == screenSize.iHeight)
434 current->flags |= SDL_FULLSCREEN;
435
436 const int numBytesPerPixel = ((bpp-1)>>3) + 1;
437 current->pitch = numBytesPerPixel * width; // Number of bytes in scanline
438
439 /* Set up the new mode framebuffer */
440 current->flags |= SDL_PREALLOC;
441
442 if(bpp <= 8)
443 current->flags |= SDL_HWPALETTE;
444
445 User::Free(Private->iSwSurface);
446 current->pixels = NULL;
447 Private->iSwSurface = NULL;
448
449 if(flags & SDL_HWSURFACE)
450 {
451 current->flags |= SDL_HWSURFACE;
452 // current->pixels = NULL;
453 // Private->iSwSurface = NULL;
454 }
455 else
456 {
457 current->flags |= SDL_SWSURFACE;
458 const TInt surfacesize = width * height * numBytesPerPixel;
459 Private->iSwSurfaceSize = TSize(width, height);
460 delete Private->iSwSurface;
461 Private->iSwSurface = NULL;
462 current->pixels = (TUint8*) User::AllocL(surfacesize);
463 Private->iSwSurface = (TUint8*) current->pixels;
464 const TInt err = EpocSdlEnv::AllocSwSurface
465 (TSize(width, height), GetDisplayMode(current->format->BitsPerPixel));
466 if(err != KErrNone)
467 return NULL;
468 }
469
470 current->w = width;
471 current->h = height;
472
473
474
475 /* Set the blit function */
476 _this->UpdateRects = EPOC_DirectUpdate;
477
478 /*
479 * Logic for getting suitable screen dimensions, offset, scaling and orientation
480 */
481
482
483 /* Centralize game window on device screen */
484
485
486 Private->iScreenPos.iX = Max(0, (screenSize.iWidth - width) / 2);
487 Private->iScreenPos.iY = Max(0, (screenSize.iHeight - height) / 2);
488
489 // delete (Private->iFrame);
490// Private->iFrame = NULL;
491
492 // TRAPD(err, CreateSurfaceL(_this, current));
493 // PANIC_IF_ERROR(err);
494
495 SDL_TRACE1("View width %d", width);
496 SDL_TRACE1("View height %d", height);
497 SDL_TRACE1("View bmode %d", bpp);
498 SDL_TRACE1("View x %d", Private->iScreenPos.iX);
499 SDL_TRACE1("View y %d", Private->iScreenPos.iY);
500
501 EpocSdlEnv::LockPalette(EFalse);
502 /* We're done */
503 return(current);
504}
505
506
507
508static int EPOC_AllocHWSurface(_THIS, SDL_Surface* surface)
509 {
510 return KErrNone == EpocSdlEnv::AllocHwSurface(TSize(surface->w, surface->h), GetDisplayMode(surface->format->BitsPerPixel));
511 }
512
513static void EPOC_FreeHWSurface(_THIS, SDL_Surface* /*surface*/)
514 {
515 }
516
517static int EPOC_LockHWSurface(_THIS, SDL_Surface* surface)
518 {
519 if(EpocSdlEnv::IsDsaAvailable())
520 {
521 TUint8* address = EpocSdlEnv::LockHwSurface();
522 if(address != NULL)
523 {
524 surface->pixels = address;
525 return 1;
526 }
527 }
528 return 0;
529 }
530static void EPOC_UnlockHWSurface(_THIS, SDL_Surface* /*surface*/)
531 {
532 EpocSdlEnv::UnlockHwSurface();
533 }
534
535static int EPOC_FlipHWSurface(_THIS, SDL_Surface* /*surface*/)
536 {
537 return(0);
538 }
539
540static void EPOC_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
541 {
542 if(EpocSdlEnv::IsDsaAvailable())
543 {
544 if(Private->iSwSurface)
545 {
546 const TRect target(Private->iScreenPos, Private->iSwSurfaceSize);
547 for(TInt i = 0; i < numrects ;i++)
548 {
549 const TRect rect(TPoint(rects[i].x, rects[i].y),
550 TSize(rects[i].w, rects[i].h));
551 if(!EpocSdlEnv::AddUpdateRect(Private->iSwSurface, rect, target))
552 return; //not succesful
553 }
554 EpocSdlEnv::UpdateSwSurface();
555 }
556 SDL_PauseAudio(0);
557 }
558 else
559 {
560 SDL_PauseAudio(1);
561 EpocSdlEnv::WaitDsaAvailable();
562 }
563 }
564
565
566/* Note: If we are terminated, this could be called in the middle of
567 another SDL video routine -- notably UpdateRects.
568*/
569void EPOC_VideoQuit(_THIS)
570 {
571// delete Private->iFrame;
572// Private->iFrame = NULL;
573 User::Free(Private->iSwSurface);
574 Private->iSwSurface = NULL;
575 EpocSdlEnv::FreeSurface();
576 }
577
578
579
580
581WMcursor *EPOC_CreateWMCursor(_THIS, Uint8* /*data*/, Uint8* /*mask*/, int /*w*/, int /*h*/, int /*hot_x*/, int /*hot_y*/)
582 {
583 return (WMcursor*) 1; //hii! prevents SDL to view a std cursor
584 }
585
586void EPOC_FreeWMCursor(_THIS, WMcursor* /*cursor*/)
587 {
588 }
589
590int EPOC_ShowWMCursor(_THIS, WMcursor *cursor)
591 {
592 return true;
593 }
594
diff --git a/apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocvideo.h b/apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocvideo.h
deleted file mode 100644
index 5aa3a20248..0000000000
--- a/apps/plugins/sdl/src/video/symbian/EKA2/SDL_epocvideo.h
+++ /dev/null
@@ -1,51 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23#ifndef EPOCVIDEO_H
24#define EPOCVIDEO_H
25
26#include<w32std.h>
27
28/* Hidden "this" pointer for the video functions */
29#define _THIS SDL_VideoDevice *_this
30#define Private _this->hidden
31
32class CFbsBitmap;
33
34struct SDL_VideoDevice;
35void DisableKeyBlocking(SDL_VideoDevice*);
36
37struct SDL_PrivateVideoData
38 {
39 TPoint iScreenPos;
40 TBool iIsWindowFocused;
41 TSize iSwSurfaceSize;
42 TUint8* iSwSurface;
43 SDL_Rect iRect; //same info in SDL format
44 SDL_Rect* iRectPtr;
45 };
46
47#endif
48
49
50
51
diff --git a/apps/plugins/sdl/src/video/symbian/EKA2/dsa.cpp b/apps/plugins/sdl/src/video/symbian/EKA2/dsa.cpp
deleted file mode 100644
index 07b1ab4137..0000000000
--- a/apps/plugins/sdl/src/video/symbian/EKA2/dsa.cpp
+++ /dev/null
@@ -1,1505 +0,0 @@
1#include "dsa.h"
2#include "sdlepocapi.h"
3#include <cdsb.h>
4
5
6LOCAL_C TInt BytesPerPixel(TDisplayMode aMode)
7 {
8 return ((TDisplayModeUtils::NumDisplayModeBitsPerPixel(aMode) - 1) >> 3) + 1;
9 }
10
11
12
13
14template<class T>
15NONSHARABLE_CLASS(CBitmapSurface) : public T
16 {
17public:
18 CBitmapSurface(RWsSession& aSession);
19private:
20 void ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice);
21 ~CBitmapSurface();
22 TUint8* LockSurface();
23 void UnlockHwSurface();
24 void CreateSurfaceL();
25 void Wipe(TInt aLength);
26 void Free();
27 void Update(CFbsBitmap& aBmp);
28 TInt ExternalUpdate();
29private:
30 CFbsBitmap* iBmp;
31 CFbsBitmap* iCopyBmp;
32 };
33
34
35template<class T>
36void CBitmapSurface<T>::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
37 {
38 delete iCopyBmp;
39 iCopyBmp = NULL;
40 iCopyBmp = new (ELeave) CFbsBitmap();
41 T::ConstructL(aWindow, aDevice);
42 }
43
44template<class T>
45CBitmapSurface<T>::CBitmapSurface(RWsSession& aSession) : T(aSession)
46 {
47 }
48
49template<class T>
50void CBitmapSurface<T>::Free()
51 {
52 delete iBmp;
53 iBmp = NULL;
54 T::Free();
55 }
56
57template<class T>
58CBitmapSurface<T>::~CBitmapSurface()
59 {
60 __ASSERT_DEBUG(iBmp == NULL, PANIC(KErrNotReady));
61 delete iCopyBmp;
62 }
63
64template<class T>
65TUint8* CBitmapSurface<T>::LockSurface()
66 {
67 iBmp->LockHeap();
68 return reinterpret_cast<TUint8*>(iBmp->DataAddress());
69 }
70
71
72template<class T>
73void CBitmapSurface<T>::UnlockHwSurface()
74 {
75 iBmp->UnlockHeap();
76 T::SetUpdating(EFalse);
77 Update(*iBmp);
78 }
79
80
81template<class T>
82void CBitmapSurface<T>::Update(CFbsBitmap& aBmp)
83 {
84 if(!T::Blitter(aBmp))
85 {
86 if(T::SwSize() == T::HwRect().Size())
87 T::Gc().BitBlt(T::HwRect().iTl, &aBmp);
88 else
89 T::Gc().DrawBitmap(T::HwRect(), &aBmp);
90 }
91 T::DrawOverlays();
92 T::CompleteUpdate();
93 }
94
95template<class T>
96void CBitmapSurface<T>::CreateSurfaceL()
97 {
98 Free();
99 iBmp = new (ELeave) CFbsBitmap();
100 User::LeaveIfError(iBmp->Create(T::SwSize(), T::DisplayMode()));
101 T::CreateSurfaceL(*iBmp);
102 }
103
104template<class T>
105void CBitmapSurface<T>::Wipe(TInt aLength) //dont call in drawing
106 {
107 iBmp->LockHeap();
108 Mem::FillZ(iBmp->DataAddress(), aLength);
109 iBmp->UnlockHeap();
110 }
111
112template<class T>
113TInt CBitmapSurface<T>::ExternalUpdate()
114 {
115 if(iCopyBmp->Handle() == 0)
116 {
117 const TInt err = iCopyBmp->Duplicate(iBmp->Handle());
118 if(err != KErrNone)
119 return err;
120 }
121 Update(*iCopyBmp);
122 return KErrNone;
123 }
124
125
126//////////////////////////////////////////////////////////////////////
127
128
129
130NONSHARABLE_CLASS(CDsaBitgdi) : public CDsa
131 {
132public:
133 CDsaBitgdi(RWsSession& aSession);
134protected:
135 void ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice);
136 CBitmapContext& Gc();
137 void CompleteUpdate();
138 ~CDsaBitgdi();
139 void CreateSurfaceL(CFbsBitmap& aBmp);
140 void Free();
141 void UnlockHWSurfaceRequestComplete();
142private:
143 void Resume();
144
145 CFbsBitGc* iGc;
146 CFbsDevice* iDevice;
147 CFbsBitmap* iBitGdiBmp;
148 CWindowGc* iWinGc;
149 RWindow* iWindow;
150 TInt iHandle;
151 };
152
153
154CDsaBitgdi::CDsaBitgdi(RWsSession& aSession) : CDsa(aSession)
155 {
156 }
157
158CDsaBitgdi::~CDsaBitgdi()
159 {
160 delete iWinGc;
161 delete iBitGdiBmp;
162 }
163
164void CDsaBitgdi::CompleteUpdate()
165 {
166 EpocSdlEnv::Request(CDsa::ERequestUpdate);
167 }
168
169
170void CDsaBitgdi::UnlockHWSurfaceRequestComplete()
171 {
172 if(iHandle == 0)
173 return;
174
175 if(iBitGdiBmp == NULL)
176 {
177 iBitGdiBmp = new CFbsBitmap();
178 if(iBitGdiBmp == NULL)
179 return;
180 iBitGdiBmp->Duplicate(iHandle);
181 }
182
183 iWindow->Invalidate();
184
185 iWindow->BeginRedraw();
186 iWinGc->Activate(*iWindow);
187 iWinGc->BitBlt(TPoint(0, 0), iBitGdiBmp);
188 iWinGc->Deactivate();
189 iWindow->EndRedraw();
190 }
191
192void CDsaBitgdi::Resume()
193 {
194 Start();
195 }
196
197CBitmapContext& CDsaBitgdi::Gc()
198 {
199 return *iGc;
200 }
201
202 void CDsaBitgdi::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
203 {
204
205 delete iBitGdiBmp;
206 iBitGdiBmp = NULL;
207 delete iWinGc;
208 iWinGc = NULL;
209 iHandle = 0;
210
211 iWindow = &aWindow;
212 User::LeaveIfError(aDevice.CreateContext(iWinGc));
213 CDsa::ConstructL(aWindow, aDevice);
214 Start();
215 }
216
217void CDsaBitgdi::CreateSurfaceL(CFbsBitmap& aBmp)
218 {
219 iDevice = CFbsBitmapDevice::NewL(&aBmp);
220 User::LeaveIfError(iDevice->CreateContext(iGc));
221 iHandle = aBmp.Handle();
222 }
223
224void CDsaBitgdi::Free()
225 {
226 delete iGc;
227 iGc = NULL;
228 delete iDevice;
229 iDevice = NULL;
230 }
231
232////////////////////////////////////////////////////////////////////////
233///////////////////////////////////////////////////////////////////////
234
235NONSHARABLE_CLASS(CDsaBase) : public CDsa, public MDirectScreenAccess
236 {
237protected:
238 inline CDirectScreenAccess& Dsa() const;
239 CDsaBase(RWsSession& aSession);
240 ~CDsaBase();
241 void ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice);
242 void Stop();
243 void Resume();
244 CBitmapContext& Gc();
245protected:
246 CDirectScreenAccess* iDsa;
247private:
248 void AbortNow(RDirectScreenAccess::TTerminationReasons aReason);
249 void Restart(RDirectScreenAccess::TTerminationReasons aReason);
250private:
251 void RestartL();
252 };
253
254
255inline CDirectScreenAccess& CDsaBase::Dsa() const
256 {
257 return *iDsa;
258 }
259
260
261CDsaBase::CDsaBase(RWsSession& aSession) : CDsa(aSession)
262 {
263 }
264
265CBitmapContext& CDsaBase::Gc()
266 {
267 return *Dsa().Gc();
268 }
269
270void CDsaBase::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
271 {
272 CDsa::ConstructL(aWindow, aDevice);
273 if(iDsa != NULL)
274 {
275 iDsa->Cancel();
276 delete iDsa;
277 iDsa = NULL;
278 }
279
280 iDsa = CDirectScreenAccess::NewL(
281 Session(),
282 aDevice,
283 aWindow,
284 *this);
285 RestartL();
286 }
287
288void CDsaBase::Resume()
289 {
290 if(Stopped())
291 Restart(RDirectScreenAccess::ETerminateRegion);
292 }
293
294CDsaBase::~CDsaBase()
295 {
296 if(iDsa != NULL)
297 {
298 iDsa->Cancel();
299 }
300 delete iDsa;
301 }
302
303
304void CDsaBase::RestartL()
305 {
306
307
308 iDsa->StartL();
309
310 const RRegion* r = iDsa->DrawingRegion();
311 const TRect rect = r->BoundingRect();
312 iDsa->Gc()->SetClippingRegion(r);
313
314 if(rect != ScreenRect())
315 {
316 return ;
317 }
318
319
320 SetTargetRect();
321 RecreateL();
322
323 Start();
324
325
326 }
327
328void CDsaBase::AbortNow(RDirectScreenAccess::TTerminationReasons /*aReason*/)
329 {
330 Stop();
331 }
332
333void CDsaBase::Restart(RDirectScreenAccess::TTerminationReasons aReason)
334 {
335 if(aReason == RDirectScreenAccess::ETerminateRegion) //auto restart
336 {
337 TRAPD(err, RestartL());
338 PANIC_IF_ERROR(err);
339 }
340 }
341
342
343void CDsaBase::Stop()
344 {
345 CDsa::Stop();
346 iDsa->Cancel();
347 }
348
349
350 ///////////////////////////////////////////////////////////////////////
351 ///////////////////////////////////////////////////////////////////////
352NONSHARABLE_CLASS(TDsa)
353 {
354 public:
355 inline TDsa(const CDsa& aDsa);
356 inline TBool IsFlip() const;
357 inline TBool IsTurn() const;
358 inline const TSize& SwSize() const;
359 inline void Copy(TUint32* aTarget, const TUint8* aSrc, TInt aBytes, TInt aHeight) const;
360 private:
361 const CDsa& iDsa;
362 };
363
364
365
366
367inline TDsa::TDsa(const CDsa& aDsa) : iDsa(aDsa)
368 {
369 }
370
371inline TBool TDsa::IsTurn() const
372 {
373 return iDsa.iStateFlags & CDsa::EOrientation90;
374 }
375
376inline TBool TDsa::IsFlip() const
377 {
378 return iDsa.iStateFlags & CDsa::EOrientation180;
379 }
380
381inline const TSize& TDsa::SwSize() const
382 {
383 return iDsa.SwSize();
384 }
385
386inline void TDsa::Copy(TUint32* aTarget, const TUint8* aSrc, TInt aBytes, TInt aHeight) const
387 {
388 iDsa.iCopyFunction(iDsa, aTarget, aSrc, aBytes, aHeight);
389 }
390
391template<class T, class S>
392void ClipCopy(const TDsa& iDsa, TUint8* aTarget,
393 const TUint8* aSource,
394 const TRect& aUpdateRect,
395 const TRect& aSourceRect)
396 {
397 const S* source = reinterpret_cast<const S*>(aSource);
398 const TInt lineWidth = aSourceRect.Width();
399
400 source += (aUpdateRect.iTl.iY * lineWidth);
401 const TInt sourceStartOffset = aUpdateRect.iTl.iX;
402 source += sourceStartOffset;
403
404 T* targetPtr = reinterpret_cast<T*>(aTarget);
405
406 const TInt scanLineWidth = iDsa.SwSize().iWidth;
407
408 targetPtr += (aSourceRect.iTl.iY + aUpdateRect.iTl.iY ) * scanLineWidth;
409 const TInt targetStartOffset = (aUpdateRect.iTl.iX + aSourceRect.iTl.iX);
410
411 targetPtr += targetStartOffset;
412
413
414 const TInt height = aUpdateRect.Height();
415
416 const TInt lineMove = iDsa.IsTurn() ? 1 : lineWidth;
417 const TInt copyLen = aUpdateRect.Width();
418
419
420 if(iDsa.IsFlip())
421 {
422
423 targetPtr += scanLineWidth * (height - 1);
424
425 for(TInt i = 0; i < height; i++) //source is always smaller
426 {
427 iDsa.Copy(reinterpret_cast<TUint32*>(targetPtr), reinterpret_cast<const TUint8*>(source), copyLen, height);
428 source += lineMove;
429 targetPtr -= scanLineWidth;
430 }
431 }
432 else
433 {
434
435
436 for(TInt i = 0; i < height; i++) //source is always smaller
437 {
438 iDsa.Copy(reinterpret_cast<TUint32*>(targetPtr), reinterpret_cast<const TUint8*>(source), copyLen, height);
439 source += lineMove;
440 targetPtr += scanLineWidth; // >> 2;
441 }
442 }
443
444 }
445
446
447
448NONSHARABLE_CLASS(CDsaA) : public CDsaBase
449 {
450 public:
451 CDsaA(RWsSession& aSession);
452 protected:
453 void ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice);
454 void CompleteUpdate();
455 void CreateSurfaceL(CFbsBitmap& aBmp);
456 void Free();
457 void UnlockHWSurfaceRequestComplete();
458 };
459
460
461CDsaA::CDsaA(RWsSession& aSession) : CDsaBase(aSession)
462 {
463 }
464
465
466void CDsaA::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
467 {
468 CDsaBase::ConstructL(aWindow, aDevice);
469 }
470
471void CDsaA::CompleteUpdate()
472 {
473 iDsa->ScreenDevice()->Update();
474 }
475
476void CDsaA::CreateSurfaceL(CFbsBitmap& /*aBmp*/)
477 {
478 }
479
480void CDsaA::Free()
481 {
482
483 }
484
485void CDsaA::UnlockHWSurfaceRequestComplete()
486 {
487 PANIC(KErrNotSupported);
488 }
489
490
491
492//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
493
494NONSHARABLE_CLASS(MDsbObs)
495 {
496 public:
497 virtual void SurfaceReady() = 0;
498 virtual CDirectScreenBitmap& Dsb() = 0;
499 };
500
501NONSHARABLE_CLASS(CDsbSurface) : public CActive
502 {
503 public:
504 CDsbSurface(MDsbObs& aDsb);
505 TUint8* Address();
506 void Complete();
507 ~CDsbSurface();
508 private:
509 void RunL();
510 void DoCancel();
511 private:
512 MDsbObs& iDsb;
513 TUint8* iAddress;
514 };
515
516CDsbSurface::CDsbSurface(MDsbObs& aDsb) : CActive(CActive::EPriorityHigh) , iDsb(aDsb)
517 {
518 CActiveScheduler::Add(this);
519 }
520
521CDsbSurface::~CDsbSurface()
522 {
523 Cancel();
524 }
525
526void CDsbSurface::Complete()
527 {
528 if(iAddress != NULL && !IsActive())
529 {
530 iAddress = NULL;
531 SetActive();
532 iDsb.Dsb().EndUpdate(iStatus);
533 }
534 }
535
536TUint8* CDsbSurface::Address()
537 {
538 if(iAddress == NULL && !IsActive())
539 {
540 TAcceleratedBitmapInfo info;
541 if(KErrNone == iDsb.Dsb().BeginUpdate(info))
542 iAddress = info.iAddress;
543 }
544 return iAddress;
545 }
546
547void CDsbSurface::RunL()
548 {
549 iDsb.SurfaceReady();
550 }
551
552void CDsbSurface::DoCancel()
553 {
554 //empty
555 }
556
557NONSHARABLE_CLASS(CDsaB) : public CDsaBase,
558 public MDsbObs
559 {
560 public:
561 CDsaB(RWsSession& aSession, TInt aFlags);
562 private:
563 ~CDsaB();
564 TUint8* LockSurface();
565 void UnlockHWSurfaceRequestComplete();
566 void UnlockHwSurface();
567 void CreateSurfaceL();
568 void Wipe(TInt aLength);
569 void RecreateL();
570 void ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice);
571 CDirectScreenBitmap& Dsb();
572 void SurfaceReady();
573 TInt ExternalUpdate();
574 private:
575 CDsbSurface* iSurface1;
576 CDsbSurface* iSurface2;
577 CDirectScreenBitmap* iDsb;
578 TInt iType;
579 };
580
581CDsaB::CDsaB(RWsSession& aSession, TInt aFlags) : CDsaBase(aSession), iType(aFlags)
582 {
583 }
584
585
586
587void CDsaB::UnlockHWSurfaceRequestComplete()
588 {
589 iSurface1->Complete();
590 if(iSurface2 != NULL)
591 iSurface2->Complete();
592 }
593
594void CDsaB::CreateSurfaceL()
595 {
596 __ASSERT_ALWAYS(SwSize() == HwRect().Size(), PANIC(KErrNotSupported));
597 }
598
599void CDsaB::Wipe(TInt aLength) //dont call in drawing
600 {
601 TUint8* addr = LockSurface();
602 if(addr != NULL)
603 {
604 Mem::FillZ(addr, aLength);
605 UnlockHwSurface();
606 }
607 }
608
609
610void CDsaB::UnlockHwSurface()
611 {
612 EpocSdlEnv::Request(CDsa::ERequestUpdate);
613 }
614
615TUint8* CDsaB::LockSurface()
616 {
617 TUint8* addr = iSurface1->Address();
618 if(addr == NULL && iSurface2 != NULL)
619 addr = iSurface2->Address();
620 SetUpdating(addr == NULL);
621 return addr;
622 }
623
624void CDsaB::SurfaceReady()
625 {
626 SetUpdating(EFalse);
627 }
628
629CDirectScreenBitmap& CDsaB::Dsb()
630 {
631 return *iDsb;
632 }
633
634void CDsaB::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
635 {
636 if(iDsb == NULL)
637 iDsb = CDirectScreenBitmap::NewL();
638 CDsaBase::ConstructL(aWindow, aDevice);
639 if(iSurface1 == NULL)
640 iSurface1 = new (ELeave) CDsbSurface(*this);
641 if(iSurface2 == NULL && iType & CDirectScreenBitmap::EDoubleBuffer)
642 iSurface2 = new (ELeave) CDsbSurface(*this);
643 }
644
645CDsaB::~CDsaB()
646 {
647 delete iSurface1;
648 delete iSurface2;
649 delete iDsb;
650 }
651
652void CDsaB::RecreateL()
653 {
654 iDsb->Close();
655 iDsb->Create(HwRect(), CDirectScreenBitmap::TSettingsFlags(iType));
656 }
657
658TInt CDsaB::ExternalUpdate()
659 {
660 if(LockSurface())
661 {
662 UnlockHWSurfaceRequestComplete();
663 return KErrNone;
664 }
665 return KErrNotReady;
666 }
667
668
669/////////////////////////////////////////////////////////////////////////////////////////////////////
670
671
672
673CDsa* CDsa::CreateL(RWsSession& aSession)
674 {
675 if(EpocSdlEnv::Flags(CSDL::EDrawModeDSB))
676 {
677 TInt flags = CDirectScreenBitmap::ENone;
678 if(EpocSdlEnv::Flags(CSDL::EDrawModeDSBDoubleBuffer))
679 flags |= CDirectScreenBitmap::EDoubleBuffer;
680 if(EpocSdlEnv::Flags(CSDL::EDrawModeDSBIncrementalUpdate))
681 flags |= CDirectScreenBitmap::EIncrementalUpdate;
682 return new (ELeave) CDsaB(aSession, flags);
683 }
684 else if(EpocSdlEnv::Flags(CSDL::EDrawModeGdi))
685 {
686 return new (ELeave) CBitmapSurface<CDsaBitgdi>(aSession);
687 }
688 else
689 {
690 return new (ELeave) CBitmapSurface<CDsaA>(aSession);
691 }
692 }
693
694
695void CDsa::RecreateL()
696 {
697 }
698
699void CDsa::Free()
700 {
701 }
702
703TSize CDsa::WindowSize() const
704 {
705 TSize size = iSwSize;
706 if(iStateFlags & EOrientation90)
707 {
708 const TInt tmp = size.iWidth;
709 size.iWidth = size.iHeight;
710 size.iHeight = tmp;
711 }
712 return size;
713 }
714
715void CDsa::SetSuspend()
716 {
717 iStateFlags |= ESdlThreadSuspend;
718 }
719
720
721void CDsa::SetUpdating(TBool aUpdate)
722 {
723 if(aUpdate)
724 iStateFlags |= EUpdating;
725 else
726 iStateFlags &= ~EUpdating;
727 }
728
729
730TBool CDsa::Stopped() const
731 {
732 return (iStateFlags & ESdlThreadExplicitStop);
733 }
734
735void CDsa::SetOrientation(CSDL::TOrientationMode aOrientation)
736 {
737 TInt flags = 0;
738 switch(aOrientation)
739 {
740 case CSDL::EOrientation90:
741 flags = EOrientation90;
742 break;
743 case CSDL::EOrientation180:
744 flags = EOrientation180;
745 break;
746 case CSDL::EOrientation270:
747 flags = EOrientation90 | EOrientation180;
748 break;
749 case CSDL::EOrientation0:
750 flags = 0;
751 break;
752 }
753 if(flags != (iStateFlags & EOrientationFlags))
754 {
755 iStateFlags |= EOrientationChanged;
756 iNewFlags = flags; //cannot be set during drawing...
757 }
758 }
759
760CDsa::~CDsa()
761 {
762 iOverlays.Close();
763 User::Free(iLut256);
764 }
765
766void CDsa::ConstructL(RWindow& aWindow, CWsScreenDevice& /*aDevice*/)
767 {
768 if(iLut256 == NULL)
769 iLut256 = (TUint32*) User::AllocL(256 * sizeof(TUint32));
770 iTargetMode = aWindow.DisplayMode();
771 iTargetBpp = BytesPerPixel(DisplayMode());
772 iScreenRect = TRect(aWindow.Position(), aWindow.Size());
773 SetTargetRect();
774 }
775
776void CDsa::DrawOverlays()
777 {
778 const TInt last = iOverlays.Count() - 1;
779 for(TInt i = last; i >= 0 ; i--)
780 iOverlays[i].iOverlay->Draw(Gc(), HwRect(), SwSize());
781 }
782
783TInt CDsa::AppendOverlay(MOverlay& aOverlay, TInt aPriority)
784 {
785 TInt i;
786 for(i = 0; i < iOverlays.Count() && iOverlays[i].iPriority < aPriority; i++)
787 {}
788 const TOverlay overlay = {&aOverlay, aPriority};
789 return iOverlays.Insert(overlay, i);
790 }
791
792TInt CDsa::RemoveOverlay(MOverlay& aOverlay)
793 {
794 for(TInt i = 0; i < iOverlays.Count(); i++)
795 {
796 if(iOverlays[i].iOverlay == &aOverlay)
797 {
798 iOverlays.Remove(i);
799 return KErrNone;
800 }
801 }
802 return KErrNotFound;
803 }
804
805void CDsa::LockPalette(TBool aLock)
806 {
807 if(aLock)
808 iStateFlags |= EPaletteLocked;
809 else
810 iStateFlags &= ~EPaletteLocked;
811 }
812TInt CDsa::SetPalette(TInt aFirst, TInt aCount, TUint32* aPalette)
813 {
814 if(iLut256 == NULL)
815 return KErrNotFound;
816 const TInt count = aCount - aFirst;
817 if(count > 256)
818 return KErrArgument;
819 if(iStateFlags & EPaletteLocked)
820 return KErrNone;
821 for(TInt i = aFirst; i < count; i++) //not so busy here:-)
822 {
823 iLut256[i] = aPalette[i];
824 }
825 return KErrNone;
826 }
827
828
829
830
831
832CDsa::CDsa(RWsSession& aSession) :
833 iStateFlags(0),
834 iSession(aSession)
835
836 {
837// CActiveScheduler::Add(this);
838 iCFTable[0] = CopyMem;
839 iCFTable[1] = CopyMemFlipReversed;
840 iCFTable[2] = CopyMemReversed;
841 iCFTable[3] = CopyMemFlip;
842
843 iCFTable[4] = Copy256;
844 iCFTable[5] = Copy256FlipReversed;
845 iCFTable[6] = Copy256Reversed;
846 iCFTable[7] = Copy256Flip;
847
848
849 iCFTable[8] = CopySlow;
850 iCFTable[9] = CopySlowFlipReversed;
851 iCFTable[10] = CopySlowReversed;
852 iCFTable[11] = CopySlowFlip;
853 }
854
855RWsSession& CDsa::Session()
856 {
857 return iSession;
858 }
859
860TInt CDsa::RedrawRequest()
861 {
862 if(!(iStateFlags & (EUpdating) && (iStateFlags & ERunning)))
863 {
864 return ExternalUpdate();
865 }
866 return KErrNotReady;
867 }
868
869TUint8* CDsa::LockHwSurface()
870 {
871 if((iStateFlags & EUpdating) == 0) //else frame is skipped
872 {
873 return LockSurface();
874 }
875 return NULL;
876 }
877
878/*
879void CDsa::RunL()
880 {
881 iStateFlags &= ~EUpdating;
882 }
883
884
885void CDsa::DoCancel()
886 {
887 iStateFlags &= ~EUpdating;
888 //nothing can do, just wait?
889 }
890*/
891
892
893TInt CDsa::AllocSurface(TBool aHwSurface, const TSize& aSize, TDisplayMode aMode)
894 {
895 if(aHwSurface && aMode != DisplayMode())
896 return KErrArgument;
897
898 iSourceMode = aMode;
899
900 iSourceBpp = BytesPerPixel(aMode);
901
902 const TSize size = WindowSize();
903 if(aSize.iWidth > size.iWidth)
904 return KErrTooBig;
905 if(aSize.iHeight > size.iHeight)
906 return KErrTooBig;
907
908 TRAPD(err, CreateSurfaceL());
909 if(err != KErrNone)
910 return err;
911
912 SetCopyFunction();
913
914 return KErrNone;
915 }
916
917
918void CDsa::CreateZoomerL(const TSize& aSize)
919 {
920 iSwSize = aSize;
921 iStateFlags |= EResizeRequest;
922 CreateSurfaceL();
923 SetTargetRect();
924 }
925
926
927/*
928void SaveBmp(const TDesC& aName, const TAny* aData, TInt aLength, const TSize& aSz, TDisplayMode aMode)
929 {
930 CFbsBitmap* s = new CFbsBitmap();
931 s->Create(aSz, aMode);
932 s->LockHeap();
933 TUint32* addr = s->DataAddress();
934 Mem::Copy(addr, aData, aLength);
935 s->UnlockHeap();
936 s->Save(aName);
937 s->Reset();
938 delete s;
939 }
940
941void SaveBmp(const TDesC& aName, const TUint32* aData, const TSize& aSz)
942 {
943 CFbsBitmap* s = new CFbsBitmap();
944 s->Create(aSz, EColor64K);
945 TBitmapUtil bmp(s);
946 bmp.Begin(TPoint(0, 0));
947 for(TInt j = 0; j < aSz.iHeight; j++)
948 {
949 bmp.SetPos(TPoint(0, j));
950 for(TInt i = 0; i < aSz.iWidth; i++)
951 {
952 bmp.SetPixel(*aData);
953 aData++;
954 bmp.IncXPos();
955 }
956 }
957 bmp.End();
958 s->Save(aName);
959 s->Reset();
960 delete s;
961 }
962
963TBuf<16> FooName(TInt aFoo)
964 {
965 TBuf<16> b;
966 b.Format(_L("C:\\pic%d.mbm"), aFoo);
967 return b;
968 }
969
970*/
971
972
973void CDsa::ClipCopy(TUint8* aTarget,
974 const TUint8* aSource,
975 const TRect& aUpdateRect,
976 const TRect& aSourceRect) const
977 {
978 const TDsa dsa(*this);
979 switch(iSourceBpp)
980 {
981 case 1:
982 ::ClipCopy<TUint32, TUint8>(dsa, aTarget, aSource, aUpdateRect, aSourceRect);
983 break;
984 case 2:
985 ::ClipCopy<TUint32, TUint16>(dsa, aTarget, aSource, aUpdateRect, aSourceRect);
986 break;
987 case 4:
988 ::ClipCopy<TUint32, TUint32>(dsa, aTarget, aSource, aUpdateRect, aSourceRect);
989 break;
990 }
991 }
992
993
994void CDsa::Wipe() //dont call in drawing
995 {
996 if(IsDsaAvailable())
997 Wipe(iTargetBpp * SwSize().iWidth * SwSize().iHeight);
998 }
999
1000void CDsa::SetCopyFunction()
1001 {
1002 //calculate offset to correct function in iCFTable according to given parameters
1003 TInt function = 0;
1004 const TInt KCopyFunctions = 4;
1005 const TInt KOffsetToNative = 0;
1006 const TInt KOffsetTo256 = KOffsetToNative + KCopyFunctions;
1007 const TInt KOffsetToOtherModes = KOffsetTo256 + KCopyFunctions;
1008 const TInt KOffsetTo90Functions = 1;
1009 const TInt KOffsetTo180Functions = 2;
1010
1011 if(iSourceMode == DisplayMode())
1012 function = KOffsetToNative; //0
1013 else if(iSourceMode == EColor256)
1014 function = KOffsetTo256; //4
1015 else
1016 function = KOffsetToOtherModes; //8
1017
1018 if(iStateFlags & EOrientation90)
1019 function += KOffsetTo90Functions; // + 1
1020 if(iStateFlags & EOrientation180)
1021 function += KOffsetTo180Functions; //+ 2
1022
1023 iCopyFunction = iCFTable[function];
1024
1025 Wipe();
1026 }
1027
1028inline void Rotate(TRect& aRect)
1029 {
1030 const TInt dx = aRect.iBr.iX - aRect.iTl.iX;
1031 const TInt dy = aRect.iBr.iY - aRect.iTl.iY;
1032
1033 aRect.iBr.iX = aRect.iTl.iX + dy;
1034 aRect.iBr.iY = aRect.iTl.iY + dx;
1035
1036 const TInt tmp = aRect.iTl.iX;
1037 aRect.iTl.iX = aRect.iTl.iY;
1038 aRect.iTl.iY = tmp;
1039 }
1040
1041/*
1042int bar = 0;
1043*/
1044
1045TBool CDsa::AddUpdateRect(const TUint8* aBits, const TRect& aUpdateRect, const TRect& aRect)
1046 {
1047
1048 if(iStateFlags & EOrientationChanged)
1049 {
1050 iStateFlags &= ~EOrientationFlags;
1051 iStateFlags |= iNewFlags;
1052 SetCopyFunction();
1053 iStateFlags &= ~EOrientationChanged;
1054 EpocSdlEnv::WaitDeviceChange();
1055 return EFalse; //skip this frame as data is may be changed
1056 }
1057
1058 if(iTargetAddr == NULL)
1059 {
1060 iTargetAddr = LockHwSurface();
1061 }
1062
1063 TUint8* target = iTargetAddr;
1064 if(target == NULL)
1065 return EFalse;
1066
1067
1068 TRect targetRect = TRect(TPoint(0, 0), SwSize());
1069
1070 TRect sourceRect = aRect;
1071 TRect updateRect = aUpdateRect;
1072
1073// TPoint move(0, 0);
1074
1075
1076 if(iStateFlags & EOrientation90)
1077 {
1078 Rotate(sourceRect);
1079 Rotate(updateRect);
1080 }
1081
1082 if(iSourceMode != DisplayMode() || targetRect != sourceRect || targetRect != updateRect || ((iStateFlags & EOrientationFlags) != 0))
1083 {
1084 sourceRect.Intersection(targetRect); //so source always smaller or equal than target
1085 //updateRect.Intersection(targetRect);
1086 ClipCopy(target, aBits, updateRect, sourceRect);
1087 }
1088 else
1089 {
1090 const TInt byteCount = aRect.Width() * aRect.Height() * iSourceBpp; //this could be stored
1091 Mem::Copy(target, aBits, byteCount);
1092 }
1093
1094 return ETrue;
1095 }
1096
1097
1098void CDsa::UpdateSwSurface()
1099 {
1100 iTargetAddr = NULL;
1101 UnlockHwSurface(); //could be faster if does not use AO, but only check status before redraw, then no context switch needed
1102 }
1103
1104
1105
1106
1107void CDsa::DoStop()
1108 {
1109 if(IsDsaAvailable())
1110 iStateFlags |= ESdlThreadExplicitStop;
1111 Stop();
1112 }
1113
1114
1115void CDsa::Stop()
1116 {
1117 iStateFlags &= ~ERunning;
1118 }
1119
1120void CDsa::Start()
1121 {
1122 iStateFlags |= ERunning;
1123
1124 iStateFlags &= ~ESdlThreadExplicitStop;
1125
1126 if(iStateFlags & ESdlThreadSuspend)
1127 {
1128 EpocSdlEnv::Resume();
1129 iStateFlags &= ~ ESdlThreadSuspend;
1130 }
1131 EpocSdlEnv::ObserverEvent(MSDLObserver::EEventWindowReserved);
1132 }
1133
1134
1135TBool CDsa::Blitter(CFbsBitmap& aBmp)
1136 {
1137 return iBlitter && iBlitter->BitBlt(Gc(), aBmp, HwRect(), SwSize());
1138 }
1139
1140void CDsa::SetBlitter(MBlitter* aBlitter)
1141 {
1142 iBlitter = aBlitter;
1143 }
1144
1145
1146TPoint CDsa::WindowCoordinates(const TPoint& aPoint) const
1147 {
1148 TPoint pos = aPoint - iScreenRect.iTl;
1149 const TSize asz = iScreenRect.Size();
1150 if(iStateFlags & EOrientation180)
1151 {
1152 pos.iX = asz.iWidth - pos.iX;
1153 pos.iY = asz.iHeight - pos.iY;
1154 }
1155 if(iStateFlags & EOrientation90)
1156 {
1157 pos.iX = aPoint.iY;
1158 pos.iY = aPoint.iX;
1159 }
1160 pos.iX <<= 16;
1161 pos.iY <<= 16;
1162 pos.iX /= asz.iWidth;
1163 pos.iY /= asz.iHeight;
1164 pos.iX *= iSwSize.iWidth;
1165 pos.iY *= iSwSize.iHeight;
1166 pos.iX >>= 16;
1167 pos.iY >>= 16;
1168 return pos;
1169 }
1170
1171void CDsa::SetTargetRect()
1172 {
1173 iTargetRect = iScreenRect;
1174 if(iStateFlags & EResizeRequest && EpocSdlEnv::Flags(CSDL::EAllowImageResizeKeepRatio))
1175 {
1176 const TSize asz = iScreenRect.Size();
1177 const TSize sz = iSwSize;
1178
1179 TRect rect;
1180
1181 const TInt dh = (sz.iHeight << 16) / sz.iWidth;
1182
1183 if((asz.iWidth * dh ) >> 16 <= asz.iHeight)
1184 {
1185 rect.SetRect(TPoint(0, 0), TSize(asz.iWidth, (asz.iWidth * dh) >> 16));
1186 }
1187 else
1188 {
1189 const TInt dw = (sz.iWidth << 16) / sz.iHeight;
1190 rect.SetRect(TPoint(0, 0), TSize((asz.iHeight * dw) >> 16, asz.iHeight));
1191 }
1192 rect.Move((asz.iWidth - rect.Size().iWidth) >> 1, (asz.iHeight - rect.Size().iHeight) >> 1);
1193
1194 iTargetRect = rect;
1195 iTargetRect.Move(iScreenRect.iTl);
1196
1197 }
1198 if(!(iStateFlags & EResizeRequest))
1199 iSwSize = iScreenRect.Size();
1200
1201 }
1202
1203
1204/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1205
1206void CDsa::Copy256(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1207 {
1208 TUint32* target = aTarget;
1209 const TUint32* endt = target + aBytes;
1210 const TUint8* source = aSource;
1211 while(target < endt)
1212 {
1213 *target++ = aDsa.iLut256[*source++];
1214 }
1215 }
1216
1217void CDsa::Copy256Reversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1218 {
1219 const TUint32* target = aTarget;
1220 TUint32* endt = aTarget + aBytes;
1221 const TUint8* source = aSource;
1222 while(target < endt)
1223 {
1224 *(--endt) = aDsa.iLut256[*source++];
1225 }
1226 }
1227
1228void CDsa::Copy256Flip(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1229 {
1230 TUint32* target = aTarget;
1231 const TUint32* endt = target + aBytes;
1232 const TUint8* column = aSource;
1233
1234 while(target < endt)
1235 {
1236 *target++ = aDsa.iLut256[*column];
1237 column += aLineLen;
1238 }
1239 }
1240
1241void CDsa::Copy256FlipReversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1242 {
1243 const TUint32* target = aTarget;
1244 TUint32* endt = aTarget + aBytes;
1245 const TUint8* column = aSource;
1246
1247 while(target < endt)
1248 {
1249 *(--endt) = aDsa.iLut256[*column];
1250 column += aLineLen;
1251 }
1252 }
1253
1254void CDsa::CopyMem(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1255 {
1256 const TUint32* src = reinterpret_cast<const TUint32*>(aSource);
1257 Mem::Copy(aTarget, src, aBytes << 2);
1258 }
1259
1260void CDsa::CopyMemFlip(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1261 {
1262 TUint32* target = aTarget;
1263 const TUint32* endt = target + aBytes;
1264 const TUint32* column = reinterpret_cast<const TUint32*>(aSource);
1265
1266 while(target < endt)
1267 {
1268 *target++ = *column;
1269 column += aLineLen;
1270 }
1271 }
1272
1273void CDsa::CopyMemReversed(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1274 {
1275 const TUint32* target = aTarget;
1276 TUint32* endt = aTarget + aBytes;
1277 const TUint32* source = reinterpret_cast<const TUint32*>(aSource);
1278 while(target < endt)
1279 {
1280 *(--endt) = *source++;
1281 }
1282 }
1283
1284
1285void CDsa::CopyMemFlipReversed(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1286 {
1287 const TUint32* target = aTarget;
1288 TUint32* endt = aTarget + aBytes;
1289 const TUint32* column = reinterpret_cast<const TUint32*>(aSource);
1290
1291 while(target < endt)
1292 {
1293 *(--endt) = *column;
1294 column += aLineLen;
1295 }
1296 }
1297
1298/*
1299
1300LOCAL_C TRgb rgb16MA(TInt aValue)
1301 {
1302 return TRgb::Color16MA(aValue);
1303 }
1304*/
1305NONSHARABLE_CLASS(MRgbCopy)
1306 {
1307 public:
1308 virtual void Copy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TBool aReversed) = 0;
1309 virtual void FlipCopy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen, TBool aReversed) = 0;
1310 };
1311
1312template <class T>
1313NONSHARABLE_CLASS(TRgbCopy) : public MRgbCopy
1314 {
1315 public:
1316 TRgbCopy(TDisplayMode aMode);
1317 void* operator new(TUint aBytes, TAny* aMem);
1318 void Copy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TBool aReversed);
1319 void FlipCopy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen, TBool aReversed);
1320 static TUint32 Gray256(const TUint8& aPixel);
1321 static TUint32 Color256(const TUint8& aPixel);
1322 static TUint32 Color4K(const TUint16& aPixel);
1323 static TUint32 Color64K(const TUint16& aPixel);
1324 static TUint32 Color16M(const TUint32& aPixel);
1325 static TUint32 Color16MU(const TUint32& aPixel);
1326 static TUint32 Color16MA(const TUint32& aPixel);
1327 private:
1328 typedef TUint32 (*TRgbFunc) (const T& aValue);
1329 TRgbFunc iFunc;
1330 };
1331
1332
1333template <class T>
1334void* TRgbCopy<T>::operator new(TUint /*aBytes*/, TAny* aMem)
1335 {
1336 return aMem;
1337 }
1338
1339template <class T>
1340TRgbCopy<T>::TRgbCopy(TDisplayMode aMode)
1341 {
1342 switch(aMode)
1343 {
1344 case EGray256 : iFunc = (TRgbFunc) Gray256; break;
1345 case EColor256 : iFunc = (TRgbFunc) Color256; break;
1346 case EColor4K : iFunc = (TRgbFunc) Color4K; break;
1347 case EColor64K : iFunc = (TRgbFunc) Color64K; break;
1348 case EColor16M : iFunc = (TRgbFunc) Color16M; break;
1349 case EColor16MU : iFunc = (TRgbFunc) Color16MU; break;
1350 case EColor16MA : iFunc = (TRgbFunc) Color16MA; break;
1351 default:
1352 PANIC(KErrNotSupported);
1353 }
1354 }
1355
1356template <class T>
1357void TRgbCopy<T>::Copy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TBool aReversed)
1358 {
1359 const T* source = reinterpret_cast<const T*>(aSource);
1360 TUint32* target = aTarget;
1361 TUint32* endt = target + aBytes;
1362
1363 if(aReversed)
1364 {
1365 while(target < endt)
1366 {
1367 const T value = *source++;
1368 *(--endt) = iFunc(value);//iFunc(value).Value();
1369 }
1370 }
1371 else
1372 {
1373 while(target < endt)
1374 {
1375 const T value = *source++;
1376 *target++ = iFunc(value);//iFunc(value).Value();
1377 }
1378 }
1379 }
1380
1381template <class T>
1382void TRgbCopy<T>::FlipCopy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen, TBool aReversed)
1383 {
1384 const T* column = reinterpret_cast<const T*>(aSource);
1385 TUint32* target = aTarget;
1386 TUint32* endt = target + aBytes;
1387
1388 if(aReversed)
1389 {
1390 while(target < endt)
1391 {
1392 *(--endt) = iFunc(*column);
1393 column += aLineLen;
1394 }
1395 }
1396 else
1397 {
1398 while(target < endt)
1399 {
1400 *target++ = iFunc(*column);
1401 column += aLineLen;
1402 }
1403 }
1404 }
1405
1406template <class T> TUint32 TRgbCopy<T>::Gray256(const TUint8& aPixel)
1407 {
1408 const TUint32 px = aPixel << 16 | aPixel << 8 | aPixel;
1409 return px;
1410 }
1411
1412template <class T> TUint32 TRgbCopy<T>::Color256(const TUint8& aPixel)
1413 {
1414 return TRgb::Color256(aPixel).Value();
1415 }
1416
1417template <class T> TUint32 TRgbCopy<T>::Color4K(const TUint16& aPixel)
1418 {
1419 TUint32 col = (aPixel & 0xF00) << 12;
1420 col |= (aPixel & 0xF00) << 8;
1421
1422 col |= (aPixel & 0x0F0) << 8;
1423 col |= (aPixel & 0x0F0);
1424
1425 col |= (aPixel & 0x00F) << 4;
1426 col |= (aPixel & 0x00F);
1427
1428 return col;
1429 }
1430
1431template <class T> TUint32 TRgbCopy<T>::Color64K(const TUint16& aPixel)
1432 {
1433 TUint32 col = (aPixel & 0xF800)<< 8;
1434 col |= (aPixel & 0xE000) << 3;
1435
1436 col |= (aPixel & 0x07E0) << 5;
1437 col |= (aPixel & 0xC0) >> 1;
1438
1439 col |= (aPixel & 0x07E0) << 3;
1440 col |= (aPixel & 0x1C) >> 2;
1441
1442 return col;
1443 }
1444
1445template <class T> TUint32 TRgbCopy<T>::Color16M(const TUint32& aPixel)
1446 {
1447 return TRgb::Color16M(aPixel).Value();
1448 }
1449
1450template <class T> TUint32 TRgbCopy<T>::Color16MU(const TUint32& aPixel)
1451 {
1452 return TRgb::Color16MU(aPixel).Value();
1453 }
1454
1455template <class T> TUint32 TRgbCopy<T>::Color16MA(const TUint32& aPixel)
1456 {
1457 return TRgb::Color16MA(aPixel).Value();
1458 }
1459
1460typedef TUint64 TStackMem;
1461
1462LOCAL_C MRgbCopy* GetCopy(TAny* mem, TDisplayMode aMode)
1463 {
1464 if(aMode == EColor256 || aMode == EGray256)
1465 {
1466 return new (mem) TRgbCopy<TUint8>(aMode);
1467 }
1468 if(aMode == EColor4K || aMode == EColor64K)
1469 {
1470 return new (mem) TRgbCopy<TUint16>(aMode);
1471 }
1472 if(aMode == EColor16M || aMode == EColor16MU || aMode == EColor16MA)
1473 {
1474 return new (mem) TRgbCopy<TUint32>(aMode);
1475 }
1476 PANIC(KErrNotSupported);
1477 return NULL;
1478 }
1479
1480
1481void CDsa::CopySlowFlipReversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1482 {
1483 TStackMem mem = 0;
1484 GetCopy(&mem, aDsa.iSourceMode)->FlipCopy(aTarget, aSource, aBytes, aLineLen, ETrue);
1485 }
1486
1487void CDsa::CopySlowFlip(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1488 {
1489 TStackMem mem = 0;
1490 GetCopy(&mem, aDsa.iSourceMode)->FlipCopy(aTarget, aSource, aBytes, aLineLen, EFalse);
1491 }
1492
1493void CDsa::CopySlow(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1494 {
1495 TStackMem mem = 0;
1496 GetCopy(&mem, aDsa.iSourceMode)->Copy(aTarget, aSource, aBytes, EFalse);
1497 }
1498
1499void CDsa::CopySlowReversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1500 {
1501 TStackMem mem = 0;
1502 GetCopy(&mem, aDsa.iSourceMode)->Copy(aTarget, aSource, aBytes, ETrue);
1503 }
1504
1505////////////////////////////////////////////////////////////////////////////////////////////////////////////////7
diff --git a/apps/plugins/sdl/src/video/symbian/EKA2/dsa_new.cpp b/apps/plugins/sdl/src/video/symbian/EKA2/dsa_new.cpp
deleted file mode 100644
index 638fbe8c94..0000000000
--- a/apps/plugins/sdl/src/video/symbian/EKA2/dsa_new.cpp
+++ /dev/null
@@ -1,1443 +0,0 @@
1#include "dsa.h"
2#include "sdlepocapi.h"
3#include <cdsb.h>
4
5
6LOCAL_C TInt BytesPerPixel(TDisplayMode aMode)
7 {
8 return ((TDisplayModeUtils::NumDisplayModeBitsPerPixel(aMode) - 1) >> 3) + 1;
9 }
10
11
12NONSHARABLE_CLASS(TDsa)
13 {
14 public:
15 inline TDsa(const CDsa& aDsa);
16 inline TBool IsFlip() const;
17 inline TBool IsTurn() const;
18 inline const TSize& SwSize() const;
19 inline void Copy(TUint32* aTarget, const TUint8* aSrc, TInt aBytes, TInt aHeight) const;
20 private:
21 const CDsa& iDsa;
22 };
23
24
25inline TDsa::TDsa(const CDsa& aDsa) : iDsa(aDsa)
26 {
27 }
28
29inline TBool TDsa::IsTurn() const
30 {
31 return iDsa.iStateFlags & CDsa::EOrientation90;
32 }
33
34inline TBool TDsa::IsFlip() const
35 {
36 return iDsa.iStateFlags & CDsa::EOrientation180;
37 }
38
39inline const TSize& TDsa::SwSize() const
40 {
41 return iDsa.SwSize();
42 }
43
44inline void TDsa::Copy(TUint32* aTarget, const TUint8* aSrc, TInt aBytes, TInt aHeight) const
45 {
46 iDsa.iCopyFunction(iDsa, aTarget, aSrc, aBytes, aHeight);
47 }
48
49template<class T, class S>
50void ClipCopy(const TDsa& iDsa, TUint8* aTarget,
51 const TUint8* aSource,
52 const TRect& aUpdateRect,
53 const TRect& aSourceRect)
54 {
55 const S* source = reinterpret_cast<const S*>(aSource);
56 const TInt lineWidth = aSourceRect.Width();
57
58 source += (aUpdateRect.iTl.iY * lineWidth);
59 const TInt sourceStartOffset = aUpdateRect.iTl.iX;
60 source += sourceStartOffset;
61
62 T* targetPtr = reinterpret_cast<T*>(aTarget);
63
64 const TInt scanLineWidth = iDsa.SwSize().iWidth;
65
66 targetPtr += (aSourceRect.iTl.iY + aUpdateRect.iTl.iY ) * scanLineWidth;
67 const TInt targetStartOffset = (aUpdateRect.iTl.iX + aSourceRect.iTl.iX);
68
69 targetPtr += targetStartOffset;
70
71
72 const TInt height = aUpdateRect.Height();
73
74 const TInt lineMove = iDsa.IsTurn() ? 1 : lineWidth;
75 const TInt copyLen = aUpdateRect.Width();
76
77
78 if(iDsa.IsFlip())
79 {
80
81 targetPtr += scanLineWidth * (height - 1);
82
83 for(TInt i = 0; i < height; i++) //source is always smaller
84 {
85 iDsa.Copy(reinterpret_cast<TUint32*>(targetPtr), reinterpret_cast<const TUint8*>(source), copyLen, height);
86 source += lineMove;
87 targetPtr -= scanLineWidth;
88 }
89 }
90 else
91 {
92
93
94 for(TInt i = 0; i < height; i++) //source is always smaller
95 {
96 iDsa.Copy(reinterpret_cast<TUint32*>(targetPtr), reinterpret_cast<const TUint8*>(source), copyLen, height);
97 source += lineMove;
98 targetPtr += scanLineWidth; // >> 2;
99 }
100 }
101
102 }
103
104
105
106NONSHARABLE_CLASS(CDsaA) : public CDsa
107 {
108 public:
109 CDsaA(RWsSession& aSession);
110 private:
111 ~CDsaA();
112 TUint8* LockSurface();
113 void UnlockHWSurfaceRequestComplete();
114 void UnlockHwSurface();
115 void CreateSurfaceL();
116 void Wipe(TInt aLength);
117 void Free();
118 void Update(CFbsBitmap& aBmp);
119 void ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice);
120 TInt ExternalUpdate();
121 // void ExternalUpdate();
122 protected:
123 CFbsBitmap* iBmp;
124 CFbsBitmap* iCopyBmp;
125 };
126
127
128CDsaA::CDsaA(RWsSession& aSession) : CDsa(aSession)
129 {
130 }
131
132
133void CDsaA::Free()
134 {
135 delete iBmp;
136 iBmp = NULL;
137 }
138
139CDsaA::~CDsaA()
140 {
141 __ASSERT_DEBUG(iBmp == NULL, PANIC(KErrNotReady));
142 delete iCopyBmp;
143 }
144
145TUint8* CDsaA::LockSurface()
146 {
147 iBmp->LockHeap();
148 return reinterpret_cast<TUint8*>(iBmp->DataAddress());
149 }
150
151void CDsaA::UnlockHWSurfaceRequestComplete()
152 {
153 PANIC(KErrNotSupported);
154 }
155
156void CDsaA::UnlockHwSurface()
157 {
158 iBmp->UnlockHeap();
159 SetUpdating(EFalse);
160 Update(*iBmp);
161 }
162
163void CDsaA::Update(CFbsBitmap& aBmp)
164 {
165 if(!Blitter(aBmp))
166 {
167 if(SwSize() == HwRect().Size())
168 Dsa().Gc()->BitBlt(HwRect().iTl, &aBmp);
169 else
170 Dsa().Gc()->DrawBitmap(HwRect(), &aBmp);
171 }
172 DrawOverlays();
173 Dsa().ScreenDevice()->Update();
174 }
175void CDsaA::CreateSurfaceL()
176 {
177 delete iBmp;
178 iBmp = NULL;
179 iBmp = new (ELeave) CFbsBitmap();
180 User::LeaveIfError(iBmp->Create(SwSize(), DisplayMode()));
181 }
182
183void CDsaA::Wipe(TInt aLength) //dont call in drawing
184 {
185 iBmp->LockHeap();
186 Mem::FillZ(iBmp->DataAddress(), aLength);
187 iBmp->UnlockHeap();
188 }
189
190
191
192TInt CDsaA::ExternalUpdate()
193 {
194 if(iCopyBmp->Handle() == 0)
195 {
196 const TInt err = iCopyBmp->Duplicate(iBmp->Handle());
197 if(err != KErrNone)
198 return err;
199 }
200 Update(*iCopyBmp);
201 return KErrNone;
202 }
203
204void CDsaA::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
205 {
206 iCopyBmp = new (ELeave) CFbsBitmap();
207 CDsa::ConstructL(aWindow, aDevice);
208 }
209
210
211//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
212
213NONSHARABLE_CLASS(MDsbObs)
214 {
215 public:
216 virtual void SurfaceReady() = 0;
217 virtual CDirectScreenBitmap& Dsb() = 0;
218 };
219
220NONSHARABLE_CLASS(CDsbSurface) : public CActive
221 {
222 public:
223 CDsbSurface(MDsbObs& aDsb);
224 TUint8* Address();
225 void Complete();
226 ~CDsbSurface();
227 private:
228 void RunL();
229 void DoCancel();
230 private:
231 MDsbObs& iDsb;
232 TUint8* iAddress;
233 };
234
235CDsbSurface::CDsbSurface(MDsbObs& aDsb) : CActive(CActive::EPriorityHigh) , iDsb(aDsb)
236 {
237 CActiveScheduler::Add(this);
238 }
239
240CDsbSurface::~CDsbSurface()
241 {
242 Cancel();
243 }
244
245void CDsbSurface::Complete()
246 {
247 if(iAddress != NULL && !IsActive())
248 {
249 iAddress = NULL;
250 SetActive();
251 iDsb.Dsb().EndUpdate(iStatus);
252 }
253 }
254
255TUint8* CDsbSurface::Address()
256 {
257 if(iAddress == NULL && !IsActive())
258 {
259 TAcceleratedBitmapInfo info;
260 if(KErrNone == iDsb.Dsb().BeginUpdate(info))
261 iAddress = info.iAddress;
262 }
263 return iAddress;
264 }
265
266void CDsbSurface::RunL()
267 {
268 iDsb.SurfaceReady();
269 }
270
271void CDsbSurface::DoCancel()
272 {
273 //empty
274 }
275
276NONSHARABLE_CLASS(CDsaB) : public CDsa, public MDsbObs
277 {
278 public:
279 CDsaB(RWsSession& aSession, TInt aFlags);
280 private:
281 ~CDsaB();
282 TUint8* LockSurface();
283 void UnlockHWSurfaceRequestComplete();
284 void UnlockHwSurface();
285 void CreateSurfaceL();
286 void Wipe(TInt aLength);
287 void RecreateL();
288 void ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice);
289 CDirectScreenBitmap& Dsb();
290 void SurfaceReady();
291 TInt ExternalUpdate();
292 private:
293 CDsbSurface* iSurface1;
294 CDsbSurface* iSurface2;
295 CDirectScreenBitmap* iDsb;
296 TInt iType;
297 };
298
299CDsaB::CDsaB(RWsSession& aSession, TInt aFlags) : CDsa(aSession), iType(aFlags)
300 {
301 }
302
303
304
305void CDsaB::UnlockHWSurfaceRequestComplete()
306 {
307 iSurface1->Complete();
308 if(iSurface2 != NULL)
309 iSurface2->Complete();
310 }
311
312void CDsaB::CreateSurfaceL()
313 {
314 __ASSERT_ALWAYS(SwSize() == HwRect().Size(), PANIC(KErrNotSupported));
315 }
316
317void CDsaB::Wipe(TInt aLength) //dont call in drawing
318 {
319 TUint8* addr = LockSurface();
320 if(addr != NULL)
321 {
322 Mem::FillZ(addr, aLength);
323 UnlockHwSurface();
324 }
325 }
326
327
328void CDsaB::UnlockHwSurface()
329 {
330 EpocSdlEnv::Request(CDsa::ERequestUpdate);
331 }
332
333TUint8* CDsaB::LockSurface()
334 {
335 TUint8* addr = iSurface1->Address();
336 if(addr == NULL && iSurface2 != NULL)
337 addr = iSurface2->Address();
338 SetUpdating(addr == NULL);
339 return addr;
340 }
341
342void CDsaB::SurfaceReady()
343 {
344 SetUpdating(EFalse);
345 }
346
347CDirectScreenBitmap& CDsaB::Dsb()
348 {
349 return *iDsb;
350 }
351
352void CDsaB::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
353 {
354 if(iDsb == NULL)
355 iDsb = CDirectScreenBitmap::NewL();
356 CDsa::ConstructL(aWindow, aDevice);
357 if(iSurface1 == NULL)
358 iSurface1 = new (ELeave) CDsbSurface(*this);
359 if(iSurface2 == NULL && iType & CDirectScreenBitmap::EDoubleBuffer)
360 iSurface2 = new (ELeave) CDsbSurface(*this);
361 }
362
363CDsaB::~CDsaB()
364 {
365 delete iSurface1;
366 delete iSurface2;
367 delete iDsb;
368 }
369
370void CDsaB::RecreateL()
371 {
372 iDsb->Close();
373 iDsb->Create(HwRect(), CDirectScreenBitmap::TSettingsFlags(iType));
374 }
375
376TInt CDsaB::ExternalUpdate()
377 {
378 if(LockSurface())
379 {
380 UnlockHWSurfaceRequestComplete();
381 return KErrNone;
382 }
383 return KErrNotReady;
384 }
385
386
387/////////////////////////////////////////////////////////////////////////////////////////////////////
388
389
390CDsa* CDsa::CreateL(RWsSession& aSession)
391 {
392 if(EpocSdlEnv::Flags(CSDL::EDrawModeDSB))
393 {
394 TInt flags = CDirectScreenBitmap::ENone;
395 if(EpocSdlEnv::Flags(CSDL::EDrawModeDSBDoubleBuffer))
396 flags |= CDirectScreenBitmap::EDoubleBuffer;
397 if(EpocSdlEnv::Flags(CSDL::EDrawModeDSBIncrentalUpdate))
398 flags |= CDirectScreenBitmap::EIncrementalUpdate;
399 return new (ELeave) CDsaB(aSession, flags);
400 }
401 else
402 return new (ELeave) CDsaA(aSession);
403 }
404
405
406void CDsa::RecreateL()
407 {
408 }
409
410void CDsa::Free()
411 {
412 }
413
414TSize CDsa::WindowSize() const
415 {
416 TSize size = iSwSize;
417 if(iStateFlags & EOrientation90)
418 {
419 const TInt tmp = size.iWidth;
420 size.iWidth = size.iHeight;
421 size.iHeight = tmp;
422 }
423 return size;
424 }
425
426void CDsa::SetSuspend()
427 {
428 iStateFlags |= ESdlThreadSuspend;
429 }
430
431void CDsa::ReleaseStop()
432 {
433 iStateFlags &= ~ESdlThreadExplicitStop;
434 }
435
436
437TBool CDsa::Stopped() const
438 {
439 return (iStateFlags & ESdlThreadExplicitStop);
440 }
441
442void CDsa::SetOrientation(CSDL::TOrientationMode aOrientation)
443 {
444 TInt flags = 0;
445 switch(aOrientation)
446 {
447 case CSDL::EOrientation90:
448 flags = EOrientation90;
449 break;
450 case CSDL::EOrientation180:
451 flags = EOrientation180;
452 break;
453 case CSDL::EOrientation270:
454 flags = EOrientation90 | EOrientation180;
455 break;
456 case CSDL::EOrientation0:
457 flags = 0;
458 break;
459 }
460 if(flags != (iStateFlags & EOrientationFlags))
461 {
462 iStateFlags |= EOrientationChanged;
463 iNewFlags = flags; //cannot be set during drawing...
464 }
465 }
466
467CDsa::~CDsa()
468 {
469 if(iDsa != NULL)
470 {
471 iDsa->Cancel();
472 }
473 iOverlays.Close();
474 delete iDsa;
475 User::Free(iLut256);
476 }
477
478void CDsa::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
479 {
480 if(iDsa != NULL)
481 {
482 iDsa->Cancel();
483 delete iDsa;
484 iDsa = NULL;
485 }
486
487 iDsa = CDirectScreenAccess::NewL(
488 iSession,
489 aDevice,
490 aWindow,
491 *this);
492
493 if(iLut256 == NULL)
494 iLut256 = (TUint32*) User::AllocL(256 * sizeof(TUint32));
495 iTargetMode = aWindow.DisplayMode();
496 iTargetBpp = BytesPerPixel(DisplayMode());
497 iScreenRect = TRect(aWindow.Position(), aWindow.Size());
498 SetTargetRect();
499 RestartL();
500 }
501
502void CDsa::DrawOverlays()
503 {
504 const TInt last = iOverlays.Count() - 1;
505 for(TInt i = last; i >= 0 ; i--)
506 iOverlays[i].iOverlay->Draw(*iDsa->Gc(), HwRect(), SwSize());
507 }
508
509TInt CDsa::AppendOverlay(MOverlay& aOverlay, TInt aPriority)
510 {
511 TInt i;
512 for(i = 0; i < iOverlays.Count() && iOverlays[i].iPriority < aPriority; i++)
513 {}
514 const TOverlay overlay = {&aOverlay, aPriority};
515 return iOverlays.Insert(overlay, i);
516 }
517
518TInt CDsa::RemoveOverlay(MOverlay& aOverlay)
519 {
520 for(TInt i = 0; i < iOverlays.Count(); i++)
521 {
522 if(iOverlays[i].iOverlay == &aOverlay)
523 {
524 iOverlays.Remove(i);
525 return KErrNone;
526 }
527 }
528 return KErrNotFound;
529 }
530
531void CDsa::LockPalette(TBool aLock)
532 {
533 if(aLock)
534 iStateFlags |= EPaletteLocked;
535 else
536 iStateFlags &= ~EPaletteLocked;
537 }
538TInt CDsa::SetPalette(TInt aFirst, TInt aCount, TUint32* aPalette)
539 {
540 if(iLut256 == NULL)
541 return KErrNotFound;
542 const TInt count = aCount - aFirst;
543 if(count > 256)
544 return KErrArgument;
545 if(iStateFlags & EPaletteLocked)
546 return KErrNone;
547 for(TInt i = aFirst; i < count; i++) //not so busy here:-)
548 {
549 iLut256[i] = aPalette[i];
550 }
551 return KErrNone;
552 }
553
554
555
556void CDsa::RestartL()
557 {
558 //const TBool active = iDsa->IsActive();
559
560 //if(!active)
561
562 iDsa->StartL();
563
564 const RRegion* r = iDsa->DrawingRegion();
565 const TRect rect = r->BoundingRect();
566 iDsa->Gc()->SetClippingRegion(r);
567
568 if(rect != iScreenRect)
569 {
570 // iDsa->Cancel();
571 return ;
572 }
573
574
575
576 //iScreenRect = rect; //to ensure properly set, albeit may not(?) match to value SDL has - therefore may has to clip
577 //targetrect shall no change
578 SetTargetRect();
579 RecreateL();
580
581 iStateFlags |= ERunning;
582
583 ReleaseStop();
584 if(iStateFlags & ESdlThreadSuspend)
585 {
586 EpocSdlEnv::Resume();
587 iStateFlags &= ~ ESdlThreadSuspend;
588 }
589 EpocSdlEnv::ObserverEvent(MSDLObserver::EEventWindowReserved);
590 }
591
592CDsa::CDsa(RWsSession& aSession) :
593 iSession(aSession),
594 iStateFlags(0)
595 {
596// CActiveScheduler::Add(this);
597 iCFTable[0] = CopyMem;
598 iCFTable[1] = CopyMemFlipReversed;
599 iCFTable[2] = CopyMemReversed;
600 iCFTable[3] = CopyMemFlip;
601
602 iCFTable[4] = Copy256;
603 iCFTable[5] = Copy256FlipReversed;
604 iCFTable[6] = Copy256Reversed;
605 iCFTable[7] = Copy256Flip;
606
607
608 iCFTable[8] = CopySlow;
609 iCFTable[9] = CopySlowFlipReversed;
610 iCFTable[10] = CopySlowReversed;
611 iCFTable[11] = CopySlowFlip;
612 }
613
614RWsSession& CDsa::Session()
615 {
616 return iSession;
617 }
618
619TInt CDsa::RedrawRequest()
620 {
621 if(!(iStateFlags & (EUpdating) && (iStateFlags & ERunning)))
622 {
623 return ExternalUpdate();
624 }
625 return KErrNotReady;
626 }
627
628TUint8* CDsa::LockHwSurface()
629 {
630 if((iStateFlags & EUpdating) == 0) //else frame is skipped
631 {
632 return LockSurface();
633 }
634 return NULL;
635 }
636
637/*
638void CDsa::RunL()
639 {
640 iStateFlags &= ~EUpdating;
641 }
642
643
644void CDsa::DoCancel()
645 {
646 iStateFlags &= ~EUpdating;
647 //nothing can do, just wait?
648 }
649*/
650
651
652TInt CDsa::AllocSurface(TBool aHwSurface, const TSize& aSize, TDisplayMode aMode)
653 {
654 if(aHwSurface && aMode != DisplayMode())
655 return KErrArgument;
656
657 iSourceMode = aMode;
658
659 iSourceBpp = BytesPerPixel(aMode);
660
661 const TSize size = WindowSize();
662 if(aSize.iWidth > size.iWidth)
663 return KErrTooBig;
664 if(aSize.iHeight > size.iHeight)
665 return KErrTooBig;
666
667 TRAPD(err, CreateSurfaceL());
668 if(err != KErrNone)
669 return err;
670
671 SetCopyFunction();
672
673 return KErrNone;
674 }
675
676
677void CDsa::CreateZoomerL(const TSize& aSize)
678 {
679 iSwSize = aSize;
680 iStateFlags |= EResizeRequest;
681 CreateSurfaceL();
682 SetTargetRect();
683 }
684
685
686/*
687void SaveBmp(const TDesC& aName, const TAny* aData, TInt aLength, const TSize& aSz, TDisplayMode aMode)
688 {
689 CFbsBitmap* s = new CFbsBitmap();
690 s->Create(aSz, aMode);
691 s->LockHeap();
692 TUint32* addr = s->DataAddress();
693 Mem::Copy(addr, aData, aLength);
694 s->UnlockHeap();
695 s->Save(aName);
696 s->Reset();
697 delete s;
698 }
699
700void SaveBmp(const TDesC& aName, const TUint32* aData, const TSize& aSz)
701 {
702 CFbsBitmap* s = new CFbsBitmap();
703 s->Create(aSz, EColor64K);
704 TBitmapUtil bmp(s);
705 bmp.Begin(TPoint(0, 0));
706 for(TInt j = 0; j < aSz.iHeight; j++)
707 {
708 bmp.SetPos(TPoint(0, j));
709 for(TInt i = 0; i < aSz.iWidth; i++)
710 {
711 bmp.SetPixel(*aData);
712 aData++;
713 bmp.IncXPos();
714 }
715 }
716 bmp.End();
717 s->Save(aName);
718 s->Reset();
719 delete s;
720 }
721
722TBuf<16> FooName(TInt aFoo)
723 {
724 TBuf<16> b;
725 b.Format(_L("C:\\pic%d.mbm"), aFoo);
726 return b;
727 }
728
729void ClipCopy(TUint8* aTarget, const TUint8* aSource, const TRect& aRect, const TPoint& aTargetPos)
730 {
731 const TInt iSourceBpp = 1;
732 const TInt iTargetBpp = 4;
733 const TInt iScanLineWidth = 800;
734
735 TUint8* target = aTarget;
736 const TUint8* source = aSource;
737 const TInt lineWidth = aRect.Width();
738 source += iSourceBpp * (aRect.iTl.iY * lineWidth);
739 const TInt sourceStartOffset = iSourceBpp * aRect.iTl.iX;
740 source += sourceStartOffset;
741 target += iTargetBpp * ((aTargetPos.iY + aRect.iTl.iY ) * lineWidth);
742 const TInt targetStartOffset = iTargetBpp * (aRect.iTl.iX + aTargetPos.iX);
743 target += targetStartOffset;
744 TUint32* targetPtr = reinterpret_cast<TUint32*>(target);
745 const TInt targetWidth = iScanLineWidth >> 2;
746 const TInt height = aRect.Height();
747 }
748*/
749/*
750void CDsa::ClipCopy(TUint8* aTarget,
751 const TUint8* aSource,
752 const TRect& aUpdateRect,
753 const TRect& aSourceRect) const
754 {
755 //TUint8* target = aTarget;
756 const TUint32* source = (const TUint32*) aSource;
757 const TInt lineWidth = aSourceRect.Width();
758
759 source += (aUpdateRect.iTl.iY * lineWidth);
760 const TInt sourceStartOffset = aUpdateRect.iTl.iX;
761 source += sourceStartOffset;
762
763 TUint32* targetPtr = reinterpret_cast<TUint32*>(aTarget);
764
765 targetPtr += (aSourceRect.iTl.iY + aUpdateRect.iTl.iY ) * SwSize().iWidth;
766 const TInt targetStartOffset = (aUpdateRect.iTl.iX + aSourceRect.iTl.iX);
767
768 targetPtr += targetStartOffset;
769
770// TUint32* targetPtr = reinterpret_cast<TUint32*>(target);
771
772 const TInt targetWidth32 = SwSize().iWidth;
773
774 const TInt height = aUpdateRect.Height();
775
776 const TInt lineMove = iStateFlags & EOrientation90 ? 1 : lineWidth;
777 const TInt copyLen = aUpdateRect.Width();
778
779
780 if(iStateFlags & EOrientation180)
781 {
782
783 targetPtr += targetWidth32 * (height - 1);
784
785 for(TInt i = 0; i < height; i++) //source is always smaller
786 {
787 iCopyFunction(*this, targetPtr, (TUint8*)source, copyLen, height);
788 source += lineMove;
789 targetPtr -= targetWidth32;
790 }
791 }
792 else
793 {
794
795
796 for(TInt i = 0; i < height; i++) //source is always smaller
797 {
798 iCopyFunction(*this, targetPtr, (TUint8*)source, copyLen, height);
799 source += lineMove;
800 targetPtr += targetWidth32; // >> 2;
801 }
802 }
803
804 }
805
806*/
807
808void CDsa::ClipCopy(TUint8* aTarget, const TUint8* aSource, const TRect& aRect, const TPoint& aTargetPos) const
809 {
810 TUint8* target = aTarget;
811 const TUint8* source = aSource;
812 const TInt lineWidth = aRect.Width();
813 source += iSourceBpp * (aRect.iTl.iY * lineWidth);
814 TInt sourceStartOffset = iSourceBpp * aRect.iTl.iX;
815 source += sourceStartOffset;
816 target += iTargetBpp * ((aTargetPos.iY + aRect.iTl.iY ) * lineWidth);
817 TInt targetStartOffset = iTargetBpp * (aRect.iTl.iX + aTargetPos.iX);
818 target += targetStartOffset;
819 TUint32* targetPtr = reinterpret_cast<TUint32*>(target);
820 const TInt targetWidth = iScanLineWidth >> 2;
821 const TInt height = aRect.Height();
822
823 TInt lineMove = iStateFlags & EOrientation90 ? 1 : lineWidth;
824
825 if(iStateFlags & EOrientation180)
826 {
827
828 targetPtr += targetWidth * (height - 1);
829
830 for(TInt i = 0; i < height; i++) //source is always smaller
831 {
832 iCopyFunction(*this, targetPtr, source, lineWidth, height);
833 source += lineMove;
834 targetPtr -= targetWidth;
835 }
836 }
837 else
838 {
839
840
841 for(TInt i = 0; i < height; i++) //source is always smaller
842 {
843 iCopyFunction(*this, targetPtr, source, lineWidth, height);
844 source += lineMove;
845 targetPtr += targetWidth;
846 }
847 }
848
849 }
850
851
852
853 /*
854void CDsa::ClipCopy(TUint8* aTarget,
855 const TUint8* aSource,
856 const TRect& aUpdateRect,
857 const TRect& aSourceRect) const
858 {
859 const TDsa dsa(*this);
860 switch(iSourceBpp)
861 {
862 case 1:
863 ::ClipCopy<TUint32, TUint8>(dsa, aTarget, aSource, aUpdateRect, aSourceRect);
864 break;
865 case 2:
866 ::ClipCopy<TUint32, TUint16>(dsa, aTarget, aSource, aUpdateRect, aSourceRect);
867 break;
868 case 4:
869 ::ClipCopy<TUint32, TUint32>(dsa, aTarget, aSource, aUpdateRect, aSourceRect);
870 break;
871 }
872 }
873
874
875*/
876
877
878
879void CDsa::Wipe() //dont call in drawing
880 {
881 if(IsDsaAvailable())
882 Wipe(iTargetBpp * SwSize().iWidth * SwSize().iHeight);
883 }
884
885void CDsa::SetCopyFunction()
886 {
887 //calculate offset to correct function in iCFTable according to given parameters
888 TInt function = 0;
889 const TInt KCopyFunctions = 4;
890 const TInt KOffsetToNative = 0;
891 const TInt KOffsetTo256 = KOffsetToNative + KCopyFunctions;
892 const TInt KOffsetToOtherModes = KOffsetTo256 + KCopyFunctions;
893 const TInt KOffsetTo90Functions = 1;
894 const TInt KOffsetTo180Functions = 2;
895
896 if(iSourceMode == DisplayMode())
897 function = KOffsetToNative; //0
898 else if(iSourceMode == EColor256)
899 function = KOffsetTo256; //4
900 else
901 function = KOffsetToOtherModes; //8
902
903 if(iStateFlags & EOrientation90)
904 function += KOffsetTo90Functions; // + 1
905 if(iStateFlags & EOrientation180)
906 function += KOffsetTo180Functions; //+ 2
907
908 iCopyFunction = iCFTable[function];
909
910 Wipe();
911 }
912
913inline void Rotate(TRect& aRect)
914 {
915 const TInt dx = aRect.iBr.iX - aRect.iTl.iX;
916 const TInt dy = aRect.iBr.iY - aRect.iTl.iY;
917
918 aRect.iBr.iX = aRect.iTl.iX + dy;
919 aRect.iBr.iY = aRect.iTl.iY + dx;
920
921 const TInt tmp = aRect.iTl.iX;
922 aRect.iTl.iX = aRect.iTl.iY;
923 aRect.iTl.iY = tmp;
924 }
925
926/*
927int bar = 0;
928*/
929/*
930TBool CDsa::AddUpdateRect(const TUint8* aBits, const TRect& aUpdateRect, const TRect& aRect)
931 {
932
933 if(iStateFlags & EOrientationChanged)
934 {
935 iStateFlags &= ~EOrientationFlags;
936 iStateFlags |= iNewFlags;
937 SetCopyFunction();
938 iStateFlags &= ~EOrientationChanged;
939 EpocSdlEnv::WaitDeviceChange();
940 return EFalse; //skip this frame as data is may be changed
941 }
942
943 if(iTargetAddr == NULL)
944 {
945 iTargetAddr = LockHwSurface();
946 }
947
948 TUint8* target = iTargetAddr;
949 if(target == NULL)
950 return EFalse;
951
952
953 TRect targetRect = TRect(TPoint(0, 0), SwSize());
954
955 TRect sourceRect = aRect;
956 TRect updateRect = aUpdateRect;
957
958// TPoint move(0, 0);
959
960
961 if(iStateFlags & EOrientation90)
962 {
963 Rotate(sourceRect);
964 Rotate(updateRect);
965 }
966
967 if(iSourceMode != DisplayMode() || targetRect != sourceRect || targetRect != updateRect || ((iStateFlags & EOrientationFlags) != 0))
968 {
969 sourceRect.Intersection(targetRect); //so source always smaller or equal than target
970 //updateRect.Intersection(targetRect);
971 ClipCopy(target, aBits, updateRect, sourceRect);
972 }
973 else
974 {
975 const TInt byteCount = aRect.Width() * aRect.Height() * iSourceBpp; //this could be stored
976 Mem::Copy(target, aBits, byteCount);
977 }
978
979 return ETrue;
980 }
981 */
982
983TBool CDsa::AddUpdateRect(const TUint8* aBits, const TRect& aUpdateRect, const TRect& aRect)
984 {
985
986 if(iStateFlags & EOrientationChanged)
987 {
988 iStateFlags &= ~EOrientationFlags;
989 iStateFlags |= iNewFlags;
990 SetCopyFunction();
991 iStateFlags &= ~EOrientationChanged;
992 EpocSdlEnv::WaitDeviceChange();
993 return EFalse; //skip this frame as data is may be changed
994 }
995
996 if(iTargetAddr == NULL)
997 {
998 iTargetAddr = LockHwSurface();
999 }
1000 TUint8* target = iTargetAddr;
1001 if(target == NULL)
1002 return EFalse;
1003
1004
1005 TRect targetRect = Rect();
1006 TRect sourceRect = aRect;
1007 TRect updateRect = aUpdateRect;
1008
1009 if(iStateFlags & EOrientation90)
1010 {
1011 Rotate(sourceRect);
1012 Rotate(updateRect);
1013 }
1014
1015 if(iSourceMode != DisplayMode() || targetRect != sourceRect || targetRect != updateRect || ((iStateFlags & EOrientationFlags) != 0))
1016 {
1017 sourceRect.Intersection(targetRect); //so source always smaller or equal than target
1018 updateRect.Intersection(targetRect);
1019 ClipCopy(target, aBits, updateRect, sourceRect.iTl);
1020 }
1021 else
1022 {
1023 const TInt byteCount = aRect.Width() * aRect.Height() * iSourceBpp; //this could be stored
1024 Mem::Copy(target, aBits, byteCount);
1025 }
1026
1027 return ETrue;
1028 }
1029void CDsa::UpdateSwSurface()
1030 {
1031 iTargetAddr = NULL;
1032 UnlockHwSurface(); //could be faster if does not use AO, but only check status before redraw, then no context switch needed
1033 }
1034
1035
1036void CDsa::Resume()
1037 {
1038 if(Stopped())
1039 Restart(RDirectScreenAccess::ETerminateRegion);
1040 }
1041
1042void CDsa::DoStop()
1043 {
1044 if(IsDsaAvailable())
1045 iStateFlags |= ESdlThreadExplicitStop;
1046 Stop();
1047 }
1048
1049void CDsa::Stop()
1050 {
1051 iStateFlags &= ~ERunning;
1052// Cancel(); //can be called only from main!
1053 iDsa->Cancel();
1054 }
1055
1056void CDsa::AbortNow(RDirectScreenAccess::TTerminationReasons /*aReason*/)
1057 {
1058// iStateFlags |= EChangeNotify;
1059 Stop();
1060 }
1061
1062void CDsa::Restart(RDirectScreenAccess::TTerminationReasons aReason)
1063 {
1064 if(aReason == RDirectScreenAccess::ETerminateRegion) //auto restart
1065 {
1066 TRAPD(err, RestartL());
1067 PANIC_IF_ERROR(err);
1068 }
1069 }
1070
1071void CDsa::SetBlitter(MBlitter* aBlitter)
1072 {
1073 iBlitter = aBlitter;
1074 }
1075
1076
1077TPoint CDsa::WindowCoordinates(const TPoint& aPoint) const
1078 {
1079 TPoint pos = aPoint - iScreenRect.iTl;
1080 const TSize asz = iScreenRect.Size();
1081 if(iStateFlags & EOrientation180)
1082 {
1083 pos.iX = asz.iWidth - pos.iX;
1084 pos.iY = asz.iHeight - pos.iY;
1085 }
1086 if(iStateFlags & EOrientation90)
1087 {
1088 pos.iX = aPoint.iY;
1089 pos.iY = aPoint.iX;
1090 }
1091 pos.iX <<= 16;
1092 pos.iY <<= 16;
1093 pos.iX /= asz.iWidth;
1094 pos.iY /= asz.iHeight;
1095 pos.iX *= iSwSize.iWidth;
1096 pos.iY *= iSwSize.iHeight;
1097 pos.iX >>= 16;
1098 pos.iY >>= 16;
1099 return pos;
1100 }
1101
1102void CDsa::SetTargetRect()
1103 {
1104 iTargetRect = iScreenRect;
1105 if(iStateFlags & EResizeRequest && EpocSdlEnv::Flags(CSDL::EAllowImageResizeKeepRatio))
1106 {
1107 const TSize asz = iScreenRect.Size();
1108 const TSize sz = iSwSize;
1109
1110 TRect rect;
1111
1112 const TInt dh = (sz.iHeight << 16) / sz.iWidth;
1113
1114 if((asz.iWidth * dh ) >> 16 <= asz.iHeight)
1115 {
1116 rect.SetRect(TPoint(0, 0), TSize(asz.iWidth, (asz.iWidth * dh) >> 16));
1117 }
1118 else
1119 {
1120 const TInt dw = (sz.iWidth << 16) / sz.iHeight;
1121 rect.SetRect(TPoint(0, 0), TSize((asz.iHeight * dw) >> 16, asz.iHeight));
1122 }
1123 rect.Move((asz.iWidth - rect.Size().iWidth) >> 1, (asz.iHeight - rect.Size().iHeight) >> 1);
1124
1125 iTargetRect = rect;
1126 iTargetRect.Move(iScreenRect.iTl);
1127
1128 }
1129 if(!(iStateFlags & EResizeRequest))
1130 iSwSize = iScreenRect.Size();
1131// iScanLineWidth = /*iTargetBpp **/ SwSize().iWidth;
1132 }
1133
1134/*)
1135TBool CDsa::ChangeTrigger()
1136 {
1137 const TBool change = iStateFlags & EChangeNotify;
1138 iStateFlags &= ~EChangeNotify;
1139 return change;
1140 }
1141*/
1142/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1143
1144void CDsa::Copy256(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1145 {
1146 TUint32* target = aTarget;
1147 const TUint32* endt = target + aBytes;
1148 const TUint8* source = aSource;
1149 while(target < endt)
1150 {
1151 *target++ = aDsa.iLut256[*source++];
1152 }
1153 }
1154
1155void CDsa::Copy256Reversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1156 {
1157 const TUint32* target = aTarget;
1158 TUint32* endt = aTarget + aBytes;
1159 const TUint8* source = aSource;
1160 while(target < endt)
1161 {
1162 *(--endt) = aDsa.iLut256[*source++];
1163 }
1164 }
1165
1166void CDsa::Copy256Flip(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1167 {
1168 TUint32* target = aTarget;
1169 const TUint32* endt = target + aBytes;
1170 const TUint8* column = aSource;
1171
1172 while(target < endt)
1173 {
1174 *target++ = aDsa.iLut256[*column];
1175 column += aLineLen;
1176 }
1177 }
1178
1179void CDsa::Copy256FlipReversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1180 {
1181 const TUint32* target = aTarget;
1182 TUint32* endt = aTarget + aBytes;
1183 const TUint8* column = aSource;
1184
1185 while(target < endt)
1186 {
1187 *(--endt) = aDsa.iLut256[*column];
1188 column += aLineLen;
1189 }
1190 }
1191
1192void CDsa::CopyMem(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1193 {
1194 const TUint32* src = reinterpret_cast<const TUint32*>(aSource);
1195 Mem::Copy(aTarget, src, aBytes << 2);
1196 }
1197
1198void CDsa::CopyMemFlip(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1199 {
1200 TUint32* target = aTarget;
1201 const TUint32* endt = target + aBytes;
1202 const TUint32* column = reinterpret_cast<const TUint32*>(aSource);
1203
1204 while(target < endt)
1205 {
1206 *target++ = *column;
1207 column += aLineLen;
1208 }
1209 }
1210
1211void CDsa::CopyMemReversed(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1212 {
1213 const TUint32* target = aTarget;
1214 TUint32* endt = aTarget + aBytes;
1215 const TUint32* source = reinterpret_cast<const TUint32*>(aSource);
1216 while(target < endt)
1217 {
1218 *(--endt) = *source++;
1219 }
1220 }
1221
1222
1223void CDsa::CopyMemFlipReversed(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1224 {
1225 const TUint32* target = aTarget;
1226 TUint32* endt = aTarget + aBytes;
1227 const TUint32* column = reinterpret_cast<const TUint32*>(aSource);
1228
1229 while(target < endt)
1230 {
1231 *(--endt) = *column;
1232 column += aLineLen;
1233 }
1234 }
1235
1236/*
1237
1238LOCAL_C TRgb rgb16MA(TInt aValue)
1239 {
1240 return TRgb::Color16MA(aValue);
1241 }
1242*/
1243NONSHARABLE_CLASS(MRgbCopy)
1244 {
1245 public:
1246 virtual void Copy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TBool aReversed) = 0;
1247 virtual void FlipCopy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen, TBool aReversed) = 0;
1248 };
1249
1250template <class T>
1251NONSHARABLE_CLASS(TRgbCopy) : public MRgbCopy
1252 {
1253 public:
1254 TRgbCopy(TDisplayMode aMode);
1255 void* operator new(TUint aBytes, TAny* aMem);
1256 void Copy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TBool aReversed);
1257 void FlipCopy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen, TBool aReversed);
1258 static TUint32 Gray256(const TUint8& aPixel);
1259 static TUint32 Color256(const TUint8& aPixel);
1260 static TUint32 Color4K(const TUint16& aPixel);
1261 static TUint32 Color64K(const TUint16& aPixel);
1262 static TUint32 Color16M(const TUint32& aPixel);
1263 static TUint32 Color16MU(const TUint32& aPixel);
1264 static TUint32 Color16MA(const TUint32& aPixel);
1265 private:
1266 typedef TUint32 (*TRgbFunc) (const T& aValue);
1267 TRgbFunc iFunc;
1268 };
1269
1270
1271template <class T>
1272void* TRgbCopy<T>::operator new(TUint /*aBytes*/, TAny* aMem)
1273 {
1274 return aMem;
1275 }
1276
1277template <class T>
1278TRgbCopy<T>::TRgbCopy(TDisplayMode aMode)
1279 {
1280 switch(aMode)
1281 {
1282 case EGray256 : iFunc = (TRgbFunc) Gray256; break;
1283 case EColor256 : iFunc = (TRgbFunc) Color256; break;
1284 case EColor4K : iFunc = (TRgbFunc) Color4K; break;
1285 case EColor64K : iFunc = (TRgbFunc) Color64K; break;
1286 case EColor16M : iFunc = (TRgbFunc) Color16M; break;
1287 case EColor16MU : iFunc = (TRgbFunc) Color16MU; break;
1288 case EColor16MA : iFunc = (TRgbFunc) Color16MA; break;
1289 default:
1290 PANIC(KErrNotSupported);
1291 }
1292 }
1293
1294template <class T>
1295void TRgbCopy<T>::Copy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TBool aReversed)
1296 {
1297 const T* source = reinterpret_cast<const T*>(aSource);
1298 TUint32* target = aTarget;
1299 TUint32* endt = target + aBytes;
1300
1301 if(aReversed)
1302 {
1303 while(target < endt)
1304 {
1305 const T value = *source++;
1306 *(--endt) = iFunc(value);//iFunc(value).Value();
1307 }
1308 }
1309 else
1310 {
1311 while(target < endt)
1312 {
1313 const T value = *source++;
1314 *target++ = iFunc(value);//iFunc(value).Value();
1315 }
1316 }
1317 }
1318
1319template <class T>
1320void TRgbCopy<T>::FlipCopy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen, TBool aReversed)
1321 {
1322 const T* column = reinterpret_cast<const T*>(aSource);
1323 TUint32* target = aTarget;
1324 TUint32* endt = target + aBytes;
1325
1326 if(aReversed)
1327 {
1328 while(target < endt)
1329 {
1330 *(--endt) = iFunc(*column);
1331 column += aLineLen;
1332 }
1333 }
1334 else
1335 {
1336 while(target < endt)
1337 {
1338 *target++ = iFunc(*column);
1339 column += aLineLen;
1340 }
1341 }
1342 }
1343
1344template <class T> TUint32 TRgbCopy<T>::Gray256(const TUint8& aPixel)
1345 {
1346 const TUint32 px = aPixel << 16 | aPixel << 8 | aPixel;
1347 return px;
1348 }
1349
1350template <class T> TUint32 TRgbCopy<T>::Color256(const TUint8& aPixel)
1351 {
1352 return TRgb::Color256(aPixel).Value();
1353 }
1354
1355template <class T> TUint32 TRgbCopy<T>::Color4K(const TUint16& aPixel)
1356 {
1357 TUint32 col = (aPixel & 0xF00) << 12;
1358 col |= (aPixel & 0xF00) << 8;
1359
1360 col |= (aPixel & 0x0F0) << 8;
1361 col |= (aPixel & 0x0F0);
1362
1363 col |= (aPixel & 0x00F) << 4;
1364 col |= (aPixel & 0x00F);
1365
1366 return col;
1367 }
1368
1369template <class T> TUint32 TRgbCopy<T>::Color64K(const TUint16& aPixel)
1370 {
1371 TUint32 col = (aPixel & 0xF800)<< 8;
1372 col |= (aPixel & 0xE000) << 3;
1373
1374 col |= (aPixel & 0x07E0) << 5;
1375 col |= (aPixel & 0xC0) >> 1;
1376
1377 col |= (aPixel & 0x07E0) << 3;
1378 col |= (aPixel & 0x1C) >> 2;
1379
1380 return col;
1381 }
1382
1383template <class T> TUint32 TRgbCopy<T>::Color16M(const TUint32& aPixel)
1384 {
1385 return TRgb::Color16M(aPixel).Value();
1386 }
1387
1388template <class T> TUint32 TRgbCopy<T>::Color16MU(const TUint32& aPixel)
1389 {
1390 return TRgb::Color16MU(aPixel).Value();
1391 }
1392
1393template <class T> TUint32 TRgbCopy<T>::Color16MA(const TUint32& aPixel)
1394 {
1395 return TRgb::Color16MA(aPixel).Value();
1396 }
1397
1398typedef TUint64 TStackMem;
1399
1400LOCAL_C MRgbCopy* GetCopy(TAny* mem, TDisplayMode aMode)
1401 {
1402 if(aMode == EColor256 || aMode == EGray256)
1403 {
1404 return new (mem) TRgbCopy<TUint8>(aMode);
1405 }
1406 if(aMode == EColor4K || aMode == EColor64K)
1407 {
1408 return new (mem) TRgbCopy<TUint16>(aMode);
1409 }
1410 if(aMode == EColor16M || aMode == EColor16MU || aMode == EColor16MA)
1411 {
1412 return new (mem) TRgbCopy<TUint32>(aMode);
1413 }
1414 PANIC(KErrNotSupported);
1415 return NULL;
1416 }
1417
1418
1419void CDsa::CopySlowFlipReversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1420 {
1421 TStackMem mem = 0;
1422 GetCopy(&mem, aDsa.iSourceMode)->FlipCopy(aTarget, aSource, aBytes, aLineLen, ETrue);
1423 }
1424
1425void CDsa::CopySlowFlip(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1426 {
1427 TStackMem mem = 0;
1428 GetCopy(&mem, aDsa.iSourceMode)->FlipCopy(aTarget, aSource, aBytes, aLineLen, EFalse);
1429 }
1430
1431void CDsa::CopySlow(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1432 {
1433 TStackMem mem = 0;
1434 GetCopy(&mem, aDsa.iSourceMode)->Copy(aTarget, aSource, aBytes, EFalse);
1435 }
1436
1437void CDsa::CopySlowReversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1438 {
1439 TStackMem mem = 0;
1440 GetCopy(&mem, aDsa.iSourceMode)->Copy(aTarget, aSource, aBytes, ETrue);
1441 }
1442
1443////////////////////////////////////////////////////////////////////////////////////////////////////////////////7
diff --git a/apps/plugins/sdl/src/video/symbian/EKA2/dsa_old.cpp b/apps/plugins/sdl/src/video/symbian/EKA2/dsa_old.cpp
deleted file mode 100644
index 7e32de2cfd..0000000000
--- a/apps/plugins/sdl/src/video/symbian/EKA2/dsa_old.cpp
+++ /dev/null
@@ -1,1075 +0,0 @@
1#include "dsa.h"
2#include "sdlepocapi.h"
3#include <cdsb.h>
4
5LOCAL_C TInt BytesPerPixel(TDisplayMode aMode)
6 {
7 return ((TDisplayModeUtils::NumDisplayModeBitsPerPixel(aMode) - 1) >> 3) + 1;
8 }
9
10
11////////////////////////////////////////////////////////////////////////////////////////////////
12
13NONSHARABLE_CLASS(CDsaA) : public CDsa
14 {
15 public:
16 CDsaA(RWsSession& aSession);
17 private:
18 ~CDsaA();
19 TUint8* LockSurface();
20 void UnlockHWSurfaceRequestComplete();
21 void UnlockHwSurface();
22 void CreateSurfaceL();
23 void Wipe(TInt aLength);
24 void RecreateL();
25 void Free();
26 TInt ExternalUpdate() {return 0;}
27 private:
28 CFbsBitmap* iBmp;
29 };
30
31
32CDsaA::CDsaA(RWsSession& aSession) : CDsa(aSession)
33 {
34 }
35
36void CDsaA::Free()
37 {
38 delete iBmp;
39 iBmp = NULL;
40 }
41
42CDsaA::~CDsaA()
43 {
44 __ASSERT_DEBUG(iBmp == NULL, PANIC(KErrNotReady));
45 }
46
47TUint8* CDsaA::LockSurface()
48 {
49 iBmp->LockHeap();
50 return reinterpret_cast<TUint8*>(iBmp->DataAddress());
51 }
52
53void CDsaA::UnlockHWSurfaceRequestComplete()
54 {
55 PANIC(KErrNotSupported);
56 }
57
58void CDsaA::UnlockHwSurface()
59 {
60 iBmp->UnlockHeap();
61 SetUpdating(EFalse);
62 Dsa().Gc()->BitBlt(HwRect().iTl, iBmp);
63 Dsa().ScreenDevice()->Update();
64 }
65
66void CDsaA::CreateSurfaceL()
67 {
68 delete iBmp;
69 iBmp = NULL;
70 iBmp = new (ELeave) CFbsBitmap();
71 User::LeaveIfError(iBmp->Create(HwRect().Size(), DisplayMode()));
72 }
73
74void CDsaA::Wipe(TInt aLength) //dont call in drawing
75 {
76 iBmp->LockHeap();
77 Mem::FillZ(iBmp->DataAddress(), aLength);
78 iBmp->UnlockHeap();
79 }
80
81void CDsaA::RecreateL()
82 {
83 }
84
85//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
86
87NONSHARABLE_CLASS(MDsbObs)
88 {
89 public:
90 virtual void SurfaceReady() = 0;
91 virtual CDirectScreenBitmap& Dsb() = 0;
92 };
93
94NONSHARABLE_CLASS(CDsbSurface) : public CActive
95 {
96 public:
97 CDsbSurface(MDsbObs& aDsb);
98 TUint8* Address();
99 void Complete();
100 ~CDsbSurface();
101 private:
102 void RunL();
103 void DoCancel();
104 private:
105 MDsbObs& iDsb;
106 TUint8* iAddress;
107 };
108
109CDsbSurface::CDsbSurface(MDsbObs& aDsb) : CActive(CActive::EPriorityHigh) , iDsb(aDsb)
110 {
111 CActiveScheduler::Add(this);
112 }
113
114CDsbSurface::~CDsbSurface()
115 {
116 Cancel();
117 }
118
119void CDsbSurface::Complete()
120 {
121 if(iAddress != NULL && !IsActive())
122 {
123 iAddress = NULL;
124 SetActive();
125 iDsb.Dsb().EndUpdate(iStatus);
126 }
127 }
128
129TUint8* CDsbSurface::Address()
130 {
131 if(iAddress == NULL && !IsActive())
132 {
133 TAcceleratedBitmapInfo info;
134 if(KErrNone == iDsb.Dsb().BeginUpdate(info))
135 iAddress = info.iAddress;
136 }
137 return iAddress;
138 }
139
140void CDsbSurface::RunL()
141 {
142 iDsb.SurfaceReady();
143 }
144
145void CDsbSurface::DoCancel()
146 {
147 //empty
148 }
149
150NONSHARABLE_CLASS(CDsaB) : public CDsa, public MDsbObs
151 {
152 public:
153 CDsaB(RWsSession& aSession);
154 private:
155 ~CDsaB();
156 TUint8* LockSurface();
157 void UnlockHWSurfaceRequestComplete();
158 void UnlockHwSurface();
159 void CreateSurfaceL();
160 void Wipe(TInt aLength);
161 void RecreateL();
162 void ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice);
163 void Free();
164 CDirectScreenBitmap& Dsb();
165 void SurfaceReady();
166 TInt ExternalUpdate() {return 0;}
167 private:
168 CDsbSurface* iSurface1;
169 CDsbSurface* iSurface2;
170 CDirectScreenBitmap* iDsb;
171 };
172
173CDsaB::CDsaB(RWsSession& aSession) : CDsa(aSession)
174 {
175 }
176
177void CDsaB::Free()
178 {
179 }
180
181void CDsaB::UnlockHWSurfaceRequestComplete()
182 {
183 iSurface1->Complete();
184 iSurface2->Complete();
185 }
186
187void CDsaB::CreateSurfaceL()
188 {
189 }
190
191void CDsaB::Wipe(TInt aLength) //dont call in drawing
192 {
193 TUint8* addr = LockSurface();
194 if(addr != NULL)
195 {
196 Mem::FillZ(addr, aLength);
197 UnlockHwSurface();
198 }
199 }
200
201void CDsaB::UnlockHwSurface()
202 {
203 EpocSdlEnv::Request(CDsa::ERequestUpdate);
204 }
205
206TUint8* CDsaB::LockSurface()
207 {
208 TUint8* addr = iSurface1->Address();
209 if(addr == NULL)
210 addr = iSurface2->Address();
211 SetUpdating(addr == NULL);
212 return addr;
213 }
214
215void CDsaB::SurfaceReady()
216 {
217 SetUpdating(EFalse);
218 }
219
220CDirectScreenBitmap& CDsaB::Dsb()
221 {
222 return *iDsb;
223 }
224
225void CDsaB::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
226 {
227 if(iDsb == NULL)
228 iDsb = CDirectScreenBitmap::NewL();
229 CDsa::ConstructL(aWindow, aDevice);
230 iSurface1 = new (ELeave) CDsbSurface(*this);
231 iSurface2 = new (ELeave) CDsbSurface(*this);
232 }
233
234CDsaB::~CDsaB()
235 {
236 delete iSurface1;
237 delete iSurface2;
238 delete iDsb;
239 }
240
241void CDsaB::RecreateL()
242 {
243 iDsb->Close();
244 iDsb->Create(HwRect(), CDirectScreenBitmap::EDoubleBuffer);
245 }
246
247/////////////////////////////////////////////////////////////////////////////////////////////////////
248
249
250TSize CDsa::WindowSize() const
251 {
252 TSize size = HwRect().Size();
253 if(iStateFlags & EOrientation90)
254 {
255 const TInt tmp = size.iWidth;
256 size.iWidth = size.iHeight;
257 size.iHeight = tmp;
258 }
259 return size;
260 }
261
262void CDsa::SetSuspend()
263 {
264 iStateFlags |= ESdlThreadSuspend;
265 }
266
267void CDsa::ReleaseStop()
268 {
269 iStateFlags &= ~ESdlThreadExplicitStop;
270 }
271
272
273TBool CDsa::Stopped() const
274 {
275 return (iStateFlags & ESdlThreadExplicitStop);
276 }
277
278void CDsa::SetOrientation(CSDL::TOrientationMode aOrientation)
279 {
280 TInt flags = 0;
281 switch(aOrientation)
282 {
283 case CSDL::EOrientation90:
284 flags = EOrientation90;
285 break;
286 case CSDL::EOrientation180:
287 flags = EOrientation180;
288 break;
289 case CSDL::EOrientation270:
290 flags = EOrientation90 | EOrientation180;
291 break;
292 case CSDL::EOrientation0:
293 flags = 0;
294 break;
295 }
296 if(flags != (iStateFlags & EOrientationFlags))
297 {
298 iStateFlags |= EOrientationChanged;
299 iNewFlags = flags; //cannot be set during drawing...
300 }
301 }
302
303CDsa::~CDsa()
304 {
305 if(iDsa != NULL)
306 {
307 iDsa->Cancel();
308 }
309 delete iDsa;
310 User::Free(iLut256);
311 }
312
313void CDsa::ConstructL(RWindow& aWindow, CWsScreenDevice& aDevice)
314 {
315 if(iDsa != NULL)
316 {
317 iDsa->Cancel();
318 delete iDsa;
319 iDsa = NULL;
320 }
321
322
323 iDsa = CDirectScreenAccess::NewL(
324 iSession,
325 aDevice,
326 aWindow,
327 *this);
328
329 if(iLut256 == NULL)
330 iLut256 = (TUint32*) User::AllocL(256 * sizeof(TUint32));
331 iTargetMode = aWindow.DisplayMode();
332 iTargetBpp = BytesPerPixel(DisplayMode());
333 iTargetRect = TRect(aWindow.Position(), aWindow.Size());
334 RestartL();
335 }
336
337void CDsa::LockPalette(TBool aLock)
338 {
339 if(aLock)
340 iStateFlags |= EPaletteLocked;
341 else
342 iStateFlags &= ~EPaletteLocked;
343 }
344TInt CDsa::SetPalette(TInt aFirst, TInt aCount, TUint32* aPalette)
345 {
346 if(iLut256 == NULL)
347 return KErrNotFound;
348 const TInt count = aCount - aFirst;
349 if(count > 256)
350 return KErrArgument;
351 if(iStateFlags & EPaletteLocked)
352 return KErrNone;
353 for(TInt i = aFirst; i < count; i++) //not so busy here:-)
354 {
355 iLut256[i] = aPalette[i];
356 }
357 return KErrNone;
358 }
359
360
361
362
363void CDsa::RestartL()
364 {
365 //const TBool active = iDsa->IsActive();
366
367 //if(!active)
368 iDsa->StartL();
369
370 RRegion* r = iDsa->DrawingRegion();
371 iDsa->Gc()->SetClippingRegion(r);
372 TRect rect = r->BoundingRect();
373
374 if(rect.IsEmpty())
375 {
376 return;
377 }
378
379 iScreenRect = rect; //to ensure properly set, albeit may not(?) match to value SDL has - therefore may has to clip
380
381 RecreateL();
382
383 iStateFlags |= ERunning;
384// iScanLineWidth = iTargetBpp * HwRect().Width();
385 ReleaseStop();
386 if(iStateFlags & ESdlThreadSuspend)
387 {
388 EpocSdlEnv::Resume();
389 iStateFlags &= ~ ESdlThreadSuspend;
390 }
391 }
392
393CDsa::CDsa(RWsSession& aSession) :
394 iSession(aSession),
395 iStateFlags(0)
396 {
397// CActiveScheduler::Add(this);
398 iCFTable[0] = CopyMem;
399 iCFTable[1] = CopyMemFlipReversed;
400 iCFTable[2] = CopyMemReversed;
401 iCFTable[3] = CopyMemFlip;
402
403 iCFTable[4] = Copy256;
404 iCFTable[5] = Copy256FlipReversed;
405 iCFTable[6] = Copy256Reversed;
406 iCFTable[7] = Copy256Flip;
407
408
409 iCFTable[8] = CopySlow;
410 iCFTable[9] = CopySlowFlipReversed;
411 iCFTable[10] = CopySlowReversed;
412 iCFTable[11] = CopySlowFlip;
413 }
414
415RWsSession& CDsa::Session()
416 {
417 return iSession;
418 }
419
420
421
422TUint8* CDsa::LockHwSurface()
423 {
424 if((iStateFlags & EUpdating) == 0) //else frame is skipped
425 {
426 return LockSurface();
427 }
428 return NULL;
429 }
430
431/*
432void CDsa::RunL()
433 {
434 iStateFlags &= ~EUpdating;
435 }
436
437
438void CDsa::DoCancel()
439 {
440 iStateFlags &= ~EUpdating;
441 //nothing can do, just wait?
442 }
443*/
444
445TInt CDsa::AllocSurface(TBool aHwSurface, const TSize& aSize, TDisplayMode aMode)
446 {
447 if(aHwSurface && aMode != DisplayMode())
448 return KErrArgument;
449
450 iSourceMode = aMode;
451
452 iSourceBpp = BytesPerPixel(aMode);
453
454 const TSize size = WindowSize();
455 if(aSize.iWidth > size.iWidth)
456 return KErrTooBig;
457 if(aSize.iHeight > size.iHeight)
458 return KErrTooBig;
459
460 TRAPD(err, CreateSurfaceL());
461 if(err != KErrNone)
462 return err;
463
464
465 SetCopyFunction();
466
467 EpocSdlEnv::ObserverEvent(MSDLObserver::EEventWindowReserved);
468
469 return KErrNone;
470 }
471
472
473/*
474void SaveBmp(const TDesC& aName, const TAny* aData, TInt aLength, const TSize& aSz, TDisplayMode aMode)
475 {
476 CFbsBitmap* s = new CFbsBitmap();
477 s->Create(aSz, aMode);
478 s->LockHeap();
479 TUint32* addr = s->DataAddress();
480 Mem::Copy(addr, aData, aLength);
481 s->UnlockHeap();
482 s->Save(aName);
483 s->Reset();
484 delete s;
485 }
486
487void SaveBmp(const TDesC& aName, const TUint32* aData, const TSize& aSz)
488 {
489 CFbsBitmap* s = new CFbsBitmap();
490 s->Create(aSz, EColor64K);
491 TBitmapUtil bmp(s);
492 bmp.Begin(TPoint(0, 0));
493 for(TInt j = 0; j < aSz.iHeight; j++)
494 {
495 bmp.SetPos(TPoint(0, j));
496 for(TInt i = 0; i < aSz.iWidth; i++)
497 {
498 bmp.SetPixel(*aData);
499 aData++;
500 bmp.IncXPos();
501 }
502 }
503 bmp.End();
504 s->Save(aName);
505 s->Reset();
506 delete s;
507 }
508
509TBuf<16> FooName(TInt aFoo)
510 {
511 TBuf<16> b;
512 b.Format(_L("C:\\pic%d.mbm"), aFoo);
513 return b;
514 }
515*/
516void CDsa::ClipCopy(TUint8* aTarget, const TUint8* aSource, const TRect& aRect, const TRect& aTargetPos) const
517 {
518 TUint8* target = aTarget;
519 const TUint8* source = aSource;
520 const TInt lineWidth = aRect.Width();
521 source += iSourceBpp * (aRect.iTl.iY * lineWidth);
522 TInt sourceStartOffset = iSourceBpp * aRect.iTl.iX;
523 source += sourceStartOffset;
524 target += iTargetBpp * ((aTargetPos.iTl.iY + aRect.iTl.iY ) * lineWidth);
525 TInt targetStartOffset = iTargetBpp * (aRect.iTl.iX + aTargetPos.iTl.iX);
526 target += targetStartOffset;
527 TUint32* targetPtr = reinterpret_cast<TUint32*>(target);
528 const TInt targetWidth = HwRect().Size().iWidth;
529 const TInt height = aRect.Height();
530
531 TInt lineMove = iStateFlags & EOrientation90 ? 1 : lineWidth;
532
533 if(iStateFlags & EOrientation180)
534 {
535
536 targetPtr += targetWidth * (height - 1);
537
538 for(TInt i = 0; i < height; i++) //source is always smaller
539 {
540 iCopyFunction(*this, targetPtr, source, lineWidth, height);
541 source += lineMove;
542 targetPtr -= targetWidth;
543 }
544 }
545 else
546 {
547
548
549 for(TInt i = 0; i < height; i++) //source is always smaller
550 {
551 iCopyFunction(*this, targetPtr, source, lineWidth, height);
552 source += lineMove;
553 targetPtr += targetWidth;
554 }
555 }
556
557 }
558
559
560
561
562void CDsa::Wipe() //dont call in drawing
563 {
564 if(IsDsaAvailable())
565 Wipe(iTargetBpp * iScreenRect.Width() * iScreenRect.Height());
566 }
567
568void CDsa::SetCopyFunction()
569 {
570 //calculate offset to correct function in iCFTable according to given parameters
571 TInt function = 0;
572 const TInt KCopyFunctions = 4;
573 const TInt KOffsetToNative = 0;
574 const TInt KOffsetTo256 = KOffsetToNative + KCopyFunctions;
575 const TInt KOffsetToOtherModes = KOffsetTo256 + KCopyFunctions;
576 const TInt KOffsetTo90Functions = 1;
577 const TInt KOffsetTo180Functions = 2;
578
579 if(iSourceMode == DisplayMode())
580 function = KOffsetToNative; //0
581 else if(iSourceMode == EColor256)
582 function = KOffsetTo256; //4
583 else
584 function = KOffsetToOtherModes; //8
585
586 if(iStateFlags & EOrientation90)
587 function += KOffsetTo90Functions; // + 1
588 if(iStateFlags & EOrientation180)
589 function += KOffsetTo180Functions; //+ 2
590
591 iCopyFunction = iCFTable[function];
592
593 Wipe();
594 }
595
596inline void Rotate(TRect& aRect)
597 {
598 const TInt dx = aRect.iBr.iX - aRect.iTl.iX;
599 const TInt dy = aRect.iBr.iY - aRect.iTl.iY;
600
601 aRect.iBr.iX = aRect.iTl.iX + dy;
602 aRect.iBr.iY = aRect.iTl.iY + dx;
603
604 const TInt tmp = aRect.iTl.iX;
605 aRect.iTl.iX = aRect.iTl.iY;
606 aRect.iTl.iY = tmp;
607 }
608
609/*
610int bar = 0;
611*/
612TBool CDsa::AddUpdateRect(const TUint8* aBits, const TRect& aUpdateRect, const TRect& aRect)
613 {
614
615 if(iStateFlags & EOrientationChanged)
616 {
617 iStateFlags &= ~EOrientationFlags;
618 iStateFlags |= iNewFlags;
619 SetCopyFunction();
620 iStateFlags &= ~EOrientationChanged;
621 EpocSdlEnv::WaitDeviceChange();
622 return EFalse; //skip this frame as data is may be changed
623 }
624
625 if(iTargetAddr == NULL)
626 {
627 iTargetAddr = LockHwSurface();
628 }
629 TUint8* target = iTargetAddr;
630 if(target == NULL)
631 return EFalse;
632
633
634 TRect targetRect = HwRect();
635 TRect sourceRect = aRect;
636 TRect updateRect = aUpdateRect;
637
638 if(iStateFlags & EOrientation90)
639 {
640 Rotate(sourceRect);
641 Rotate(updateRect);
642 }
643
644 if(iSourceMode != DisplayMode() || targetRect != sourceRect || targetRect != updateRect || ((iStateFlags & EOrientationFlags) != 0))
645 {
646 sourceRect.Intersection(targetRect); //so source always smaller or equal than target
647 updateRect.Intersection(targetRect);
648 ClipCopy(target, aBits, updateRect, sourceRect);
649 }
650 else
651 {
652 const TInt byteCount = aRect.Width() * aRect.Height() * iSourceBpp; //this could be stored
653 Mem::Copy(target, aBits, byteCount);
654 }
655
656 return ETrue;
657 }
658
659CDsa* CDsa::CreateL(RWsSession& aSession)
660 {
661 if(EpocSdlEnv::Flags(CSDL::EDrawModeDSB))
662 {
663 TInt flags = CDirectScreenBitmap::ENone;
664 if(EpocSdlEnv::Flags(CSDL::EDrawModeDSBDoubleBuffer))
665 flags |= CDirectScreenBitmap::EDoubleBuffer;
666 if(EpocSdlEnv::Flags(CSDL::EDrawModeDSBIncrentalUpdate))
667 flags |= CDirectScreenBitmap::EIncrementalUpdate;
668 return new (ELeave) CDsaB(aSession);
669 }
670 else
671 return new (ELeave) CDsaA(aSession);
672 }
673
674void CDsa::CreateZoomerL(const TSize& aSize)
675 {
676 iSwSize = aSize;
677 iStateFlags |= EResizeRequest;
678 CreateSurfaceL();
679 SetTargetRect();
680 }
681
682TPoint CDsa::WindowCoordinates(const TPoint& aPoint) const
683 {
684 TPoint pos = aPoint - iScreenRect.iTl;
685 const TSize asz = iScreenRect.Size();
686 if(iStateFlags & EOrientation180)
687 {
688 pos.iX = asz.iWidth - pos.iX;
689 pos.iY = asz.iHeight - pos.iY;
690 }
691 if(iStateFlags & EOrientation90)
692 {
693 pos.iX = aPoint.iY;
694 pos.iY = aPoint.iX;
695 }
696 pos.iX <<= 16;
697 pos.iY <<= 16;
698 pos.iX /= asz.iWidth;
699 pos.iY /= asz.iHeight;
700 pos.iX *= iSwSize.iWidth;
701 pos.iY *= iSwSize.iHeight;
702 pos.iX >>= 16;
703 pos.iY >>= 16;
704 return pos;
705 }
706
707void CDsa::SetTargetRect()
708 {
709 iTargetRect = iScreenRect;
710 if(iStateFlags & EResizeRequest && EpocSdlEnv::Flags(CSDL::EAllowImageResizeKeepRatio))
711 {
712 const TSize asz = iScreenRect.Size();
713 const TSize sz = iSwSize;
714
715 TRect rect;
716
717 const TInt dh = (sz.iHeight << 16) / sz.iWidth;
718
719 if((asz.iWidth * dh ) >> 16 <= asz.iHeight)
720 {
721 rect.SetRect(TPoint(0, 0), TSize(asz.iWidth, (asz.iWidth * dh) >> 16));
722 }
723 else
724 {
725 const TInt dw = (sz.iWidth << 16) / sz.iHeight;
726 rect.SetRect(TPoint(0, 0), TSize((asz.iHeight * dw) >> 16, asz.iHeight));
727 }
728 rect.Move((asz.iWidth - rect.Size().iWidth) >> 1, (asz.iHeight - rect.Size().iHeight) >> 1);
729
730 iTargetRect = rect;
731 iTargetRect.Move(iScreenRect.iTl);
732
733 }
734 if(!(iStateFlags & EResizeRequest))
735 iSwSize = iScreenRect.Size();
736// iScanLineWidth = /*iTargetBpp **/ SwSize().iWidth;
737 }
738
739void CDsa::RecreateL()
740 {
741 }
742
743void CDsa::Free()
744 {
745 }
746
747void CDsa::UpdateSwSurface()
748 {
749 iTargetAddr = NULL;
750 UnlockHwSurface(); //could be faster if does not use AO, but only check status before redraw, then no context switch needed
751 }
752
753void CDsa::SetBlitter(MBlitter* aBlitter)
754 {
755 iBlitter = aBlitter;
756 }
757
758void CDsa::DrawOverlays()
759 {
760 const TInt last = iOverlays.Count() - 1;
761 for(TInt i = last; i >= 0 ; i--)
762 iOverlays[i].iOverlay->Draw(*iDsa->Gc(), HwRect(), SwSize());
763 }
764
765TInt CDsa::AppendOverlay(MOverlay& aOverlay, TInt aPriority)
766 {
767 TInt i;
768 for(i = 0; i < iOverlays.Count() && iOverlays[i].iPriority < aPriority; i++)
769 {}
770 const TOverlay overlay = {&aOverlay, aPriority};
771 return iOverlays.Insert(overlay, i);
772 }
773
774TInt CDsa::RemoveOverlay(MOverlay& aOverlay)
775 {
776 for(TInt i = 0; i < iOverlays.Count(); i++)
777 {
778 if(iOverlays[i].iOverlay == &aOverlay)
779 {
780 iOverlays.Remove(i);
781 return KErrNone;
782 }
783 }
784 return KErrNotFound;
785 }
786
787TInt CDsa::RedrawRequest()
788 {
789 if(!(iStateFlags & (EUpdating) && (iStateFlags & ERunning)))
790 {
791 return ExternalUpdate();
792 }
793 return KErrNotReady;
794 }
795
796
797void CDsa::Resume()
798 {
799 if(Stopped())
800 Restart(RDirectScreenAccess::ETerminateRegion);
801 }
802
803void CDsa::DoStop()
804 {
805 if(IsDsaAvailable())
806 iStateFlags |= ESdlThreadExplicitStop;
807 Stop();
808 }
809
810void CDsa::Stop()
811 {
812 iStateFlags &= ~ERunning;
813// Cancel(); //can be called only from main!
814 iDsa->Cancel();
815 }
816
817void CDsa::AbortNow(RDirectScreenAccess::TTerminationReasons /*aReason*/)
818 {
819// iStateFlags |= EChangeNotify;
820 Stop();
821 }
822
823void CDsa::Restart(RDirectScreenAccess::TTerminationReasons aReason)
824 {
825 if(aReason == RDirectScreenAccess::ETerminateRegion) //auto restart
826 {
827 TRAPD(err, RestartL());
828 PANIC_IF_ERROR(err);
829 }
830 }
831/*)
832TBool CDsa::ChangeTrigger()
833 {
834 const TBool change = iStateFlags & EChangeNotify;
835 iStateFlags &= ~EChangeNotify;
836 return change;
837 }
838*/
839/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
840
841void CDsa::Copy256(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
842 {
843 TUint32* target = aTarget;
844 const TUint32* endt = target + aBytes;
845 const TUint8* source = aSource;
846 while(target < endt)
847 {
848 *target++ = aDsa.iLut256[*source++];
849 }
850 }
851
852void CDsa::Copy256Reversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
853 {
854 const TUint32* target = aTarget;
855 TUint32* endt = aTarget + aBytes;
856 const TUint8* source = aSource;
857 while(target < endt)
858 {
859 *(--endt) = aDsa.iLut256[*source++];
860 }
861 }
862
863void CDsa::Copy256Flip(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
864 {
865 TUint32* target = aTarget;
866 const TUint32* endt = target + aBytes;
867 const TUint8* column = aSource;
868
869 while(target < endt)
870 {
871 *target++ = aDsa.iLut256[*column];
872 column += aLineLen;
873 }
874 }
875
876void CDsa::Copy256FlipReversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
877 {
878 const TUint32* target = aTarget;
879 TUint32* endt = aTarget + aBytes;
880 const TUint8* column = aSource;
881
882 while(target < endt)
883 {
884 *(--endt) = aDsa.iLut256[*column];
885 column += aLineLen;
886 }
887 }
888
889void CDsa::CopyMem(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
890 {
891 Mem::Copy(aTarget, aSource, aBytes);
892 }
893
894void CDsa::CopyMemFlip(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
895 {
896 TUint32* target = aTarget;
897 const TUint32* endt = target + aBytes;
898 const TUint32* column = reinterpret_cast<const TUint32*>(aSource);
899
900 while(target < endt)
901 {
902 *target++ = *column;
903 column += aLineLen;
904 }
905 }
906
907void CDsa::CopyMemReversed(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
908 {
909 const TUint32* target = aTarget;
910 TUint32* endt = aTarget + aBytes;
911 const TUint32* source = reinterpret_cast<const TUint32*>(aSource);
912 while(target < endt)
913 {
914 *(--endt) = *source++;
915 }
916 }
917
918
919void CDsa::CopyMemFlipReversed(const CDsa& /*aDsa*/, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
920 {
921 const TUint32* target = aTarget;
922 TUint32* endt = aTarget + aBytes;
923 const TUint32* column = reinterpret_cast<const TUint32*>(aSource);
924
925 while(target < endt)
926 {
927 *(--endt) = *column;
928 column += aLineLen;
929 }
930 }
931
932
933typedef TRgb (*TRgbFunc) (TInt aValue);
934
935LOCAL_C TRgb rgb16MA(TInt aValue)
936 {
937 return TRgb::Color16MA(aValue);
938 }
939
940NONSHARABLE_CLASS(MRgbCopy)
941 {
942 public:
943 virtual void Copy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TBool aReversed) = 0;
944 virtual void FlipCopy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen, TBool aReversed) = 0;
945 };
946template <class T>
947NONSHARABLE_CLASS(TRgbCopy) : public MRgbCopy
948 {
949 public:
950 TRgbCopy(TDisplayMode aMode);
951 void* operator new(TUint aBytes, TAny* aMem);
952 void Copy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TBool aReversed);
953 void FlipCopy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen, TBool aReversed);
954 private:
955 TRgbFunc iFunc;
956 };
957
958template <class T>
959void* TRgbCopy<T>::operator new(TUint /*aBytes*/, TAny* aMem)
960 {
961 return aMem;
962 }
963
964template <class T>
965TRgbCopy<T>::TRgbCopy(TDisplayMode aMode)
966 {
967 switch(aMode)
968 {
969 case EGray256 : iFunc = TRgb::Gray256; break;
970 case EColor256 : iFunc = TRgb::Color256; break;
971 case EColor4K : iFunc = TRgb::Color4K; break;
972 case EColor64K : iFunc = TRgb::Color64K; break;
973 case EColor16M : iFunc = TRgb::Color16M; break;
974 case EColor16MU : iFunc = TRgb::Color16MU; break;
975 case EColor16MA : iFunc = rgb16MA; break;
976 default:
977 PANIC(KErrNotSupported);
978 }
979 }
980
981template <class T>
982void TRgbCopy<T>::Copy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TBool aReversed)
983 {
984 const T* source = reinterpret_cast<const T*>(aSource);
985 TUint32* target = aTarget;
986 TUint32* endt = target + aBytes;
987
988 if(aReversed)
989 {
990 while(target < endt)
991 {
992 TUint32 value = *source++;
993 *(--endt) = iFunc(value).Value();
994 }
995 }
996 else
997 {
998 while(target < endt)
999 {
1000 TUint32 value = *source++;
1001 *target++ = iFunc(value).Value();
1002 }
1003 }
1004 }
1005
1006template <class T>
1007void TRgbCopy<T>::FlipCopy(TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen, TBool aReversed)
1008 {
1009 const T* column = reinterpret_cast<const T*>(aSource);
1010 TUint32* target = aTarget;
1011 TUint32* endt = target + aBytes;
1012
1013 if(aReversed)
1014 {
1015 while(target < endt)
1016 {
1017 *(--endt) = iFunc(*column).Value();
1018 column += aLineLen;
1019 }
1020 }
1021 else
1022 {
1023 while(target < endt)
1024 {
1025 *target++ = iFunc(*column).Value();
1026 column += aLineLen;
1027 }
1028 }
1029 }
1030
1031
1032typedef TUint64 TStackMem;
1033
1034LOCAL_C MRgbCopy* GetCopy(TAny* mem, TDisplayMode aMode)
1035 {
1036 if(aMode == EColor256 || aMode == EGray256)
1037 {
1038 return new (mem) TRgbCopy<TUint8>(aMode);
1039 }
1040 if(aMode == EColor4K || aMode == EColor64K)
1041 {
1042 return new (mem) TRgbCopy<TUint16>(aMode);
1043 }
1044 if(aMode == EColor16M || aMode == EColor16MU || aMode == EColor16MA)
1045 {
1046 return new (mem) TRgbCopy<TUint32>(aMode);
1047 }
1048 PANIC(KErrNotSupported);
1049 return NULL;
1050 }
1051
1052
1053void CDsa::CopySlowFlipReversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1054 {
1055 TStackMem mem = 0;
1056 GetCopy(&mem, aDsa.iSourceMode)->FlipCopy(aTarget, aSource, aBytes, aLineLen, ETrue);
1057 }
1058
1059void CDsa::CopySlowFlip(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt aLineLen)
1060 {
1061 TStackMem mem = 0;
1062 GetCopy(&mem, aDsa.iSourceMode)->FlipCopy(aTarget, aSource, aBytes, aLineLen, EFalse);
1063 }
1064
1065void CDsa::CopySlow(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1066 {
1067 TStackMem mem = 0;
1068 GetCopy(&mem, aDsa.iSourceMode)->Copy(aTarget, aSource, aBytes, EFalse);
1069 }
1070
1071void CDsa::CopySlowReversed(const CDsa& aDsa, TUint32* aTarget, const TUint8* aSource, TInt aBytes, TInt)
1072 {
1073 TStackMem mem = 0;
1074 GetCopy(&mem, aDsa.iSourceMode)->Copy(aTarget, aSource, aBytes, ETrue);
1075 } \ No newline at end of file
diff --git a/apps/plugins/sdl/src/video/symbian/SDL_epocevents_c.h b/apps/plugins/sdl/src/video/symbian/SDL_epocevents_c.h
deleted file mode 100644
index 8e10a04293..0000000000
--- a/apps/plugins/sdl/src/video/symbian/SDL_epocevents_c.h
+++ /dev/null
@@ -1,60 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@devolution.com
21*/
22
23/*
24 SDL_epocevents_c.h
25 Handle the event stream, converting Epoc events into SDL events
26
27 Epoc version by Hannu Viitala (hannu.j.viitala@mbnet.fi) and Markus Mertama
28
29*/
30
31
32#ifdef SAVE_RCSID
33static char rcsid =
34 "@(#) $Id: SDL_aaevents_c.h,v 1.1.2.2 2000/03/16 15:20:39 hercules Exp $";
35#endif
36
37extern "C" {
38#include "SDL_sysvideo.h"
39//#include "SDL_epocvideo.h"
40}
41
42
43
44#define MAX_SCANCODE 255
45
46/* Variables and functions exported by SDL_sysevents.c to other parts
47 of the native video subsystem (SDL_sysvideo.c)
48*/
49
50/* Hidden "this" pointer for the video functions */
51#define _THIS SDL_VideoDevice *_this
52#define Private _this->hidden
53
54extern "C" {
55extern void EPOC_InitOSKeymap(_THIS);
56extern void EPOC_PumpEvents(_THIS);
57}
58
59extern TBool isCursorVisible;
60
diff --git a/apps/plugins/sdl/src/video/vgl/SDL_vglevents.c b/apps/plugins/sdl/src/video/vgl/SDL_vglevents.c
deleted file mode 100644
index fa6c9e7b8c..0000000000
--- a/apps/plugins/sdl/src/video/vgl/SDL_vglevents.c
+++ /dev/null
@@ -1,299 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting X11 events into SDL events */
25
26#include <stdio.h>
27
28#include <sys/fbio.h>
29#include <sys/consio.h>
30#include <sys/kbio.h>
31#include <vgl.h>
32
33#include "SDL.h"
34#include "SDL_thread.h"
35#include "../../events/SDL_sysevents.h"
36#include "../../events/SDL_events_c.h"
37#include "SDL_vglvideo.h"
38#include "SDL_vglevents_c.h"
39
40/* The translation tables from a console scancode to a SDL keysym */
41/* FIXME: Free the keymap when we shut down the video mode */
42static keymap_t *vga_keymap = NULL;
43static SDLKey keymap[128];
44static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym);
45
46static int posted = 0;
47static int oldx = -1;
48static int oldy = -1;
49static struct mouse_info mouseinfo;
50
51/* Ugh, we have to duplicate the kernel's keysym mapping code...
52 Oh, it's not so bad. :-)
53
54 FIXME: Add keyboard LED handling code
55 */
56int VGL_initkeymaps(int fd)
57{
58 vga_keymap = SDL_malloc(sizeof(keymap_t));
59 if ( ! vga_keymap ) {
60 SDL_OutOfMemory();
61 return(-1);
62 }
63 if (ioctl(fd, GIO_KEYMAP, vga_keymap) == -1) {
64 SDL_free(vga_keymap);
65 vga_keymap = NULL;
66 SDL_SetError("Unable to get keyboard map");
67 return(-1);
68 }
69 return(0);
70}
71
72static void handle_keyboard(_THIS)
73{
74 SDL_keysym keysym;
75 int c, pressed, scancode;
76
77 while ((c = VGLKeyboardGetCh()) != 0) {
78 scancode = c & 0x7F;
79 if (c & 0x80) {
80 pressed = SDL_RELEASED;
81 } else {
82 pressed = SDL_PRESSED;
83 }
84
85 posted += SDL_PrivateKeyboard(pressed,
86 TranslateKey(scancode, &keysym));
87 }
88}
89
90int VGL_initmouse(int fd)
91{
92 mouseinfo.operation = MOUSE_GETINFO;
93 if (ioctl(fd, CONS_MOUSECTL, &mouseinfo) != 0)
94 return -1;
95
96 return 0;
97}
98
99static void handle_mouse(_THIS)
100{
101 char buttons;
102 int x, y;
103 int button_state, state_changed, state;
104 int i;
105
106 ioctl(0, CONS_MOUSECTL, &mouseinfo);
107 x = mouseinfo.u.data.x;
108 y = mouseinfo.u.data.y;
109 buttons = mouseinfo.u.data.buttons;
110
111 if ((x != oldx) || (y != oldy)) {
112 posted += SDL_PrivateMouseMotion(0, 0, x, y);
113 oldx = x;
114 oldy = y;
115 }
116
117 /* See what's changed */
118 button_state = SDL_GetMouseState(NULL, NULL);
119 state_changed = button_state ^ buttons;
120 for (i = 0; i < 8; i++) {
121 if (state_changed & (1<<i)) {
122 if (buttons & (1<<i)) {
123 state = SDL_PRESSED;
124 } else {
125 state = SDL_RELEASED;
126 }
127 posted += SDL_PrivateMouseButton(state, i + 1, 0, 0);
128 }
129 }
130}
131
132
133void VGL_PumpEvents(_THIS)
134{
135 do {
136 posted = 0;
137 handle_keyboard(this);
138 handle_mouse(this);
139 } while (posted != 0);
140}
141
142void VGL_InitOSKeymap(_THIS)
143{
144 int i;
145
146 /* Initialize the BeOS key translation table */
147 for ( i=0; i<SDL_arraysize(keymap); ++i )
148 keymap[i] = SDLK_UNKNOWN;
149
150 keymap[SCANCODE_ESCAPE] = SDLK_ESCAPE;
151 keymap[SCANCODE_1] = SDLK_1;
152 keymap[SCANCODE_2] = SDLK_2;
153 keymap[SCANCODE_3] = SDLK_3;
154 keymap[SCANCODE_4] = SDLK_4;
155 keymap[SCANCODE_5] = SDLK_5;
156 keymap[SCANCODE_6] = SDLK_6;
157 keymap[SCANCODE_7] = SDLK_7;
158 keymap[SCANCODE_8] = SDLK_8;
159 keymap[SCANCODE_9] = SDLK_9;
160 keymap[SCANCODE_0] = SDLK_0;
161 keymap[SCANCODE_MINUS] = SDLK_MINUS;
162 keymap[SCANCODE_EQUAL] = SDLK_EQUALS;
163 keymap[SCANCODE_BACKSPACE] = SDLK_BACKSPACE;
164 keymap[SCANCODE_TAB] = SDLK_TAB;
165 keymap[SCANCODE_Q] = SDLK_q;
166 keymap[SCANCODE_W] = SDLK_w;
167 keymap[SCANCODE_E] = SDLK_e;
168 keymap[SCANCODE_R] = SDLK_r;
169 keymap[SCANCODE_T] = SDLK_t;
170 keymap[SCANCODE_Y] = SDLK_y;
171 keymap[SCANCODE_U] = SDLK_u;
172 keymap[SCANCODE_I] = SDLK_i;
173 keymap[SCANCODE_O] = SDLK_o;
174 keymap[SCANCODE_P] = SDLK_p;
175 keymap[SCANCODE_BRACKET_LEFT] = SDLK_LEFTBRACKET;
176 keymap[SCANCODE_BRACKET_RIGHT] = SDLK_RIGHTBRACKET;
177 keymap[SCANCODE_ENTER] = SDLK_RETURN;
178 keymap[SCANCODE_LEFTCONTROL] = SDLK_LCTRL;
179 keymap[SCANCODE_A] = SDLK_a;
180 keymap[SCANCODE_S] = SDLK_s;
181 keymap[SCANCODE_D] = SDLK_d;
182 keymap[SCANCODE_F] = SDLK_f;
183 keymap[SCANCODE_G] = SDLK_g;
184 keymap[SCANCODE_H] = SDLK_h;
185 keymap[SCANCODE_J] = SDLK_j;
186 keymap[SCANCODE_K] = SDLK_k;
187 keymap[SCANCODE_L] = SDLK_l;
188 keymap[SCANCODE_SEMICOLON] = SDLK_SEMICOLON;
189 keymap[SCANCODE_APOSTROPHE] = SDLK_QUOTE;
190 keymap[SCANCODE_GRAVE] = SDLK_BACKQUOTE;
191 keymap[SCANCODE_LEFTSHIFT] = SDLK_LSHIFT;
192 keymap[SCANCODE_BACKSLASH] = SDLK_BACKSLASH;
193 keymap[SCANCODE_Z] = SDLK_z;
194 keymap[SCANCODE_X] = SDLK_x;
195 keymap[SCANCODE_C] = SDLK_c;
196 keymap[SCANCODE_V] = SDLK_v;
197 keymap[SCANCODE_B] = SDLK_b;
198 keymap[SCANCODE_N] = SDLK_n;
199 keymap[SCANCODE_M] = SDLK_m;
200 keymap[SCANCODE_COMMA] = SDLK_COMMA;
201 keymap[SCANCODE_PERIOD] = SDLK_PERIOD;
202 keymap[SCANCODE_SLASH] = SDLK_SLASH;
203 keymap[SCANCODE_RIGHTSHIFT] = SDLK_RSHIFT;
204 keymap[SCANCODE_KEYPADMULTIPLY] = SDLK_KP_MULTIPLY;
205 keymap[SCANCODE_LEFTALT] = SDLK_LALT;
206 keymap[SCANCODE_SPACE] = SDLK_SPACE;
207 keymap[SCANCODE_CAPSLOCK] = SDLK_CAPSLOCK;
208 keymap[SCANCODE_F1] = SDLK_F1;
209 keymap[SCANCODE_F2] = SDLK_F2;
210 keymap[SCANCODE_F3] = SDLK_F3;
211 keymap[SCANCODE_F4] = SDLK_F4;
212 keymap[SCANCODE_F5] = SDLK_F5;
213 keymap[SCANCODE_F6] = SDLK_F6;
214 keymap[SCANCODE_F7] = SDLK_F7;
215 keymap[SCANCODE_F8] = SDLK_F8;
216 keymap[SCANCODE_F9] = SDLK_F9;
217 keymap[SCANCODE_F10] = SDLK_F10;
218 keymap[SCANCODE_NUMLOCK] = SDLK_NUMLOCK;
219 keymap[SCANCODE_SCROLLLOCK] = SDLK_SCROLLOCK;
220 keymap[SCANCODE_KEYPAD7] = SDLK_KP7;
221 keymap[SCANCODE_CURSORUPLEFT] = SDLK_KP7;
222 keymap[SCANCODE_KEYPAD8] = SDLK_KP8;
223 keymap[SCANCODE_CURSORUP] = SDLK_KP8;
224 keymap[SCANCODE_KEYPAD9] = SDLK_KP9;
225 keymap[SCANCODE_CURSORUPRIGHT] = SDLK_KP9;
226 keymap[SCANCODE_KEYPADMINUS] = SDLK_KP_MINUS;
227 keymap[SCANCODE_KEYPAD4] = SDLK_KP4;
228 keymap[SCANCODE_CURSORLEFT] = SDLK_KP4;
229 keymap[SCANCODE_KEYPAD5] = SDLK_KP5;
230 keymap[SCANCODE_KEYPAD6] = SDLK_KP6;
231 keymap[SCANCODE_CURSORRIGHT] = SDLK_KP6;
232 keymap[SCANCODE_KEYPADPLUS] = SDLK_KP_PLUS;
233 keymap[SCANCODE_KEYPAD1] = SDLK_KP1;
234 keymap[SCANCODE_CURSORDOWNLEFT] = SDLK_KP1;
235 keymap[SCANCODE_KEYPAD2] = SDLK_KP2;
236 keymap[SCANCODE_CURSORDOWN] = SDLK_KP2;
237 keymap[SCANCODE_KEYPAD3] = SDLK_KP3;
238 keymap[SCANCODE_CURSORDOWNRIGHT] = SDLK_KP3;
239 keymap[SCANCODE_KEYPAD0] = SDLK_KP0;
240 keymap[SCANCODE_KEYPADPERIOD] = SDLK_KP_PERIOD;
241 keymap[SCANCODE_LESS] = SDLK_LESS;
242 keymap[SCANCODE_F11] = SDLK_F11;
243 keymap[SCANCODE_F12] = SDLK_F12;
244 keymap[SCANCODE_KEYPADENTER] = SDLK_KP_ENTER;
245 keymap[SCANCODE_RIGHTCONTROL] = SDLK_RCTRL;
246 keymap[SCANCODE_CONTROL] = SDLK_RCTRL;
247 keymap[SCANCODE_KEYPADDIVIDE] = SDLK_KP_DIVIDE;
248 keymap[SCANCODE_PRINTSCREEN] = SDLK_PRINT;
249 keymap[SCANCODE_RIGHTALT] = SDLK_RALT;
250 keymap[SCANCODE_BREAK] = SDLK_BREAK;
251 keymap[SCANCODE_BREAK_ALTERNATIVE] = SDLK_UNKNOWN;
252 keymap[SCANCODE_HOME] = SDLK_HOME;
253 keymap[SCANCODE_CURSORBLOCKUP] = SDLK_UP;
254 keymap[SCANCODE_PAGEUP] = SDLK_PAGEUP;
255 keymap[SCANCODE_CURSORBLOCKLEFT] = SDLK_LEFT;
256 keymap[SCANCODE_CURSORBLOCKRIGHT] = SDLK_RIGHT;
257 keymap[SCANCODE_END] = SDLK_END;
258 keymap[SCANCODE_CURSORBLOCKDOWN] = SDLK_DOWN;
259 keymap[SCANCODE_PAGEDOWN] = SDLK_PAGEDOWN;
260 keymap[SCANCODE_INSERT] = SDLK_INSERT;
261 keymap[SCANCODE_REMOVE] = SDLK_DELETE;
262 keymap[119] = SDLK_PAUSE;
263 keymap[SCANCODE_RIGHTWIN] = SDLK_RSUPER;
264 keymap[SCANCODE_LEFTWIN] = SDLK_LSUPER;
265 keymap[127] = SDLK_MENU;
266}
267
268static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym)
269{
270 /* Set the keysym information */
271 keysym->scancode = scancode;
272 keysym->sym = keymap[scancode];
273 keysym->mod = KMOD_NONE;
274
275 /* If UNICODE is on, get the UNICODE value for the key */
276 keysym->unicode = 0;
277 if ( SDL_TranslateUNICODE && vga_keymap ) {
278 int map;
279 SDLMod modstate;
280
281 modstate = SDL_GetModState();
282 map = 0;
283 if ( modstate & KMOD_SHIFT ) {
284 map += 1;
285 }
286 if ( modstate & KMOD_CTRL ) {
287 map += 2;
288 }
289 if ( modstate & KMOD_ALT ) {
290 map += 4;
291 }
292 if ( !(vga_keymap->key[scancode].spcl & (0x80 >> map)) ) {
293 keysym->unicode = vga_keymap->key[scancode].map[map];
294 }
295
296 }
297 return(keysym);
298}
299
diff --git a/apps/plugins/sdl/src/video/vgl/SDL_vglevents_c.h b/apps/plugins/sdl/src/video/vgl/SDL_vglevents_c.h
deleted file mode 100644
index 614cab55a4..0000000000
--- a/apps/plugins/sdl/src/video/vgl/SDL_vglevents_c.h
+++ /dev/null
@@ -1,155 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_vglvideo.h"
25
26/* Variables and functions exported by SDL_sysevents.c to other parts
27 of the native video subsystem (SDL_sysvideo.c)
28*/
29extern int VGL_initkeymaps(int fd);
30extern int VGL_initmouse(int fd);
31extern void VGL_keyboardcallback(int scancode, int pressed);
32
33extern void VGL_InitOSKeymap(_THIS);
34extern void VGL_PumpEvents(_THIS);
35
36/* Mouse buttons */
37#define MOUSE_LEFTBUTTON 0x01
38#define MOUSE_MIDDLEBUTTON 0x02
39#define MOUSE_RIGHTBUTTON 0x04
40
41/* Scancodes */
42#define SCANCODE_ESCAPE 1
43#define SCANCODE_1 2
44#define SCANCODE_2 3
45#define SCANCODE_3 4
46#define SCANCODE_4 5
47#define SCANCODE_5 6
48#define SCANCODE_6 7
49#define SCANCODE_7 8
50#define SCANCODE_8 9
51#define SCANCODE_9 10
52#define SCANCODE_0 11
53#define SCANCODE_MINUS 12
54#define SCANCODE_EQUAL 13
55#define SCANCODE_BACKSPACE 14
56#define SCANCODE_TAB 15
57#define SCANCODE_Q 16
58#define SCANCODE_W 17
59#define SCANCODE_E 18
60#define SCANCODE_R 19
61#define SCANCODE_T 20
62#define SCANCODE_Y 21
63#define SCANCODE_U 22
64#define SCANCODE_I 23
65#define SCANCODE_O 24
66#define SCANCODE_P 25
67#define SCANCODE_BRACKET_LEFT 26
68#define SCANCODE_BRACKET_RIGHT 27
69#define SCANCODE_ENTER 28
70#define SCANCODE_LEFTCONTROL 29
71#define SCANCODE_A 30
72#define SCANCODE_S 31
73#define SCANCODE_D 32
74#define SCANCODE_F 33
75#define SCANCODE_G 34
76#define SCANCODE_H 35
77#define SCANCODE_J 36
78#define SCANCODE_K 37
79#define SCANCODE_L 38
80#define SCANCODE_SEMICOLON 39
81#define SCANCODE_APOSTROPHE 40
82#define SCANCODE_GRAVE 41
83#define SCANCODE_LEFTSHIFT 42
84#define SCANCODE_BACKSLASH 43
85#define SCANCODE_Z 44
86#define SCANCODE_X 45
87#define SCANCODE_C 46
88#define SCANCODE_V 47
89#define SCANCODE_B 48
90#define SCANCODE_N 49
91#define SCANCODE_M 50
92#define SCANCODE_COMMA 51
93#define SCANCODE_PERIOD 52
94#define SCANCODE_SLASH 53
95#define SCANCODE_RIGHTSHIFT 54
96#define SCANCODE_KEYPADMULTIPLY 55
97#define SCANCODE_LEFTALT 56
98#define SCANCODE_SPACE 57
99#define SCANCODE_CAPSLOCK 58
100#define SCANCODE_F1 59
101#define SCANCODE_F2 60
102#define SCANCODE_F3 61
103#define SCANCODE_F4 62
104#define SCANCODE_F5 63
105#define SCANCODE_F6 64
106#define SCANCODE_F7 65
107#define SCANCODE_F8 66
108#define SCANCODE_F9 67
109#define SCANCODE_F10 68
110#define SCANCODE_NUMLOCK 69
111#define SCANCODE_SCROLLLOCK 70
112#define SCANCODE_KEYPAD7 71
113#define SCANCODE_CURSORUPLEFT 71
114#define SCANCODE_KEYPAD8 72
115#define SCANCODE_CURSORUP 72
116#define SCANCODE_KEYPAD9 73
117#define SCANCODE_CURSORUPRIGHT 73
118#define SCANCODE_KEYPADMINUS 74
119#define SCANCODE_KEYPAD4 75
120#define SCANCODE_CURSORLEFT 75
121#define SCANCODE_KEYPAD5 76
122#define SCANCODE_KEYPAD6 77
123#define SCANCODE_CURSORRIGHT 77
124#define SCANCODE_KEYPADPLUS 78
125#define SCANCODE_KEYPAD1 79
126#define SCANCODE_CURSORDOWNLEFT 79
127#define SCANCODE_KEYPAD2 80
128#define SCANCODE_CURSORDOWN 80
129#define SCANCODE_KEYPAD3 81
130#define SCANCODE_CURSORDOWNRIGHT 81
131#define SCANCODE_KEYPAD0 82
132#define SCANCODE_KEYPADPERIOD 83
133#define SCANCODE_LESS 86
134#define SCANCODE_F11 87
135#define SCANCODE_F12 88
136#define SCANCODE_KEYPADENTER 89
137#define SCANCODE_RIGHTCONTROL 90
138#define SCANCODE_CONTROL 107
139#define SCANCODE_KEYPADDIVIDE 91
140#define SCANCODE_PRINTSCREEN 92
141#define SCANCODE_RIGHTALT 93
142#define SCANCODE_BREAK 104 /* Beware: is 119 */
143#define SCANCODE_BREAK_ALTERNATIVE 104 /* on some keyboards! */
144#define SCANCODE_HOME 94
145#define SCANCODE_CURSORBLOCKUP 95 /* Cursor key block */
146#define SCANCODE_PAGEUP 96
147#define SCANCODE_CURSORBLOCKLEFT 97 /* Cursor key block */
148#define SCANCODE_CURSORBLOCKRIGHT 98 /* Cursor key block */
149#define SCANCODE_END 99
150#define SCANCODE_CURSORBLOCKDOWN 100 /* Cursor key block */
151#define SCANCODE_PAGEDOWN 101
152#define SCANCODE_INSERT 102
153#define SCANCODE_REMOVE 103
154#define SCANCODE_RIGHTWIN 106
155#define SCANCODE_LEFTWIN 105
diff --git a/apps/plugins/sdl/src/video/vgl/SDL_vglmouse.c b/apps/plugins/sdl/src/video/vgl/SDL_vglmouse.c
deleted file mode 100644
index 466f1c51d3..0000000000
--- a/apps/plugins/sdl/src/video/vgl/SDL_vglmouse.c
+++ /dev/null
@@ -1,56 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_mouse.h"
25#include "../../events/SDL_events_c.h"
26#include "SDL_vglvideo.h"
27#include "SDL_vglmouse_c.h"
28
29
30/* The implementation dependent data for the window manager cursor */
31struct WMcursor {
32 int unused;
33};
34
35
36void VGL_FreeWMCursor(_THIS, WMcursor *cursor)
37{
38 return;
39}
40
41WMcursor *VGL_CreateWMCursor(_THIS,
42 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
43{
44 return(NULL);
45}
46
47int VGL_ShowWMCursor(_THIS, WMcursor *cursor)
48{
49 return(0);
50}
51
52void VGL_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
53{
54 SDL_PrivateMouseMotion(0, 0, x, y);
55}
56
diff --git a/apps/plugins/sdl/src/video/vgl/SDL_vglmouse_c.h b/apps/plugins/sdl/src/video/vgl/SDL_vglmouse_c.h
deleted file mode 100644
index f579d654d7..0000000000
--- a/apps/plugins/sdl/src/video/vgl/SDL_vglmouse_c.h
+++ /dev/null
@@ -1,32 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_vglvideo.h"
25
26/* Functions to be exported */
27extern void VGL_FreeWMCursor(_THIS, WMcursor *cursor);
28extern WMcursor *VGL_CreateWMCursor(_THIS,
29 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
30extern int VGL_ShowWMCursor(_THIS, WMcursor *cursor);
31extern void VGL_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
32
diff --git a/apps/plugins/sdl/src/video/vgl/SDL_vglvideo.c b/apps/plugins/sdl/src/video/vgl/SDL_vglvideo.c
deleted file mode 100644
index 0b61615593..0000000000
--- a/apps/plugins/sdl/src/video/vgl/SDL_vglvideo.c
+++ /dev/null
@@ -1,624 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* libvga based SDL video driver implementation.
25*/
26
27#include <err.h>
28#include <osreldate.h>
29#include <unistd.h>
30#include <sys/stat.h>
31
32#include <sys/fbio.h>
33#include <sys/consio.h>
34#include <sys/kbio.h>
35#include <vgl.h>
36
37#include "SDL_video.h"
38#include "SDL_mouse.h"
39#include "../SDL_sysvideo.h"
40#include "../SDL_pixels_c.h"
41#include "../../events/SDL_events_c.h"
42#include "SDL_vglvideo.h"
43#include "SDL_vglevents_c.h"
44#include "SDL_vglmouse_c.h"
45
46
47/* Initialization/Query functions */
48static int VGL_VideoInit(_THIS, SDL_PixelFormat *vformat);
49static SDL_Rect **VGL_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
50static SDL_Surface *VGL_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
51static int VGL_SetColors(_THIS, int firstcolor, int ncolors,
52 SDL_Color *colors);
53static void VGL_VideoQuit(_THIS);
54
55/* Hardware surface functions */
56static int VGL_AllocHWSurface(_THIS, SDL_Surface *surface);
57static int VGL_LockHWSurface(_THIS, SDL_Surface *surface);
58static int VGL_FlipHWSurface(_THIS, SDL_Surface *surface);
59static void VGL_UnlockHWSurface(_THIS, SDL_Surface *surface);
60static void VGL_FreeHWSurface(_THIS, SDL_Surface *surface);
61
62/* Misc function */
63static VGLMode ** VGLListModes(int depth, int mem_model);
64
65/* VGL driver bootstrap functions */
66
67static int VGL_Available(void)
68{
69 /*
70 * Check to see if we are root and stdin is a
71 * virtual console. Also try to ensure that
72 * modes other than 320x200 are available
73 */
74 int console, hires_available, i;
75 VGLMode **modes;
76
77 console = STDIN_FILENO;
78 if ( console >= 0 ) {
79 struct stat sb;
80 struct vt_mode dummy;
81
82 if ( (fstat(console, &sb) < 0) ||
83 (ioctl(console, VT_GETMODE, &dummy) < 0) ) {
84 console = -1;
85 }
86 }
87 if (geteuid() != 0 && console == -1)
88 return 0;
89
90 modes = VGLListModes(8, V_INFO_MM_DIRECT | V_INFO_MM_PACKED);
91 hires_available = 0;
92 for (i = 0; modes[i] != NULL; i++) {
93 if ((modes[i]->ModeInfo.Xsize > 320) &&
94 (modes[i]->ModeInfo.Ysize > 200) &&
95 ((modes[i]->ModeInfo.Type == VIDBUF8) ||
96 (modes[i]->ModeInfo.Type == VIDBUF16) ||
97 (modes[i]->ModeInfo.Type == VIDBUF32))) {
98 hires_available = 1;
99 break;
100 }
101 }
102 return hires_available;
103}
104
105static void VGL_DeleteDevice(SDL_VideoDevice *device)
106{
107 SDL_free(device->hidden);
108 SDL_free(device);
109}
110
111static SDL_VideoDevice *VGL_CreateDevice(int devindex)
112{
113 SDL_VideoDevice *device;
114
115 /* Initialize all variables that we clean on shutdown */
116 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
117 if ( device ) {
118 SDL_memset(device, 0, (sizeof *device));
119 device->hidden = (struct SDL_PrivateVideoData *)
120 SDL_malloc((sizeof *device->hidden));
121 }
122 if ( (device == NULL) || (device->hidden == NULL) ) {
123 SDL_OutOfMemory();
124 if ( device ) {
125 SDL_free(device);
126 }
127 return(0);
128 }
129 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
130
131 /* Set the function pointers */
132 device->VideoInit = VGL_VideoInit;
133 device->ListModes = VGL_ListModes;
134 device->SetVideoMode = VGL_SetVideoMode;
135 device->SetColors = VGL_SetColors;
136 device->UpdateRects = NULL;
137 device->VideoQuit = VGL_VideoQuit;
138 device->AllocHWSurface = VGL_AllocHWSurface;
139 device->CheckHWBlit = NULL;
140 device->FillHWRect = NULL;
141 device->SetHWColorKey = NULL;
142 device->SetHWAlpha = NULL;
143 device->LockHWSurface = VGL_LockHWSurface;
144 device->UnlockHWSurface = VGL_UnlockHWSurface;
145 device->FlipHWSurface = VGL_FlipHWSurface;
146 device->FreeHWSurface = VGL_FreeHWSurface;
147 device->SetIcon = NULL;
148 device->SetCaption = NULL;
149 device->GetWMInfo = NULL;
150 device->FreeWMCursor = VGL_FreeWMCursor;
151 device->CreateWMCursor = VGL_CreateWMCursor;
152 device->ShowWMCursor = VGL_ShowWMCursor;
153 device->WarpWMCursor = VGL_WarpWMCursor;
154 device->InitOSKeymap = VGL_InitOSKeymap;
155 device->PumpEvents = VGL_PumpEvents;
156
157 device->free = VGL_DeleteDevice;
158
159 return device;
160}
161
162VideoBootStrap VGL_bootstrap = {
163 "vgl", "FreeBSD libVGL",
164 VGL_Available, VGL_CreateDevice
165};
166
167static int VGL_AddMode(_THIS, VGLMode *inmode)
168{
169 SDL_Rect *mode;
170
171 int i, index;
172 int next_mode;
173
174 /* Check to see if we already have this mode */
175 if (inmode->Depth < 8) { /* Not supported */
176 return 0;
177 }
178 index = ((inmode->Depth + 7) / 8) - 1;
179 for (i=0; i<SDL_nummodes[index]; ++i) {
180 mode = SDL_modelist[index][i];
181 if ((mode->w == inmode->ModeInfo.Xsize) &&
182 (mode->h == inmode->ModeInfo.Ysize))
183 return 0;
184 }
185
186 /* Set up the new video mode rectangle */
187 mode = (SDL_Rect *)SDL_malloc(sizeof *mode);
188 if (mode == NULL) {
189 SDL_OutOfMemory();
190 return -1;
191 }
192 mode->x = 0;
193 mode->y = 0;
194 mode->w = inmode->ModeInfo.Xsize;
195 mode->h = inmode->ModeInfo.Ysize;
196
197 /* Allocate the new list of modes, and fill in the new mode */
198 next_mode = SDL_nummodes[index];
199 SDL_modelist[index] = (SDL_Rect **)
200 SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *));
201 if (SDL_modelist[index] == NULL) {
202 SDL_OutOfMemory();
203 SDL_nummodes[index] = 0;
204 SDL_free(mode);
205 return -1;
206 }
207 SDL_modelist[index][next_mode] = mode;
208 SDL_modelist[index][next_mode+1] = NULL;
209 SDL_nummodes[index]++;
210
211 return 0;
212}
213
214static void VGL_UpdateVideoInfo(_THIS)
215{
216 this->info.wm_available = 0;
217 this->info.hw_available = 1;
218 this->info.video_mem = 0;
219 if (VGLCurMode == NULL) {
220 return;
221 }
222 if (VGLCurMode->ModeInfo.PixelBytes > 0) {
223 this->info.video_mem = VGLCurMode->ModeInfo.PixelBytes *
224 VGLCurMode->ModeInfo.Xsize *
225 VGLCurMode->ModeInfo.Ysize;
226 }
227}
228
229int VGL_VideoInit(_THIS, SDL_PixelFormat *vformat)
230{
231 int i;
232 int total_modes;
233 VGLMode **modes;
234
235 /* Initialize all variables that we clean on shutdown */
236 for ( i=0; i<NUM_MODELISTS; ++i ) {
237 SDL_nummodes[i] = 0;
238 SDL_modelist[i] = NULL;
239 }
240
241 /* Enable mouse and keyboard support */
242 if (SDL_getenv("SDL_NO_RAWKBD") == NULL) {
243 if (VGLKeyboardInit(VGL_CODEKEYS) != 0) {
244 SDL_SetError("Unable to initialize keyboard");
245 return -1;
246 }
247 } else {
248 warnx("Requiest to put keyboard into a raw mode ignored");
249 }
250 if (VGL_initkeymaps(STDIN_FILENO) != 0) {
251 SDL_SetError("Unable to initialize keymap");
252 return -1;
253 }
254 if (VGL_initmouse(STDIN_FILENO) != 0) {
255 SDL_SetError("Unable to initialize mouse");
256 return -1;
257 }
258
259 /* Determine the current screen size */
260 if (VGLCurMode != NULL) {
261 this->info.current_w = VGLCurMode->ModeInfo.Xsize;
262 this->info.current_h = VGLCurMode->ModeInfo.Ysize;
263 }
264
265 /* Determine the screen depth */
266 if (VGLCurMode != NULL)
267 vformat->BitsPerPixel = VGLCurMode->Depth;
268 else
269 vformat->BitsPerPixel = 16; /* Good default */
270
271 /* Query for the list of available video modes */
272 total_modes = 0;
273 modes = VGLListModes(-1, V_INFO_MM_DIRECT | V_INFO_MM_PACKED);
274 for (i = 0; modes[i] != NULL; i++) {
275 if ((modes[i]->ModeInfo.Type == VIDBUF8) ||
276 (modes[i]->ModeInfo.Type == VIDBUF16) ||
277 (modes[i]->ModeInfo.Type == VIDBUF32)) {
278 VGL_AddMode(this, modes[i]);
279 total_modes++;
280 }
281 }
282 if (total_modes == 0) {
283 SDL_SetError("No linear video modes available");
284 return -1;
285 }
286
287 /* Fill in our hardware acceleration capabilities */
288 VGL_UpdateVideoInfo(this);
289
290 /* Create the hardware surface lock mutex */
291 hw_lock = SDL_CreateMutex();
292 if (hw_lock == NULL) {
293 SDL_SetError("Unable to create lock mutex");
294 VGL_VideoQuit(this);
295 return -1;
296 }
297
298 /* We're done! */
299 return 0;
300}
301
302SDL_Rect **VGL_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
303{
304 return SDL_modelist[((format->BitsPerPixel+7)/8)-1];
305}
306
307/* Various screen update functions available */
308static void VGL_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
309
310SDL_Surface *VGL_SetVideoMode(_THIS, SDL_Surface *current,
311 int width, int height, int bpp, Uint32 flags)
312{
313 int mode_found;
314 int i;
315 VGLMode **modes;
316
317 modes = VGLListModes(bpp, V_INFO_MM_DIRECT | V_INFO_MM_PACKED);
318 mode_found = 0;
319 for (i = 0; modes[i] != NULL; i++) {
320 if ((modes[i]->ModeInfo.Xsize == width) &&
321 (modes[i]->ModeInfo.Ysize == height) &&
322 ((modes[i]->ModeInfo.Type == VIDBUF8) ||
323 (modes[i]->ModeInfo.Type == VIDBUF16) ||
324 (modes[i]->ModeInfo.Type == VIDBUF32))) {
325 mode_found = 1;
326 break;
327 }
328 }
329 if (mode_found == 0) {
330 SDL_SetError("No matching video mode found");
331 return NULL;
332 }
333
334 /* Shutdown previous videomode (if any) */
335 if (VGLCurMode != NULL)
336 VGLEnd();
337
338 /* Try to set the requested linear video mode */
339 if (VGLInit(modes[i]->ModeId) != 0) {
340 SDL_SetError("Unable to switch to requested mode");
341 return NULL;
342 }
343
344 VGLCurMode = SDL_realloc(VGLCurMode, sizeof(VGLMode));
345 VGLCurMode->ModeInfo = *VGLDisplay;
346 VGLCurMode->Depth = modes[i]->Depth;
347 VGLCurMode->ModeId = modes[i]->ModeId;
348 VGLCurMode->Rmask = modes[i]->Rmask;
349 VGLCurMode->Gmask = modes[i]->Gmask;
350 VGLCurMode->Bmask = modes[i]->Bmask;
351
352 /* Workaround a bug in libvgl */
353 if (VGLCurMode->ModeInfo.PixelBytes == 0)
354 (VGLCurMode->ModeInfo.PixelBytes = 1);
355
356 current->w = VGLCurMode->ModeInfo.Xsize;
357 current->h = VGLCurMode->ModeInfo.Ysize;
358 current->pixels = VGLCurMode->ModeInfo.Bitmap;
359 current->pitch = VGLCurMode->ModeInfo.Xsize *
360 VGLCurMode->ModeInfo.PixelBytes;
361 current->flags = (SDL_FULLSCREEN | SDL_HWSURFACE);
362
363 /* Check if we are in a pseudo-color mode */
364 if (VGLCurMode->ModeInfo.Type == VIDBUF8)
365 current->flags |= SDL_HWPALETTE;
366
367 /* Check if we can do doublebuffering */
368 if (flags & SDL_DOUBLEBUF) {
369 if (VGLCurMode->ModeInfo.Xsize * 2 <=
370 VGLCurMode->ModeInfo.VYsize) {
371 current->flags |= SDL_DOUBLEBUF;
372 flip_page = 0;
373 flip_address[0] = (byte *)current->pixels;
374 flip_address[1] = (byte *)current->pixels +
375 current->h * current->pitch;
376 VGL_FlipHWSurface(this, current);
377 }
378 }
379
380 if (! SDL_ReallocFormat(current, modes[i]->Depth, VGLCurMode->Rmask,
381 VGLCurMode->Gmask, VGLCurMode->Bmask, 0)) {
382 return NULL;
383 }
384
385 /* Update hardware acceleration info */
386 VGL_UpdateVideoInfo(this);
387
388 /* Set the blit function */
389 this->UpdateRects = VGL_DirectUpdate;
390
391 /* We're done */
392 return current;
393}
394
395/* We don't actually allow hardware surfaces other than the main one */
396static int VGL_AllocHWSurface(_THIS, SDL_Surface *surface)
397{
398 return -1;
399}
400static void VGL_FreeHWSurface(_THIS, SDL_Surface *surface)
401{
402 return;
403}
404
405/* We need to wait for vertical retrace on page flipped displays */
406static int VGL_LockHWSurface(_THIS, SDL_Surface *surface)
407{
408 if (surface == SDL_VideoSurface) {
409 SDL_mutexP(hw_lock);
410 }
411 return 0;
412}
413static void VGL_UnlockHWSurface(_THIS, SDL_Surface *surface)
414{
415 if (surface == SDL_VideoSurface) {
416 SDL_mutexV(hw_lock);
417 }
418}
419
420static int VGL_FlipHWSurface(_THIS, SDL_Surface *surface)
421{
422 if (VGLPanScreen(VGLDisplay, 0, flip_page * surface->h) < 0) {
423 SDL_SetError("VGLPanSreen() failed");
424 return -1;
425 }
426
427 flip_page = !flip_page;
428 surface->pixels = flip_address[flip_page];
429
430 return 0;
431}
432
433static void VGL_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
434{
435 return;
436}
437
438int VGL_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
439{
440 int i;
441
442 for(i = 0; i < ncolors; i++) {
443 VGLSetPaletteIndex(firstcolor + i,
444 colors[i].r>>2,
445 colors[i].g>>2,
446 colors[i].b>>2);
447 }
448 return 1;
449}
450
451/* Note: If we are terminated, this could be called in the middle of
452 another SDL video routine -- notably UpdateRects.
453*/
454void VGL_VideoQuit(_THIS)
455{
456 int i, j;
457
458 /* Return the keyboard to the normal state */
459 VGLKeyboardEnd();
460
461 /* Reset the console video mode if we actually initialised one */
462 if (VGLCurMode != NULL) {
463 VGLEnd();
464 SDL_free(VGLCurMode);
465 VGLCurMode = NULL;
466 }
467
468 /* Clear the lock mutex */
469 if (hw_lock != NULL) {
470 SDL_DestroyMutex(hw_lock);
471 hw_lock = NULL;
472 }
473
474 /* Free video mode lists */
475 for (i = 0; i < NUM_MODELISTS; i++) {
476 if (SDL_modelist[i] != NULL) {
477 for (j = 0; SDL_modelist[i][j] != NULL; ++j) {
478 SDL_free(SDL_modelist[i][j]);
479 }
480 SDL_free(SDL_modelist[i]);
481 SDL_modelist[i] = NULL;
482 }
483 }
484
485 if ( this->screen && (this->screen->flags & SDL_HWSURFACE) ) {
486 /* Direct screen access, not a memory buffer */
487 this->screen->pixels = NULL;
488 }
489}
490
491#define VGL_RED_INDEX 0
492#define VGL_GREEN_INDEX 1
493#define VGL_BLUE_INDEX 2
494
495static VGLMode **
496VGLListModes(int depth, int mem_model)
497{
498 static VGLMode **modes = NULL;
499
500 VGLBitmap *vminfop;
501 VGLMode **modesp, *modescp;
502 video_info_t minfo;
503 int adptype, i, modenum;
504
505 if (modes == NULL) {
506 modes = SDL_malloc(sizeof(VGLMode *) * M_VESA_MODE_MAX);
507 bzero(modes, sizeof(VGLMode *) * M_VESA_MODE_MAX);
508 }
509 modesp = modes;
510
511 for (modenum = 0; modenum < M_VESA_MODE_MAX; modenum++) {
512 minfo.vi_mode = modenum;
513 if (ioctl(0, CONS_MODEINFO, &minfo) || ioctl(0, CONS_CURRENT, &adptype))
514 continue;
515 if (minfo.vi_mode != modenum)
516 continue;
517 if ((minfo.vi_flags & V_INFO_GRAPHICS) == 0)
518 continue;
519 if ((mem_model != -1) && ((minfo.vi_mem_model & mem_model) == 0))
520 continue;
521 if ((depth > 1) && (minfo.vi_depth != depth))
522 continue;
523
524 /* reallocf can fail */
525 if ((*modesp = reallocf(*modesp, sizeof(VGLMode))) == NULL)
526 return NULL;
527 modescp = *modesp;
528
529 vminfop = &(modescp->ModeInfo);
530 bzero(vminfop, sizeof(VGLBitmap));
531
532 vminfop->Type = NOBUF;
533
534 vminfop->PixelBytes = 1; /* Good default value */
535 switch (minfo.vi_mem_model) {
536 case V_INFO_MM_PLANAR:
537 /* we can handle EGA/VGA planar modes only */
538 if (!(minfo.vi_depth != 4 || minfo.vi_planes != 4
539 || (adptype != KD_EGA && adptype != KD_VGA)))
540 vminfop->Type = VIDBUF4;
541 break;
542 case V_INFO_MM_PACKED:
543 /* we can do only 256 color packed modes */
544 if (minfo.vi_depth == 8)
545 vminfop->Type = VIDBUF8;
546 break;
547 case V_INFO_MM_VGAX:
548 vminfop->Type = VIDBUF8X;
549 break;
550#if defined(__FREEBSD__) && (defined(__DragonFly__) || __FreeBSD_version >= 500000)
551 case V_INFO_MM_DIRECT:
552 vminfop->PixelBytes = minfo.vi_pixel_size;
553 switch (vminfop->PixelBytes) {
554 case 2:
555 vminfop->Type = VIDBUF16;
556 break;
557#if notyet
558 case 3:
559 vminfop->Type = VIDBUF24;
560 break;
561#endif
562 case 4:
563 vminfop->Type = VIDBUF32;
564 break;
565 default:
566 break;
567 }
568#endif
569 default:
570 break;
571 }
572 if (vminfop->Type == NOBUF)
573 continue;
574
575 switch (vminfop->Type) {
576 case VIDBUF16:
577 case VIDBUF32:
578 modescp->Rmask = ((1 << minfo.vi_pixel_fsizes[VGL_RED_INDEX]) - 1) <<
579 minfo.vi_pixel_fields[VGL_RED_INDEX];
580 modescp->Gmask = ((1 << minfo.vi_pixel_fsizes[VGL_GREEN_INDEX]) - 1) <<
581 minfo.vi_pixel_fields[VGL_GREEN_INDEX];
582 modescp->Bmask = ((1 << minfo.vi_pixel_fsizes[VGL_BLUE_INDEX]) - 1) <<
583 minfo.vi_pixel_fields[VGL_BLUE_INDEX];
584 break;
585
586 default:
587 break;
588 }
589
590 vminfop->Xsize = minfo.vi_width;
591 vminfop->Ysize = minfo.vi_height;
592 modescp->Depth = minfo.vi_depth;
593
594 /* XXX */
595 if (minfo.vi_mode >= M_VESA_BASE)
596 modescp->ModeId = _IO('V', minfo.vi_mode - M_VESA_BASE);
597 else
598 modescp->ModeId = _IO('S', minfo.vi_mode);
599
600 /* Sort list */
601 for (i = 0; modes + i < modesp ; i++) {
602 if (modes[i]->ModeInfo.Xsize * modes[i]->ModeInfo.Ysize >
603 vminfop->Xsize * modes[i]->ModeInfo.Ysize)
604 continue;
605 if ((modes[i]->ModeInfo.Xsize * modes[i]->ModeInfo.Ysize ==
606 vminfop->Xsize * vminfop->Ysize) &&
607 (modes[i]->Depth >= modescp->Depth))
608 continue;
609 *modesp = modes[i];
610 modes[i] = modescp;
611 modescp = *modesp;
612 vminfop = &(modescp->ModeInfo);
613 }
614
615 modesp++;
616 }
617
618 if (*modesp != NULL) {
619 SDL_free(*modesp);
620 *modesp = NULL;
621 }
622
623 return modes;
624}
diff --git a/apps/plugins/sdl/src/video/vgl/SDL_vglvideo.h b/apps/plugins/sdl/src/video/vgl/SDL_vglvideo.h
deleted file mode 100644
index 9fc3569679..0000000000
--- a/apps/plugins/sdl/src/video/vgl/SDL_vglvideo.h
+++ /dev/null
@@ -1,65 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_vglvideo_h
25#define _SDL_vglvideo_h
26
27#include <sys/fbio.h>
28#include <sys/consio.h>
29#include <vgl.h>
30
31#include "SDL_mouse.h"
32#include "SDL_mutex.h"
33#include "../SDL_sysvideo.h"
34
35/* Hidden "this" pointer for the video functions */
36#define _THIS SDL_VideoDevice *this
37
38typedef struct {
39 int ModeId;
40 int Depth;
41 int Rmask;
42 int Gmask;
43 int Bmask;
44 VGLBitmap ModeInfo;
45} VGLMode;
46
47/* Private display data */
48struct SDL_PrivateVideoData {
49#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
50 int SDL_nummodes[NUM_MODELISTS];
51 SDL_Rect **SDL_modelist[NUM_MODELISTS];
52 SDL_mutex *hw_lock;
53 VGLMode *VGLCurMode;
54 int flip_page;
55 byte *flip_address[2];
56};
57/* Old variable names */
58#define SDL_nummodes (this->hidden->SDL_nummodes)
59#define SDL_modelist (this->hidden->SDL_modelist)
60#define hw_lock (this->hidden->hw_lock)
61#define VGLCurMode (this->hidden->VGLCurMode)
62#define flip_page (this->hidden->flip_page)
63#define flip_address (this->hidden->flip_address)
64
65#endif /* _SDL_vglvideo_h */
diff --git a/apps/plugins/sdl/src/video/wincommon/SDL_lowvideo.h b/apps/plugins/sdl/src/video/wincommon/SDL_lowvideo.h
deleted file mode 100644
index 89d1a88e89..0000000000
--- a/apps/plugins/sdl/src/video/wincommon/SDL_lowvideo.h
+++ /dev/null
@@ -1,152 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_lowvideo_h
25#define _SDL_lowvideo_h
26
27#define WIN32_LEAN_AND_MEAN
28#include <windows.h>
29
30#ifndef SetClassLongPtr
31#define SetClassLongPtr SetClassLong
32#endif
33#ifndef GetWindowLongPtr
34#define GetWindowLongPtr GetWindowLong
35#endif
36#ifndef SetWindowLongPtr
37#define SetWindowLongPtr SetWindowLong
38#endif
39#ifndef GWLP_WNDPROC
40#define GWLP_WNDPROC GWL_WNDPROC
41#endif
42#ifndef GWLP_HINSTANCE
43#define GWLP_HINSTANCE GWL_HINSTANCE
44#endif
45#ifndef GCLP_HICON
46#define GCLP_HICON GCL_HICON
47#endif
48
49#include "../SDL_sysvideo.h"
50
51/* Hidden "this" pointer for the video functions */
52#define _THIS SDL_VideoDevice *this
53
54#define FULLSCREEN() \
55 ((SDL_VideoSurface->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)
56
57#define WINDIB_FULLSCREEN() \
58( \
59 SDL_VideoSurface && \
60 FULLSCREEN() && \
61 (((SDL_VideoSurface->flags & SDL_OPENGL ) == SDL_OPENGL ) || \
62 ((SDL_strcmp(this->name, "windib") == 0) || \
63 (SDL_strcmp(this->name, "gapi") == 0))) \
64)
65#define DDRAW_FULLSCREEN() \
66( \
67 SDL_VideoSurface && \
68 FULLSCREEN() && \
69 ((SDL_VideoSurface->flags & SDL_OPENGL ) != SDL_OPENGL ) && \
70 (SDL_strcmp(this->name, "directx") == 0) \
71)
72
73#define DINPUT_FULLSCREEN() \
74( \
75 FULLSCREEN() && \
76 (strcmp(this->name, "directx") == 0) \
77)
78
79#define DINPUT() (strcmp(this->name, "directx") == 0)
80
81/* The main window -- and a function to set it for the audio */
82#ifdef _WIN32_WCE
83extern LPWSTR SDL_Appname;
84#else
85extern LPSTR SDL_Appname;
86#endif
87extern HINSTANCE SDL_Instance;
88extern HWND SDL_Window;
89extern BOOL SDL_windowid;
90
91/* Variables and functions exported to other parts of the native video
92 subsystem (SDL_sysevents.c)
93*/
94extern void WIN_FlushMessageQueue();
95
96/* Called by windows message loop when application is activated */
97extern void (*WIN_Activate)(_THIS, BOOL active, BOOL minimized);
98
99/* Called by windows message loop when system palette is available */
100extern void (*WIN_RealizePalette)(_THIS);
101
102/* Called by windows message loop when the system palette changes */
103extern void (*WIN_PaletteChanged)(_THIS, HWND window);
104
105/* Called by windows message loop when a portion of the screen needs update */
106extern void (*WIN_WinPAINT)(_THIS, HDC hdc);
107
108/* Called by windows message loop when the message isn't handled */
109extern LONG (*HandleMessage)(_THIS, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
110
111/* The window cursor (from SDL_sysmouse.c) */
112extern HCURSOR SDL_hcursor;
113
114/* The bounds of the window in screen coordinates */
115extern RECT SDL_bounds;
116
117/* The position of the window in windowed mode */
118extern int SDL_windowX;
119extern int SDL_windowY;
120
121/* Flag -- SDL is performing a resize, rather than the user */
122extern int SDL_resizing;
123
124/* Flag -- the mouse is in relative motion mode */
125extern int mouse_relative;
126
127/* The GDI fullscreen mode currently active */
128#ifndef NO_CHANGEDISPLAYSETTINGS
129extern DEVMODE SDL_desktop_mode;
130extern DEVMODE SDL_fullscreen_mode;
131#endif
132
133/* The system gamma ramp for GDI modes */
134extern WORD *gamma_saved;
135
136/* This is really from SDL_dx5audio.c */
137extern void DX5_SoundFocus(HWND window);
138
139/* DJM: This is really from SDL_sysevents.c, we need it in
140 GDL_CreateWindow as well */
141LRESULT CALLBACK WinMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
142
143#ifdef _WIN64
144#define SDL_ToUnicode ToUnicode
145#else
146/* JFP: Implementation of ToUnicode() that works on 9x/ME/2K/XP */
147typedef int (WINAPI *ToUnicodeFN)(UINT, UINT, const BYTE *, LPWSTR, int, UINT);
148
149extern ToUnicodeFN SDL_ToUnicode;
150#endif
151
152#endif /* SDL_lowvideo_h */
diff --git a/apps/plugins/sdl/src/video/wincommon/SDL_sysevents.c b/apps/plugins/sdl/src/video/wincommon/SDL_sysevents.c
deleted file mode 100644
index 76c67a1ccd..0000000000
--- a/apps/plugins/sdl/src/video/wincommon/SDL_sysevents.c
+++ /dev/null
@@ -1,855 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#define WIN32_LEAN_AND_MEAN
25#include <windows.h>
26
27/* Make sure XBUTTON stuff is defined that isn't in older Platform SDKs... */
28#ifndef WM_XBUTTONDOWN
29#define WM_XBUTTONDOWN 0x020B
30#endif
31#ifndef WM_XBUTTONUP
32#define WM_XBUTTONUP 0x020C
33#endif
34#ifndef GET_XBUTTON_WPARAM
35#define GET_XBUTTON_WPARAM(w) (HIWORD(w))
36#endif
37
38#include "SDL_events.h"
39#include "SDL_video.h"
40#include "SDL_syswm.h"
41#include "../SDL_sysvideo.h"
42#include "../../events/SDL_sysevents.h"
43#include "../../events/SDL_events_c.h"
44#include "SDL_lowvideo.h"
45#include "SDL_syswm_c.h"
46#include "SDL_main.h"
47#include "SDL_loadso.h"
48
49#ifdef WMMSG_DEBUG
50#include "wmmsg.h"
51#endif
52
53#include "../windib/SDL_gapidibvideo.h"
54
55#ifdef SDL_VIDEO_DRIVER_GAPI
56#include "../gapi/SDL_gapivideo.h"
57#endif
58
59#ifdef _WIN32_WCE
60#define IsZoomed(HWND) 1
61#define NO_GETKEYBOARDSTATE
62#if _WIN32_WCE < 420
63#define NO_CHANGEDISPLAYSETTINGS
64#endif
65#endif
66
67/* The window we use for everything... */
68#ifdef _WIN32_WCE
69LPWSTR SDL_Appname = NULL;
70#else
71LPSTR SDL_Appname = NULL;
72#endif
73Uint32 SDL_Appstyle = 0;
74HINSTANCE SDL_Instance = NULL;
75HWND SDL_Window = NULL;
76RECT SDL_bounds = {0, 0, 0, 0};
77int SDL_windowX = 0;
78int SDL_windowY = 0;
79int SDL_resizing = 0;
80int mouse_relative = 0;
81int posted = 0;
82#ifndef NO_CHANGEDISPLAYSETTINGS
83DEVMODE SDL_desktop_mode;
84DEVMODE SDL_fullscreen_mode;
85#endif
86WORD *gamma_saved = NULL;
87
88
89/* Functions called by the message processing function */
90LONG (*HandleMessage)(_THIS, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)=NULL;
91void (*WIN_Activate)(_THIS, BOOL active, BOOL iconic);
92void (*WIN_RealizePalette)(_THIS);
93void (*WIN_PaletteChanged)(_THIS, HWND window);
94void (*WIN_WinPAINT)(_THIS, HDC hdc);
95extern void DIB_SwapGamma(_THIS);
96
97#ifndef NO_GETKEYBOARDSTATE
98#ifndef _WIN64
99/* Variables and support functions for SDL_ToUnicode() */
100static int codepage;
101static int Is9xME();
102static int GetCodePage();
103static int WINAPI ToUnicode9xME(UINT vkey, UINT scancode, const BYTE *keystate, LPWSTR wchars, int wsize, UINT flags);
104
105ToUnicodeFN SDL_ToUnicode = ToUnicode9xME;
106#endif
107#endif /* !NO_GETKEYBOARDSTATE */
108
109
110#if defined(_WIN32_WCE)
111
112//AdjustWindowRect is not available under WinCE 2003
113#define AdjustWindowRect(a,b,c) (AdjustWindowRectEx((a),(b),(c),0))
114
115// dynamically load aygshell dll because we want SDL to work on HPC and be300
116HINSTANCE aygshell = NULL;
117BOOL (WINAPI *SHFullScreen)(HWND hwndRequester, DWORD dwState) = 0;
118
119#define SHFS_SHOWTASKBAR 0x0001
120#define SHFS_HIDETASKBAR 0x0002
121#define SHFS_SHOWSIPBUTTON 0x0004
122#define SHFS_HIDESIPBUTTON 0x0008
123#define SHFS_SHOWSTARTICON 0x0010
124#define SHFS_HIDESTARTICON 0x0020
125
126static void LoadAygshell(void)
127{
128 if( !aygshell )
129 aygshell = SDL_LoadObject("aygshell.dll");
130 if( (aygshell != 0) && (SHFullScreen == 0) )
131 {
132 SHFullScreen = (int (WINAPI *)(struct HWND__ *,unsigned long)) SDL_LoadFunction(aygshell, "SHFullScreen");
133 }
134}
135
136#endif
137
138/* JC 14 Mar 2006
139 This is used all over the place, in the windib driver and in the dx5 driver
140 So we may as well stick it here instead of having multiple copies scattered
141 about
142*/
143void WIN_FlushMessageQueue()
144{
145 MSG msg;
146 while ( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) ) {
147 if ( msg.message == WM_QUIT ) break;
148 TranslateMessage( &msg );
149 DispatchMessage( &msg );
150 }
151}
152
153static void SDL_RestoreGameMode(void)
154{
155#ifdef _WIN32_WCE //Under ce we don't minimize, therefore no restore
156
157#ifdef SDL_VIDEO_DRIVER_GAPI
158 SDL_VideoDevice *this = current_video;
159 if(SDL_strcmp(this->name, "gapi") == 0)
160 {
161 if( this->hidden->gapiInfo->suspended )
162 {
163 this->hidden->gapiInfo->suspended = 0;
164 }
165 }
166#endif
167
168#else
169 ShowWindow(SDL_Window, SW_RESTORE);
170#endif
171
172#ifndef NO_CHANGEDISPLAYSETTINGS
173#ifndef _WIN32_WCE
174 ChangeDisplaySettings(&SDL_fullscreen_mode, CDS_FULLSCREEN);
175#endif
176#endif /* NO_CHANGEDISPLAYSETTINGS */
177}
178static void SDL_RestoreDesktopMode(void)
179{
180
181#ifdef _WIN32_WCE
182
183#ifdef SDL_VIDEO_DRIVER_GAPI
184 SDL_VideoDevice *this = current_video;
185 if(SDL_strcmp(this->name, "gapi") == 0)
186 {
187 if( !this->hidden->gapiInfo->suspended )
188 {
189 this->hidden->gapiInfo->suspended = 1;
190 }
191 }
192#endif
193
194#else
195 /* WinCE does not have a taskbar, so minimizing is not convenient */
196 ShowWindow(SDL_Window, SW_MINIMIZE);
197#endif
198
199#ifndef NO_CHANGEDISPLAYSETTINGS
200#ifndef _WIN32_WCE
201 ChangeDisplaySettings(NULL, 0);
202#endif
203#endif /* NO_CHANGEDISPLAYSETTINGS */
204}
205
206#ifdef WM_MOUSELEAVE
207/*
208 Special code to handle mouse leave events - this sucks...
209 http://support.microsoft.com/support/kb/articles/q183/1/07.asp
210
211 TrackMouseEvent() is only available on Win98 and WinNT.
212 _TrackMouseEvent() is available on Win95, but isn't yet in the mingw32
213 development environment, and only works on systems that have had IE 3.0
214 or newer installed on them (which is not the case with the base Win95).
215 Therefore, we implement our own version of _TrackMouseEvent() which
216 uses our own implementation if TrackMouseEvent() is not available.
217*/
218static BOOL (WINAPI *_TrackMouseEvent)(TRACKMOUSEEVENT *ptme) = NULL;
219
220static VOID CALLBACK
221TrackMouseTimerProc(HWND hWnd, UINT uMsg, UINT idEvent, DWORD dwTime)
222{
223 union { RECT rect; POINT pt; } rectpt; /* prevent type-punning issue. */
224 POINT pt;
225
226 GetClientRect(hWnd, &rectpt.rect);
227 MapWindowPoints(hWnd, NULL, &rectpt.pt, 2);
228 GetCursorPos(&pt);
229 if ( !PtInRect(&rectpt.rect, pt) || (WindowFromPoint(pt) != hWnd) ) {
230 if ( !KillTimer(hWnd, idEvent) ) {
231 /* Error killing the timer! */
232 }
233 PostMessage(hWnd, WM_MOUSELEAVE, 0, 0);
234 }
235}
236static BOOL WINAPI WIN_TrackMouseEvent(TRACKMOUSEEVENT *ptme)
237{
238 if ( ptme->dwFlags == TME_LEAVE ) {
239 return SetTimer(ptme->hwndTrack, ptme->dwFlags, 100,
240 (TIMERPROC)TrackMouseTimerProc) != 0;
241 }
242 return FALSE;
243}
244#endif /* WM_MOUSELEAVE */
245
246int sysevents_mouse_pressed = 0;
247
248/* The main Win32 event handler
249DJM: This is no longer static as (DX5/DIB)_CreateWindow needs it
250*/
251LRESULT CALLBACK WinMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
252{
253 SDL_VideoDevice *this = current_video;
254#ifdef WMMSG_DEBUG
255 fprintf(stderr, "Received windows message: ");
256 if ( msg > MAX_WMMSG ) {
257 fprintf(stderr, "%d", msg);
258 } else {
259 fprintf(stderr, "%s", wmtab[msg]);
260 }
261 fprintf(stderr, " -- 0x%X, 0x%X\n", wParam, lParam);
262#endif
263 switch (msg) {
264
265 case WM_ACTIVATE: {
266 SDL_VideoDevice *this = current_video;
267 BOOL active, minimized;
268 Uint8 appstate;
269
270 minimized = HIWORD(wParam);
271 active = (LOWORD(wParam) != WA_INACTIVE) && !minimized;
272 if ( active ) {
273 /* Gain the following states */
274 appstate = SDL_APPACTIVE|SDL_APPINPUTFOCUS;
275 if ( !(SDL_GetAppState() & SDL_APPINPUTFOCUS) ) {
276 if ( this->input_grab != SDL_GRAB_OFF ) {
277 WIN_GrabInput(this, SDL_GRAB_ON);
278 }
279 if ( ! DDRAW_FULLSCREEN() ) {
280 DIB_SwapGamma(this);
281 }
282 if ( WINDIB_FULLSCREEN() ) {
283 SDL_RestoreGameMode();
284 }
285 }
286#if defined(_WIN32_WCE)
287 if ( WINDIB_FULLSCREEN() ) {
288 LoadAygshell();
289 if( SHFullScreen )
290 SHFullScreen(SDL_Window, SHFS_HIDESTARTICON|SHFS_HIDETASKBAR|SHFS_HIDESIPBUTTON);
291 else
292 ShowWindow(FindWindow(TEXT("HHTaskBar"),NULL),SW_HIDE);
293 }
294#endif
295 posted = SDL_PrivateAppActive(1, appstate);
296 } else {
297 /* Lose the following states */
298 appstate = SDL_APPINPUTFOCUS;
299 if ( minimized ) {
300 appstate |= SDL_APPACTIVE;
301 }
302
303 if ( SDL_GetAppState() & SDL_APPINPUTFOCUS ) {
304 if ( this->input_grab != SDL_GRAB_OFF ) {
305 WIN_GrabInput(this, SDL_GRAB_OFF);
306 }
307 if ( ! DDRAW_FULLSCREEN() ) {
308 DIB_SwapGamma(this);
309 }
310 if ( WINDIB_FULLSCREEN() ) {
311 appstate |= SDL_APPMOUSEFOCUS;
312 SDL_RestoreDesktopMode();
313 /* A fullscreen app gets hidden but will not get a minimize event */
314 appstate |= (SDL_APPACTIVE | SDL_APPMOUSEFOCUS);
315#if defined(_WIN32_WCE)
316 LoadAygshell();
317 if( SHFullScreen )
318 SHFullScreen(SDL_Window, SHFS_SHOWSTARTICON|SHFS_SHOWTASKBAR|SHFS_SHOWSIPBUTTON);
319 else
320 ShowWindow(FindWindow(TEXT("HHTaskBar"),NULL),SW_SHOW);
321#endif
322 }
323 }
324 posted = SDL_PrivateAppActive(0, appstate);
325 }
326 WIN_Activate(this, active, minimized);
327 return(0);
328 }
329 break;
330
331 case WM_MOUSEMOVE: {
332
333#ifdef WM_MOUSELEAVE
334 if ( SDL_VideoSurface ) {
335 /* mouse has entered the window */
336
337 if ( !(SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) {
338 TRACKMOUSEEVENT tme;
339
340 tme.cbSize = sizeof(tme);
341 tme.dwFlags = TME_LEAVE;
342 tme.hwndTrack = SDL_Window;
343 _TrackMouseEvent(&tme);
344 }
345 }
346#endif /* WM_MOUSELEAVE */
347
348 /* Mouse motion is handled in DIB_PumpEvents or
349 * DX5_PumpEvents, depending on the video driver
350 * in use */
351
352 posted = SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
353 }
354 return(0);
355
356#ifdef WM_MOUSELEAVE
357 case WM_MOUSELEAVE: {
358
359 if ( SDL_VideoSurface ) {
360 /* mouse has left the window */
361 posted = SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
362 }
363 }
364 return(0);
365#endif /* WM_MOUSELEAVE */
366
367 case WM_LBUTTONDOWN:
368 case WM_LBUTTONUP:
369 case WM_MBUTTONDOWN:
370 case WM_MBUTTONUP:
371 case WM_RBUTTONDOWN:
372 case WM_RBUTTONUP:
373 case WM_XBUTTONDOWN:
374 case WM_XBUTTONUP: {
375 /* Mouse is handled by DirectInput when fullscreen */
376 if ( SDL_VideoSurface && ! DINPUT() ) {
377 WORD xbuttonval = 0;
378 Uint8 button, state;
379 int x, y;
380
381 /* DJM:
382 We want the SDL window to take focus so that
383 it acts like a normal windows "component"
384 (e.g. gains keyboard focus on a mouse click).
385 */
386 SetFocus(SDL_Window);
387
388 /* Figure out which button to use */
389 switch (msg) {
390 case WM_LBUTTONDOWN:
391 button = SDL_BUTTON_LEFT;
392 state = SDL_PRESSED;
393 break;
394 case WM_LBUTTONUP:
395 button = SDL_BUTTON_LEFT;
396 state = SDL_RELEASED;
397 break;
398 case WM_MBUTTONDOWN:
399 button = SDL_BUTTON_MIDDLE;
400 state = SDL_PRESSED;
401 break;
402 case WM_MBUTTONUP:
403 button = SDL_BUTTON_MIDDLE;
404 state = SDL_RELEASED;
405 break;
406 case WM_RBUTTONDOWN:
407 button = SDL_BUTTON_RIGHT;
408 state = SDL_PRESSED;
409 break;
410 case WM_RBUTTONUP:
411 button = SDL_BUTTON_RIGHT;
412 state = SDL_RELEASED;
413 break;
414 case WM_XBUTTONDOWN:
415 xbuttonval = GET_XBUTTON_WPARAM(wParam);
416 button = SDL_BUTTON_X1 + xbuttonval - 1;
417 state = SDL_PRESSED;
418 break;
419 case WM_XBUTTONUP:
420 xbuttonval = GET_XBUTTON_WPARAM(wParam);
421 button = SDL_BUTTON_X1 + xbuttonval - 1;
422 state = SDL_RELEASED;
423 break;
424 default:
425 /* Eh? Unknown button? */
426 return(0);
427 }
428 if ( state == SDL_PRESSED ) {
429 /* Grab mouse so we get up events */
430 if ( ++sysevents_mouse_pressed > 0 ) {
431 SetCapture(hwnd);
432 }
433 } else {
434 /* Release mouse after all up events */
435 if ( --sysevents_mouse_pressed <= 0 ) {
436 ReleaseCapture();
437 sysevents_mouse_pressed = 0;
438 }
439 }
440 if ( mouse_relative ) {
441 /* RJR: March 28, 2000
442 report internal mouse position if in relative mode */
443 x = 0; y = 0;
444 } else {
445 x = (Sint16)LOWORD(lParam);
446 y = (Sint16)HIWORD(lParam);
447#ifdef _WIN32_WCE
448 if (SDL_VideoSurface)
449 GapiTransform(this->hidden->userOrientation,
450this->hidden->hiresFix, &x, &y);
451#endif
452 }
453 posted = SDL_PrivateMouseButton(
454 state, button, x, y);
455
456 /*
457 * MSDN says:
458 * "Unlike the WM_LBUTTONUP, WM_MBUTTONUP, and WM_RBUTTONUP
459 * messages, an application should return TRUE from [an
460 * XBUTTON message] if it processes it. Doing so will allow
461 * software that simulates this message on Microsoft Windows
462 * systems earlier than Windows 2000 to determine whether
463 * the window procedure processed the message or called
464 * DefWindowProc to process it.
465 */
466 if (xbuttonval > 0)
467 return(TRUE);
468 }
469 }
470 return(0);
471
472
473#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)
474 case WM_MOUSEWHEEL:
475 if ( SDL_VideoSurface && ! DINPUT() ) {
476 int move = (short)HIWORD(wParam);
477 if ( move ) {
478 Uint8 button;
479 if ( move > 0 )
480 button = SDL_BUTTON_WHEELUP;
481 else
482 button = SDL_BUTTON_WHEELDOWN;
483 posted = SDL_PrivateMouseButton(
484 SDL_PRESSED, button, 0, 0);
485 posted |= SDL_PrivateMouseButton(
486 SDL_RELEASED, button, 0, 0);
487 }
488 }
489 return(0);
490#endif
491
492#ifdef WM_GETMINMAXINFO
493 /* This message is sent as a way for us to "check" the values
494 * of a position change. If we don't like it, we can adjust
495 * the values before they are changed.
496 */
497 case WM_GETMINMAXINFO: {
498 MINMAXINFO *info;
499 RECT size;
500 int x, y;
501 int style;
502 int width;
503 int height;
504
505 /* We don't want to clobber an internal resize */
506 if ( SDL_resizing )
507 return(0);
508
509 /* We allow resizing with the SDL_RESIZABLE flag */
510 if ( SDL_PublicSurface &&
511 (SDL_PublicSurface->flags & SDL_RESIZABLE) ) {
512 return(0);
513 }
514
515 /* Get the current position of our window */
516 GetWindowRect(SDL_Window, &size);
517 x = size.left;
518 y = size.top;
519
520 /* Calculate current width and height of our window */
521 size.top = 0;
522 size.left = 0;
523 if ( SDL_PublicSurface != NULL ) {
524 size.bottom = SDL_PublicSurface->h;
525 size.right = SDL_PublicSurface->w;
526 } else {
527 size.bottom = 0;
528 size.right = 0;
529 }
530
531 /* DJM - according to the docs for GetMenu(), the
532 return value is undefined if hwnd is a child window.
533 Aparently it's too difficult for MS to check
534 inside their function, so I have to do it here.
535 */
536 style = GetWindowLong(hwnd, GWL_STYLE);
537 AdjustWindowRect(
538 &size,
539 style,
540 style & WS_CHILDWINDOW ? FALSE
541 : GetMenu(hwnd) != NULL);
542
543 width = size.right - size.left;
544 height = size.bottom - size.top;
545
546 /* Fix our size to the current size */
547 info = (MINMAXINFO *)lParam;
548 info->ptMaxSize.x = width;
549 info->ptMaxSize.y = height;
550 info->ptMaxPosition.x = x;
551 info->ptMaxPosition.y = y;
552 info->ptMinTrackSize.x = width;
553 info->ptMinTrackSize.y = height;
554 info->ptMaxTrackSize.x = width;
555 info->ptMaxTrackSize.y = height;
556 }
557 return(0);
558#endif /* WM_GETMINMAXINFO */
559
560 case WM_WINDOWPOSCHANGING: {
561 WINDOWPOS *windowpos = (WINDOWPOS*)lParam;
562
563 /* When menu is at the side or top, Windows likes
564 to try to reposition the fullscreen window when
565 changing video modes.
566 */
567 if ( !SDL_resizing &&
568 SDL_PublicSurface &&
569 (SDL_PublicSurface->flags & SDL_FULLSCREEN) ) {
570 windowpos->x = 0;
571 windowpos->y = 0;
572 }
573 }
574 return(0);
575
576 case WM_WINDOWPOSCHANGED: {
577 SDL_VideoDevice *this = current_video;
578 POINT pt;
579 int w, h;
580
581 GetClientRect(SDL_Window, &SDL_bounds);
582
583 /* avoiding type-punning here... */
584 pt.x = SDL_bounds.left;
585 pt.y = SDL_bounds.top;
586 ClientToScreen(SDL_Window, &pt);
587 SDL_bounds.left = pt.x;
588 SDL_bounds.top = pt.y;
589
590 pt.x = SDL_bounds.right;
591 pt.y = SDL_bounds.bottom;
592 ClientToScreen(SDL_Window, &pt);
593 SDL_bounds.right = pt.x;
594 SDL_bounds.bottom = pt.y;
595
596 if ( !SDL_resizing && !IsZoomed(SDL_Window) &&
597 SDL_PublicSurface &&
598 !(SDL_PublicSurface->flags & SDL_FULLSCREEN) ) {
599 SDL_windowX = SDL_bounds.left;
600 SDL_windowY = SDL_bounds.top;
601 }
602 w = SDL_bounds.right-SDL_bounds.left;
603 h = SDL_bounds.bottom-SDL_bounds.top;
604 if ( this->input_grab != SDL_GRAB_OFF ) {
605 ClipCursor(&SDL_bounds);
606 }
607 if ( SDL_PublicSurface &&
608 (SDL_PublicSurface->flags & SDL_RESIZABLE) ) {
609 SDL_PrivateResize(w, h);
610 }
611 }
612 break;
613
614 /* We need to set the cursor */
615 case WM_SETCURSOR: {
616 Uint16 hittest;
617
618 hittest = LOWORD(lParam);
619 if ( hittest == HTCLIENT ) {
620 SetCursor(SDL_hcursor);
621 return(TRUE);
622 }
623 }
624 break;
625
626 /* We are about to get palette focus! */
627 case WM_QUERYNEWPALETTE: {
628 WIN_RealizePalette(current_video);
629 return(TRUE);
630 }
631 break;
632
633 /* Another application changed the palette */
634 case WM_PALETTECHANGED: {
635 WIN_PaletteChanged(current_video, (HWND)wParam);
636 }
637 break;
638
639 /* We were occluded, refresh our display */
640 case WM_PAINT: {
641 HDC hdc;
642 PAINTSTRUCT ps;
643
644 hdc = BeginPaint(SDL_Window, &ps);
645 if ( current_video->screen &&
646 !(current_video->screen->flags & SDL_OPENGL) ) {
647 WIN_WinPAINT(current_video, hdc);
648 }
649 EndPaint(SDL_Window, &ps);
650 }
651 return(0);
652
653 /* DJM: Send an expose event in this case */
654 case WM_ERASEBKGND: {
655 posted = SDL_PrivateExpose();
656 }
657 return(0);
658
659 case WM_CLOSE: {
660 if ( (posted = SDL_PrivateQuit()) )
661 PostQuitMessage(0);
662 }
663 return(0);
664
665 case WM_DESTROY: {
666 PostQuitMessage(0);
667 }
668 return(0);
669
670#ifndef NO_GETKEYBOARDSTATE
671 case WM_INPUTLANGCHANGE:
672#ifndef _WIN64
673 codepage = GetCodePage();
674#endif
675 return(TRUE);
676#endif
677
678 default: {
679 /* Special handling by the video driver */
680 if (HandleMessage) {
681 return(HandleMessage(current_video,
682 hwnd, msg, wParam, lParam));
683 }
684 }
685 break;
686 }
687 return(DefWindowProc(hwnd, msg, wParam, lParam));
688}
689
690/* Allow the application handle to be stored and retrieved later */
691static void *SDL_handle = NULL;
692
693void SDL_SetModuleHandle(void *handle)
694{
695 SDL_handle = handle;
696}
697void *SDL_GetModuleHandle(void)
698{
699 void *handle;
700
701 if ( SDL_handle ) {
702 handle = SDL_handle;
703 } else {
704 handle = GetModuleHandle(NULL);
705 }
706 return(handle);
707}
708
709/* This allows the SDL_WINDOWID hack */
710BOOL SDL_windowid = FALSE;
711
712static int app_registered = 0;
713
714/* Register the class for this application -- exported for winmain.c */
715int SDL_RegisterApp(char *name, Uint32 style, void *hInst)
716{
717 WNDCLASS class;
718#ifdef WM_MOUSELEAVE
719 HMODULE handle;
720#endif
721
722 /* Only do this once... */
723 if ( app_registered ) {
724 ++app_registered;
725 return(0);
726 }
727
728#ifndef CS_BYTEALIGNCLIENT
729#define CS_BYTEALIGNCLIENT 0
730#endif
731 if ( ! name && ! SDL_Appname ) {
732 name = "SDL_app";
733 SDL_Appstyle = CS_BYTEALIGNCLIENT;
734 SDL_Instance = hInst ? hInst : SDL_GetModuleHandle();
735 }
736
737 if ( name ) {
738#ifdef _WIN32_WCE
739 /* WinCE uses the UNICODE version */
740 SDL_Appname = SDL_iconv_utf8_ucs2(name);
741#else
742 SDL_Appname = SDL_iconv_utf8_locale(name);
743#endif /* _WIN32_WCE */
744 SDL_Appstyle = style;
745 SDL_Instance = hInst ? hInst : SDL_GetModuleHandle();
746 }
747
748 /* Register the application class */
749 class.hCursor = NULL;
750 class.hIcon = LoadImage(SDL_Instance, SDL_Appname,
751 IMAGE_ICON,
752 0, 0, LR_DEFAULTCOLOR);
753 class.lpszMenuName = NULL;
754 class.lpszClassName = SDL_Appname;
755 class.hbrBackground = NULL;
756 class.hInstance = SDL_Instance;
757 class.style = SDL_Appstyle;
758#if SDL_VIDEO_OPENGL
759 class.style |= CS_OWNDC;
760#endif
761 class.lpfnWndProc = WinMessage;
762 class.cbWndExtra = 0;
763 class.cbClsExtra = 0;
764 if ( ! RegisterClass(&class) ) {
765 SDL_SetError("Couldn't register application class");
766 return(-1);
767 }
768
769#ifdef WM_MOUSELEAVE
770 /* Get the version of TrackMouseEvent() we use */
771 _TrackMouseEvent = NULL;
772 handle = GetModuleHandle("USER32.DLL");
773 if ( handle ) {
774 _TrackMouseEvent = (BOOL (WINAPI *)(TRACKMOUSEEVENT *))GetProcAddress(handle, "TrackMouseEvent");
775 }
776 if ( _TrackMouseEvent == NULL ) {
777 _TrackMouseEvent = WIN_TrackMouseEvent;
778 }
779#endif /* WM_MOUSELEAVE */
780
781#ifndef NO_GETKEYBOARDSTATE
782#ifndef _WIN64
783 /* Initialise variables for SDL_ToUnicode() */
784 codepage = GetCodePage();
785
786 /* Cygwin headers don't match windows.h, so we have to cast around a
787 const issue here... */
788 SDL_ToUnicode = Is9xME() ? ToUnicode9xME : (ToUnicodeFN) ToUnicode;
789#endif
790#endif /* NO_GETKEYBOARDSTATE */
791
792 app_registered = 1;
793 return(0);
794}
795
796/* Unregisters the windowclass registered in SDL_RegisterApp above. */
797void SDL_UnregisterApp()
798{
799 WNDCLASS class;
800
801 /* SDL_RegisterApp might not have been called before */
802 if ( !app_registered ) {
803 return;
804 }
805 --app_registered;
806 if ( app_registered == 0 ) {
807 /* Check for any registered window classes. */
808 if ( GetClassInfo(SDL_Instance, SDL_Appname, &class) ) {
809 UnregisterClass(SDL_Appname, SDL_Instance);
810 }
811 SDL_free(SDL_Appname);
812 SDL_Appname = NULL;
813 }
814}
815
816#ifndef NO_GETKEYBOARDSTATE
817#ifndef _WIN64
818/* JFP: Implementation of ToUnicode() that works on 9x/ME/2K/XP */
819
820static int Is9xME()
821{
822 OSVERSIONINFO info;
823
824 SDL_memset(&info, 0, sizeof(info));
825 info.dwOSVersionInfoSize = sizeof(info);
826 if (!GetVersionEx(&info)) {
827 return 0;
828 }
829 return (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
830}
831
832static int GetCodePage()
833{
834 char buff[8];
835 int lcid = MAKELCID(LOWORD(GetKeyboardLayout(0)), SORT_DEFAULT);
836 int cp = GetACP();
837
838 if (GetLocaleInfo(lcid, LOCALE_IDEFAULTANSICODEPAGE, buff, sizeof(buff))) {
839 cp = SDL_atoi(buff);
840 }
841 return cp;
842}
843
844static int WINAPI ToUnicode9xME(UINT vkey, UINT scancode, const BYTE *keystate, LPWSTR wchars, int wsize, UINT flags)
845{
846 BYTE chars[2];
847
848 /* arg #3 should be const BYTE *, but cygwin lists it as PBYTE. */
849 if (ToAsciiEx(vkey, scancode, (PBYTE) keystate, (WORD*)chars, 0, GetKeyboardLayout(0)) == 1) {
850 return MultiByteToWideChar(codepage, 0, (LPCSTR) chars, 1, wchars, wsize);
851 }
852 return 0;
853}
854#endif
855#endif /* !NO_GETKEYBOARDSTATE */
diff --git a/apps/plugins/sdl/src/video/wincommon/SDL_sysmouse.c b/apps/plugins/sdl/src/video/wincommon/SDL_sysmouse.c
deleted file mode 100644
index 12d17e0e83..0000000000
--- a/apps/plugins/sdl/src/video/wincommon/SDL_sysmouse.c
+++ /dev/null
@@ -1,259 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#define WIN32_LEAN_AND_MEAN
25#include <windows.h>
26
27#include "SDL_mouse.h"
28#include "../../events/SDL_events_c.h"
29#include "../SDL_cursor_c.h"
30#include "SDL_sysmouse_c.h"
31#include "SDL_lowvideo.h"
32
33#ifdef _WIN32_WCE
34#define USE_STATIC_CURSOR
35#endif
36
37HCURSOR SDL_hcursor = NULL; /* Exported for SDL_eventloop.c */
38
39/* The implementation dependent data for the window manager cursor */
40/* For some reason when creating a windows cursor, the ands and xors memory
41 is not copied, so we need to keep track of it and free it when we are done
42 with the cursor. If we free the memory prematurely, the app crashes. :-}
43*/
44struct WMcursor {
45 HCURSOR curs;
46#ifndef USE_STATIC_CURSOR
47 Uint8 *ands;
48 Uint8 *xors;
49#endif
50};
51
52/* Convert bits to padded bytes */
53#define PAD_BITS(bits) ((bits+7)/8)
54
55#ifdef CURSOR_DEBUG
56static void PrintBITMAP(FILE *out, char *bits, int w, int h)
57{
58 int i;
59 unsigned char ch;
60
61 while ( h-- > 0 ) {
62 for ( i=0; i<w; ++i ) {
63 if ( (i%8) == 0 )
64 ch = *bits++;
65 if ( ch&0x80 )
66 fprintf(out, "X");
67 else
68 fprintf(out, " ");
69 ch <<= 1;
70 }
71 fprintf(out, "\n");
72 }
73}
74#endif
75
76#ifndef USE_STATIC_CURSOR
77/* Local functions to convert the SDL cursor mask into Windows format */
78static void memnot(Uint8 *dst, Uint8 *src, int len)
79{
80 while ( len-- > 0 )
81 *dst++ = ~*src++;
82}
83static void memxor(Uint8 *dst, Uint8 *src1, Uint8 *src2, int len)
84{
85 while ( len-- > 0 )
86 *dst++ = (*src1++)^(*src2++);
87}
88#endif /* !USE_STATIC_CURSOR */
89
90void WIN_FreeWMCursor(_THIS, WMcursor *cursor)
91{
92#ifndef USE_STATIC_CURSOR
93 if ( cursor->curs == GetCursor() )
94 SetCursor(NULL);
95 if ( cursor->curs != NULL )
96 DestroyCursor(cursor->curs);
97 if ( cursor->ands != NULL )
98 SDL_free(cursor->ands);
99 if ( cursor->xors != NULL )
100 SDL_free(cursor->xors);
101#endif /* !USE_STATIC_CURSOR */
102 SDL_free(cursor);
103}
104
105WMcursor *WIN_CreateWMCursor(_THIS,
106 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
107{
108#ifdef USE_STATIC_CURSOR
109 WMcursor *cursor;
110
111 /* Allocate the cursor */
112 cursor = (WMcursor *)SDL_malloc(sizeof(*cursor));
113 if ( cursor ) {
114 cursor->curs = LoadCursor(NULL, IDC_ARROW);
115 }
116 return(cursor);
117#else
118 WMcursor *cursor;
119 int allowed_x;
120 int allowed_y;
121 int run, pad, i;
122 Uint8 *aptr, *xptr;
123
124 /* Check to make sure the cursor size is okay */
125 allowed_x = GetSystemMetrics(SM_CXCURSOR);
126 allowed_y = GetSystemMetrics(SM_CYCURSOR);
127 if ( (w > allowed_x) || (h > allowed_y) ) {
128 SDL_SetError("Only cursors of dimension (%dx%d) are allowed",
129 allowed_x, allowed_y);
130 return(NULL);
131 }
132
133 /* Allocate the cursor */
134 cursor = (WMcursor *)SDL_malloc(sizeof(*cursor));
135 if ( cursor == NULL ) {
136 SDL_SetError("Out of memory");
137 return(NULL);
138 }
139 cursor->curs = NULL;
140 cursor->ands = NULL;
141 cursor->xors = NULL;
142
143 /* Pad out to the normal cursor size */
144 run = PAD_BITS(w);
145 pad = PAD_BITS(allowed_x)-run;
146 aptr = cursor->ands = (Uint8 *)SDL_malloc((run+pad)*allowed_y);
147 xptr = cursor->xors = (Uint8 *)SDL_malloc((run+pad)*allowed_y);
148 if ( (aptr == NULL) || (xptr == NULL) ) {
149 WIN_FreeWMCursor(NULL, cursor);
150 SDL_OutOfMemory();
151 return(NULL);
152 }
153 for ( i=0; i<h; ++i ) {
154 memxor(xptr, data, mask, run);
155 xptr += run;
156 data += run;
157 memnot(aptr, mask, run);
158 mask += run;
159 aptr += run;
160 SDL_memset(xptr, 0, pad);
161 xptr += pad;
162 SDL_memset(aptr, ~0, pad);
163 aptr += pad;
164 }
165 pad += run;
166 for ( ; i<allowed_y; ++i ) {
167 SDL_memset(xptr, 0, pad);
168 xptr += pad;
169 SDL_memset(aptr, ~0, pad);
170 aptr += pad;
171 }
172
173 /* Create the cursor */
174 cursor->curs = CreateCursor(
175 (HINSTANCE)GetWindowLongPtr(SDL_Window, GWLP_HINSTANCE),
176 hot_x, hot_y, allowed_x, allowed_y,
177 cursor->ands, cursor->xors);
178 if ( cursor->curs == NULL ) {
179 WIN_FreeWMCursor(NULL, cursor);
180 SDL_SetError("Windows couldn't create the requested cursor");
181 return(NULL);
182 }
183 return(cursor);
184#endif /* USE_STATIC_CURSOR */
185}
186
187int WIN_ShowWMCursor(_THIS, WMcursor *cursor)
188{
189 POINT mouse_pos;
190
191 if ( !this->screen ) {
192 return(0);
193 }
194
195 /* Set the window cursor to our cursor, if applicable */
196 if ( cursor != NULL ) {
197 SDL_hcursor = cursor->curs;
198 } else {
199 SDL_hcursor = NULL;
200 }
201 GetCursorPos(&mouse_pos);
202 if ( PtInRect(&SDL_bounds, mouse_pos) ) {
203 SetCursor(SDL_hcursor);
204 }
205 return(1);
206}
207
208void WIN_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
209{
210 if ( mouse_relative) {
211 /* RJR: March 28, 2000
212 leave physical cursor at center of screen if
213 mouse hidden and grabbed */
214 SDL_PrivateMouseMotion(0, 0, x, y);
215 } else {
216 POINT pt;
217
218 /* With DirectInput the position doesn't follow
219 * the cursor, so it is set manually */
220 if ( DINPUT() ) {
221 SDL_PrivateMouseMotion(0, 0, x, y);
222 }
223
224 pt.x = x;
225 pt.y = y;
226 ClientToScreen(SDL_Window, &pt);
227 SetCursorPos(pt.x, pt.y);
228 }
229}
230
231/* Update the current mouse state and position */
232void WIN_UpdateMouse(_THIS)
233{
234 POINT pt;
235
236 /* Always unset SDL_APPMOUSEFOCUS to give the WM_MOUSEMOVE event
237 * handler a chance to install a TRACKMOUSEEVENT */
238 SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
239
240 GetCursorPos(&pt);
241 ScreenToClient(SDL_Window, &pt);
242 SDL_PrivateMouseMotion(0,0, (Sint16)pt.x, (Sint16)pt.y);
243}
244
245/* Check to see if we need to enter or leave mouse relative mode */
246void WIN_CheckMouseMode(_THIS)
247{
248#ifndef _WIN32_WCE
249 /* If the mouse is hidden and input is grabbed, we use relative mode */
250 if ( !(SDL_cursorstate & CURSOR_VISIBLE) &&
251 (this->input_grab != SDL_GRAB_OFF) ) {
252 mouse_relative = 1;
253 } else {
254 mouse_relative = 0;
255 }
256#else
257 mouse_relative = 0;
258#endif
259}
diff --git a/apps/plugins/sdl/src/video/wincommon/SDL_sysmouse_c.h b/apps/plugins/sdl/src/video/wincommon/SDL_sysmouse_c.h
deleted file mode 100644
index 5d5fe8d44a..0000000000
--- a/apps/plugins/sdl/src/video/wincommon/SDL_sysmouse_c.h
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_lowvideo.h"
25
26/* Functions to be exported */
27extern void WIN_FreeWMCursor(_THIS, WMcursor *cursor);
28extern WMcursor *WIN_CreateWMCursor(_THIS,
29 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
30extern int WIN_ShowWMCursor(_THIS, WMcursor *cursor);
31extern void WIN_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
32extern void WIN_UpdateMouse(_THIS);
33extern void WIN_CheckMouseMode(_THIS);
diff --git a/apps/plugins/sdl/src/video/wincommon/SDL_syswm.c b/apps/plugins/sdl/src/video/wincommon/SDL_syswm.c
deleted file mode 100644
index 504d95d2c6..0000000000
--- a/apps/plugins/sdl/src/video/wincommon/SDL_syswm.c
+++ /dev/null
@@ -1,297 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#define WIN32_LEAN_AND_MEAN
25#include <windows.h>
26
27#include "SDL_version.h"
28#include "SDL_video.h"
29#include "SDL_loadso.h"
30#include "SDL_syswm.h"
31#include "../SDL_pixels_c.h"
32#include "../SDL_cursor_c.h"
33#include "SDL_syswm_c.h"
34#include "SDL_wingl_c.h"
35
36
37#ifdef _WIN32_WCE
38#define DISABLE_ICON_SUPPORT
39#endif
40
41/* The screen icon -- needs to be freed on SDL_VideoQuit() */
42HICON screen_icn = NULL;
43
44/* Win32 icon mask semantics are different from those of SDL:
45 SDL applies the mask to the icon and copies result to desktop.
46 Win32 applies the mask to the desktop and XORs the icon on.
47 This means that the SDL mask needs to be applied to the icon and
48 then inverted and passed to Win32.
49*/
50void WIN_SetWMIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
51{
52#ifdef DISABLE_ICON_SUPPORT
53 return;
54#else
55 SDL_Palette *pal_256;
56 SDL_Surface *icon_256;
57 Uint8 *pdata, *pwin32;
58 Uint8 *mdata, *mwin32, m = 0;
59 int icon_len;
60 int icon_plen;
61 int icon_mlen;
62 int icon_pitch;
63 int mask_pitch;
64 SDL_Rect bounds;
65 int i, skip;
66 int row, col;
67 struct /* quasi-BMP format */ Win32Icon {
68 Uint32 biSize;
69 Sint32 biWidth;
70 Sint32 biHeight;
71 Uint16 biPlanes;
72 Uint16 biBitCount;
73 Uint32 biCompression;
74 Uint32 biSizeImage;
75 Sint32 biXPelsPerMeter;
76 Sint32 biYPelsPerMeter;
77 Uint32 biClrUsed;
78 Uint32 biClrImportant;
79 struct /* RGBQUAD -- note it's BGR ordered */ {
80 Uint8 rgbBlue;
81 Uint8 rgbGreen;
82 Uint8 rgbRed;
83 Uint8 rgbReserved;
84 } biColors[256];
85 /* Pixels:
86 Uint8 pixels[]
87 */
88 /* Mask:
89 Uint8 mask[]
90 */
91 } *icon_win32;
92
93 /* Allocate the win32 bmp icon and set everything to zero */
94 icon_pitch = ((icon->w+3)&~3);
95 mask_pitch = ((icon->w+7)/8);
96 icon_plen = icon->h*icon_pitch;
97 icon_mlen = icon->h*mask_pitch;
98 icon_len = sizeof(*icon_win32)+icon_plen+icon_mlen;
99 icon_win32 = (struct Win32Icon *)SDL_stack_alloc(Uint8, icon_len);
100 if ( icon_win32 == NULL ) {
101 return;
102 }
103 SDL_memset(icon_win32, 0, icon_len);
104
105 /* Set the basic BMP parameters */
106 icon_win32->biSize = sizeof(*icon_win32)-sizeof(icon_win32->biColors);
107 icon_win32->biWidth = icon->w;
108 icon_win32->biHeight = icon->h*2;
109 icon_win32->biPlanes = 1;
110 icon_win32->biBitCount = 8;
111 icon_win32->biSizeImage = icon_plen+icon_mlen;
112
113 /* Allocate a standard 256 color icon surface */
114 icon_256 = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h,
115 icon_win32->biBitCount, 0, 0, 0, 0);
116 if ( icon_256 == NULL ) {
117 SDL_stack_free(icon_win32);
118 return;
119 }
120 pal_256 = icon_256->format->palette;
121 if (icon->format->palette &&
122 (icon->format->BitsPerPixel == icon_256->format->BitsPerPixel)){
123 Uint8 black;
124 SDL_memcpy(pal_256->colors, icon->format->palette->colors,
125 pal_256->ncolors*sizeof(SDL_Color));
126 /* Make sure that 0 is black! */
127 black = SDL_FindColor(pal_256, 0x00, 0x00, 0x00);
128 pal_256->colors[black] = pal_256->colors[0];
129 pal_256->colors[0].r = 0x00;
130 pal_256->colors[0].g = 0x00;
131 pal_256->colors[0].b = 0x00;
132 } else {
133 SDL_DitherColors(pal_256->colors,
134 icon_256->format->BitsPerPixel);
135 }
136
137 /* Now copy color data to the icon BMP */
138 for ( i=0; i<(1<<icon_win32->biBitCount); ++i ) {
139 icon_win32->biColors[i].rgbRed = pal_256->colors[i].r;
140 icon_win32->biColors[i].rgbGreen = pal_256->colors[i].g;
141 icon_win32->biColors[i].rgbBlue = pal_256->colors[i].b;
142 }
143
144 /* Convert icon to a standard surface format. This may not always
145 be necessary, as Windows supports a variety of BMP formats, but
146 it greatly simplifies our code.
147 */
148 bounds.x = 0;
149 bounds.y = 0;
150 bounds.w = icon->w;
151 bounds.h = icon->h;
152 if ( SDL_LowerBlit(icon, &bounds, icon_256, &bounds) < 0 ) {
153 SDL_stack_free(icon_win32);
154 SDL_FreeSurface(icon_256);
155 return;
156 }
157
158 /* Copy pixels upside-down to icon BMP, masked with the icon mask */
159 if ( SDL_MUSTLOCK(icon_256) || (icon_256->pitch != icon_pitch) ) {
160 SDL_stack_free(icon_win32);
161 SDL_FreeSurface(icon_256);
162 SDL_SetError("Warning: Unexpected icon_256 characteristics");
163 return;
164 }
165 pdata = (Uint8 *)icon_256->pixels;
166 mdata = mask;
167 pwin32 = (Uint8 *)icon_win32+sizeof(*icon_win32)+icon_plen-icon_pitch;
168 skip = icon_pitch - icon->w;
169 for ( row=0; row<icon->h; ++row ) {
170 for ( col=0; col<icon->w; ++col ) {
171 if ( (col%8) == 0 ) {
172 m = *mdata++;
173 }
174 if ( (m&0x80) != 0x00 ) {
175 *pwin32 = *pdata;
176 }
177 m <<= 1;
178 ++pdata;
179 ++pwin32;
180 }
181 pdata += skip;
182 pwin32 += skip;
183 pwin32 -= 2*icon_pitch;
184 }
185 SDL_FreeSurface(icon_256);
186
187 /* Copy mask inverted and upside-down to icon BMP */
188 mdata = mask;
189 mwin32 = (Uint8 *)icon_win32
190 +sizeof(*icon_win32)+icon_plen+icon_mlen-mask_pitch;
191 for ( row=0; row<icon->h; ++row ) {
192 for ( col=0; col<mask_pitch; ++col ) {
193 *mwin32++ = ~*mdata++;
194 }
195 mwin32 -= 2*mask_pitch;
196 }
197
198 /* Finally, create the icon handle and set the window icon */
199 screen_icn = CreateIconFromResourceEx((Uint8 *)icon_win32, icon_len,
200 TRUE, 0x00030000, icon->w, icon->h, LR_DEFAULTCOLOR);
201 if ( screen_icn == NULL ) {
202 SDL_SetError("Couldn't create Win32 icon handle");
203 } else {
204 SetClassLongPtr(SDL_Window, GCLP_HICON, (LONG_PTR)screen_icn);
205 }
206 SDL_stack_free(icon_win32);
207#endif /* DISABLE_ICON_SUPPORT */
208}
209
210typedef BOOL (WINAPI *PtrSetWindowTextW)(HWND hWnd, LPCWSTR lpString);
211
212void WIN_SetWMCaption(_THIS, const char *title, const char *icon)
213{
214#ifdef _WIN32_WCE
215 /* WinCE uses the UNICODE version */
216 LPWSTR lpszW = SDL_iconv_utf8_ucs2((char *)title);
217 SetWindowText(SDL_Window, lpszW);
218 SDL_free(lpszW);
219#else
220 Uint16 *lpsz = SDL_iconv_utf8_ucs2(title);
221 size_t len = WideCharToMultiByte(CP_ACP, 0, lpsz, -1, NULL, 0, NULL, NULL);
222 char *cvt = SDL_stack_alloc(char, len + 1);
223 WideCharToMultiByte(CP_ACP, 0, lpsz, -1, cvt, len, NULL, NULL);
224 SetWindowText(SDL_Window, cvt);
225 SDL_stack_free(cvt);
226 SDL_free(lpsz);
227#endif
228}
229
230int WIN_IconifyWindow(_THIS)
231{
232 ShowWindow(SDL_Window, SW_MINIMIZE);
233 return(1);
234}
235
236SDL_GrabMode WIN_GrabInput(_THIS, SDL_GrabMode mode)
237{
238 if ( mode == SDL_GRAB_OFF ) {
239 ClipCursor(NULL);
240 if ( !(SDL_cursorstate & CURSOR_VISIBLE) ) {
241 /* RJR: March 28, 2000
242 must be leaving relative mode, move mouse from
243 center of window to where it belongs ... */
244 POINT pt;
245 int x, y;
246 SDL_GetMouseState(&x,&y);
247 pt.x = x;
248 pt.y = y;
249 ClientToScreen(SDL_Window, &pt);
250 SetCursorPos(pt.x,pt.y);
251 }
252#ifdef _WIN32_WCE
253 AllKeys(0);
254#endif
255 } else {
256 ClipCursor(&SDL_bounds);
257 if ( !(SDL_cursorstate & CURSOR_VISIBLE) ) {
258 /* RJR: March 28, 2000
259 must be entering relative mode, get ready by
260 moving mouse to center of window ... */
261 POINT pt;
262 pt.x = (SDL_VideoSurface->w/2);
263 pt.y = (SDL_VideoSurface->h/2);
264 ClientToScreen(SDL_Window, &pt);
265 SetCursorPos(pt.x, pt.y);
266 }
267#ifdef _WIN32_WCE
268 AllKeys(1);
269#endif
270 }
271 return(mode);
272}
273
274/* If 'info' is the right version, this function fills it and returns 1.
275 Otherwise, in case of a version mismatch, it returns -1.
276*/
277int WIN_GetWMInfo(_THIS, SDL_SysWMinfo *info)
278{
279 if ( info->version.major <= SDL_MAJOR_VERSION ) {
280 info->window = SDL_Window;
281 if ( SDL_VERSIONNUM(info->version.major,
282 info->version.minor,
283 info->version.patch) >=
284 SDL_VERSIONNUM(1, 2, 5) ) {
285#if SDL_VIDEO_OPENGL
286 info->hglrc = GL_hrc;
287#else
288 info->hglrc = NULL;
289#endif
290 }
291 return(1);
292 } else {
293 SDL_SetError("Application not compiled with SDL %d.%d\n",
294 SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
295 return(-1);
296 }
297}
diff --git a/apps/plugins/sdl/src/video/wincommon/SDL_syswm_c.h b/apps/plugins/sdl/src/video/wincommon/SDL_syswm_c.h
deleted file mode 100644
index a103b433b4..0000000000
--- a/apps/plugins/sdl/src/video/wincommon/SDL_syswm_c.h
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_lowvideo.h"
25
26/* Data that needs to be freed at SDL_SYS_VideoQuit() */
27extern HICON screen_icn;
28
29/* Functions to be exported */
30extern void WIN_SetWMIcon(_THIS, SDL_Surface *icon, Uint8 *mask);
31extern void WIN_SetWMCaption(_THIS, const char *title, const char *icon);
32extern int WIN_IconifyWindow(_THIS);
33extern SDL_GrabMode WIN_GrabInput(_THIS, SDL_GrabMode mode);
34extern int WIN_GetWMInfo(_THIS, SDL_SysWMinfo *info);
35
diff --git a/apps/plugins/sdl/src/video/wincommon/SDL_wingl.c b/apps/plugins/sdl/src/video/wincommon/SDL_wingl.c
deleted file mode 100644
index fc4e9846d9..0000000000
--- a/apps/plugins/sdl/src/video/wincommon/SDL_wingl.c
+++ /dev/null
@@ -1,659 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* WGL implementation of SDL OpenGL support */
25
26#if SDL_VIDEO_OPENGL
27#include "SDL_opengl.h"
28#endif
29#include "SDL_lowvideo.h"
30#include "SDL_wingl_c.h"
31
32#if SDL_VIDEO_OPENGL
33#define DEFAULT_GL_DRIVER_PATH "OPENGL32.DLL"
34#endif
35
36/* If setting the HDC fails, we may need to recreate the window (MSDN) */
37static int WIN_GL_ResetWindow(_THIS)
38{
39 int status = 0;
40
41#ifndef _WIN32_WCE /* FIXME WinCE needs the UNICODE version of CreateWindow() */
42 /* This doesn't work with DirectX code (see CVS comments) */
43 /* If we were passed a window, then we can't create a new one */
44 if ( !SDL_windowid && SDL_strcmp(this->name, "windib") == 0 ) {
45 /* Save the existing window attributes */
46 LONG style;
47 RECT rect = { 0, 0, 0, 0 };
48 style = GetWindowLong(SDL_Window, GWL_STYLE);
49 GetWindowRect(SDL_Window, &rect);
50 DestroyWindow(SDL_Window);
51 WIN_FlushMessageQueue();
52
53 SDL_resizing = 1;
54 SDL_Window = CreateWindow(SDL_Appname, SDL_Appname,
55 style,
56 rect.left, rect.top,
57 (rect.right-rect.left)+1,
58 (rect.bottom-rect.top)+1,
59 NULL, NULL, SDL_Instance, NULL);
60 WIN_FlushMessageQueue();
61 SDL_resizing = 0;
62
63 if ( SDL_Window ) {
64 this->SetCaption(this, this->wm_title, this->wm_icon);
65 } else {
66 SDL_SetError("Couldn't create window");
67 status = -1;
68 }
69 } else
70#endif /* !_WIN32_WCE */
71 {
72 SDL_SetError("Unable to reset window for OpenGL context");
73 status = -1;
74 }
75 return(status);
76}
77
78#if SDL_VIDEO_OPENGL
79
80static int ExtensionSupported(const char *extension, const char *extensions)
81{
82 const char *start;
83 const char *where, *terminator;
84
85 /* Extension names should not have spaces. */
86 where = SDL_strchr(extension, ' ');
87 if ( where || *extension == '\0' )
88 return 0;
89
90 if ( ! extensions )
91 return 0;
92
93 /* It takes a bit of care to be fool-proof about parsing the
94 * OpenGL extensions string. Don't be fooled by sub-strings,
95 * etc. */
96
97 start = extensions;
98
99 for (;;)
100 {
101 where = SDL_strstr(start, extension);
102 if (!where) break;
103
104 terminator = where + SDL_strlen(extension);
105 if (where == start || *(where - 1) == ' ')
106 if (*terminator == ' ' || *terminator == '\0') return 1;
107
108 start = terminator;
109 }
110
111 return 0;
112}
113
114static int ChoosePixelFormatARB(_THIS, const int *iAttribs, const FLOAT *fAttribs)
115{
116 HWND hwnd;
117 HDC hdc;
118 HGLRC hglrc;
119 const char * (WINAPI *wglGetExtensionsStringARB)(HDC) = 0;
120 const char *extensions;
121 int pformat = 0;
122 UINT matches = 0;
123
124 hwnd = CreateWindow(SDL_Appname, SDL_Appname, WS_POPUP | WS_DISABLED,
125 0, 0, 10, 10,
126 NULL, NULL, SDL_Instance, NULL);
127 WIN_FlushMessageQueue();
128
129 hdc = GetDC(hwnd);
130
131 SetPixelFormat(hdc, ChoosePixelFormat(hdc, &GL_pfd), &GL_pfd);
132
133 hglrc = this->gl_data->wglCreateContext(hdc);
134 if ( hglrc ) {
135 this->gl_data->wglMakeCurrent(hdc, hglrc);
136 }
137
138 wglGetExtensionsStringARB = (const char * (WINAPI *)(HDC))
139 this->gl_data->wglGetProcAddress("wglGetExtensionsStringARB");
140
141 if( wglGetExtensionsStringARB ) {
142 extensions = wglGetExtensionsStringARB(hdc);
143 } else {
144 extensions = NULL;
145 }
146
147 this->gl_data->WGL_ARB_pixel_format = 0;
148 if( ExtensionSupported("WGL_ARB_pixel_format", extensions) ) {
149 BOOL (WINAPI *wglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
150 wglChoosePixelFormatARB =
151 (BOOL (WINAPI *)(HDC, const int *, const FLOAT *, UINT, int *, UINT *))
152 this->gl_data->wglGetProcAddress("wglChoosePixelFormatARB");
153 if( wglChoosePixelFormatARB &&
154 wglChoosePixelFormatARB(hdc, iAttribs, fAttribs, 1, &pformat, &matches) && pformat ) {
155 this->gl_data->WGL_ARB_pixel_format = 1;
156 }
157 }
158
159 if ( hglrc ) {
160 this->gl_data->wglMakeCurrent(NULL, NULL);
161 this->gl_data->wglDeleteContext(hglrc);
162 }
163 ReleaseDC(hwnd, hdc);
164 DestroyWindow(hwnd);
165 WIN_FlushMessageQueue();
166
167 return pformat;
168}
169
170#endif /* SDL_VIDEO_OPENGL */
171
172int WIN_GL_SetupWindow(_THIS)
173{
174 int retval;
175#if SDL_VIDEO_OPENGL
176 int i;
177 int iAttribs[64];
178 int *iAttr;
179 int *iAccelAttr = NULL;
180 float fAttribs[1] = { 0 };
181 const GLubyte *(WINAPI *glGetStringFunc)(GLenum);
182 const char *wglext;
183
184 /* load the gl driver from a default path */
185 if ( ! this->gl_config.driver_loaded ) {
186 /* no driver has been loaded, use default (ourselves) */
187 if ( WIN_GL_LoadLibrary(this, NULL) < 0 ) {
188 return(-1);
189 }
190 }
191
192 /* Set up the pixel format descriptor with our needed format */
193 SDL_memset(&GL_pfd, 0, sizeof(GL_pfd));
194 GL_pfd.nSize = sizeof(GL_pfd);
195 GL_pfd.nVersion = 1;
196 GL_pfd.dwFlags = (PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL);
197 if ( this->gl_config.double_buffer ) {
198 GL_pfd.dwFlags |= PFD_DOUBLEBUFFER;
199 }
200 if ( this->gl_config.stereo ) {
201 GL_pfd.dwFlags |= PFD_STEREO;
202 }
203 GL_pfd.iPixelType = PFD_TYPE_RGBA;
204 GL_pfd.cColorBits = this->gl_config.buffer_size;
205 GL_pfd.cRedBits = this->gl_config.red_size;
206 GL_pfd.cGreenBits = this->gl_config.green_size;
207 GL_pfd.cBlueBits = this->gl_config.blue_size;
208 GL_pfd.cAlphaBits = this->gl_config.alpha_size;
209 GL_pfd.cAccumRedBits = this->gl_config.accum_red_size;
210 GL_pfd.cAccumGreenBits = this->gl_config.accum_green_size;
211 GL_pfd.cAccumBlueBits = this->gl_config.accum_blue_size;
212 GL_pfd.cAccumAlphaBits = this->gl_config.accum_alpha_size;
213 GL_pfd.cAccumBits =
214 (GL_pfd.cAccumRedBits + GL_pfd.cAccumGreenBits +
215 GL_pfd.cAccumBlueBits + GL_pfd.cAccumAlphaBits);
216 GL_pfd.cDepthBits = this->gl_config.depth_size;
217 GL_pfd.cStencilBits = this->gl_config.stencil_size;
218
219 /* setup WGL_ARB_pixel_format attribs */
220 iAttr = &iAttribs[0];
221
222 *iAttr++ = WGL_DRAW_TO_WINDOW_ARB;
223 *iAttr++ = GL_TRUE;
224 *iAttr++ = WGL_RED_BITS_ARB;
225 *iAttr++ = this->gl_config.red_size;
226 *iAttr++ = WGL_GREEN_BITS_ARB;
227 *iAttr++ = this->gl_config.green_size;
228 *iAttr++ = WGL_BLUE_BITS_ARB;
229 *iAttr++ = this->gl_config.blue_size;
230
231 /* We always choose either FULL or NO accel on Windows, because of flaky
232 drivers. If the app didn't specify, we use FULL, because that's
233 probably what they wanted (and if you didn't care and got FULL, that's
234 a perfectly valid result in any case. */
235 *iAttr++ = WGL_ACCELERATION_ARB;
236 iAccelAttr = iAttr;
237 if (this->gl_config.accelerated) {
238 *iAttr++ = WGL_FULL_ACCELERATION_ARB;
239 } else {
240 *iAttr++ = WGL_NO_ACCELERATION_ARB;
241 }
242
243 if ( this->gl_config.alpha_size ) {
244 *iAttr++ = WGL_ALPHA_BITS_ARB;
245 *iAttr++ = this->gl_config.alpha_size;
246 }
247
248 *iAttr++ = WGL_DOUBLE_BUFFER_ARB;
249 *iAttr++ = this->gl_config.double_buffer;
250
251 *iAttr++ = WGL_DEPTH_BITS_ARB;
252 *iAttr++ = this->gl_config.depth_size;
253
254 if ( this->gl_config.stencil_size ) {
255 *iAttr++ = WGL_STENCIL_BITS_ARB;
256 *iAttr++ = this->gl_config.stencil_size;
257 }
258
259 if ( this->gl_config.accum_red_size ) {
260 *iAttr++ = WGL_ACCUM_RED_BITS_ARB;
261 *iAttr++ = this->gl_config.accum_red_size;
262 }
263
264 if ( this->gl_config.accum_green_size ) {
265 *iAttr++ = WGL_ACCUM_GREEN_BITS_ARB;
266 *iAttr++ = this->gl_config.accum_green_size;
267 }
268
269 if ( this->gl_config.accum_blue_size ) {
270 *iAttr++ = WGL_ACCUM_BLUE_BITS_ARB;
271 *iAttr++ = this->gl_config.accum_blue_size;
272 }
273
274 if ( this->gl_config.accum_alpha_size ) {
275 *iAttr++ = WGL_ACCUM_ALPHA_BITS_ARB;
276 *iAttr++ = this->gl_config.accum_alpha_size;
277 }
278
279 if ( this->gl_config.stereo ) {
280 *iAttr++ = WGL_STEREO_ARB;
281 *iAttr++ = GL_TRUE;
282 }
283
284 if ( this->gl_config.multisamplebuffers ) {
285 *iAttr++ = WGL_SAMPLE_BUFFERS_ARB;
286 *iAttr++ = this->gl_config.multisamplebuffers;
287 }
288
289 if ( this->gl_config.multisamplesamples ) {
290 *iAttr++ = WGL_SAMPLES_ARB;
291 *iAttr++ = this->gl_config.multisamplesamples;
292 }
293
294 *iAttr = 0;
295
296 for ( i=0; ; ++i ) {
297 /* Get the window device context for our OpenGL drawing */
298 GL_hdc = GetDC(SDL_Window);
299 if ( GL_hdc == NULL ) {
300 SDL_SetError("Unable to get DC for SDL_Window");
301 return(-1);
302 }
303
304 /* Choose and set the closest available pixel format */
305 pixel_format = ChoosePixelFormatARB(this, iAttribs, fAttribs);
306 /* App said "don't care about accel" and FULL accel failed. Try NO. */
307 if ( ( !pixel_format ) && ( this->gl_config.accelerated < 0 ) ) {
308 *iAccelAttr = WGL_NO_ACCELERATION_ARB;
309 pixel_format = ChoosePixelFormatARB(this, iAttribs, fAttribs);
310 *iAccelAttr = WGL_FULL_ACCELERATION_ARB; /* if we try again. */
311 }
312 if ( !pixel_format ) {
313 pixel_format = ChoosePixelFormat(GL_hdc, &GL_pfd);
314 }
315 if ( !pixel_format ) {
316 SDL_SetError("No matching GL pixel format available");
317 return(-1);
318 }
319 if ( !SetPixelFormat(GL_hdc, pixel_format, &GL_pfd) ) {
320 if ( i == 0 ) {
321 /* First time through, try resetting the window */
322 if ( WIN_GL_ResetWindow(this) < 0 ) {
323 return(-1);
324 }
325 continue;
326 }
327 SDL_SetError("Unable to set HDC pixel format");
328 return(-1);
329 }
330 /* We either succeeded or failed by this point */
331 break;
332 }
333 DescribePixelFormat(GL_hdc, pixel_format, sizeof(GL_pfd), &GL_pfd);
334
335 GL_hrc = this->gl_data->wglCreateContext(GL_hdc);
336 if ( GL_hrc == NULL ) {
337 SDL_SetError("Unable to create GL context");
338 return(-1);
339 }
340 if ( WIN_GL_MakeCurrent(this) < 0 ) {
341 return(-1);
342 }
343 gl_active = 1;
344
345 /* Get the wglGetPixelFormatAttribivARB pointer for the context */
346 if ( this->gl_data->WGL_ARB_pixel_format ) {
347 this->gl_data->wglGetPixelFormatAttribivARB =
348 (BOOL (WINAPI *)(HDC, int, int, UINT, const int *, int *))
349 this->gl_data->wglGetProcAddress("wglGetPixelFormatAttribivARB");
350 } else {
351 this->gl_data->wglGetPixelFormatAttribivARB = NULL;
352 }
353
354 /* Vsync control under Windows. Checking glGetString here is
355 * somewhat a documented and reliable hack - it was originally
356 * as a feature added by mistake, but since so many people rely
357 * on it, it will not be removed. strstr should be safe here.*/
358 glGetStringFunc = WIN_GL_GetProcAddress(this, "glGetString");
359 if ( glGetStringFunc ) {
360 wglext = (const char *)glGetStringFunc(GL_EXTENSIONS);
361 } else {
362 /* Uh oh, something is seriously wrong here... */
363 wglext = NULL;
364 }
365 if ( wglext && SDL_strstr(wglext, "WGL_EXT_swap_control") ) {
366 this->gl_data->wglSwapIntervalEXT = WIN_GL_GetProcAddress(this, "wglSwapIntervalEXT");
367 this->gl_data->wglGetSwapIntervalEXT = WIN_GL_GetProcAddress(this, "wglGetSwapIntervalEXT");
368 } else {
369 this->gl_data->wglSwapIntervalEXT = NULL;
370 this->gl_data->wglGetSwapIntervalEXT = NULL;
371 }
372 if ( this->gl_config.swap_control >= 0 ) {
373 if ( this->gl_data->wglSwapIntervalEXT ) {
374 this->gl_data->wglSwapIntervalEXT(this->gl_config.swap_control);
375 }
376 }
377#else
378 SDL_SetError("WIN driver not configured with OpenGL");
379#endif
380 if ( gl_active ) {
381 retval = 0;
382 } else {
383 retval = -1;
384 }
385 return(retval);
386}
387
388void WIN_GL_ShutDown(_THIS)
389{
390#if SDL_VIDEO_OPENGL
391 /* Clean up OpenGL */
392 if ( GL_hrc ) {
393 this->gl_data->wglMakeCurrent(NULL, NULL);
394 this->gl_data->wglDeleteContext(GL_hrc);
395 GL_hrc = NULL;
396 }
397 if ( GL_hdc ) {
398 ReleaseDC(SDL_Window, GL_hdc);
399 GL_hdc = NULL;
400 }
401 gl_active = 0;
402
403 WIN_GL_UnloadLibrary(this);
404#endif /* SDL_VIDEO_OPENGL */
405}
406
407#if SDL_VIDEO_OPENGL
408
409/* Make the current context active */
410int WIN_GL_MakeCurrent(_THIS)
411{
412 int retval;
413
414 retval = 0;
415 if ( ! this->gl_data->wglMakeCurrent(GL_hdc, GL_hrc) ) {
416 SDL_SetError("Unable to make GL context current");
417 retval = -1;
418 }
419 return(retval);
420}
421
422/* Get attribute data from wgl. */
423int WIN_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value)
424{
425 int retval;
426
427 if (attrib == SDL_GL_SWAP_CONTROL) {
428 if ( this->gl_data->wglGetSwapIntervalEXT ) {
429 *value = this->gl_data->wglGetSwapIntervalEXT();
430 return 0;
431 }
432 return -1;
433 }
434
435 if ( this->gl_data->wglGetPixelFormatAttribivARB ) {
436 int wgl_attrib;
437
438 switch(attrib) {
439 case SDL_GL_RED_SIZE:
440 wgl_attrib = WGL_RED_BITS_ARB;
441 break;
442 case SDL_GL_GREEN_SIZE:
443 wgl_attrib = WGL_GREEN_BITS_ARB;
444 break;
445 case SDL_GL_BLUE_SIZE:
446 wgl_attrib = WGL_BLUE_BITS_ARB;
447 break;
448 case SDL_GL_ALPHA_SIZE:
449 wgl_attrib = WGL_ALPHA_BITS_ARB;
450 break;
451 case SDL_GL_DOUBLEBUFFER:
452 wgl_attrib = WGL_DOUBLE_BUFFER_ARB;
453 break;
454 case SDL_GL_BUFFER_SIZE:
455 wgl_attrib = WGL_COLOR_BITS_ARB;
456 break;
457 case SDL_GL_DEPTH_SIZE:
458 wgl_attrib = WGL_DEPTH_BITS_ARB;
459 break;
460 case SDL_GL_STENCIL_SIZE:
461 wgl_attrib = WGL_STENCIL_BITS_ARB;
462 break;
463 case SDL_GL_ACCUM_RED_SIZE:
464 wgl_attrib = WGL_ACCUM_RED_BITS_ARB;
465 break;
466 case SDL_GL_ACCUM_GREEN_SIZE:
467 wgl_attrib = WGL_ACCUM_GREEN_BITS_ARB;
468 break;
469 case SDL_GL_ACCUM_BLUE_SIZE:
470 wgl_attrib = WGL_ACCUM_BLUE_BITS_ARB;
471 break;
472 case SDL_GL_ACCUM_ALPHA_SIZE:
473 wgl_attrib = WGL_ACCUM_ALPHA_BITS_ARB;
474 break;
475 case SDL_GL_STEREO:
476 wgl_attrib = WGL_STEREO_ARB;
477 break;
478 case SDL_GL_MULTISAMPLEBUFFERS:
479 wgl_attrib = WGL_SAMPLE_BUFFERS_ARB;
480 break;
481 case SDL_GL_MULTISAMPLESAMPLES:
482 wgl_attrib = WGL_SAMPLES_ARB;
483 break;
484 case SDL_GL_ACCELERATED_VISUAL:
485 wgl_attrib = WGL_ACCELERATION_ARB;
486 this->gl_data->wglGetPixelFormatAttribivARB(GL_hdc, pixel_format, 0, 1, &wgl_attrib, value);
487 if ( *value == WGL_NO_ACCELERATION_ARB ) {
488 *value = SDL_FALSE;
489 } else {
490 *value = SDL_TRUE;
491 }
492 return 0;
493 default:
494 return(-1);
495 }
496 this->gl_data->wglGetPixelFormatAttribivARB(GL_hdc, pixel_format, 0, 1, &wgl_attrib, value);
497
498 return 0;
499 }
500
501 retval = 0;
502 switch ( attrib ) {
503 case SDL_GL_RED_SIZE:
504 *value = GL_pfd.cRedBits;
505 break;
506 case SDL_GL_GREEN_SIZE:
507 *value = GL_pfd.cGreenBits;
508 break;
509 case SDL_GL_BLUE_SIZE:
510 *value = GL_pfd.cBlueBits;
511 break;
512 case SDL_GL_ALPHA_SIZE:
513 *value = GL_pfd.cAlphaBits;
514 break;
515 case SDL_GL_DOUBLEBUFFER:
516 if ( GL_pfd.dwFlags & PFD_DOUBLEBUFFER ) {
517 *value = 1;
518 } else {
519 *value = 0;
520 }
521 break;
522 case SDL_GL_BUFFER_SIZE:
523 *value = GL_pfd.cColorBits;
524 break;
525 case SDL_GL_DEPTH_SIZE:
526 *value = GL_pfd.cDepthBits;
527 break;
528 case SDL_GL_STENCIL_SIZE:
529 *value = GL_pfd.cStencilBits;
530 break;
531 case SDL_GL_ACCUM_RED_SIZE:
532 *value = GL_pfd.cAccumRedBits;
533 break;
534 case SDL_GL_ACCUM_GREEN_SIZE:
535 *value = GL_pfd.cAccumGreenBits;
536 break;
537 case SDL_GL_ACCUM_BLUE_SIZE:
538 *value = GL_pfd.cAccumBlueBits;
539 break;
540 case SDL_GL_ACCUM_ALPHA_SIZE:
541 *value = GL_pfd.cAccumAlphaBits;
542 break;
543 case SDL_GL_STEREO:
544 if ( GL_pfd.dwFlags & PFD_STEREO ) {
545 *value = 1;
546 } else {
547 *value = 0;
548 }
549 break;
550 case SDL_GL_MULTISAMPLEBUFFERS:
551 *value = 0;
552 break;
553 case SDL_GL_MULTISAMPLESAMPLES:
554 *value = 1;
555 break;
556 case SDL_GL_SWAP_CONTROL:
557 if ( this->gl_data->wglGetSwapIntervalEXT ) {
558 *value = this->gl_data->wglGetSwapIntervalEXT();
559 return 0;
560 } else {
561 return -1;
562 }
563 break;
564 default:
565 retval = -1;
566 break;
567 }
568 return retval;
569}
570
571void WIN_GL_SwapBuffers(_THIS)
572{
573 SwapBuffers(GL_hdc);
574}
575
576void WIN_GL_UnloadLibrary(_THIS)
577{
578 if ( this->gl_config.driver_loaded ) {
579 FreeLibrary((HMODULE)this->gl_config.dll_handle);
580
581 this->gl_data->wglGetProcAddress = NULL;
582 this->gl_data->wglCreateContext = NULL;
583 this->gl_data->wglDeleteContext = NULL;
584 this->gl_data->wglMakeCurrent = NULL;
585 this->gl_data->wglGetPixelFormatAttribivARB = NULL;
586 this->gl_data->wglSwapIntervalEXT = NULL;
587 this->gl_data->wglGetSwapIntervalEXT = NULL;
588
589 this->gl_config.dll_handle = NULL;
590 this->gl_config.driver_loaded = 0;
591 }
592}
593
594/* Passing a NULL path means load pointers from the application */
595int WIN_GL_LoadLibrary(_THIS, const char* path)
596{
597 HMODULE handle;
598
599 if ( gl_active ) {
600 SDL_SetError("OpenGL context already created");
601 return -1;
602 }
603
604 if ( path == NULL ) {
605 path = DEFAULT_GL_DRIVER_PATH;
606 }
607 handle = LoadLibrary(path);
608 if ( handle == NULL ) {
609 SDL_SetError("Could not load OpenGL library");
610 return -1;
611 }
612
613 /* Unload the old driver and reset the pointers */
614 WIN_GL_UnloadLibrary(this);
615
616 /* Load new function pointers */
617 SDL_memset(this->gl_data, 0, sizeof(*this->gl_data));
618 this->gl_data->wglGetProcAddress = (void * (WINAPI *)(const char *))
619 GetProcAddress(handle, "wglGetProcAddress");
620 this->gl_data->wglCreateContext = (HGLRC (WINAPI *)(HDC))
621 GetProcAddress(handle, "wglCreateContext");
622 this->gl_data->wglDeleteContext = (BOOL (WINAPI *)(HGLRC))
623 GetProcAddress(handle, "wglDeleteContext");
624 this->gl_data->wglMakeCurrent = (BOOL (WINAPI *)(HDC, HGLRC))
625 GetProcAddress(handle, "wglMakeCurrent");
626 this->gl_data->wglSwapIntervalEXT = (void (WINAPI *)(int))
627 GetProcAddress(handle, "wglSwapIntervalEXT");
628 this->gl_data->wglGetSwapIntervalEXT = (int (WINAPI *)(void))
629 GetProcAddress(handle, "wglGetSwapIntervalEXT");
630
631 if ( (this->gl_data->wglGetProcAddress == NULL) ||
632 (this->gl_data->wglCreateContext == NULL) ||
633 (this->gl_data->wglDeleteContext == NULL) ||
634 (this->gl_data->wglMakeCurrent == NULL) ) {
635 SDL_SetError("Could not retrieve OpenGL functions");
636 FreeLibrary(handle);
637 return -1;
638 }
639
640 this->gl_config.dll_handle = handle;
641 SDL_strlcpy(this->gl_config.driver_path, path, SDL_arraysize(this->gl_config.driver_path));
642 this->gl_config.driver_loaded = 1;
643 return 0;
644}
645
646void *WIN_GL_GetProcAddress(_THIS, const char* proc)
647{
648 void *func;
649
650 /* This is to pick up extensions */
651 func = this->gl_data->wglGetProcAddress(proc);
652 if ( ! func ) {
653 /* This is probably a normal GL function */
654 func = GetProcAddress(this->gl_config.dll_handle, proc);
655 }
656 return func;
657}
658
659#endif /* SDL_VIDEO_OPENGL */
diff --git a/apps/plugins/sdl/src/video/wincommon/SDL_wingl_c.h b/apps/plugins/sdl/src/video/wincommon/SDL_wingl_c.h
deleted file mode 100644
index c3f2291dbb..0000000000
--- a/apps/plugins/sdl/src/video/wincommon/SDL_wingl_c.h
+++ /dev/null
@@ -1,135 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* WGL implementation of SDL OpenGL support */
25
26#include "../SDL_sysvideo.h"
27
28
29struct SDL_PrivateGLData {
30 int gl_active; /* to stop switching drivers while we have a valid context */
31
32#if SDL_VIDEO_OPENGL
33 PIXELFORMATDESCRIPTOR GL_pfd;
34 HDC GL_hdc;
35 HGLRC GL_hrc;
36 int pixel_format;
37 int WGL_ARB_pixel_format;
38
39 void * (WINAPI *wglGetProcAddress)(const char *proc);
40
41 HGLRC (WINAPI *wglCreateContext)(HDC hdc);
42
43 BOOL (WINAPI *wglDeleteContext)(HGLRC hglrc);
44
45 BOOL (WINAPI *wglMakeCurrent)(HDC hdc, HGLRC hglrc);
46
47 BOOL (WINAPI *wglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat,
48 int iLayerPlane,
49 UINT nAttributes,
50 const int *piAttributes,
51 int *piValues);
52 void (WINAPI *wglSwapIntervalEXT)(int interval);
53 int (WINAPI *wglGetSwapIntervalEXT)(void);
54#endif /* SDL_VIDEO_OPENGL */
55};
56
57/* Old variable names */
58#define gl_active (this->gl_data->gl_active)
59#define GL_pfd (this->gl_data->GL_pfd)
60#define GL_hdc (this->gl_data->GL_hdc)
61#define GL_hrc (this->gl_data->GL_hrc)
62#define pixel_format (this->gl_data->pixel_format)
63
64/* OpenGL functions */
65extern int WIN_GL_SetupWindow(_THIS);
66extern void WIN_GL_ShutDown(_THIS);
67#if SDL_VIDEO_OPENGL
68extern int WIN_GL_MakeCurrent(_THIS);
69extern int WIN_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value);
70extern void WIN_GL_SwapBuffers(_THIS);
71extern void WIN_GL_UnloadLibrary(_THIS);
72extern int WIN_GL_LoadLibrary(_THIS, const char* path);
73extern void *WIN_GL_GetProcAddress(_THIS, const char* proc);
74#endif
75
76#if SDL_VIDEO_OPENGL
77
78#ifndef WGL_ARB_pixel_format
79#define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
80#define WGL_DRAW_TO_WINDOW_ARB 0x2001
81#define WGL_DRAW_TO_BITMAP_ARB 0x2002
82#define WGL_ACCELERATION_ARB 0x2003
83#define WGL_NEED_PALETTE_ARB 0x2004
84#define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005
85#define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006
86#define WGL_SWAP_METHOD_ARB 0x2007
87#define WGL_NUMBER_OVERLAYS_ARB 0x2008
88#define WGL_NUMBER_UNDERLAYS_ARB 0x2009
89#define WGL_TRANSPARENT_ARB 0x200A
90#define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037
91#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
92#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
93#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
94#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
95#define WGL_SHARE_DEPTH_ARB 0x200C
96#define WGL_SHARE_STENCIL_ARB 0x200D
97#define WGL_SHARE_ACCUM_ARB 0x200E
98#define WGL_SUPPORT_GDI_ARB 0x200F
99#define WGL_SUPPORT_OPENGL_ARB 0x2010
100#define WGL_DOUBLE_BUFFER_ARB 0x2011
101#define WGL_STEREO_ARB 0x2012
102#define WGL_PIXEL_TYPE_ARB 0x2013
103#define WGL_COLOR_BITS_ARB 0x2014
104#define WGL_RED_BITS_ARB 0x2015
105#define WGL_RED_SHIFT_ARB 0x2016
106#define WGL_GREEN_BITS_ARB 0x2017
107#define WGL_GREEN_SHIFT_ARB 0x2018
108#define WGL_BLUE_BITS_ARB 0x2019
109#define WGL_BLUE_SHIFT_ARB 0x201A
110#define WGL_ALPHA_BITS_ARB 0x201B
111#define WGL_ALPHA_SHIFT_ARB 0x201C
112#define WGL_ACCUM_BITS_ARB 0x201D
113#define WGL_ACCUM_RED_BITS_ARB 0x201E
114#define WGL_ACCUM_GREEN_BITS_ARB 0x201F
115#define WGL_ACCUM_BLUE_BITS_ARB 0x2020
116#define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
117#define WGL_DEPTH_BITS_ARB 0x2022
118#define WGL_STENCIL_BITS_ARB 0x2023
119#define WGL_AUX_BUFFERS_ARB 0x2024
120#define WGL_NO_ACCELERATION_ARB 0x2025
121#define WGL_GENERIC_ACCELERATION_ARB 0x2026
122#define WGL_FULL_ACCELERATION_ARB 0x2027
123#define WGL_SWAP_EXCHANGE_ARB 0x2028
124#define WGL_SWAP_COPY_ARB 0x2029
125#define WGL_SWAP_UNDEFINED_ARB 0x202A
126#define WGL_TYPE_RGBA_ARB 0x202B
127#define WGL_TYPE_COLORINDEX_ARB 0x202C
128#endif
129
130#ifndef WGL_ARB_multisample
131#define WGL_SAMPLE_BUFFERS_ARB 0x2041
132#define WGL_SAMPLES_ARB 0x2042
133#endif
134
135#endif
diff --git a/apps/plugins/sdl/src/video/wincommon/wmmsg.h b/apps/plugins/sdl/src/video/wincommon/wmmsg.h
deleted file mode 100644
index 175a8ceece..0000000000
--- a/apps/plugins/sdl/src/video/wincommon/wmmsg.h
+++ /dev/null
@@ -1,1030 +0,0 @@
1
2#define MAX_WMMSG (sizeof(wmtab)/sizeof(wmtab[0]))
3
4char *wmtab[] = {
5 "WM_NULL",
6 "WM_CREATE",
7 "WM_DESTROY",
8 "WM_MOVE",
9 "UNKNOWN (4)",
10 "WM_SIZE",
11 "WM_ACTIVATE",
12 "WM_SETFOCUS",
13 "WM_KILLFOCUS",
14 "UNKNOWN (9)",
15 "WM_ENABLE",
16 "WM_SETREDRAW",
17 "WM_SETTEXT",
18 "WM_GETTEXT",
19 "WM_GETTEXTLENGTH",
20 "WM_PAINT",
21 "WM_CLOSE",
22 "WM_QUERYENDSESSION",
23 "WM_QUIT",
24 "WM_QUERYOPEN",
25 "WM_ERASEBKGND",
26 "WM_SYSCOLORCHANGE",
27 "WM_ENDSESSION",
28 "UNKNOWN (23)",
29 "WM_SHOWWINDOW",
30 "UNKNOWN (25)",
31 "WM_SETTINGCHANGE",
32 "WM_DEVMODECHANGE",
33 "WM_ACTIVATEAPP",
34 "WM_FONTCHANGE",
35 "WM_TIMECHANGE",
36 "WM_CANCELMODE",
37 "WM_SETCURSOR",
38 "WM_MOUSEACTIVATE",
39 "WM_CHILDACTIVATE",
40 "WM_QUEUESYNC",
41 "WM_GETMINMAXINFO",
42 "UNKNOWN (37)",
43 "WM_PAINTICON",
44 "WM_ICONERASEBKGND",
45 "WM_NEXTDLGCTL",
46 "UNKNOWN (41)",
47 "WM_SPOOLERSTATUS",
48 "WM_DRAWITEM",
49 "WM_MEASUREITEM",
50 "WM_DELETEITEM",
51 "WM_VKEYTOITEM",
52 "WM_CHARTOITEM",
53 "WM_SETFONT",
54 "WM_GETFONT",
55 "WM_SETHOTKEY",
56 "WM_GETHOTKEY",
57 "UNKNOWN (52)",
58 "UNKNOWN (53)",
59 "UNKNOWN (54)",
60 "WM_QUERYDRAGICON",
61 "UNKNOWN (56)",
62 "WM_COMPAREITEM",
63 "UNKNOWN (58)",
64 "UNKNOWN (59)",
65 "UNKNOWN (60)",
66 "WM_GETOBJECT",
67 "UNKNOWN (62)",
68 "UNKNOWN (63)",
69 "UNKNOWN (64)",
70 "WM_COMPACTING",
71 "UNKNOWN (66)",
72 "UNKNOWN (67)",
73 "WM_COMMNOTIFY",
74 "UNKNOWN (69)",
75 "WM_WINDOWPOSCHANGING",
76 "WM_WINDOWPOSCHANGED",
77 "WM_POWER",
78 "UNKNOWN (73)",
79 "WM_COPYDATA",
80 "WM_CANCELJOURNAL",
81 "UNKNOWN (76)",
82 "UNKNOWN (77)",
83 "WM_NOTIFY",
84 "UNKNOWN (79)",
85 "WM_INPUTLANGCHANGEREQUEST",
86 "WM_INPUTLANGCHANGE",
87 "WM_TCARD",
88 "WM_HELP",
89 "WM_USERCHANGED",
90 "WM_NOTIFYFORMAT",
91 "UNKNOWN (86)",
92 "UNKNOWN (87)",
93 "UNKNOWN (88)",
94 "UNKNOWN (89)",
95 "UNKNOWN (90)",
96 "UNKNOWN (91)",
97 "UNKNOWN (92)",
98 "UNKNOWN (93)",
99 "UNKNOWN (94)",
100 "UNKNOWN (95)",
101 "UNKNOWN (96)",
102 "UNKNOWN (97)",
103 "UNKNOWN (98)",
104 "UNKNOWN (99)",
105 "UNKNOWN (100)",
106 "UNKNOWN (101)",
107 "UNKNOWN (102)",
108 "UNKNOWN (103)",
109 "UNKNOWN (104)",
110 "UNKNOWN (105)",
111 "UNKNOWN (106)",
112 "UNKNOWN (107)",
113 "UNKNOWN (108)",
114 "UNKNOWN (109)",
115 "UNKNOWN (110)",
116 "UNKNOWN (111)",
117 "UNKNOWN (112)",
118 "UNKNOWN (113)",
119 "UNKNOWN (114)",
120 "UNKNOWN (115)",
121 "UNKNOWN (116)",
122 "UNKNOWN (117)",
123 "UNKNOWN (118)",
124 "UNKNOWN (119)",
125 "UNKNOWN (120)",
126 "UNKNOWN (121)",
127 "UNKNOWN (122)",
128 "WM_CONTEXTMENU",
129 "WM_STYLECHANGING",
130 "WM_STYLECHANGED",
131 "WM_DISPLAYCHANGE",
132 "WM_GETICON",
133 "WM_SETICON",
134 "WM_NCCREATE",
135 "WM_NCDESTROY",
136 "WM_NCCALCSIZE",
137 "WM_NCHITTEST",
138 "WM_NCPAINT",
139 "WM_NCACTIVATE",
140 "WM_GETDLGCODE",
141 "WM_SYNCPAINT",
142 "UNKNOWN (137)",
143 "UNKNOWN (138)",
144 "UNKNOWN (139)",
145 "UNKNOWN (140)",
146 "UNKNOWN (141)",
147 "UNKNOWN (142)",
148 "UNKNOWN (143)",
149 "UNKNOWN (144)",
150 "UNKNOWN (145)",
151 "UNKNOWN (146)",
152 "UNKNOWN (147)",
153 "UNKNOWN (148)",
154 "UNKNOWN (149)",
155 "UNKNOWN (150)",
156 "UNKNOWN (151)",
157 "UNKNOWN (152)",
158 "UNKNOWN (153)",
159 "UNKNOWN (154)",
160 "UNKNOWN (155)",
161 "UNKNOWN (156)",
162 "UNKNOWN (157)",
163 "UNKNOWN (158)",
164 "UNKNOWN (159)",
165 "WM_NCMOUSEMOVE",
166 "WM_NCLBUTTONDOWN",
167 "WM_NCLBUTTONUP",
168 "WM_NCLBUTTONDBLCLK",
169 "WM_NCRBUTTONDOWN",
170 "WM_NCRBUTTONUP",
171 "WM_NCRBUTTONDBLCLK",
172 "WM_NCMBUTTONDOWN",
173 "WM_NCMBUTTONUP",
174 "WM_NCMBUTTONDBLCLK",
175 "UNKNOWN (170)",
176 "UNKNOWN (171)",
177 "UNKNOWN (172)",
178 "UNKNOWN (173)",
179 "UNKNOWN (174)",
180 "UNKNOWN (175)",
181 "UNKNOWN (176)",
182 "UNKNOWN (177)",
183 "UNKNOWN (178)",
184 "UNKNOWN (179)",
185 "UNKNOWN (180)",
186 "UNKNOWN (181)",
187 "UNKNOWN (182)",
188 "UNKNOWN (183)",
189 "UNKNOWN (184)",
190 "UNKNOWN (185)",
191 "UNKNOWN (186)",
192 "UNKNOWN (187)",
193 "UNKNOWN (188)",
194 "UNKNOWN (189)",
195 "UNKNOWN (190)",
196 "UNKNOWN (191)",
197 "UNKNOWN (192)",
198 "UNKNOWN (193)",
199 "UNKNOWN (194)",
200 "UNKNOWN (195)",
201 "UNKNOWN (196)",
202 "UNKNOWN (197)",
203 "UNKNOWN (198)",
204 "UNKNOWN (199)",
205 "UNKNOWN (200)",
206 "UNKNOWN (201)",
207 "UNKNOWN (202)",
208 "UNKNOWN (203)",
209 "UNKNOWN (204)",
210 "UNKNOWN (205)",
211 "UNKNOWN (206)",
212 "UNKNOWN (207)",
213 "UNKNOWN (208)",
214 "UNKNOWN (209)",
215 "UNKNOWN (210)",
216 "UNKNOWN (211)",
217 "UNKNOWN (212)",
218 "UNKNOWN (213)",
219 "UNKNOWN (214)",
220 "UNKNOWN (215)",
221 "UNKNOWN (216)",
222 "UNKNOWN (217)",
223 "UNKNOWN (218)",
224 "UNKNOWN (219)",
225 "UNKNOWN (220)",
226 "UNKNOWN (221)",
227 "UNKNOWN (222)",
228 "UNKNOWN (223)",
229 "UNKNOWN (224)",
230 "UNKNOWN (225)",
231 "UNKNOWN (226)",
232 "UNKNOWN (227)",
233 "UNKNOWN (228)",
234 "UNKNOWN (229)",
235 "UNKNOWN (230)",
236 "UNKNOWN (231)",
237 "UNKNOWN (232)",
238 "UNKNOWN (233)",
239 "UNKNOWN (234)",
240 "UNKNOWN (235)",
241 "UNKNOWN (236)",
242 "UNKNOWN (237)",
243 "UNKNOWN (238)",
244 "UNKNOWN (239)",
245 "UNKNOWN (240)",
246 "UNKNOWN (241)",
247 "UNKNOWN (242)",
248 "UNKNOWN (243)",
249 "UNKNOWN (244)",
250 "UNKNOWN (245)",
251 "UNKNOWN (246)",
252 "UNKNOWN (247)",
253 "UNKNOWN (248)",
254 "UNKNOWN (249)",
255 "UNKNOWN (250)",
256 "UNKNOWN (251)",
257 "UNKNOWN (252)",
258 "UNKNOWN (253)",
259 "UNKNOWN (254)",
260 "UNKNOWN (255)",
261 "WM_KEYDOWN",
262 "WM_KEYUP",
263 "WM_CHAR",
264 "WM_DEADCHAR",
265 "WM_SYSKEYDOWN",
266 "WM_SYSKEYUP",
267 "WM_SYSCHAR",
268 "WM_SYSDEADCHAR",
269 "WM_KEYLAST",
270 "UNKNOWN (265)",
271 "UNKNOWN (266)",
272 "UNKNOWN (267)",
273 "UNKNOWN (268)",
274 "UNKNOWN (269)",
275 "UNKNOWN (270)",
276 "UNKNOWN (271)",
277 "WM_INITDIALOG",
278 "WM_COMMAND",
279 "WM_SYSCOMMAND",
280 "WM_TIMER",
281 "WM_HSCROLL",
282 "WM_VSCROLL",
283 "WM_INITMENU",
284 "WM_INITMENUPOPUP",
285 "UNKNOWN (280)",
286 "UNKNOWN (281)",
287 "UNKNOWN (282)",
288 "UNKNOWN (283)",
289 "UNKNOWN (284)",
290 "UNKNOWN (285)",
291 "UNKNOWN (286)",
292 "WM_MENUSELECT",
293 "WM_MENUCHAR",
294 "WM_ENTERIDLE",
295 "WM_MENURBUTTONUP",
296 "WM_MENUDRAG",
297 "WM_MENUGETOBJECT",
298 "WM_UNINITMENUPOPUP",
299 "WM_MENUCOMMAND",
300 "UNKNOWN (295)",
301 "UNKNOWN (296)",
302 "UNKNOWN (297)",
303 "UNKNOWN (298)",
304 "UNKNOWN (299)",
305 "UNKNOWN (300)",
306 "UNKNOWN (301)",
307 "UNKNOWN (302)",
308 "UNKNOWN (303)",
309 "UNKNOWN (304)",
310 "UNKNOWN (305)",
311 "WM_CTLCOLORMSGBOX",
312 "WM_CTLCOLOREDIT",
313 "WM_CTLCOLORLISTBOX",
314 "WM_CTLCOLORBTN",
315 "WM_CTLCOLORDLG",
316 "WM_CTLCOLORSCROLLBAR",
317 "WM_CTLCOLORSTATIC",
318 "UNKNOWN (313)",
319 "UNKNOWN (314)",
320 "UNKNOWN (315)",
321 "UNKNOWN (316)",
322 "UNKNOWN (317)",
323 "UNKNOWN (318)",
324 "UNKNOWN (319)",
325 "UNKNOWN (320)",
326 "UNKNOWN (321)",
327 "UNKNOWN (322)",
328 "UNKNOWN (323)",
329 "UNKNOWN (324)",
330 "UNKNOWN (325)",
331 "UNKNOWN (326)",
332 "UNKNOWN (327)",
333 "UNKNOWN (328)",
334 "UNKNOWN (329)",
335 "UNKNOWN (330)",
336 "UNKNOWN (331)",
337 "UNKNOWN (332)",
338 "UNKNOWN (333)",
339 "UNKNOWN (334)",
340 "UNKNOWN (335)",
341 "UNKNOWN (336)",
342 "UNKNOWN (337)",
343 "UNKNOWN (338)",
344 "UNKNOWN (339)",
345 "UNKNOWN (340)",
346 "UNKNOWN (341)",
347 "UNKNOWN (342)",
348 "UNKNOWN (343)",
349 "UNKNOWN (344)",
350 "UNKNOWN (345)",
351 "UNKNOWN (346)",
352 "UNKNOWN (347)",
353 "UNKNOWN (348)",
354 "UNKNOWN (349)",
355 "UNKNOWN (350)",
356 "UNKNOWN (351)",
357 "UNKNOWN (352)",
358 "UNKNOWN (353)",
359 "UNKNOWN (354)",
360 "UNKNOWN (355)",
361 "UNKNOWN (356)",
362 "UNKNOWN (357)",
363 "UNKNOWN (358)",
364 "UNKNOWN (359)",
365 "UNKNOWN (360)",
366 "UNKNOWN (361)",
367 "UNKNOWN (362)",
368 "UNKNOWN (363)",
369 "UNKNOWN (364)",
370 "UNKNOWN (365)",
371 "UNKNOWN (366)",
372 "UNKNOWN (367)",
373 "UNKNOWN (368)",
374 "UNKNOWN (369)",
375 "UNKNOWN (370)",
376 "UNKNOWN (371)",
377 "UNKNOWN (372)",
378 "UNKNOWN (373)",
379 "UNKNOWN (374)",
380 "UNKNOWN (375)",
381 "UNKNOWN (376)",
382 "UNKNOWN (377)",
383 "UNKNOWN (378)",
384 "UNKNOWN (379)",
385 "UNKNOWN (380)",
386 "UNKNOWN (381)",
387 "UNKNOWN (382)",
388 "UNKNOWN (383)",
389 "UNKNOWN (384)",
390 "UNKNOWN (385)",
391 "UNKNOWN (386)",
392 "UNKNOWN (387)",
393 "UNKNOWN (388)",
394 "UNKNOWN (389)",
395 "UNKNOWN (390)",
396 "UNKNOWN (391)",
397 "UNKNOWN (392)",
398 "UNKNOWN (393)",
399 "UNKNOWN (394)",
400 "UNKNOWN (395)",
401 "UNKNOWN (396)",
402 "UNKNOWN (397)",
403 "UNKNOWN (398)",
404 "UNKNOWN (399)",
405 "UNKNOWN (400)",
406 "UNKNOWN (401)",
407 "UNKNOWN (402)",
408 "UNKNOWN (403)",
409 "UNKNOWN (404)",
410 "UNKNOWN (405)",
411 "UNKNOWN (406)",
412 "UNKNOWN (407)",
413 "UNKNOWN (408)",
414 "UNKNOWN (409)",
415 "UNKNOWN (410)",
416 "UNKNOWN (411)",
417 "UNKNOWN (412)",
418 "UNKNOWN (413)",
419 "UNKNOWN (414)",
420 "UNKNOWN (415)",
421 "UNKNOWN (416)",
422 "UNKNOWN (417)",
423 "UNKNOWN (418)",
424 "UNKNOWN (419)",
425 "UNKNOWN (420)",
426 "UNKNOWN (421)",
427 "UNKNOWN (422)",
428 "UNKNOWN (423)",
429 "UNKNOWN (424)",
430 "UNKNOWN (425)",
431 "UNKNOWN (426)",
432 "UNKNOWN (427)",
433 "UNKNOWN (428)",
434 "UNKNOWN (429)",
435 "UNKNOWN (430)",
436 "UNKNOWN (431)",
437 "UNKNOWN (432)",
438 "UNKNOWN (433)",
439 "UNKNOWN (434)",
440 "UNKNOWN (435)",
441 "UNKNOWN (436)",
442 "UNKNOWN (437)",
443 "UNKNOWN (438)",
444 "UNKNOWN (439)",
445 "UNKNOWN (440)",
446 "UNKNOWN (441)",
447 "UNKNOWN (442)",
448 "UNKNOWN (443)",
449 "UNKNOWN (444)",
450 "UNKNOWN (445)",
451 "UNKNOWN (446)",
452 "UNKNOWN (447)",
453 "UNKNOWN (448)",
454 "UNKNOWN (449)",
455 "UNKNOWN (450)",
456 "UNKNOWN (451)",
457 "UNKNOWN (452)",
458 "UNKNOWN (453)",
459 "UNKNOWN (454)",
460 "UNKNOWN (455)",
461 "UNKNOWN (456)",
462 "UNKNOWN (457)",
463 "UNKNOWN (458)",
464 "UNKNOWN (459)",
465 "UNKNOWN (460)",
466 "UNKNOWN (461)",
467 "UNKNOWN (462)",
468 "UNKNOWN (463)",
469 "UNKNOWN (464)",
470 "UNKNOWN (465)",
471 "UNKNOWN (466)",
472 "UNKNOWN (467)",
473 "UNKNOWN (468)",
474 "UNKNOWN (469)",
475 "UNKNOWN (470)",
476 "UNKNOWN (471)",
477 "UNKNOWN (472)",
478 "UNKNOWN (473)",
479 "UNKNOWN (474)",
480 "UNKNOWN (475)",
481 "UNKNOWN (476)",
482 "UNKNOWN (477)",
483 "UNKNOWN (478)",
484 "UNKNOWN (479)",
485 "UNKNOWN (480)",
486 "UNKNOWN (481)",
487 "UNKNOWN (482)",
488 "UNKNOWN (483)",
489 "UNKNOWN (484)",
490 "UNKNOWN (485)",
491 "UNKNOWN (486)",
492 "UNKNOWN (487)",
493 "UNKNOWN (488)",
494 "UNKNOWN (489)",
495 "UNKNOWN (490)",
496 "UNKNOWN (491)",
497 "UNKNOWN (492)",
498 "UNKNOWN (493)",
499 "UNKNOWN (494)",
500 "UNKNOWN (495)",
501 "UNKNOWN (496)",
502 "UNKNOWN (497)",
503 "UNKNOWN (498)",
504 "UNKNOWN (499)",
505 "UNKNOWN (500)",
506 "UNKNOWN (501)",
507 "UNKNOWN (502)",
508 "UNKNOWN (503)",
509 "UNKNOWN (504)",
510 "UNKNOWN (505)",
511 "UNKNOWN (506)",
512 "UNKNOWN (507)",
513 "UNKNOWN (508)",
514 "UNKNOWN (509)",
515 "UNKNOWN (510)",
516 "UNKNOWN (511)",
517 "WM_MOUSEMOVE",
518 "WM_LBUTTONDOWN",
519 "WM_LBUTTONUP",
520 "WM_LBUTTONDBLCLK",
521 "WM_RBUTTONDOWN",
522 "WM_RBUTTONUP",
523 "WM_RBUTTONDBLCLK",
524 "WM_MBUTTONDOWN",
525 "WM_MBUTTONUP",
526 "WM_MOUSELAST",
527 "WM_MOUSEWHEEL",
528 "WM_XBUTTONDOWN",
529 "WM_XBUTTONUP",
530 "UNKNOWN (525)",
531 "UNKNOWN (526)",
532 "UNKNOWN (527)",
533 "WM_PARENTNOTIFY",
534 "WM_ENTERMENULOOP",
535 "WM_EXITMENULOOP",
536 "WM_NEXTMENU",
537 "WM_SIZING",
538 "WM_CAPTURECHANGED",
539 "WM_MOVING",
540 "UNKNOWN (535)",
541 "WM_POWERBROADCAST",
542 "WM_DEVICECHANGE",
543 "UNKNOWN (538)",
544 "UNKNOWN (539)",
545 "UNKNOWN (540)",
546 "UNKNOWN (541)",
547 "UNKNOWN (542)",
548 "UNKNOWN (543)",
549 "WM_MDICREATE",
550 "WM_MDIDESTROY",
551 "WM_MDIACTIVATE",
552 "WM_MDIRESTORE",
553 "WM_MDINEXT",
554 "WM_MDIMAXIMIZE",
555 "WM_MDITILE",
556 "WM_MDICASCADE",
557 "WM_MDIICONARRANGE",
558 "WM_MDIGETACTIVE",
559 "UNKNOWN (554)",
560 "UNKNOWN (555)",
561 "UNKNOWN (556)",
562 "UNKNOWN (557)",
563 "UNKNOWN (558)",
564 "UNKNOWN (559)",
565 "WM_MDISETMENU",
566 "WM_ENTERSIZEMOVE",
567 "WM_EXITSIZEMOVE",
568 "WM_DROPFILES",
569 "WM_MDIREFRESHMENU",
570 "UNKNOWN (565)",
571 "UNKNOWN (566)",
572 "UNKNOWN (567)",
573 "UNKNOWN (568)",
574 "UNKNOWN (569)",
575 "UNKNOWN (570)",
576 "UNKNOWN (571)",
577 "UNKNOWN (572)",
578 "UNKNOWN (573)",
579 "UNKNOWN (574)",
580 "UNKNOWN (575)",
581 "UNKNOWN (576)",
582 "UNKNOWN (577)",
583 "UNKNOWN (578)",
584 "UNKNOWN (579)",
585 "UNKNOWN (580)",
586 "UNKNOWN (581)",
587 "UNKNOWN (582)",
588 "UNKNOWN (583)",
589 "UNKNOWN (584)",
590 "UNKNOWN (585)",
591 "UNKNOWN (586)",
592 "UNKNOWN (587)",
593 "UNKNOWN (588)",
594 "UNKNOWN (589)",
595 "UNKNOWN (590)",
596 "UNKNOWN (591)",
597 "UNKNOWN (592)",
598 "UNKNOWN (593)",
599 "UNKNOWN (594)",
600 "UNKNOWN (595)",
601 "UNKNOWN (596)",
602 "UNKNOWN (597)",
603 "UNKNOWN (598)",
604 "UNKNOWN (599)",
605 "UNKNOWN (600)",
606 "UNKNOWN (601)",
607 "UNKNOWN (602)",
608 "UNKNOWN (603)",
609 "UNKNOWN (604)",
610 "UNKNOWN (605)",
611 "UNKNOWN (606)",
612 "UNKNOWN (607)",
613 "UNKNOWN (608)",
614 "UNKNOWN (609)",
615 "UNKNOWN (610)",
616 "UNKNOWN (611)",
617 "UNKNOWN (612)",
618 "UNKNOWN (613)",
619 "UNKNOWN (614)",
620 "UNKNOWN (615)",
621 "UNKNOWN (616)",
622 "UNKNOWN (617)",
623 "UNKNOWN (618)",
624 "UNKNOWN (619)",
625 "UNKNOWN (620)",
626 "UNKNOWN (621)",
627 "UNKNOWN (622)",
628 "UNKNOWN (623)",
629 "UNKNOWN (624)",
630 "UNKNOWN (625)",
631 "UNKNOWN (626)",
632 "UNKNOWN (627)",
633 "UNKNOWN (628)",
634 "UNKNOWN (629)",
635 "UNKNOWN (630)",
636 "UNKNOWN (631)",
637 "UNKNOWN (632)",
638 "UNKNOWN (633)",
639 "UNKNOWN (634)",
640 "UNKNOWN (635)",
641 "UNKNOWN (636)",
642 "UNKNOWN (637)",
643 "UNKNOWN (638)",
644 "UNKNOWN (639)",
645 "UNKNOWN (640)",
646 "UNKNOWN (641)",
647 "UNKNOWN (642)",
648 "UNKNOWN (643)",
649 "UNKNOWN (644)",
650 "UNKNOWN (645)",
651 "UNKNOWN (646)",
652 "UNKNOWN (647)",
653 "UNKNOWN (648)",
654 "UNKNOWN (649)",
655 "UNKNOWN (650)",
656 "UNKNOWN (651)",
657 "UNKNOWN (652)",
658 "UNKNOWN (653)",
659 "UNKNOWN (654)",
660 "UNKNOWN (655)",
661 "UNKNOWN (656)",
662 "UNKNOWN (657)",
663 "UNKNOWN (658)",
664 "UNKNOWN (659)",
665 "UNKNOWN (660)",
666 "UNKNOWN (661)",
667 "UNKNOWN (662)",
668 "UNKNOWN (663)",
669 "UNKNOWN (664)",
670 "UNKNOWN (665)",
671 "UNKNOWN (666)",
672 "UNKNOWN (667)",
673 "UNKNOWN (668)",
674 "UNKNOWN (669)",
675 "UNKNOWN (670)",
676 "UNKNOWN (671)",
677 "UNKNOWN (672)",
678 "WM_MOUSEHOVER",
679 "UNKNOWN (674)",
680 "WM_MOUSELEAVE",
681 "UNKNOWN (676)",
682 "UNKNOWN (677)",
683 "UNKNOWN (678)",
684 "UNKNOWN (679)",
685 "UNKNOWN (680)",
686 "UNKNOWN (681)",
687 "UNKNOWN (682)",
688 "UNKNOWN (683)",
689 "UNKNOWN (684)",
690 "UNKNOWN (685)",
691 "UNKNOWN (686)",
692 "UNKNOWN (687)",
693 "UNKNOWN (688)",
694 "UNKNOWN (689)",
695 "UNKNOWN (690)",
696 "UNKNOWN (691)",
697 "UNKNOWN (692)",
698 "UNKNOWN (693)",
699 "UNKNOWN (694)",
700 "UNKNOWN (695)",
701 "UNKNOWN (696)",
702 "UNKNOWN (697)",
703 "UNKNOWN (698)",
704 "UNKNOWN (699)",
705 "UNKNOWN (700)",
706 "UNKNOWN (701)",
707 "UNKNOWN (702)",
708 "UNKNOWN (703)",
709 "UNKNOWN (704)",
710 "UNKNOWN (705)",
711 "UNKNOWN (706)",
712 "UNKNOWN (707)",
713 "UNKNOWN (708)",
714 "UNKNOWN (709)",
715 "UNKNOWN (710)",
716 "UNKNOWN (711)",
717 "UNKNOWN (712)",
718 "UNKNOWN (713)",
719 "UNKNOWN (714)",
720 "UNKNOWN (715)",
721 "UNKNOWN (716)",
722 "UNKNOWN (717)",
723 "UNKNOWN (718)",
724 "UNKNOWN (719)",
725 "UNKNOWN (720)",
726 "UNKNOWN (721)",
727 "UNKNOWN (722)",
728 "UNKNOWN (723)",
729 "UNKNOWN (724)",
730 "UNKNOWN (725)",
731 "UNKNOWN (726)",
732 "UNKNOWN (727)",
733 "UNKNOWN (728)",
734 "UNKNOWN (729)",
735 "UNKNOWN (730)",
736 "UNKNOWN (731)",
737 "UNKNOWN (732)",
738 "UNKNOWN (733)",
739 "UNKNOWN (734)",
740 "UNKNOWN (735)",
741 "UNKNOWN (736)",
742 "UNKNOWN (737)",
743 "UNKNOWN (738)",
744 "UNKNOWN (739)",
745 "UNKNOWN (740)",
746 "UNKNOWN (741)",
747 "UNKNOWN (742)",
748 "UNKNOWN (743)",
749 "UNKNOWN (744)",
750 "UNKNOWN (745)",
751 "UNKNOWN (746)",
752 "UNKNOWN (747)",
753 "UNKNOWN (748)",
754 "UNKNOWN (749)",
755 "UNKNOWN (750)",
756 "UNKNOWN (751)",
757 "UNKNOWN (752)",
758 "UNKNOWN (753)",
759 "UNKNOWN (754)",
760 "UNKNOWN (755)",
761 "UNKNOWN (756)",
762 "UNKNOWN (757)",
763 "UNKNOWN (758)",
764 "UNKNOWN (759)",
765 "UNKNOWN (760)",
766 "UNKNOWN (761)",
767 "UNKNOWN (762)",
768 "UNKNOWN (763)",
769 "UNKNOWN (764)",
770 "UNKNOWN (765)",
771 "UNKNOWN (766)",
772 "UNKNOWN (767)",
773 "WM_CUT",
774 "WM_COPY",
775 "WM_PASTE",
776 "WM_CLEAR",
777 "WM_UNDO",
778 "WM_RENDERFORMAT",
779 "WM_RENDERALLFORMATS",
780 "WM_DESTROYCLIPBOARD",
781 "WM_DRAWCLIPBOARD",
782 "WM_PAINTCLIPBOARD",
783 "WM_VSCROLLCLIPBOARD",
784 "WM_SIZECLIPBOARD",
785 "WM_ASKCBFORMATNAME",
786 "WM_CHANGECBCHAIN",
787 "WM_HSCROLLCLIPBOARD",
788 "WM_QUERYNEWPALETTE",
789 "WM_PALETTEISCHANGING",
790 "WM_PALETTECHANGED",
791 "WM_HOTKEY",
792 "UNKNOWN (787)",
793 "UNKNOWN (788)",
794 "UNKNOWN (789)",
795 "UNKNOWN (790)",
796 "WM_PRINT",
797 "WM_PRINTCLIENT",
798 "UNKNOWN (793)",
799 "UNKNOWN (794)",
800 "UNKNOWN (795)",
801 "UNKNOWN (796)",
802 "UNKNOWN (797)",
803 "UNKNOWN (798)",
804 "UNKNOWN (799)",
805 "UNKNOWN (800)",
806 "UNKNOWN (801)",
807 "UNKNOWN (802)",
808 "UNKNOWN (803)",
809 "UNKNOWN (804)",
810 "UNKNOWN (805)",
811 "UNKNOWN (806)",
812 "UNKNOWN (807)",
813 "UNKNOWN (808)",
814 "UNKNOWN (809)",
815 "UNKNOWN (810)",
816 "UNKNOWN (811)",
817 "UNKNOWN (812)",
818 "UNKNOWN (813)",
819 "UNKNOWN (814)",
820 "UNKNOWN (815)",
821 "UNKNOWN (816)",
822 "UNKNOWN (817)",
823 "UNKNOWN (818)",
824 "UNKNOWN (819)",
825 "UNKNOWN (820)",
826 "UNKNOWN (821)",
827 "UNKNOWN (822)",
828 "UNKNOWN (823)",
829 "UNKNOWN (824)",
830 "UNKNOWN (825)",
831 "UNKNOWN (826)",
832 "UNKNOWN (827)",
833 "UNKNOWN (828)",
834 "UNKNOWN (829)",
835 "UNKNOWN (830)",
836 "UNKNOWN (831)",
837 "UNKNOWN (832)",
838 "UNKNOWN (833)",
839 "UNKNOWN (834)",
840 "UNKNOWN (835)",
841 "UNKNOWN (836)",
842 "UNKNOWN (837)",
843 "UNKNOWN (838)",
844 "UNKNOWN (839)",
845 "UNKNOWN (840)",
846 "UNKNOWN (841)",
847 "UNKNOWN (842)",
848 "UNKNOWN (843)",
849 "UNKNOWN (844)",
850 "UNKNOWN (845)",
851 "UNKNOWN (846)",
852 "UNKNOWN (847)",
853 "UNKNOWN (848)",
854 "UNKNOWN (849)",
855 "UNKNOWN (850)",
856 "UNKNOWN (851)",
857 "UNKNOWN (852)",
858 "UNKNOWN (853)",
859 "UNKNOWN (854)",
860 "UNKNOWN (855)",
861 "WM_HANDHELDFIRST",
862 "UNKNOWN (857)",
863 "UNKNOWN (858)",
864 "UNKNOWN (859)",
865 "UNKNOWN (860)",
866 "UNKNOWN (861)",
867 "UNKNOWN (862)",
868 "WM_HANDHELDLAST",
869 "WM_AFXFIRST",
870 "UNKNOWN (865)",
871 "UNKNOWN (866)",
872 "UNKNOWN (867)",
873 "UNKNOWN (868)",
874 "UNKNOWN (869)",
875 "UNKNOWN (870)",
876 "UNKNOWN (871)",
877 "UNKNOWN (872)",
878 "UNKNOWN (873)",
879 "UNKNOWN (874)",
880 "UNKNOWN (875)",
881 "UNKNOWN (876)",
882 "UNKNOWN (877)",
883 "UNKNOWN (878)",
884 "UNKNOWN (879)",
885 "UNKNOWN (880)",
886 "UNKNOWN (881)",
887 "UNKNOWN (882)",
888 "UNKNOWN (883)",
889 "UNKNOWN (884)",
890 "UNKNOWN (885)",
891 "UNKNOWN (886)",
892 "UNKNOWN (887)",
893 "UNKNOWN (888)",
894 "UNKNOWN (889)",
895 "UNKNOWN (890)",
896 "UNKNOWN (891)",
897 "UNKNOWN (892)",
898 "UNKNOWN (893)",
899 "UNKNOWN (894)",
900 "WM_AFXLAST",
901 "WM_PENWINFIRST",
902 "UNKNOWN (897)",
903 "UNKNOWN (898)",
904 "UNKNOWN (899)",
905 "UNKNOWN (900)",
906 "UNKNOWN (901)",
907 "UNKNOWN (902)",
908 "UNKNOWN (903)",
909 "UNKNOWN (904)",
910 "UNKNOWN (905)",
911 "UNKNOWN (906)",
912 "UNKNOWN (907)",
913 "UNKNOWN (908)",
914 "UNKNOWN (909)",
915 "UNKNOWN (910)",
916 "WM_PENWINLAST",
917 "UNKNOWN (912)",
918 "UNKNOWN (913)",
919 "UNKNOWN (914)",
920 "UNKNOWN (915)",
921 "UNKNOWN (916)",
922 "UNKNOWN (917)",
923 "UNKNOWN (918)",
924 "UNKNOWN (919)",
925 "UNKNOWN (920)",
926 "UNKNOWN (921)",
927 "UNKNOWN (922)",
928 "UNKNOWN (923)",
929 "UNKNOWN (924)",
930 "UNKNOWN (925)",
931 "UNKNOWN (926)",
932 "UNKNOWN (927)",
933 "UNKNOWN (928)",
934 "UNKNOWN (929)",
935 "UNKNOWN (930)",
936 "UNKNOWN (931)",
937 "UNKNOWN (932)",
938 "UNKNOWN (933)",
939 "UNKNOWN (934)",
940 "UNKNOWN (935)",
941 "UNKNOWN (936)",
942 "UNKNOWN (937)",
943 "UNKNOWN (938)",
944 "UNKNOWN (939)",
945 "UNKNOWN (940)",
946 "UNKNOWN (941)",
947 "UNKNOWN (942)",
948 "UNKNOWN (943)",
949 "UNKNOWN (944)",
950 "UNKNOWN (945)",
951 "UNKNOWN (946)",
952 "UNKNOWN (947)",
953 "UNKNOWN (948)",
954 "UNKNOWN (949)",
955 "UNKNOWN (950)",
956 "UNKNOWN (951)",
957 "UNKNOWN (952)",
958 "UNKNOWN (953)",
959 "UNKNOWN (954)",
960 "UNKNOWN (955)",
961 "UNKNOWN (956)",
962 "UNKNOWN (957)",
963 "UNKNOWN (958)",
964 "UNKNOWN (959)",
965 "UNKNOWN (960)",
966 "UNKNOWN (961)",
967 "UNKNOWN (962)",
968 "UNKNOWN (963)",
969 "UNKNOWN (964)",
970 "UNKNOWN (965)",
971 "UNKNOWN (966)",
972 "UNKNOWN (967)",
973 "UNKNOWN (968)",
974 "UNKNOWN (969)",
975 "UNKNOWN (970)",
976 "UNKNOWN (971)",
977 "UNKNOWN (972)",
978 "UNKNOWN (973)",
979 "UNKNOWN (974)",
980 "UNKNOWN (975)",
981 "UNKNOWN (976)",
982 "UNKNOWN (977)",
983 "UNKNOWN (978)",
984 "UNKNOWN (979)",
985 "UNKNOWN (980)",
986 "UNKNOWN (981)",
987 "UNKNOWN (982)",
988 "UNKNOWN (983)",
989 "UNKNOWN (984)",
990 "UNKNOWN (985)",
991 "UNKNOWN (986)",
992 "UNKNOWN (987)",
993 "UNKNOWN (988)",
994 "UNKNOWN (989)",
995 "UNKNOWN (990)",
996 "UNKNOWN (991)",
997 "UNKNOWN (992)",
998 "UNKNOWN (993)",
999 "UNKNOWN (994)",
1000 "UNKNOWN (995)",
1001 "UNKNOWN (996)",
1002 "UNKNOWN (997)",
1003 "UNKNOWN (998)",
1004 "UNKNOWN (999)",
1005 "UNKNOWN (1000)",
1006 "UNKNOWN (1001)",
1007 "UNKNOWN (1002)",
1008 "UNKNOWN (1003)",
1009 "UNKNOWN (1004)",
1010 "UNKNOWN (1005)",
1011 "UNKNOWN (1006)",
1012 "UNKNOWN (1007)",
1013 "UNKNOWN (1008)",
1014 "UNKNOWN (1009)",
1015 "UNKNOWN (1010)",
1016 "UNKNOWN (1011)",
1017 "UNKNOWN (1012)",
1018 "UNKNOWN (1013)",
1019 "UNKNOWN (1014)",
1020 "UNKNOWN (1015)",
1021 "UNKNOWN (1016)",
1022 "UNKNOWN (1017)",
1023 "UNKNOWN (1018)",
1024 "UNKNOWN (1019)",
1025 "UNKNOWN (1020)",
1026 "UNKNOWN (1021)",
1027 "UNKNOWN (1022)",
1028 "UNKNOWN (1023)",
1029 "WM_USER"
1030};
diff --git a/apps/plugins/sdl/src/video/windib/SDL_dibevents.c b/apps/plugins/sdl/src/video/windib/SDL_dibevents.c
deleted file mode 100644
index 6cee54ad2c..0000000000
--- a/apps/plugins/sdl/src/video/windib/SDL_dibevents.c
+++ /dev/null
@@ -1,704 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#define WIN32_LEAN_AND_MEAN
25#include <windows.h>
26
27#include "SDL_main.h"
28#include "SDL_events.h"
29#include "SDL_syswm.h"
30#include "../../events/SDL_sysevents.h"
31#include "../../events/SDL_events_c.h"
32#include "../wincommon/SDL_lowvideo.h"
33#include "SDL_gapidibvideo.h"
34#include "SDL_vkeys.h"
35
36#ifdef SDL_VIDEO_DRIVER_GAPI
37#include "../gapi/SDL_gapivideo.h"
38#endif
39
40#ifdef SDL_VIDEO_DRIVER_WINDIB
41#include "SDL_dibvideo.h"
42#endif
43
44#ifndef WM_APP
45#define WM_APP 0x8000
46#endif
47
48#ifdef _WIN32_WCE
49#define NO_GETKEYBOARDSTATE
50#endif
51
52/* The translation table from a Microsoft VK keysym to a SDL keysym */
53static SDLKey VK_keymap[SDLK_LAST];
54static SDL_keysym *TranslateKey(WPARAM vkey, UINT scancode, SDL_keysym *keysym, int pressed);
55static SDLKey Arrows_keymap[4];
56
57/* Masks for processing the windows KEYDOWN and KEYUP messages */
58#define REPEATED_KEYMASK (1<<30)
59#define EXTENDED_KEYMASK (1<<24)
60
61/* DJM: If the user setup the window for us, we want to save his window proc,
62 and give him a chance to handle some messages. */
63#ifdef STRICT
64#define WNDPROCTYPE WNDPROC
65#else
66#define WNDPROCTYPE FARPROC
67#endif
68static WNDPROCTYPE userWindowProc = NULL;
69
70
71#ifdef SDL_VIDEO_DRIVER_GAPI
72
73WPARAM rotateKey(WPARAM key,int direction)
74{
75 if(direction ==0 ) return key;
76
77 switch (key) {
78 case 0x26: /* up */
79 return Arrows_keymap[(2 + direction) % 4];
80 case 0x27: /* right */
81 return Arrows_keymap[(1 + direction) % 4];
82 case 0x28: /* down */
83 return Arrows_keymap[direction % 4];
84 case 0x25: /* left */
85 return Arrows_keymap[(3 + direction) % 4];
86 }
87
88 return key;
89}
90
91static void GapiTransform(GapiInfo *gapiInfo, LONG *x, LONG *y)
92{
93 if(gapiInfo->hiresFix)
94 {
95 *x *= 2;
96 *y *= 2;
97 }
98
99 // 0 3 0
100 if((!gapiInfo->userOrientation && gapiInfo->systemOrientation && !gapiInfo->gapiOrientation) ||
101 // 3 0 3
102 (gapiInfo->userOrientation && !gapiInfo->systemOrientation && gapiInfo->gapiOrientation) ||
103 // 3 0 0
104 (gapiInfo->userOrientation && !gapiInfo->systemOrientation && !gapiInfo->gapiOrientation))
105 {
106 Sint16 temp = *x;
107 *x = SDL_VideoSurface->w - *y;
108 *y = temp;
109 }
110 else
111 // 0 0 0
112 if((!gapiInfo->userOrientation && !gapiInfo->systemOrientation && !gapiInfo->gapiOrientation) ||
113 // 0 0 3
114 (!gapiInfo->userOrientation && !gapiInfo->systemOrientation && gapiInfo->gapiOrientation))
115 {
116 // without changes
117 // *x = *x;
118 // *y = *y;
119 }
120 // default
121 else
122 {
123 // without changes
124 // *x = *x;
125 // *y = *y;
126 }
127}
128#endif
129
130
131/* The main Win32 event handler */
132LRESULT DIB_HandleMessage(_THIS, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
133{
134 extern int posted;
135
136 switch (msg) {
137 case WM_SYSKEYDOWN:
138 case WM_KEYDOWN: {
139 SDL_keysym keysym;
140
141#ifdef SDL_VIDEO_DRIVER_GAPI
142 if(this->hidden->gapiInfo)
143 {
144 // Drop GAPI artefacts
145 if (wParam == 0x84 || wParam == 0x5B)
146 return 0;
147
148 wParam = rotateKey(wParam, this->hidden->gapiInfo->coordinateTransform);
149 }
150#endif
151 /* Ignore repeated keys */
152 if ( lParam&REPEATED_KEYMASK ) {
153 return(0);
154 }
155 switch (wParam) {
156 case VK_CONTROL:
157 if ( lParam&EXTENDED_KEYMASK )
158 wParam = VK_RCONTROL;
159 else
160 wParam = VK_LCONTROL;
161 break;
162 case VK_SHIFT:
163 /* EXTENDED trick doesn't work here */
164 {
165 Uint8 *state = SDL_GetKeyState(NULL);
166 if (state[SDLK_LSHIFT] == SDL_RELEASED && (GetKeyState(VK_LSHIFT) & 0x8000)) {
167 wParam = VK_LSHIFT;
168 } else if (state[SDLK_RSHIFT] == SDL_RELEASED && (GetKeyState(VK_RSHIFT) & 0x8000)) {
169 wParam = VK_RSHIFT;
170 } else {
171 /* Win9x */
172 int sc = HIWORD(lParam) & 0xFF;
173
174 if (sc == 0x2A)
175 wParam = VK_LSHIFT;
176 else
177 if (sc == 0x36)
178 wParam = VK_RSHIFT;
179 else
180 wParam = VK_LSHIFT;
181 }
182 }
183 break;
184 case VK_MENU:
185 if ( lParam&EXTENDED_KEYMASK )
186 wParam = VK_RMENU;
187 else
188 wParam = VK_LMENU;
189 break;
190 }
191#ifdef NO_GETKEYBOARDSTATE
192 /* this is the workaround for the missing ToAscii() and ToUnicode() in CE (not necessary at KEYUP!) */
193 if ( SDL_TranslateUNICODE ) {
194 MSG m;
195
196 m.hwnd = hwnd;
197 m.message = msg;
198 m.wParam = wParam;
199 m.lParam = lParam;
200 m.time = 0;
201 if ( TranslateMessage(&m) && PeekMessage(&m, hwnd, 0, WM_USER, PM_NOREMOVE) && (m.message == WM_CHAR) ) {
202 GetMessage(&m, hwnd, 0, WM_USER);
203 wParam = m.wParam;
204 }
205 }
206#endif /* NO_GETKEYBOARDSTATE */
207 posted = SDL_PrivateKeyboard(SDL_PRESSED,
208 TranslateKey(wParam,HIWORD(lParam),&keysym,1));
209 }
210 return(0);
211
212 case WM_SYSKEYUP:
213 case WM_KEYUP: {
214 SDL_keysym keysym;
215
216#ifdef SDL_VIDEO_DRIVER_GAPI
217 if(this->hidden->gapiInfo)
218 {
219 // Drop GAPI artifacts
220 if (wParam == 0x84 || wParam == 0x5B)
221 return 0;
222
223 wParam = rotateKey(wParam, this->hidden->gapiInfo->coordinateTransform);
224 }
225#endif
226
227 switch (wParam) {
228 case VK_CONTROL:
229 if ( lParam&EXTENDED_KEYMASK )
230 wParam = VK_RCONTROL;
231 else
232 wParam = VK_LCONTROL;
233 break;
234 case VK_SHIFT:
235 /* EXTENDED trick doesn't work here */
236 {
237 Uint8 *state = SDL_GetKeyState(NULL);
238 if (state[SDLK_LSHIFT] == SDL_PRESSED && !(GetKeyState(VK_LSHIFT) & 0x8000)) {
239 wParam = VK_LSHIFT;
240 } else if (state[SDLK_RSHIFT] == SDL_PRESSED && !(GetKeyState(VK_RSHIFT) & 0x8000)) {
241 wParam = VK_RSHIFT;
242 } else {
243 /* Win9x */
244 int sc = HIWORD(lParam) & 0xFF;
245
246 if (sc == 0x2A)
247 wParam = VK_LSHIFT;
248 else
249 if (sc == 0x36)
250 wParam = VK_RSHIFT;
251 else
252 wParam = VK_LSHIFT;
253 }
254 }
255 break;
256 case VK_MENU:
257 if ( lParam&EXTENDED_KEYMASK )
258 wParam = VK_RMENU;
259 else
260 wParam = VK_LMENU;
261 break;
262 }
263 /* Windows only reports keyup for print screen */
264 if ( wParam == VK_SNAPSHOT && SDL_GetKeyState(NULL)[SDLK_PRINT] == SDL_RELEASED ) {
265 posted = SDL_PrivateKeyboard(SDL_PRESSED,
266 TranslateKey(wParam,HIWORD(lParam),&keysym,1));
267 }
268 posted = SDL_PrivateKeyboard(SDL_RELEASED,
269 TranslateKey(wParam,HIWORD(lParam),&keysym,0));
270 }
271 return(0);
272#if defined(SC_SCREENSAVE) && defined(SC_MONITORPOWER)
273 case WM_SYSCOMMAND: {
274 const DWORD val = (DWORD) (wParam & 0xFFF0);
275 if ((val == SC_SCREENSAVE) || (val == SC_MONITORPOWER)) {
276 if (this->hidden->dibInfo && !allow_screensaver) {
277 /* Note that this doesn't stop anything on Vista
278 if the screensaver has a password. */
279 return(0);
280 }
281 }
282 }
283 /* Fall through to default processing */
284#endif /* SC_SCREENSAVE && SC_MONITORPOWER */
285
286 default: {
287 /* Only post the event if we're watching for it */
288 if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) {
289 SDL_SysWMmsg wmmsg;
290
291 SDL_VERSION(&wmmsg.version);
292 wmmsg.hwnd = hwnd;
293 wmmsg.msg = msg;
294 wmmsg.wParam = wParam;
295 wmmsg.lParam = lParam;
296 posted = SDL_PrivateSysWMEvent(&wmmsg);
297
298 /* DJM: If the user isn't watching for private
299 messages in her SDL event loop, then pass it
300 along to any win32 specific window proc.
301 */
302 } else if (userWindowProc) {
303 return CallWindowProc(userWindowProc, hwnd, msg, wParam, lParam);
304 }
305 }
306 break;
307 }
308 return(DefWindowProc(hwnd, msg, wParam, lParam));
309}
310
311#ifdef _WIN32_WCE
312static BOOL GetLastStylusPos(POINT* ptLast)
313{
314 BOOL bResult = FALSE;
315 UINT nRet;
316 GetMouseMovePoints(ptLast, 1, &nRet);
317 if ( nRet == 1 ) {
318 ptLast->x /= 4;
319 ptLast->y /= 4;
320 bResult = TRUE;
321 }
322 return bResult;
323}
324#endif
325
326static void DIB_GenerateMouseMotionEvent(_THIS)
327{
328 extern int mouse_relative;
329 extern int posted;
330
331 POINT mouse;
332#ifdef _WIN32_WCE
333 if ( !GetCursorPos(&mouse) && !GetLastStylusPos(&mouse) ) return;
334#else
335 if ( !GetCursorPos(&mouse) ) return;
336#endif
337
338 if ( mouse_relative ) {
339 POINT center;
340 center.x = (SDL_VideoSurface->w/2);
341 center.y = (SDL_VideoSurface->h/2);
342 ClientToScreen(SDL_Window, &center);
343
344 mouse.x -= center.x;
345 mouse.y -= center.y;
346 if ( mouse.x || mouse.y ) {
347 SetCursorPos(center.x, center.y);
348 posted = SDL_PrivateMouseMotion(0, 1, (Sint16)mouse.x, (Sint16)mouse.y);
349 }
350 } else {
351 ScreenToClient(SDL_Window, &mouse);
352#ifdef SDL_VIDEO_DRIVER_GAPI
353 if (SDL_VideoSurface && this->hidden->gapiInfo)
354 GapiTransform(this->hidden->gapiInfo, &mouse.x, &mouse.y);
355#endif
356 posted = SDL_PrivateMouseMotion(0, 0, (Sint16)mouse.x, (Sint16)mouse.y);
357 }
358}
359
360void DIB_PumpEvents(_THIS)
361{
362 MSG msg;
363
364 while ( PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) ) {
365 if ( GetMessage(&msg, NULL, 0, 0) > 0 ) {
366 DispatchMessage(&msg);
367 }
368 }
369
370 if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) {
371 DIB_GenerateMouseMotionEvent( this );
372 }
373}
374
375static HKL hLayoutUS = NULL;
376
377void DIB_InitOSKeymap(_THIS)
378{
379 int i;
380#ifndef _WIN32_WCE
381 char current_layout[KL_NAMELENGTH];
382
383 GetKeyboardLayoutName(current_layout);
384 //printf("Initial Keyboard Layout Name: '%s'\n", current_layout);
385
386 hLayoutUS = LoadKeyboardLayout("00000409", KLF_NOTELLSHELL);
387
388 if (!hLayoutUS) {
389 //printf("Failed to load US keyboard layout. Using current.\n");
390 hLayoutUS = GetKeyboardLayout(0);
391 }
392 LoadKeyboardLayout(current_layout, KLF_ACTIVATE);
393#else
394#if _WIN32_WCE >=420
395 TCHAR current_layout[KL_NAMELENGTH];
396
397 GetKeyboardLayoutName(current_layout);
398 //printf("Initial Keyboard Layout Name: '%s'\n", current_layout);
399
400 hLayoutUS = LoadKeyboardLayout(L"00000409", 0);
401
402 if (!hLayoutUS) {
403 //printf("Failed to load US keyboard layout. Using current.\n");
404 hLayoutUS = GetKeyboardLayout(0);
405 }
406 LoadKeyboardLayout(current_layout, 0);
407#endif // _WIN32_WCE >=420
408#endif
409 /* Map the VK keysyms */
410 for ( i=0; i<SDL_arraysize(VK_keymap); ++i )
411 VK_keymap[i] = SDLK_UNKNOWN;
412
413 VK_keymap[VK_BACK] = SDLK_BACKSPACE;
414 VK_keymap[VK_TAB] = SDLK_TAB;
415 VK_keymap[VK_CLEAR] = SDLK_CLEAR;
416 VK_keymap[VK_RETURN] = SDLK_RETURN;
417 VK_keymap[VK_PAUSE] = SDLK_PAUSE;
418 VK_keymap[VK_ESCAPE] = SDLK_ESCAPE;
419 VK_keymap[VK_SPACE] = SDLK_SPACE;
420 VK_keymap[VK_APOSTROPHE] = SDLK_QUOTE;
421 VK_keymap[VK_COMMA] = SDLK_COMMA;
422 VK_keymap[VK_MINUS] = SDLK_MINUS;
423 VK_keymap[VK_PERIOD] = SDLK_PERIOD;
424 VK_keymap[VK_SLASH] = SDLK_SLASH;
425 VK_keymap[VK_0] = SDLK_0;
426 VK_keymap[VK_1] = SDLK_1;
427 VK_keymap[VK_2] = SDLK_2;
428 VK_keymap[VK_3] = SDLK_3;
429 VK_keymap[VK_4] = SDLK_4;
430 VK_keymap[VK_5] = SDLK_5;
431 VK_keymap[VK_6] = SDLK_6;
432 VK_keymap[VK_7] = SDLK_7;
433 VK_keymap[VK_8] = SDLK_8;
434 VK_keymap[VK_9] = SDLK_9;
435 VK_keymap[VK_SEMICOLON] = SDLK_SEMICOLON;
436 VK_keymap[VK_EQUALS] = SDLK_EQUALS;
437 VK_keymap[VK_LBRACKET] = SDLK_LEFTBRACKET;
438 VK_keymap[VK_BACKSLASH] = SDLK_BACKSLASH;
439 VK_keymap[VK_OEM_102] = SDLK_LESS;
440 VK_keymap[VK_RBRACKET] = SDLK_RIGHTBRACKET;
441 VK_keymap[VK_GRAVE] = SDLK_BACKQUOTE;
442 VK_keymap[VK_BACKTICK] = SDLK_BACKQUOTE;
443 VK_keymap[VK_A] = SDLK_a;
444 VK_keymap[VK_B] = SDLK_b;
445 VK_keymap[VK_C] = SDLK_c;
446 VK_keymap[VK_D] = SDLK_d;
447 VK_keymap[VK_E] = SDLK_e;
448 VK_keymap[VK_F] = SDLK_f;
449 VK_keymap[VK_G] = SDLK_g;
450 VK_keymap[VK_H] = SDLK_h;
451 VK_keymap[VK_I] = SDLK_i;
452 VK_keymap[VK_J] = SDLK_j;
453 VK_keymap[VK_K] = SDLK_k;
454 VK_keymap[VK_L] = SDLK_l;
455 VK_keymap[VK_M] = SDLK_m;
456 VK_keymap[VK_N] = SDLK_n;
457 VK_keymap[VK_O] = SDLK_o;
458 VK_keymap[VK_P] = SDLK_p;
459 VK_keymap[VK_Q] = SDLK_q;
460 VK_keymap[VK_R] = SDLK_r;
461 VK_keymap[VK_S] = SDLK_s;
462 VK_keymap[VK_T] = SDLK_t;
463 VK_keymap[VK_U] = SDLK_u;
464 VK_keymap[VK_V] = SDLK_v;
465 VK_keymap[VK_W] = SDLK_w;
466 VK_keymap[VK_X] = SDLK_x;
467 VK_keymap[VK_Y] = SDLK_y;
468 VK_keymap[VK_Z] = SDLK_z;
469 VK_keymap[VK_DELETE] = SDLK_DELETE;
470
471 VK_keymap[VK_NUMPAD0] = SDLK_KP0;
472 VK_keymap[VK_NUMPAD1] = SDLK_KP1;
473 VK_keymap[VK_NUMPAD2] = SDLK_KP2;
474 VK_keymap[VK_NUMPAD3] = SDLK_KP3;
475 VK_keymap[VK_NUMPAD4] = SDLK_KP4;
476 VK_keymap[VK_NUMPAD5] = SDLK_KP5;
477 VK_keymap[VK_NUMPAD6] = SDLK_KP6;
478 VK_keymap[VK_NUMPAD7] = SDLK_KP7;
479 VK_keymap[VK_NUMPAD8] = SDLK_KP8;
480 VK_keymap[VK_NUMPAD9] = SDLK_KP9;
481 VK_keymap[VK_DECIMAL] = SDLK_KP_PERIOD;
482 VK_keymap[VK_DIVIDE] = SDLK_KP_DIVIDE;
483 VK_keymap[VK_MULTIPLY] = SDLK_KP_MULTIPLY;
484 VK_keymap[VK_SUBTRACT] = SDLK_KP_MINUS;
485 VK_keymap[VK_ADD] = SDLK_KP_PLUS;
486
487 VK_keymap[VK_UP] = SDLK_UP;
488 VK_keymap[VK_DOWN] = SDLK_DOWN;
489 VK_keymap[VK_RIGHT] = SDLK_RIGHT;
490 VK_keymap[VK_LEFT] = SDLK_LEFT;
491 VK_keymap[VK_INSERT] = SDLK_INSERT;
492 VK_keymap[VK_HOME] = SDLK_HOME;
493 VK_keymap[VK_END] = SDLK_END;
494 VK_keymap[VK_PRIOR] = SDLK_PAGEUP;
495 VK_keymap[VK_NEXT] = SDLK_PAGEDOWN;
496
497 VK_keymap[VK_F1] = SDLK_F1;
498 VK_keymap[VK_F2] = SDLK_F2;
499 VK_keymap[VK_F3] = SDLK_F3;
500 VK_keymap[VK_F4] = SDLK_F4;
501 VK_keymap[VK_F5] = SDLK_F5;
502 VK_keymap[VK_F6] = SDLK_F6;
503 VK_keymap[VK_F7] = SDLK_F7;
504 VK_keymap[VK_F8] = SDLK_F8;
505 VK_keymap[VK_F9] = SDLK_F9;
506 VK_keymap[VK_F10] = SDLK_F10;
507 VK_keymap[VK_F11] = SDLK_F11;
508 VK_keymap[VK_F12] = SDLK_F12;
509 VK_keymap[VK_F13] = SDLK_F13;
510 VK_keymap[VK_F14] = SDLK_F14;
511 VK_keymap[VK_F15] = SDLK_F15;
512
513 VK_keymap[VK_NUMLOCK] = SDLK_NUMLOCK;
514 VK_keymap[VK_CAPITAL] = SDLK_CAPSLOCK;
515 VK_keymap[VK_SCROLL] = SDLK_SCROLLOCK;
516 VK_keymap[VK_RSHIFT] = SDLK_RSHIFT;
517 VK_keymap[VK_LSHIFT] = SDLK_LSHIFT;
518 VK_keymap[VK_RCONTROL] = SDLK_RCTRL;
519 VK_keymap[VK_LCONTROL] = SDLK_LCTRL;
520 VK_keymap[VK_RMENU] = SDLK_RALT;
521 VK_keymap[VK_LMENU] = SDLK_LALT;
522 VK_keymap[VK_RWIN] = SDLK_RSUPER;
523 VK_keymap[VK_LWIN] = SDLK_LSUPER;
524
525 VK_keymap[VK_HELP] = SDLK_HELP;
526#ifdef VK_PRINT
527 VK_keymap[VK_PRINT] = SDLK_PRINT;
528#endif
529 VK_keymap[VK_SNAPSHOT] = SDLK_PRINT;
530 VK_keymap[VK_CANCEL] = SDLK_BREAK;
531 VK_keymap[VK_APPS] = SDLK_MENU;
532
533 Arrows_keymap[3] = 0x25;
534 Arrows_keymap[2] = 0x26;
535 Arrows_keymap[1] = 0x27;
536 Arrows_keymap[0] = 0x28;
537}
538
539#define EXTKEYPAD(keypad) ((scancode & 0x100)?(mvke):(keypad))
540
541static int SDL_MapVirtualKey(int scancode, int vkey)
542{
543#ifndef _WIN32_WCE
544 int mvke = MapVirtualKeyEx(scancode & 0xFF, 1, hLayoutUS);
545#else
546 int mvke = MapVirtualKey(scancode & 0xFF, 1);
547#endif
548
549 switch(vkey) {
550 /* These are always correct */
551 case VK_DIVIDE:
552 case VK_MULTIPLY:
553 case VK_SUBTRACT:
554 case VK_ADD:
555 case VK_LWIN:
556 case VK_RWIN:
557 case VK_APPS:
558 /* These are already handled */
559 case VK_LCONTROL:
560 case VK_RCONTROL:
561 case VK_LSHIFT:
562 case VK_RSHIFT:
563 case VK_LMENU:
564 case VK_RMENU:
565 case VK_SNAPSHOT:
566 case VK_PAUSE:
567 return vkey;
568 }
569 switch(mvke) {
570 /* Distinguish between keypad and extended keys */
571 case VK_INSERT: return EXTKEYPAD(VK_NUMPAD0);
572 case VK_DELETE: return EXTKEYPAD(VK_DECIMAL);
573 case VK_END: return EXTKEYPAD(VK_NUMPAD1);
574 case VK_DOWN: return EXTKEYPAD(VK_NUMPAD2);
575 case VK_NEXT: return EXTKEYPAD(VK_NUMPAD3);
576 case VK_LEFT: return EXTKEYPAD(VK_NUMPAD4);
577 case VK_CLEAR: return EXTKEYPAD(VK_NUMPAD5);
578 case VK_RIGHT: return EXTKEYPAD(VK_NUMPAD6);
579 case VK_HOME: return EXTKEYPAD(VK_NUMPAD7);
580 case VK_UP: return EXTKEYPAD(VK_NUMPAD8);
581 case VK_PRIOR: return EXTKEYPAD(VK_NUMPAD9);
582 }
583 return mvke?mvke:vkey;
584}
585
586static SDL_keysym *TranslateKey(WPARAM vkey, UINT scancode, SDL_keysym *keysym, int pressed)
587{
588 /* Set the keysym information */
589 keysym->scancode = (unsigned char) scancode;
590 keysym->mod = KMOD_NONE;
591 keysym->unicode = 0;
592
593 if ((vkey == VK_RETURN) && (scancode & 0x100)) {
594 /* No VK_ code for the keypad enter key */
595 keysym->sym = SDLK_KP_ENTER;
596 }
597 else {
598 keysym->sym = VK_keymap[SDL_MapVirtualKey(scancode, vkey)];
599 }
600
601 if ( pressed && SDL_TranslateUNICODE ) {
602#ifdef NO_GETKEYBOARDSTATE
603 /* Uh oh, better hope the vkey is close enough.. */
604 if((keysym->sym == vkey) || (vkey > 0x7f))
605 keysym->unicode = vkey;
606#else
607 BYTE keystate[256];
608 Uint16 wchars[2];
609
610 GetKeyboardState(keystate);
611 /* Numlock isn't taken into account in ToUnicode,
612 * so we handle it as a special case here */
613 if ((keystate[VK_NUMLOCK] & 1) && vkey >= VK_NUMPAD0 && vkey <= VK_NUMPAD9)
614 {
615 keysym->unicode = vkey - VK_NUMPAD0 + '0';
616 }
617 else if (SDL_ToUnicode((UINT)vkey, scancode, keystate, wchars, sizeof(wchars)/sizeof(wchars[0]), 0) > 0)
618 {
619 keysym->unicode = wchars[0];
620 }
621#endif /* NO_GETKEYBOARDSTATE */
622 }
623
624#if 0
625 {
626 HKL hLayoutCurrent = GetKeyboardLayout(0);
627 int sc = scancode & 0xFF;
628
629 printf("SYM:%d, VK:0x%02X, SC:0x%04X, US:(1:0x%02X, 3:0x%02X), "
630 "Current:(1:0x%02X, 3:0x%02X)\n",
631 keysym->sym, vkey, scancode,
632 MapVirtualKeyEx(sc, 1, hLayoutUS),
633 MapVirtualKeyEx(sc, 3, hLayoutUS),
634 MapVirtualKeyEx(sc, 1, hLayoutCurrent),
635 MapVirtualKeyEx(sc, 3, hLayoutCurrent)
636 );
637 }
638#endif
639 return(keysym);
640}
641
642int DIB_CreateWindow(_THIS)
643{
644 char *windowid;
645
646 SDL_RegisterApp(NULL, 0, 0);
647
648 windowid = SDL_getenv("SDL_WINDOWID");
649 SDL_windowid = (windowid != NULL);
650 if ( SDL_windowid ) {
651#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
652 /* wince 2.1 does not have strtol */
653 wchar_t *windowid_t = SDL_malloc((SDL_strlen(windowid) + 1) * sizeof(wchar_t));
654 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, windowid, -1, windowid_t, SDL_strlen(windowid) + 1);
655 SDL_Window = (HWND)wcstol(windowid_t, NULL, 0);
656 SDL_free(windowid_t);
657#else
658 SDL_Window = (HWND)((size_t)SDL_strtoull(windowid, NULL, 0));
659#endif
660 if ( SDL_Window == NULL ) {
661 SDL_SetError("Couldn't get user specified window");
662 return(-1);
663 }
664
665 /* DJM: we want all event's for the user specified
666 window to be handled by SDL.
667 */
668 userWindowProc = (WNDPROCTYPE)GetWindowLongPtr(SDL_Window, GWLP_WNDPROC);
669 SetWindowLongPtr(SDL_Window, GWLP_WNDPROC, (LONG_PTR)WinMessage);
670 } else {
671 SDL_Window = CreateWindow(SDL_Appname, SDL_Appname,
672 (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX),
673 CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, NULL, NULL, SDL_Instance, NULL);
674 if ( SDL_Window == NULL ) {
675 SDL_SetError("Couldn't create window");
676 return(-1);
677 }
678 ShowWindow(SDL_Window, SW_HIDE);
679 }
680
681 /* JC 14 Mar 2006
682 Flush the message loop or this can cause big problems later
683 Especially if the user decides to use dialog boxes or assert()!
684 */
685 WIN_FlushMessageQueue();
686
687 return(0);
688}
689
690void DIB_DestroyWindow(_THIS)
691{
692 if ( SDL_windowid ) {
693 SetWindowLongPtr(SDL_Window, GWLP_WNDPROC, (LONG_PTR)userWindowProc);
694 } else {
695 DestroyWindow(SDL_Window);
696 }
697 SDL_UnregisterApp();
698
699 /* JC 14 Mar 2006
700 Flush the message loop or this can cause big problems later
701 Especially if the user decides to use dialog boxes or assert()!
702 */
703 WIN_FlushMessageQueue();
704}
diff --git a/apps/plugins/sdl/src/video/windib/SDL_dibevents_c.h b/apps/plugins/sdl/src/video/windib/SDL_dibevents_c.h
deleted file mode 100644
index 236aa68ee9..0000000000
--- a/apps/plugins/sdl/src/video/windib/SDL_dibevents_c.h
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "../wincommon/SDL_lowvideo.h"
25
26/* Variables and functions exported by SDL_dibevents.c to other parts
27 of the native video subsystem (SDL_dibvideo.c)
28*/
29extern LONG
30 DIB_HandleMessage(_THIS, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
31extern int DIB_CreateWindow(_THIS);
32extern void DIB_DestroyWindow(_THIS);
33
34extern void DIB_PumpEvents(_THIS);
35extern void DIB_InitOSKeymap(_THIS);
diff --git a/apps/plugins/sdl/src/video/windib/SDL_dibvideo.c b/apps/plugins/sdl/src/video/windib/SDL_dibvideo.c
deleted file mode 100644
index 6187bfcf7e..0000000000
--- a/apps/plugins/sdl/src/video/windib/SDL_dibvideo.c
+++ /dev/null
@@ -1,1323 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#define WIN32_LEAN_AND_MEAN
25#include <windows.h>
26
27/* Not yet in the mingw32 cross-compile headers */
28#ifndef CDS_FULLSCREEN
29#define CDS_FULLSCREEN 4
30#endif
31
32#include "SDL_syswm.h"
33#include "../SDL_sysvideo.h"
34#include "../SDL_pixels_c.h"
35#include "../../events/SDL_sysevents.h"
36#include "../../events/SDL_events_c.h"
37#include "SDL_gapidibvideo.h"
38#include "SDL_dibvideo.h"
39#include "../wincommon/SDL_syswm_c.h"
40#include "../wincommon/SDL_sysmouse_c.h"
41#include "SDL_dibevents_c.h"
42#include "../wincommon/SDL_wingl_c.h"
43
44#ifdef _WIN32_WCE
45
46#ifndef DM_DISPLAYORIENTATION
47#define DM_DISPLAYORIENTATION 0x00800000L
48#endif
49#ifndef DM_DISPLAYQUERYORIENTATION
50#define DM_DISPLAYQUERYORIENTATION 0x01000000L
51#endif
52#ifndef DMDO_0
53#define DMDO_0 0
54#endif
55#ifndef DMDO_90
56#define DMDO_90 1
57#endif
58#ifndef DMDO_180
59#define DMDO_180 2
60#endif
61#ifndef DMDO_270
62#define DMDO_270 4
63#endif
64
65#define NO_GETDIBITS
66#define NO_GAMMA_SUPPORT
67 #if _WIN32_WCE < 420
68 #define NO_CHANGEDISPLAYSETTINGS
69 #else
70 #define ChangeDisplaySettings(lpDevMode, dwFlags) ChangeDisplaySettingsEx(NULL, (lpDevMode), 0, (dwFlags), 0)
71 #endif
72#endif
73#ifndef WS_MAXIMIZE
74#define WS_MAXIMIZE 0
75#endif
76#ifndef WS_THICKFRAME
77#define WS_THICKFRAME 0
78#endif
79#ifndef SWP_NOCOPYBITS
80#define SWP_NOCOPYBITS 0
81#endif
82#ifndef PC_NOCOLLAPSE
83#define PC_NOCOLLAPSE 0
84#endif
85
86#ifdef _WIN32_WCE
87// defined and used in SDL_sysevents.c
88extern HINSTANCE aygshell;
89#endif
90
91/* Initialization/Query functions */
92static int DIB_VideoInit(_THIS, SDL_PixelFormat *vformat);
93static SDL_Rect **DIB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
94SDL_Surface *DIB_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
95static int DIB_SetColors(_THIS, int firstcolor, int ncolors,
96 SDL_Color *colors);
97static void DIB_CheckGamma(_THIS);
98void DIB_SwapGamma(_THIS);
99void DIB_QuitGamma(_THIS);
100int DIB_SetGammaRamp(_THIS, Uint16 *ramp);
101int DIB_GetGammaRamp(_THIS, Uint16 *ramp);
102static void DIB_VideoQuit(_THIS);
103
104/* Hardware surface functions */
105static int DIB_AllocHWSurface(_THIS, SDL_Surface *surface);
106static int DIB_LockHWSurface(_THIS, SDL_Surface *surface);
107static void DIB_UnlockHWSurface(_THIS, SDL_Surface *surface);
108static void DIB_FreeHWSurface(_THIS, SDL_Surface *surface);
109
110/* Windows message handling functions */
111static void DIB_GrabStaticColors(HWND window);
112static void DIB_ReleaseStaticColors(HWND window);
113static void DIB_Activate(_THIS, BOOL active, BOOL minimized);
114static void DIB_RealizePalette(_THIS);
115static void DIB_PaletteChanged(_THIS, HWND window);
116static void DIB_WinPAINT(_THIS, HDC hdc);
117
118/* helper fn */
119static int DIB_SussScreenDepth();
120
121/* DIB driver bootstrap functions */
122
123static int DIB_Available(void)
124{
125 return(1);
126}
127
128static void DIB_DeleteDevice(SDL_VideoDevice *device)
129{
130 if ( device ) {
131 if ( device->hidden ) {
132 if ( device->hidden->dibInfo ) {
133 SDL_free( device->hidden->dibInfo );
134 }
135 SDL_free(device->hidden);
136 }
137 if ( device->gl_data ) {
138 SDL_free(device->gl_data);
139 }
140 SDL_free(device);
141 }
142}
143
144static SDL_VideoDevice *DIB_CreateDevice(int devindex)
145{
146 SDL_VideoDevice *device;
147
148 /* Initialize all variables that we clean on shutdown */
149 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
150 if ( device ) {
151 SDL_memset(device, 0, (sizeof *device));
152 device->hidden = (struct SDL_PrivateVideoData *)
153 SDL_malloc((sizeof *device->hidden));
154 if(device->hidden){
155 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
156 device->hidden->dibInfo = (DibInfo *)SDL_malloc((sizeof(DibInfo)));
157 if(device->hidden->dibInfo == NULL)
158 {
159 SDL_free(device->hidden);
160 device->hidden = NULL;
161 }
162 }
163
164 device->gl_data = (struct SDL_PrivateGLData *)
165 SDL_malloc((sizeof *device->gl_data));
166 }
167 if ( (device == NULL) || (device->hidden == NULL) ||
168 (device->gl_data == NULL) ) {
169 SDL_OutOfMemory();
170 DIB_DeleteDevice(device);
171 return(NULL);
172 }
173 SDL_memset(device->hidden->dibInfo, 0, (sizeof *device->hidden->dibInfo));
174 SDL_memset(device->gl_data, 0, (sizeof *device->gl_data));
175
176 /* Set the function pointers */
177 device->VideoInit = DIB_VideoInit;
178 device->ListModes = DIB_ListModes;
179 device->SetVideoMode = DIB_SetVideoMode;
180 device->UpdateMouse = WIN_UpdateMouse;
181 device->SetColors = DIB_SetColors;
182 device->UpdateRects = NULL;
183 device->VideoQuit = DIB_VideoQuit;
184 device->AllocHWSurface = DIB_AllocHWSurface;
185 device->CheckHWBlit = NULL;
186 device->FillHWRect = NULL;
187 device->SetHWColorKey = NULL;
188 device->SetHWAlpha = NULL;
189 device->LockHWSurface = DIB_LockHWSurface;
190 device->UnlockHWSurface = DIB_UnlockHWSurface;
191 device->FlipHWSurface = NULL;
192 device->FreeHWSurface = DIB_FreeHWSurface;
193 device->SetGammaRamp = DIB_SetGammaRamp;
194 device->GetGammaRamp = DIB_GetGammaRamp;
195#if SDL_VIDEO_OPENGL
196 device->GL_LoadLibrary = WIN_GL_LoadLibrary;
197 device->GL_GetProcAddress = WIN_GL_GetProcAddress;
198 device->GL_GetAttribute = WIN_GL_GetAttribute;
199 device->GL_MakeCurrent = WIN_GL_MakeCurrent;
200 device->GL_SwapBuffers = WIN_GL_SwapBuffers;
201#endif
202 device->SetCaption = WIN_SetWMCaption;
203 device->SetIcon = WIN_SetWMIcon;
204 device->IconifyWindow = WIN_IconifyWindow;
205 device->GrabInput = WIN_GrabInput;
206 device->GetWMInfo = WIN_GetWMInfo;
207 device->FreeWMCursor = WIN_FreeWMCursor;
208 device->CreateWMCursor = WIN_CreateWMCursor;
209 device->ShowWMCursor = WIN_ShowWMCursor;
210 device->WarpWMCursor = WIN_WarpWMCursor;
211 device->CheckMouseMode = WIN_CheckMouseMode;
212 device->InitOSKeymap = DIB_InitOSKeymap;
213 device->PumpEvents = DIB_PumpEvents;
214
215 /* Set up the windows message handling functions */
216 WIN_Activate = DIB_Activate;
217 WIN_RealizePalette = DIB_RealizePalette;
218 WIN_PaletteChanged = DIB_PaletteChanged;
219 WIN_WinPAINT = DIB_WinPAINT;
220 HandleMessage = DIB_HandleMessage;
221
222 device->free = DIB_DeleteDevice;
223
224 /* We're finally ready */
225 return device;
226}
227
228VideoBootStrap WINDIB_bootstrap = {
229 "windib", "Win95/98/NT/2000/CE GDI",
230 DIB_Available, DIB_CreateDevice
231};
232
233static int cmpmodes(const void *va, const void *vb)
234{
235 SDL_Rect *a = *(SDL_Rect **)va;
236 SDL_Rect *b = *(SDL_Rect **)vb;
237 if ( a->w == b->w )
238 return b->h - a->h;
239 else
240 return b->w - a->w;
241}
242
243static int DIB_AddMode(_THIS, int bpp, int w, int h)
244{
245 SDL_Rect *mode;
246 int i, index;
247 int next_mode;
248
249 /* Check to see if we already have this mode */
250 if ( bpp < 8 || bpp > 32 ) { /* Not supported */
251 return(0);
252 }
253 index = ((bpp+7)/8)-1;
254 for ( i=0; i<SDL_nummodes[index]; ++i ) {
255 mode = SDL_modelist[index][i];
256 if ( (mode->w == w) && (mode->h == h) ) {
257 return(0);
258 }
259 }
260
261 /* Set up the new video mode rectangle */
262 mode = (SDL_Rect *)SDL_malloc(sizeof *mode);
263 if ( mode == NULL ) {
264 SDL_OutOfMemory();
265 return(-1);
266 }
267 mode->x = 0;
268 mode->y = 0;
269 mode->w = w;
270 mode->h = h;
271
272 /* Allocate the new list of modes, and fill in the new mode */
273 next_mode = SDL_nummodes[index];
274 SDL_modelist[index] = (SDL_Rect **)
275 SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *));
276 if ( SDL_modelist[index] == NULL ) {
277 SDL_OutOfMemory();
278 SDL_nummodes[index] = 0;
279 SDL_free(mode);
280 return(-1);
281 }
282 SDL_modelist[index][next_mode] = mode;
283 SDL_modelist[index][next_mode+1] = NULL;
284 SDL_nummodes[index]++;
285
286 return(0);
287}
288
289static void DIB_CreatePalette(_THIS, int bpp)
290{
291/* RJR: March 28, 2000
292 moved palette creation here from "DIB_VideoInit" */
293
294 LOGPALETTE *palette;
295 HDC hdc;
296 int ncolors;
297
298 ncolors = (1 << bpp);
299 palette = (LOGPALETTE *)SDL_malloc(sizeof(*palette)+
300 ncolors*sizeof(PALETTEENTRY));
301 palette->palVersion = 0x300;
302 palette->palNumEntries = ncolors;
303 hdc = GetDC(SDL_Window);
304 GetSystemPaletteEntries(hdc, 0, ncolors, palette->palPalEntry);
305 ReleaseDC(SDL_Window, hdc);
306 screen_pal = CreatePalette(palette);
307 screen_logpal = palette;
308}
309
310int DIB_VideoInit(_THIS, SDL_PixelFormat *vformat)
311{
312 const char *env = NULL;
313#ifndef NO_CHANGEDISPLAYSETTINGS
314 int i;
315 DEVMODE settings;
316#endif
317
318 /* Create the window */
319 if ( DIB_CreateWindow(this) < 0 ) {
320 return(-1);
321 }
322
323#if !SDL_AUDIO_DISABLED
324 DX5_SoundFocus(SDL_Window);
325#endif
326
327 /* Determine the screen depth */
328 vformat->BitsPerPixel = DIB_SussScreenDepth();
329 switch (vformat->BitsPerPixel) {
330 case 15:
331 vformat->Rmask = 0x00007c00;
332 vformat->Gmask = 0x000003e0;
333 vformat->Bmask = 0x0000001f;
334 vformat->BitsPerPixel = 16;
335 break;
336 case 16:
337 vformat->Rmask = 0x0000f800;
338 vformat->Gmask = 0x000007e0;
339 vformat->Bmask = 0x0000001f;
340 break;
341 case 24:
342 case 32:
343 /* GDI defined as 8-8-8 */
344 vformat->Rmask = 0x00ff0000;
345 vformat->Gmask = 0x0000ff00;
346 vformat->Bmask = 0x000000ff;
347 break;
348 default:
349 break;
350 }
351
352 /* See if gamma is supported on this screen */
353 DIB_CheckGamma(this);
354
355#ifndef NO_CHANGEDISPLAYSETTINGS
356
357 settings.dmSize = sizeof(DEVMODE);
358 settings.dmDriverExtra = 0;
359#ifdef _WIN32_WCE
360 settings.dmFields = DM_DISPLAYQUERYORIENTATION;
361 this->hidden->supportRotation = ChangeDisplaySettingsEx(NULL, &settings, NULL, CDS_TEST, NULL) == DISP_CHANGE_SUCCESSFUL;
362#endif
363 /* Query for the desktop resolution */
364 SDL_desktop_mode.dmSize = sizeof(SDL_desktop_mode);
365 SDL_desktop_mode.dmDriverExtra = 0;
366 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &SDL_desktop_mode);
367 this->info.current_w = SDL_desktop_mode.dmPelsWidth;
368 this->info.current_h = SDL_desktop_mode.dmPelsHeight;
369
370 /* Query for the list of available video modes */
371 for ( i=0; EnumDisplaySettings(NULL, i, &settings); ++i ) {
372 DIB_AddMode(this, settings.dmBitsPerPel,
373 settings.dmPelsWidth, settings.dmPelsHeight);
374#ifdef _WIN32_WCE
375 if( this->hidden->supportRotation )
376 DIB_AddMode(this, settings.dmBitsPerPel,
377 settings.dmPelsHeight, settings.dmPelsWidth);
378#endif
379 }
380 /* Sort the mode lists */
381 for ( i=0; i<NUM_MODELISTS; ++i ) {
382 if ( SDL_nummodes[i] > 0 ) {
383 SDL_qsort(SDL_modelist[i], SDL_nummodes[i], sizeof *SDL_modelist[i], cmpmodes);
384 }
385 }
386#else
387 // WinCE and fullscreen mode:
388 // We use only vformat->BitsPerPixel that allow SDL to
389 // emulate other bpp (8, 32) and use triple buffer,
390 // because SDL surface conversion is much faster than the WinCE one.
391 // Although it should be tested on devices with graphics accelerator.
392
393 DIB_AddMode(this, vformat->BitsPerPixel,
394 GetDeviceCaps(GetDC(NULL), HORZRES),
395 GetDeviceCaps(GetDC(NULL), VERTRES));
396
397#endif /* !NO_CHANGEDISPLAYSETTINGS */
398
399 /* Grab an identity palette if we are in a palettized mode */
400 if ( vformat->BitsPerPixel <= 8 ) {
401 /* RJR: March 28, 2000
402 moved palette creation to "DIB_CreatePalette" */
403 DIB_CreatePalette(this, vformat->BitsPerPixel);
404 }
405
406 /* Fill in some window manager capabilities */
407 this->info.wm_available = 1;
408
409#ifdef _WIN32_WCE
410 this->hidden->origRotation = -1;
411#endif
412
413 /* Allow environment override of screensaver disable. */
414 env = SDL_getenv("SDL_VIDEO_ALLOW_SCREENSAVER");
415 if ( env ) {
416 allow_screensaver = SDL_atoi(env);
417 } else {
418#ifdef SDL_VIDEO_DISABLE_SCREENSAVER
419 allow_screensaver = 0;
420#else
421 allow_screensaver = 1;
422#endif
423 }
424
425 /* We're done! */
426 return(0);
427}
428
429/* We support any format at any dimension */
430SDL_Rect **DIB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
431{
432 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
433 return(SDL_modelist[((format->BitsPerPixel+7)/8)-1]);
434 } else {
435 return((SDL_Rect **)-1);
436 }
437}
438
439
440/*
441 Helper fn to work out which screen depth windows is currently using.
442 15 bit mode is considered 555 format, 16 bit is 565.
443 returns 0 for unknown mode.
444 (Derived from code in sept 1999 Windows Developer Journal
445 http://www.wdj.com/code/archive.html)
446*/
447static int DIB_SussScreenDepth()
448{
449#ifdef NO_GETDIBITS
450 int depth;
451 HDC hdc;
452
453 hdc = GetDC(SDL_Window);
454 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
455 ReleaseDC(SDL_Window, hdc);
456 return(depth);
457#else
458 int depth;
459 int dib_size;
460 LPBITMAPINFOHEADER dib_hdr;
461 HDC hdc;
462 HBITMAP hbm;
463
464 /* Allocate enough space for a DIB header plus palette (for
465 * 8-bit modes) or bitfields (for 16- and 32-bit modes)
466 */
467 dib_size = sizeof(BITMAPINFOHEADER) + 256 * sizeof (RGBQUAD);
468 dib_hdr = (LPBITMAPINFOHEADER) SDL_malloc(dib_size);
469 SDL_memset(dib_hdr, 0, dib_size);
470 dib_hdr->biSize = sizeof(BITMAPINFOHEADER);
471
472 /* Get a device-dependent bitmap that's compatible with the
473 screen.
474 */
475 hdc = GetDC(NULL);
476 hbm = CreateCompatibleBitmap( hdc, 1, 1 );
477
478 /* Convert the DDB to a DIB. We need to call GetDIBits twice:
479 * the first call just fills in the BITMAPINFOHEADER; the
480 * second fills in the bitfields or palette.
481 */
482 GetDIBits(hdc, hbm, 0, 1, NULL, (LPBITMAPINFO) dib_hdr, DIB_RGB_COLORS);
483 GetDIBits(hdc, hbm, 0, 1, NULL, (LPBITMAPINFO) dib_hdr, DIB_RGB_COLORS);
484 DeleteObject(hbm);
485 ReleaseDC(NULL, hdc);
486
487 depth = 0;
488 switch( dib_hdr->biBitCount )
489 {
490 case 8: depth = 8; break;
491 case 24: depth = 24; break;
492 case 32: depth = 32; break;
493 case 16:
494 if( dib_hdr->biCompression == BI_BITFIELDS ) {
495 /* check the red mask */
496 switch( ((DWORD*)((char*)dib_hdr + dib_hdr->biSize))[0] ) {
497 case 0xf800: depth = 16; break; /* 565 */
498 case 0x7c00: depth = 15; break; /* 555 */
499 }
500 }
501 }
502 SDL_free(dib_hdr);
503 return depth;
504#endif /* NO_GETDIBITS */
505}
506
507
508/* Various screen update functions available */
509static void DIB_NormalUpdate(_THIS, int numrects, SDL_Rect *rects);
510
511static void DIB_ResizeWindow(_THIS, int width, int height, int prev_width, int prev_height, Uint32 flags)
512{
513 RECT bounds;
514 int x, y;
515
516#ifndef _WIN32_WCE
517 /* Resize the window */
518 if ( !SDL_windowid && !IsZoomed(SDL_Window) ) {
519#else
520 if ( !SDL_windowid ) {
521#endif
522 HWND top;
523 UINT swp_flags;
524 const char *window = NULL;
525 const char *center = NULL;
526
527 if ( width != prev_width || height != prev_height ) {
528 window = SDL_getenv("SDL_VIDEO_WINDOW_POS");
529 center = SDL_getenv("SDL_VIDEO_CENTERED");
530 if ( window ) {
531 if ( SDL_sscanf(window, "%d,%d", &x, &y) == 2 ) {
532 SDL_windowX = x;
533 SDL_windowY = y;
534 }
535 if ( SDL_strcmp(window, "center") == 0 ) {
536 center = window;
537 }
538 }
539 }
540 swp_flags = (SWP_NOCOPYBITS | SWP_SHOWWINDOW);
541
542 bounds.left = SDL_windowX;
543 bounds.top = SDL_windowY;
544 bounds.right = SDL_windowX+width;
545 bounds.bottom = SDL_windowY+height;
546#ifndef _WIN32_WCE
547 AdjustWindowRectEx(&bounds, GetWindowLong(SDL_Window, GWL_STYLE), (GetMenu(SDL_Window) != NULL), 0);
548#else
549 // The bMenu parameter must be FALSE; menu bars are not supported
550 AdjustWindowRectEx(&bounds, GetWindowLong(SDL_Window, GWL_STYLE), 0, 0);
551#endif
552 width = bounds.right-bounds.left;
553 height = bounds.bottom-bounds.top;
554 if ( (flags & SDL_FULLSCREEN) ) {
555 x = (GetSystemMetrics(SM_CXSCREEN)-width)/2;
556 y = (GetSystemMetrics(SM_CYSCREEN)-height)/2;
557 } else if ( center ) {
558 x = (GetSystemMetrics(SM_CXSCREEN)-width)/2;
559 y = (GetSystemMetrics(SM_CYSCREEN)-height)/2;
560 } else if ( SDL_windowX || SDL_windowY || window ) {
561 x = bounds.left;
562 y = bounds.top;
563 } else {
564 x = y = -1;
565 swp_flags |= SWP_NOMOVE;
566 }
567 if ( flags & SDL_FULLSCREEN ) {
568 top = HWND_TOPMOST;
569 } else {
570 top = HWND_NOTOPMOST;
571 }
572 SetWindowPos(SDL_Window, top, x, y, width, height, swp_flags);
573 if ( !(flags & SDL_FULLSCREEN) ) {
574 SDL_windowX = SDL_bounds.left;
575 SDL_windowY = SDL_bounds.top;
576 }
577 if ( GetParent(SDL_Window) == NULL ) {
578 SetForegroundWindow(SDL_Window);
579 }
580 }
581}
582
583SDL_Surface *DIB_SetVideoMode(_THIS, SDL_Surface *current,
584 int width, int height, int bpp, Uint32 flags)
585{
586 SDL_Surface *video;
587 int prev_w, prev_h;
588 Uint32 prev_flags;
589 DWORD style;
590 const DWORD directstyle =
591 (WS_POPUP);
592 const DWORD windowstyle =
593 (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX);
594 const DWORD resizestyle =
595 (WS_THICKFRAME|WS_MAXIMIZEBOX);
596 int binfo_size;
597 BITMAPINFO *binfo;
598 HDC hdc;
599 Uint32 Rmask, Gmask, Bmask;
600
601 prev_w = current->w;
602 prev_h = current->h;
603 prev_flags = current->flags;
604
605 /*
606 * Special case for OpenGL windows...since the app needs to call
607 * SDL_SetVideoMode() in response to resize events to continue to
608 * function, but WGL handles the GL context details behind the scenes,
609 * there's no sense in tearing the context down just to rebuild it
610 * to what it already was...tearing it down sacrifices your GL state
611 * and uploaded textures. So if we're requesting the same video mode
612 * attributes just resize the window and return immediately.
613 */
614 if ( SDL_Window &&
615 ((current->flags & ~SDL_ANYFORMAT) == (flags & ~SDL_ANYFORMAT)) &&
616 (current->format->BitsPerPixel == bpp) &&
617 (flags & SDL_OPENGL) &&
618 !(flags & SDL_FULLSCREEN) ) { /* probably not safe for fs */
619 current->w = width;
620 current->h = height;
621 SDL_resizing = 1;
622 DIB_ResizeWindow(this, width, height, prev_w, prev_h, flags);
623 SDL_resizing = 0;
624 return current;
625 }
626
627 /* Clean up any GL context that may be hanging around */
628 if ( current->flags & SDL_OPENGL ) {
629 WIN_GL_ShutDown(this);
630 }
631 SDL_resizing = 1;
632
633 /* Recalculate the bitmasks if necessary */
634 if ( bpp == current->format->BitsPerPixel ) {
635 video = current;
636 } else {
637 switch (bpp) {
638 case 15:
639 case 16:
640 if ( DIB_SussScreenDepth() == 15 ) {
641 /* 5-5-5 */
642 Rmask = 0x00007c00;
643 Gmask = 0x000003e0;
644 Bmask = 0x0000001f;
645 } else {
646 /* 5-6-5 */
647 Rmask = 0x0000f800;
648 Gmask = 0x000007e0;
649 Bmask = 0x0000001f;
650 }
651 break;
652 case 24:
653 case 32:
654 /* GDI defined as 8-8-8 */
655 Rmask = 0x00ff0000;
656 Gmask = 0x0000ff00;
657 Bmask = 0x000000ff;
658 break;
659 default:
660 Rmask = 0x00000000;
661 Gmask = 0x00000000;
662 Bmask = 0x00000000;
663 break;
664 }
665 video = SDL_CreateRGBSurface(SDL_SWSURFACE,
666 0, 0, bpp, Rmask, Gmask, Bmask, 0);
667 if ( video == NULL ) {
668 SDL_OutOfMemory();
669 return(NULL);
670 }
671 }
672
673 /* Fill in part of the video surface */
674 video->flags = 0; /* Clear flags */
675 video->w = width;
676 video->h = height;
677 video->pitch = SDL_CalculatePitch(video);
678
679 /* Small fix for WinCE/Win32 - when activating window
680 SDL_VideoSurface is equal to zero, so activating code
681 is not called properly for fullscreen windows because
682 macros WINDIB_FULLSCREEN uses SDL_VideoSurface
683 */
684 SDL_VideoSurface = video;
685
686#if defined(_WIN32_WCE)
687 if ( flags & SDL_FULLSCREEN )
688 video->flags |= SDL_FULLSCREEN;
689#endif
690
691#ifndef NO_CHANGEDISPLAYSETTINGS
692 /* Set fullscreen mode if appropriate */
693 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
694 DEVMODE settings;
695 BOOL changed;
696
697 SDL_memset(&settings, 0, sizeof(DEVMODE));
698 settings.dmSize = sizeof(DEVMODE);
699
700#ifdef _WIN32_WCE
701 // try to rotate screen to fit requested resolution
702 if( this->hidden->supportRotation )
703 {
704 DWORD rotation;
705
706 // ask current mode
707 settings.dmFields = DM_DISPLAYORIENTATION;
708 ChangeDisplaySettingsEx(NULL, &settings, NULL, CDS_TEST, NULL);
709 rotation = settings.dmDisplayOrientation;
710
711 if( (width > GetDeviceCaps(GetDC(NULL), HORZRES))
712 && (height < GetDeviceCaps(GetDC(NULL), VERTRES)))
713 {
714 switch( rotation )
715 {
716 case DMDO_0:
717 settings.dmDisplayOrientation = DMDO_90;
718 break;
719 case DMDO_270:
720 settings.dmDisplayOrientation = DMDO_180;
721 break;
722 }
723 if( settings.dmDisplayOrientation != rotation )
724 {
725 // go to landscape
726 this->hidden->origRotation = rotation;
727 ChangeDisplaySettingsEx(NULL,&settings,NULL,CDS_RESET,NULL);
728 }
729 }
730 if( (width < GetDeviceCaps(GetDC(NULL), HORZRES))
731 && (height > GetDeviceCaps(GetDC(NULL), VERTRES)))
732 {
733 switch( rotation )
734 {
735 case DMDO_90:
736 settings.dmDisplayOrientation = DMDO_0;
737 break;
738 case DMDO_180:
739 settings.dmDisplayOrientation = DMDO_270;
740 break;
741 }
742 if( settings.dmDisplayOrientation != rotation )
743 {
744 // go to portrait
745 this->hidden->origRotation = rotation;
746 ChangeDisplaySettingsEx(NULL,&settings,NULL,CDS_RESET,NULL);
747 }
748 }
749
750 }
751#endif
752
753#ifndef _WIN32_WCE
754 settings.dmBitsPerPel = video->format->BitsPerPixel;
755 settings.dmPelsWidth = width;
756 settings.dmPelsHeight = height;
757 settings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
758 if ( width <= (int)SDL_desktop_mode.dmPelsWidth &&
759 height <= (int)SDL_desktop_mode.dmPelsHeight ) {
760 settings.dmDisplayFrequency = SDL_desktop_mode.dmDisplayFrequency;
761 settings.dmFields |= DM_DISPLAYFREQUENCY;
762 }
763 changed = (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL);
764 if ( ! changed && (settings.dmFields & DM_DISPLAYFREQUENCY) ) {
765 settings.dmFields &= ~DM_DISPLAYFREQUENCY;
766 changed = (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL);
767 }
768#else
769 changed = 1;
770#endif
771 if ( changed ) {
772 video->flags |= SDL_FULLSCREEN;
773 SDL_fullscreen_mode = settings;
774 }
775
776 }
777#endif /* !NO_CHANGEDISPLAYSETTINGS */
778
779 /* Reset the palette and create a new one if necessary */
780 if ( grab_palette ) {
781 DIB_ReleaseStaticColors(SDL_Window);
782 grab_palette = FALSE;
783 }
784 if ( screen_pal != NULL ) {
785 /* RJR: March 28, 2000
786 delete identity palette if switching from a palettized mode */
787 DeleteObject(screen_pal);
788 screen_pal = NULL;
789 }
790 if ( screen_logpal != NULL ) {
791 SDL_free(screen_logpal);
792 screen_logpal = NULL;
793 }
794
795 if ( bpp <= 8 )
796 {
797 /* RJR: March 28, 2000
798 create identity palette switching to a palettized mode */
799 DIB_CreatePalette(this, bpp);
800 }
801
802 style = GetWindowLong(SDL_Window, GWL_STYLE);
803 style &= ~(resizestyle|WS_MAXIMIZE);
804 if ( (video->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
805 style &= ~windowstyle;
806 style |= directstyle;
807 } else {
808#ifndef NO_CHANGEDISPLAYSETTINGS
809 if ( (prev_flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
810 ChangeDisplaySettings(NULL, 0);
811 }
812#endif
813 if ( flags & SDL_NOFRAME ) {
814 style &= ~windowstyle;
815 style |= directstyle;
816 video->flags |= SDL_NOFRAME;
817 } else {
818 style &= ~directstyle;
819 style |= windowstyle;
820 if ( flags & SDL_RESIZABLE ) {
821 style |= resizestyle;
822 video->flags |= SDL_RESIZABLE;
823 }
824 }
825#if WS_MAXIMIZE && !defined(_WIN32_WCE)
826 if (IsZoomed(SDL_Window)) style |= WS_MAXIMIZE;
827#endif
828 }
829
830 /* DJM: Don't piss of anyone who has setup his own window */
831 if ( !SDL_windowid )
832 SetWindowLong(SDL_Window, GWL_STYLE, style);
833
834 /* Delete the old bitmap if necessary */
835 if ( screen_bmp != NULL ) {
836 DeleteObject(screen_bmp);
837 }
838 if ( ! (flags & SDL_OPENGL) ) {
839 BOOL is16bitmode = (video->format->BytesPerPixel == 2);
840
841 /* Suss out the bitmap info header */
842 binfo_size = sizeof(*binfo);
843 if( is16bitmode ) {
844 /* 16bit modes, palette area used for rgb bitmasks */
845 binfo_size += 3*sizeof(DWORD);
846 } else if ( video->format->palette ) {
847 binfo_size += video->format->palette->ncolors *
848 sizeof(RGBQUAD);
849 }
850 binfo = (BITMAPINFO *)SDL_malloc(binfo_size);
851 if ( ! binfo ) {
852 if ( video != current ) {
853 SDL_FreeSurface(video);
854 }
855 SDL_OutOfMemory();
856 return(NULL);
857 }
858
859 binfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
860 binfo->bmiHeader.biWidth = video->w;
861 binfo->bmiHeader.biHeight = -video->h; /* -ve for topdown bitmap */
862 binfo->bmiHeader.biPlanes = 1;
863 binfo->bmiHeader.biSizeImage = video->h * video->pitch;
864 binfo->bmiHeader.biXPelsPerMeter = 0;
865 binfo->bmiHeader.biYPelsPerMeter = 0;
866 binfo->bmiHeader.biClrUsed = 0;
867 binfo->bmiHeader.biClrImportant = 0;
868 binfo->bmiHeader.biBitCount = video->format->BitsPerPixel;
869
870 if ( is16bitmode ) {
871 /* BI_BITFIELDS tells CreateDIBSection about the rgb masks in the palette */
872 binfo->bmiHeader.biCompression = BI_BITFIELDS;
873 ((Uint32*)binfo->bmiColors)[0] = video->format->Rmask;
874 ((Uint32*)binfo->bmiColors)[1] = video->format->Gmask;
875 ((Uint32*)binfo->bmiColors)[2] = video->format->Bmask;
876 } else {
877 binfo->bmiHeader.biCompression = BI_RGB; /* BI_BITFIELDS for 565 vs 555 */
878 if ( video->format->palette ) {
879 SDL_memset(binfo->bmiColors, 0,
880 video->format->palette->ncolors*sizeof(RGBQUAD));
881 }
882 }
883
884 /* Create the offscreen bitmap buffer */
885 hdc = GetDC(SDL_Window);
886 screen_bmp = CreateDIBSection(hdc, binfo, DIB_RGB_COLORS,
887 (void **)(&video->pixels), NULL, 0);
888 ReleaseDC(SDL_Window, hdc);
889 SDL_free(binfo);
890 if ( screen_bmp == NULL ) {
891 if ( video != current ) {
892 SDL_FreeSurface(video);
893 }
894 SDL_SetError("Couldn't create DIB section");
895 return(NULL);
896 }
897 this->UpdateRects = DIB_NormalUpdate;
898
899 /* Set video surface flags */
900 if ( screen_pal && (flags & (SDL_FULLSCREEN|SDL_HWPALETTE)) ) {
901 grab_palette = TRUE;
902 }
903 if ( screen_pal ) {
904 /* BitBlt() maps colors for us */
905 video->flags |= SDL_HWPALETTE;
906 }
907 }
908 DIB_ResizeWindow(this, width, height, prev_w, prev_h, flags);
909 SDL_resizing = 0;
910
911 /* Set up for OpenGL */
912 if ( flags & SDL_OPENGL ) {
913 if ( WIN_GL_SetupWindow(this) < 0 ) {
914 return(NULL);
915 }
916 video->flags |= SDL_OPENGL;
917 }
918
919 /* JC 14 Mar 2006
920 Flush the message loop or this can cause big problems later
921 Especially if the user decides to use dialog boxes or assert()!
922 */
923 WIN_FlushMessageQueue();
924
925 /* We're live! */
926 return(video);
927}
928
929/* We don't actually allow hardware surfaces in the DIB driver */
930static int DIB_AllocHWSurface(_THIS, SDL_Surface *surface)
931{
932 return(-1);
933}
934static void DIB_FreeHWSurface(_THIS, SDL_Surface *surface)
935{
936 return;
937}
938static int DIB_LockHWSurface(_THIS, SDL_Surface *surface)
939{
940 return(0);
941}
942static void DIB_UnlockHWSurface(_THIS, SDL_Surface *surface)
943{
944 return;
945}
946
947static void DIB_NormalUpdate(_THIS, int numrects, SDL_Rect *rects)
948{
949 HDC hdc, mdc;
950 int i;
951
952 hdc = GetDC(SDL_Window);
953 if ( screen_pal ) {
954 SelectPalette(hdc, screen_pal, FALSE);
955 }
956 mdc = CreateCompatibleDC(hdc);
957 SelectObject(mdc, screen_bmp);
958 for ( i=0; i<numrects; ++i ) {
959 BitBlt(hdc, rects[i].x, rects[i].y, rects[i].w, rects[i].h,
960 mdc, rects[i].x, rects[i].y, SRCCOPY);
961 }
962 DeleteDC(mdc);
963 ReleaseDC(SDL_Window, hdc);
964}
965
966static int FindPaletteIndex(LOGPALETTE *pal, BYTE r, BYTE g, BYTE b)
967{
968 PALETTEENTRY *entry;
969 int i;
970 int nentries = pal->palNumEntries;
971
972 for ( i = 0; i < nentries; ++i ) {
973 entry = &pal->palPalEntry[i];
974 if ( entry->peRed == r && entry->peGreen == g && entry->peBlue == b ) {
975 return i;
976 }
977 }
978 return -1;
979}
980
981static BOOL CheckPaletteEntry(LOGPALETTE *pal, int index, BYTE r, BYTE g, BYTE b)
982{
983 PALETTEENTRY *entry;
984 BOOL moved = 0;
985
986 entry = &pal->palPalEntry[index];
987 if ( entry->peRed != r || entry->peGreen != g || entry->peBlue != b ) {
988 int found = FindPaletteIndex(pal, r, g, b);
989 if ( found >= 0 ) {
990 pal->palPalEntry[found] = *entry;
991 }
992 entry->peRed = r;
993 entry->peGreen = g;
994 entry->peBlue = b;
995 moved = 1;
996 }
997 entry->peFlags = 0;
998
999 return moved;
1000}
1001
1002int DIB_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
1003{
1004#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
1005 HDC hdc, mdc;
1006 RGBQUAD *pal;
1007#else
1008 HDC hdc;
1009#endif
1010 int i;
1011 int moved_entries = 0;
1012
1013 /* Update the display palette */
1014 hdc = GetDC(SDL_Window);
1015 if ( screen_pal ) {
1016 PALETTEENTRY *entry;
1017
1018 for ( i=0; i<ncolors; ++i ) {
1019 entry = &screen_logpal->palPalEntry[firstcolor+i];
1020 entry->peRed = colors[i].r;
1021 entry->peGreen = colors[i].g;
1022 entry->peBlue = colors[i].b;
1023 entry->peFlags = PC_NOCOLLAPSE;
1024 }
1025#if defined(SYSPAL_NOSTATIC) && !defined(_WIN32_WCE)
1026 /* Check to make sure black and white are in position */
1027 if ( GetSystemPaletteUse(hdc) != SYSPAL_NOSTATIC256 ) {
1028 moved_entries += CheckPaletteEntry(screen_logpal, 0, 0x00, 0x00, 0x00);
1029 moved_entries += CheckPaletteEntry(screen_logpal, screen_logpal->palNumEntries-1, 0xff, 0xff, 0xff);
1030 }
1031 /* FIXME:
1032 If we don't have full access to the palette, what we
1033 really want to do is find the 236 most diverse colors
1034 in the desired palette, set those entries (10-245) and
1035 then map everything into the new system palette.
1036 */
1037#endif
1038
1039#ifndef _WIN32_WCE
1040 /* Copy the entries into the system palette */
1041 UnrealizeObject(screen_pal);
1042#endif
1043 SetPaletteEntries(screen_pal, 0, screen_logpal->palNumEntries, screen_logpal->palPalEntry);
1044 SelectPalette(hdc, screen_pal, FALSE);
1045 RealizePalette(hdc);
1046 }
1047
1048#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
1049 /* Copy palette colors into DIB palette */
1050 pal = SDL_stack_alloc(RGBQUAD, ncolors);
1051 for ( i=0; i<ncolors; ++i ) {
1052 pal[i].rgbRed = colors[i].r;
1053 pal[i].rgbGreen = colors[i].g;
1054 pal[i].rgbBlue = colors[i].b;
1055 pal[i].rgbReserved = 0;
1056 }
1057
1058 /* Set the DIB palette and update the display */
1059 mdc = CreateCompatibleDC(hdc);
1060 SelectObject(mdc, screen_bmp);
1061 SetDIBColorTable(mdc, firstcolor, ncolors, pal);
1062 if ( moved_entries || !grab_palette ) {
1063 BitBlt(hdc, 0, 0, this->screen->w, this->screen->h,
1064 mdc, 0, 0, SRCCOPY);
1065 }
1066 DeleteDC(mdc);
1067 SDL_stack_free(pal);
1068#endif
1069 ReleaseDC(SDL_Window, hdc);
1070 return(1);
1071}
1072
1073
1074static void DIB_CheckGamma(_THIS)
1075{
1076#ifndef NO_GAMMA_SUPPORT
1077 HDC hdc;
1078 WORD ramp[3*256];
1079
1080 /* If we fail to get gamma, disable gamma control */
1081 hdc = GetDC(SDL_Window);
1082 if ( ! GetDeviceGammaRamp(hdc, ramp) ) {
1083 this->GetGammaRamp = NULL;
1084 this->SetGammaRamp = NULL;
1085 }
1086 ReleaseDC(SDL_Window, hdc);
1087#endif /* !NO_GAMMA_SUPPORT */
1088}
1089void DIB_SwapGamma(_THIS)
1090{
1091#ifndef NO_GAMMA_SUPPORT
1092 HDC hdc;
1093
1094 if ( gamma_saved ) {
1095 hdc = GetDC(SDL_Window);
1096 if ( SDL_GetAppState() & SDL_APPINPUTFOCUS ) {
1097 /* About to leave active state, restore gamma */
1098 SetDeviceGammaRamp(hdc, gamma_saved);
1099 } else {
1100 /* About to enter active state, set game gamma */
1101 GetDeviceGammaRamp(hdc, gamma_saved);
1102 SetDeviceGammaRamp(hdc, this->gamma);
1103 }
1104 ReleaseDC(SDL_Window, hdc);
1105 }
1106#endif /* !NO_GAMMA_SUPPORT */
1107}
1108void DIB_QuitGamma(_THIS)
1109{
1110#ifndef NO_GAMMA_SUPPORT
1111 if ( gamma_saved ) {
1112 /* Restore the original gamma if necessary */
1113 if ( SDL_GetAppState() & SDL_APPINPUTFOCUS ) {
1114 HDC hdc;
1115
1116 hdc = GetDC(SDL_Window);
1117 SetDeviceGammaRamp(hdc, gamma_saved);
1118 ReleaseDC(SDL_Window, hdc);
1119 }
1120
1121 /* Free the saved gamma memory */
1122 SDL_free(gamma_saved);
1123 gamma_saved = 0;
1124 }
1125#endif /* !NO_GAMMA_SUPPORT */
1126}
1127
1128int DIB_SetGammaRamp(_THIS, Uint16 *ramp)
1129{
1130#ifdef NO_GAMMA_SUPPORT
1131 SDL_SetError("SDL compiled without gamma ramp support");
1132 return -1;
1133#else
1134 HDC hdc;
1135 BOOL succeeded;
1136
1137 /* Set the ramp for the display */
1138 if ( ! gamma_saved ) {
1139 gamma_saved = (WORD *)SDL_malloc(3*256*sizeof(*gamma_saved));
1140 if ( ! gamma_saved ) {
1141 SDL_OutOfMemory();
1142 return -1;
1143 }
1144 hdc = GetDC(SDL_Window);
1145 GetDeviceGammaRamp(hdc, gamma_saved);
1146 ReleaseDC(SDL_Window, hdc);
1147 }
1148 if ( SDL_GetAppState() & SDL_APPINPUTFOCUS ) {
1149 hdc = GetDC(SDL_Window);
1150 succeeded = SetDeviceGammaRamp(hdc, ramp);
1151 ReleaseDC(SDL_Window, hdc);
1152 } else {
1153 succeeded = TRUE;
1154 }
1155 return succeeded ? 0 : -1;
1156#endif /* !NO_GAMMA_SUPPORT */
1157}
1158
1159int DIB_GetGammaRamp(_THIS, Uint16 *ramp)
1160{
1161#ifdef NO_GAMMA_SUPPORT
1162 SDL_SetError("SDL compiled without gamma ramp support");
1163 return -1;
1164#else
1165 HDC hdc;
1166 BOOL succeeded;
1167
1168 /* Get the ramp from the display */
1169 hdc = GetDC(SDL_Window);
1170 succeeded = GetDeviceGammaRamp(hdc, ramp);
1171 ReleaseDC(SDL_Window, hdc);
1172 return succeeded ? 0 : -1;
1173#endif /* !NO_GAMMA_SUPPORT */
1174}
1175
1176void DIB_VideoQuit(_THIS)
1177{
1178 int i, j;
1179
1180 /* Destroy the window and everything associated with it */
1181 if ( SDL_Window ) {
1182 /* Delete the screen bitmap (also frees screen->pixels) */
1183 if ( this->screen ) {
1184 if ( grab_palette ) {
1185 DIB_ReleaseStaticColors(SDL_Window);
1186 }
1187#ifndef NO_CHANGEDISPLAYSETTINGS
1188 if ( this->screen->flags & SDL_FULLSCREEN ) {
1189 ChangeDisplaySettings(NULL, 0);
1190 ShowWindow(SDL_Window, SW_HIDE);
1191 }
1192#endif
1193 if ( this->screen->flags & SDL_OPENGL ) {
1194 WIN_GL_ShutDown(this);
1195 }
1196 this->screen->pixels = NULL;
1197 }
1198 if ( screen_pal != NULL ) {
1199 DeleteObject(screen_pal);
1200 screen_pal = NULL;
1201 }
1202 if ( screen_logpal != NULL ) {
1203 SDL_free(screen_logpal);
1204 screen_logpal = NULL;
1205 }
1206 if ( screen_bmp ) {
1207 DeleteObject(screen_bmp);
1208 screen_bmp = NULL;
1209 }
1210 if ( screen_icn ) {
1211 DestroyIcon(screen_icn);
1212 screen_icn = NULL;
1213 }
1214 DIB_QuitGamma(this);
1215 DIB_DestroyWindow(this);
1216
1217 SDL_Window = NULL;
1218
1219#if defined(_WIN32_WCE)
1220
1221// Unload wince aygshell library to prevent leak
1222 if( aygshell )
1223 {
1224 FreeLibrary(aygshell);
1225 aygshell = NULL;
1226 }
1227#endif
1228 }
1229
1230 for ( i=0; i < SDL_arraysize(SDL_modelist); ++i ) {
1231 if ( !SDL_modelist[i] ) {
1232 continue;
1233 }
1234 for ( j=0; SDL_modelist[i][j]; ++j ) {
1235 SDL_free(SDL_modelist[i][j]);
1236 }
1237 SDL_free(SDL_modelist[i]);
1238 SDL_modelist[i] = NULL;
1239 SDL_nummodes[i] = 0;
1240 }
1241}
1242
1243/* Exported for the windows message loop only */
1244static void DIB_GrabStaticColors(HWND window)
1245{
1246#if defined(SYSPAL_NOSTATIC) && !defined(_WIN32_WCE)
1247 HDC hdc;
1248
1249 hdc = GetDC(window);
1250 SetSystemPaletteUse(hdc, SYSPAL_NOSTATIC256);
1251 if ( GetSystemPaletteUse(hdc) != SYSPAL_NOSTATIC256 ) {
1252 SetSystemPaletteUse(hdc, SYSPAL_NOSTATIC);
1253 }
1254 ReleaseDC(window, hdc);
1255#endif
1256}
1257static void DIB_ReleaseStaticColors(HWND window)
1258{
1259#if defined(SYSPAL_NOSTATIC) && !defined(_WIN32_WCE)
1260 HDC hdc;
1261
1262 hdc = GetDC(window);
1263 SetSystemPaletteUse(hdc, SYSPAL_STATIC);
1264 ReleaseDC(window, hdc);
1265#endif
1266}
1267static void DIB_Activate(_THIS, BOOL active, BOOL minimized)
1268{
1269 if ( grab_palette ) {
1270 if ( !active ) {
1271 DIB_ReleaseStaticColors(SDL_Window);
1272 DIB_RealizePalette(this);
1273 } else if ( !minimized ) {
1274 DIB_GrabStaticColors(SDL_Window);
1275 DIB_RealizePalette(this);
1276 }
1277 }
1278}
1279static void DIB_RealizePalette(_THIS)
1280{
1281 if ( screen_pal != NULL ) {
1282 HDC hdc;
1283
1284 hdc = GetDC(SDL_Window);
1285#ifndef _WIN32_WCE
1286 UnrealizeObject(screen_pal);
1287#endif
1288 SelectPalette(hdc, screen_pal, FALSE);
1289 if ( RealizePalette(hdc) ) {
1290 InvalidateRect(SDL_Window, NULL, FALSE);
1291 }
1292 ReleaseDC(SDL_Window, hdc);
1293 }
1294}
1295static void DIB_PaletteChanged(_THIS, HWND window)
1296{
1297 if ( window != SDL_Window ) {
1298 DIB_RealizePalette(this);
1299 }
1300}
1301
1302/* Exported for the windows message loop only */
1303static void DIB_WinPAINT(_THIS, HDC hdc)
1304{
1305 HDC mdc;
1306
1307 if ( screen_pal ) {
1308 SelectPalette(hdc, screen_pal, FALSE);
1309 }
1310 mdc = CreateCompatibleDC(hdc);
1311 SelectObject(mdc, screen_bmp);
1312 BitBlt(hdc, 0, 0, SDL_VideoSurface->w, SDL_VideoSurface->h,
1313 mdc, 0, 0, SRCCOPY);
1314 DeleteDC(mdc);
1315}
1316
1317/* Stub in case DirectX isn't available */
1318#if !SDL_AUDIO_DRIVER_DSOUND
1319void DX5_SoundFocus(HWND hwnd)
1320{
1321 return;
1322}
1323#endif
diff --git a/apps/plugins/sdl/src/video/windib/SDL_dibvideo.h b/apps/plugins/sdl/src/video/windib/SDL_dibvideo.h
deleted file mode 100644
index 48b1943a9a..0000000000
--- a/apps/plugins/sdl/src/video/windib/SDL_dibvideo.h
+++ /dev/null
@@ -1,59 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_dibvideo_h
25#define _SDL_dibvideo_h
26
27#define WIN32_LEAN_AND_MEAN
28#include <windows.h>
29
30
31/* Private display data */
32struct DibInfo {
33 HBITMAP screen_bmp;
34 HPALETTE screen_pal;
35 LOGPALETTE *screen_logpal;
36 BOOL grab_palette;
37
38#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
39 int SDL_nummodes[NUM_MODELISTS];
40 SDL_Rect **SDL_modelist[NUM_MODELISTS];
41
42#ifdef _WIN32_WCE
43 int supportRotation; /* for Pocket PC devices */
44 DWORD origRotation; /* for Pocket PC devices */
45#endif
46
47 /* Screensaver settings */
48 int allow_screensaver;
49};
50/* Old variable names */
51#define screen_bmp (this->hidden->dibInfo->screen_bmp)
52#define screen_pal (this->hidden->dibInfo->screen_pal)
53#define screen_logpal (this->hidden->dibInfo->screen_logpal)
54#define grab_palette (this->hidden->dibInfo->grab_palette)
55#define SDL_nummodes (this->hidden->dibInfo->SDL_nummodes)
56#define SDL_modelist (this->hidden->dibInfo->SDL_modelist)
57#define allow_screensaver (this->hidden->dibInfo->allow_screensaver)
58
59#endif /* _SDL_dibvideo_h */
diff --git a/apps/plugins/sdl/src/video/windib/SDL_gapidibvideo.h b/apps/plugins/sdl/src/video/windib/SDL_gapidibvideo.h
deleted file mode 100644
index 64743d1af4..0000000000
--- a/apps/plugins/sdl/src/video/windib/SDL_gapidibvideo.h
+++ /dev/null
@@ -1,56 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_gapidibvideo_h
25#define _SDL_gapidibvideo_h
26
27#define WIN32_LEAN_AND_MEAN
28#include <windows.h>
29
30/* Hidden "this" pointer for the video functions */
31#define _THIS SDL_VideoDevice *this
32
33/* typedef these to be able to define pointers, but still force everybody who
34 * wants to access them to include the corresponding header */
35typedef struct GapiInfo GapiInfo;
36typedef struct DibInfo DibInfo;
37
38/* for PDA */
39typedef enum
40{
41 SDL_ORIENTATION_UP,
42 SDL_ORIENTATION_DOWN,
43 SDL_ORIENTATION_LEFT,
44 SDL_ORIENTATION_RIGHT
45} SDL_ScreenOrientation;
46
47/* Private display data shared by gapi and windib*/
48struct SDL_PrivateVideoData {
49 int supportRotation; /* for Pocket PC devices */
50 DWORD origRotation; /* for Pocket PC devices */
51
52 GapiInfo* gapiInfo;
53 DibInfo* dibInfo;
54};
55
56#endif
diff --git a/apps/plugins/sdl/src/video/windib/SDL_vkeys.h b/apps/plugins/sdl/src/video/windib/SDL_vkeys.h
deleted file mode 100644
index 53d9246455..0000000000
--- a/apps/plugins/sdl/src/video/windib/SDL_vkeys.h
+++ /dev/null
@@ -1,75 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23#ifndef VK_0
24#define VK_0 '0'
25#define VK_1 '1'
26#define VK_2 '2'
27#define VK_3 '3'
28#define VK_4 '4'
29#define VK_5 '5'
30#define VK_6 '6'
31#define VK_7 '7'
32#define VK_8 '8'
33#define VK_9 '9'
34#define VK_A 'A'
35#define VK_B 'B'
36#define VK_C 'C'
37#define VK_D 'D'
38#define VK_E 'E'
39#define VK_F 'F'
40#define VK_G 'G'
41#define VK_H 'H'
42#define VK_I 'I'
43#define VK_J 'J'
44#define VK_K 'K'
45#define VK_L 'L'
46#define VK_M 'M'
47#define VK_N 'N'
48#define VK_O 'O'
49#define VK_P 'P'
50#define VK_Q 'Q'
51#define VK_R 'R'
52#define VK_S 'S'
53#define VK_T 'T'
54#define VK_U 'U'
55#define VK_V 'V'
56#define VK_W 'W'
57#define VK_X 'X'
58#define VK_Y 'Y'
59#define VK_Z 'Z'
60#endif /* VK_0 */
61
62/* These keys haven't been defined, but were experimentally determined */
63#define VK_SEMICOLON 0xBA
64#define VK_EQUALS 0xBB
65#define VK_COMMA 0xBC
66#define VK_MINUS 0xBD
67#define VK_PERIOD 0xBE
68#define VK_SLASH 0xBF
69#define VK_GRAVE 0xC0
70#define VK_LBRACKET 0xDB
71#define VK_BACKSLASH 0xDC
72#define VK_RBRACKET 0xDD
73#define VK_APOSTROPHE 0xDE
74#define VK_BACKTICK 0xDF
75#define VK_OEM_102 0xE2
diff --git a/apps/plugins/sdl/src/video/windx5/SDL_dx5events.c b/apps/plugins/sdl/src/video/windx5/SDL_dx5events.c
deleted file mode 100644
index e12092fd68..0000000000
--- a/apps/plugins/sdl/src/video/windx5/SDL_dx5events.c
+++ /dev/null
@@ -1,1005 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* CAUTION!!!! If you modify this file, check ../windib/SDL_sysevents.c */
25
26#include "directx.h"
27
28#include "SDL_main.h"
29#include "SDL_events.h"
30#include "SDL_video.h"
31#include "SDL_syswm.h"
32#include "../../events/SDL_sysevents.h"
33#include "../../events/SDL_events_c.h"
34#include "../wincommon/SDL_lowvideo.h"
35#include "SDL_dx5video.h"
36
37#ifndef WM_APP
38#define WM_APP 0x8000
39#endif
40
41#ifdef _WIN32_WCE
42#define NO_GETKEYBOARDSTATE
43#endif
44
45/* The keyboard and mouse device input */
46#define MAX_INPUTS 2
47#define INPUT_QSIZE 512 /* Buffer up to 512 input messages */
48
49static LPDIRECTINPUT dinput = NULL;
50static LPDIRECTINPUTDEVICE2 SDL_DIdev[MAX_INPUTS];
51static HANDLE SDL_DIevt[MAX_INPUTS];
52static void (*SDL_DIfun[MAX_INPUTS])(const int, DIDEVICEOBJECTDATA *);
53static int SDL_DIndev = 0;
54static int mouse_lost;
55static int mouse_pressed;
56static int mouse_buttons_swapped = 0;
57
58/* The translation table from a DirectInput scancode to an SDL keysym */
59static SDLKey DIK_keymap[256];
60static SDL_keysym *TranslateKey(UINT scancode, SDL_keysym *keysym, int pressed);
61
62/* DJM: If the user setup the window for us, we want to save his window proc,
63 and give him a chance to handle some messages. */
64#ifdef STRICT
65#define WNDPROCTYPE WNDPROC
66#else
67#define WNDPROCTYPE FARPROC
68#endif
69static WNDPROCTYPE userWindowProc = NULL;
70
71static HWND GetTopLevelParent(HWND hWnd)
72{
73 HWND hParentWnd;
74 while (1)
75 {
76 hParentWnd = GetParent(hWnd);
77 if (hParentWnd == NULL)
78 break;
79 hWnd = hParentWnd;
80 }
81 return hWnd;
82}
83
84/* Convert a DirectInput return code to a text message */
85static void SetDIerror(char *function, int code)
86{
87 static char *error;
88 static char errbuf[1024];
89
90 errbuf[0] = 0;
91 switch (code) {
92 case DIERR_GENERIC:
93 error = "Undefined error!";
94 break;
95 case DIERR_OLDDIRECTINPUTVERSION:
96 error = "Your version of DirectInput needs upgrading";
97 break;
98 case DIERR_INVALIDPARAM:
99 error = "Invalid parameters";
100 break;
101 case DIERR_OUTOFMEMORY:
102 error = "Out of memory";
103 break;
104 case DIERR_DEVICENOTREG:
105 error = "Device not registered";
106 break;
107 case DIERR_NOINTERFACE:
108 error = "Interface not supported";
109 break;
110 case DIERR_NOTINITIALIZED:
111 error = "Device not initialized";
112 break;
113 default:
114 SDL_snprintf(errbuf, SDL_arraysize(errbuf),
115 "%s: Unknown DirectInput error: 0x%x",
116 function, code);
117 break;
118 }
119 if ( ! errbuf[0] ) {
120 SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error);
121 }
122 SDL_SetError("%s", errbuf);
123 return;
124}
125
126/* Initialize DirectInput
127 Note: If NONEXCLUSIVE access is requested for the devices, normal
128 windows input messages will continue to be generated for that
129 input device, in addition to DirectInput messages.
130 */
131static void handle_keyboard(const int numevents, DIDEVICEOBJECTDATA *events);
132static void handle_mouse(const int numevents, DIDEVICEOBJECTDATA *events);
133struct {
134 char *name;
135 REFGUID guid;
136 LPCDIDATAFORMAT format;
137 DWORD win_level;
138 DWORD raw_level;
139 void (*fun)(const int numevents, DIDEVICEOBJECTDATA *events);
140} inputs[] = {
141 { "keyboard",
142 &GUID_SysKeyboard, &c_dfDIKeyboard,
143 (DISCL_FOREGROUND|DISCL_NONEXCLUSIVE),
144 (DISCL_FOREGROUND|DISCL_NONEXCLUSIVE), handle_keyboard },
145 { "mouse",
146 &GUID_SysMouse,
147#if DIRECTINPUT_VERSION >= 0x700
148 &c_dfDIMouse2,
149#else
150 &c_dfDIMouse,
151#endif
152 (DISCL_BACKGROUND|DISCL_NONEXCLUSIVE),
153 (DISCL_BACKGROUND|DISCL_NONEXCLUSIVE), handle_mouse },
154 { NULL, NULL, NULL, 0, 0, NULL }
155};
156
157static int DX5_DInputInit(_THIS)
158{
159 int i;
160 LPDIRECTINPUTDEVICE device;
161 HRESULT result;
162 DIPROPDWORD dipdw;
163 HWND topwnd;
164
165 /* Create the DirectInput object */
166 result = DInputCreate(SDL_Instance, DIRECTINPUT_VERSION,
167 &dinput, NULL);
168 if ( result != DI_OK ) {
169 SetDIerror("DirectInputCreate", result);
170 return(-1);
171 }
172
173 /* Create all of our registered input devices */
174 SDL_DIndev = 0;
175 for ( i=0; inputs[i].name; ++i ) {
176 /* Create the DirectInput device */
177 result = IDirectInput_CreateDevice(dinput, inputs[i].guid,
178 &device, NULL);
179 if ( result != DI_OK ) {
180 SetDIerror("DirectInput::CreateDevice", result);
181 return(-1);
182 }
183 result = IDirectInputDevice_QueryInterface(device,
184 &IID_IDirectInputDevice2, (LPVOID *)&SDL_DIdev[i]);
185 IDirectInputDevice_Release(device);
186 if ( result != DI_OK ) {
187 SetDIerror("DirectInputDevice::QueryInterface", result);
188 return(-1);
189 }
190 topwnd = GetTopLevelParent(SDL_Window);
191 result = IDirectInputDevice2_SetCooperativeLevel(SDL_DIdev[i],
192 topwnd, inputs[i].win_level);
193 if ( result != DI_OK ) {
194 SetDIerror("DirectInputDevice::SetCooperativeLevel",
195 result);
196 return(-1);
197 }
198 result = IDirectInputDevice2_SetDataFormat(SDL_DIdev[i],
199 inputs[i].format);
200 if ( result != DI_OK ) {
201 SetDIerror("DirectInputDevice::SetDataFormat", result);
202 return(-1);
203 }
204
205 /* Set buffered input -- we aren't polling */
206 SDL_memset(&dipdw, 0, sizeof(dipdw));
207 dipdw.diph.dwSize = sizeof(dipdw);
208 dipdw.diph.dwHeaderSize = sizeof(dipdw.diph);
209 dipdw.diph.dwObj = 0;
210 dipdw.diph.dwHow = DIPH_DEVICE;
211 dipdw.dwData = INPUT_QSIZE;
212 result = IDirectInputDevice2_SetProperty(SDL_DIdev[i],
213 DIPROP_BUFFERSIZE, &dipdw.diph);
214 if ( result != DI_OK ) {
215 SetDIerror("DirectInputDevice::SetProperty", result);
216 return(-1);
217 }
218
219 /* Create an event to be signaled when input is ready */
220 SDL_DIevt[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
221 if ( SDL_DIevt[i] == NULL ) {
222 SDL_SetError("Couldn't create DirectInput event");
223 return(-1);
224 }
225 result = IDirectInputDevice2_SetEventNotification(SDL_DIdev[i],
226 SDL_DIevt[i]);
227 if ( result != DI_OK ) {
228 SetDIerror("DirectInputDevice::SetEventNotification",
229 result);
230 return(-1);
231 }
232 SDL_DIfun[i] = inputs[i].fun;
233
234 /* Acquire the device for input */
235 IDirectInputDevice2_Acquire(SDL_DIdev[i]);
236
237 /* Increment the number of devices we have */
238 ++SDL_DIndev;
239 }
240 mouse_pressed = 0;
241 mouse_buttons_swapped = GetSystemMetrics(SM_SWAPBUTTON);
242
243 /* DirectInput is ready! */
244 return(0);
245}
246
247/* Clean up DirectInput */
248static void DX5_DInputQuit(_THIS)
249{
250 int i;
251
252 if ( dinput != NULL ) {
253 /* Close and release all DirectInput devices */
254 for ( i=0; i<MAX_INPUTS; ++i ) {
255 if ( SDL_DIdev[i] != NULL ) {
256 IDirectInputDevice2_Unacquire(SDL_DIdev[i]);
257 IDirectInputDevice2_SetEventNotification(
258 SDL_DIdev[i], NULL);
259 if ( SDL_DIevt[i] != NULL ) {
260 CloseHandle(SDL_DIevt[i]);
261 SDL_DIevt[i] = NULL;
262 }
263 IDirectInputDevice2_Release(SDL_DIdev[i]);
264 SDL_DIdev[i] = NULL;
265 }
266 }
267 SDL_DIndev = 0;
268
269 /* Release DirectInput */
270 IDirectInput_Release(dinput);
271 dinput = NULL;
272 }
273}
274
275/* Flag to tell SDL whether or not we queued an event */
276static int posted = 0;
277
278/* Input event handler functions */
279static void handle_keyboard(const int numevents, DIDEVICEOBJECTDATA *keybuf)
280{
281 int i;
282 SDL_keysym keysym;
283
284 /* Translate keyboard messages */
285 for ( i=0; i<numevents; ++i ) {
286 if ( keybuf[i].dwData & 0x80 ) {
287 posted = SDL_PrivateKeyboard(SDL_PRESSED,
288 TranslateKey(keybuf[i].dwOfs, &keysym, 1));
289 } else {
290 posted = SDL_PrivateKeyboard(SDL_RELEASED,
291 TranslateKey(keybuf[i].dwOfs, &keysym, 0));
292 }
293 }
294}
295
296static void post_mouse_motion(int relative, Sint16 x, Sint16 y)
297{
298 extern int mouse_relative;
299
300 if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) {
301 posted = SDL_PrivateMouseMotion(
302 0, relative, x, y);
303
304 if ( !mouse_relative ) {
305 /* As DirectInput reads raw device coordinates, it has no notion of
306 * cursors or absolute position. We must assume responsibility for
307 * keeping track of this. */
308 int current_x, current_y;
309 POINT cursor;
310 RECT trap;
311 RECT window;
312 int at_edge;
313
314 /* Get the current cursor position */
315 SDL_GetMouseState(&current_x, &current_y);
316 cursor.x = current_x;
317 cursor.y = current_y;
318 ClientToScreen(SDL_Window, &cursor);
319
320 /* Construct a 1 pixel square RECT that is used to confine the cursor
321 * pointer to a specific pixel using ClipCursor. This is used in
322 * preference to SetCursorPos as it avoids the cursor jumping around as
323 * both the OS and SDL attempt to move it simultaneously. */
324 trap.left = cursor.x;
325 trap.top = cursor.y;
326 trap.right = cursor.x + 1;
327 trap.bottom = cursor.y + 1;
328
329 GetClientRect(SDL_Window, &window);
330 window.right -= window.left; window.left = 0;
331 window.bottom -= window.top; window.top = 0;
332
333 /* As we're assuming control over the cursor, we need to know when to
334 * relinquish control of it back to the operating system. This is when
335 * the cursor reaches the edge of the window. */
336 at_edge = (current_x == window.left) ||
337 (current_x == (window.right - 1)) ||
338 (current_y == window.top) ||
339 (current_y == (window.bottom - 1));
340
341 if ( at_edge ) {
342 ClipCursor(NULL);
343 } else {
344 ClipCursor(&trap);
345 }
346 } else {
347 /* When in relative mode, warp the OS's idea of where the cursor is to
348 * the center of the screen. This isn't really necessary as DirectInput
349 * reads from the hardware itself, but in case things go wrong, the
350 * cursor will be left in a sensible place. */
351 POINT center;
352 center.x = (SDL_VideoSurface->w/2);
353 center.y = (SDL_VideoSurface->h/2);
354 ClientToScreen(SDL_Window, &center);
355 SetCursorPos(center.x, center.y);
356 }
357 }
358}
359
360static void handle_mouse(const int numevents, DIDEVICEOBJECTDATA *ptrbuf)
361{
362 int i;
363 Sint16 xrel, yrel;
364 Uint8 state;
365 Uint8 button;
366 DWORD timestamp = 0;
367
368 /* Sanity check. Mailing list reports this being NULL unexpectedly. */
369 if (SDL_PublicSurface == NULL) {
370 return;
371 }
372
373 /* If mouse focus has been lost, make sure we release the cursor. */
374 if ( !(SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) {
375 mouse_lost = 1;
376 ClipCursor(NULL);
377 } else {
378 /* If the mouse was lost, regain some sense of mouse state */
379 if ( mouse_lost ) {
380 POINT mouse_pos;
381 Uint8 old_state;
382 Uint8 new_state;
383
384 /* Set ourselves up with the current cursor position */
385 GetCursorPos(&mouse_pos);
386 ScreenToClient(SDL_Window, &mouse_pos);
387 post_mouse_motion( 0, (Sint16)mouse_pos.x, (Sint16)mouse_pos.y);
388
389 /* Check for mouse button changes */
390 old_state = SDL_GetMouseState(NULL, NULL);
391 new_state = 0;
392 { /* Get the new DirectInput button state for the mouse */
393 #if DIRECTINPUT_VERSION >= 0x700
394 DIMOUSESTATE2 distate;
395 #else
396 DIMOUSESTATE distate;
397 #endif
398 HRESULT result;
399
400 result=IDirectInputDevice2_GetDeviceState(SDL_DIdev[1],
401 sizeof(distate), &distate);
402 if ( result != DI_OK ) {
403 /* Try again next time */
404 SetDIerror(
405 "IDirectInputDevice2::GetDeviceState", result);
406 return;
407 }
408 for ( i=3; i>=0; --i ) {
409 if ( (distate.rgbButtons[i]&0x80) == 0x80 ) {
410 new_state |= 0x01;
411 }
412 new_state <<= 1;
413 }
414 }
415 for ( i=0; i<8; ++i ) {
416 if ( (old_state&0x01) != (new_state&0x01) ) {
417 button = (Uint8)(i+1);
418 /* Map DI button numbers to SDL */
419 switch ( button ) {
420 case 2: button = SDL_BUTTON_RIGHT; break;
421 case 3: button = SDL_BUTTON_MIDDLE; break;
422 case 4: button = SDL_BUTTON_X1; break;
423 case 5: button = SDL_BUTTON_X2; break;
424 default: break;
425 }
426 if ( new_state & 0x01 ) {
427 /* Grab mouse so we get mouse-up */
428 if ( ++mouse_pressed > 0 ) {
429 SetCapture(SDL_Window);
430 }
431 state = SDL_PRESSED;
432 } else {
433 /* Release mouse after all mouse-ups */
434 if ( --mouse_pressed <= 0 ) {
435 ReleaseCapture();
436 mouse_pressed = 0;
437 }
438 state = SDL_RELEASED;
439 }
440 if ( mouse_buttons_swapped ) {
441 if ( button == 1 ) button = 3;
442 else
443 if ( button == 3 ) button = 1;
444 }
445 posted = SDL_PrivateMouseButton(state, button,
446 0, 0);
447 }
448 old_state >>= 1;
449 new_state >>= 1;
450 }
451 mouse_lost = 0;
452 return;
453 }
454
455 /* Translate mouse messages */
456 xrel = 0;
457 yrel = 0;
458 for ( i=0; i<(int)numevents; ++i ) {
459 switch (ptrbuf[i].dwOfs) {
460 case DIMOFS_X:
461 if ( timestamp != ptrbuf[i].dwTimeStamp ) {
462 if ( xrel || yrel ) {
463 post_mouse_motion(1, xrel, yrel);
464 xrel = 0;
465 yrel = 0;
466 }
467 timestamp = ptrbuf[i].dwTimeStamp;
468 }
469 xrel += (Sint16)ptrbuf[i].dwData;
470 break;
471 case DIMOFS_Y:
472 if ( timestamp != ptrbuf[i].dwTimeStamp ) {
473 if ( xrel || yrel ) {
474 post_mouse_motion(1, xrel, yrel);
475 xrel = 0;
476 yrel = 0;
477 }
478 timestamp = ptrbuf[i].dwTimeStamp;
479 }
480 yrel += (Sint16)ptrbuf[i].dwData;
481 break;
482 case DIMOFS_Z:
483 if ( xrel || yrel ) {
484 post_mouse_motion(1, xrel, yrel);
485 xrel = 0;
486 yrel = 0;
487 }
488 timestamp = 0;
489 if((int)ptrbuf[i].dwData > 0)
490 button = SDL_BUTTON_WHEELUP;
491 else
492 button = SDL_BUTTON_WHEELDOWN;
493 posted = SDL_PrivateMouseButton(
494 SDL_PRESSED, button, 0, 0);
495 posted |= SDL_PrivateMouseButton(
496 SDL_RELEASED, button, 0, 0);
497 break;
498 case DIMOFS_BUTTON0:
499 case DIMOFS_BUTTON1:
500 case DIMOFS_BUTTON2:
501 case DIMOFS_BUTTON3:
502 #if DIRECTINPUT_VERSION >= 0x700
503 case DIMOFS_BUTTON4:
504 case DIMOFS_BUTTON5:
505 case DIMOFS_BUTTON6:
506 case DIMOFS_BUTTON7:
507 #endif
508 if ( xrel || yrel ) {
509 post_mouse_motion(1, xrel, yrel);
510 xrel = 0;
511 yrel = 0;
512 }
513 timestamp = 0;
514 button = (Uint8)(ptrbuf[i].dwOfs-DIMOFS_BUTTON0)+1;
515 /* Map DI button numbers to SDL */
516 switch ( button ) {
517 case 2: button = SDL_BUTTON_RIGHT; break;
518 case 3: button = SDL_BUTTON_MIDDLE; break;
519 case 4: button = SDL_BUTTON_X1; break;
520 case 5: button = SDL_BUTTON_X2; break;
521 default: break;
522 }
523 if ( ptrbuf[i].dwData & 0x80 ) {
524 /* Grab mouse so we get mouse-up */
525 if ( ++mouse_pressed > 0 ) {
526 SetCapture(SDL_Window);
527 }
528 state = SDL_PRESSED;
529 } else {
530 /* Release mouse after all mouse-ups */
531 if ( --mouse_pressed <= 0 ) {
532 ReleaseCapture();
533 mouse_pressed = 0;
534 }
535 state = SDL_RELEASED;
536 }
537 if ( mouse_buttons_swapped ) {
538 if ( button == 1 ) button = 3;
539 else
540 if ( button == 3 ) button = 1;
541 }
542 posted = SDL_PrivateMouseButton(state, button,
543 0, 0);
544 break;
545 }
546 }
547 if ( xrel || yrel ) {
548 post_mouse_motion(1, xrel, yrel);
549 }
550 }
551}
552
553/* The main Win32 event handler */
554LRESULT DX5_HandleMessage(_THIS, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
555{
556 switch (msg) {
557#ifdef WM_ACTIVATEAPP
558 case WM_ACTIVATEAPP: {
559 int i, active;
560
561 active = (wParam && (GetForegroundWindow() == hwnd));
562 if ( active ) {
563 for ( i=0; i<MAX_INPUTS; ++i ) {
564 if (SDL_DIdev[i] != NULL)
565 IDirectInputDevice2_Acquire(
566 SDL_DIdev[i]);
567 }
568 } else {
569 for ( i=0; i<MAX_INPUTS; ++i ) {
570 if (SDL_DIdev[i] != NULL)
571 IDirectInputDevice2_Unacquire(
572 SDL_DIdev[i]);
573 }
574 mouse_lost = 1;
575 }
576 }
577 break;
578#endif /* WM_ACTIVATEAPP */
579
580#ifdef WM_DISPLAYCHANGE
581 case WM_DISPLAYCHANGE: {
582 WPARAM BitsPerPixel;
583 WORD SizeX, SizeY;
584
585 /* Ack! The display changed size and/or depth! */
586 SizeX = LOWORD(lParam);
587 SizeY = HIWORD(lParam);
588 BitsPerPixel = wParam;
589 /* We cause this message when we go fullscreen */
590 }
591 break;
592#endif /* WM_DISPLAYCHANGE */
593
594 /* The keyboard is handled via DirectInput */
595 case WM_SYSKEYUP:
596 case WM_SYSKEYDOWN:
597 case WM_KEYUP:
598 case WM_KEYDOWN: {
599 /* Ignore windows keyboard messages */;
600 }
601 return(0);
602
603#if defined(SC_SCREENSAVE) || defined(SC_MONITORPOWER)
604 /* Don't allow screen savers or monitor power downs.
605 This is because they quietly clear DirectX surfaces.
606 It would be better to allow the application to
607 decide whether or not to blow these off, but the
608 semantics of SDL_PrivateSysWMEvent() don't allow
609 the application that choice.
610 */
611 case WM_SYSCOMMAND: {
612 if ((wParam&0xFFF0)==SC_SCREENSAVE ||
613 (wParam&0xFFF0)==SC_MONITORPOWER)
614 return(0);
615 }
616 /* Fall through to default processing */
617
618#endif /* SC_SCREENSAVE || SC_MONITORPOWER */
619
620 default: {
621 /* Only post the event if we're watching for it */
622 if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) {
623 SDL_SysWMmsg wmmsg;
624
625 SDL_VERSION(&wmmsg.version);
626 wmmsg.hwnd = hwnd;
627 wmmsg.msg = msg;
628 wmmsg.wParam = wParam;
629 wmmsg.lParam = lParam;
630 posted = SDL_PrivateSysWMEvent(&wmmsg);
631
632 /* DJM: If the user isn't watching for private
633 messages in her SDL event loop, then pass it
634 along to any win32 specific window proc.
635 */
636 } else if (userWindowProc) {
637 return CallWindowProc(userWindowProc, hwnd, msg, wParam, lParam);
638 }
639 }
640 break;
641 }
642 return(DefWindowProc(hwnd, msg, wParam, lParam));
643}
644
645/* This function checks the windows message queue and DirectInput and returns
646 1 if there was input, 0 if there was no input, or -1 if the application has
647 posted a quit message.
648*/
649static int DX5_CheckInput(_THIS, int timeout, BOOL processInput)
650{
651 MSG msg;
652 int i;
653 HRESULT result;
654 DWORD event;
655
656 /* Check the normal windows queue (highest preference) */
657 posted = 0;
658 while ( ! posted &&
659 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) ) {
660 if ( GetMessage(&msg, NULL, 0, 0) > 0 ) {
661 DispatchMessage(&msg);
662 } else {
663 return(-1);
664 }
665 }
666 if ( posted ) {
667 return(1);
668 }
669
670 /* Pump the DirectInput flow */
671 if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) {
672 for ( i=0; i<MAX_INPUTS; ++i ) {
673 if ( SDL_DIdev[i] != NULL ) {
674 result = IDirectInputDevice2_Poll(SDL_DIdev[i]);
675 if ( (result == DIERR_INPUTLOST) ||
676 (result == DIERR_NOTACQUIRED) ) {
677 if ( SDL_strcmp(inputs[i].name, "mouse") == 0 ) {
678 mouse_lost = 1;
679 }
680 IDirectInputDevice2_Acquire(SDL_DIdev[i]);
681 IDirectInputDevice2_Poll(SDL_DIdev[i]);
682 }
683 }
684 }
685 }
686
687 /* Wait for messages and input events */
688 event = MsgWaitForMultipleObjects(SDL_DIndev, SDL_DIevt, FALSE,
689 timeout, QS_ALLEVENTS);
690 if ((event >= WAIT_OBJECT_0) && (event < (WAIT_OBJECT_0+SDL_DIndev))) {
691 DWORD numevents;
692 static DIDEVICEOBJECTDATA evtbuf[INPUT_QSIZE];
693
694 event -= WAIT_OBJECT_0;
695 numevents = INPUT_QSIZE;
696 result = IDirectInputDevice2_GetDeviceData(
697 SDL_DIdev[event], sizeof(DIDEVICEOBJECTDATA),
698 evtbuf, &numevents, 0);
699 if ( (result == DIERR_INPUTLOST) ||
700 (result == DIERR_NOTACQUIRED) ) {
701 if ( SDL_strcmp(inputs[event].name, "mouse") == 0 ) {
702 mouse_lost = 1;
703 }
704 IDirectInputDevice2_Acquire(SDL_DIdev[event]);
705 result = IDirectInputDevice2_GetDeviceData(
706 SDL_DIdev[event], sizeof(DIDEVICEOBJECTDATA),
707 evtbuf, &numevents, 0);
708 }
709 /* Handle the events */
710 if ( result == DI_OK && processInput ) {
711 /* Note: This can post multiple events to event queue
712 */
713 (*SDL_DIfun[event])((int)numevents, evtbuf);
714 return(1);
715 }
716 }
717 if ( event != WAIT_TIMEOUT ) {
718 /* Maybe there was a windows message? */
719 if ( PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) ) {
720 if ( GetMessage(&msg, NULL, 0, 0) > 0 ) {
721 DispatchMessage(&msg);
722 } else {
723 return(-1);
724 }
725 return(1);
726 }
727 }
728 return(0);
729}
730
731/* Change cooperative level based on whether or not we are fullscreen */
732void DX5_DInputReset(_THIS, int fullscreen)
733{
734 DWORD level;
735 int i;
736 HRESULT result;
737 HWND topwnd;
738
739 for ( i=0; i<MAX_INPUTS; ++i ) {
740 if ( SDL_DIdev[i] != NULL ) {
741 if ( fullscreen ) {
742 level = inputs[i].raw_level;
743 } else {
744 level = inputs[i].win_level;
745 }
746 IDirectInputDevice2_Unacquire(SDL_DIdev[i]);
747 topwnd = GetTopLevelParent(SDL_Window);
748 result = IDirectInputDevice2_SetCooperativeLevel(
749 SDL_DIdev[i], topwnd, level);
750 IDirectInputDevice2_Acquire(SDL_DIdev[i]);
751 if ( result != DI_OK ) {
752 SetDIerror(
753 "DirectInputDevice::SetCooperativeLevel", result);
754 }
755 }
756 }
757 mouse_lost = 1;
758
759 /* Flush pending input */
760 DX5_CheckInput(this, 0, FALSE);
761}
762
763void DX5_PumpEvents(_THIS)
764{
765 /* Wait for messages and DirectInput */
766 while ( DX5_CheckInput(this, 0, TRUE) > 0 ) {
767 /* Loop and check again */;
768 }
769}
770
771void DX5_InitOSKeymap(_THIS)
772{
773#ifndef DIK_PAUSE
774#define DIK_PAUSE 0xC5
775#endif
776#ifndef DIK_OEM_102
777#define DIK_OEM_102 0x56 /* < > | on UK/Germany keyboards */
778#endif
779 int i;
780
781 /* Map the DIK scancodes to SDL keysyms */
782 for ( i=0; i<SDL_arraysize(DIK_keymap); ++i )
783 DIK_keymap[i] = 0;
784
785 /* Defined DIK_* constants */
786 DIK_keymap[DIK_ESCAPE] = SDLK_ESCAPE;
787 DIK_keymap[DIK_1] = SDLK_1;
788 DIK_keymap[DIK_2] = SDLK_2;
789 DIK_keymap[DIK_3] = SDLK_3;
790 DIK_keymap[DIK_4] = SDLK_4;
791 DIK_keymap[DIK_5] = SDLK_5;
792 DIK_keymap[DIK_6] = SDLK_6;
793 DIK_keymap[DIK_7] = SDLK_7;
794 DIK_keymap[DIK_8] = SDLK_8;
795 DIK_keymap[DIK_9] = SDLK_9;
796 DIK_keymap[DIK_0] = SDLK_0;
797 DIK_keymap[DIK_MINUS] = SDLK_MINUS;
798 DIK_keymap[DIK_EQUALS] = SDLK_EQUALS;
799 DIK_keymap[DIK_BACK] = SDLK_BACKSPACE;
800 DIK_keymap[DIK_TAB] = SDLK_TAB;
801 DIK_keymap[DIK_Q] = SDLK_q;
802 DIK_keymap[DIK_W] = SDLK_w;
803 DIK_keymap[DIK_E] = SDLK_e;
804 DIK_keymap[DIK_R] = SDLK_r;
805 DIK_keymap[DIK_T] = SDLK_t;
806 DIK_keymap[DIK_Y] = SDLK_y;
807 DIK_keymap[DIK_U] = SDLK_u;
808 DIK_keymap[DIK_I] = SDLK_i;
809 DIK_keymap[DIK_O] = SDLK_o;
810 DIK_keymap[DIK_P] = SDLK_p;
811 DIK_keymap[DIK_LBRACKET] = SDLK_LEFTBRACKET;
812 DIK_keymap[DIK_RBRACKET] = SDLK_RIGHTBRACKET;
813 DIK_keymap[DIK_RETURN] = SDLK_RETURN;
814 DIK_keymap[DIK_LCONTROL] = SDLK_LCTRL;
815 DIK_keymap[DIK_A] = SDLK_a;
816 DIK_keymap[DIK_S] = SDLK_s;
817 DIK_keymap[DIK_D] = SDLK_d;
818 DIK_keymap[DIK_F] = SDLK_f;
819 DIK_keymap[DIK_G] = SDLK_g;
820 DIK_keymap[DIK_H] = SDLK_h;
821 DIK_keymap[DIK_J] = SDLK_j;
822 DIK_keymap[DIK_K] = SDLK_k;
823 DIK_keymap[DIK_L] = SDLK_l;
824 DIK_keymap[DIK_SEMICOLON] = SDLK_SEMICOLON;
825 DIK_keymap[DIK_APOSTROPHE] = SDLK_QUOTE;
826 DIK_keymap[DIK_GRAVE] = SDLK_BACKQUOTE;
827 DIK_keymap[DIK_LSHIFT] = SDLK_LSHIFT;
828 DIK_keymap[DIK_BACKSLASH] = SDLK_BACKSLASH;
829 DIK_keymap[DIK_OEM_102] = SDLK_LESS;
830 DIK_keymap[DIK_Z] = SDLK_z;
831 DIK_keymap[DIK_X] = SDLK_x;
832 DIK_keymap[DIK_C] = SDLK_c;
833 DIK_keymap[DIK_V] = SDLK_v;
834 DIK_keymap[DIK_B] = SDLK_b;
835 DIK_keymap[DIK_N] = SDLK_n;
836 DIK_keymap[DIK_M] = SDLK_m;
837 DIK_keymap[DIK_COMMA] = SDLK_COMMA;
838 DIK_keymap[DIK_PERIOD] = SDLK_PERIOD;
839 DIK_keymap[DIK_SLASH] = SDLK_SLASH;
840 DIK_keymap[DIK_RSHIFT] = SDLK_RSHIFT;
841 DIK_keymap[DIK_MULTIPLY] = SDLK_KP_MULTIPLY;
842 DIK_keymap[DIK_LMENU] = SDLK_LALT;
843 DIK_keymap[DIK_SPACE] = SDLK_SPACE;
844 DIK_keymap[DIK_CAPITAL] = SDLK_CAPSLOCK;
845 DIK_keymap[DIK_F1] = SDLK_F1;
846 DIK_keymap[DIK_F2] = SDLK_F2;
847 DIK_keymap[DIK_F3] = SDLK_F3;
848 DIK_keymap[DIK_F4] = SDLK_F4;
849 DIK_keymap[DIK_F5] = SDLK_F5;
850 DIK_keymap[DIK_F6] = SDLK_F6;
851 DIK_keymap[DIK_F7] = SDLK_F7;
852 DIK_keymap[DIK_F8] = SDLK_F8;
853 DIK_keymap[DIK_F9] = SDLK_F9;
854 DIK_keymap[DIK_F10] = SDLK_F10;
855 DIK_keymap[DIK_NUMLOCK] = SDLK_NUMLOCK;
856 DIK_keymap[DIK_SCROLL] = SDLK_SCROLLOCK;
857 DIK_keymap[DIK_NUMPAD7] = SDLK_KP7;
858 DIK_keymap[DIK_NUMPAD8] = SDLK_KP8;
859 DIK_keymap[DIK_NUMPAD9] = SDLK_KP9;
860 DIK_keymap[DIK_SUBTRACT] = SDLK_KP_MINUS;
861 DIK_keymap[DIK_NUMPAD4] = SDLK_KP4;
862 DIK_keymap[DIK_NUMPAD5] = SDLK_KP5;
863 DIK_keymap[DIK_NUMPAD6] = SDLK_KP6;
864 DIK_keymap[DIK_ADD] = SDLK_KP_PLUS;
865 DIK_keymap[DIK_NUMPAD1] = SDLK_KP1;
866 DIK_keymap[DIK_NUMPAD2] = SDLK_KP2;
867 DIK_keymap[DIK_NUMPAD3] = SDLK_KP3;
868 DIK_keymap[DIK_NUMPAD0] = SDLK_KP0;
869 DIK_keymap[DIK_DECIMAL] = SDLK_KP_PERIOD;
870 DIK_keymap[DIK_F11] = SDLK_F11;
871 DIK_keymap[DIK_F12] = SDLK_F12;
872
873 DIK_keymap[DIK_F13] = SDLK_F13;
874 DIK_keymap[DIK_F14] = SDLK_F14;
875 DIK_keymap[DIK_F15] = SDLK_F15;
876
877 DIK_keymap[DIK_NUMPADEQUALS] = SDLK_KP_EQUALS;
878 DIK_keymap[DIK_NUMPADENTER] = SDLK_KP_ENTER;
879 DIK_keymap[DIK_RCONTROL] = SDLK_RCTRL;
880 DIK_keymap[DIK_DIVIDE] = SDLK_KP_DIVIDE;
881 DIK_keymap[DIK_SYSRQ] = SDLK_PRINT;
882 DIK_keymap[DIK_RMENU] = SDLK_RALT;
883 DIK_keymap[DIK_PAUSE] = SDLK_PAUSE;
884 DIK_keymap[DIK_HOME] = SDLK_HOME;
885 DIK_keymap[DIK_UP] = SDLK_UP;
886 DIK_keymap[DIK_PRIOR] = SDLK_PAGEUP;
887 DIK_keymap[DIK_LEFT] = SDLK_LEFT;
888 DIK_keymap[DIK_RIGHT] = SDLK_RIGHT;
889 DIK_keymap[DIK_END] = SDLK_END;
890 DIK_keymap[DIK_DOWN] = SDLK_DOWN;
891 DIK_keymap[DIK_NEXT] = SDLK_PAGEDOWN;
892 DIK_keymap[DIK_INSERT] = SDLK_INSERT;
893 DIK_keymap[DIK_DELETE] = SDLK_DELETE;
894 DIK_keymap[DIK_LWIN] = SDLK_LMETA;
895 DIK_keymap[DIK_RWIN] = SDLK_RMETA;
896 DIK_keymap[DIK_APPS] = SDLK_MENU;
897}
898
899static SDL_keysym *TranslateKey(UINT scancode, SDL_keysym *keysym, int pressed)
900{
901 /* Set the keysym information */
902 keysym->scancode = (unsigned char)scancode;
903 keysym->sym = DIK_keymap[scancode];
904 keysym->mod = KMOD_NONE;
905 keysym->unicode = 0;
906 if ( pressed && SDL_TranslateUNICODE ) {
907 UINT vkey;
908#ifndef NO_GETKEYBOARDSTATE
909 BYTE keystate[256];
910 Uint16 wchars[2];
911#endif
912
913 vkey = MapVirtualKey(scancode, 1);
914#ifdef NO_GETKEYBOARDSTATE
915 /* Uh oh, better hope the vkey is close enough.. */
916 keysym->unicode = vkey;
917#else
918 GetKeyboardState(keystate);
919 /* Numlock isn't taken into account in ToUnicode,
920 * so we handle it as a special case here */
921 if ((keystate[VK_NUMLOCK] & 1) && vkey >= VK_NUMPAD0 && vkey <= VK_NUMPAD9)
922 {
923 keysym->unicode = vkey - VK_NUMPAD0 + '0';
924 }
925 else if (SDL_ToUnicode(vkey, scancode, keystate, wchars, sizeof(wchars)/sizeof(wchars[0]), 0) > 0)
926 {
927 keysym->unicode = wchars[0];
928 }
929#endif /* NO_GETKEYBOARDSTATE */
930 }
931 return(keysym);
932}
933
934int DX5_CreateWindow(_THIS)
935{
936 char *windowid = SDL_getenv("SDL_WINDOWID");
937 int i;
938
939 /* Clear out DirectInput variables in case we fail */
940 for ( i=0; i<MAX_INPUTS; ++i ) {
941 SDL_DIdev[i] = NULL;
942 SDL_DIevt[i] = NULL;
943 SDL_DIfun[i] = NULL;
944 }
945
946 SDL_RegisterApp(NULL, 0, 0);
947
948 SDL_windowid = (windowid != NULL);
949 if ( SDL_windowid ) {
950 SDL_Window = (HWND)((size_t)SDL_strtoull(windowid, NULL, 0));
951 if ( SDL_Window == NULL ) {
952 SDL_SetError("Couldn't get user specified window");
953 return(-1);
954 }
955
956 /* DJM: we want all event's for the user specified
957 window to be handled by SDL.
958 */
959 userWindowProc = (WNDPROCTYPE)GetWindowLongPtr(SDL_Window, GWLP_WNDPROC);
960 SetWindowLongPtr(SDL_Window, GWLP_WNDPROC, (LONG_PTR)WinMessage);
961 } else {
962 SDL_Window = CreateWindow(SDL_Appname, SDL_Appname,
963 (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX),
964 CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, NULL, NULL, SDL_Instance, NULL);
965 if ( SDL_Window == NULL ) {
966 SDL_SetError("Couldn't create window");
967 return(-1);
968 }
969 ShowWindow(SDL_Window, SW_HIDE);
970 }
971
972 /* Initialize DirectInput */
973 if ( DX5_DInputInit(this) < 0 ) {
974 return(-1);
975 }
976
977 /* JC 14 Mar 2006
978 Flush the message loop or this can cause big problems later
979 Especially if the user decides to use dialog boxes or assert()!
980 */
981 WIN_FlushMessageQueue();
982
983 /* Ready to roll */
984 return(0);
985}
986
987void DX5_DestroyWindow(_THIS)
988{
989 /* Close down DirectInput */
990 DX5_DInputQuit(this);
991
992 /* Destroy our window */
993 if ( SDL_windowid ) {
994 SetWindowLongPtr(SDL_Window, GWLP_WNDPROC, (LONG_PTR)userWindowProc);
995 } else {
996 DestroyWindow(SDL_Window);
997 }
998 SDL_UnregisterApp();
999
1000 /* JC 14 Mar 2006
1001 Flush the message loop or this can cause big problems later
1002 Especially if the user decides to use dialog boxes or assert()!
1003 */
1004 WIN_FlushMessageQueue();
1005}
diff --git a/apps/plugins/sdl/src/video/windx5/SDL_dx5events_c.h b/apps/plugins/sdl/src/video/windx5/SDL_dx5events_c.h
deleted file mode 100644
index 28e1b6c03e..0000000000
--- a/apps/plugins/sdl/src/video/windx5/SDL_dx5events_c.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "../wincommon/SDL_lowvideo.h"
25
26/* Variables and functions exported by SDL_dx5events.c to other parts
27 of the native video subsystem (SDL_dx5video.c)
28*/
29extern LONG
30 DX5_HandleMessage(_THIS, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
31extern int DX5_CreateWindow(_THIS);
32extern void DX5_DestroyWindow(_THIS);
33
34extern void DX5_PumpEvents(_THIS);
35extern void DX5_InitOSKeymap(_THIS);
36extern void DX5_DInputReset(_THIS, int fullscreen);
37
diff --git a/apps/plugins/sdl/src/video/windx5/SDL_dx5video.c b/apps/plugins/sdl/src/video/windx5/SDL_dx5video.c
deleted file mode 100644
index f80ca97b07..0000000000
--- a/apps/plugins/sdl/src/video/windx5/SDL_dx5video.c
+++ /dev/null
@@ -1,2537 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "directx.h"
25
26/* Not yet in the mingw32 cross-compile headers */
27#ifndef CDS_FULLSCREEN
28#define CDS_FULLSCREEN 4
29#endif
30
31#include "SDL_timer.h"
32#include "SDL_events.h"
33#include "SDL_syswm.h"
34#include "../SDL_sysvideo.h"
35#include "../SDL_blit.h"
36#include "../SDL_pixels_c.h"
37#include "SDL_dx5video.h"
38#include "../wincommon/SDL_syswm_c.h"
39#include "../wincommon/SDL_sysmouse_c.h"
40#include "SDL_dx5events_c.h"
41#include "SDL_dx5yuv_c.h"
42#include "../wincommon/SDL_wingl_c.h"
43
44#ifdef _WIN32_WCE
45#define NO_CHANGEDISPLAYSETTINGS
46#endif
47#ifndef WS_MAXIMIZE
48#define WS_MAXIMIZE 0
49#endif
50#ifndef SWP_NOCOPYBITS
51#define SWP_NOCOPYBITS 0
52#endif
53#ifndef PC_NOCOLLAPSE
54#define PC_NOCOLLAPSE 0
55#endif
56
57
58/* DirectX function pointers for video and events */
59HRESULT (WINAPI *DDrawCreate)( GUID FAR *lpGUID, LPDIRECTDRAW FAR *lplpDD, IUnknown FAR *pUnkOuter );
60HRESULT (WINAPI *DInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT *ppDI, LPUNKNOWN punkOuter);
61
62/* This is the rect EnumModes2 uses */
63struct DX5EnumRect {
64 SDL_Rect r;
65 int refreshRate;
66 struct DX5EnumRect* next;
67};
68static struct DX5EnumRect *enumlists[NUM_MODELISTS];
69
70/*
71 * Experimentally determined values for c_cfDI* constants used in DirectX 5.0
72 */
73
74/* Keyboard */
75
76static DIOBJECTDATAFORMAT KBD_fmt[] = {
77 { &GUID_Key, 0, 0x8000000C, 0x00000000 },
78 { &GUID_Key, 1, 0x8000010C, 0x00000000 },
79 { &GUID_Key, 2, 0x8000020C, 0x00000000 },
80 { &GUID_Key, 3, 0x8000030C, 0x00000000 },
81 { &GUID_Key, 4, 0x8000040C, 0x00000000 },
82 { &GUID_Key, 5, 0x8000050C, 0x00000000 },
83 { &GUID_Key, 6, 0x8000060C, 0x00000000 },
84 { &GUID_Key, 7, 0x8000070C, 0x00000000 },
85 { &GUID_Key, 8, 0x8000080C, 0x00000000 },
86 { &GUID_Key, 9, 0x8000090C, 0x00000000 },
87 { &GUID_Key, 10, 0x80000A0C, 0x00000000 },
88 { &GUID_Key, 11, 0x80000B0C, 0x00000000 },
89 { &GUID_Key, 12, 0x80000C0C, 0x00000000 },
90 { &GUID_Key, 13, 0x80000D0C, 0x00000000 },
91 { &GUID_Key, 14, 0x80000E0C, 0x00000000 },
92 { &GUID_Key, 15, 0x80000F0C, 0x00000000 },
93 { &GUID_Key, 16, 0x8000100C, 0x00000000 },
94 { &GUID_Key, 17, 0x8000110C, 0x00000000 },
95 { &GUID_Key, 18, 0x8000120C, 0x00000000 },
96 { &GUID_Key, 19, 0x8000130C, 0x00000000 },
97 { &GUID_Key, 20, 0x8000140C, 0x00000000 },
98 { &GUID_Key, 21, 0x8000150C, 0x00000000 },
99 { &GUID_Key, 22, 0x8000160C, 0x00000000 },
100 { &GUID_Key, 23, 0x8000170C, 0x00000000 },
101 { &GUID_Key, 24, 0x8000180C, 0x00000000 },
102 { &GUID_Key, 25, 0x8000190C, 0x00000000 },
103 { &GUID_Key, 26, 0x80001A0C, 0x00000000 },
104 { &GUID_Key, 27, 0x80001B0C, 0x00000000 },
105 { &GUID_Key, 28, 0x80001C0C, 0x00000000 },
106 { &GUID_Key, 29, 0x80001D0C, 0x00000000 },
107 { &GUID_Key, 30, 0x80001E0C, 0x00000000 },
108 { &GUID_Key, 31, 0x80001F0C, 0x00000000 },
109 { &GUID_Key, 32, 0x8000200C, 0x00000000 },
110 { &GUID_Key, 33, 0x8000210C, 0x00000000 },
111 { &GUID_Key, 34, 0x8000220C, 0x00000000 },
112 { &GUID_Key, 35, 0x8000230C, 0x00000000 },
113 { &GUID_Key, 36, 0x8000240C, 0x00000000 },
114 { &GUID_Key, 37, 0x8000250C, 0x00000000 },
115 { &GUID_Key, 38, 0x8000260C, 0x00000000 },
116 { &GUID_Key, 39, 0x8000270C, 0x00000000 },
117 { &GUID_Key, 40, 0x8000280C, 0x00000000 },
118 { &GUID_Key, 41, 0x8000290C, 0x00000000 },
119 { &GUID_Key, 42, 0x80002A0C, 0x00000000 },
120 { &GUID_Key, 43, 0x80002B0C, 0x00000000 },
121 { &GUID_Key, 44, 0x80002C0C, 0x00000000 },
122 { &GUID_Key, 45, 0x80002D0C, 0x00000000 },
123 { &GUID_Key, 46, 0x80002E0C, 0x00000000 },
124 { &GUID_Key, 47, 0x80002F0C, 0x00000000 },
125 { &GUID_Key, 48, 0x8000300C, 0x00000000 },
126 { &GUID_Key, 49, 0x8000310C, 0x00000000 },
127 { &GUID_Key, 50, 0x8000320C, 0x00000000 },
128 { &GUID_Key, 51, 0x8000330C, 0x00000000 },
129 { &GUID_Key, 52, 0x8000340C, 0x00000000 },
130 { &GUID_Key, 53, 0x8000350C, 0x00000000 },
131 { &GUID_Key, 54, 0x8000360C, 0x00000000 },
132 { &GUID_Key, 55, 0x8000370C, 0x00000000 },
133 { &GUID_Key, 56, 0x8000380C, 0x00000000 },
134 { &GUID_Key, 57, 0x8000390C, 0x00000000 },
135 { &GUID_Key, 58, 0x80003A0C, 0x00000000 },
136 { &GUID_Key, 59, 0x80003B0C, 0x00000000 },
137 { &GUID_Key, 60, 0x80003C0C, 0x00000000 },
138 { &GUID_Key, 61, 0x80003D0C, 0x00000000 },
139 { &GUID_Key, 62, 0x80003E0C, 0x00000000 },
140 { &GUID_Key, 63, 0x80003F0C, 0x00000000 },
141 { &GUID_Key, 64, 0x8000400C, 0x00000000 },
142 { &GUID_Key, 65, 0x8000410C, 0x00000000 },
143 { &GUID_Key, 66, 0x8000420C, 0x00000000 },
144 { &GUID_Key, 67, 0x8000430C, 0x00000000 },
145 { &GUID_Key, 68, 0x8000440C, 0x00000000 },
146 { &GUID_Key, 69, 0x8000450C, 0x00000000 },
147 { &GUID_Key, 70, 0x8000460C, 0x00000000 },
148 { &GUID_Key, 71, 0x8000470C, 0x00000000 },
149 { &GUID_Key, 72, 0x8000480C, 0x00000000 },
150 { &GUID_Key, 73, 0x8000490C, 0x00000000 },
151 { &GUID_Key, 74, 0x80004A0C, 0x00000000 },
152 { &GUID_Key, 75, 0x80004B0C, 0x00000000 },
153 { &GUID_Key, 76, 0x80004C0C, 0x00000000 },
154 { &GUID_Key, 77, 0x80004D0C, 0x00000000 },
155 { &GUID_Key, 78, 0x80004E0C, 0x00000000 },
156 { &GUID_Key, 79, 0x80004F0C, 0x00000000 },
157 { &GUID_Key, 80, 0x8000500C, 0x00000000 },
158 { &GUID_Key, 81, 0x8000510C, 0x00000000 },
159 { &GUID_Key, 82, 0x8000520C, 0x00000000 },
160 { &GUID_Key, 83, 0x8000530C, 0x00000000 },
161 { &GUID_Key, 84, 0x8000540C, 0x00000000 },
162 { &GUID_Key, 85, 0x8000550C, 0x00000000 },
163 { &GUID_Key, 86, 0x8000560C, 0x00000000 },
164 { &GUID_Key, 87, 0x8000570C, 0x00000000 },
165 { &GUID_Key, 88, 0x8000580C, 0x00000000 },
166 { &GUID_Key, 89, 0x8000590C, 0x00000000 },
167 { &GUID_Key, 90, 0x80005A0C, 0x00000000 },
168 { &GUID_Key, 91, 0x80005B0C, 0x00000000 },
169 { &GUID_Key, 92, 0x80005C0C, 0x00000000 },
170 { &GUID_Key, 93, 0x80005D0C, 0x00000000 },
171 { &GUID_Key, 94, 0x80005E0C, 0x00000000 },
172 { &GUID_Key, 95, 0x80005F0C, 0x00000000 },
173 { &GUID_Key, 96, 0x8000600C, 0x00000000 },
174 { &GUID_Key, 97, 0x8000610C, 0x00000000 },
175 { &GUID_Key, 98, 0x8000620C, 0x00000000 },
176 { &GUID_Key, 99, 0x8000630C, 0x00000000 },
177 { &GUID_Key, 100, 0x8000640C, 0x00000000 },
178 { &GUID_Key, 101, 0x8000650C, 0x00000000 },
179 { &GUID_Key, 102, 0x8000660C, 0x00000000 },
180 { &GUID_Key, 103, 0x8000670C, 0x00000000 },
181 { &GUID_Key, 104, 0x8000680C, 0x00000000 },
182 { &GUID_Key, 105, 0x8000690C, 0x00000000 },
183 { &GUID_Key, 106, 0x80006A0C, 0x00000000 },
184 { &GUID_Key, 107, 0x80006B0C, 0x00000000 },
185 { &GUID_Key, 108, 0x80006C0C, 0x00000000 },
186 { &GUID_Key, 109, 0x80006D0C, 0x00000000 },
187 { &GUID_Key, 110, 0x80006E0C, 0x00000000 },
188 { &GUID_Key, 111, 0x80006F0C, 0x00000000 },
189 { &GUID_Key, 112, 0x8000700C, 0x00000000 },
190 { &GUID_Key, 113, 0x8000710C, 0x00000000 },
191 { &GUID_Key, 114, 0x8000720C, 0x00000000 },
192 { &GUID_Key, 115, 0x8000730C, 0x00000000 },
193 { &GUID_Key, 116, 0x8000740C, 0x00000000 },
194 { &GUID_Key, 117, 0x8000750C, 0x00000000 },
195 { &GUID_Key, 118, 0x8000760C, 0x00000000 },
196 { &GUID_Key, 119, 0x8000770C, 0x00000000 },
197 { &GUID_Key, 120, 0x8000780C, 0x00000000 },
198 { &GUID_Key, 121, 0x8000790C, 0x00000000 },
199 { &GUID_Key, 122, 0x80007A0C, 0x00000000 },
200 { &GUID_Key, 123, 0x80007B0C, 0x00000000 },
201 { &GUID_Key, 124, 0x80007C0C, 0x00000000 },
202 { &GUID_Key, 125, 0x80007D0C, 0x00000000 },
203 { &GUID_Key, 126, 0x80007E0C, 0x00000000 },
204 { &GUID_Key, 127, 0x80007F0C, 0x00000000 },
205 { &GUID_Key, 128, 0x8000800C, 0x00000000 },
206 { &GUID_Key, 129, 0x8000810C, 0x00000000 },
207 { &GUID_Key, 130, 0x8000820C, 0x00000000 },
208 { &GUID_Key, 131, 0x8000830C, 0x00000000 },
209 { &GUID_Key, 132, 0x8000840C, 0x00000000 },
210 { &GUID_Key, 133, 0x8000850C, 0x00000000 },
211 { &GUID_Key, 134, 0x8000860C, 0x00000000 },
212 { &GUID_Key, 135, 0x8000870C, 0x00000000 },
213 { &GUID_Key, 136, 0x8000880C, 0x00000000 },
214 { &GUID_Key, 137, 0x8000890C, 0x00000000 },
215 { &GUID_Key, 138, 0x80008A0C, 0x00000000 },
216 { &GUID_Key, 139, 0x80008B0C, 0x00000000 },
217 { &GUID_Key, 140, 0x80008C0C, 0x00000000 },
218 { &GUID_Key, 141, 0x80008D0C, 0x00000000 },
219 { &GUID_Key, 142, 0x80008E0C, 0x00000000 },
220 { &GUID_Key, 143, 0x80008F0C, 0x00000000 },
221 { &GUID_Key, 144, 0x8000900C, 0x00000000 },
222 { &GUID_Key, 145, 0x8000910C, 0x00000000 },
223 { &GUID_Key, 146, 0x8000920C, 0x00000000 },
224 { &GUID_Key, 147, 0x8000930C, 0x00000000 },
225 { &GUID_Key, 148, 0x8000940C, 0x00000000 },
226 { &GUID_Key, 149, 0x8000950C, 0x00000000 },
227 { &GUID_Key, 150, 0x8000960C, 0x00000000 },
228 { &GUID_Key, 151, 0x8000970C, 0x00000000 },
229 { &GUID_Key, 152, 0x8000980C, 0x00000000 },
230 { &GUID_Key, 153, 0x8000990C, 0x00000000 },
231 { &GUID_Key, 154, 0x80009A0C, 0x00000000 },
232 { &GUID_Key, 155, 0x80009B0C, 0x00000000 },
233 { &GUID_Key, 156, 0x80009C0C, 0x00000000 },
234 { &GUID_Key, 157, 0x80009D0C, 0x00000000 },
235 { &GUID_Key, 158, 0x80009E0C, 0x00000000 },
236 { &GUID_Key, 159, 0x80009F0C, 0x00000000 },
237 { &GUID_Key, 160, 0x8000A00C, 0x00000000 },
238 { &GUID_Key, 161, 0x8000A10C, 0x00000000 },
239 { &GUID_Key, 162, 0x8000A20C, 0x00000000 },
240 { &GUID_Key, 163, 0x8000A30C, 0x00000000 },
241 { &GUID_Key, 164, 0x8000A40C, 0x00000000 },
242 { &GUID_Key, 165, 0x8000A50C, 0x00000000 },
243 { &GUID_Key, 166, 0x8000A60C, 0x00000000 },
244 { &GUID_Key, 167, 0x8000A70C, 0x00000000 },
245 { &GUID_Key, 168, 0x8000A80C, 0x00000000 },
246 { &GUID_Key, 169, 0x8000A90C, 0x00000000 },
247 { &GUID_Key, 170, 0x8000AA0C, 0x00000000 },
248 { &GUID_Key, 171, 0x8000AB0C, 0x00000000 },
249 { &GUID_Key, 172, 0x8000AC0C, 0x00000000 },
250 { &GUID_Key, 173, 0x8000AD0C, 0x00000000 },
251 { &GUID_Key, 174, 0x8000AE0C, 0x00000000 },
252 { &GUID_Key, 175, 0x8000AF0C, 0x00000000 },
253 { &GUID_Key, 176, 0x8000B00C, 0x00000000 },
254 { &GUID_Key, 177, 0x8000B10C, 0x00000000 },
255 { &GUID_Key, 178, 0x8000B20C, 0x00000000 },
256 { &GUID_Key, 179, 0x8000B30C, 0x00000000 },
257 { &GUID_Key, 180, 0x8000B40C, 0x00000000 },
258 { &GUID_Key, 181, 0x8000B50C, 0x00000000 },
259 { &GUID_Key, 182, 0x8000B60C, 0x00000000 },
260 { &GUID_Key, 183, 0x8000B70C, 0x00000000 },
261 { &GUID_Key, 184, 0x8000B80C, 0x00000000 },
262 { &GUID_Key, 185, 0x8000B90C, 0x00000000 },
263 { &GUID_Key, 186, 0x8000BA0C, 0x00000000 },
264 { &GUID_Key, 187, 0x8000BB0C, 0x00000000 },
265 { &GUID_Key, 188, 0x8000BC0C, 0x00000000 },
266 { &GUID_Key, 189, 0x8000BD0C, 0x00000000 },
267 { &GUID_Key, 190, 0x8000BE0C, 0x00000000 },
268 { &GUID_Key, 191, 0x8000BF0C, 0x00000000 },
269 { &GUID_Key, 192, 0x8000C00C, 0x00000000 },
270 { &GUID_Key, 193, 0x8000C10C, 0x00000000 },
271 { &GUID_Key, 194, 0x8000C20C, 0x00000000 },
272 { &GUID_Key, 195, 0x8000C30C, 0x00000000 },
273 { &GUID_Key, 196, 0x8000C40C, 0x00000000 },
274 { &GUID_Key, 197, 0x8000C50C, 0x00000000 },
275 { &GUID_Key, 198, 0x8000C60C, 0x00000000 },
276 { &GUID_Key, 199, 0x8000C70C, 0x00000000 },
277 { &GUID_Key, 200, 0x8000C80C, 0x00000000 },
278 { &GUID_Key, 201, 0x8000C90C, 0x00000000 },
279 { &GUID_Key, 202, 0x8000CA0C, 0x00000000 },
280 { &GUID_Key, 203, 0x8000CB0C, 0x00000000 },
281 { &GUID_Key, 204, 0x8000CC0C, 0x00000000 },
282 { &GUID_Key, 205, 0x8000CD0C, 0x00000000 },
283 { &GUID_Key, 206, 0x8000CE0C, 0x00000000 },
284 { &GUID_Key, 207, 0x8000CF0C, 0x00000000 },
285 { &GUID_Key, 208, 0x8000D00C, 0x00000000 },
286 { &GUID_Key, 209, 0x8000D10C, 0x00000000 },
287 { &GUID_Key, 210, 0x8000D20C, 0x00000000 },
288 { &GUID_Key, 211, 0x8000D30C, 0x00000000 },
289 { &GUID_Key, 212, 0x8000D40C, 0x00000000 },
290 { &GUID_Key, 213, 0x8000D50C, 0x00000000 },
291 { &GUID_Key, 214, 0x8000D60C, 0x00000000 },
292 { &GUID_Key, 215, 0x8000D70C, 0x00000000 },
293 { &GUID_Key, 216, 0x8000D80C, 0x00000000 },
294 { &GUID_Key, 217, 0x8000D90C, 0x00000000 },
295 { &GUID_Key, 218, 0x8000DA0C, 0x00000000 },
296 { &GUID_Key, 219, 0x8000DB0C, 0x00000000 },
297 { &GUID_Key, 220, 0x8000DC0C, 0x00000000 },
298 { &GUID_Key, 221, 0x8000DD0C, 0x00000000 },
299 { &GUID_Key, 222, 0x8000DE0C, 0x00000000 },
300 { &GUID_Key, 223, 0x8000DF0C, 0x00000000 },
301 { &GUID_Key, 224, 0x8000E00C, 0x00000000 },
302 { &GUID_Key, 225, 0x8000E10C, 0x00000000 },
303 { &GUID_Key, 226, 0x8000E20C, 0x00000000 },
304 { &GUID_Key, 227, 0x8000E30C, 0x00000000 },
305 { &GUID_Key, 228, 0x8000E40C, 0x00000000 },
306 { &GUID_Key, 229, 0x8000E50C, 0x00000000 },
307 { &GUID_Key, 230, 0x8000E60C, 0x00000000 },
308 { &GUID_Key, 231, 0x8000E70C, 0x00000000 },
309 { &GUID_Key, 232, 0x8000E80C, 0x00000000 },
310 { &GUID_Key, 233, 0x8000E90C, 0x00000000 },
311 { &GUID_Key, 234, 0x8000EA0C, 0x00000000 },
312 { &GUID_Key, 235, 0x8000EB0C, 0x00000000 },
313 { &GUID_Key, 236, 0x8000EC0C, 0x00000000 },
314 { &GUID_Key, 237, 0x8000ED0C, 0x00000000 },
315 { &GUID_Key, 238, 0x8000EE0C, 0x00000000 },
316 { &GUID_Key, 239, 0x8000EF0C, 0x00000000 },
317 { &GUID_Key, 240, 0x8000F00C, 0x00000000 },
318 { &GUID_Key, 241, 0x8000F10C, 0x00000000 },
319 { &GUID_Key, 242, 0x8000F20C, 0x00000000 },
320 { &GUID_Key, 243, 0x8000F30C, 0x00000000 },
321 { &GUID_Key, 244, 0x8000F40C, 0x00000000 },
322 { &GUID_Key, 245, 0x8000F50C, 0x00000000 },
323 { &GUID_Key, 246, 0x8000F60C, 0x00000000 },
324 { &GUID_Key, 247, 0x8000F70C, 0x00000000 },
325 { &GUID_Key, 248, 0x8000F80C, 0x00000000 },
326 { &GUID_Key, 249, 0x8000F90C, 0x00000000 },
327 { &GUID_Key, 250, 0x8000FA0C, 0x00000000 },
328 { &GUID_Key, 251, 0x8000FB0C, 0x00000000 },
329 { &GUID_Key, 252, 0x8000FC0C, 0x00000000 },
330 { &GUID_Key, 253, 0x8000FD0C, 0x00000000 },
331 { &GUID_Key, 254, 0x8000FE0C, 0x00000000 },
332 { &GUID_Key, 255, 0x8000FF0C, 0x00000000 },
333};
334
335const DIDATAFORMAT c_dfDIKeyboard = { sizeof(DIDATAFORMAT), sizeof(DIOBJECTDATAFORMAT), 0x00000002, 256, 256, KBD_fmt };
336
337
338/* Mouse */
339
340static DIOBJECTDATAFORMAT PTR_fmt[] = {
341 { &GUID_XAxis, 0, 0x00FFFF03, 0x00000000 },
342 { &GUID_YAxis, 4, 0x00FFFF03, 0x00000000 },
343 { &GUID_ZAxis, 8, 0x80FFFF03, 0x00000000 },
344 { NULL, 12, 0x00FFFF0C, 0x00000000 },
345 { NULL, 13, 0x00FFFF0C, 0x00000000 },
346 { NULL, 14, 0x80FFFF0C, 0x00000000 },
347 { NULL, 15, 0x80FFFF0C, 0x00000000 },
348};
349
350const DIDATAFORMAT c_dfDIMouse = { sizeof(DIDATAFORMAT), sizeof(DIOBJECTDATAFORMAT), 0x00000002, 16, 7, PTR_fmt };
351
352static DIOBJECTDATAFORMAT PTR2_fmt[] = {
353 { &GUID_XAxis, 0, 0x00FFFF03, 0x00000000 },
354 { &GUID_YAxis, 4, 0x00FFFF03, 0x00000000 },
355 { &GUID_ZAxis, 8, 0x80FFFF03, 0x00000000 },
356 { NULL, 12, 0x00FFFF0C, 0x00000000 },
357 { NULL, 13, 0x00FFFF0C, 0x00000000 },
358 { NULL, 14, 0x80FFFF0C, 0x00000000 },
359 { NULL, 15, 0x80FFFF0C, 0x00000000 },
360 { NULL, 16, 0x80FFFF0C, 0x00000000 },
361 { NULL, 17, 0x80FFFF0C, 0x00000000 },
362 { NULL, 18, 0x80FFFF0C, 0x00000000 },
363 { NULL, 19, 0x80FFFF0C, 0x00000000 }
364};
365
366const DIDATAFORMAT c_dfDIMouse2 = { sizeof(DIDATAFORMAT), sizeof(DIOBJECTDATAFORMAT), 0x00000002, 20, 11, PTR2_fmt };
367
368
369/* Joystick */
370
371static DIOBJECTDATAFORMAT JOY_fmt[] = {
372 { &GUID_XAxis, 0, 0x80FFFF03, 0x00000100 },
373 { &GUID_YAxis, 4, 0x80FFFF03, 0x00000100 },
374 { &GUID_ZAxis, 8, 0x80FFFF03, 0x00000100 },
375 { &GUID_RxAxis, 12, 0x80FFFF03, 0x00000100 },
376 { &GUID_RyAxis, 16, 0x80FFFF03, 0x00000100 },
377 { &GUID_RzAxis, 20, 0x80FFFF03, 0x00000100 },
378 { &GUID_Slider, 24, 0x80FFFF03, 0x00000100 },
379 { &GUID_Slider, 28, 0x80FFFF03, 0x00000100 },
380 { &GUID_POV, 32, 0x80FFFF10, 0x00000000 },
381 { &GUID_POV, 36, 0x80FFFF10, 0x00000000 },
382 { &GUID_POV, 40, 0x80FFFF10, 0x00000000 },
383 { &GUID_POV, 44, 0x80FFFF10, 0x00000000 },
384 { NULL, 48, 0x80FFFF0C, 0x00000000 },
385 { NULL, 49, 0x80FFFF0C, 0x00000000 },
386 { NULL, 50, 0x80FFFF0C, 0x00000000 },
387 { NULL, 51, 0x80FFFF0C, 0x00000000 },
388 { NULL, 52, 0x80FFFF0C, 0x00000000 },
389 { NULL, 53, 0x80FFFF0C, 0x00000000 },
390 { NULL, 54, 0x80FFFF0C, 0x00000000 },
391 { NULL, 55, 0x80FFFF0C, 0x00000000 },
392 { NULL, 56, 0x80FFFF0C, 0x00000000 },
393 { NULL, 57, 0x80FFFF0C, 0x00000000 },
394 { NULL, 58, 0x80FFFF0C, 0x00000000 },
395 { NULL, 59, 0x80FFFF0C, 0x00000000 },
396 { NULL, 60, 0x80FFFF0C, 0x00000000 },
397 { NULL, 61, 0x80FFFF0C, 0x00000000 },
398 { NULL, 62, 0x80FFFF0C, 0x00000000 },
399 { NULL, 63, 0x80FFFF0C, 0x00000000 },
400 { NULL, 64, 0x80FFFF0C, 0x00000000 },
401 { NULL, 65, 0x80FFFF0C, 0x00000000 },
402 { NULL, 66, 0x80FFFF0C, 0x00000000 },
403 { NULL, 67, 0x80FFFF0C, 0x00000000 },
404 { NULL, 68, 0x80FFFF0C, 0x00000000 },
405 { NULL, 69, 0x80FFFF0C, 0x00000000 },
406 { NULL, 70, 0x80FFFF0C, 0x00000000 },
407 { NULL, 71, 0x80FFFF0C, 0x00000000 },
408 { NULL, 72, 0x80FFFF0C, 0x00000000 },
409 { NULL, 73, 0x80FFFF0C, 0x00000000 },
410 { NULL, 74, 0x80FFFF0C, 0x00000000 },
411 { NULL, 75, 0x80FFFF0C, 0x00000000 },
412 { NULL, 76, 0x80FFFF0C, 0x00000000 },
413 { NULL, 77, 0x80FFFF0C, 0x00000000 },
414 { NULL, 78, 0x80FFFF0C, 0x00000000 },
415 { NULL, 79, 0x80FFFF0C, 0x00000000 },
416};
417
418const DIDATAFORMAT c_dfDIJoystick = { sizeof(DIDATAFORMAT), sizeof(DIOBJECTDATAFORMAT), 0x00000001, 80, 44, JOY_fmt };
419
420
421/* Initialization/Query functions */
422static int DX5_VideoInit(_THIS, SDL_PixelFormat *vformat);
423static SDL_Rect **DX5_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
424static SDL_Surface *DX5_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
425static int DX5_SetColors(_THIS, int firstcolor, int ncolors,
426 SDL_Color *colors);
427static int DX5_SetGammaRamp(_THIS, Uint16 *ramp);
428static int DX5_GetGammaRamp(_THIS, Uint16 *ramp);
429static void DX5_VideoQuit(_THIS);
430
431/* Hardware surface functions */
432static int DX5_AllocHWSurface(_THIS, SDL_Surface *surface);
433static int DX5_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst);
434static int DX5_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color);
435static int DX5_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key);
436static int DX5_SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 alpha);
437static int DX5_LockHWSurface(_THIS, SDL_Surface *surface);
438static void DX5_UnlockHWSurface(_THIS, SDL_Surface *surface);
439static int DX5_FlipHWSurface(_THIS, SDL_Surface *surface);
440static void DX5_FreeHWSurface(_THIS, SDL_Surface *surface);
441
442static int DX5_AllocDDSurface(_THIS, SDL_Surface *surface,
443 LPDIRECTDRAWSURFACE3 requested, Uint32 flag);
444
445/* Windows message handling functions */
446static void DX5_Activate(_THIS, BOOL active, BOOL minimized);
447static void DX5_RealizePalette(_THIS);
448static void DX5_PaletteChanged(_THIS, HWND window);
449static void DX5_WinPAINT(_THIS, HDC hdc);
450
451/* WinDIB driver functions for manipulating gamma ramps */
452extern int DIB_SetGammaRamp(_THIS, Uint16 *ramp);
453extern int DIB_GetGammaRamp(_THIS, Uint16 *ramp);
454extern void DIB_QuitGamma(_THIS);
455
456/* DX5 driver bootstrap functions */
457
458static int DX5_Available(void)
459{
460 HINSTANCE DInputDLL;
461 HINSTANCE DDrawDLL;
462 int dinput_ok;
463 int ddraw_ok;
464
465 /* Version check DINPUT.DLL and DDRAW.DLL (Is DirectX okay?) */
466 dinput_ok = 0;
467 DInputDLL = LoadLibrary(TEXT("DINPUT.DLL"));
468 if ( DInputDLL != NULL ) {
469 dinput_ok = 1;
470 FreeLibrary(DInputDLL);
471 }
472 ddraw_ok = 0;
473 DDrawDLL = LoadLibrary(TEXT("DDRAW.DLL"));
474 if ( DDrawDLL != NULL ) {
475 HRESULT (WINAPI *DDrawCreate)(GUID *,LPDIRECTDRAW *,IUnknown *);
476 LPDIRECTDRAW DDraw;
477
478 /* Try to create a valid DirectDraw object */
479 DDrawCreate = (void *)GetProcAddress(DDrawDLL, TEXT("DirectDrawCreate"));
480 if ( (DDrawCreate != NULL)
481 && !FAILED(DDrawCreate(NULL, &DDraw, NULL)) ) {
482 if ( !FAILED(IDirectDraw_SetCooperativeLevel(DDraw,
483 NULL, DDSCL_NORMAL)) ) {
484 DDSURFACEDESC desc;
485 LPDIRECTDRAWSURFACE DDrawSurf;
486 LPDIRECTDRAWSURFACE3 DDrawSurf3;
487
488 /* Try to create a DirectDrawSurface3 object */
489 SDL_memset(&desc, 0, sizeof(desc));
490 desc.dwSize = sizeof(desc);
491 desc.dwFlags = DDSD_CAPS;
492 desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE|DDSCAPS_VIDEOMEMORY;
493 if ( !FAILED(IDirectDraw_CreateSurface(DDraw, &desc,
494 &DDrawSurf, NULL)) ) {
495 if ( !FAILED(IDirectDrawSurface_QueryInterface(DDrawSurf,
496 &IID_IDirectDrawSurface3, (LPVOID *)&DDrawSurf3)) ) {
497 /* Yay! */
498 ddraw_ok = 1;
499
500 /* Clean up.. */
501 IDirectDrawSurface3_Release(DDrawSurf3);
502 }
503 IDirectDrawSurface_Release(DDrawSurf);
504 }
505 }
506 IDirectDraw_Release(DDraw);
507 }
508 FreeLibrary(DDrawDLL);
509 }
510 return(dinput_ok && ddraw_ok);
511}
512
513/* Functions for loading the DirectX functions dynamically */
514static HINSTANCE DDrawDLL = NULL;
515static HINSTANCE DInputDLL = NULL;
516
517static void DX5_Unload(void)
518{
519 if ( DDrawDLL != NULL ) {
520 FreeLibrary(DDrawDLL);
521 DDrawCreate = NULL;
522 DDrawDLL = NULL;
523 }
524 if ( DInputDLL != NULL ) {
525 FreeLibrary(DInputDLL);
526 DInputCreate = NULL;
527 DInputDLL = NULL;
528 }
529}
530static int DX5_Load(void)
531{
532 int status;
533
534 DX5_Unload();
535 DDrawDLL = LoadLibrary(TEXT("DDRAW.DLL"));
536 if ( DDrawDLL != NULL ) {
537 DDrawCreate = (void *)GetProcAddress(DDrawDLL,
538 TEXT("DirectDrawCreate"));
539 }
540 DInputDLL = LoadLibrary(TEXT("DINPUT.DLL"));
541 if ( DInputDLL != NULL ) {
542 DInputCreate = (void *)GetProcAddress(DInputDLL,
543 TEXT("DirectInputCreateA"));
544 }
545 if ( DDrawDLL && DDrawCreate && DInputDLL && DInputCreate ) {
546 status = 0;
547 } else {
548 DX5_Unload();
549 status = -1;
550 }
551 return status;
552}
553
554static void DX5_DeleteDevice(SDL_VideoDevice *this)
555{
556 /* Free DirectDraw object */
557 if ( ddraw2 != NULL ) {
558 IDirectDraw2_Release(ddraw2);
559 }
560 DX5_Unload();
561 if ( this ) {
562 if ( this->hidden ) {
563 SDL_free(this->hidden);
564 }
565 if ( this->gl_data ) {
566 SDL_free(this->gl_data);
567 }
568 SDL_free(this);
569 }
570}
571
572static SDL_VideoDevice *DX5_CreateDevice(int devindex)
573{
574 SDL_VideoDevice *device;
575
576 /* Load DirectX */
577 if ( DX5_Load() < 0 ) {
578 return(NULL);
579 }
580
581 /* Initialize all variables that we clean on shutdown */
582 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
583 if ( device ) {
584 SDL_memset(device, 0, (sizeof *device));
585 device->hidden = (struct SDL_PrivateVideoData *)
586 SDL_malloc((sizeof *device->hidden));
587 device->gl_data = (struct SDL_PrivateGLData *)
588 SDL_malloc((sizeof *device->gl_data));
589 }
590 if ( (device == NULL) || (device->hidden == NULL) ||
591 (device->gl_data == NULL) ) {
592 SDL_OutOfMemory();
593 DX5_DeleteDevice(device);
594 return(NULL);
595 }
596 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
597 SDL_memset(device->gl_data, 0, (sizeof *device->gl_data));
598
599 /* Set the function pointers */
600 device->VideoInit = DX5_VideoInit;
601 device->ListModes = DX5_ListModes;
602 device->SetVideoMode = DX5_SetVideoMode;
603 device->UpdateMouse = WIN_UpdateMouse;
604 device->CreateYUVOverlay = DX5_CreateYUVOverlay;
605 device->SetColors = DX5_SetColors;
606 device->UpdateRects = NULL;
607 device->VideoQuit = DX5_VideoQuit;
608 device->AllocHWSurface = DX5_AllocHWSurface;
609 device->CheckHWBlit = DX5_CheckHWBlit;
610 device->FillHWRect = DX5_FillHWRect;
611 device->SetHWColorKey = DX5_SetHWColorKey;
612 device->SetHWAlpha = DX5_SetHWAlpha;
613 device->LockHWSurface = DX5_LockHWSurface;
614 device->UnlockHWSurface = DX5_UnlockHWSurface;
615 device->FlipHWSurface = DX5_FlipHWSurface;
616 device->FreeHWSurface = DX5_FreeHWSurface;
617 device->SetGammaRamp = DX5_SetGammaRamp;
618 device->GetGammaRamp = DX5_GetGammaRamp;
619#if SDL_VIDEO_OPENGL
620 device->GL_LoadLibrary = WIN_GL_LoadLibrary;
621 device->GL_GetProcAddress = WIN_GL_GetProcAddress;
622 device->GL_GetAttribute = WIN_GL_GetAttribute;
623 device->GL_MakeCurrent = WIN_GL_MakeCurrent;
624 device->GL_SwapBuffers = WIN_GL_SwapBuffers;
625#endif
626 device->SetCaption = WIN_SetWMCaption;
627 device->SetIcon = WIN_SetWMIcon;
628 device->IconifyWindow = WIN_IconifyWindow;
629 device->GrabInput = WIN_GrabInput;
630 device->GetWMInfo = WIN_GetWMInfo;
631 device->FreeWMCursor = WIN_FreeWMCursor;
632 device->CreateWMCursor = WIN_CreateWMCursor;
633 device->ShowWMCursor = WIN_ShowWMCursor;
634 device->WarpWMCursor = WIN_WarpWMCursor;
635 device->CheckMouseMode = WIN_CheckMouseMode;
636 device->InitOSKeymap = DX5_InitOSKeymap;
637 device->PumpEvents = DX5_PumpEvents;
638
639 /* Set up the windows message handling functions */
640 WIN_Activate = DX5_Activate;
641 WIN_RealizePalette = DX5_RealizePalette;
642 WIN_PaletteChanged = DX5_PaletteChanged;
643 WIN_WinPAINT = DX5_WinPAINT;
644 HandleMessage = DX5_HandleMessage;
645
646 device->free = DX5_DeleteDevice;
647
648 /* We're finally ready */
649 return device;
650}
651
652VideoBootStrap DIRECTX_bootstrap = {
653 "directx", "Win95/98/2000 DirectX",
654 DX5_Available, DX5_CreateDevice
655};
656
657static int cmpmodes(const void *va, const void *vb)
658{
659 SDL_Rect *a = *(SDL_Rect **)va;
660 SDL_Rect *b = *(SDL_Rect **)vb;
661 if ( a->w == b->w )
662 return b->h - a->h;
663 else
664 return b->w - a->w;
665}
666
667static HRESULT WINAPI EnumModes2(DDSURFACEDESC *desc, VOID *udata)
668{
669 SDL_VideoDevice *this = (SDL_VideoDevice *)udata;
670 struct DX5EnumRect *enumrect;
671#if defined(NONAMELESSUNION)
672 int bpp = desc->ddpfPixelFormat.u1.dwRGBBitCount;
673 int refreshRate = desc->u2.dwRefreshRate;
674#else
675 int bpp = desc->ddpfPixelFormat.dwRGBBitCount;
676 int refreshRate = desc->dwRefreshRate;
677#endif
678 int maxRefreshRate;
679
680 if ( desc->dwWidth <= SDL_desktop_mode.dmPelsWidth &&
681 desc->dwHeight <= SDL_desktop_mode.dmPelsHeight ) {
682 maxRefreshRate = SDL_desktop_mode.dmDisplayFrequency;
683 } else {
684 maxRefreshRate = 85; /* safe value? */
685 }
686
687 switch (bpp) {
688 case 8:
689 case 16:
690 case 24:
691 case 32:
692 bpp /= 8; --bpp;
693 if ( enumlists[bpp] &&
694 enumlists[bpp]->r.w == (Uint16)desc->dwWidth &&
695 enumlists[bpp]->r.h == (Uint16)desc->dwHeight ) {
696 if ( refreshRate > enumlists[bpp]->refreshRate &&
697 refreshRate <= maxRefreshRate ) {
698 enumlists[bpp]->refreshRate = refreshRate;
699#ifdef DDRAW_DEBUG
700 fprintf(stderr, "New refresh rate for %d bpp: %dx%d at %d Hz\n", (bpp+1)*8, (int)desc->dwWidth, (int)desc->dwHeight, refreshRate);
701#endif
702 }
703 break;
704 }
705 ++SDL_nummodes[bpp];
706 enumrect = (struct DX5EnumRect*)SDL_malloc(sizeof(struct DX5EnumRect));
707 if ( !enumrect ) {
708 SDL_OutOfMemory();
709 return(DDENUMRET_CANCEL);
710 }
711 enumrect->refreshRate = refreshRate;
712 enumrect->r.x = 0;
713 enumrect->r.y = 0;
714 enumrect->r.w = (Uint16)desc->dwWidth;
715 enumrect->r.h = (Uint16)desc->dwHeight;
716 enumrect->next = enumlists[bpp];
717 enumlists[bpp] = enumrect;
718#ifdef DDRAW_DEBUG
719 fprintf(stderr, "New mode for %d bpp: %dx%d at %d Hz\n", (bpp+1)*8, (int)desc->dwWidth, (int)desc->dwHeight, refreshRate);
720#endif
721 break;
722 }
723
724 return(DDENUMRET_OK);
725}
726
727void SetDDerror(const char *function, int code)
728{
729 static char *error;
730 static char errbuf[1024];
731
732 errbuf[0] = 0;
733 switch (code) {
734 case DDERR_GENERIC:
735 error = "Undefined error!";
736 break;
737 case DDERR_EXCEPTION:
738 error = "Exception encountered";
739 break;
740 case DDERR_INVALIDOBJECT:
741 error = "Invalid object";
742 break;
743 case DDERR_INVALIDPARAMS:
744 error = "Invalid parameters";
745 break;
746 case DDERR_NOTFOUND:
747 error = "Object not found";
748 break;
749 case DDERR_INVALIDRECT:
750 error = "Invalid rectangle";
751 break;
752 case DDERR_INVALIDCAPS:
753 error = "Invalid caps member";
754 break;
755 case DDERR_INVALIDPIXELFORMAT:
756 error = "Invalid pixel format";
757 break;
758 case DDERR_OUTOFMEMORY:
759 error = "Out of memory";
760 break;
761 case DDERR_OUTOFVIDEOMEMORY:
762 error = "Out of video memory";
763 break;
764 case DDERR_SURFACEBUSY:
765 error = "Surface busy";
766 break;
767 case DDERR_SURFACELOST:
768 error = "Surface was lost";
769 break;
770 case DDERR_WASSTILLDRAWING:
771 error = "DirectDraw is still drawing";
772 break;
773 case DDERR_INVALIDSURFACETYPE:
774 error = "Invalid surface type";
775 break;
776 case DDERR_NOEXCLUSIVEMODE:
777 error = "Not in exclusive access mode";
778 break;
779 case DDERR_NOPALETTEATTACHED:
780 error = "No palette attached";
781 break;
782 case DDERR_NOPALETTEHW:
783 error = "No palette hardware";
784 break;
785 case DDERR_NOT8BITCOLOR:
786 error = "Not 8-bit color";
787 break;
788 case DDERR_EXCLUSIVEMODEALREADYSET:
789 error = "Exclusive mode was already set";
790 break;
791 case DDERR_HWNDALREADYSET:
792 error = "Window handle already set";
793 break;
794 case DDERR_HWNDSUBCLASSED:
795 error = "Window handle is subclassed";
796 break;
797 case DDERR_NOBLTHW:
798 error = "No blit hardware";
799 break;
800 case DDERR_IMPLICITLYCREATED:
801 error = "Surface was implicitly created";
802 break;
803 case DDERR_INCOMPATIBLEPRIMARY:
804 error = "Incompatible primary surface";
805 break;
806 case DDERR_NOCOOPERATIVELEVELSET:
807 error = "No cooperative level set";
808 break;
809 case DDERR_NODIRECTDRAWHW:
810 error = "No DirectDraw hardware";
811 break;
812 case DDERR_NOEMULATION:
813 error = "No emulation available";
814 break;
815 case DDERR_NOFLIPHW:
816 error = "No flip hardware";
817 break;
818 case DDERR_NOTFLIPPABLE:
819 error = "Surface not flippable";
820 break;
821 case DDERR_PRIMARYSURFACEALREADYEXISTS:
822 error = "Primary surface already exists";
823 break;
824 case DDERR_UNSUPPORTEDMODE:
825 error = "Unsupported mode";
826 break;
827 case DDERR_WRONGMODE:
828 error = "Surface created in different mode";
829 break;
830 case DDERR_UNSUPPORTED:
831 error = "Operation not supported";
832 break;
833 case E_NOINTERFACE:
834 error = "Interface not present";
835 break;
836 default:
837 SDL_snprintf(errbuf, SDL_arraysize(errbuf),
838 "%s: Unknown DirectDraw error: 0x%x",
839 function, code);
840 break;
841 }
842 if ( ! errbuf[0] ) {
843 SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error);
844 }
845 SDL_SetError("%s", errbuf);
846 return;
847}
848
849
850static int DX5_UpdateVideoInfo(_THIS)
851{
852 /* This needs to be DDCAPS_DX5 for the DirectDraw2 interface */
853#if DIRECTDRAW_VERSION <= 0x300
854#error Your version of DirectX must be greater than or equal to 5.0
855#endif
856#ifndef IDirectDrawGammaControl_SetGammaRamp
857 /*if gamma is undefined then we really have directx <= 0x500*/
858 DDCAPS DDCaps;
859#else
860 DDCAPS_DX5 DDCaps;
861#endif
862 HRESULT result;
863
864 /* Fill in our hardware acceleration capabilities */
865 SDL_memset(&DDCaps, 0, sizeof(DDCaps));
866 DDCaps.dwSize = sizeof(DDCaps);
867 result = IDirectDraw2_GetCaps(ddraw2, (DDCAPS *)&DDCaps, NULL);
868 if ( result != DD_OK ) {
869 SetDDerror("DirectDraw2::GetCaps", result);
870 return(-1);
871 }
872 this->info.hw_available = 1;
873 if ( (DDCaps.dwCaps & DDCAPS_BLT) == DDCAPS_BLT ) {
874 this->info.blit_hw = 1;
875 }
876 if ( ((DDCaps.dwCaps & DDCAPS_COLORKEY) == DDCAPS_COLORKEY) &&
877 ((DDCaps.dwCKeyCaps & DDCKEYCAPS_SRCBLT) == DDCKEYCAPS_SRCBLT) ) {
878 this->info.blit_hw_CC = 1;
879 }
880 if ( (DDCaps.dwCaps & DDCAPS_ALPHA) == DDCAPS_ALPHA ) {
881 /* This is only for alpha channel, and DirectX 6
882 doesn't support 2D alpha blits yet, so set it 0
883 */
884 this->info.blit_hw_A = 0;
885 }
886 if ( (DDCaps.dwCaps & DDCAPS_CANBLTSYSMEM) == DDCAPS_CANBLTSYSMEM ) {
887 this->info.blit_sw = 1;
888 /* This isn't necessarily true, but the HEL will cover us */
889 this->info.blit_sw_CC = this->info.blit_hw_CC;
890 this->info.blit_sw_A = this->info.blit_hw_A;
891 }
892 if ( (DDCaps.dwCaps & DDCAPS_BLTCOLORFILL) == DDCAPS_BLTCOLORFILL ) {
893 this->info.blit_fill = 1;
894 }
895
896 /* Find out how much video memory is available */
897 { DDSCAPS ddsCaps;
898 DWORD total_mem;
899 ddsCaps.dwCaps = DDSCAPS_VIDEOMEMORY;
900 result = IDirectDraw2_GetAvailableVidMem(ddraw2,
901 &ddsCaps, &total_mem, NULL);
902 if ( result != DD_OK ) {
903 total_mem = DDCaps.dwVidMemTotal;
904 }
905 this->info.video_mem = total_mem/1024;
906 }
907 return(0);
908}
909
910int DX5_VideoInit(_THIS, SDL_PixelFormat *vformat)
911{
912 HRESULT result;
913 LPDIRECTDRAW ddraw;
914 int i, j;
915 HDC hdc;
916
917 /* Intialize everything */
918 ddraw2 = NULL;
919 SDL_primary = NULL;
920 SDL_clipper = NULL;
921 SDL_palette = NULL;
922 for ( i=0; i<NUM_MODELISTS; ++i ) {
923 SDL_nummodes[i] = 0;
924 SDL_modelist[i] = NULL;
925 SDL_modeindex[i] = 0;
926 }
927 colorchange_expected = 0;
928
929 /* Create the window */
930 if ( DX5_CreateWindow(this) < 0 ) {
931 return(-1);
932 }
933
934#if !SDL_AUDIO_DISABLED
935 DX5_SoundFocus(SDL_Window);
936#endif
937
938 /* Create the DirectDraw object */
939 result = DDrawCreate(NULL, &ddraw, NULL);
940 if ( result != DD_OK ) {
941 SetDDerror("DirectDrawCreate", result);
942 return(-1);
943 }
944 result = IDirectDraw_QueryInterface(ddraw, &IID_IDirectDraw2,
945 (LPVOID *)&ddraw2);
946 IDirectDraw_Release(ddraw);
947 if ( result != DD_OK ) {
948 SetDDerror("DirectDraw::QueryInterface", result);
949 return(-1);
950 }
951
952 /* Determine the screen depth */
953 hdc = GetDC(SDL_Window);
954 vformat->BitsPerPixel = GetDeviceCaps(hdc,PLANES) *
955 GetDeviceCaps(hdc,BITSPIXEL);
956 ReleaseDC(SDL_Window, hdc);
957
958#ifndef NO_CHANGEDISPLAYSETTINGS
959 /* Query for the desktop resolution */
960 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &SDL_desktop_mode);
961 this->info.current_w = SDL_desktop_mode.dmPelsWidth;
962 this->info.current_h = SDL_desktop_mode.dmPelsHeight;
963#endif
964
965 /* Enumerate the available fullscreen modes */
966 for ( i=0; i<NUM_MODELISTS; ++i )
967 enumlists[i] = NULL;
968
969 result = IDirectDraw2_EnumDisplayModes(ddraw2,DDEDM_REFRESHRATES,NULL,this,EnumModes2);
970 if ( result != DD_OK ) {
971 SetDDerror("DirectDraw2::EnumDisplayModes", result);
972 return(-1);
973 }
974 for ( i=0; i<NUM_MODELISTS; ++i ) {
975 struct DX5EnumRect *rect;
976 SDL_modelist[i] = (SDL_Rect **)
977 SDL_malloc((SDL_nummodes[i]+1)*sizeof(SDL_Rect *));
978 if ( SDL_modelist[i] == NULL ) {
979 SDL_OutOfMemory();
980 return(-1);
981 }
982 for ( j = 0, rect = enumlists[i]; rect; ++j, rect = rect->next ) {
983 SDL_modelist[i][j] = &rect->r;
984 }
985 SDL_modelist[i][j] = NULL;
986
987 if ( SDL_nummodes[i] > 0 ) {
988 SDL_qsort(SDL_modelist[i], SDL_nummodes[i], sizeof *SDL_modelist[i], cmpmodes);
989 }
990 }
991
992 /* Fill in some window manager capabilities */
993 this->info.wm_available = 1;
994
995 /* Fill in the video hardware capabilities */
996 DX5_UpdateVideoInfo(this);
997
998 return(0);
999}
1000
1001SDL_Rect **DX5_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
1002{
1003 int bpp;
1004
1005 bpp = format->BitsPerPixel;
1006 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
1007 /* FIXME: No support for 1 bpp or 4 bpp formats */
1008 switch (bpp) { /* Does windows support other BPP? */
1009 case 8:
1010 case 16:
1011 case 24:
1012 case 32:
1013 bpp = (bpp/8)-1;
1014 if ( SDL_nummodes[bpp] > 0 )
1015 return(SDL_modelist[bpp]);
1016 /* Fall through */
1017 default:
1018 return((SDL_Rect **)0);
1019 }
1020 } else {
1021 if ( this->screen->format->BitsPerPixel == bpp ) {
1022 return((SDL_Rect **)-1);
1023 } else {
1024 return((SDL_Rect **)0);
1025 }
1026 }
1027}
1028
1029/* Various screen update functions available */
1030static void DX5_WindowUpdate(_THIS, int numrects, SDL_Rect *rects);
1031static void DX5_DirectUpdate(_THIS, int numrects, SDL_Rect *rects);
1032
1033SDL_Surface *DX5_SetVideoMode(_THIS, SDL_Surface *current,
1034 int width, int height, int bpp, Uint32 flags)
1035{
1036 SDL_Surface *video;
1037 int prev_w = -1;
1038 int prev_h = -1;
1039 HRESULT result;
1040 DWORD sharemode;
1041 DWORD style;
1042 const DWORD directstyle =
1043 (WS_POPUP);
1044 const DWORD windowstyle =
1045 (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX);
1046 const DWORD resizestyle =
1047 (WS_THICKFRAME|WS_MAXIMIZEBOX);
1048 DDSURFACEDESC ddsd;
1049 LPDIRECTDRAWSURFACE dd_surface1;
1050 LPDIRECTDRAWSURFACE3 dd_surface3;
1051
1052 SDL_resizing = 1;
1053#ifdef DDRAW_DEBUG
1054 fprintf(stderr, "Setting %dx%dx%d video mode\n", width, height, bpp);
1055#endif
1056 /* Clean up any previous DirectDraw surfaces */
1057 if ( current->hwdata ) {
1058 this->FreeHWSurface(this, current);
1059 current->hwdata = NULL;
1060 }
1061 if ( SDL_primary != NULL ) {
1062 IDirectDrawSurface3_Release(SDL_primary);
1063 SDL_primary = NULL;
1064 }
1065
1066#ifndef NO_CHANGEDISPLAYSETTINGS
1067 /* Unset any previous OpenGL fullscreen mode */
1068 if ( (current->flags & (SDL_OPENGL|SDL_FULLSCREEN)) ==
1069 (SDL_OPENGL|SDL_FULLSCREEN) ) {
1070 ChangeDisplaySettings(NULL, 0);
1071 }
1072#endif
1073
1074 /* Clean up any GL context that may be hanging around */
1075 if ( current->flags & SDL_OPENGL ) {
1076 WIN_GL_ShutDown(this);
1077 }
1078
1079 /* If we are setting a GL mode, use GDI, not DirectX (yuck) */
1080 if ( flags & SDL_OPENGL ) {
1081 Uint32 Rmask, Gmask, Bmask;
1082
1083 /* Recalculate the bitmasks if necessary */
1084 if ( bpp == current->format->BitsPerPixel ) {
1085 video = current;
1086 } else {
1087 switch (bpp) {
1088 case 15:
1089 case 16:
1090 if ( 0 /*DIB_SussScreenDepth() == 15*/ ) {
1091 /* 5-5-5 */
1092 Rmask = 0x00007c00;
1093 Gmask = 0x000003e0;
1094 Bmask = 0x0000001f;
1095 } else {
1096 /* 5-6-5 */
1097 Rmask = 0x0000f800;
1098 Gmask = 0x000007e0;
1099 Bmask = 0x0000001f;
1100 }
1101 break;
1102 case 24:
1103 case 32:
1104 /* GDI defined as 8-8-8 */
1105 Rmask = 0x00ff0000;
1106 Gmask = 0x0000ff00;
1107 Bmask = 0x000000ff;
1108 break;
1109 default:
1110 Rmask = 0x00000000;
1111 Gmask = 0x00000000;
1112 Bmask = 0x00000000;
1113 break;
1114 }
1115 video = SDL_CreateRGBSurface(SDL_SWSURFACE, 0, 0, bpp,
1116 Rmask, Gmask, Bmask, 0);
1117 if ( video == NULL ) {
1118 SDL_OutOfMemory();
1119 return(NULL);
1120 }
1121 }
1122
1123 /* Fill in part of the video surface */
1124 prev_w = video->w;
1125 prev_h = video->h;
1126 video->flags = 0; /* Clear flags */
1127 video->w = width;
1128 video->h = height;
1129 video->pitch = SDL_CalculatePitch(video);
1130
1131#ifndef NO_CHANGEDISPLAYSETTINGS
1132 /* Set fullscreen mode if appropriate.
1133 Ugh, since our list of valid video modes comes from
1134 the DirectX driver, we may not actually be able to
1135 change to the desired resolution here.
1136 FIXME: Should we do a closest match?
1137 */
1138 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
1139 DEVMODE settings;
1140 BOOL changed;
1141
1142 SDL_memset(&settings, 0, sizeof(DEVMODE));
1143 settings.dmSize = sizeof(DEVMODE);
1144 settings.dmBitsPerPel = video->format->BitsPerPixel;
1145 settings.dmPelsWidth = width;
1146 settings.dmPelsHeight = height;
1147 settings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
1148 if ( width <= (int)SDL_desktop_mode.dmPelsWidth &&
1149 height <= (int)SDL_desktop_mode.dmPelsHeight ) {
1150 settings.dmDisplayFrequency = SDL_desktop_mode.dmDisplayFrequency;
1151 settings.dmFields |= DM_DISPLAYFREQUENCY;
1152 }
1153 changed = (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL);
1154 if ( ! changed && (settings.dmFields & DM_DISPLAYFREQUENCY) ) {
1155 settings.dmFields &= ~DM_DISPLAYFREQUENCY;
1156 changed = (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL);
1157 }
1158 if ( changed ) {
1159 video->flags |= SDL_FULLSCREEN;
1160 SDL_fullscreen_mode = settings;
1161 }
1162 }
1163#endif /* !NO_CHANGEDISPLAYSETTINGS */
1164
1165 style = GetWindowLong(SDL_Window, GWL_STYLE);
1166 style &= ~(resizestyle|WS_MAXIMIZE);
1167 if ( video->flags & SDL_FULLSCREEN ) {
1168 style &= ~windowstyle;
1169 style |= directstyle;
1170 } else {
1171 if ( flags & SDL_NOFRAME ) {
1172 style &= ~windowstyle;
1173 style |= directstyle;
1174 video->flags |= SDL_NOFRAME;
1175 } else {
1176 style &= ~directstyle;
1177 style |= windowstyle;
1178 if ( flags & SDL_RESIZABLE ) {
1179 style |= resizestyle;
1180 video->flags |= SDL_RESIZABLE;
1181 }
1182 }
1183#if WS_MAXIMIZE
1184 if (IsZoomed(SDL_Window)) style |= WS_MAXIMIZE;
1185#endif
1186 }
1187
1188 /* DJM: Don't piss of anyone who has setup his own window */
1189 if ( !SDL_windowid )
1190 SetWindowLong(SDL_Window, GWL_STYLE, style);
1191
1192 /* Resize the window (copied from SDL WinDIB driver) */
1193 if ( !SDL_windowid && !IsZoomed(SDL_Window) ) {
1194 RECT bounds;
1195 int x, y;
1196 HWND top;
1197 UINT swp_flags;
1198 const char *window = NULL;
1199 const char *center = NULL;
1200
1201 if ( video->w != prev_w || video->h != prev_h ) {
1202 window = SDL_getenv("SDL_VIDEO_WINDOW_POS");
1203 center = SDL_getenv("SDL_VIDEO_CENTERED");
1204 if ( window ) {
1205 if ( SDL_sscanf(window, "%d,%d", &x, &y) == 2 ) {
1206 SDL_windowX = x;
1207 SDL_windowY = y;
1208 }
1209 if ( SDL_strcmp(window, "center") == 0 ) {
1210 center = window;
1211 }
1212 }
1213 }
1214 swp_flags = (SWP_NOCOPYBITS | SWP_SHOWWINDOW);
1215
1216 bounds.left = SDL_windowX;
1217 bounds.top = SDL_windowY;
1218 bounds.right = SDL_windowX+video->w;
1219 bounds.bottom = SDL_windowY+video->h;
1220 AdjustWindowRectEx(&bounds, GetWindowLong(SDL_Window, GWL_STYLE), (GetMenu(SDL_Window) != NULL), 0);
1221 width = bounds.right-bounds.left;
1222 height = bounds.bottom-bounds.top;
1223 if ( (flags & SDL_FULLSCREEN) ) {
1224 x = (GetSystemMetrics(SM_CXSCREEN)-width)/2;
1225 y = (GetSystemMetrics(SM_CYSCREEN)-height)/2;
1226 } else if ( center ) {
1227 x = (GetSystemMetrics(SM_CXSCREEN)-width)/2;
1228 y = (GetSystemMetrics(SM_CYSCREEN)-height)/2;
1229 } else if ( SDL_windowX || SDL_windowY || window ) {
1230 x = bounds.left;
1231 y = bounds.top;
1232 } else {
1233 x = y = -1;
1234 swp_flags |= SWP_NOMOVE;
1235 }
1236 if ( flags & SDL_FULLSCREEN ) {
1237 top = HWND_TOPMOST;
1238 } else {
1239 top = HWND_NOTOPMOST;
1240 }
1241 SetWindowPos(SDL_Window, top, x, y, width, height, swp_flags);
1242 if ( !(flags & SDL_FULLSCREEN) ) {
1243 SDL_windowX = SDL_bounds.left;
1244 SDL_windowY = SDL_bounds.top;
1245 }
1246 SetForegroundWindow(SDL_Window);
1247 }
1248 SDL_resizing = 0;
1249
1250 /* Set up for OpenGL */
1251 if ( WIN_GL_SetupWindow(this) < 0 ) {
1252 return(NULL);
1253 }
1254 video->flags |= SDL_OPENGL;
1255 return(video);
1256 }
1257
1258 /* Set the appropriate window style */
1259 style = GetWindowLong(SDL_Window, GWL_STYLE);
1260 style &= ~(resizestyle|WS_MAXIMIZE);
1261 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
1262 style &= ~windowstyle;
1263 style |= directstyle;
1264 } else {
1265 if ( flags & SDL_NOFRAME ) {
1266 style &= ~windowstyle;
1267 style |= directstyle;
1268 } else {
1269 style &= ~directstyle;
1270 style |= windowstyle;
1271 if ( flags & SDL_RESIZABLE ) {
1272 style |= resizestyle;
1273 }
1274 }
1275#if WS_MAXIMIZE
1276 if (IsZoomed(SDL_Window)) style |= WS_MAXIMIZE;
1277#endif
1278 }
1279 /* DJM: Don't piss of anyone who has setup his own window */
1280 if ( !SDL_windowid )
1281 SetWindowLong(SDL_Window, GWL_STYLE, style);
1282
1283 /* Set DirectDraw sharing mode.. exclusive when fullscreen */
1284 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
1285 sharemode = DDSCL_FULLSCREEN|DDSCL_EXCLUSIVE|DDSCL_ALLOWREBOOT;
1286 } else {
1287 sharemode = DDSCL_NORMAL;
1288 }
1289 result = IDirectDraw2_SetCooperativeLevel(ddraw2,SDL_Window,sharemode);
1290 if ( result != DD_OK ) {
1291 SetDDerror("DirectDraw2::SetCooperativeLevel", result);
1292 return(NULL);
1293 }
1294
1295 /* Set the display mode, if we are in fullscreen mode */
1296 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
1297 RECT bounds;
1298 struct DX5EnumRect *rect;
1299 int maxRefreshRate;
1300
1301 /* Cover up desktop during mode change */
1302 bounds.left = 0;
1303 bounds.top = 0;
1304 bounds.right = GetSystemMetrics(SM_CXSCREEN);
1305 bounds.bottom = GetSystemMetrics(SM_CYSCREEN);
1306 AdjustWindowRectEx(&bounds, GetWindowLong(SDL_Window, GWL_STYLE), (GetMenu(SDL_Window) != NULL), 0);
1307 SetWindowPos(SDL_Window, HWND_TOPMOST,
1308 bounds.left, bounds.top,
1309 bounds.right - bounds.left,
1310 bounds.bottom - bounds.top, SWP_NOCOPYBITS);
1311 ShowWindow(SDL_Window, SW_SHOW);
1312 while ( GetForegroundWindow() != SDL_Window ) {
1313 SetForegroundWindow(SDL_Window);
1314 SDL_Delay(100);
1315 }
1316
1317 /* find maximum monitor refresh rate for this resolution */
1318 /* Dmitry Yakimov ftech@tula.net */
1319 maxRefreshRate = 0; /* system default */
1320 for ( rect = enumlists[bpp / 8 - 1]; rect; rect = rect->next ) {
1321 if ( (width == rect->r.w) && (height == rect->r.h) ) {
1322 maxRefreshRate = rect->refreshRate;
1323 break;
1324 }
1325 }
1326#ifdef DDRAW_DEBUG
1327 fprintf(stderr, "refresh rate = %d Hz\n", maxRefreshRate);
1328#endif
1329
1330 result = IDirectDraw2_SetDisplayMode(ddraw2, width, height, bpp, maxRefreshRate, 0);
1331 if ( result != DD_OK ) {
1332 result = IDirectDraw2_SetDisplayMode(ddraw2, width, height, bpp, 0, 0);
1333 if ( result != DD_OK ) {
1334 /* We couldn't set fullscreen mode, try window */
1335 return(DX5_SetVideoMode(this, current, width, height, bpp, flags & ~SDL_FULLSCREEN));
1336 }
1337 }
1338 DX5_DInputReset(this, 1);
1339 } else {
1340 DX5_DInputReset(this, 0);
1341 }
1342 DX5_UpdateVideoInfo(this);
1343
1344 /* Create a primary DirectDraw surface */
1345 SDL_memset(&ddsd, 0, sizeof(ddsd));
1346 ddsd.dwSize = sizeof(ddsd);
1347 ddsd.dwFlags = DDSD_CAPS;
1348 ddsd.ddsCaps.dwCaps = (DDSCAPS_PRIMARYSURFACE|DDSCAPS_VIDEOMEMORY);
1349 if ( (flags & SDL_FULLSCREEN) != SDL_FULLSCREEN ) {
1350 /* There's no windowed double-buffering */
1351 flags &= ~SDL_DOUBLEBUF;
1352 }
1353 if ( (flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) {
1354 ddsd.dwFlags |= DDSD_BACKBUFFERCOUNT;
1355 ddsd.ddsCaps.dwCaps |= (DDSCAPS_COMPLEX|DDSCAPS_FLIP);
1356 ddsd.dwBackBufferCount = 1;
1357 }
1358 result = IDirectDraw2_CreateSurface(ddraw2, &ddsd, &dd_surface1, NULL);
1359 if ( (result != DD_OK) && ((flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) ) {
1360 ddsd.dwFlags &= ~DDSD_BACKBUFFERCOUNT;
1361 ddsd.ddsCaps.dwCaps &= ~(DDSCAPS_COMPLEX|DDSCAPS_FLIP);
1362 ddsd.dwBackBufferCount = 0;
1363 result = IDirectDraw2_CreateSurface(ddraw2,
1364 &ddsd, &dd_surface1, NULL);
1365 }
1366 if ( result != DD_OK ) {
1367 SetDDerror("DirectDraw2::CreateSurface(PRIMARY)", result);
1368 return(NULL);
1369 }
1370 result = IDirectDrawSurface_QueryInterface(dd_surface1,
1371 &IID_IDirectDrawSurface3, (LPVOID *)&SDL_primary);
1372 if ( result != DD_OK ) {
1373 SetDDerror("DirectDrawSurface::QueryInterface", result);
1374 return(NULL);
1375 }
1376 IDirectDrawSurface_Release(dd_surface1);
1377
1378 /* Get the format of the primary DirectDraw surface */
1379 SDL_memset(&ddsd, 0, sizeof(ddsd));
1380 ddsd.dwSize = sizeof(ddsd);
1381 ddsd.dwFlags = DDSD_PIXELFORMAT|DDSD_CAPS;
1382 result = IDirectDrawSurface3_GetSurfaceDesc(SDL_primary, &ddsd);
1383 if ( result != DD_OK ) {
1384 SetDDerror("DirectDrawSurface::GetSurfaceDesc", result);
1385 return(NULL);
1386 }
1387 if ( ! (ddsd.ddpfPixelFormat.dwFlags&DDPF_RGB) ) {
1388 SDL_SetError("Primary DDRAW surface is not RGB format");
1389 return(NULL);
1390 }
1391
1392 /* Free old palette and create a new one if we're in 8-bit mode */
1393 if ( SDL_palette != NULL ) {
1394 IDirectDrawPalette_Release(SDL_palette);
1395 SDL_palette = NULL;
1396 }
1397#if defined(NONAMELESSUNION)
1398 if ( ddsd.ddpfPixelFormat.u1.dwRGBBitCount == 8 ) {
1399#else
1400 if ( ddsd.ddpfPixelFormat.dwRGBBitCount == 8 ) {
1401#endif
1402 int i;
1403
1404 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
1405 /* We have access to the entire palette */
1406 for ( i=0; i<256; ++i ) {
1407 SDL_colors[i].peFlags =
1408 (PC_NOCOLLAPSE|PC_RESERVED);
1409 SDL_colors[i].peRed = 0;
1410 SDL_colors[i].peGreen = 0;
1411 SDL_colors[i].peBlue = 0;
1412 }
1413 } else {
1414 /* First 10 colors are reserved by Windows */
1415 for ( i=0; i<10; ++i ) {
1416 SDL_colors[i].peFlags = PC_EXPLICIT;
1417 SDL_colors[i].peRed = i;
1418 SDL_colors[i].peGreen = 0;
1419 SDL_colors[i].peBlue = 0;
1420 }
1421 for ( i=10; i<(10+236); ++i ) {
1422 SDL_colors[i].peFlags = PC_NOCOLLAPSE;
1423 SDL_colors[i].peRed = 0;
1424 SDL_colors[i].peGreen = 0;
1425 SDL_colors[i].peBlue = 0;
1426 }
1427 /* Last 10 colors are reserved by Windows */
1428 for ( i=246; i<256; ++i ) {
1429 SDL_colors[i].peFlags = PC_EXPLICIT;
1430 SDL_colors[i].peRed = i;
1431 SDL_colors[i].peGreen = 0;
1432 SDL_colors[i].peBlue = 0;
1433 }
1434 }
1435 result = IDirectDraw2_CreatePalette(ddraw2,
1436 (DDPCAPS_8BIT|DDPCAPS_ALLOW256),
1437 SDL_colors, &SDL_palette, NULL);
1438 if ( result != DD_OK ) {
1439 SetDDerror("DirectDraw2::CreatePalette", result);
1440 return(NULL);
1441 }
1442 result = IDirectDrawSurface3_SetPalette(SDL_primary,
1443 SDL_palette);
1444 if ( result != DD_OK ) {
1445 SetDDerror("DirectDrawSurface3::SetPalette", result);
1446 return(NULL);
1447 }
1448 }
1449
1450 /* Create our video surface using the same pixel format */
1451 video = current;
1452 if ( (width != video->w) || (height != video->h)
1453 || (video->format->BitsPerPixel !=
1454#if defined(NONAMELESSUNION)
1455 ddsd.ddpfPixelFormat.u1.dwRGBBitCount) ) {
1456#else
1457 ddsd.ddpfPixelFormat.dwRGBBitCount) ) {
1458#endif
1459 SDL_FreeSurface(video);
1460 video = SDL_CreateRGBSurface(SDL_SWSURFACE, 0, 0,
1461#if defined(NONAMELESSUNION)
1462 ddsd.ddpfPixelFormat.u1.dwRGBBitCount,
1463 ddsd.ddpfPixelFormat.u2.dwRBitMask,
1464 ddsd.ddpfPixelFormat.u3.dwGBitMask,
1465 ddsd.ddpfPixelFormat.u4.dwBBitMask,
1466#else
1467 ddsd.ddpfPixelFormat.dwRGBBitCount,
1468 ddsd.ddpfPixelFormat.dwRBitMask,
1469 ddsd.ddpfPixelFormat.dwGBitMask,
1470 ddsd.ddpfPixelFormat.dwBBitMask,
1471#endif
1472 0);
1473 if ( video == NULL ) {
1474 SDL_OutOfMemory();
1475 return(NULL);
1476 }
1477 prev_w = video->w;
1478 prev_h = video->h;
1479 video->w = width;
1480 video->h = height;
1481 video->pitch = 0;
1482 }
1483 video->flags = 0; /* Clear flags */
1484
1485 /* If not fullscreen, locking is possible, but it doesn't do what
1486 the caller really expects -- if the locked surface is written to,
1487 the appropriate portion of the entire screen is modified, not
1488 the application window, as we would like.
1489 Note that it is still possible to write directly to display
1490 memory, but the application must respect the clip list of
1491 the surface. There might be some odd timing interactions
1492 involving clip list updates and background refreshing as
1493 Windows moves other windows across our window.
1494 We currently don't support this, even though it might be a
1495 good idea since BeOS has an implementation of BDirectWindow
1496 that does the same thing. This would be most useful for
1497 applications that do complete screen updates every frame.
1498 -- Fixme?
1499 */
1500 if ( (flags & SDL_FULLSCREEN) != SDL_FULLSCREEN ) {
1501 /* Necessary if we're going from fullscreen to window */
1502 if ( video->pixels == NULL ) {
1503 video->pitch = (width*video->format->BytesPerPixel);
1504 /* Pitch needs to be QWORD (8-byte) aligned */
1505 video->pitch = (video->pitch + 7) & ~7;
1506 video->pixels = (void *)SDL_malloc(video->h*video->pitch);
1507 if ( video->pixels == NULL ) {
1508 if ( video != current ) {
1509 SDL_FreeSurface(video);
1510 }
1511 SDL_OutOfMemory();
1512 return(NULL);
1513 }
1514 }
1515 dd_surface3 = NULL;
1516#if 0 /* FIXME: enable this when SDL consistently reports lost surfaces */
1517 if ( (flags & SDL_HWSURFACE) == SDL_HWSURFACE ) {
1518 video->flags |= SDL_HWSURFACE;
1519 } else {
1520 video->flags |= SDL_SWSURFACE;
1521 }
1522#else
1523 video->flags |= SDL_SWSURFACE;
1524#endif
1525 if ( (flags & SDL_RESIZABLE) && !(flags & SDL_NOFRAME) ) {
1526 video->flags |= SDL_RESIZABLE;
1527 }
1528 if ( flags & SDL_NOFRAME ) {
1529 video->flags |= SDL_NOFRAME;
1530 }
1531 } else {
1532 /* Necessary if we're going from window to fullscreen */
1533 if ( video->pixels != NULL ) {
1534 SDL_free(video->pixels);
1535 video->pixels = NULL;
1536 }
1537 dd_surface3 = SDL_primary;
1538 video->flags |= SDL_HWSURFACE;
1539 }
1540
1541 /* See if the primary surface has double-buffering enabled */
1542 if ( (ddsd.ddsCaps.dwCaps & DDSCAPS_FLIP) == DDSCAPS_FLIP ) {
1543 video->flags |= SDL_DOUBLEBUF;
1544 }
1545
1546 /* Allocate the SDL surface associated with the primary surface */
1547 if ( DX5_AllocDDSurface(this, video, dd_surface3,
1548 video->flags&SDL_HWSURFACE) < 0 ) {
1549 if ( video != current ) {
1550 SDL_FreeSurface(video);
1551 }
1552 return(NULL);
1553 }
1554
1555 /* Use the appropriate blitting function */
1556 if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
1557 video->flags |= SDL_FULLSCREEN;
1558 if ( video->format->palette != NULL ) {
1559 video->flags |= SDL_HWPALETTE;
1560 }
1561 this->UpdateRects = DX5_DirectUpdate;
1562 } else {
1563 this->UpdateRects = DX5_WindowUpdate;
1564 }
1565
1566 /* Make our window the proper size, set the clipper, then show it */
1567 if ( (flags & SDL_FULLSCREEN) != SDL_FULLSCREEN ) {
1568 /* Create and set a clipper on our primary surface */
1569 if ( SDL_clipper == NULL ) {
1570 result = IDirectDraw2_CreateClipper(ddraw2,
1571 0, &SDL_clipper, NULL);
1572 if ( result != DD_OK ) {
1573 if ( video != current ) {
1574 SDL_FreeSurface(video);
1575 }
1576 SetDDerror("DirectDraw2::CreateClipper",result);
1577 return(NULL);
1578 }
1579 }
1580 result = IDirectDrawClipper_SetHWnd(SDL_clipper, 0, SDL_Window);
1581 if ( result != DD_OK ) {
1582 if ( video != current ) {
1583 SDL_FreeSurface(video);
1584 }
1585 SetDDerror("DirectDrawClipper::SetHWnd", result);
1586 return(NULL);
1587 }
1588 result = IDirectDrawSurface3_SetClipper(SDL_primary,
1589 SDL_clipper);
1590 if ( result != DD_OK ) {
1591 if ( video != current ) {
1592 SDL_FreeSurface(video);
1593 }
1594 SetDDerror("DirectDrawSurface3::SetClipper", result);
1595 return(NULL);
1596 }
1597
1598 /* Resize the window (copied from SDL WinDIB driver) */
1599 if ( !SDL_windowid && !IsZoomed(SDL_Window) ) {
1600 RECT bounds;
1601 int x, y;
1602 UINT swp_flags;
1603 const char *window = NULL;
1604 const char *center = NULL;
1605
1606 if ( video->w != prev_w || video->h != prev_h ) {
1607 window = SDL_getenv("SDL_VIDEO_WINDOW_POS");
1608 center = SDL_getenv("SDL_VIDEO_CENTERED");
1609 if ( window ) {
1610 if ( SDL_sscanf(window, "%d,%d", &x, &y) == 2 ) {
1611 SDL_windowX = x;
1612 SDL_windowY = y;
1613 }
1614 if ( SDL_strcmp(window, "center") == 0 ) {
1615 center = window;
1616 }
1617 }
1618 }
1619 swp_flags = SWP_NOCOPYBITS;
1620
1621 bounds.left = SDL_windowX;
1622 bounds.top = SDL_windowY;
1623 bounds.right = SDL_windowX+video->w;
1624 bounds.bottom = SDL_windowY+video->h;
1625 AdjustWindowRectEx(&bounds, GetWindowLong(SDL_Window, GWL_STYLE), (GetMenu(SDL_Window) != NULL), 0);
1626 width = bounds.right-bounds.left;
1627 height = bounds.bottom-bounds.top;
1628 if ( center ) {
1629 x = (GetSystemMetrics(SM_CXSCREEN)-width)/2;
1630 y = (GetSystemMetrics(SM_CYSCREEN)-height)/2;
1631 } else if ( SDL_windowX || SDL_windowY || window ) {
1632 x = bounds.left;
1633 y = bounds.top;
1634 } else {
1635 x = y = -1;
1636 swp_flags |= SWP_NOMOVE;
1637 }
1638 SetWindowPos(SDL_Window, HWND_NOTOPMOST, x, y, width, height, swp_flags);
1639 SDL_windowX = SDL_bounds.left;
1640 SDL_windowY = SDL_bounds.top;
1641 }
1642
1643 }
1644 ShowWindow(SDL_Window, SW_SHOW);
1645 SetForegroundWindow(SDL_Window);
1646 SDL_resizing = 0;
1647
1648 /* JC 14 Mar 2006
1649 Flush the message loop or this can cause big problems later
1650 Especially if the user decides to use dialog boxes or assert()!
1651 */
1652 WIN_FlushMessageQueue();
1653
1654 /* We're live! */
1655 return(video);
1656}
1657
1658struct private_hwdata {
1659 LPDIRECTDRAWSURFACE3 dd_surface;
1660 LPDIRECTDRAWSURFACE3 dd_writebuf;
1661};
1662
1663static int DX5_AllocDDSurface(_THIS, SDL_Surface *surface,
1664 LPDIRECTDRAWSURFACE3 requested, Uint32 flag)
1665{
1666 LPDIRECTDRAWSURFACE dd_surface1;
1667 LPDIRECTDRAWSURFACE3 dd_surface3;
1668 DDSURFACEDESC ddsd;
1669 HRESULT result;
1670
1671 /* Clear the hardware flag, in case we fail */
1672 surface->flags &= ~flag;
1673
1674 /* Allocate the hardware acceleration data */
1675 surface->hwdata = (struct private_hwdata *)
1676 SDL_malloc(sizeof(*surface->hwdata));
1677 if ( surface->hwdata == NULL ) {
1678 SDL_OutOfMemory();
1679 return(-1);
1680 }
1681 dd_surface3 = NULL;
1682
1683 /* Set up the surface description */
1684 SDL_memset(&ddsd, 0, sizeof(ddsd));
1685 ddsd.dwSize = sizeof(ddsd);
1686 ddsd.dwFlags = (DDSD_WIDTH|DDSD_HEIGHT|DDSD_CAPS|
1687 DDSD_PITCH|DDSD_PIXELFORMAT);
1688 ddsd.dwWidth = surface->w;
1689 ddsd.dwHeight= surface->h;
1690#if defined(NONAMELESSUNION)
1691 ddsd.u1.lPitch = surface->pitch;
1692#else
1693 ddsd.lPitch = surface->pitch;
1694#endif
1695 if ( (flag & SDL_HWSURFACE) == SDL_HWSURFACE ) {
1696 ddsd.ddsCaps.dwCaps =
1697 (DDSCAPS_OFFSCREENPLAIN|DDSCAPS_VIDEOMEMORY);
1698 } else {
1699 ddsd.ddsCaps.dwCaps =
1700 (DDSCAPS_OFFSCREENPLAIN|DDSCAPS_SYSTEMMEMORY);
1701 }
1702 ddsd.ddpfPixelFormat.dwSize = sizeof(ddsd.ddpfPixelFormat);
1703 ddsd.ddpfPixelFormat.dwFlags = DDPF_RGB;
1704 if ( surface->format->palette ) {
1705 ddsd.ddpfPixelFormat.dwFlags |= DDPF_PALETTEINDEXED8;
1706 }
1707#if defined(NONAMELESSUNION)
1708 ddsd.ddpfPixelFormat.u1.dwRGBBitCount = surface->format->BitsPerPixel;
1709 ddsd.ddpfPixelFormat.u2.dwRBitMask = surface->format->Rmask;
1710 ddsd.ddpfPixelFormat.u3.dwGBitMask = surface->format->Gmask;
1711 ddsd.ddpfPixelFormat.u4.dwBBitMask = surface->format->Bmask;
1712#else
1713 ddsd.ddpfPixelFormat.dwRGBBitCount = surface->format->BitsPerPixel;
1714 ddsd.ddpfPixelFormat.dwRBitMask = surface->format->Rmask;
1715 ddsd.ddpfPixelFormat.dwGBitMask = surface->format->Gmask;
1716 ddsd.ddpfPixelFormat.dwBBitMask = surface->format->Bmask;
1717#endif
1718
1719 /* Create the DirectDraw video surface */
1720 if ( requested != NULL ) {
1721 dd_surface3 = requested;
1722 } else {
1723 result = IDirectDraw2_CreateSurface(ddraw2,
1724 &ddsd, &dd_surface1, NULL);
1725 if ( result != DD_OK ) {
1726 SetDDerror("DirectDraw2::CreateSurface", result);
1727 goto error_end;
1728 }
1729 result = IDirectDrawSurface_QueryInterface(dd_surface1,
1730 &IID_IDirectDrawSurface3, (LPVOID *)&dd_surface3);
1731 IDirectDrawSurface_Release(dd_surface1);
1732 if ( result != DD_OK ) {
1733 SetDDerror("DirectDrawSurface::QueryInterface", result);
1734 goto error_end;
1735 }
1736 }
1737
1738 if ( (flag & SDL_HWSURFACE) == SDL_HWSURFACE ) {
1739 /* Check to see whether the surface actually ended up
1740 in video memory, and fail if not. We expect the
1741 surfaces we create here to actually be in hardware!
1742 */
1743 result = IDirectDrawSurface3_GetCaps(dd_surface3,&ddsd.ddsCaps);
1744 if ( result != DD_OK ) {
1745 SetDDerror("DirectDrawSurface3::GetCaps", result);
1746 goto error_end;
1747 }
1748 if ( (ddsd.ddsCaps.dwCaps&DDSCAPS_VIDEOMEMORY) !=
1749 DDSCAPS_VIDEOMEMORY ) {
1750 SDL_SetError("No room in video memory");
1751 goto error_end;
1752 }
1753 } else {
1754 /* Try to hook our surface memory */
1755 ddsd.dwFlags = DDSD_LPSURFACE;
1756 ddsd.lpSurface = surface->pixels;
1757 result = IDirectDrawSurface3_SetSurfaceDesc(dd_surface3,
1758 &ddsd, 0);
1759 if ( result != DD_OK ) {
1760 SetDDerror("DirectDraw2::SetSurfaceDesc", result);
1761 goto error_end;
1762 }
1763
1764 }
1765
1766 /* Make sure the surface format was set properly */
1767 SDL_memset(&ddsd, 0, sizeof(ddsd));
1768 ddsd.dwSize = sizeof(ddsd);
1769 result = IDirectDrawSurface3_Lock(dd_surface3, NULL,
1770 &ddsd, (DDLOCK_NOSYSLOCK|DDLOCK_WAIT), NULL);
1771 if ( result != DD_OK ) {
1772 SetDDerror("DirectDrawSurface3::Lock", result);
1773 goto error_end;
1774 }
1775 IDirectDrawSurface3_Unlock(dd_surface3, NULL);
1776
1777 if ( (flag & SDL_HWSURFACE) == SDL_SWSURFACE ) {
1778 if ( ddsd.lpSurface != surface->pixels ) {
1779 SDL_SetError("DDraw didn't use SDL surface memory");
1780 goto error_end;
1781 }
1782 if (
1783#if defined(NONAMELESSUNION)
1784 ddsd.u1.lPitch
1785#else
1786 ddsd.lPitch
1787#endif
1788 != (LONG)surface->pitch ) {
1789 SDL_SetError("DDraw created surface with wrong pitch");
1790 goto error_end;
1791 }
1792 } else {
1793#if defined(NONAMELESSUNION)
1794 surface->pitch = (Uint16)ddsd.u1.lPitch;
1795#else
1796 surface->pitch = (Uint16)ddsd.lPitch;
1797#endif
1798 }
1799#if defined(NONAMELESSUNION)
1800 if ( (ddsd.ddpfPixelFormat.u1.dwRGBBitCount !=
1801 surface->format->BitsPerPixel) ||
1802 (ddsd.ddpfPixelFormat.u2.dwRBitMask != surface->format->Rmask) ||
1803 (ddsd.ddpfPixelFormat.u3.dwGBitMask != surface->format->Gmask) ||
1804 (ddsd.ddpfPixelFormat.u4.dwBBitMask != surface->format->Bmask) ){
1805#else
1806 if ( (ddsd.ddpfPixelFormat.dwRGBBitCount !=
1807 surface->format->BitsPerPixel) ||
1808 (ddsd.ddpfPixelFormat.dwRBitMask != surface->format->Rmask) ||
1809 (ddsd.ddpfPixelFormat.dwGBitMask != surface->format->Gmask) ||
1810 (ddsd.ddpfPixelFormat.dwBBitMask != surface->format->Bmask) ){
1811#endif
1812 SDL_SetError("DDraw didn't use SDL surface description");
1813 goto error_end;
1814 }
1815 if ( (ddsd.dwWidth != (DWORD)surface->w) ||
1816 (ddsd.dwHeight != (DWORD)surface->h) ) {
1817 SDL_SetError("DDraw created surface with wrong size");
1818 goto error_end;
1819 }
1820
1821 /* Set the surface private data */
1822 surface->flags |= flag;
1823 surface->hwdata->dd_surface = dd_surface3;
1824 if ( (surface->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) {
1825 LPDIRECTDRAWSURFACE3 dd_writebuf;
1826
1827 ddsd.ddsCaps.dwCaps = DDSCAPS_BACKBUFFER;
1828 result = IDirectDrawSurface3_GetAttachedSurface(dd_surface3,
1829 &ddsd.ddsCaps, &dd_writebuf);
1830 if ( result != DD_OK ) {
1831 SetDDerror("DirectDrawSurface3::GetAttachedSurface",
1832 result);
1833 } else {
1834 dd_surface3 = dd_writebuf;
1835 }
1836 }
1837 surface->hwdata->dd_writebuf = dd_surface3;
1838
1839 /* We're ready to go! */
1840 return(0);
1841
1842 /* Okay, so goto's are cheesy, but there are so many possible
1843 errors in this function, and the cleanup is the same in
1844 every single case. Is there a better way, other than deeply
1845 nesting the code?
1846 */
1847error_end:
1848 if ( (dd_surface3 != NULL) && (dd_surface3 != requested) ) {
1849 IDirectDrawSurface_Release(dd_surface3);
1850 }
1851 SDL_free(surface->hwdata);
1852 surface->hwdata = NULL;
1853 return(-1);
1854}
1855
1856static int DX5_AllocHWSurface(_THIS, SDL_Surface *surface)
1857{
1858 /* DDraw limitation -- you need to set cooperative level first */
1859 if ( SDL_primary == NULL ) {
1860 SDL_SetError("You must set a non-GL video mode first");
1861 return(-1);
1862 }
1863 return(DX5_AllocDDSurface(this, surface, NULL, SDL_HWSURFACE));
1864}
1865
1866#ifdef DDRAW_DEBUG
1867void PrintSurface(char *title, LPDIRECTDRAWSURFACE3 surface, Uint32 flags)
1868{
1869 DDSURFACEDESC ddsd;
1870
1871 /* Lock and load! */
1872 SDL_memset(&ddsd, 0, sizeof(ddsd));
1873 ddsd.dwSize = sizeof(ddsd);
1874 if ( IDirectDrawSurface3_Lock(surface, NULL, &ddsd,
1875 (DDLOCK_NOSYSLOCK|DDLOCK_WAIT), NULL) != DD_OK ) {
1876 return;
1877 }
1878 IDirectDrawSurface3_Unlock(surface, NULL);
1879
1880 fprintf(stderr, "%s:\n", title);
1881 fprintf(stderr, "\tSize: %dx%d in %s at %ld bpp (pitch = %ld)\n",
1882 ddsd.dwWidth, ddsd.dwHeight,
1883 (flags & SDL_HWSURFACE) ? "hardware" : "software",
1884#if defined(NONAMELESSUNION)
1885 ddsd.ddpfPixelFormat.u1.dwRGBBitCount, ddsd.u1.lPitch);
1886#else
1887 ddsd.ddpfPixelFormat.dwRGBBitCount, ddsd.lPitch);
1888#endif
1889 fprintf(stderr, "\tR = 0x%X, G = 0x%X, B = 0x%X\n",
1890#if defined(NONAMELESSUNION)
1891 ddsd.ddpfPixelFormat.u2.dwRBitMask,
1892 ddsd.ddpfPixelFormat.u3.dwGBitMask,
1893 ddsd.ddpfPixelFormat.u4.dwBBitMask);
1894#else
1895 ddsd.ddpfPixelFormat.dwRBitMask,
1896 ddsd.ddpfPixelFormat.dwGBitMask,
1897 ddsd.ddpfPixelFormat.dwBBitMask);
1898#endif
1899}
1900#endif /* DDRAW_DEBUG */
1901
1902static int DX5_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect,
1903 SDL_Surface *dst, SDL_Rect *dstrect)
1904{
1905 LPDIRECTDRAWSURFACE3 src_surface;
1906 LPDIRECTDRAWSURFACE3 dst_surface;
1907 DWORD flags;
1908 RECT rect;
1909 HRESULT result;
1910
1911 /* Set it up.. the desination must have a DDRAW surface */
1912 src_surface = src->hwdata->dd_writebuf;
1913 dst_surface = dst->hwdata->dd_writebuf;
1914 rect.top = (LONG)srcrect->y;
1915 rect.bottom = (LONG)srcrect->y+srcrect->h;
1916 rect.left = (LONG)srcrect->x;
1917 rect.right = (LONG)srcrect->x+srcrect->w;
1918 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY )
1919 flags = DDBLTFAST_SRCCOLORKEY;
1920 else
1921 flags = DDBLTFAST_NOCOLORKEY;
1922 /* FIXME: We can remove this flag for _really_ fast blit queuing,
1923 but it will affect the return values of locks and flips.
1924 */
1925 flags |= DDBLTFAST_WAIT;
1926
1927 /* Do the blit! */
1928 result = IDirectDrawSurface3_BltFast(dst_surface,
1929 dstrect->x, dstrect->y, src_surface, &rect, flags);
1930 if ( result != DD_OK ) {
1931 if ( result == DDERR_SURFACELOST ) {
1932 result = IDirectDrawSurface3_Restore(src_surface);
1933 result = IDirectDrawSurface3_Restore(dst_surface);
1934 /* The surfaces need to be reloaded with artwork */
1935 SDL_SetError("Blit surfaces were lost, reload them");
1936 return(-2);
1937 }
1938 SetDDerror("IDirectDrawSurface3::BltFast", result);
1939#ifdef DDRAW_DEBUG
1940 fprintf(stderr, "Original dest rect: %dx%d at %d,%d\n", dstrect->w, dstrect->h, dstrect->x, dstrect->y);
1941 fprintf(stderr, "HW accelerated %sblit to from 0x%p to 0x%p at (%d,%d)\n",
1942 (src->flags & SDL_SRCCOLORKEY) ? "colorkey " : "", src, dst,
1943 dstrect->x, dstrect->y);
1944 PrintSurface("SRC", src_surface, src->flags);
1945 PrintSurface("DST", dst_surface, dst->flags);
1946 fprintf(stderr, "Source rectangle: (%d,%d) - (%d,%d)\n",
1947 rect.left, rect.top, rect.right, rect.bottom);
1948#endif
1949 /* Unexpected error, fall back to software blit */
1950 return(src->map->sw_blit(src, srcrect, dst, dstrect));
1951 }
1952 return(0);
1953}
1954
1955static int DX5_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst)
1956{
1957 int accelerated;
1958
1959 /* We need to have a DDraw surface for HW blits */
1960 if ( (src->flags & SDL_HWSURFACE) == SDL_SWSURFACE ) {
1961 /* Allocate a DDraw surface for the blit */
1962 if ( src->hwdata == NULL ) {
1963 DX5_AllocDDSurface(this, src, NULL, SDL_SWSURFACE);
1964 }
1965 }
1966 if ( src->hwdata == NULL ) {
1967 return(0);
1968 }
1969
1970 /* Set initial acceleration on */
1971 src->flags |= SDL_HWACCEL;
1972
1973 /* Set the surface attributes */
1974 if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
1975 if ( DX5_SetHWColorKey(this, src, src->format->colorkey) < 0 ) {
1976 src->flags &= ~SDL_HWACCEL;
1977 }
1978 }
1979 if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
1980 if ( DX5_SetHWAlpha(this, src, src->format->alpha) < 0 ) {
1981 src->flags &= ~SDL_HWACCEL;
1982 }
1983 }
1984
1985 /* Check to see if final surface blit is accelerated */
1986 accelerated = !!(src->flags & SDL_HWACCEL);
1987 if ( accelerated ) {
1988#ifdef DDRAW_DEBUG
1989 fprintf(stderr, "Setting accelerated blit on 0x%p\n", src);
1990#endif
1991 src->map->hw_blit = DX5_HWAccelBlit;
1992 }
1993 return(accelerated);
1994}
1995
1996static int DX5_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color)
1997{
1998 LPDIRECTDRAWSURFACE3 dst_surface;
1999 RECT area;
2000 DDBLTFX bltfx;
2001 HRESULT result;
2002
2003#ifdef DDRAW_DEBUG
2004 fprintf(stderr, "HW accelerated fill at (%d,%d)\n", dstrect->x, dstrect->y);
2005#endif
2006 dst_surface = dst->hwdata->dd_writebuf;
2007 area.top = (LONG)dstrect->y;
2008 area.bottom = (LONG)dstrect->y+dstrect->h;
2009 area.left = (LONG)dstrect->x;
2010 area.right = (LONG)dstrect->x+dstrect->w;
2011 bltfx.dwSize = sizeof(bltfx);
2012#if defined(NONAMELESSUNION)
2013 bltfx.u5.dwFillColor = color;
2014#else
2015 bltfx.dwFillColor = color;
2016#endif
2017 result = IDirectDrawSurface3_Blt(dst_surface,
2018 &area, NULL, NULL, DDBLT_COLORFILL|DDBLT_WAIT, &bltfx);
2019 if ( result == DDERR_SURFACELOST ) {
2020 IDirectDrawSurface3_Restore(dst_surface);
2021 result = IDirectDrawSurface3_Blt(dst_surface,
2022 &area, NULL, NULL, DDBLT_COLORFILL|DDBLT_WAIT, &bltfx);
2023 }
2024 if ( result != DD_OK ) {
2025 SetDDerror("IDirectDrawSurface3::Blt", result);
2026 return(-1);
2027 }
2028 return(0);
2029}
2030
2031static int DX5_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key)
2032{
2033 DDCOLORKEY colorkey;
2034 HRESULT result;
2035
2036 /* Set the surface colorkey */
2037 colorkey.dwColorSpaceLowValue = key;
2038 colorkey.dwColorSpaceHighValue = key;
2039 result = IDirectDrawSurface3_SetColorKey(
2040 surface->hwdata->dd_surface, DDCKEY_SRCBLT, &colorkey);
2041 if ( result != DD_OK ) {
2042 SetDDerror("IDirectDrawSurface3::SetColorKey", result);
2043 return(-1);
2044 }
2045 return(0);
2046}
2047static int DX5_SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 alpha)
2048{
2049 return(-1);
2050}
2051
2052static int DX5_LockHWSurface(_THIS, SDL_Surface *surface)
2053{
2054 HRESULT result;
2055 LPDIRECTDRAWSURFACE3 dd_surface;
2056 DDSURFACEDESC ddsd;
2057
2058 /* Lock and load! */
2059 dd_surface = surface->hwdata->dd_writebuf;
2060 SDL_memset(&ddsd, 0, sizeof(ddsd));
2061 ddsd.dwSize = sizeof(ddsd);
2062 result = IDirectDrawSurface3_Lock(dd_surface, NULL, &ddsd,
2063 (DDLOCK_NOSYSLOCK|DDLOCK_WAIT), NULL);
2064 if ( result == DDERR_SURFACELOST ) {
2065 result = IDirectDrawSurface3_Restore(
2066 surface->hwdata->dd_surface);
2067 result = IDirectDrawSurface3_Lock(dd_surface, NULL, &ddsd,
2068 (DDLOCK_NOSYSLOCK|DDLOCK_WAIT), NULL);
2069 }
2070 if ( result != DD_OK ) {
2071 SetDDerror("DirectDrawSurface3::Lock", result);
2072 return(-1);
2073 }
2074 /* Pitch might have changed -- recalculate pitch and offset */
2075#if defined(NONAMELESSUNION)
2076 if ( surface->pitch != ddsd.u1.lPitch ) {
2077 surface->pitch = ddsd.u1.lPitch;
2078#else
2079 if ( surface->pitch != ddsd.lPitch ) {
2080 surface->pitch = (Uint16)ddsd.lPitch;
2081#endif
2082 surface->offset =
2083 ((ddsd.dwHeight-surface->h)/2)*surface->pitch +
2084 ((ddsd.dwWidth-surface->w)/2)*
2085 surface->format->BytesPerPixel;
2086 }
2087 surface->pixels = ddsd.lpSurface;
2088 return(0);
2089}
2090
2091static void DX5_UnlockHWSurface(_THIS, SDL_Surface *surface)
2092{
2093 IDirectDrawSurface3_Unlock(surface->hwdata->dd_writebuf, NULL);
2094 surface->pixels = NULL;
2095}
2096
2097static int DX5_FlipHWSurface(_THIS, SDL_Surface *surface)
2098{
2099 HRESULT result;
2100 LPDIRECTDRAWSURFACE3 dd_surface;
2101
2102 dd_surface = surface->hwdata->dd_surface;
2103
2104 /* to prevent big slowdown on fast computers, wait here instead of driver ring 0 code */
2105 /* Dmitry Yakimov (ftech@tula.net) */
2106 while(IDirectDrawSurface3_GetFlipStatus(dd_surface, DDGBS_ISBLTDONE) == DDERR_WASSTILLDRAWING);
2107
2108 result = IDirectDrawSurface3_Flip(dd_surface, NULL, DDFLIP_WAIT);
2109 if ( result == DDERR_SURFACELOST ) {
2110 result = IDirectDrawSurface3_Restore(
2111 surface->hwdata->dd_surface);
2112 while(IDirectDrawSurface3_GetFlipStatus(dd_surface, DDGBS_ISBLTDONE) == DDERR_WASSTILLDRAWING);
2113 result = IDirectDrawSurface3_Flip(dd_surface, NULL, DDFLIP_WAIT);
2114 }
2115 if ( result != DD_OK ) {
2116 SetDDerror("DirectDrawSurface3::Flip", result);
2117 return(-1);
2118 }
2119 return(0);
2120}
2121
2122static void DX5_FreeHWSurface(_THIS, SDL_Surface *surface)
2123{
2124 if ( surface->hwdata ) {
2125 if ( surface->hwdata->dd_surface != SDL_primary ) {
2126 IDirectDrawSurface3_Release(surface->hwdata->dd_surface);
2127 }
2128 SDL_free(surface->hwdata);
2129 surface->hwdata = NULL;
2130 }
2131}
2132
2133void DX5_WindowUpdate(_THIS, int numrects, SDL_Rect *rects)
2134{
2135 HRESULT result;
2136 int i;
2137 RECT src, dst;
2138
2139 for ( i=0; i<numrects; ++i ) {
2140 src.top = (LONG)rects[i].y;
2141 src.bottom = (LONG)rects[i].y+rects[i].h;
2142 src.left = (LONG)rects[i].x;
2143 src.right = (LONG)rects[i].x+rects[i].w;
2144 dst.top = SDL_bounds.top+src.top;
2145 dst.left = SDL_bounds.left+src.left;
2146 dst.bottom = SDL_bounds.top+src.bottom;
2147 dst.right = SDL_bounds.left+src.right;
2148 result = IDirectDrawSurface3_Blt(SDL_primary, &dst,
2149 this->screen->hwdata->dd_surface, &src,
2150 DDBLT_WAIT, NULL);
2151 /* Doh! Check for lost surface and restore it */
2152 if ( result == DDERR_SURFACELOST ) {
2153 IDirectDrawSurface3_Restore(SDL_primary);
2154 IDirectDrawSurface3_Blt(SDL_primary, &dst,
2155 this->screen->hwdata->dd_surface, &src,
2156 DDBLT_WAIT, NULL);
2157 }
2158 }
2159}
2160
2161void DX5_DirectUpdate(_THIS, int numrects, SDL_Rect *rects)
2162{
2163}
2164
2165/* Compress a full palette into the limited number of colors given to us
2166 by windows.
2167
2168 The "best" way to do this is to sort the colors by diversity and place
2169 the most diverse colors into the limited palette. Unfortunately this
2170 results in widely varying colors being displayed in the interval during
2171 which the windows palette has been set, and the mapping of the shadow
2172 surface to the new palette. This is especially noticeable during fades.
2173
2174 To deal with this problem, we can copy a predetermined portion of the
2175 full palette, and use that as the limited palette. This allows colors
2176 to fade smoothly as the remapping is very similar on each palette change.
2177 Unfortunately, this breaks applications which partition the palette into
2178 distinct and widely varying areas, expecting all colors to be available.
2179
2180 I'm making them both available, chosen at compile time.
2181 If you want the chunk-o-palette algorithm, define SIMPLE_COMPRESSION,
2182 otherwise the sort-by-diversity algorithm will be used.
2183*/
2184#define SIMPLE_COMPRESSION
2185#define CS_CS_DIST(A, B) ({ \
2186 int r = (A.r - B.r); \
2187 int g = (A.g - B.g); \
2188 int b = (A.b - B.b); \
2189 (r*r + g*g + b*b); \
2190})
2191static void DX5_CompressPalette(_THIS, SDL_Color *colors, int ncolors, int maxcolors)
2192{
2193#ifdef SIMPLE_COMPRESSION
2194 int i, j;
2195#else
2196 static SDL_Color zero = { 0, 0, 0, 0 };
2197 int i, j;
2198 int max, dist;
2199 int prev, next;
2200 int *pool;
2201 int *seen, *order;
2202#endif
2203
2204 /* Does this happen? */
2205 if ( maxcolors > ncolors ) {
2206 maxcolors = ncolors;
2207 }
2208
2209#ifdef SIMPLE_COMPRESSION
2210 /* Just copy the first "maxcolors" colors */
2211 for ( j=10, i=0; i<maxcolors; ++i, ++j ) {
2212 SDL_colors[j].peRed = colors[i].r;
2213 SDL_colors[j].peGreen = colors[i].g;
2214 SDL_colors[j].peBlue = colors[i].b;
2215 }
2216#else
2217 /* Allocate memory for the arrays we use */
2218 pool = SDL_stack_alloc(int, 2*ncolors);
2219 if ( pool == NULL ) {
2220 /* No worries, just return */;
2221 return;
2222 }
2223 seen = pool;
2224 SDL_memset(seen, 0, ncolors*sizeof(int));
2225 order = pool+ncolors;
2226
2227 /* Start with the brightest color */
2228 max = 0;
2229 for ( i=0; i<ncolors; ++i ) {
2230 dist = CS_CS_DIST(zero, colors[i]);
2231 if ( dist >= max ) {
2232 max = dist;
2233 next = i;
2234 }
2235 }
2236 j = 0;
2237 order[j++] = next;
2238 seen[next] = 1;
2239 prev = next;
2240
2241 /* Keep going through all the colors */
2242 while ( j < maxcolors ) {
2243 max = 0;
2244 for ( i=0; i<ncolors; ++i ) {
2245 if ( seen[i] ) {
2246 continue;
2247 }
2248 dist = CS_CS_DIST(colors[i], colors[prev]);
2249 if ( dist >= max ) {
2250 max = dist;
2251 next = i;
2252 }
2253 }
2254 order[j++] = next;
2255 seen[next] = 1;
2256 prev = next;
2257 }
2258
2259 /* Compress the colors to the palette */
2260 for ( j=10, i=0; i<maxcolors; ++i, ++j ) {
2261 SDL_colors[j].peRed = colors[order[i]].r;
2262 SDL_colors[j].peGreen = colors[order[i]].g;
2263 SDL_colors[j].peBlue = colors[order[i]].b;
2264 }
2265 SDL_stack_free(pool);
2266#endif /* SIMPLE_COMPRESSION */
2267}
2268
2269/* Set the system colormap in both fullscreen and windowed modes */
2270int DX5_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
2271{
2272 int i;
2273 int alloct_all;
2274
2275 /* Copy palette colors into display palette */
2276 alloct_all = 0;
2277 if ( SDL_palette != NULL ) {
2278 if ( (this->screen->flags&SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
2279 /* We can set all entries explicitly */
2280 for ( i=0; i< ncolors; ++i ) {
2281 int j = firstcolor + i;
2282 SDL_colors[j].peRed = colors[i].r;
2283 SDL_colors[j].peGreen = colors[i].g;
2284 SDL_colors[j].peBlue = colors[i].b;
2285 }
2286 /* This sends an WM_PALETTECHANGED message to us */
2287 colorchange_expected = 1;
2288 IDirectDrawPalette_SetEntries(SDL_palette, 0,
2289 firstcolor, ncolors, &SDL_colors[firstcolor]);
2290 alloct_all = 1;
2291 } else {
2292 /* Grab the 236 most diverse colors in the palette */
2293 DX5_CompressPalette(this, colors, ncolors, 236);
2294 /* This sends an WM_PALETTECHANGED message to us */
2295 colorchange_expected = 1;
2296 IDirectDrawPalette_SetEntries(SDL_palette, 0,
2297 0, 256, SDL_colors);
2298 }
2299 }
2300 return(alloct_all);
2301}
2302
2303/* Gamma code is only available on DirectX 7 and newer */
2304static int DX5_SetGammaRamp(_THIS, Uint16 *ramp)
2305{
2306#ifdef IDirectDrawGammaControl_SetGammaRamp
2307 LPDIRECTDRAWGAMMACONTROL gamma;
2308 DDGAMMARAMP gamma_ramp;
2309 HRESULT result;
2310#endif
2311
2312 /* In windowed or OpenGL mode, use windib gamma code */
2313 if ( ! DDRAW_FULLSCREEN() ) {
2314 return DIB_SetGammaRamp(this, ramp);
2315 }
2316
2317#ifndef IDirectDrawGammaControl_SetGammaRamp
2318 SDL_SetError("SDL compiled without DirectX gamma ramp support");
2319 return -1;
2320#else
2321 /* Check for a video mode! */
2322 if ( ! SDL_primary ) {
2323 SDL_SetError("A video mode must be set for gamma correction");
2324 return(-1);
2325 }
2326
2327 /* Get the gamma control object */
2328 result = IDirectDrawSurface3_QueryInterface(SDL_primary,
2329 &IID_IDirectDrawGammaControl, (LPVOID *)&gamma);
2330 if ( result != DD_OK ) {
2331 SetDDerror("DirectDrawSurface3::QueryInterface(GAMMA)", result);
2332 return(-1);
2333 }
2334
2335 /* Set up the gamma ramp */
2336 SDL_memcpy(gamma_ramp.red, &ramp[0*256], 256*sizeof(*ramp));
2337 SDL_memcpy(gamma_ramp.green, &ramp[1*256], 256*sizeof(*ramp));
2338 SDL_memcpy(gamma_ramp.blue, &ramp[2*256], 256*sizeof(*ramp));
2339 result = IDirectDrawGammaControl_SetGammaRamp(gamma, 0, &gamma_ramp);
2340 if ( result != DD_OK ) {
2341 SetDDerror("DirectDrawGammaControl::SetGammaRamp()", result);
2342 }
2343
2344 /* Release the interface and return */
2345 IDirectDrawGammaControl_Release(gamma);
2346 return (result == DD_OK) ? 0 : -1;
2347#endif /* !IDirectDrawGammaControl_SetGammaRamp */
2348}
2349
2350static int DX5_GetGammaRamp(_THIS, Uint16 *ramp)
2351{
2352#ifdef IDirectDrawGammaControl_SetGammaRamp
2353 LPDIRECTDRAWGAMMACONTROL gamma;
2354 DDGAMMARAMP gamma_ramp;
2355 HRESULT result;
2356#endif
2357
2358 /* In windowed or OpenGL mode, use windib gamma code */
2359 if ( ! DDRAW_FULLSCREEN() ) {
2360 return DIB_GetGammaRamp(this, ramp);
2361 }
2362
2363#ifndef IDirectDrawGammaControl_SetGammaRamp
2364 SDL_SetError("SDL compiled without DirectX gamma ramp support");
2365 return -1;
2366#else
2367 /* Check for a video mode! */
2368 if ( ! SDL_primary ) {
2369 SDL_SetError("A video mode must be set for gamma correction");
2370 return(-1);
2371 }
2372
2373 /* Get the gamma control object */
2374 result = IDirectDrawSurface3_QueryInterface(SDL_primary,
2375 &IID_IDirectDrawGammaControl, (LPVOID *)&gamma);
2376 if ( result != DD_OK ) {
2377 SetDDerror("DirectDrawSurface3::QueryInterface(GAMMA)", result);
2378 return(-1);
2379 }
2380
2381 /* Set up the gamma ramp */
2382 result = IDirectDrawGammaControl_GetGammaRamp(gamma, 0, &gamma_ramp);
2383 if ( result == DD_OK ) {
2384 SDL_memcpy(&ramp[0*256], gamma_ramp.red, 256*sizeof(*ramp));
2385 SDL_memcpy(&ramp[1*256], gamma_ramp.green, 256*sizeof(*ramp));
2386 SDL_memcpy(&ramp[2*256], gamma_ramp.blue, 256*sizeof(*ramp));
2387 } else {
2388 SetDDerror("DirectDrawGammaControl::GetGammaRamp()", result);
2389 }
2390
2391 /* Release the interface and return */
2392 IDirectDrawGammaControl_Release(gamma);
2393 return (result == DD_OK) ? 0 : -1;
2394#endif /* !IDirectDrawGammaControl_SetGammaRamp */
2395}
2396
2397void DX5_VideoQuit(_THIS)
2398{
2399 int i, j;
2400
2401 /* If we're fullscreen GL, we need to reset the display */
2402 if ( this->screen != NULL ) {
2403#ifndef NO_CHANGEDISPLAYSETTINGS
2404 if ( (this->screen->flags & (SDL_OPENGL|SDL_FULLSCREEN)) ==
2405 (SDL_OPENGL|SDL_FULLSCREEN) ) {
2406 ChangeDisplaySettings(NULL, 0);
2407 ShowWindow(SDL_Window, SW_HIDE);
2408 }
2409#endif
2410 if ( this->screen->flags & SDL_OPENGL ) {
2411 WIN_GL_ShutDown(this);
2412 }
2413 }
2414
2415 /* Free any palettes we used */
2416 if ( SDL_palette != NULL ) {
2417 IDirectDrawPalette_Release(SDL_palette);
2418 SDL_palette = NULL;
2419 }
2420
2421 /* Allow the primary surface to be freed */
2422 if ( SDL_primary != NULL ) {
2423 SDL_primary = NULL;
2424 }
2425
2426 /* Free video mode lists */
2427 for ( i=0; i<NUM_MODELISTS; ++i ) {
2428 if ( SDL_modelist[i] != NULL ) {
2429 for ( j=0; SDL_modelist[i][j]; ++j )
2430 SDL_free(SDL_modelist[i][j]);
2431 SDL_free(SDL_modelist[i]);
2432 SDL_modelist[i] = NULL;
2433 }
2434 }
2435
2436 /* Free the window */
2437 DIB_QuitGamma(this);
2438 if ( SDL_Window ) {
2439 DX5_DestroyWindow(this);
2440 }
2441
2442 /* Free our window icon */
2443 if ( screen_icn ) {
2444 DestroyIcon(screen_icn);
2445 screen_icn = NULL;
2446 }
2447}
2448
2449/* Exported for the windows message loop only */
2450void DX5_Activate(_THIS, BOOL active, BOOL minimized)
2451{
2452}
2453void DX5_RealizePalette(_THIS)
2454{
2455 if ( SDL_palette ) {
2456 IDirectDrawSurface3_SetPalette(SDL_primary, SDL_palette);
2457 }
2458}
2459static void DX5_Recolor8Bit(_THIS, SDL_Surface *surface, Uint8 *mapping)
2460{
2461 int row, col;
2462 Uint8 *pixels;
2463
2464 if ( surface->w && surface->h ) {
2465 if ( (surface->flags & SDL_HWSURFACE) == SDL_HWSURFACE ) {
2466 if ( this->LockHWSurface(this, surface) < 0 ) {
2467 return;
2468 }
2469 }
2470 for ( row=0; row<surface->h; ++row ) {
2471 pixels = (Uint8 *)surface->pixels+row*surface->pitch;
2472 for ( col=0; col<surface->w; ++col, ++pixels ) {
2473 *pixels = mapping[*pixels];
2474 }
2475 }
2476 if ( (surface->flags & SDL_HWSURFACE) == SDL_HWSURFACE ) {
2477 this->UnlockHWSurface(this, surface);
2478 }
2479 SDL_UpdateRect(surface, 0, 0, 0, 0);
2480 }
2481}
2482void DX5_PaletteChanged(_THIS, HWND window)
2483{
2484 SDL_Palette *palette;
2485 SDL_Color *saved = NULL;
2486 HDC hdc;
2487 int i;
2488 PALETTEENTRY *entries;
2489
2490 /* This is true when the window is closing */
2491 if ( (SDL_primary == NULL) || (SDL_VideoSurface == NULL) )
2492 return;
2493
2494 /* We need to get the colors as they were set */
2495 palette = this->physpal;
2496 if(!palette)
2497 palette = SDL_VideoSurface->format->palette;
2498 if ( palette == NULL ) { /* Sometimes we don't have a palette */
2499 return;
2500 }
2501 entries = SDL_stack_alloc(PALETTEENTRY, palette->ncolors);
2502 hdc = GetDC(window);
2503 GetSystemPaletteEntries(hdc, 0, palette->ncolors, entries);
2504 ReleaseDC(window, hdc);
2505 if ( ! colorchange_expected ) {
2506 saved = SDL_stack_alloc(SDL_Color, palette->ncolors);
2507 SDL_memcpy(saved, palette->colors,
2508 palette->ncolors*sizeof(SDL_Color));
2509 }
2510 for ( i=0; i<palette->ncolors; ++i ) {
2511 palette->colors[i].r = entries[i].peRed;
2512 palette->colors[i].g = entries[i].peGreen;
2513 palette->colors[i].b = entries[i].peBlue;
2514 }
2515 SDL_stack_free(entries);
2516 if ( ! colorchange_expected ) {
2517 Uint8 mapping[256];
2518
2519 SDL_memset(mapping, 0, sizeof(mapping));
2520 for ( i=0; i<palette->ncolors; ++i ) {
2521 mapping[i] = SDL_FindColor(palette,
2522 saved[i].r, saved[i].g, saved[i].b);
2523 }
2524 DX5_Recolor8Bit(this, SDL_VideoSurface, mapping);
2525 SDL_stack_free(saved);
2526 }
2527 colorchange_expected = 0;
2528
2529 /* Notify all mapped surfaces of the change */
2530 SDL_FormatChanged(SDL_VideoSurface);
2531}
2532
2533/* Exported for the windows message loop only */
2534void DX5_WinPAINT(_THIS, HDC hdc)
2535{
2536 SDL_UpdateRect(SDL_PublicSurface, 0, 0, 0, 0);
2537}
diff --git a/apps/plugins/sdl/src/video/windx5/SDL_dx5video.h b/apps/plugins/sdl/src/video/windx5/SDL_dx5video.h
deleted file mode 100644
index 3d754a0e2e..0000000000
--- a/apps/plugins/sdl/src/video/windx5/SDL_dx5video.h
+++ /dev/null
@@ -1,61 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_dx5video_h
25#define _SDL_dx5video_h
26
27#include "directx.h"
28
29/* Private display data */
30struct SDL_PrivateVideoData {
31 LPDIRECTDRAW2 ddraw2;
32 LPDIRECTDRAWSURFACE3 SDL_primary;
33 LPDIRECTDRAWCLIPPER SDL_clipper;
34 LPDIRECTDRAWPALETTE SDL_palette;
35 PALETTEENTRY SDL_colors[256];
36 int colorchange_expected;
37
38#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
39 int SDL_nummodes[NUM_MODELISTS];
40 SDL_Rect **SDL_modelist[NUM_MODELISTS];
41 int SDL_modeindex[NUM_MODELISTS];
42};
43/* Old variable names */
44#define ddraw2 (this->hidden->ddraw2)
45#define SDL_primary (this->hidden->SDL_primary)
46#define SDL_clipper (this->hidden->SDL_clipper)
47#define SDL_palette (this->hidden->SDL_palette)
48#define SDL_colors (this->hidden->SDL_colors)
49#define colorchange_expected (this->hidden->colorchange_expected)
50#define SDL_nummodes (this->hidden->SDL_nummodes)
51#define SDL_modelist (this->hidden->SDL_modelist)
52#define SDL_modeindex (this->hidden->SDL_modeindex)
53
54/* DirectX function pointers for video and events */
55extern HRESULT (WINAPI *DDrawCreate)( GUID FAR *lpGUID, LPDIRECTDRAW FAR *lplpDD, IUnknown FAR *pUnkOuter );
56extern HRESULT (WINAPI *DInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT *ppDI, LPUNKNOWN punkOuter);
57
58/* DirectDraw error reporting function */
59extern void SetDDerror(const char *function, int code);
60
61#endif /* _SDL_dx5video_h */
diff --git a/apps/plugins/sdl/src/video/windx5/SDL_dx5yuv.c b/apps/plugins/sdl/src/video/windx5/SDL_dx5yuv.c
deleted file mode 100644
index cb89fdc9bb..0000000000
--- a/apps/plugins/sdl/src/video/windx5/SDL_dx5yuv.c
+++ /dev/null
@@ -1,296 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the DirectDraw implementation of YUV video overlays */
25#include "directx.h"
26#include "SDL_video.h"
27#include "SDL_dx5yuv_c.h"
28#include "../SDL_yuvfuncs.h"
29
30//#define USE_DIRECTX_OVERLAY
31
32/* The functions used to manipulate software video overlays */
33static struct private_yuvhwfuncs dx5_yuvfuncs = {
34 DX5_LockYUVOverlay,
35 DX5_UnlockYUVOverlay,
36 DX5_DisplayYUVOverlay,
37 DX5_FreeYUVOverlay
38};
39
40struct private_yuvhwdata {
41 LPDIRECTDRAWSURFACE3 surface;
42
43 /* These are just so we don't have to allocate them separately */
44 Uint16 pitches[3];
45 Uint8 *planes[3];
46};
47
48
49static LPDIRECTDRAWSURFACE3 CreateYUVSurface(_THIS,
50 int width, int height, Uint32 format)
51{
52 HRESULT result;
53 LPDIRECTDRAWSURFACE dd_surface1;
54 LPDIRECTDRAWSURFACE3 dd_surface3;
55 DDSURFACEDESC ddsd;
56
57 /* Set up the surface description */
58 SDL_memset(&ddsd, 0, sizeof(ddsd));
59 ddsd.dwSize = sizeof(ddsd);
60 ddsd.dwFlags = (DDSD_WIDTH|DDSD_HEIGHT|DDSD_CAPS|DDSD_PIXELFORMAT);
61 ddsd.dwWidth = width;
62 ddsd.dwHeight= height;
63#ifdef USE_DIRECTX_OVERLAY
64 ddsd.ddsCaps.dwCaps = (DDSCAPS_OVERLAY|DDSCAPS_VIDEOMEMORY);
65#else
66 ddsd.ddsCaps.dwCaps = (DDSCAPS_OFFSCREENPLAIN|DDSCAPS_VIDEOMEMORY);
67#endif
68 ddsd.ddpfPixelFormat.dwSize = sizeof(ddsd.ddpfPixelFormat);
69 ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC;
70 ddsd.ddpfPixelFormat.dwFourCC = format;
71
72 /* Create the DirectDraw video surface */
73 result = IDirectDraw2_CreateSurface(ddraw2, &ddsd, &dd_surface1, NULL);
74 if ( result != DD_OK ) {
75 SetDDerror("DirectDraw2::CreateSurface", result);
76 return(NULL);
77 }
78 result = IDirectDrawSurface_QueryInterface(dd_surface1,
79 &IID_IDirectDrawSurface3, (LPVOID *)&dd_surface3);
80 IDirectDrawSurface_Release(dd_surface1);
81 if ( result != DD_OK ) {
82 SetDDerror("DirectDrawSurface::QueryInterface", result);
83 return(NULL);
84 }
85
86 /* Make sure the surface format was set properly */
87 SDL_memset(&ddsd, 0, sizeof(ddsd));
88 ddsd.dwSize = sizeof(ddsd);
89 result = IDirectDrawSurface3_Lock(dd_surface3, NULL,
90 &ddsd, DDLOCK_NOSYSLOCK, NULL);
91 if ( result != DD_OK ) {
92 SetDDerror("DirectDrawSurface3::Lock", result);
93 IDirectDrawSurface_Release(dd_surface3);
94 return(NULL);
95 }
96 IDirectDrawSurface3_Unlock(dd_surface3, NULL);
97
98 if ( !(ddsd.ddpfPixelFormat.dwFlags & DDPF_FOURCC) ||
99 (ddsd.ddpfPixelFormat.dwFourCC != format) ) {
100 SDL_SetError("DDraw didn't use requested FourCC format");
101 IDirectDrawSurface_Release(dd_surface3);
102 return(NULL);
103 }
104
105 /* We're ready to go! */
106 return(dd_surface3);
107}
108
109#ifdef DEBUG_YUV
110static char *PrintFOURCC(Uint32 code)
111{
112 static char buf[5];
113
114 buf[3] = code >> 24;
115 buf[2] = (code >> 16) & 0xFF;
116 buf[1] = (code >> 8) & 0xFF;
117 buf[0] = (code & 0xFF);
118 return(buf);
119}
120#endif
121
122SDL_Overlay *DX5_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display)
123{
124 SDL_Overlay *overlay;
125 struct private_yuvhwdata *hwdata;
126
127#ifdef DEBUG_YUV
128 DWORD numcodes;
129 DWORD *codes;
130
131 printf("FOURCC format requested: 0x%x\n", PrintFOURCC(format));
132 IDirectDraw2_GetFourCCCodes(ddraw2, &numcodes, NULL);
133 if ( numcodes ) {
134 DWORD i;
135 codes = SDL_malloc(numcodes*sizeof(*codes));
136 if ( codes ) {
137 IDirectDraw2_GetFourCCCodes(ddraw2, &numcodes, codes);
138 for ( i=0; i<numcodes; ++i ) {
139 fprintf(stderr, "Code %d: 0x%x\n", i, PrintFOURCC(codes[i]));
140 }
141 SDL_free(codes);
142 }
143 } else {
144 fprintf(stderr, "No FOURCC codes supported\n");
145 }
146#endif
147
148 /* Create the overlay structure */
149 overlay = (SDL_Overlay *)SDL_malloc(sizeof *overlay);
150 if ( overlay == NULL ) {
151 SDL_OutOfMemory();
152 return(NULL);
153 }
154 SDL_memset(overlay, 0, (sizeof *overlay));
155
156 /* Fill in the basic members */
157 overlay->format = format;
158 overlay->w = width;
159 overlay->h = height;
160
161 /* Set up the YUV surface function structure */
162 overlay->hwfuncs = &dx5_yuvfuncs;
163
164 /* Create the pixel data and lookup tables */
165 hwdata = (struct private_yuvhwdata *)SDL_malloc(sizeof *hwdata);
166 overlay->hwdata = hwdata;
167 if ( hwdata == NULL ) {
168 SDL_OutOfMemory();
169 SDL_FreeYUVOverlay(overlay);
170 return(NULL);
171 }
172 hwdata->surface = CreateYUVSurface(this, width, height, format);
173 if ( hwdata->surface == NULL ) {
174 SDL_FreeYUVOverlay(overlay);
175 return(NULL);
176 }
177 overlay->hw_overlay = 1;
178
179 /* Set up the plane pointers */
180 overlay->pitches = hwdata->pitches;
181 overlay->pixels = hwdata->planes;
182 switch (format) {
183 case SDL_YV12_OVERLAY:
184 case SDL_IYUV_OVERLAY:
185 overlay->planes = 3;
186 break;
187 default:
188 overlay->planes = 1;
189 break;
190 }
191
192 /* We're all done.. */
193 return(overlay);
194}
195
196int DX5_LockYUVOverlay(_THIS, SDL_Overlay *overlay)
197{
198 HRESULT result;
199 LPDIRECTDRAWSURFACE3 surface;
200 DDSURFACEDESC ddsd;
201
202 surface = overlay->hwdata->surface;
203 SDL_memset(&ddsd, 0, sizeof(ddsd));
204 ddsd.dwSize = sizeof(ddsd);
205 result = IDirectDrawSurface3_Lock(surface, NULL,
206 &ddsd, DDLOCK_NOSYSLOCK, NULL);
207 if ( result == DDERR_SURFACELOST ) {
208 result = IDirectDrawSurface3_Restore(surface);
209 result = IDirectDrawSurface3_Lock(surface, NULL, &ddsd,
210 (DDLOCK_NOSYSLOCK|DDLOCK_WAIT), NULL);
211 }
212 if ( result != DD_OK ) {
213 SetDDerror("DirectDrawSurface3::Lock", result);
214 return(-1);
215 }
216
217 /* Find the pitch and offset values for the overlay */
218#if defined(NONAMELESSUNION)
219 overlay->pitches[0] = (Uint16)ddsd.u1.lPitch;
220#else
221 overlay->pitches[0] = (Uint16)ddsd.lPitch;
222#endif
223 overlay->pixels[0] = (Uint8 *)ddsd.lpSurface;
224 switch (overlay->format) {
225 case SDL_YV12_OVERLAY:
226 case SDL_IYUV_OVERLAY:
227 /* Add the two extra planes */
228 overlay->pitches[1] = overlay->pitches[0] / 2;
229 overlay->pitches[2] = overlay->pitches[0] / 2;
230 overlay->pixels[1] = overlay->pixels[0] +
231 overlay->pitches[0] * overlay->h;
232 overlay->pixels[2] = overlay->pixels[1] +
233 overlay->pitches[1] * overlay->h / 2;
234 break;
235 default:
236 /* Only one plane, no worries */
237 break;
238 }
239 return(0);
240}
241
242void DX5_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay)
243{
244 LPDIRECTDRAWSURFACE3 surface;
245
246 surface = overlay->hwdata->surface;
247 IDirectDrawSurface3_Unlock(surface, NULL);
248}
249
250int DX5_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst)
251{
252 HRESULT result;
253 LPDIRECTDRAWSURFACE3 surface;
254 RECT srcrect, dstrect;
255
256 surface = overlay->hwdata->surface;
257 srcrect.top = src->y;
258 srcrect.bottom = srcrect.top+src->h;
259 srcrect.left = src->x;
260 srcrect.right = srcrect.left+src->w;
261 dstrect.top = SDL_bounds.top+dst->y;
262 dstrect.left = SDL_bounds.left+dst->x;
263 dstrect.bottom = dstrect.top+dst->h;
264 dstrect.right = dstrect.left+dst->w;
265#ifdef USE_DIRECTX_OVERLAY
266 result = IDirectDrawSurface3_UpdateOverlay(surface, &srcrect,
267 SDL_primary, &dstrect, DDOVER_SHOW, NULL);
268 if ( result != DD_OK ) {
269 SetDDerror("DirectDrawSurface3::UpdateOverlay", result);
270 return(-1);
271 }
272#else
273 result = IDirectDrawSurface3_Blt(SDL_primary, &dstrect, surface, &srcrect,
274 DDBLT_WAIT, NULL);
275 if ( result != DD_OK ) {
276 SetDDerror("DirectDrawSurface3::Blt", result);
277 return(-1);
278 }
279#endif
280 return(0);
281}
282
283void DX5_FreeYUVOverlay(_THIS, SDL_Overlay *overlay)
284{
285 struct private_yuvhwdata *hwdata;
286
287 hwdata = overlay->hwdata;
288 if ( hwdata ) {
289 if ( hwdata->surface ) {
290 IDirectDrawSurface_Release(hwdata->surface);
291 }
292 SDL_free(hwdata);
293 overlay->hwdata = NULL;
294 }
295}
296
diff --git a/apps/plugins/sdl/src/video/windx5/SDL_dx5yuv_c.h b/apps/plugins/sdl/src/video/windx5/SDL_dx5yuv_c.h
deleted file mode 100644
index dfceaf929a..0000000000
--- a/apps/plugins/sdl/src/video/windx5/SDL_dx5yuv_c.h
+++ /dev/null
@@ -1,38 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the DirectDraw implementation of YUV video overlays */
25
26#include "SDL_video.h"
27#include "../wincommon/SDL_lowvideo.h"
28#include "SDL_dx5video.h"
29
30extern SDL_Overlay *DX5_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display);
31
32extern int DX5_LockYUVOverlay(_THIS, SDL_Overlay *overlay);
33
34extern void DX5_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay);
35
36extern int DX5_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst);
37
38extern void DX5_FreeYUVOverlay(_THIS, SDL_Overlay *overlay);
diff --git a/apps/plugins/sdl/src/video/windx5/directx.h b/apps/plugins/sdl/src/video/windx5/directx.h
deleted file mode 100644
index c7f536530b..0000000000
--- a/apps/plugins/sdl/src/video/windx5/directx.h
+++ /dev/null
@@ -1,97 +0,0 @@
1
2#ifndef _directx_h
3#define _directx_h
4
5/* Include all of the DirectX 5.0 headers and adds any necessary tweaks */
6
7#define WIN32_LEAN_AND_MEAN
8#include <windows.h>
9#include <mmsystem.h>
10#ifndef WIN32
11#define WIN32
12#endif
13#undef WINNT
14
15/* Far pointers don't exist in 32-bit code */
16#ifndef FAR
17#define FAR
18#endif
19
20/* Error codes not yet included in Win32 API header files */
21#ifndef MAKE_HRESULT
22#define MAKE_HRESULT(sev,fac,code) \
23 ((HRESULT)(((unsigned long)(sev)<<31) | ((unsigned long)(fac)<<16) | ((unsigned long)(code))))
24#endif
25
26#ifndef S_OK
27#define S_OK (HRESULT)0x00000000L
28#endif
29
30#ifndef SUCCEEDED
31#define SUCCEEDED(x) ((HRESULT)(x) >= 0)
32#endif
33#ifndef FAILED
34#define FAILED(x) ((HRESULT)(x)<0)
35#endif
36
37#ifndef E_FAIL
38#define E_FAIL (HRESULT)0x80000008L
39#endif
40#ifndef E_NOINTERFACE
41#define E_NOINTERFACE (HRESULT)0x80004002L
42#endif
43#ifndef E_OUTOFMEMORY
44#define E_OUTOFMEMORY (HRESULT)0x8007000EL
45#endif
46#ifndef E_INVALIDARG
47#define E_INVALIDARG (HRESULT)0x80070057L
48#endif
49#ifndef E_NOTIMPL
50#define E_NOTIMPL (HRESULT)0x80004001L
51#endif
52#ifndef REGDB_E_CLASSNOTREG
53#define REGDB_E_CLASSNOTREG (HRESULT)0x80040154L
54#endif
55
56/* Severity codes */
57#ifndef SEVERITY_ERROR
58#define SEVERITY_ERROR 1
59#endif
60
61/* Error facility codes */
62#ifndef FACILITY_WIN32
63#define FACILITY_WIN32 7
64#endif
65
66#ifndef FIELD_OFFSET
67#define FIELD_OFFSET(type, field) ((LONG)&(((type *)0)->field))
68#endif
69
70/* DirectX headers (if it isn't included, I haven't tested it yet)
71 */
72/* We need these defines to mark what version of DirectX API we use */
73#define DIRECTDRAW_VERSION 0x0700
74#define DIRECTSOUND_VERSION 0x0500
75#define DIRECTINPUT_VERSION 0x0700
76
77#include <ddraw.h>
78#include <dsound.h>
79#include <dinput.h>
80
81#if DIRECTINPUT_VERSION >= 0x0700 && !defined(DIMOFS_BUTTON4)
82typedef struct _DIMOUSESTATE2 {
83 LONG lX;
84 LONG lY;
85 LONG lZ;
86 BYTE rgbButtons[8];
87} DIMOUSESTATE2, *LPDIMOUSESTATE2;
88
89#define DIMOFS_BUTTON4 (FIELD_OFFSET(DIMOUSESTATE2, rgbButtons) + 4)
90#define DIMOFS_BUTTON5 (FIELD_OFFSET(DIMOUSESTATE2, rgbButtons) + 5)
91#define DIMOFS_BUTTON6 (FIELD_OFFSET(DIMOUSESTATE2, rgbButtons) + 6)
92#define DIMOFS_BUTTON7 (FIELD_OFFSET(DIMOUSESTATE2, rgbButtons) + 7)
93
94extern const DIDATAFORMAT c_dfDIMouse2;
95#endif
96
97#endif /* _directx_h */
diff --git a/apps/plugins/sdl/src/video/wscons/SDL_wsconsevents.c b/apps/plugins/sdl/src/video/wscons/SDL_wsconsevents.c
deleted file mode 100644
index 635b972f0a..0000000000
--- a/apps/plugins/sdl/src/video/wscons/SDL_wsconsevents.c
+++ /dev/null
@@ -1,233 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <sys/types.h>
25#include <dev/wscons/wsdisplay_usl_io.h>
26#include <sys/ioctl.h>
27#include <fcntl.h>
28#include <unistd.h>
29#include <termios.h>
30#include <errno.h>
31#include <string.h>
32
33#include "SDL.h"
34#include "../../events/SDL_sysevents.h"
35#include "../../events/SDL_events_c.h"
36#include "SDL_wsconsvideo.h"
37#include "SDL_wsconsevents_c.h"
38
39static int posted = 0;
40
41int WSCONS_InitKeyboard(_THIS)
42{
43 struct termios tty;
44
45 if (ioctl(private->fd, WSKBDIO_GTYPE, &private->kbdType) == -1) {
46 WSCONS_ReportError("cannot get keyboard type: %s", strerror(errno));
47 return -1;
48 }
49
50 if (tcgetattr(private->fd, &private->saved_tty) == -1) {
51 WSCONS_ReportError("cannot get terminal attributes: %s", strerror(errno));
52 return -1;
53 }
54 private->did_save_tty = 1;
55 tty = private->saved_tty;
56 tty.c_iflag = IGNPAR | IGNBRK;
57 tty.c_oflag = 0;
58 tty.c_cflag = CREAD | CS8;
59 tty.c_lflag = 0;
60 tty.c_cc[VTIME] = 0;
61 tty.c_cc[VMIN] = 1;
62 cfsetispeed(&tty, 9600);
63 cfsetospeed(&tty, 9600);
64 if (tcsetattr(private->fd, TCSANOW, &tty) < 0) {
65 WSCONS_ReportError("cannot set terminal attributes: %s", strerror(errno));
66 return -1;
67 }
68 if (ioctl(private->fd, KDSKBMODE, K_RAW) == -1) {
69 WSCONS_ReportError("cannot set raw keyboard mode: %s", strerror(errno));
70 return -1;
71 }
72
73 return 0;
74}
75
76void WSCONS_ReleaseKeyboard(_THIS)
77{
78 if (private->fd != -1) {
79 if (ioctl(private->fd, KDSKBMODE, K_XLATE) == -1) {
80 WSCONS_ReportError("cannot restore keyboard to translated mode: %s",
81 strerror(errno));
82 }
83 if (private->did_save_tty) {
84 if (tcsetattr(private->fd, TCSANOW, &private->saved_tty) < 0) {
85 WSCONS_ReportError("cannot restore keynoard attributes: %s",
86 strerror(errno));
87 }
88 }
89 }
90}
91
92static void updateMouse()
93{
94}
95
96static SDLKey keymap[128];
97
98static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym)
99{
100 keysym->scancode = scancode;
101 keysym->sym = SDLK_UNKNOWN;
102 keysym->mod = KMOD_NONE;
103
104 if (scancode < SDL_arraysize(keymap))
105 keysym->sym = keymap[scancode];
106
107 if (keysym->sym == SDLK_UNKNOWN)
108 printf("Unknown mapping for scancode %d\n", scancode);
109
110 return keysym;
111}
112
113static void updateKeyboard(_THIS)
114{
115 unsigned char buf[100];
116 SDL_keysym keysym;
117 int n, i;
118
119 if ((n = read(private->fd, buf, sizeof(buf))) > 0) {
120 for (i = 0; i < n; i++) {
121 unsigned char c = buf[i] & 0x7f;
122 if (c == 224) // special key prefix -- what should we do with it?
123 continue;
124 posted += SDL_PrivateKeyboard((buf[i] & 0x80) ? SDL_RELEASED : SDL_PRESSED,
125 TranslateKey(c, &keysym));
126 }
127 }
128}
129
130void WSCONS_PumpEvents(_THIS)
131{
132 do {
133 posted = 0;
134 updateMouse();
135 updateKeyboard(this);
136 } while (posted);
137}
138
139void WSCONS_InitOSKeymap(_THIS)
140{
141 int i;
142
143 /* Make sure unknown keys are mapped correctly */
144 for (i=0; i < SDL_arraysize(keymap); i++) {
145 keymap[i] = SDLK_UNKNOWN;
146 }
147
148 switch (private->kbdType) {
149#ifdef WSKBD_TYPE_ZAURUS
150 case WSKBD_TYPE_ZAURUS:
151 /* top row */
152 keymap[2] = SDLK_1;
153 keymap[3] = SDLK_2;
154 keymap[4] = SDLK_3;
155 keymap[5] = SDLK_4;
156 keymap[6] = SDLK_5;
157 keymap[7] = SDLK_6;
158 keymap[8] = SDLK_7;
159 keymap[9] = SDLK_8;
160 keymap[10] = SDLK_9;
161 keymap[11] = SDLK_0;
162 keymap[14] = SDLK_BACKSPACE;
163
164 /* second row */
165 keymap[16] = SDLK_q;
166 keymap[17] = SDLK_w;
167 keymap[18] = SDLK_e;
168 keymap[19] = SDLK_r;
169 keymap[20] = SDLK_t;
170 keymap[21] = SDLK_y;
171 keymap[22] = SDLK_u;
172 keymap[23] = SDLK_i;
173 keymap[24] = SDLK_o;
174 keymap[25] = SDLK_p;
175
176 /* third row */
177 keymap[15] = SDLK_TAB;
178 keymap[30] = SDLK_a;
179 keymap[31] = SDLK_s;
180 keymap[32] = SDLK_d;
181 keymap[33] = SDLK_f;
182 keymap[34] = SDLK_g;
183 keymap[35] = SDLK_h;
184 keymap[36] = SDLK_j;
185 keymap[37] = SDLK_k;
186 keymap[38] = SDLK_l;
187
188 /* fourth row */
189 keymap[42] = SDLK_LSHIFT;
190 keymap[44] = SDLK_z;
191 keymap[45] = SDLK_x;
192 keymap[46] = SDLK_c;
193 keymap[47] = SDLK_v;
194 keymap[48] = SDLK_b;
195 keymap[49] = SDLK_n;
196 keymap[50] = SDLK_m;
197 keymap[54] = SDLK_RSHIFT;
198 keymap[28] = SDLK_RETURN;
199
200 /* fifth row */
201 keymap[56] = SDLK_LALT;
202 keymap[29] = SDLK_LCTRL;
203 /* keymap[56] = ; */
204 keymap[0] = SDLK_LSUPER;
205 keymap[12] = SDLK_MINUS;
206 keymap[57] = SDLK_SPACE;
207 keymap[51] = SDLK_COMMA;
208 keymap[52] = SDLK_PERIOD;
209
210 /* misc */
211 keymap[59] = SDLK_F1;
212 keymap[60] = SDLK_F2;
213 keymap[61] = SDLK_F3;
214 keymap[62] = SDLK_F4;
215 keymap[63] = SDLK_F5;
216 keymap[1] = SDLK_ESCAPE;
217 /* keymap[28] = SDLK_KP_ENTER; */
218 keymap[72] = SDLK_UP;
219 keymap[75] = SDLK_LEFT;
220 keymap[77] = SDLK_RIGHT;
221 keymap[80] = SDLK_DOWN;
222 break;
223#endif /* WSKBD_TYPE_ZAURUS */
224
225 default:
226 WSCONS_ReportError("Unable to map keys for keyboard type %u",
227 private->kbdType);
228 break;
229 }
230}
231
232/* end of SDL_wsconsevents.c ... */
233
diff --git a/apps/plugins/sdl/src/video/wscons/SDL_wsconsevents_c.h b/apps/plugins/sdl/src/video/wscons/SDL_wsconsevents_c.h
deleted file mode 100644
index f68ee6e119..0000000000
--- a/apps/plugins/sdl/src/video/wscons/SDL_wsconsevents_c.h
+++ /dev/null
@@ -1,36 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_wsconsvideo.h"
25
26int WSCONS_InitKeyboard(_THIS);
27void WSCONS_ReleaseKeyboard(_THIS);
28
29/* Variables and functions exported by SDL_sysevents.c to other parts
30 of the native video subsystem (SDL_sysvideo.c)
31*/
32extern void WSCONS_InitOSKeymap(_THIS);
33extern void WSCONS_PumpEvents(_THIS);
34
35/* end of SDL_wsconsevents_c.h ... */
36
diff --git a/apps/plugins/sdl/src/video/wscons/SDL_wsconsmouse.c b/apps/plugins/sdl/src/video/wscons/SDL_wsconsmouse.c
deleted file mode 100644
index b69e0c5f48..0000000000
--- a/apps/plugins/sdl/src/video/wscons/SDL_wsconsmouse.c
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_mouse.h"
25#include "../../events/SDL_events_c.h"
26
27#include "SDL_wsconsmouse_c.h"
28
29
30/* The implementation dependent data for the window manager cursor */
31struct WMcursor {
32 int unused;
33};
diff --git a/apps/plugins/sdl/src/video/wscons/SDL_wsconsmouse_c.h b/apps/plugins/sdl/src/video/wscons/SDL_wsconsmouse_c.h
deleted file mode 100644
index 875437bcd4..0000000000
--- a/apps/plugins/sdl/src/video/wscons/SDL_wsconsmouse_c.h
+++ /dev/null
@@ -1,26 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_wsconsvideo.h"
25
26/* Functions to be exported */
diff --git a/apps/plugins/sdl/src/video/wscons/SDL_wsconsvideo.c b/apps/plugins/sdl/src/video/wscons/SDL_wsconsvideo.c
deleted file mode 100644
index 0e850d13e0..0000000000
--- a/apps/plugins/sdl/src/video/wscons/SDL_wsconsvideo.c
+++ /dev/null
@@ -1,609 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <sys/time.h>
25#include <sys/mman.h>
26#include <sys/ioctl.h>
27#include <dev/wscons/wsdisplay_usl_io.h>
28#include <fcntl.h>
29#include <unistd.h>
30#include <errno.h>
31
32#include "SDL_video.h"
33#include "SDL_mouse.h"
34#include "../SDL_sysvideo.h"
35#include "../SDL_pixels_c.h"
36#include "../../events/SDL_events_c.h"
37
38#include "SDL_wsconsvideo.h"
39#include "SDL_wsconsevents_c.h"
40#include "SDL_wsconsmouse_c.h"
41
42#define WSCONSVID_DRIVER_NAME "wscons"
43enum {
44 WSCONS_ROTATE_NONE = 0,
45 WSCONS_ROTATE_CCW = 90,
46 WSCONS_ROTATE_UD = 180,
47 WSCONS_ROTATE_CW = 270
48};
49
50#define min(a,b) ((a)<(b)?(a):(b))
51
52/* Initialization/Query functions */
53static int WSCONS_VideoInit(_THIS, SDL_PixelFormat *vformat);
54static SDL_Rect **WSCONS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
55static SDL_Surface *WSCONS_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
56static int WSCONS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
57static void WSCONS_VideoQuit(_THIS);
58
59/* Hardware surface functions */
60static int WSCONS_AllocHWSurface(_THIS, SDL_Surface *surface);
61static int WSCONS_LockHWSurface(_THIS, SDL_Surface *surface);
62static void WSCONS_UnlockHWSurface(_THIS, SDL_Surface *surface);
63static void WSCONS_FreeHWSurface(_THIS, SDL_Surface *surface);
64
65/* etc. */
66static WSCONS_bitBlit WSCONS_blit16;
67static WSCONS_bitBlit WSCONS_blit16blocked;
68static void WSCONS_UpdateRects(_THIS, int numrects, SDL_Rect *rects);
69
70void WSCONS_ReportError(char *fmt, ...)
71{
72 char message[200];
73 va_list vaArgs;
74
75 message[199] = '\0';
76
77 va_start(vaArgs, fmt);
78 vsnprintf(message, 199, fmt, vaArgs);
79 va_end(vaArgs);
80
81 SDL_SetError(message);
82 fprintf(stderr, "WSCONS error: %s\n", message);
83}
84
85/* WSCONS driver bootstrap functions */
86
87static int WSCONS_Available(void)
88{
89 return 1;
90}
91
92static void WSCONS_DeleteDevice(SDL_VideoDevice *device)
93{
94 SDL_free(device->hidden);
95 SDL_free(device);
96}
97
98static SDL_VideoDevice *WSCONS_CreateDevice(int devindex)
99{
100 SDL_VideoDevice *device;
101
102 /* Initialize all variables that we clean on shutdown */
103 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
104 if (device == NULL) {
105 SDL_OutOfMemory();
106 return 0;
107 }
108 SDL_memset(device, 0, (sizeof *device));
109 device->hidden =
110 (struct SDL_PrivateVideoData *)SDL_malloc((sizeof *device->hidden));
111 if (device->hidden == NULL) {
112 SDL_OutOfMemory();
113 SDL_free(device);
114 return(0);
115 }
116 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
117 device->hidden->fd = -1;
118
119 /* Set the function pointers */
120 device->VideoInit = WSCONS_VideoInit;
121 device->ListModes = WSCONS_ListModes;
122 device->SetVideoMode = WSCONS_SetVideoMode;
123 device->SetColors = WSCONS_SetColors;
124 device->UpdateRects = WSCONS_UpdateRects;
125 device->VideoQuit = WSCONS_VideoQuit;
126 device->AllocHWSurface = WSCONS_AllocHWSurface;
127 device->LockHWSurface = WSCONS_LockHWSurface;
128 device->UnlockHWSurface = WSCONS_UnlockHWSurface;
129 device->FreeHWSurface = WSCONS_FreeHWSurface;
130 device->InitOSKeymap = WSCONS_InitOSKeymap;
131 device->PumpEvents = WSCONS_PumpEvents;
132 device->free = WSCONS_DeleteDevice;
133
134 return device;
135}
136
137VideoBootStrap WSCONS_bootstrap = {
138 WSCONSVID_DRIVER_NAME,
139 "SDL wscons video driver",
140 WSCONS_Available,
141 WSCONS_CreateDevice
142};
143
144#define WSCONSDEV_FORMAT "/dev/ttyC%01x"
145
146int WSCONS_VideoInit(_THIS, SDL_PixelFormat *vformat)
147{
148 char devnamebuf[30];
149 char *devname;
150 char *rotation;
151 int wstype;
152 int wsmode = WSDISPLAYIO_MODE_DUMBFB;
153 size_t len, mapsize;
154 int pagemask;
155 int width, height;
156
157 devname = SDL_getenv("SDL_WSCONSDEV");
158 if (devname == NULL) {
159 int activeVT;
160 if (ioctl(STDIN_FILENO, VT_GETACTIVE, &activeVT) == -1) {
161 WSCONS_ReportError("Unable to determine active terminal: %s",
162 strerror(errno));
163 return -1;
164 }
165 SDL_snprintf(devnamebuf, sizeof(devnamebuf), WSCONSDEV_FORMAT, activeVT - 1);
166 devname = devnamebuf;
167 }
168
169 private->fd = open(devname, O_RDWR | O_NONBLOCK, 0);
170 if (private->fd == -1) {
171 WSCONS_ReportError("open %s: %s", devname, strerror(errno));
172 return -1;
173 }
174 if (ioctl(private->fd, WSDISPLAYIO_GINFO, &private->info) == -1) {
175 WSCONS_ReportError("ioctl WSDISPLAY_GINFO: %s", strerror(errno));
176 return -1;
177 }
178 if (ioctl(private->fd, WSDISPLAYIO_GTYPE, &wstype) == -1) {
179 WSCONS_ReportError("ioctl WSDISPLAY_GTYPE: %s", strerror(errno));
180 return -1;
181 }
182 if (ioctl(private->fd, WSDISPLAYIO_LINEBYTES, &private->physlinebytes) == -1) {
183 WSCONS_ReportError("ioctl WSDISPLAYIO_LINEBYTES: %s", strerror(errno));
184 return -1;
185 }
186 if (private->info.depth > 8) {
187 if (wstype == WSDISPLAY_TYPE_SUN24 ||
188 wstype == WSDISPLAY_TYPE_SUNCG12 ||
189 wstype == WSDISPLAY_TYPE_SUNCG14 ||
190 wstype == WSDISPLAY_TYPE_SUNTCX ||
191 wstype == WSDISPLAY_TYPE_SUNFFB) {
192 private->redMask = 0x0000ff;
193 private->greenMask = 0x00ff00;
194 private->blueMask = 0xff0000;
195#ifdef WSDISPLAY_TYPE_PXALCD
196 } else if (wstype == WSDISPLAY_TYPE_PXALCD) {
197 private->redMask = 0x1f << 11;
198 private->greenMask = 0x3f << 5;
199 private->blueMask = 0x1f;
200#endif
201 } else {
202 WSCONS_ReportError("Unknown video hardware");
203 return -1;
204 }
205 } else {
206 WSCONS_ReportError("Displays with 8 bpp or less are not supported");
207 return -1;
208 }
209
210 private->rotate = WSCONS_ROTATE_NONE;
211 rotation = SDL_getenv("SDL_VIDEO_WSCONS_ROTATION");
212 if (rotation != NULL) {
213 if (SDL_strlen(rotation) == 0) {
214 private->shadowFB = 0;
215 private->rotate = WSCONS_ROTATE_NONE;
216 printf("Not rotating, no shadow\n");
217 } else if (!SDL_strcmp(rotation, "NONE")) {
218 private->shadowFB = 1;
219 private->rotate = WSCONS_ROTATE_NONE;
220 printf("Not rotating, but still using shadow\n");
221 } else if (!SDL_strcmp(rotation, "CW")) {
222 private->shadowFB = 1;
223 private->rotate = WSCONS_ROTATE_CW;
224 printf("Rotating screen clockwise\n");
225 } else if (!SDL_strcmp(rotation, "CCW")) {
226 private->shadowFB = 1;
227 private->rotate = WSCONS_ROTATE_CCW;
228 printf("Rotating screen counter clockwise\n");
229 } else if (!SDL_strcmp(rotation, "UD")) {
230 private->shadowFB = 1;
231 private->rotate = WSCONS_ROTATE_UD;
232 printf("Rotating screen upside down\n");
233 } else {
234 WSCONS_ReportError("\"%s\" is not a valid value for "
235 "SDL_VIDEO_WSCONS_ROTATION", rotation);
236 return -1;
237 }
238 }
239
240 switch (private->info.depth) {
241 case 1:
242 case 4:
243 case 8:
244 len = private->physlinebytes * private->info.height;
245 break;
246 case 16:
247 if (private->physlinebytes == private->info.width) {
248 len = private->info.width * private->info.height * sizeof(short);
249 } else {
250 len = private->physlinebytes * private->info.height;
251 }
252 if (private->rotate == WSCONS_ROTATE_NONE ||
253 private->rotate == WSCONS_ROTATE_UD) {
254 private->blitFunc = WSCONS_blit16;
255 } else {
256 private->blitFunc = WSCONS_blit16blocked;
257 }
258 break;
259 case 32:
260 if (private->physlinebytes == private->info.width) {
261 len = private->info.width * private->info.height * sizeof(int);
262 } else {
263 len = private->physlinebytes * private->info.height;
264 }
265 break;
266 default:
267 WSCONS_ReportError("unsupported depth %d", private->info.depth);
268 return -1;
269 }
270
271 if (private->shadowFB && private->blitFunc == NULL) {
272 WSCONS_ReportError("Using software buffer, but no blitter function is "
273 "available for this %d bpp.", private->info.depth);
274 return -1;
275 }
276
277 if (ioctl(private->fd, WSDISPLAYIO_SMODE, &wsmode) == -1) {
278 WSCONS_ReportError("ioctl SMODE");
279 return -1;
280 }
281
282 pagemask = getpagesize() - 1;
283 mapsize = ((int)len + pagemask) & ~pagemask;
284 private->physmem = (Uint8 *)mmap(NULL, mapsize,
285 PROT_READ | PROT_WRITE, MAP_SHARED,
286 private->fd, (off_t)0);
287 if (private->physmem == (Uint8 *)MAP_FAILED) {
288 private->physmem = NULL;
289 WSCONS_ReportError("mmap: %s", strerror(errno));
290 return -1;
291 }
292 private->fbmem_len = len;
293
294 if (private->rotate == WSCONS_ROTATE_CW ||
295 private->rotate == WSCONS_ROTATE_CCW) {
296 width = private->info.height;
297 height = private->info.width;
298 } else {
299 width = private->info.width;
300 height = private->info.height;
301 }
302
303 this->info.current_w = width;
304 this->info.current_h = height;
305
306 if (private->shadowFB) {
307 private->shadowmem = (Uint8 *)SDL_malloc(len);
308 if (private->shadowmem == NULL) {
309 WSCONS_ReportError("No memory for shadow");
310 return -1;
311 }
312 private->fbstart = private->shadowmem;
313 private->fblinebytes = width * ((private->info.depth + 7) / 8);
314 } else {
315 private->fbstart = private->physmem;
316 private->fblinebytes = private->physlinebytes;
317 }
318
319 private->SDL_modelist[0] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect));
320 private->SDL_modelist[0]->w = width;
321 private->SDL_modelist[0]->h = height;
322
323 vformat->BitsPerPixel = private->info.depth;
324 vformat->BytesPerPixel = private->info.depth / 8;
325
326 if (WSCONS_InitKeyboard(this) == -1) {
327 return -1;
328 }
329
330 return 0;
331}
332
333SDL_Rect **WSCONS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
334{
335 if (format->BitsPerPixel == private->info.depth) {
336 return private->SDL_modelist;
337 } else {
338 return NULL;
339 }
340}
341
342SDL_Surface *WSCONS_SetVideoMode(_THIS, SDL_Surface *current,
343 int width, int height, int bpp, Uint32 flags)
344{
345 if (width != private->SDL_modelist[0]->w ||
346 height != private->SDL_modelist[0]->h) {
347 WSCONS_ReportError("Requested video mode %dx%d not supported.",
348 width, height);
349 return NULL;
350 }
351 if (bpp != private->info.depth) {
352 WSCONS_ReportError("Requested video depth %d bpp not supported.", bpp);
353 return NULL;
354 }
355
356 if (!SDL_ReallocFormat(current,
357 bpp,
358 private->redMask,
359 private->greenMask,
360 private->blueMask,
361 0)) {
362 WSCONS_ReportError("Couldn't allocate new pixel format");
363 return NULL;
364 }
365
366 current->flags &= SDL_FULLSCREEN;
367 if (private->shadowFB) {
368 current->flags |= SDL_SWSURFACE;
369 } else {
370 current->flags |= SDL_HWSURFACE;
371 }
372 current->w = width;
373 current->h = height;
374 current->pitch = private->fblinebytes;
375 current->pixels = private->fbstart;
376
377 SDL_memset(private->fbstart, 0, private->fbmem_len);
378
379 return current;
380}
381
382static int WSCONS_AllocHWSurface(_THIS, SDL_Surface *surface)
383{
384 return -1;
385}
386static void WSCONS_FreeHWSurface(_THIS, SDL_Surface *surface)
387{
388}
389
390static int WSCONS_LockHWSurface(_THIS, SDL_Surface *surface)
391{
392 return 0;
393}
394
395static void WSCONS_UnlockHWSurface(_THIS, SDL_Surface *surface)
396{
397}
398
399static void WSCONS_blit16(Uint8 *byte_src_pos,
400 int srcRightDelta,
401 int srcDownDelta,
402 Uint8 *byte_dst_pos,
403 int dst_linebytes,
404 int width,
405 int height)
406{
407 int w;
408 Uint16 *src_pos = (Uint16 *)byte_src_pos;
409 Uint16 *dst_pos = (Uint16 *)byte_dst_pos;
410
411 while (height) {
412 Uint16 *src = src_pos;
413 Uint16 *dst = dst_pos;
414 for (w = width; w != 0; w--) {
415 *dst = *src;
416 src += srcRightDelta;
417 dst++;
418 }
419 dst_pos = (Uint16 *)((Uint8 *)dst_pos + dst_linebytes);
420 src_pos += srcDownDelta;
421 height--;
422 }
423}
424
425#define BLOCKSIZE_W 32
426#define BLOCKSIZE_H 32
427
428static void WSCONS_blit16blocked(Uint8 *byte_src_pos,
429 int srcRightDelta,
430 int srcDownDelta,
431 Uint8 *byte_dst_pos,
432 int dst_linebytes,
433 int width,
434 int height)
435{
436 int w;
437 Uint16 *src_pos = (Uint16 *)byte_src_pos;
438 Uint16 *dst_pos = (Uint16 *)byte_dst_pos;
439
440 while (height > 0) {
441 Uint16 *src = src_pos;
442 Uint16 *dst = dst_pos;
443 for (w = width; w > 0; w -= BLOCKSIZE_W) {
444 WSCONS_blit16((Uint8 *)src,
445 srcRightDelta,
446 srcDownDelta,
447 (Uint8 *)dst,
448 dst_linebytes,
449 min(w, BLOCKSIZE_W),
450 min(height, BLOCKSIZE_H));
451 src += srcRightDelta * BLOCKSIZE_W;
452 dst += BLOCKSIZE_W;
453 }
454 dst_pos = (Uint16 *)((Uint8 *)dst_pos + dst_linebytes * BLOCKSIZE_H);
455 src_pos += srcDownDelta * BLOCKSIZE_H;
456 height -= BLOCKSIZE_H;
457 }
458}
459
460static void WSCONS_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
461{
462 int width = private->SDL_modelist[0]->w;
463 int height = private->SDL_modelist[0]->h;
464 int bytesPerPixel = (private->info.depth + 7) / 8;
465 int i;
466
467 if (!private->shadowFB) {
468 return;
469 }
470
471 if (private->info.depth != 16) {
472 WSCONS_ReportError("Shadow copy only implemented for 16 bpp");
473 return;
474 }
475
476 for (i = 0; i < numrects; i++) {
477 int x1, y1, x2, y2;
478 int scr_x1, scr_y1, scr_x2, scr_y2;
479 int sha_x1, sha_y1;
480 int shadowRightDelta; /* Address change when moving right in dest */
481 int shadowDownDelta; /* Address change when moving down in dest */
482 Uint8 *src_start;
483 Uint8 *dst_start;
484
485 x1 = rects[i].x;
486 y1 = rects[i].y;
487 x2 = x1 + rects[i].w;
488 y2 = y1 + rects[i].h;
489
490 if (x1 < 0) {
491 x1 = 0;
492 } else if (x1 > width) {
493 x1 = width;
494 }
495 if (x2 < 0) {
496 x2 = 0;
497 } else if (x2 > width) {
498 x2 = width;
499 }
500 if (y1 < 0) {
501 y1 = 0;
502 } else if (y1 > height) {
503 y1 = height;
504 }
505 if (y2 < 0) {
506 y2 = 0;
507 } else if (y2 > height) {
508 y2 = height;
509 }
510 if (x2 <= x1 || y2 <= y1) {
511 continue;
512 }
513
514 switch (private->rotate) {
515 case WSCONS_ROTATE_NONE:
516 sha_x1 = scr_x1 = x1;
517 sha_y1 = scr_y1 = y1;
518 scr_x2 = x2;
519 scr_y2 = y2;
520 shadowRightDelta = 1;
521 shadowDownDelta = width;
522 break;
523 case WSCONS_ROTATE_CCW:
524 scr_x1 = y1;
525 scr_y1 = width - x2;
526 scr_x2 = y2;
527 scr_y2 = width - x1;
528 sha_x1 = x2 - 1;
529 sha_y1 = y1;
530 shadowRightDelta = width;
531 shadowDownDelta = -1;
532 break;
533 case WSCONS_ROTATE_UD:
534 scr_x1 = width - x2;
535 scr_y1 = height - y2;
536 scr_x2 = width - x1;
537 scr_y2 = height - y1;
538 sha_x1 = x2 - 1;
539 sha_y1 = y2 - 1;
540 shadowRightDelta = -1;
541 shadowDownDelta = -width;
542 break;
543 case WSCONS_ROTATE_CW:
544 scr_x1 = height - y2;
545 scr_y1 = x1;
546 scr_x2 = height - y1;
547 scr_y2 = x2;
548 sha_x1 = x1;
549 sha_y1 = y2 - 1;
550 shadowRightDelta = -width;
551 shadowDownDelta = 1;
552 break;
553 default:
554 WSCONS_ReportError("Unknown rotation");
555 return;
556 }
557
558 src_start = private->shadowmem + (sha_y1 * width + sha_x1) * bytesPerPixel;
559 dst_start = private->physmem + scr_y1 * private->physlinebytes +
560 scr_x1 * bytesPerPixel;
561
562 private->blitFunc(src_start,
563 shadowRightDelta,
564 shadowDownDelta,
565 dst_start,
566 private->physlinebytes,
567 scr_x2 - scr_x1,
568 scr_y2 - scr_y1);
569 }
570}
571
572int WSCONS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
573{
574 return 0;
575}
576
577/*
578 * Note: If we are terminated, this could be called in the middle of
579 * another SDL video routine -- notably UpdateRects.
580 */
581void WSCONS_VideoQuit(_THIS)
582{
583 int mode = WSDISPLAYIO_MODE_EMUL;
584
585 if (private->shadowmem != NULL) {
586 SDL_free(private->shadowmem);
587 private->shadowmem = NULL;
588 }
589 private->fbstart = NULL;
590 if (this->screen != NULL) {
591 this->screen->pixels = NULL;
592 }
593
594 if (private->SDL_modelist[0] != NULL) {
595 SDL_free(private->SDL_modelist[0]);
596 private->SDL_modelist[0] = NULL;
597 }
598
599 if (ioctl(private->fd, WSDISPLAYIO_SMODE, &mode) == -1) {
600 WSCONS_ReportError("ioctl SMODE");
601 }
602
603 WSCONS_ReleaseKeyboard(this);
604
605 if (private->fd != -1) {
606 close(private->fd);
607 private->fd = -1;
608 }
609}
diff --git a/apps/plugins/sdl/src/video/wscons/SDL_wsconsvideo.h b/apps/plugins/sdl/src/video/wscons/SDL_wsconsvideo.h
deleted file mode 100644
index 9d75c170dc..0000000000
--- a/apps/plugins/sdl/src/video/wscons/SDL_wsconsvideo.h
+++ /dev/null
@@ -1,76 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_wsconsvideo_h
25#define _SDL_wsconsvideo_h
26
27#include <sys/time.h>
28#include <termios.h>
29#include <dev/wscons/wsconsio.h>
30
31#include "SDL_mouse.h"
32#include "SDL_mutex.h"
33#include "../SDL_sysvideo.h"
34
35void WSCONS_ReportError(char *fmt, ...);
36
37/* Hidden "this" pointer for the video functions */
38#define _THIS SDL_VideoDevice *this
39#define private (this->hidden)
40
41/* Private display data */
42
43typedef void WSCONS_bitBlit(Uint8 *src_pos,
44 int srcRightDelta, // pixels, not bytes
45 int srcDownDelta, // pixels, not bytes
46 Uint8 *dst_pos,
47 int dst_linebytes,
48 int width,
49 int height);
50
51struct SDL_PrivateVideoData {
52 int fd; /* file descriptor of open device */
53 struct wsdisplay_fbinfo info; /* frame buffer characteristics */
54 int physlinebytes; /* number of bytes per row */
55 int redMask, greenMask, blueMask;
56
57 Uint8 *fbstart; /* These refer to the surface used, */
58 int fblinebytes; /* physical frame buffer or shadow. */
59
60 size_t fbmem_len;
61 Uint8 *physmem;
62 Uint8 *shadowmem;
63 int rotate;
64 int shadowFB; /* Tells whether a shadow is being used. */
65
66 WSCONS_bitBlit *blitFunc;
67
68 SDL_Rect *SDL_modelist[2];
69
70 unsigned int kbdType;
71 int did_save_tty;
72 struct termios saved_tty;
73};
74
75
76#endif /* _SDL_wsconsvideo_h */
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11dga.c b/apps/plugins/sdl/src/video/x11/SDL_x11dga.c
deleted file mode 100644
index e1c0c2e8cd..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11dga.c
+++ /dev/null
@@ -1,90 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is currently only used to enable DGA mouse.
25 There is a completely separate DGA driver that is fullscreen-only.
26*/
27
28#include "SDL_video.h"
29#include "../SDL_cursor_c.h"
30#include "SDL_x11dga_c.h"
31
32/* Global for the error handler */
33int dga_event, dga_error = -1;
34
35void X11_EnableDGAMouse(_THIS)
36{
37#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
38 static int use_dgamouse = -1;
39
40 /* Check configuration to see if we should use DGA mouse */
41 if ( use_dgamouse < 0 ) {
42 int dga_major, dga_minor;
43 int dga_flags;
44 const char *env_use_dgamouse;
45
46 use_dgamouse = 1;
47 env_use_dgamouse = SDL_getenv("SDL_VIDEO_X11_DGAMOUSE");
48 if ( env_use_dgamouse ) {
49 use_dgamouse = SDL_atoi(env_use_dgamouse);
50 }
51 /* Check for buggy X servers */
52 if ( use_dgamouse && BUGGY_XFREE86(==, 4000) ) {
53 use_dgamouse = 0;
54 }
55 if ( !use_dgamouse || !local_X11 ||
56 !SDL_NAME(XF86DGAQueryExtension)(SDL_Display, &dga_event, &dga_error) ||
57 !SDL_NAME(XF86DGAQueryVersion)(SDL_Display, &dga_major, &dga_minor) ||
58 !SDL_NAME(XF86DGAQueryDirectVideo)(SDL_Display, SDL_Screen, &dga_flags) ||
59 !(dga_flags & XF86DGADirectPresent) ) {
60 use_dgamouse = 0;
61 }
62 }
63
64 if ( use_dgamouse && !(using_dga & DGA_MOUSE) ) {
65 if ( SDL_NAME(XF86DGADirectVideo)(SDL_Display, SDL_Screen, XF86DGADirectMouse) ) {
66 using_dga |= DGA_MOUSE;
67 }
68 }
69#endif /* SDL_VIDEO_DRIVER_X11_DGAMOUSE */
70}
71
72/* Argh. Glide resets DGA mouse mode when it makes the context current! */
73void X11_CheckDGAMouse(_THIS)
74{
75#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
76 if ( using_dga & DGA_MOUSE ) {
77 SDL_NAME(XF86DGADirectVideo)(SDL_Display,SDL_Screen,XF86DGADirectMouse);
78 }
79#endif
80}
81
82void X11_DisableDGAMouse(_THIS)
83{
84#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
85 if ( using_dga & DGA_MOUSE ) {
86 SDL_NAME(XF86DGADirectVideo)(SDL_Display, SDL_Screen, 0);
87 using_dga &= ~DGA_MOUSE;
88 }
89#endif /* SDL_VIDEO_DRIVER_X11_DGAMOUSE */
90}
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11dga_c.h b/apps/plugins/sdl/src/video/x11/SDL_x11dga_c.h
deleted file mode 100644
index a57511c893..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11dga_c.h
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_x11video.h"
25
26/* Different DGA access states */
27#define DGA_GRAPHICS 0x01
28#define DGA_KEYBOARD 0x02
29#define DGA_MOUSE 0x04
30
31extern void X11_EnableDGAMouse(_THIS);
32extern void X11_CheckDGAMouse(_THIS);
33extern void X11_DisableDGAMouse(_THIS);
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11dyn.c b/apps/plugins/sdl/src/video/x11/SDL_x11dyn.c
deleted file mode 100644
index 7058addfa8..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11dyn.c
+++ /dev/null
@@ -1,222 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#define DEBUG_DYNAMIC_X11 0
25
26#include "SDL_x11dyn.h"
27
28#if DEBUG_DYNAMIC_X11
29#include <stdio.h>
30#endif
31
32#ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
33
34#include "SDL_name.h"
35#include "SDL_loadso.h"
36
37typedef struct
38{
39 void *lib;
40 const char *libname;
41} x11dynlib;
42
43#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC
44#define SDL_VIDEO_DRIVER_X11_DYNAMIC NULL
45#endif
46#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT
47#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT NULL
48#endif
49#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRENDER
50#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRENDER NULL
51#endif
52#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR
53#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR NULL
54#endif
55
56static x11dynlib x11libs[] =
57{
58 { NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC },
59 { NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT },
60 { NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XRENDER },
61 { NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR },
62};
63
64static void *X11_GetSym(const char *fnname, int *rc)
65{
66 void *fn = NULL;
67 int i;
68 for (i = 0; i < SDL_TABLESIZE(x11libs); i++) {
69 if (x11libs[i].lib != NULL)
70 {
71 fn = SDL_LoadFunction(x11libs[i].lib, fnname);
72 if (fn != NULL)
73 break;
74 }
75 }
76
77 #if DEBUG_DYNAMIC_X11
78 if (fn != NULL)
79 printf("X11: Found '%s' in %s (%p)\n", fnname, x11libs[i].libname, *fn);
80 else
81 printf("X11: Symbol '%s' NOT FOUND!\n", fnname);
82 #endif
83
84 if (fn == NULL)
85 *rc = 0; /* kill this module. */
86
87 return fn;
88}
89
90
91/* Define all the function pointers and wrappers... */
92#define SDL_X11_MODULE(modname)
93#define SDL_X11_SYM(rc,fn,params,args,ret) \
94 static rc (*p##fn) params = NULL; \
95 rc fn params { ret p##fn args ; }
96#include "SDL_x11sym.h"
97#undef SDL_X11_MODULE
98#undef SDL_X11_SYM
99#endif /* SDL_VIDEO_DRIVER_X11_DYNAMIC */
100
101/* Annoying varargs entry point... */
102#ifdef X_HAVE_UTF8_STRING
103XIC (*pXCreateIC)(XIM,...) = NULL;
104char *(*pXGetICValues)(XIC, ...) = NULL;
105#endif
106
107/* These SDL_X11_HAVE_* flags are here whether you have dynamic X11 or not. */
108#define SDL_X11_MODULE(modname) int SDL_X11_HAVE_##modname = 1;
109#define SDL_X11_SYM(rc,fn,params,args,ret)
110#include "SDL_x11sym.h"
111#undef SDL_X11_MODULE
112#undef SDL_X11_SYM
113
114
115static void *SDL_XGetRequest_workaround(Display* dpy, CARD8 type, size_t len)
116{
117 xReq *req;
118 WORD64ALIGN
119 if (dpy->bufptr + len > dpy->bufmax)
120 _XFlush(dpy);
121 dpy->last_req = dpy->bufptr;
122 req = (xReq*)dpy->bufptr;
123 req->reqType = type;
124 req->length = len / 4;
125 dpy->bufptr += len;
126 dpy->request++;
127 return req;
128}
129
130static int x11_load_refcount = 0;
131
132void SDL_X11_UnloadSymbols(void)
133{
134 #ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
135 /* Don't actually unload if more than one module is using the libs... */
136 if (x11_load_refcount > 0) {
137 if (--x11_load_refcount == 0) {
138 int i;
139
140 /* set all the function pointers to NULL. */
141 #define SDL_X11_MODULE(modname) SDL_X11_HAVE_##modname = 1;
142 #define SDL_X11_SYM(rc,fn,params,args,ret) p##fn = NULL;
143 #include "SDL_x11sym.h"
144 #undef SDL_X11_MODULE
145 #undef SDL_X11_SYM
146
147 #ifdef X_HAVE_UTF8_STRING
148 pXCreateIC = NULL;
149 pXGetICValues = NULL;
150 #endif
151
152 for (i = 0; i < SDL_TABLESIZE(x11libs); i++) {
153 if (x11libs[i].lib != NULL) {
154 SDL_UnloadObject(x11libs[i].lib);
155 x11libs[i].lib = NULL;
156 }
157 }
158 }
159 }
160 #endif
161}
162
163/* returns non-zero if all needed symbols were loaded. */
164int SDL_X11_LoadSymbols(void)
165{
166 int rc = 1; /* always succeed if not using Dynamic X11 stuff. */
167
168 #ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
169 /* deal with multiple modules (dga, x11, etc) needing these symbols... */
170 if (x11_load_refcount++ == 0) {
171 int i;
172 int *thismod = NULL;
173 for (i = 0; i < SDL_TABLESIZE(x11libs); i++) {
174 if (x11libs[i].libname != NULL) {
175 x11libs[i].lib = SDL_LoadObject(x11libs[i].libname);
176 }
177 }
178 #define SDL_X11_MODULE(modname) thismod = &SDL_X11_HAVE_##modname;
179 #define SDL_X11_SYM(rc,fn,params,args,ret) \
180 p##fn = (rc(*)params) X11_GetSym(#fn, thismod);
181 #include "SDL_x11sym.h"
182 #undef SDL_X11_MODULE
183 #undef SDL_X11_SYM
184
185 #ifdef X_HAVE_UTF8_STRING
186 pXCreateIC = (XIC(*)(XIM,...)) X11_GetSym("XCreateIC",
187 &SDL_X11_HAVE_UTF8);
188 pXGetICValues = (char * (*)(XIC,...)) X11_GetSym("XGetICValues",
189 &SDL_X11_HAVE_UTF8);
190 #endif
191
192 /*
193 * In case we're built with newer Xlib headers, we need to make sure
194 * that _XGetRequest() is available, even on older systems.
195 * Otherwise, various Xlib macros we use will call a NULL pointer.
196 */
197 if (!SDL_X11_HAVE_XGETREQUEST) {
198 p_XGetRequest = SDL_XGetRequest_workaround;
199 }
200
201 if (SDL_X11_HAVE_BASEXLIB) { /* all required symbols loaded. */
202 SDL_ClearError();
203 } else {
204 SDL_X11_UnloadSymbols(); /* in case something got loaded... */
205 rc = 0;
206 }
207 }
208 #else
209 #if DEBUG_DYNAMIC_X11
210 printf("X11: No dynamic X11 support in this build of SDL.\n");
211 #endif
212 #ifdef X_HAVE_UTF8_STRING
213 pXCreateIC = XCreateIC;
214 pXGetICValues = XGetICValues;
215 #endif
216 #endif
217
218 return rc;
219}
220
221/* end of SDL_x11dyn.c ... */
222
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11dyn.h b/apps/plugins/sdl/src/video/x11/SDL_x11dyn.h
deleted file mode 100644
index c2ff82a727..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11dyn.h
+++ /dev/null
@@ -1,93 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_x11dyn_h
25#define _SDL_x11dyn_h
26
27#include <X11/Xlib.h>
28#include <X11/Xutil.h>
29#include <X11/Xatom.h>
30
31/* Apparently some X11 systems can't include this multiple times... */
32#ifndef SDL_INCLUDED_XLIBINT_H
33#define SDL_INCLUDED_XLIBINT_H 1
34#include <X11/Xlibint.h>
35#endif
36
37#include <X11/Xproto.h>
38
39#include "../Xext/extensions/Xext.h"
40#include "../Xext/extensions/extutil.h"
41
42#ifndef NO_SHARED_MEMORY
43#include <sys/ipc.h>
44#include <sys/shm.h>
45#include <X11/extensions/XShm.h>
46#endif
47
48#if SDL_VIDEO_DRIVER_X11_XRANDR
49#include <X11/extensions/Xrandr.h>
50#endif
51
52/*
53 * When using the "dynamic X11" functionality, we duplicate all the Xlib
54 * symbols that would be referenced by SDL inside of SDL itself.
55 * These duplicated symbols just serve as passthroughs to the functions
56 * in Xlib, that was dynamically loaded.
57 *
58 * This allows us to use Xlib as-is when linking against it directly, but
59 * also handles all the strange cases where there was code in the Xlib
60 * headers that may or may not exist or vary on a given platform.
61 */
62#ifdef __cplusplus
63extern "C" {
64#endif
65
66/* evil function signatures... */
67typedef Bool (*SDL_X11_XESetWireToEventRetType)(Display*,XEvent*,xEvent*);
68typedef int (*SDL_X11_XSynchronizeRetType)(Display*);
69typedef Status (*SDL_X11_XESetEventToWireRetType)(Display*,XEvent*,xEvent*);
70
71int SDL_X11_LoadSymbols(void);
72void SDL_X11_UnloadSymbols(void);
73
74/* That's really annoying...make this a function pointer no matter what. */
75#ifdef X_HAVE_UTF8_STRING
76extern XIC (*pXCreateIC)(XIM,...);
77extern char *(*pXGetICValues)(XIC, ...);
78#endif
79
80/* These SDL_X11_HAVE_* flags are here whether you have dynamic X11 or not. */
81#define SDL_X11_MODULE(modname) extern int SDL_X11_HAVE_##modname;
82#define SDL_X11_SYM(rc,fn,params,args,ret)
83#include "SDL_x11sym.h"
84#undef SDL_X11_MODULE
85#undef SDL_X11_SYM
86
87
88#ifdef __cplusplus
89}
90#endif
91
92#endif /* !defined _SDL_x11dyn_h */
93
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11events.c b/apps/plugins/sdl/src/video/x11/SDL_x11events.c
deleted file mode 100644
index 559a001486..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11events.c
+++ /dev/null
@@ -1,1414 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Handle the event stream, converting X11 events into SDL events */
25
26#include <setjmp.h>
27#include <X11/Xlib.h>
28#include <X11/Xutil.h>
29#include <X11/keysym.h>
30#ifdef __SVR4
31#include <X11/Sunkeysym.h>
32#endif
33#include <sys/types.h>
34#include <sys/time.h>
35#include <unistd.h>
36
37#include "SDL_timer.h"
38#include "SDL_syswm.h"
39#include "../SDL_sysvideo.h"
40#include "../../events/SDL_sysevents.h"
41#include "../../events/SDL_events_c.h"
42#include "SDL_x11video.h"
43#include "SDL_x11dga_c.h"
44#include "SDL_x11modes_c.h"
45#include "SDL_x11image_c.h"
46#include "SDL_x11gamma_c.h"
47#include "SDL_x11wm_c.h"
48#include "SDL_x11mouse_c.h"
49#include "SDL_x11events_c.h"
50
51
52/* Define this if you want to debug X11 events */
53/*#define DEBUG_XEVENTS*/
54
55/* The translation tables from an X11 keysym to a SDL keysym */
56static SDLKey ODD_keymap[256];
57static SDLKey MISC_keymap[256];
58SDLKey X11_TranslateKeycode(Display *display, KeyCode kc);
59
60/*
61 Pending resize target for ConfigureNotify (so outdated events don't
62 cause inappropriate resize events)
63*/
64int X11_PendingConfigureNotifyWidth = -1;
65int X11_PendingConfigureNotifyHeight = -1;
66
67#ifdef X_HAVE_UTF8_STRING
68Uint32 Utf8ToUcs4(const Uint8 *utf8)
69{
70 Uint32 c;
71 int i = 1;
72 int noOctets = 0;
73 int firstOctetMask = 0;
74 unsigned char firstOctet = utf8[0];
75 if (firstOctet < 0x80) {
76 /*
77 Characters in the range:
78 00000000 to 01111111 (ASCII Range)
79 are stored in one octet:
80 0xxxxxxx (The same as its ASCII representation)
81 The least 6 significant bits of the first octet is the most 6 significant nonzero bits
82 of the UCS4 representation.
83 */
84 noOctets = 1;
85 firstOctetMask = 0x7F; /* 0(1111111) - The most significant bit is ignored */
86 } else if ((firstOctet & 0xE0) /* get the most 3 significant bits by AND'ing with 11100000 */
87 == 0xC0 ) { /* see if those 3 bits are 110. If so, the char is in this range */
88 /*
89 Characters in the range:
90 00000000 10000000 to 00000111 11111111
91 are stored in two octets:
92 110xxxxx 10xxxxxx
93 The least 5 significant bits of the first octet is the most 5 significant nonzero bits
94 of the UCS4 representation.
95 */
96 noOctets = 2;
97 firstOctetMask = 0x1F; /* 000(11111) - The most 3 significant bits are ignored */
98 } else if ((firstOctet & 0xF0) /* get the most 4 significant bits by AND'ing with 11110000 */
99 == 0xE0) { /* see if those 4 bits are 1110. If so, the char is in this range */
100 /*
101 Characters in the range:
102 00001000 00000000 to 11111111 11111111
103 are stored in three octets:
104 1110xxxx 10xxxxxx 10xxxxxx
105 The least 4 significant bits of the first octet is the most 4 significant nonzero bits
106 of the UCS4 representation.
107 */
108 noOctets = 3;
109 firstOctetMask = 0x0F; /* 0000(1111) - The most 4 significant bits are ignored */
110 } else if ((firstOctet & 0xF8) /* get the most 5 significant bits by AND'ing with 11111000 */
111 == 0xF0) { /* see if those 5 bits are 11110. If so, the char is in this range */
112 /*
113 Characters in the range:
114 00000001 00000000 00000000 to 00011111 11111111 11111111
115 are stored in four octets:
116 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
117 The least 3 significant bits of the first octet is the most 3 significant nonzero bits
118 of the UCS4 representation.
119 */
120 noOctets = 4;
121 firstOctetMask = 0x07; /* 11110(111) - The most 5 significant bits are ignored */
122 } else if ((firstOctet & 0xFC) /* get the most 6 significant bits by AND'ing with 11111100 */
123 == 0xF8) { /* see if those 6 bits are 111110. If so, the char is in this range */
124 /*
125 Characters in the range:
126 00000000 00100000 00000000 00000000 to
127 00000011 11111111 11111111 11111111
128 are stored in five octets:
129 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
130 The least 2 significant bits of the first octet is the most 2 significant nonzero bits
131 of the UCS4 representation.
132 */
133 noOctets = 5;
134 firstOctetMask = 0x03; /* 111110(11) - The most 6 significant bits are ignored */
135 } else if ((firstOctet & 0xFE) /* get the most 7 significant bits by AND'ing with 11111110 */
136 == 0xFC) { /* see if those 7 bits are 1111110. If so, the char is in this range */
137 /*
138 Characters in the range:
139 00000100 00000000 00000000 00000000 to
140 01111111 11111111 11111111 11111111
141 are stored in six octets:
142 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
143 The least significant bit of the first octet is the most significant nonzero bit
144 of the UCS4 representation.
145 */
146 noOctets = 6;
147 firstOctetMask = 0x01; /* 1111110(1) - The most 7 significant bits are ignored */
148 } else
149 return 0; /* The given chunk is not a valid UTF-8 encoded Unicode character */
150
151 /*
152 The least noOctets significant bits of the first octet is the most 2 significant nonzero bits
153 of the UCS4 representation.
154 The first 6 bits of the UCS4 representation is the least 8-noOctets-1 significant bits of
155 firstOctet if the character is not ASCII. If so, it's the least 7 significant bits of firstOctet.
156 This done by AND'ing firstOctet with its mask to trim the bits used for identifying the
157 number of continuing octets (if any) and leave only the free bits (the x's)
158 Sample:
159 1-octet: 0xxxxxxx & 01111111 = 0xxxxxxx
160 2-octets: 110xxxxx & 00011111 = 000xxxxx
161 */
162 c = firstOctet & firstOctetMask;
163
164 /* Now, start filling c.ucs4 with the bits from the continuing octets from utf8. */
165 for (i = 1; i < noOctets; i++) {
166 /* A valid continuing octet is of the form 10xxxxxx */
167 if ((utf8[i] & 0xC0) /* get the most 2 significant bits by AND'ing with 11000000 */
168 != 0x80) /* see if those 2 bits are 10. If not, the is a malformed sequence. */
169 /*The given chunk is a partial sequence at the end of a string that could
170 begin a valid character */
171 return 0;
172
173 /* Make room for the next 6-bits */
174 c <<= 6;
175
176 /*
177 Take only the least 6 significance bits of the current octet (utf8[i]) and fill the created room
178 of c.ucs4 with them.
179 This done by AND'ing utf8[i] with 00111111 and the OR'ing the result with c.ucs4.
180 */
181 c |= utf8[i] & 0x3F;
182 }
183 return c;
184}
185
186/* Given a UTF-8 encoded string pointed to by utf8 of length length in
187 bytes, returns the corresponding UTF-16 encoded string in the
188 buffer pointed to by utf16. The maximum number of UTF-16 encoding
189 units (i.e., Unit16s) allowed in the buffer is specified in
190 utf16_max_length. The return value is the number of UTF-16
191 encoding units placed in the output buffer pointed to by utf16.
192
193 In case of an error, -1 is returned, leaving some unusable partial
194 results in the output buffer.
195
196 The caller must estimate the size of utf16 buffer by itself before
197 calling this function. Insufficient output buffer is considered as
198 an error, and once an error occured, this function doesn't give any
199 clue how large the result will be.
200
201 The error cases include following:
202
203 - Invalid byte sequences were in the input UTF-8 bytes. The caller
204 has no way to know what point in the input buffer was the
205 errornous byte.
206
207 - The input contained a character (a valid UTF-8 byte sequence)
208 whose scalar value exceeded the range that UTF-16 can represent
209 (i.e., characters whose Unicode scalar value above 0x110000).
210
211 - The output buffer has no enough space to hold entire utf16 data.
212
213 Please note:
214
215 - '\0'-termination is not assumed both on the input UTF-8 string
216 and on the output UTF-16 string; any legal zero byte in the input
217 UTF-8 string will be converted to a 16-bit zero in output. As a
218 side effect, the last UTF-16 encoding unit stored in the output
219 buffer will have a non-zero value if the input UTF-8 was not
220 '\0'-terminated.
221
222 - UTF-8 aliases are *not* considered as an error. They are
223 converted to UTF-16. For example, 0xC0 0xA0, 0xE0 0x80 0xA0,
224 and 0xF0 0x80 0x80 0xA0 are all mapped to a single UTF-16
225 encoding unit 0x0020.
226
227 - Three byte UTF-8 sequences whose value corresponds to a surrogate
228 code or other reserved scalar value are not considered as an
229 error either. They may cause an invalid UTF-16 data (e.g., those
230 containing unpaired surrogates).
231
232*/
233
234static int Utf8ToUtf16(const Uint8 *utf8, const int utf8_length, Uint16 *utf16, const int utf16_max_length) {
235
236 /* p moves over the output buffer. max_ptr points to the next to the last slot of the buffer. */
237 Uint16 *p = utf16;
238 Uint16 const *const max_ptr = utf16 + utf16_max_length;
239
240 /* end_of_input points to the last byte of input as opposed to the next to the last byte. */
241 Uint8 const *const end_of_input = utf8 + utf8_length - 1;
242
243 while (utf8 <= end_of_input) {
244 Uint8 const c = *utf8;
245 if (p >= max_ptr) {
246 /* No more output space. */
247 return -1;
248 }
249 if (c < 0x80) {
250 /* One byte ASCII. */
251 *p++ = c;
252 utf8 += 1;
253 } else if (c < 0xC0) {
254 /* Follower byte without preceeding leader bytes. */
255 return -1;
256 } else if (c < 0xE0) {
257 /* Two byte sequence. We need one follower byte. */
258 if (end_of_input - utf8 < 1 || (((utf8[1] ^ 0x80)) & 0xC0)) {
259 return -1;
260 }
261 *p++ = (Uint16)(0xCF80 + (c << 6) + utf8[1]);
262 utf8 += 2;
263 } else if (c < 0xF0) {
264 /* Three byte sequence. We need two follower byte. */
265 if (end_of_input - utf8 < 2 || (((utf8[1] ^ 0x80) | (utf8[2] ^ 0x80)) & 0xC0)) {
266 return -1;
267 }
268 *p++ = (Uint16)(0xDF80 + (c << 12) + (utf8[1] << 6) + utf8[2]);
269 utf8 += 3;
270 } else if (c < 0xF8) {
271 int plane;
272 /* Four byte sequence. We need three follower bytes. */
273 if (end_of_input - utf8 < 3 || (((utf8[1] ^ 0x80) | (utf8[2] ^0x80) | (utf8[3] ^ 0x80)) & 0xC0)) {
274 return -1;
275 }
276 plane = (-0xC8 + (c << 2) + (utf8[1] >> 4));
277 if (plane == 0) {
278 /* This four byte sequence is an alias that
279 corresponds to a Unicode scalar value in BMP.
280 It fits in an UTF-16 encoding unit. */
281 *p++ = (Uint16)(0xDF80 + (utf8[1] << 12) + (utf8[2] << 6) + utf8[3]);
282 } else if (plane <= 16) {
283 /* This is a legal four byte sequence that corresponds to a surrogate pair. */
284 if (p + 1 >= max_ptr) {
285 /* No enough space on the output buffer for the pair. */
286 return -1;
287 }
288 *p++ = (Uint16)(0xE5B8 + (c << 8) + (utf8[1] << 2) + (utf8[2] >> 4));
289 *p++ = (Uint16)(0xDB80 + ((utf8[2] & 0x0F) << 6) + utf8[3]);
290 } else {
291 /* This four byte sequence is out of UTF-16 code space. */
292 return -1;
293 }
294 utf8 += 4;
295 } else {
296 /* Longer sequence or unused byte. */
297 return -1;
298 }
299 }
300 return p - utf16;
301}
302
303#endif
304
305/* Check to see if this is a repeated key.
306 (idea shamelessly lifted from GII -- thanks guys! :)
307 */
308static int X11_KeyRepeat(Display *display, XEvent *event)
309{
310 XEvent peekevent;
311 int repeated;
312
313 repeated = 0;
314 if ( XPending(display) ) {
315 XPeekEvent(display, &peekevent);
316 if ( (peekevent.type == KeyPress) &&
317 (peekevent.xkey.keycode == event->xkey.keycode) &&
318 ((peekevent.xkey.time-event->xkey.time) < 2) ) {
319 repeated = 1;
320 XNextEvent(display, &peekevent);
321 }
322 }
323 return(repeated);
324}
325
326/* Note: The X server buffers and accumulates mouse motion events, so
327 the motion event generated by the warp may not appear exactly as we
328 expect it to. We work around this (and improve performance) by only
329 warping the pointer when it reaches the edge, and then wait for it.
330*/
331#define MOUSE_FUDGE_FACTOR 8
332
333static __inline__ int X11_WarpedMotion(_THIS, XEvent *xevent)
334{
335 int w, h, i;
336 int deltax, deltay;
337 int posted;
338
339 w = SDL_VideoSurface->w;
340 h = SDL_VideoSurface->h;
341 deltax = xevent->xmotion.x - mouse_last.x;
342 deltay = xevent->xmotion.y - mouse_last.y;
343#ifdef DEBUG_MOTION
344 printf("Warped mouse motion: %d,%d\n", deltax, deltay);
345#endif
346 mouse_last.x = xevent->xmotion.x;
347 mouse_last.y = xevent->xmotion.y;
348 posted = SDL_PrivateMouseMotion(0, 1, deltax, deltay);
349
350 if ( (xevent->xmotion.x < MOUSE_FUDGE_FACTOR) ||
351 (xevent->xmotion.x > (w-MOUSE_FUDGE_FACTOR)) ||
352 (xevent->xmotion.y < MOUSE_FUDGE_FACTOR) ||
353 (xevent->xmotion.y > (h-MOUSE_FUDGE_FACTOR)) ) {
354 /* Get the events that have accumulated */
355 while ( XCheckTypedEvent(SDL_Display, MotionNotify, xevent) ) {
356 deltax = xevent->xmotion.x - mouse_last.x;
357 deltay = xevent->xmotion.y - mouse_last.y;
358#ifdef DEBUG_MOTION
359 printf("Extra mouse motion: %d,%d\n", deltax, deltay);
360#endif
361 mouse_last.x = xevent->xmotion.x;
362 mouse_last.y = xevent->xmotion.y;
363 posted += SDL_PrivateMouseMotion(0, 1, deltax, deltay);
364 }
365 mouse_last.x = w/2;
366 mouse_last.y = h/2;
367 XWarpPointer(SDL_Display, None, SDL_Window, 0, 0, 0, 0,
368 mouse_last.x, mouse_last.y);
369 for ( i=0; i<10; ++i ) {
370 XMaskEvent(SDL_Display, PointerMotionMask, xevent);
371 if ( (xevent->xmotion.x >
372 (mouse_last.x-MOUSE_FUDGE_FACTOR)) &&
373 (xevent->xmotion.x <
374 (mouse_last.x+MOUSE_FUDGE_FACTOR)) &&
375 (xevent->xmotion.y >
376 (mouse_last.y-MOUSE_FUDGE_FACTOR)) &&
377 (xevent->xmotion.y <
378 (mouse_last.y+MOUSE_FUDGE_FACTOR)) ) {
379 break;
380 }
381#ifdef DEBUG_XEVENTS
382 printf("Lost mouse motion: %d,%d\n", xevent->xmotion.x, xevent->xmotion.y);
383#endif
384 }
385#ifdef DEBUG_XEVENTS
386 if ( i == 10 ) {
387 printf("Warning: didn't detect mouse warp motion\n");
388 }
389#endif
390 }
391 return(posted);
392}
393
394static int X11_DispatchEvent(_THIS)
395{
396 int posted;
397 XEvent xevent;
398
399 SDL_memset(&xevent, '\0', sizeof (XEvent)); /* valgrind fix. --ryan. */
400 XNextEvent(SDL_Display, &xevent);
401
402 /* Discard KeyRelease and KeyPress events generated by auto-repeat.
403 We need to do it before passing event to XFilterEvent. Otherwise,
404 KeyRelease aware IMs are confused... */
405 if ( xevent.type == KeyRelease
406 && X11_KeyRepeat(SDL_Display, &xevent) ) {
407 return 0;
408 }
409
410#ifdef X_HAVE_UTF8_STRING
411 /* If we are translating with IM, we need to pass all events
412 to XFilterEvent, and discard those filtered events immediately. */
413 if ( SDL_TranslateUNICODE
414 && SDL_IM != NULL
415 && XFilterEvent(&xevent, None) ) {
416 return 0;
417 }
418#endif
419
420 posted = 0;
421 switch (xevent.type) {
422
423 /* Gaining mouse coverage? */
424 case EnterNotify: {
425#ifdef DEBUG_XEVENTS
426printf("EnterNotify! (%d,%d)\n", xevent.xcrossing.x, xevent.xcrossing.y);
427if ( xevent.xcrossing.mode == NotifyGrab )
428printf("Mode: NotifyGrab\n");
429if ( xevent.xcrossing.mode == NotifyUngrab )
430printf("Mode: NotifyUngrab\n");
431#endif
432 if ( this->input_grab == SDL_GRAB_OFF ) {
433 posted = SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
434 }
435 posted = SDL_PrivateMouseMotion(0, 0,
436 xevent.xcrossing.x,
437 xevent.xcrossing.y);
438 }
439 break;
440
441 /* Losing mouse coverage? */
442 case LeaveNotify: {
443#ifdef DEBUG_XEVENTS
444printf("LeaveNotify! (%d,%d)\n", xevent.xcrossing.x, xevent.xcrossing.y);
445if ( xevent.xcrossing.mode == NotifyGrab )
446printf("Mode: NotifyGrab\n");
447if ( xevent.xcrossing.mode == NotifyUngrab )
448printf("Mode: NotifyUngrab\n");
449#endif
450 if ( (xevent.xcrossing.mode != NotifyGrab) &&
451 (xevent.xcrossing.mode != NotifyUngrab) &&
452 (xevent.xcrossing.detail != NotifyInferior) ) {
453 if ( this->input_grab == SDL_GRAB_OFF ) {
454 posted = SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
455 } else {
456 posted = SDL_PrivateMouseMotion(0, 0,
457 xevent.xcrossing.x,
458 xevent.xcrossing.y);
459 }
460 }
461 }
462 break;
463
464 /* Gaining input focus? */
465 case FocusIn: {
466#ifdef DEBUG_XEVENTS
467printf("FocusIn!\n");
468#endif
469 posted = SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS);
470
471#ifdef X_HAVE_UTF8_STRING
472 if ( SDL_IC != NULL ) {
473 XSetICFocus(SDL_IC);
474 }
475#endif
476 /* Queue entry into fullscreen mode */
477 switch_waiting = 0x01 | SDL_FULLSCREEN;
478 switch_time = SDL_GetTicks() + 1500;
479 }
480 break;
481
482 /* Losing input focus? */
483 case FocusOut: {
484#ifdef DEBUG_XEVENTS
485printf("FocusOut!\n");
486#endif
487 posted = SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS);
488
489#ifdef X_HAVE_UTF8_STRING
490 if ( SDL_IC != NULL ) {
491 XUnsetICFocus(SDL_IC);
492 }
493#endif
494 /* Queue leaving fullscreen mode */
495 switch_waiting = 0x01;
496 switch_time = SDL_GetTicks() + 200;
497 }
498 break;
499
500#ifdef X_HAVE_UTF8_STRING
501 /* Some IM requires MappingNotify to be passed to
502 XRefreshKeyboardMapping by the app. */
503 case MappingNotify: {
504 XRefreshKeyboardMapping(&xevent.xmapping);
505 }
506 break;
507#endif /* X_HAVE_UTF8_STRING */
508
509 /* Generated upon EnterWindow and FocusIn */
510 case KeymapNotify: {
511#ifdef DEBUG_XEVENTS
512printf("KeymapNotify!\n");
513#endif
514 X11_SetKeyboardState(SDL_Display, xevent.xkeymap.key_vector);
515 }
516 break;
517
518 /* Mouse motion? */
519 case MotionNotify: {
520 if ( SDL_VideoSurface ) {
521 if ( mouse_relative ) {
522 if ( using_dga & DGA_MOUSE ) {
523#ifdef DEBUG_MOTION
524 printf("DGA motion: %d,%d\n", xevent.xmotion.x_root, xevent.xmotion.y_root);
525#endif
526 posted = SDL_PrivateMouseMotion(0, 1,
527 xevent.xmotion.x_root,
528 xevent.xmotion.y_root);
529 } else {
530 posted = X11_WarpedMotion(this,&xevent);
531 }
532 } else {
533#ifdef DEBUG_MOTION
534 printf("X11 motion: %d,%d\n", xevent.xmotion.x, xevent.xmotion.y);
535#endif
536 posted = SDL_PrivateMouseMotion(0, 0,
537 xevent.xmotion.x,
538 xevent.xmotion.y);
539 }
540 }
541 }
542 break;
543
544 /* Mouse button press? */
545 case ButtonPress: {
546 posted = SDL_PrivateMouseButton(SDL_PRESSED,
547 xevent.xbutton.button, 0, 0);
548 }
549 break;
550
551 /* Mouse button release? */
552 case ButtonRelease: {
553 posted = SDL_PrivateMouseButton(SDL_RELEASED,
554 xevent.xbutton.button, 0, 0);
555 }
556 break;
557
558 /* Key press? */
559 case KeyPress: {
560 SDL_keysym keysym;
561 KeyCode keycode = xevent.xkey.keycode;
562
563#ifdef DEBUG_XEVENTS
564printf("KeyPress (X11 keycode = 0x%X)\n", xevent.xkey.keycode);
565#endif
566 /* If we're not doing translation, we're done! */
567 if ( !SDL_TranslateUNICODE ) {
568 /* Get the translated SDL virtual keysym and put it on the queue.*/
569 keysym.scancode = keycode;
570 keysym.sym = X11_TranslateKeycode(SDL_Display, keycode);
571 keysym.mod = KMOD_NONE;
572 keysym.unicode = 0;
573 posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
574 break;
575 }
576
577 /* Look up the translated value for the key event */
578#ifdef X_HAVE_UTF8_STRING
579 if ( SDL_IC != NULL ) {
580 Status status;
581 KeySym xkeysym;
582 int i;
583 /* A UTF-8 character can be at most 6 bytes */
584 /* ... It's true, but Xutf8LookupString can
585 return more than one characters. Moreover,
586 the spec. put no upper bound, so we should
587 be ready for longer strings. */
588 char keybuf[32];
589 char *keydata = keybuf;
590 int count;
591 Uint16 utf16buf[32];
592 Uint16 *utf16data = utf16buf;
593 int utf16size;
594 int utf16length;
595
596 count = Xutf8LookupString(SDL_IC, &xevent.xkey, keydata, sizeof(keybuf), &xkeysym, &status);
597 if (XBufferOverflow == status) {
598 /* The IM has just generated somewhat long
599 string. We need a longer buffer in this
600 case. */
601 keydata = SDL_malloc(count);
602 if ( keydata == NULL ) {
603 SDL_OutOfMemory();
604 break;
605 }
606 count = Xutf8LookupString(SDL_IC, &xevent.xkey, keydata, count, &xkeysym, &status);
607 }
608
609 switch (status) {
610
611 case XBufferOverflow: {
612 /* Oops! We have allocated the bytes as
613 requested by Xutf8LookupString, so the
614 length of the buffer must be
615 sufficient. This case should never
616 happen! */
617 SDL_SetError("Xutf8LookupString indicated a double buffer overflow!");
618 break;
619 }
620
621 case XLookupChars:
622 case XLookupBoth: {
623 if (0 == count) {
624 break;
625 }
626
627 /* We got a converted string from IM. Make
628 sure to deliver all characters to the
629 application as SDL events. Note that
630 an SDL event can only carry one UTF-16
631 encoding unit, and a surrogate pair is
632 delivered as two SDL events. I guess
633 this behaviour is probably _imported_
634 from Windows or MacOS. To do so, we need
635 to convert the UTF-8 data into UTF-16
636 data (not UCS4/UTF-32!). We need an
637 estimate of the number of UTF-16 encoding
638 units here. The worst case is pure ASCII
639 string. Assume so. */
640 /* In 1.3 SDL may have a text event instead, that
641 carries the whole UTF-8 string with it. */
642 utf16size = count * sizeof(Uint16);
643 if (utf16size > sizeof(utf16buf)) {
644 utf16data = (Uint16 *) SDL_malloc(utf16size);
645 if (utf16data == NULL) {
646 SDL_OutOfMemory();
647 break;
648 }
649 }
650 utf16length = Utf8ToUtf16((Uint8 *)keydata, count, utf16data, utf16size);
651 if (utf16length < 0) {
652 /* The keydata contained an invalid byte
653 sequence. It should be a bug of the IM
654 or Xlib... */
655 SDL_SetError("Oops! Xutf8LookupString returned an invalid UTF-8 sequence!");
656 break;
657 }
658
659 /* Deliver all UTF-16 encoding units. At
660 this moment, SDL event queue has a
661 fixed size (128 events), and an SDL
662 event can hold just one UTF-16 encoding
663 unit. So, if we receive more than 128
664 UTF-16 encoding units from a commit,
665 exceeded characters will be lost. */
666 for (i = 0; i < utf16length - 1; i++) {
667 keysym.scancode = 0;
668 keysym.sym = SDLK_UNKNOWN;
669 keysym.mod = KMOD_NONE;
670 keysym.unicode = utf16data[i];
671 posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
672 }
673 /* The keysym for the last character carries the
674 scancode and symbol that corresponds to the X11
675 keycode. */
676 if (utf16length > 0) {
677 keysym.scancode = keycode;
678 keysym.sym = (keycode ? X11_TranslateKeycode(SDL_Display, keycode) : 0);
679 keysym.mod = KMOD_NONE;
680 keysym.unicode = utf16data[utf16length - 1];
681 posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
682 }
683 break;
684 }
685
686 case XLookupKeySym: {
687 /* I'm not sure whether it is possible that
688 a zero keycode makes XLookupKeySym
689 status. What I'm sure is that a
690 combination of a zero scan code and a non
691 zero sym makes SDL_PrivateKeyboard
692 strange state... So, just discard it.
693 If this doesn't work, I'm receiving bug
694 reports, and I can know under what
695 condition this case happens. */
696 if (keycode) {
697 keysym.scancode = keycode;
698 keysym.sym = X11_TranslateKeycode(SDL_Display, keycode);
699 keysym.mod = KMOD_NONE;
700 keysym.unicode = 0;
701 posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
702 }
703 break;
704 }
705
706 case XLookupNone: {
707 /* IM has eaten the event. */
708 break;
709 }
710
711 default:
712 /* An unknown status from Xutf8LookupString. */
713 SDL_SetError("Oops! Xutf8LookupStringreturned an unknown status");
714 }
715
716 /* Release dynamic buffers if allocated. */
717 if (keydata != NULL && keybuf != keydata) {
718 SDL_free(keydata);
719 }
720 if (utf16data != NULL && utf16buf != utf16data) {
721 SDL_free(utf16data);
722 }
723 }
724 else
725#endif
726 {
727 static XComposeStatus state;
728 char keybuf[32];
729
730 keysym.scancode = keycode;
731 keysym.sym = X11_TranslateKeycode(SDL_Display, keycode);
732 keysym.mod = KMOD_NONE;
733 keysym.unicode = 0;
734 if ( XLookupString(&xevent.xkey,
735 keybuf, sizeof(keybuf),
736 NULL, &state) ) {
737 /*
738 * FIXME: XLookupString() may yield more than one
739 * character, so we need a mechanism to allow for
740 * this (perhaps null keypress events with a
741 * unicode value)
742 */
743 keysym.unicode = (Uint8)keybuf[0];
744 }
745
746 posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
747 }
748 }
749 break;
750
751 /* Key release? */
752 case KeyRelease: {
753 SDL_keysym keysym;
754 KeyCode keycode = xevent.xkey.keycode;
755
756 if (keycode == 0) {
757 /* There should be no KeyRelease for keycode == 0,
758 since it is a notification from IM but a real
759 keystroke. */
760 /* We need to emit some diagnostic message here. */
761 break;
762 }
763
764#ifdef DEBUG_XEVENTS
765printf("KeyRelease (X11 keycode = 0x%X)\n", xevent.xkey.keycode);
766#endif
767
768 /* Get the translated SDL virtual keysym */
769 keysym.scancode = keycode;
770 keysym.sym = X11_TranslateKeycode(SDL_Display, keycode);
771 keysym.mod = KMOD_NONE;
772 keysym.unicode = 0;
773
774 posted = SDL_PrivateKeyboard(SDL_RELEASED, &keysym);
775 }
776 break;
777
778 /* Have we been iconified? */
779 case UnmapNotify: {
780#ifdef DEBUG_XEVENTS
781printf("UnmapNotify!\n");
782#endif
783 /* If we're active, make ourselves inactive */
784 if ( SDL_GetAppState() & SDL_APPACTIVE ) {
785 /* Swap out the gamma before we go inactive */
786 X11_SwapVidModeGamma(this);
787
788 /* Send an internal deactivate event */
789 posted = SDL_PrivateAppActive(0,
790 SDL_APPACTIVE|SDL_APPINPUTFOCUS);
791 }
792 }
793 break;
794
795 /* Have we been restored? */
796 case MapNotify: {
797#ifdef DEBUG_XEVENTS
798printf("MapNotify!\n");
799#endif
800 /* If we're not active, make ourselves active */
801 if ( !(SDL_GetAppState() & SDL_APPACTIVE) ) {
802 /* Send an internal activate event */
803 posted = SDL_PrivateAppActive(1, SDL_APPACTIVE);
804
805 /* Now that we're active, swap the gamma back */
806 X11_SwapVidModeGamma(this);
807 }
808
809 if ( SDL_VideoSurface &&
810 (SDL_VideoSurface->flags & SDL_FULLSCREEN) ) {
811 X11_EnterFullScreen(this);
812 } else {
813 X11_GrabInputNoLock(this, this->input_grab);
814 }
815 X11_CheckMouseModeNoLock(this);
816
817 if ( SDL_VideoSurface ) {
818 X11_RefreshDisplay(this);
819 }
820 }
821 break;
822
823 /* Have we been resized or moved? */
824 case ConfigureNotify: {
825#ifdef DEBUG_XEVENTS
826printf("ConfigureNotify! (resize: %dx%d)\n", xevent.xconfigure.width, xevent.xconfigure.height);
827#endif
828 if ((X11_PendingConfigureNotifyWidth != -1) &&
829 (X11_PendingConfigureNotifyHeight != -1)) {
830 if ((xevent.xconfigure.width != X11_PendingConfigureNotifyWidth) &&
831 (xevent.xconfigure.height != X11_PendingConfigureNotifyHeight)) {
832 /* Event is from before the resize, so ignore. */
833 break;
834 }
835 X11_PendingConfigureNotifyWidth = -1;
836 X11_PendingConfigureNotifyHeight = -1;
837 }
838 if ( SDL_VideoSurface ) {
839 if ((xevent.xconfigure.width != SDL_VideoSurface->w) ||
840 (xevent.xconfigure.height != SDL_VideoSurface->h)) {
841 /* FIXME: Find a better fix for the bug with KDE 1.2 */
842 if ( ! ((xevent.xconfigure.width == 32) &&
843 (xevent.xconfigure.height == 32)) ) {
844 SDL_PrivateResize(xevent.xconfigure.width,
845 xevent.xconfigure.height);
846 }
847 } else {
848 /* OpenGL windows need to know about the change */
849 if ( SDL_VideoSurface->flags & SDL_OPENGL ) {
850 SDL_PrivateExpose();
851 }
852 }
853 }
854 }
855 break;
856
857 /* Have we been requested to quit (or another client message?) */
858 case ClientMessage: {
859 if ( (xevent.xclient.format == 32) &&
860 (xevent.xclient.data.l[0] == WM_DELETE_WINDOW) )
861 {
862 posted = SDL_PrivateQuit();
863 } else
864 if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) {
865 SDL_SysWMmsg wmmsg;
866
867 SDL_VERSION(&wmmsg.version);
868 wmmsg.subsystem = SDL_SYSWM_X11;
869 wmmsg.event.xevent = xevent;
870 posted = SDL_PrivateSysWMEvent(&wmmsg);
871 }
872 }
873 break;
874
875 /* Do we need to refresh ourselves? */
876 case Expose: {
877#ifdef DEBUG_XEVENTS
878printf("Expose (count = %d)\n", xevent.xexpose.count);
879#endif
880 if ( SDL_VideoSurface && (xevent.xexpose.count == 0) ) {
881 X11_RefreshDisplay(this);
882 }
883 }
884 break;
885
886 default: {
887#ifdef DEBUG_XEVENTS
888printf("Unhandled event %d\n", xevent.type);
889#endif
890 /* Only post the event if we're watching for it */
891 if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) {
892 SDL_SysWMmsg wmmsg;
893
894 SDL_VERSION(&wmmsg.version);
895 wmmsg.subsystem = SDL_SYSWM_X11;
896 wmmsg.event.xevent = xevent;
897 posted = SDL_PrivateSysWMEvent(&wmmsg);
898 }
899 }
900 break;
901 }
902 return(posted);
903}
904
905/* Ack! XPending() actually performs a blocking read if no events available */
906int X11_Pending(Display *display)
907{
908 /* Flush the display connection and look to see if events are queued */
909 XFlush(display);
910 if ( XEventsQueued(display, QueuedAlready) ) {
911 return(1);
912 }
913
914 /* More drastic measures are required -- see if X is ready to talk */
915 {
916 static struct timeval zero_time; /* static == 0 */
917 int x11_fd;
918 fd_set fdset;
919
920 x11_fd = ConnectionNumber(display);
921 FD_ZERO(&fdset);
922 FD_SET(x11_fd, &fdset);
923 if ( select(x11_fd+1, &fdset, NULL, NULL, &zero_time) == 1 ) {
924 return(XPending(display));
925 }
926 }
927
928 /* Oh well, nothing is ready .. */
929 return(0);
930}
931
932void X11_PumpEvents(_THIS)
933{
934 int pending;
935
936 /* Update activity every five seconds to prevent screensaver. --ryan. */
937 if (!allow_screensaver) {
938 static Uint32 screensaverTicks;
939 Uint32 nowTicks = SDL_GetTicks();
940 if ((nowTicks - screensaverTicks) > 5000) {
941 XResetScreenSaver(SDL_Display);
942 screensaverTicks = nowTicks;
943 }
944 }
945
946 /* Keep processing pending events */
947 pending = 0;
948 while ( X11_Pending(SDL_Display) ) {
949 X11_DispatchEvent(this);
950 ++pending;
951 }
952 if ( switch_waiting ) {
953 Uint32 now;
954
955 now = SDL_GetTicks();
956 if ( pending || !SDL_VideoSurface ) {
957 /* Try again later... */
958 if ( switch_waiting & SDL_FULLSCREEN ) {
959 switch_time = now + 1500;
960 } else {
961 switch_time = now + 200;
962 }
963 } else if ( (int)(switch_time-now) <= 0 ) {
964 Uint32 go_fullscreen;
965
966 go_fullscreen = switch_waiting & SDL_FULLSCREEN;
967 switch_waiting = 0;
968 if ( SDL_VideoSurface->flags & SDL_FULLSCREEN ) {
969 if ( go_fullscreen ) {
970 X11_EnterFullScreen(this);
971 } else {
972 X11_LeaveFullScreen(this);
973 }
974 }
975 /* Handle focus in/out when grabbed */
976 if ( go_fullscreen ) {
977 X11_GrabInputNoLock(this, this->input_grab);
978 } else {
979 X11_GrabInputNoLock(this, SDL_GRAB_OFF);
980 }
981 X11_CheckMouseModeNoLock(this);
982 }
983 }
984}
985
986void X11_InitKeymap(void)
987{
988 int i;
989
990 /* Odd keys used in international keyboards */
991 for ( i=0; i<SDL_arraysize(ODD_keymap); ++i )
992 ODD_keymap[i] = SDLK_UNKNOWN;
993
994 /* Some of these might be mappable to an existing SDLK_ code */
995 ODD_keymap[XK_dead_grave&0xFF] = SDLK_COMPOSE;
996 ODD_keymap[XK_dead_acute&0xFF] = SDLK_COMPOSE;
997 ODD_keymap[XK_dead_tilde&0xFF] = SDLK_COMPOSE;
998 ODD_keymap[XK_dead_macron&0xFF] = SDLK_COMPOSE;
999 ODD_keymap[XK_dead_breve&0xFF] = SDLK_COMPOSE;
1000 ODD_keymap[XK_dead_abovedot&0xFF] = SDLK_COMPOSE;
1001 ODD_keymap[XK_dead_diaeresis&0xFF] = SDLK_COMPOSE;
1002 ODD_keymap[XK_dead_abovering&0xFF] = SDLK_COMPOSE;
1003 ODD_keymap[XK_dead_doubleacute&0xFF] = SDLK_COMPOSE;
1004 ODD_keymap[XK_dead_caron&0xFF] = SDLK_COMPOSE;
1005 ODD_keymap[XK_dead_cedilla&0xFF] = SDLK_COMPOSE;
1006 ODD_keymap[XK_dead_ogonek&0xFF] = SDLK_COMPOSE;
1007 ODD_keymap[XK_dead_iota&0xFF] = SDLK_COMPOSE;
1008 ODD_keymap[XK_dead_voiced_sound&0xFF] = SDLK_COMPOSE;
1009 ODD_keymap[XK_dead_semivoiced_sound&0xFF] = SDLK_COMPOSE;
1010 ODD_keymap[XK_dead_belowdot&0xFF] = SDLK_COMPOSE;
1011#ifdef XK_dead_hook
1012 ODD_keymap[XK_dead_hook&0xFF] = SDLK_COMPOSE;
1013#endif
1014#ifdef XK_dead_horn
1015 ODD_keymap[XK_dead_horn&0xFF] = SDLK_COMPOSE;
1016#endif
1017
1018#ifdef XK_dead_circumflex
1019 /* These X keysyms have 0xFE as the high byte */
1020 ODD_keymap[XK_dead_circumflex&0xFF] = SDLK_CARET;
1021#endif
1022#ifdef XK_ISO_Level3_Shift
1023 ODD_keymap[XK_ISO_Level3_Shift&0xFF] = SDLK_MODE; /* "Alt Gr" key */
1024#endif
1025
1026 /* Map the miscellaneous keys */
1027 for ( i=0; i<SDL_arraysize(MISC_keymap); ++i )
1028 MISC_keymap[i] = SDLK_UNKNOWN;
1029
1030 /* These X keysyms have 0xFF as the high byte */
1031 MISC_keymap[XK_BackSpace&0xFF] = SDLK_BACKSPACE;
1032 MISC_keymap[XK_Tab&0xFF] = SDLK_TAB;
1033 MISC_keymap[XK_Clear&0xFF] = SDLK_CLEAR;
1034 MISC_keymap[XK_Return&0xFF] = SDLK_RETURN;
1035 MISC_keymap[XK_Pause&0xFF] = SDLK_PAUSE;
1036 MISC_keymap[XK_Escape&0xFF] = SDLK_ESCAPE;
1037 MISC_keymap[XK_Delete&0xFF] = SDLK_DELETE;
1038
1039 MISC_keymap[XK_KP_0&0xFF] = SDLK_KP0; /* Keypad 0-9 */
1040 MISC_keymap[XK_KP_1&0xFF] = SDLK_KP1;
1041 MISC_keymap[XK_KP_2&0xFF] = SDLK_KP2;
1042 MISC_keymap[XK_KP_3&0xFF] = SDLK_KP3;
1043 MISC_keymap[XK_KP_4&0xFF] = SDLK_KP4;
1044 MISC_keymap[XK_KP_5&0xFF] = SDLK_KP5;
1045 MISC_keymap[XK_KP_6&0xFF] = SDLK_KP6;
1046 MISC_keymap[XK_KP_7&0xFF] = SDLK_KP7;
1047 MISC_keymap[XK_KP_8&0xFF] = SDLK_KP8;
1048 MISC_keymap[XK_KP_9&0xFF] = SDLK_KP9;
1049 MISC_keymap[XK_KP_Insert&0xFF] = SDLK_KP0;
1050 MISC_keymap[XK_KP_End&0xFF] = SDLK_KP1;
1051 MISC_keymap[XK_KP_Down&0xFF] = SDLK_KP2;
1052 MISC_keymap[XK_KP_Page_Down&0xFF] = SDLK_KP3;
1053 MISC_keymap[XK_KP_Left&0xFF] = SDLK_KP4;
1054 MISC_keymap[XK_KP_Begin&0xFF] = SDLK_KP5;
1055 MISC_keymap[XK_KP_Right&0xFF] = SDLK_KP6;
1056 MISC_keymap[XK_KP_Home&0xFF] = SDLK_KP7;
1057 MISC_keymap[XK_KP_Up&0xFF] = SDLK_KP8;
1058 MISC_keymap[XK_KP_Page_Up&0xFF] = SDLK_KP9;
1059 MISC_keymap[XK_KP_Delete&0xFF] = SDLK_KP_PERIOD;
1060 MISC_keymap[XK_KP_Decimal&0xFF] = SDLK_KP_PERIOD;
1061 MISC_keymap[XK_KP_Divide&0xFF] = SDLK_KP_DIVIDE;
1062 MISC_keymap[XK_KP_Multiply&0xFF] = SDLK_KP_MULTIPLY;
1063 MISC_keymap[XK_KP_Subtract&0xFF] = SDLK_KP_MINUS;
1064 MISC_keymap[XK_KP_Add&0xFF] = SDLK_KP_PLUS;
1065 MISC_keymap[XK_KP_Enter&0xFF] = SDLK_KP_ENTER;
1066 MISC_keymap[XK_KP_Equal&0xFF] = SDLK_KP_EQUALS;
1067
1068 MISC_keymap[XK_Up&0xFF] = SDLK_UP;
1069 MISC_keymap[XK_Down&0xFF] = SDLK_DOWN;
1070 MISC_keymap[XK_Right&0xFF] = SDLK_RIGHT;
1071 MISC_keymap[XK_Left&0xFF] = SDLK_LEFT;
1072 MISC_keymap[XK_Insert&0xFF] = SDLK_INSERT;
1073 MISC_keymap[XK_Home&0xFF] = SDLK_HOME;
1074 MISC_keymap[XK_End&0xFF] = SDLK_END;
1075 MISC_keymap[XK_Page_Up&0xFF] = SDLK_PAGEUP;
1076 MISC_keymap[XK_Page_Down&0xFF] = SDLK_PAGEDOWN;
1077
1078 MISC_keymap[XK_F1&0xFF] = SDLK_F1;
1079 MISC_keymap[XK_F2&0xFF] = SDLK_F2;
1080 MISC_keymap[XK_F3&0xFF] = SDLK_F3;
1081 MISC_keymap[XK_F4&0xFF] = SDLK_F4;
1082 MISC_keymap[XK_F5&0xFF] = SDLK_F5;
1083 MISC_keymap[XK_F6&0xFF] = SDLK_F6;
1084 MISC_keymap[XK_F7&0xFF] = SDLK_F7;
1085 MISC_keymap[XK_F8&0xFF] = SDLK_F8;
1086 MISC_keymap[XK_F9&0xFF] = SDLK_F9;
1087 MISC_keymap[XK_F10&0xFF] = SDLK_F10;
1088 MISC_keymap[XK_F11&0xFF] = SDLK_F11;
1089 MISC_keymap[XK_F12&0xFF] = SDLK_F12;
1090 MISC_keymap[XK_F13&0xFF] = SDLK_F13;
1091 MISC_keymap[XK_F14&0xFF] = SDLK_F14;
1092 MISC_keymap[XK_F15&0xFF] = SDLK_F15;
1093
1094 MISC_keymap[XK_Num_Lock&0xFF] = SDLK_NUMLOCK;
1095 MISC_keymap[XK_Caps_Lock&0xFF] = SDLK_CAPSLOCK;
1096 MISC_keymap[XK_Scroll_Lock&0xFF] = SDLK_SCROLLOCK;
1097 MISC_keymap[XK_Shift_R&0xFF] = SDLK_RSHIFT;
1098 MISC_keymap[XK_Shift_L&0xFF] = SDLK_LSHIFT;
1099 MISC_keymap[XK_Control_R&0xFF] = SDLK_RCTRL;
1100 MISC_keymap[XK_Control_L&0xFF] = SDLK_LCTRL;
1101 MISC_keymap[XK_Alt_R&0xFF] = SDLK_RALT;
1102 MISC_keymap[XK_Alt_L&0xFF] = SDLK_LALT;
1103 MISC_keymap[XK_Meta_R&0xFF] = SDLK_RMETA;
1104 MISC_keymap[XK_Meta_L&0xFF] = SDLK_LMETA;
1105 MISC_keymap[XK_Super_L&0xFF] = SDLK_LSUPER; /* Left "Windows" */
1106 MISC_keymap[XK_Super_R&0xFF] = SDLK_RSUPER; /* Right "Windows */
1107 MISC_keymap[XK_Mode_switch&0xFF] = SDLK_MODE; /* "Alt Gr" key */
1108 MISC_keymap[XK_Multi_key&0xFF] = SDLK_COMPOSE; /* Multi-key compose */
1109
1110 MISC_keymap[XK_Help&0xFF] = SDLK_HELP;
1111 MISC_keymap[XK_Print&0xFF] = SDLK_PRINT;
1112 MISC_keymap[XK_Sys_Req&0xFF] = SDLK_SYSREQ;
1113 MISC_keymap[XK_Break&0xFF] = SDLK_BREAK;
1114 MISC_keymap[XK_Menu&0xFF] = SDLK_MENU;
1115 MISC_keymap[XK_Hyper_R&0xFF] = SDLK_MENU; /* Windows "Menu" key */
1116}
1117
1118/* Get the translated SDL virtual keysym */
1119SDLKey X11_TranslateKeycode(Display *display, KeyCode kc)
1120{
1121 KeySym xsym;
1122 SDLKey key;
1123
1124 xsym = XKeycodeToKeysym(display, kc, 0);
1125#ifdef DEBUG_KEYS
1126 fprintf(stderr, "Translating key code %d -> 0x%.4x\n", kc, xsym);
1127#endif
1128 key = SDLK_UNKNOWN;
1129 if ( xsym ) {
1130 switch (xsym>>8) {
1131 case 0x1005FF:
1132#ifdef SunXK_F36
1133 if ( xsym == SunXK_F36 )
1134 key = SDLK_F11;
1135#endif
1136#ifdef SunXK_F37
1137 if ( xsym == SunXK_F37 )
1138 key = SDLK_F12;
1139#endif
1140 break;
1141 case 0x00: /* Latin 1 */
1142 key = (SDLKey)(xsym & 0xFF);
1143 break;
1144 case 0x01: /* Latin 2 */
1145 case 0x02: /* Latin 3 */
1146 case 0x03: /* Latin 4 */
1147 case 0x04: /* Katakana */
1148 case 0x05: /* Arabic */
1149 case 0x06: /* Cyrillic */
1150 case 0x07: /* Greek */
1151 case 0x08: /* Technical */
1152 case 0x0A: /* Publishing */
1153 case 0x0C: /* Hebrew */
1154 case 0x0D: /* Thai */
1155 /* These are wrong, but it's better than nothing */
1156 key = (SDLKey)(xsym & 0xFF);
1157 break;
1158 case 0xFE:
1159 key = ODD_keymap[xsym&0xFF];
1160 break;
1161 case 0xFF:
1162 key = MISC_keymap[xsym&0xFF];
1163 break;
1164 default:
1165 /*
1166 fprintf(stderr, "X11: Unhandled xsym, sym = 0x%04x\n",
1167 (unsigned int)xsym);
1168 */
1169 break;
1170 }
1171 } else {
1172 /* X11 doesn't know how to translate the key! */
1173 switch (kc) {
1174 /* Caution:
1175 These keycodes are from the Microsoft Keyboard
1176 */
1177 case 115:
1178 key = SDLK_LSUPER;
1179 break;
1180 case 116:
1181 key = SDLK_RSUPER;
1182 break;
1183 case 117:
1184 key = SDLK_MENU;
1185 break;
1186 default:
1187 /*
1188 * no point in an error message; happens for
1189 * several keys when we get a keymap notify
1190 */
1191 break;
1192 }
1193 }
1194 return key;
1195}
1196
1197/* X11 modifier masks for various keys */
1198static unsigned meta_l_mask, meta_r_mask, alt_l_mask, alt_r_mask;
1199static unsigned num_mask, mode_switch_mask;
1200
1201static void get_modifier_masks(Display *display)
1202{
1203 static unsigned got_masks;
1204 int i, j;
1205 XModifierKeymap *xmods;
1206 unsigned n;
1207
1208 if(got_masks)
1209 return;
1210
1211 xmods = XGetModifierMapping(display);
1212 n = xmods->max_keypermod;
1213 for(i = 3; i < 8; i++) {
1214 for(j = 0; j < n; j++) {
1215 KeyCode kc = xmods->modifiermap[i * n + j];
1216 KeySym ks = XKeycodeToKeysym(display, kc, 0);
1217 unsigned mask = 1 << i;
1218 switch(ks) {
1219 case XK_Num_Lock:
1220 num_mask = mask; break;
1221 case XK_Alt_L:
1222 alt_l_mask = mask; break;
1223 case XK_Alt_R:
1224 alt_r_mask = mask; break;
1225 case XK_Meta_L:
1226 meta_l_mask = mask; break;
1227 case XK_Meta_R:
1228 meta_r_mask = mask; break;
1229 case XK_Mode_switch:
1230 mode_switch_mask = mask; break;
1231 }
1232 }
1233 }
1234 XFreeModifiermap(xmods);
1235 got_masks = 1;
1236}
1237
1238
1239/*
1240 * This function is semi-official; it is not officially exported and should
1241 * not be considered part of the SDL API, but may be used by client code
1242 * that *really* needs it (including legacy code).
1243 * It is slow, though, and should be avoided if possible.
1244 *
1245 * Note that it isn't completely accurate either; in particular, multi-key
1246 * sequences (dead accents, compose key sequences) will not work since the
1247 * state has been irrevocably lost.
1248 */
1249Uint16 X11_KeyToUnicode(SDLKey keysym, SDLMod modifiers)
1250{
1251 struct SDL_VideoDevice *this = current_video;
1252 char keybuf[32];
1253 int i;
1254 KeySym xsym = 0;
1255 XKeyEvent xkey;
1256 Uint16 unicode;
1257
1258 if ( !this || !SDL_Display ) {
1259 return 0;
1260 }
1261
1262 SDL_memset(&xkey, 0, sizeof(xkey));
1263 xkey.display = SDL_Display;
1264
1265 xsym = keysym; /* last resort if not found */
1266 for (i = 0; i < 256; ++i) {
1267 if ( MISC_keymap[i] == keysym ) {
1268 xsym = 0xFF00 | i;
1269 break;
1270 } else if ( ODD_keymap[i] == keysym ) {
1271 xsym = 0xFE00 | i;
1272 break;
1273 }
1274 }
1275
1276 xkey.keycode = XKeysymToKeycode(xkey.display, xsym);
1277
1278 get_modifier_masks(SDL_Display);
1279 if(modifiers & KMOD_SHIFT)
1280 xkey.state |= ShiftMask;
1281 if(modifiers & KMOD_CAPS)
1282 xkey.state |= LockMask;
1283 if(modifiers & KMOD_CTRL)
1284 xkey.state |= ControlMask;
1285 if(modifiers & KMOD_MODE)
1286 xkey.state |= mode_switch_mask;
1287 if(modifiers & KMOD_LALT)
1288 xkey.state |= alt_l_mask;
1289 if(modifiers & KMOD_RALT)
1290 xkey.state |= alt_r_mask;
1291 if(modifiers & KMOD_LMETA)
1292 xkey.state |= meta_l_mask;
1293 if(modifiers & KMOD_RMETA)
1294 xkey.state |= meta_r_mask;
1295 if(modifiers & KMOD_NUM)
1296 xkey.state |= num_mask;
1297
1298 unicode = 0;
1299 if ( XLookupString(&xkey, keybuf, sizeof(keybuf), NULL, NULL) )
1300 unicode = (unsigned char)keybuf[0];
1301 return(unicode);
1302}
1303
1304
1305/*
1306 * Called when focus is regained, to read the keyboard state and generate
1307 * synthetic keypress/release events.
1308 * key_vec is a bit vector of keycodes (256 bits)
1309 */
1310void X11_SetKeyboardState(Display *display, const char *key_vec)
1311{
1312 char keys_return[32];
1313 int i;
1314 Uint8 *kstate = SDL_GetKeyState(NULL);
1315 SDLMod modstate;
1316 Window junk_window;
1317 int x, y;
1318 unsigned int mask;
1319
1320 /* The first time the window is mapped, we initialize key state */
1321 if ( ! key_vec ) {
1322 XQueryKeymap(display, keys_return);
1323 key_vec = keys_return;
1324 }
1325
1326 /* Get the keyboard modifier state */
1327 modstate = 0;
1328 get_modifier_masks(display);
1329 if ( XQueryPointer(display, DefaultRootWindow(display),
1330 &junk_window, &junk_window, &x, &y, &x, &y, &mask) ) {
1331 if ( mask & LockMask ) {
1332 modstate |= KMOD_CAPS;
1333 }
1334 if ( mask & mode_switch_mask ) {
1335 modstate |= KMOD_MODE;
1336 }
1337 if ( mask & num_mask ) {
1338 modstate |= KMOD_NUM;
1339 }
1340 }
1341
1342 /* Zero the new keyboard state and generate it */
1343 SDL_memset(kstate, 0, SDLK_LAST);
1344 /*
1345 * An obvious optimisation is to check entire longwords at a time in
1346 * both loops, but we can't be sure the arrays are aligned so it's not
1347 * worth the extra complexity
1348 */
1349 for ( i = 0; i < 32; i++ ) {
1350 int j;
1351 if ( !key_vec[i] )
1352 continue;
1353 for ( j = 0; j < 8; j++ ) {
1354 if ( key_vec[i] & (1 << j) ) {
1355 SDLKey key;
1356 KeyCode kc = (i << 3 | j);
1357 key = X11_TranslateKeycode(display, kc);
1358 if ( key == SDLK_UNKNOWN ) {
1359 continue;
1360 }
1361 kstate[key] = SDL_PRESSED;
1362 switch (key) {
1363 case SDLK_LSHIFT:
1364 modstate |= KMOD_LSHIFT;
1365 break;
1366 case SDLK_RSHIFT:
1367 modstate |= KMOD_RSHIFT;
1368 break;
1369 case SDLK_LCTRL:
1370 modstate |= KMOD_LCTRL;
1371 break;
1372 case SDLK_RCTRL:
1373 modstate |= KMOD_RCTRL;
1374 break;
1375 case SDLK_LALT:
1376 modstate |= KMOD_LALT;
1377 break;
1378 case SDLK_RALT:
1379 modstate |= KMOD_RALT;
1380 break;
1381 case SDLK_LMETA:
1382 modstate |= KMOD_LMETA;
1383 break;
1384 case SDLK_RMETA:
1385 modstate |= KMOD_RMETA;
1386 break;
1387 default:
1388 break;
1389 }
1390 }
1391 }
1392 }
1393
1394 /* Hack - set toggle key state */
1395 if ( modstate & KMOD_CAPS ) {
1396 kstate[SDLK_CAPSLOCK] = SDL_PRESSED;
1397 } else {
1398 kstate[SDLK_CAPSLOCK] = SDL_RELEASED;
1399 }
1400 if ( modstate & KMOD_NUM ) {
1401 kstate[SDLK_NUMLOCK] = SDL_PRESSED;
1402 } else {
1403 kstate[SDLK_NUMLOCK] = SDL_RELEASED;
1404 }
1405
1406 /* Set the final modifier state */
1407 SDL_SetModState(modstate);
1408}
1409
1410void X11_InitOSKeymap(_THIS)
1411{
1412 X11_InitKeymap();
1413}
1414
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11events_c.h b/apps/plugins/sdl/src/video/x11/SDL_x11events_c.h
deleted file mode 100644
index fe26d9c263..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11events_c.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_x11video.h"
25
26/* Functions to be exported */
27extern void X11_InitOSKeymap(_THIS);
28extern void X11_PumpEvents(_THIS);
29extern void X11_SetKeyboardState(Display *display, const char *key_vec);
30
31/* Variables to be exported */
32extern int X11_PendingConfigureNotifyWidth;
33extern int X11_PendingConfigureNotifyHeight;
34
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11gamma.c b/apps/plugins/sdl/src/video/x11/SDL_x11gamma.c
deleted file mode 100644
index c6afbda11c..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11gamma.c
+++ /dev/null
@@ -1,142 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL.h"
25#include "SDL_events.h"
26#include "../../events/SDL_events_c.h"
27#include "SDL_x11video.h"
28
29/* From the X server sources... */
30#define MAX_GAMMA 10.0
31#define MIN_GAMMA (1.0/MAX_GAMMA)
32
33static int X11_SetGammaNoLock(_THIS, float red, float green, float blue)
34{
35#if SDL_VIDEO_DRIVER_X11_VIDMODE
36 if (use_vidmode >= 200) {
37 SDL_NAME(XF86VidModeGamma) gamma;
38 Bool succeeded;
39
40 /* Clamp the gamma values */
41 if ( red < MIN_GAMMA ) {
42 gamma.red = MIN_GAMMA;
43 } else
44 if ( red > MAX_GAMMA ) {
45 gamma.red = MAX_GAMMA;
46 } else {
47 gamma.red = red;
48 }
49 if ( green < MIN_GAMMA ) {
50 gamma.green = MIN_GAMMA;
51 } else
52 if ( green > MAX_GAMMA ) {
53 gamma.green = MAX_GAMMA;
54 } else {
55 gamma.green = green;
56 }
57 if ( blue < MIN_GAMMA ) {
58 gamma.blue = MIN_GAMMA;
59 } else
60 if ( blue > MAX_GAMMA ) {
61 gamma.blue = MAX_GAMMA;
62 } else {
63 gamma.blue = blue;
64 }
65 if ( SDL_GetAppState() & SDL_APPACTIVE ) {
66 succeeded = SDL_NAME(XF86VidModeSetGamma)(SDL_Display, SDL_Screen, &gamma);
67 XSync(SDL_Display, False);
68 } else {
69 gamma_saved[0] = gamma.red;
70 gamma_saved[1] = gamma.green;
71 gamma_saved[2] = gamma.blue;
72 succeeded = True;
73 }
74 if ( succeeded ) {
75 ++gamma_changed;
76 }
77 return succeeded ? 0 : -1;
78 }
79#endif
80 SDL_SetError("Gamma correction not supported");
81 return -1;
82}
83int X11_SetVidModeGamma(_THIS, float red, float green, float blue)
84{
85 int result;
86
87 SDL_Lock_EventThread();
88 result = X11_SetGammaNoLock(this, red, green, blue);
89 SDL_Unlock_EventThread();
90
91 return(result);
92}
93
94static int X11_GetGammaNoLock(_THIS, float *red, float *green, float *blue)
95{
96#if SDL_VIDEO_DRIVER_X11_VIDMODE
97 if (use_vidmode >= 200) {
98 SDL_NAME(XF86VidModeGamma) gamma;
99 if (SDL_NAME(XF86VidModeGetGamma)(SDL_Display, SDL_Screen, &gamma)) {
100 *red = gamma.red;
101 *green = gamma.green;
102 *blue = gamma.blue;
103 return 0;
104 }
105 return -1;
106 }
107#endif
108 return -1;
109}
110int X11_GetVidModeGamma(_THIS, float *red, float *green, float *blue)
111{
112 int result;
113
114 SDL_Lock_EventThread();
115 result = X11_GetGammaNoLock(this, red, green, blue);
116 SDL_Unlock_EventThread();
117
118 return(result);
119}
120
121void X11_SaveVidModeGamma(_THIS)
122{
123 /* Try to save the current gamma, otherwise disable gamma control */
124 if ( X11_GetGammaNoLock(this,
125 &gamma_saved[0], &gamma_saved[1], &gamma_saved[2]) < 0 ) {
126 this->SetGamma = 0;
127 this->GetGamma = 0;
128 }
129 gamma_changed = 0;
130}
131void X11_SwapVidModeGamma(_THIS)
132{
133 float new_gamma[3];
134
135 if ( gamma_changed ) {
136 new_gamma[0] = gamma_saved[0];
137 new_gamma[1] = gamma_saved[1];
138 new_gamma[2] = gamma_saved[2];
139 X11_GetGammaNoLock(this, &gamma_saved[0], &gamma_saved[1], &gamma_saved[2]);
140 X11_SetGammaNoLock(this, new_gamma[0], new_gamma[1], new_gamma[2]);
141 }
142}
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11gamma_c.h b/apps/plugins/sdl/src/video/x11/SDL_x11gamma_c.h
deleted file mode 100644
index c46350fd22..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11gamma_c.h
+++ /dev/null
@@ -1,32 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_x11gamma_h
25#define _SDL_x11gamma_h
26
27extern int X11_SetVidModeGamma(_THIS, float red, float green, float blue);
28extern int X11_GetVidModeGamma(_THIS, float *red, float *green, float *blue);
29extern void X11_SaveVidModeGamma(_THIS);
30extern void X11_SwapVidModeGamma(_THIS);
31
32#endif
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11gl.c b/apps/plugins/sdl/src/video/x11/SDL_x11gl.c
deleted file mode 100644
index aa5297b674..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11gl.c
+++ /dev/null
@@ -1,577 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_x11video.h"
25#include "../../events/SDL_events_c.h"
26#include "SDL_x11dga_c.h"
27#include "SDL_x11gl_c.h"
28
29#if defined(__IRIX__)
30/* IRIX doesn't have a GL library versioning system */
31#define DEFAULT_OPENGL "libGL.so"
32#elif defined(__MACOSX__)
33#define DEFAULT_OPENGL "/usr/X11R6/lib/libGL.1.dylib"
34#elif defined(__QNXNTO__)
35#define DEFAULT_OPENGL "libGL.so.3"
36#elif defined(__OpenBSD__)
37#define DEFAULT_OPENGL "libGL.so.4.0"
38#else
39#define DEFAULT_OPENGL "libGL.so.1"
40#endif
41
42#ifndef GLX_ARB_multisample
43#define GLX_ARB_multisample
44#define GLX_SAMPLE_BUFFERS_ARB 100000
45#define GLX_SAMPLES_ARB 100001
46#endif
47
48/* GLX_EXT_visual_rating stuff that might not be in the system headers... */
49#ifndef GLX_VISUAL_CAVEAT_EXT
50#define GLX_VISUAL_CAVEAT_EXT 0x20
51#endif
52#ifndef GLX_NONE_EXT
53#define GLX_NONE_EXT 0x8000
54#endif
55#ifndef GLX_SLOW_VISUAL_EXT
56#define GLX_SLOW_VISUAL_EXT 0x8001
57#endif
58#ifndef GLX_NON_CONFORMANT_VISUAL_EXT
59#define GLX_NON_CONFORMANT_VISUAL_EXT 0x800D
60#endif
61
62
63#if SDL_VIDEO_OPENGL_GLX
64static int glXExtensionSupported(_THIS, const char *extension)
65{
66 const char *extensions;
67 const char *start;
68 const char *where, *terminator;
69
70 /* Extension names should not have spaces. */
71 where = SDL_strchr(extension, ' ');
72 if ( where || *extension == '\0' ) {
73 return 0;
74 }
75
76 extensions = this->gl_data->glXQueryExtensionsString(GFX_Display,SDL_Screen);
77 /* It takes a bit of care to be fool-proof about parsing the
78 * OpenGL extensions string. Don't be fooled by sub-strings, etc.
79 */
80
81 /* http://bugs.debian.org/537487 */
82 if (extensions == NULL) {
83 return 0;
84 }
85
86 start = extensions;
87
88 for (;;) {
89 where = SDL_strstr(start, extension);
90 if (!where) break;
91
92 terminator = where + strlen(extension);
93 if (where == start || *(where - 1) == ' ')
94 if (*terminator == ' ' || *terminator == '\0') return 1;
95
96 start = terminator;
97 }
98 return 0;
99}
100#endif /* SDL_VIDEO_OPENGL_GLX */
101
102XVisualInfo *X11_GL_GetVisual(_THIS)
103{
104#if SDL_VIDEO_OPENGL_GLX
105 /* 64 seems nice. */
106 int attribs[64];
107 int i;
108
109 /* load the gl driver from a default path */
110 if ( ! this->gl_config.driver_loaded ) {
111 /* no driver has been loaded, use default (ourselves) */
112 if ( X11_GL_LoadLibrary(this, NULL) < 0 ) {
113 return NULL;
114 }
115 }
116
117 /* See if we already have a window which we must use */
118 if ( SDL_windowid ) {
119 XWindowAttributes a;
120 XVisualInfo vi_in;
121 int out_count;
122
123 XGetWindowAttributes(SDL_Display, SDL_Window, &a);
124 vi_in.screen = SDL_Screen;
125 vi_in.visualid = XVisualIDFromVisual(a.visual);
126 glx_visualinfo = XGetVisualInfo(SDL_Display,
127 VisualScreenMask|VisualIDMask, &vi_in, &out_count);
128 return glx_visualinfo;
129 }
130
131 /* Setup our GLX attributes according to the gl_config. */
132 i = 0;
133 attribs[i++] = GLX_RGBA;
134 attribs[i++] = GLX_RED_SIZE;
135 attribs[i++] = this->gl_config.red_size;
136 attribs[i++] = GLX_GREEN_SIZE;
137 attribs[i++] = this->gl_config.green_size;
138 attribs[i++] = GLX_BLUE_SIZE;
139 attribs[i++] = this->gl_config.blue_size;
140
141 if( this->gl_config.alpha_size ) {
142 attribs[i++] = GLX_ALPHA_SIZE;
143 attribs[i++] = this->gl_config.alpha_size;
144 }
145
146 if( this->gl_config.double_buffer ) {
147 attribs[i++] = GLX_DOUBLEBUFFER;
148 }
149
150 attribs[i++] = GLX_DEPTH_SIZE;
151 attribs[i++] = this->gl_config.depth_size;
152
153 if( this->gl_config.stencil_size ) {
154 attribs[i++] = GLX_STENCIL_SIZE;
155 attribs[i++] = this->gl_config.stencil_size;
156 }
157
158 if( this->gl_config.accum_red_size ) {
159 attribs[i++] = GLX_ACCUM_RED_SIZE;
160 attribs[i++] = this->gl_config.accum_red_size;
161 }
162
163 if( this->gl_config.accum_green_size ) {
164 attribs[i++] = GLX_ACCUM_GREEN_SIZE;
165 attribs[i++] = this->gl_config.accum_green_size;
166 }
167
168 if( this->gl_config.accum_blue_size ) {
169 attribs[i++] = GLX_ACCUM_BLUE_SIZE;
170 attribs[i++] = this->gl_config.accum_blue_size;
171 }
172
173 if( this->gl_config.accum_alpha_size ) {
174 attribs[i++] = GLX_ACCUM_ALPHA_SIZE;
175 attribs[i++] = this->gl_config.accum_alpha_size;
176 }
177
178 if( this->gl_config.stereo ) {
179 attribs[i++] = GLX_STEREO;
180 }
181
182 if( this->gl_config.multisamplebuffers ) {
183 attribs[i++] = GLX_SAMPLE_BUFFERS_ARB;
184 attribs[i++] = this->gl_config.multisamplebuffers;
185 }
186
187 if( this->gl_config.multisamplesamples ) {
188 attribs[i++] = GLX_SAMPLES_ARB;
189 attribs[i++] = this->gl_config.multisamplesamples;
190 }
191
192 if( this->gl_config.accelerated >= 0 &&
193 glXExtensionSupported(this, "GLX_EXT_visual_rating") ) {
194 attribs[i++] = GLX_VISUAL_CAVEAT_EXT;
195 attribs[i++] = GLX_NONE_EXT;
196 }
197
198#ifdef GLX_DIRECT_COLOR /* Try for a DirectColor visual for gamma support */
199 if ( !SDL_getenv("SDL_VIDEO_X11_NODIRECTCOLOR") ) {
200 attribs[i++] = GLX_X_VISUAL_TYPE;
201 attribs[i++] = GLX_DIRECT_COLOR;
202 }
203#endif
204 attribs[i++] = None;
205
206 glx_visualinfo = this->gl_data->glXChooseVisual(GFX_Display,
207 SDL_Screen, attribs);
208#ifdef GLX_DIRECT_COLOR
209 if( !glx_visualinfo && !SDL_getenv("SDL_VIDEO_X11_NODIRECTCOLOR") ) { /* No DirectColor visual? Try again.. */
210 attribs[i-3] = None;
211 glx_visualinfo = this->gl_data->glXChooseVisual(GFX_Display,
212 SDL_Screen, attribs);
213 }
214#endif
215 if( !glx_visualinfo ) {
216 SDL_SetError( "Couldn't find matching GLX visual");
217 return NULL;
218 }
219/*
220 printf("Found GLX visual 0x%x\n", glx_visualinfo->visualid);
221*/
222 return glx_visualinfo;
223#else
224 SDL_SetError("X11 driver not configured with OpenGL");
225 return NULL;
226#endif
227}
228
229int X11_GL_CreateWindow(_THIS, int w, int h)
230{
231 int retval;
232#if SDL_VIDEO_OPENGL_GLX
233 XSetWindowAttributes attributes;
234 unsigned long mask;
235 unsigned long black;
236
237 black = (glx_visualinfo->visual == DefaultVisual(SDL_Display,
238 SDL_Screen))
239 ? BlackPixel(SDL_Display, SDL_Screen) : 0;
240 attributes.background_pixel = black;
241 attributes.border_pixel = black;
242 attributes.colormap = SDL_XColorMap;
243 mask = CWBackPixel | CWBorderPixel | CWColormap;
244
245 SDL_Window = XCreateWindow(SDL_Display, WMwindow,
246 0, 0, w, h, 0, glx_visualinfo->depth,
247 InputOutput, glx_visualinfo->visual,
248 mask, &attributes);
249 if ( !SDL_Window ) {
250 SDL_SetError("Could not create window");
251 return -1;
252 }
253 retval = 0;
254#else
255 SDL_SetError("X11 driver not configured with OpenGL");
256 retval = -1;
257#endif
258 return(retval);
259}
260
261int X11_GL_CreateContext(_THIS)
262{
263 int retval;
264#if SDL_VIDEO_OPENGL_GLX
265
266 /* We do this to create a clean separation between X and GLX errors. */
267 XSync( SDL_Display, False );
268 glx_context = this->gl_data->glXCreateContext(GFX_Display,
269 glx_visualinfo, NULL, True);
270 XSync( GFX_Display, False );
271
272 if ( glx_context == NULL ) {
273 SDL_SetError("Could not create GL context");
274 return(-1);
275 }
276 if ( X11_GL_MakeCurrent(this) < 0 ) {
277 return(-1);
278 }
279 gl_active = 1;
280
281 if ( !glXExtensionSupported(this, "GLX_SGI_swap_control") ) {
282 this->gl_data->glXSwapIntervalSGI = NULL;
283 }
284 if ( !glXExtensionSupported(this, "GLX_MESA_swap_control") ) {
285 this->gl_data->glXSwapIntervalMESA = NULL;
286 }
287 if ( !glXExtensionSupported(this, "GLX_EXT_swap_control") ) {
288 this->gl_data->glXSwapIntervalEXT = NULL;
289 }
290
291 if ( this->gl_config.swap_control >= 0 ) {
292 int rc = -1;
293 if ( this->gl_data->glXSwapIntervalEXT ) {
294 rc = this->gl_data->glXSwapIntervalEXT(GFX_Display, SDL_Window,
295 this->gl_config.swap_control);
296 } else if ( this->gl_data->glXSwapIntervalMESA ) {
297 rc = this->gl_data->glXSwapIntervalMESA(this->gl_config.swap_control);
298 } else if ( this->gl_data->glXSwapIntervalSGI ) {
299 rc = this->gl_data->glXSwapIntervalSGI(this->gl_config.swap_control);
300 }
301 if (rc == 0) {
302 this->gl_data->swap_interval = this->gl_config.swap_control;
303 }
304 }
305#else
306 SDL_SetError("X11 driver not configured with OpenGL");
307#endif
308 if ( gl_active ) {
309 retval = 0;
310 } else {
311 retval = -1;
312 }
313 return(retval);
314}
315
316void X11_GL_Shutdown(_THIS)
317{
318#if SDL_VIDEO_OPENGL_GLX
319 /* Clean up OpenGL */
320 if( glx_context ) {
321 this->gl_data->glXMakeCurrent(GFX_Display, None, NULL);
322
323 if (glx_context != NULL)
324 this->gl_data->glXDestroyContext(GFX_Display, glx_context);
325
326 glx_context = NULL;
327 }
328 gl_active = 0;
329#endif /* SDL_VIDEO_OPENGL_GLX */
330}
331
332#if SDL_VIDEO_OPENGL_GLX
333
334/* Make the current context active */
335int X11_GL_MakeCurrent(_THIS)
336{
337 int retval;
338
339 retval = 0;
340 if ( ! this->gl_data->glXMakeCurrent(GFX_Display,
341 SDL_Window, glx_context) ) {
342 SDL_SetError("Unable to make GL context current");
343 retval = -1;
344 }
345 XSync( GFX_Display, False );
346
347 /* More Voodoo X server workarounds... Grr... */
348 SDL_Lock_EventThread();
349 X11_CheckDGAMouse(this);
350 SDL_Unlock_EventThread();
351
352 return(retval);
353}
354
355/* Get attribute data from glX. */
356int X11_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value)
357{
358 int retval = -1;
359 int unsupported = 0;
360 int glx_attrib = None;
361
362 switch( attrib ) {
363 case SDL_GL_RED_SIZE:
364 glx_attrib = GLX_RED_SIZE;
365 break;
366 case SDL_GL_GREEN_SIZE:
367 glx_attrib = GLX_GREEN_SIZE;
368 break;
369 case SDL_GL_BLUE_SIZE:
370 glx_attrib = GLX_BLUE_SIZE;
371 break;
372 case SDL_GL_ALPHA_SIZE:
373 glx_attrib = GLX_ALPHA_SIZE;
374 break;
375 case SDL_GL_DOUBLEBUFFER:
376 glx_attrib = GLX_DOUBLEBUFFER;
377 break;
378 case SDL_GL_BUFFER_SIZE:
379 glx_attrib = GLX_BUFFER_SIZE;
380 break;
381 case SDL_GL_DEPTH_SIZE:
382 glx_attrib = GLX_DEPTH_SIZE;
383 break;
384 case SDL_GL_STENCIL_SIZE:
385 glx_attrib = GLX_STENCIL_SIZE;
386 break;
387 case SDL_GL_ACCUM_RED_SIZE:
388 glx_attrib = GLX_ACCUM_RED_SIZE;
389 break;
390 case SDL_GL_ACCUM_GREEN_SIZE:
391 glx_attrib = GLX_ACCUM_GREEN_SIZE;
392 break;
393 case SDL_GL_ACCUM_BLUE_SIZE:
394 glx_attrib = GLX_ACCUM_BLUE_SIZE;
395 break;
396 case SDL_GL_ACCUM_ALPHA_SIZE:
397 glx_attrib = GLX_ACCUM_ALPHA_SIZE;
398 break;
399 case SDL_GL_STEREO:
400 glx_attrib = GLX_STEREO;
401 break;
402 case SDL_GL_MULTISAMPLEBUFFERS:
403 glx_attrib = GLX_SAMPLE_BUFFERS_ARB;
404 break;
405 case SDL_GL_MULTISAMPLESAMPLES:
406 glx_attrib = GLX_SAMPLES_ARB;
407 break;
408 case SDL_GL_ACCELERATED_VISUAL:
409 if ( glXExtensionSupported(this, "GLX_EXT_visual_rating") ) {
410 glx_attrib = GLX_VISUAL_CAVEAT_EXT;
411 retval = this->gl_data->glXGetConfig(GFX_Display, glx_visualinfo, glx_attrib, value);
412 if ( *value == GLX_SLOW_VISUAL_EXT ) {
413 *value = SDL_FALSE;
414 } else {
415 *value = SDL_TRUE;
416 }
417 return retval;
418 } else {
419 unsupported = 1;
420 }
421 break;
422 case SDL_GL_SWAP_CONTROL:
423 if ( ( this->gl_data->glXSwapIntervalEXT ) ||
424 ( this->gl_data->glXSwapIntervalMESA ) ||
425 ( this->gl_data->glXSwapIntervalSGI ) ) {
426 *value = this->gl_data->swap_interval;
427 return 0;
428 } else {
429 unsupported = 1;
430 }
431 break;
432 default:
433 unsupported = 1;
434 break;
435 }
436
437 if (unsupported) {
438 SDL_SetError("OpenGL attribute is unsupported on this system");
439 } else {
440 retval = this->gl_data->glXGetConfig(GFX_Display, glx_visualinfo, glx_attrib, value);
441 }
442 return retval;
443}
444
445void X11_GL_SwapBuffers(_THIS)
446{
447 this->gl_data->glXSwapBuffers(GFX_Display, SDL_Window);
448}
449
450#endif /* SDL_VIDEO_OPENGL_GLX */
451
452#define OPENGL_REQUIRS_DLOPEN
453#if defined(OPENGL_REQUIRS_DLOPEN) && defined(SDL_LOADSO_DLOPEN)
454#include <dlfcn.h>
455#define GL_LoadObject(X) dlopen(X, (RTLD_NOW|RTLD_GLOBAL))
456#define GL_LoadFunction dlsym
457#define GL_UnloadObject dlclose
458#else
459#define GL_LoadObject SDL_LoadObject
460#define GL_LoadFunction SDL_LoadFunction
461#define GL_UnloadObject SDL_UnloadObject
462#endif
463
464void X11_GL_UnloadLibrary(_THIS)
465{
466#if SDL_VIDEO_OPENGL_GLX
467 if ( this->gl_config.driver_loaded ) {
468
469 GL_UnloadObject(this->gl_config.dll_handle);
470
471 this->gl_data->glXGetProcAddress = NULL;
472 this->gl_data->glXChooseVisual = NULL;
473 this->gl_data->glXCreateContext = NULL;
474 this->gl_data->glXDestroyContext = NULL;
475 this->gl_data->glXMakeCurrent = NULL;
476 this->gl_data->glXSwapBuffers = NULL;
477 this->gl_data->glXSwapIntervalSGI = NULL;
478 this->gl_data->glXSwapIntervalMESA = NULL;
479 this->gl_data->glXSwapIntervalEXT = NULL;
480
481 this->gl_config.dll_handle = NULL;
482 this->gl_config.driver_loaded = 0;
483 }
484#endif
485}
486
487#if SDL_VIDEO_OPENGL_GLX
488
489/* Passing a NULL path means load pointers from the application */
490int X11_GL_LoadLibrary(_THIS, const char* path)
491{
492 void* handle = NULL;
493
494 if ( gl_active ) {
495 SDL_SetError("OpenGL context already created");
496 return -1;
497 }
498
499 if ( path == NULL ) {
500 path = SDL_getenv("SDL_VIDEO_GL_DRIVER");
501 if ( path == NULL ) {
502 path = DEFAULT_OPENGL;
503 }
504 }
505
506 handle = GL_LoadObject(path);
507 if ( handle == NULL ) {
508#if defined(OPENGL_REQUIRS_DLOPEN) && defined(SDL_LOADSO_DLOPEN)
509 SDL_SetError("Failed loading %s", path);
510#else
511 /* SDL_LoadObject() will call SDL_SetError() for us. */
512#endif
513 return -1;
514 }
515
516 /* Unload the old driver and reset the pointers */
517 X11_GL_UnloadLibrary(this);
518
519 /* Save the handle for X11_GL_GetProcAddress() */
520 this->gl_config.dll_handle = handle;
521
522 /* Load new function pointers */
523 this->gl_data->glXGetProcAddress =
524 (void *(*)(const GLubyte *)) GL_LoadFunction(handle, "glXGetProcAddressARB");
525 this->gl_data->glXChooseVisual =
526 (XVisualInfo *(*)(Display *, int, int *)) X11_GL_GetProcAddress(this, "glXChooseVisual");
527 this->gl_data->glXCreateContext =
528 (GLXContext (*)(Display *, XVisualInfo *, GLXContext, int)) X11_GL_GetProcAddress(this, "glXCreateContext");
529 this->gl_data->glXDestroyContext =
530 (void (*)(Display *, GLXContext)) X11_GL_GetProcAddress(this, "glXDestroyContext");
531 this->gl_data->glXMakeCurrent =
532 (int (*)(Display *, GLXDrawable, GLXContext)) X11_GL_GetProcAddress(this, "glXMakeCurrent");
533 this->gl_data->glXSwapBuffers =
534 (void (*)(Display *, GLXDrawable)) X11_GL_GetProcAddress(this, "glXSwapBuffers");
535 this->gl_data->glXGetConfig =
536 (int (*)(Display *, XVisualInfo *, int, int *)) X11_GL_GetProcAddress(this, "glXGetConfig");
537 this->gl_data->glXQueryExtensionsString =
538 (const char *(*)(Display *, int)) X11_GL_GetProcAddress(this, "glXQueryExtensionsString");
539 this->gl_data->glXSwapIntervalSGI =
540 (int (*)(int)) X11_GL_GetProcAddress(this, "glXSwapIntervalSGI");
541 this->gl_data->glXSwapIntervalMESA =
542 (GLint (*)(unsigned)) X11_GL_GetProcAddress(this, "glXSwapIntervalMESA");
543 this->gl_data->glXSwapIntervalEXT =
544 (int (*)(Display*,GLXDrawable,int)) X11_GL_GetProcAddress(this, "glXSwapIntervalEXT");
545
546 if ( (this->gl_data->glXChooseVisual == NULL) ||
547 (this->gl_data->glXCreateContext == NULL) ||
548 (this->gl_data->glXDestroyContext == NULL) ||
549 (this->gl_data->glXMakeCurrent == NULL) ||
550 (this->gl_data->glXSwapBuffers == NULL) ||
551 (this->gl_data->glXGetConfig == NULL) ||
552 (this->gl_data->glXQueryExtensionsString == NULL)) {
553 GL_UnloadObject(this->gl_config.dll_handle);
554 this->gl_config.dll_handle = NULL;
555 SDL_SetError("Could not retrieve OpenGL functions");
556 return -1;
557 }
558
559 this->gl_config.driver_loaded = 1;
560 if ( path ) {
561 SDL_strlcpy(this->gl_config.driver_path, path,
562 SDL_arraysize(this->gl_config.driver_path));
563 } else {
564 *this->gl_config.driver_path = '\0';
565 }
566 return 0;
567}
568
569void *X11_GL_GetProcAddress(_THIS, const char* proc)
570{
571 if ( this->gl_data->glXGetProcAddress ) {
572 return this->gl_data->glXGetProcAddress((const GLubyte *)proc);
573 }
574 return GL_LoadFunction(this->gl_config.dll_handle, proc);
575}
576
577#endif /* SDL_VIDEO_OPENGL_GLX */
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11gl_c.h b/apps/plugins/sdl/src/video/x11/SDL_x11gl_c.h
deleted file mode 100644
index b4822cb3c0..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11gl_c.h
+++ /dev/null
@@ -1,99 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#if SDL_VIDEO_OPENGL_GLX
25#include <GL/glx.h>
26#include "SDL_loadso.h"
27#endif
28
29#include "../SDL_sysvideo.h"
30
31struct SDL_PrivateGLData {
32 int gl_active; /* to stop switching drivers while we have a valid context */
33
34#if SDL_VIDEO_OPENGL_GLX
35 GLXContext glx_context; /* Current GL context */
36 XVisualInfo* glx_visualinfo; /* XVisualInfo* returned by glXChooseVisual */
37
38 void * (*glXGetProcAddress)(const GLubyte *procName);
39
40 XVisualInfo* (*glXChooseVisual)
41 ( Display* dpy,
42 int screen,
43 int* attribList );
44
45 GLXContext (*glXCreateContext)
46 ( Display* dpy,
47 XVisualInfo* vis,
48 GLXContext shareList,
49 Bool direct );
50
51 void (*glXDestroyContext)
52 ( Display* dpy,
53 GLXContext ctx );
54
55 Bool (*glXMakeCurrent)
56 ( Display* dpy,
57 GLXDrawable drawable,
58 GLXContext ctx );
59
60 void (*glXSwapBuffers)
61 ( Display* dpy,
62 GLXDrawable drawable );
63
64 int (*glXGetConfig)
65 ( Display* dpy,
66 XVisualInfo* visual_info,
67 int attrib,
68 int* value );
69
70 const char *(*glXQueryExtensionsString)
71 ( Display* dpy,
72 int screen );
73
74 int (*glXSwapIntervalSGI) ( int interval );
75 GLint (*glXSwapIntervalMESA) ( unsigned interval );
76 int (*glXSwapIntervalEXT)( Display *dpy, GLXDrawable drw, int interval);
77 int swap_interval;
78#endif /* SDL_VIDEO_OPENGL_GLX */
79};
80
81/* Old variable names */
82#define gl_active (this->gl_data->gl_active)
83#define glx_context (this->gl_data->glx_context)
84#define glx_visualinfo (this->gl_data->glx_visualinfo)
85
86/* OpenGL functions */
87extern XVisualInfo *X11_GL_GetVisual(_THIS);
88extern int X11_GL_CreateWindow(_THIS, int w, int h);
89extern int X11_GL_CreateContext(_THIS);
90extern void X11_GL_Shutdown(_THIS);
91#if SDL_VIDEO_OPENGL_GLX
92extern int X11_GL_MakeCurrent(_THIS);
93extern int X11_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value);
94extern void X11_GL_SwapBuffers(_THIS);
95extern int X11_GL_LoadLibrary(_THIS, const char* path);
96extern void *X11_GL_GetProcAddress(_THIS, const char* proc);
97#endif
98extern void X11_GL_UnloadLibrary(_THIS);
99
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11image.c b/apps/plugins/sdl/src/video/x11/SDL_x11image.c
deleted file mode 100644
index 464bc37ba7..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11image.c
+++ /dev/null
@@ -1,316 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <stdio.h>
25#include <unistd.h>
26
27#include "SDL_endian.h"
28#include "../../events/SDL_events_c.h"
29#include "SDL_x11image_c.h"
30
31#ifndef NO_SHARED_MEMORY
32
33/* Shared memory error handler routine */
34static int shm_error;
35static int (*X_handler)(Display *, XErrorEvent *) = NULL;
36static int shm_errhandler(Display *d, XErrorEvent *e)
37{
38 if ( e->error_code == BadAccess ) {
39 shm_error = True;
40 return(0);
41 } else
42 return(X_handler(d,e));
43}
44
45static void try_mitshm(_THIS, SDL_Surface *screen)
46{
47 /* Dynamic X11 may not have SHM entry points on this box. */
48 if ((use_mitshm) && (!SDL_X11_HAVE_SHM))
49 use_mitshm = 0;
50
51 if(!use_mitshm)
52 return;
53 shminfo.shmid = shmget(IPC_PRIVATE, screen->h*screen->pitch,
54 IPC_CREAT | 0777);
55 if ( shminfo.shmid >= 0 ) {
56 shminfo.shmaddr = (char *)shmat(shminfo.shmid, 0, 0);
57 shminfo.readOnly = False;
58 if ( shminfo.shmaddr != (char *)-1 ) {
59 shm_error = False;
60 X_handler = XSetErrorHandler(shm_errhandler);
61 XShmAttach(SDL_Display, &shminfo);
62 XSync(SDL_Display, True);
63 XSetErrorHandler(X_handler);
64 if ( shm_error )
65 shmdt(shminfo.shmaddr);
66 } else {
67 shm_error = True;
68 }
69 shmctl(shminfo.shmid, IPC_RMID, NULL);
70 } else {
71 shm_error = True;
72 }
73 if ( shm_error )
74 use_mitshm = 0;
75 if ( use_mitshm )
76 screen->pixels = shminfo.shmaddr;
77}
78#endif /* ! NO_SHARED_MEMORY */
79
80/* Various screen update functions available */
81static void X11_NormalUpdate(_THIS, int numrects, SDL_Rect *rects);
82static void X11_MITSHMUpdate(_THIS, int numrects, SDL_Rect *rects);
83
84int X11_SetupImage(_THIS, SDL_Surface *screen)
85{
86#ifndef NO_SHARED_MEMORY
87 try_mitshm(this, screen);
88 if(use_mitshm) {
89 SDL_Ximage = XShmCreateImage(SDL_Display, SDL_Visual,
90 this->hidden->depth, ZPixmap,
91 shminfo.shmaddr, &shminfo,
92 screen->w, screen->h);
93 if(!SDL_Ximage) {
94 XShmDetach(SDL_Display, &shminfo);
95 XSync(SDL_Display, False);
96 shmdt(shminfo.shmaddr);
97 screen->pixels = NULL;
98 goto error;
99 }
100 this->UpdateRects = X11_MITSHMUpdate;
101 }
102 if(!use_mitshm)
103#endif /* not NO_SHARED_MEMORY */
104 {
105 screen->pixels = SDL_malloc(screen->h*screen->pitch);
106 if ( screen->pixels == NULL ) {
107 SDL_OutOfMemory();
108 return -1;
109 }
110 SDL_Ximage = XCreateImage(SDL_Display, SDL_Visual,
111 this->hidden->depth, ZPixmap, 0,
112 (char *)screen->pixels,
113 screen->w, screen->h,
114 32, 0);
115 if ( SDL_Ximage == NULL )
116 goto error;
117 /* XPutImage will convert byte sex automatically */
118 SDL_Ximage->byte_order = (SDL_BYTEORDER == SDL_BIG_ENDIAN)
119 ? MSBFirst : LSBFirst;
120 this->UpdateRects = X11_NormalUpdate;
121 }
122 screen->pitch = SDL_Ximage->bytes_per_line;
123 return(0);
124
125error:
126 SDL_SetError("Couldn't create XImage");
127 return 1;
128}
129
130void X11_DestroyImage(_THIS, SDL_Surface *screen)
131{
132 if ( SDL_Ximage ) {
133 XDestroyImage(SDL_Ximage);
134#ifndef NO_SHARED_MEMORY
135 if ( use_mitshm ) {
136 XShmDetach(SDL_Display, &shminfo);
137 XSync(SDL_Display, False);
138 shmdt(shminfo.shmaddr);
139 }
140#endif /* ! NO_SHARED_MEMORY */
141 SDL_Ximage = NULL;
142 }
143 if ( screen ) {
144 screen->pixels = NULL;
145 }
146}
147
148/* Determine the number of CPUs in the system */
149static int num_CPU(void)
150{
151 static int num_cpus = 0;
152
153 if(!num_cpus) {
154#if defined(__LINUX__)
155 char line[BUFSIZ];
156 FILE *pstat = fopen("/proc/stat", "r");
157 if ( pstat ) {
158 while ( fgets(line, sizeof(line), pstat) ) {
159 if (SDL_memcmp(line, "cpu", 3) == 0 && line[3] != ' ') {
160 ++num_cpus;
161 }
162 }
163 fclose(pstat);
164 }
165#elif defined(__IRIX__)
166 num_cpus = sysconf(_SC_NPROC_ONLN);
167#elif defined(_SC_NPROCESSORS_ONLN)
168 /* number of processors online (SVR4.0MP compliant machines) */
169 num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
170#elif defined(_SC_NPROCESSORS_CONF)
171 /* number of processors configured (SVR4.0MP compliant machines) */
172 num_cpus = sysconf(_SC_NPROCESSORS_CONF);
173#endif
174 if ( num_cpus <= 0 ) {
175 num_cpus = 1;
176 }
177 }
178 return num_cpus;
179}
180
181int X11_ResizeImage(_THIS, SDL_Surface *screen, Uint32 flags)
182{
183 int retval;
184
185 X11_DestroyImage(this, screen);
186 if ( flags & SDL_OPENGL ) { /* No image when using GL */
187 retval = 0;
188 } else {
189 retval = X11_SetupImage(this, screen);
190 /* We support asynchronous blitting on the display */
191 if ( flags & SDL_ASYNCBLIT ) {
192 /* This is actually slower on single-CPU systems,
193 probably because of CPU contention between the
194 X server and the application.
195 Note: Is this still true with XFree86 4.0?
196 */
197 if ( num_CPU() > 1 ) {
198 screen->flags |= SDL_ASYNCBLIT;
199 }
200 }
201 }
202 return(retval);
203}
204
205/* We don't actually allow hardware surfaces other than the main one */
206int X11_AllocHWSurface(_THIS, SDL_Surface *surface)
207{
208 return(-1);
209}
210void X11_FreeHWSurface(_THIS, SDL_Surface *surface)
211{
212 return;
213}
214
215int X11_LockHWSurface(_THIS, SDL_Surface *surface)
216{
217 if ( (surface == SDL_VideoSurface) && blit_queued ) {
218 XSync(GFX_Display, False);
219 blit_queued = 0;
220 }
221 return(0);
222}
223void X11_UnlockHWSurface(_THIS, SDL_Surface *surface)
224{
225 return;
226}
227
228int X11_FlipHWSurface(_THIS, SDL_Surface *surface)
229{
230 return(0);
231}
232
233static void X11_NormalUpdate(_THIS, int numrects, SDL_Rect *rects)
234{
235 int i;
236
237 for (i = 0; i < numrects; ++i) {
238 if ( rects[i].w == 0 || rects[i].h == 0 ) { /* Clipped? */
239 continue;
240 }
241 XPutImage(GFX_Display, SDL_Window, SDL_GC, SDL_Ximage,
242 rects[i].x, rects[i].y,
243 rects[i].x, rects[i].y, rects[i].w, rects[i].h);
244 }
245 if ( SDL_VideoSurface->flags & SDL_ASYNCBLIT ) {
246 XFlush(GFX_Display);
247 blit_queued = 1;
248 } else {
249 XSync(GFX_Display, False);
250 }
251}
252
253static void X11_MITSHMUpdate(_THIS, int numrects, SDL_Rect *rects)
254{
255#ifndef NO_SHARED_MEMORY
256 int i;
257
258 for ( i=0; i<numrects; ++i ) {
259 if ( rects[i].w == 0 || rects[i].h == 0 ) { /* Clipped? */
260 continue;
261 }
262 XShmPutImage(GFX_Display, SDL_Window, SDL_GC, SDL_Ximage,
263 rects[i].x, rects[i].y,
264 rects[i].x, rects[i].y, rects[i].w, rects[i].h,
265 False);
266 }
267 if ( SDL_VideoSurface->flags & SDL_ASYNCBLIT ) {
268 XFlush(GFX_Display);
269 blit_queued = 1;
270 } else {
271 XSync(GFX_Display, False);
272 }
273#endif /* ! NO_SHARED_MEMORY */
274}
275
276/* There's a problem with the automatic refreshing of the display.
277 Even though the XVideo code uses the GFX_Display to update the
278 video memory, it appears that updating the window asynchronously
279 from a different thread will cause "blackouts" of the window.
280 This is a sort of a hacked workaround for the problem.
281*/
282static int enable_autorefresh = 1;
283
284void X11_DisableAutoRefresh(_THIS)
285{
286 --enable_autorefresh;
287}
288
289void X11_EnableAutoRefresh(_THIS)
290{
291 ++enable_autorefresh;
292}
293
294void X11_RefreshDisplay(_THIS)
295{
296 /* Don't refresh a display that doesn't have an image (like GL)
297 Instead, post an expose event so the application can refresh.
298 */
299 if ( ! SDL_Ximage || (enable_autorefresh <= 0) ) {
300 SDL_PrivateExpose();
301 return;
302 }
303#ifndef NO_SHARED_MEMORY
304 if ( this->UpdateRects == X11_MITSHMUpdate ) {
305 XShmPutImage(SDL_Display, SDL_Window, SDL_GC, SDL_Ximage,
306 0, 0, 0, 0, this->screen->w, this->screen->h,
307 False);
308 } else
309#endif /* ! NO_SHARED_MEMORY */
310 {
311 XPutImage(SDL_Display, SDL_Window, SDL_GC, SDL_Ximage,
312 0, 0, 0, 0, this->screen->w, this->screen->h);
313 }
314 XSync(SDL_Display, False);
315}
316
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11image_c.h b/apps/plugins/sdl/src/video/x11/SDL_x11image_c.h
deleted file mode 100644
index 2de15717ba..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11image_c.h
+++ /dev/null
@@ -1,38 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_x11video.h"
25
26extern int X11_SetupImage(_THIS, SDL_Surface *screen);
27extern void X11_DestroyImage(_THIS, SDL_Surface *screen);
28extern int X11_ResizeImage(_THIS, SDL_Surface *screen, Uint32 flags);
29
30extern int X11_AllocHWSurface(_THIS, SDL_Surface *surface);
31extern void X11_FreeHWSurface(_THIS, SDL_Surface *surface);
32extern int X11_LockHWSurface(_THIS, SDL_Surface *surface);
33extern void X11_UnlockHWSurface(_THIS, SDL_Surface *surface);
34extern int X11_FlipHWSurface(_THIS, SDL_Surface *surface);
35
36extern void X11_DisableAutoRefresh(_THIS);
37extern void X11_EnableAutoRefresh(_THIS);
38extern void X11_RefreshDisplay(_THIS);
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11modes.c b/apps/plugins/sdl/src/video/x11/SDL_x11modes.c
deleted file mode 100644
index c232e6aa36..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11modes.c
+++ /dev/null
@@ -1,1143 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Utilities for getting and setting the X display mode */
25
26#include <stdio.h>
27
28#include "SDL_timer.h"
29#include "SDL_events.h"
30#include "../../events/SDL_events_c.h"
31#include "SDL_x11video.h"
32#include "SDL_x11wm_c.h"
33#include "SDL_x11modes_c.h"
34#include "SDL_x11image_c.h"
35
36/*#define X11MODES_DEBUG*/
37
38#define MAX(a, b) (a > b ? a : b)
39
40#if SDL_VIDEO_DRIVER_X11_XRANDR
41static int cmpmodelist(const void *va, const void *vb)
42{
43 const SDL_Rect *a = *(const SDL_Rect **)va;
44 const SDL_Rect *b = *(const SDL_Rect **)vb;
45 if ( a->w == b->w )
46 return b->h - a->h;
47 else
48 return b->w - a->w;
49}
50#endif
51
52#if SDL_VIDEO_DRIVER_X11_VIDMODE
53Bool SDL_NAME(XF86VidModeGetModeInfo)(Display *dpy, int scr, SDL_NAME(XF86VidModeModeInfo) *info)
54{
55 Bool retval;
56 int dotclock;
57 SDL_NAME(XF86VidModeModeLine) l;
58 SDL_memset(&l, 0, sizeof(l));
59 retval = SDL_NAME(XF86VidModeGetModeLine)(dpy, scr, &dotclock, &l);
60 info->dotclock = dotclock;
61 info->hdisplay = l.hdisplay;
62 info->hsyncstart = l.hsyncstart;
63 info->hsyncend = l.hsyncend;
64 info->htotal = l.htotal;
65 info->hskew = l.hskew;
66 info->vdisplay = l.vdisplay;
67 info->vsyncstart = l.vsyncstart;
68 info->vsyncend = l.vsyncend;
69 info->vtotal = l.vtotal;
70 info->flags = l.flags;
71 info->privsize = l.privsize;
72 info->private = l.private;
73 return retval;
74}
75#endif /* SDL_VIDEO_DRIVER_X11_VIDMODE */
76
77#if SDL_VIDEO_DRIVER_X11_VIDMODE
78static void save_mode(_THIS)
79{
80 SDL_memset(&saved_mode, 0, sizeof(saved_mode));
81 SDL_NAME(XF86VidModeGetModeInfo)(SDL_Display,SDL_Screen,&saved_mode);
82 SDL_NAME(XF86VidModeGetViewPort)(SDL_Display,SDL_Screen,&saved_view.x,&saved_view.y);
83}
84#endif
85
86#if SDL_VIDEO_DRIVER_X11_VIDMODE
87static void restore_mode(_THIS)
88{
89 SDL_NAME(XF86VidModeModeLine) mode;
90 int unused;
91
92 if ( SDL_NAME(XF86VidModeGetModeLine)(SDL_Display, SDL_Screen, &unused, &mode) ) {
93 if ( (saved_mode.hdisplay != mode.hdisplay) ||
94 (saved_mode.vdisplay != mode.vdisplay) ) {
95 SDL_NAME(XF86VidModeSwitchToMode)(SDL_Display, SDL_Screen, &saved_mode);
96 }
97 }
98 if ( (saved_view.x != 0) || (saved_view.y != 0) ) {
99 SDL_NAME(XF86VidModeSetViewPort)(SDL_Display, SDL_Screen, saved_view.x, saved_view.y);
100 }
101}
102#endif
103
104#if SDL_VIDEO_DRIVER_X11_VIDMODE
105static int cmpmodes(const void *va, const void *vb)
106{
107 const SDL_NAME(XF86VidModeModeInfo) *a = *(const SDL_NAME(XF86VidModeModeInfo)**)va;
108 const SDL_NAME(XF86VidModeModeInfo) *b = *(const SDL_NAME(XF86VidModeModeInfo)**)vb;
109 if ( a->hdisplay == b->hdisplay )
110 return b->vdisplay - a->vdisplay;
111 else
112 return b->hdisplay - a->hdisplay;
113}
114#endif
115
116static void get_real_resolution(_THIS, int* w, int* h);
117
118static void set_best_resolution(_THIS, int width, int height)
119{
120#if SDL_VIDEO_DRIVER_X11_VIDMODE
121 if ( use_vidmode ) {
122 SDL_NAME(XF86VidModeModeLine) mode;
123 SDL_NAME(XF86VidModeModeInfo) **modes;
124 int i;
125 int nmodes;
126 int best = -1;
127
128 if ( SDL_NAME(XF86VidModeGetModeLine)(SDL_Display, SDL_Screen, &i, &mode) &&
129 SDL_NAME(XF86VidModeGetAllModeLines)(SDL_Display,SDL_Screen,&nmodes,&modes) ) {
130 for ( i = 0; i < nmodes ; i++ ) {
131 if ( (modes[i]->hdisplay == width) &&
132 (modes[i]->vdisplay == height) ) {
133 best = i;
134 break;
135 }
136 if ( modes[i]->hdisplay >= width &&
137 modes[i]->vdisplay >= height ) {
138 if ( best < 0 ||
139 (modes[i]->hdisplay < modes[best]->hdisplay &&
140 modes[i]->vdisplay <= modes[best]->vdisplay) ||
141 (modes[i]->vdisplay < modes[best]->vdisplay &&
142 modes[i]->hdisplay <= modes[best]->hdisplay) ) {
143 best = i;
144 }
145 }
146 }
147 if ( best >= 0 &&
148 ((modes[best]->hdisplay != mode.hdisplay) ||
149 (modes[best]->vdisplay != mode.vdisplay)) ) {
150#ifdef X11MODES_DEBUG
151 printf("Best Mode %d: %d x %d @ %d\n", best,
152 modes[best]->hdisplay, modes[best]->vdisplay,
153 (modes[best]->htotal && modes[best]->vtotal) ? (1000 * modes[best]->dotclock / (modes[best]->htotal * modes[best]->vtotal)) : 0 );
154#endif
155 SDL_NAME(XF86VidModeSwitchToMode)(SDL_Display, SDL_Screen, modes[best]);
156 }
157 XFree(modes);
158 }
159 }
160#endif /* SDL_VIDEO_DRIVER_X11_VIDMODE */
161
162 /* XiG */
163#if SDL_VIDEO_DRIVER_X11_XME
164 if ( use_xme && SDL_modelist ) {
165 int i;
166
167#ifdef X11MODES_DEBUG
168 fprintf(stderr, "XME: set_best_resolution(): w = %d, h = %d\n",
169 width, height);
170#endif
171 for ( i=0; SDL_modelist[i]; ++i ) {
172 if ( (SDL_modelist[i]->w >= width) &&
173 (SDL_modelist[i]->h >= height) ) {
174 break;
175 }
176 }
177
178 if ( SDL_modelist[i] ) { /* found one, lets try it */
179 int w, h;
180
181 /* check current mode so we can avoid uneccessary mode changes */
182 get_real_resolution(this, &w, &h);
183
184 if ( (SDL_modelist[i]->w != w) || (SDL_modelist[i]->h != h) ) {
185#ifdef X11MODES_DEBUG
186 fprintf(stderr, "XME: set_best_resolution: "
187 "XiGMiscChangeResolution: %d %d\n",
188 SDL_modelist[i]->w, SDL_modelist[i]->h);
189#endif
190 XiGMiscChangeResolution(SDL_Display,
191 SDL_Screen,
192 0, /* view */
193 SDL_modelist[i]->w,
194 SDL_modelist[i]->h,
195 0);
196 XSync(SDL_Display, False);
197 }
198 }
199 }
200#endif /* SDL_VIDEO_DRIVER_X11_XME */
201
202#if SDL_VIDEO_DRIVER_X11_XRANDR
203 if ( use_xrandr && SDL_modelist ) {
204#ifdef X11MODES_DEBUG
205 fprintf(stderr, "XRANDR: set_best_resolution(): w = %d, h = %d\n",
206 width, height);
207#endif
208 int i, nsizes;
209 XRRScreenSize *sizes;
210
211 /* find the smallest resolution that is at least as big as the user requested */
212 sizes = XRRConfigSizes(screen_config, &nsizes);
213 for ( i = (nsizes-1); i >= 0; i-- ) {
214 if ( (SDL_modelist[i]->w >= width) &&
215 (SDL_modelist[i]->h >= height) ) {
216 break;
217 }
218 }
219
220 if ( i >= 0 && SDL_modelist[i] ) { /* found one, lets try it */
221 int w, h;
222
223 /* check current mode so we can avoid uneccessary mode changes */
224 get_real_resolution(this, &w, &h);
225
226 if ( (SDL_modelist[i]->w != w) || (SDL_modelist[i]->h != h) ) {
227 int size_id;
228
229#ifdef X11MODES_DEBUG
230 fprintf(stderr, "XRANDR: set_best_resolution: "
231 "XXRSetScreenConfig: %d %d\n",
232 SDL_modelist[i]->w, SDL_modelist[i]->h);
233#endif
234
235 /* find the matching size entry index */
236 for ( size_id = 0; size_id < nsizes; ++size_id ) {
237 if ( (sizes[size_id].width == SDL_modelist[i]->w) &&
238 (sizes[size_id].height == SDL_modelist[i]->h) )
239 break;
240 }
241
242 XRRSetScreenConfig(SDL_Display, screen_config, SDL_Root,
243 size_id, saved_rotation, CurrentTime);
244 }
245 }
246 }
247#endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
248}
249
250static void get_real_resolution(_THIS, int* w, int* h)
251{
252#if SDL_VIDEO_DRIVER_X11_XME
253 if ( use_xme ) {
254 int ractive;
255 XiGMiscResolutionInfo *modelist;
256
257 XiGMiscQueryResolutions(SDL_Display, SDL_Screen,
258 0, /* view */
259 &ractive, &modelist);
260 *w = modelist[ractive].width;
261 *h = modelist[ractive].height;
262#ifdef X11MODES_DEBUG
263 fprintf(stderr, "XME: get_real_resolution: w = %d h = %d\n", *w, *h);
264#endif
265 XFree(modelist);
266 return;
267 }
268#endif /* SDL_VIDEO_DRIVER_X11_XME */
269
270#if SDL_VIDEO_DRIVER_X11_VIDMODE
271 if ( use_vidmode ) {
272 SDL_NAME(XF86VidModeModeLine) mode;
273 int unused;
274
275 if ( SDL_NAME(XF86VidModeGetModeLine)(SDL_Display, SDL_Screen, &unused, &mode) ) {
276 *w = mode.hdisplay;
277 *h = mode.vdisplay;
278 return;
279 }
280 }
281#endif /* SDL_VIDEO_DRIVER_X11_VIDMODE */
282
283#if SDL_VIDEO_DRIVER_X11_XRANDR
284 if ( use_xrandr ) {
285 int nsizes;
286 XRRScreenSize* sizes;
287
288 sizes = XRRConfigSizes(screen_config, &nsizes);
289 if ( nsizes > 0 ) {
290 int cur_size;
291 Rotation cur_rotation;
292
293 cur_size = XRRConfigCurrentConfiguration(screen_config, &cur_rotation);
294 if ( cur_size >= 0 && cur_size < nsizes ) {
295 *w = sizes[cur_size].width;
296 *h = sizes[cur_size].height;
297 }
298#ifdef X11MODES_DEBUG
299 fprintf(stderr, "XRANDR: get_real_resolution: w = %d h = %d\n", *w, *h);
300#endif
301 return;
302 }
303 }
304#endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
305
306#if SDL_VIDEO_DRIVER_X11_XINERAMA
307 if ( use_xinerama ) {
308 *w = xinerama_info.width;
309 *h = xinerama_info.height;
310 return;
311 }
312#endif /* SDL_VIDEO_DRIVER_X11_XINERAMA */
313
314 *w = DisplayWidth(SDL_Display, SDL_Screen);
315 *h = DisplayHeight(SDL_Display, SDL_Screen);
316}
317
318/* Called after mapping a window - waits until the window is mapped */
319void X11_WaitMapped(_THIS, Window win)
320{
321 XEvent event;
322 do {
323 XMaskEvent(SDL_Display, StructureNotifyMask, &event);
324 } while ( (event.type != MapNotify) || (event.xmap.event != win) );
325}
326
327/* Called after unmapping a window - waits until the window is unmapped */
328void X11_WaitUnmapped(_THIS, Window win)
329{
330 XEvent event;
331 do {
332 XMaskEvent(SDL_Display, StructureNotifyMask, &event);
333 } while ( (event.type != UnmapNotify) || (event.xunmap.event != win) );
334}
335
336static void move_cursor_to(_THIS, int x, int y)
337{
338 XWarpPointer(SDL_Display, None, SDL_Root, 0, 0, 0, 0, x, y);
339}
340
341static int add_default_visual(_THIS)
342{
343 int i;
344 int n = this->hidden->nvisuals;
345 for (i=0; i<n; i++) {
346 if (this->hidden->visuals[i].visual == DefaultVisual(SDL_Display, SDL_Screen)) return n;
347 }
348 this->hidden->visuals[n].depth = DefaultDepth(SDL_Display, SDL_Screen);;
349 this->hidden->visuals[n].visual = DefaultVisual(SDL_Display, SDL_Screen);;
350 this->hidden->nvisuals++;
351 return(this->hidden->nvisuals);
352}
353static int add_visual(_THIS, int depth, int class)
354{
355 XVisualInfo vi;
356 if(XMatchVisualInfo(SDL_Display, SDL_Screen, depth, class, &vi)) {
357 int n = this->hidden->nvisuals;
358 this->hidden->visuals[n].depth = vi.depth;
359 this->hidden->visuals[n].visual = vi.visual;
360 this->hidden->nvisuals++;
361 }
362 return(this->hidden->nvisuals);
363}
364static int add_visual_byid(_THIS, const char *visual_id)
365{
366 XVisualInfo *vi, template;
367 int nvis;
368
369 if ( visual_id ) {
370 SDL_memset(&template, 0, (sizeof template));
371 template.visualid = SDL_strtol(visual_id, NULL, 0);
372 vi = XGetVisualInfo(SDL_Display, VisualIDMask, &template, &nvis);
373 if ( vi ) {
374 int n = this->hidden->nvisuals;
375 this->hidden->visuals[n].depth = vi->depth;
376 this->hidden->visuals[n].visual = vi->visual;
377 this->hidden->nvisuals++;
378 XFree(vi);
379 }
380 }
381 return(this->hidden->nvisuals);
382}
383
384/* Global for the error handler */
385int vm_event, vm_error = -1;
386
387#if SDL_VIDEO_DRIVER_X11_XINERAMA
388static int CheckXinerama(_THIS, int *major, int *minor)
389{
390 const char *env;
391
392 /* Default the extension not available */
393 *major = *minor = 0;
394
395 /* Allow environment override */
396 env = getenv("SDL_VIDEO_X11_XINERAMA");
397 if ( env && !SDL_atoi(env) ) {
398 return 0;
399 }
400
401 /* Query the extension version */
402 if ( !SDL_NAME(XineramaQueryExtension)(SDL_Display, major, minor) ||
403 !SDL_NAME(XineramaIsActive)(SDL_Display) ) {
404 return 0;
405 }
406 return 1;
407}
408#endif /* SDL_VIDEO_DRIVER_X11_XINERAMA */
409
410#if SDL_VIDEO_DRIVER_X11_XRANDR
411static int CheckXRandR(_THIS, int *major, int *minor)
412{
413 const char *env;
414
415 /* Default the extension not available */
416 *major = *minor = 0;
417
418 /* Allow environment override */
419 env = getenv("SDL_VIDEO_X11_XRANDR");
420 if ( env && !SDL_atoi(env) ) {
421 return 0;
422 }
423
424 /* This defaults off now, due to KDE window maximize problems */
425 if ( !env ) {
426 return 0;
427 }
428
429 if ( !SDL_X11_HAVE_XRANDR ) {
430 return 0;
431 }
432
433 /* Query the extension version */
434 if ( !XRRQueryVersion(SDL_Display, major, minor) ) {
435 return 0;
436 }
437 return 1;
438}
439#endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
440
441#if SDL_VIDEO_DRIVER_X11_VIDMODE
442static int CheckVidMode(_THIS, int *major, int *minor)
443{
444 const char *env;
445
446 /* Default the extension not available */
447 *major = *minor = 0;
448
449 /* Allow environment override */
450 env = getenv("SDL_VIDEO_X11_VIDMODE");
451 if ( env && !SDL_atoi(env) ) {
452 return 0;
453 }
454
455 /* Metro-X 4.3.0 and earlier has a broken implementation of
456 XF86VidModeGetAllModeLines() - it hangs the client.
457 */
458 if ( SDL_strcmp(ServerVendor(SDL_Display), "Metro Link Incorporated") == 0 ) {
459 FILE *metro_fp;
460
461 metro_fp = fopen("/usr/X11R6/lib/X11/Metro/.version", "r");
462 if ( metro_fp != NULL ) {
463 int major, minor, patch, version, scannum;
464 major = 0; minor = 0; patch = 0;
465 scannum = fscanf(metro_fp, "%d.%d.%d", &major, &minor, &patch);
466 fclose(metro_fp);
467 if ( (scannum < 0) || (scannum > 3) ) {
468 return 0; /* we need _something_ useful from fscanf(). */
469 }
470 version = major*100+minor*10+patch;
471 if ( version < 431 ) {
472 return 0;
473 }
474 }
475 }
476
477 /* Query the extension version */
478 vm_error = -1;
479 if ( !SDL_NAME(XF86VidModeQueryExtension)(SDL_Display, &vm_event, &vm_error) ||
480 !SDL_NAME(XF86VidModeQueryVersion)(SDL_Display, major, minor) ) {
481 return 0;
482 }
483 return 1;
484}
485#endif /* SDL_VIDEO_DRIVER_X11_VIDMODE */
486
487#if SDL_VIDEO_DRIVER_X11_XME
488static int CheckXME(_THIS, int *major, int *minor)
489{
490 const char *env;
491
492 /* Default the extension not available */
493 *major = *minor = 0;
494
495 /* Allow environment override */
496 env = getenv("SDL_VIDEO_X11_VIDMODE");
497 if ( env && !SDL_atoi(env) ) {
498 return 0;
499 }
500
501 /* Query the extension version */
502 if ( !XiGMiscQueryVersion(SDL_Display, major, minor) ) {
503 return 0;
504 }
505 return 1;
506}
507#endif /* SDL_VIDEO_DRIVER_X11_XME */
508
509int X11_GetVideoModes(_THIS)
510{
511#if SDL_VIDEO_DRIVER_X11_XINERAMA
512 int xinerama_major, xinerama_minor;
513#endif
514#if SDL_VIDEO_DRIVER_X11_XRANDR
515 int xrandr_major, xrandr_minor;
516 int nsizes;
517 XRRScreenSize *sizes;
518#endif
519#if SDL_VIDEO_DRIVER_X11_VIDMODE
520 int vm_major, vm_minor;
521 int nmodes;
522 SDL_NAME(XF86VidModeModeInfo) **modes;
523#endif
524#if SDL_VIDEO_DRIVER_X11_XME
525 int xme_major, xme_minor;
526 int ractive, nummodes;
527 XiGMiscResolutionInfo *modelist;
528#endif
529 int i, n;
530 int screen_w;
531 int screen_h;
532
533 use_xinerama = 0;
534 use_xrandr = 0;
535 use_vidmode = 0;
536 use_xme = 0;
537 screen_w = DisplayWidth(SDL_Display, SDL_Screen);
538 screen_h = DisplayHeight(SDL_Display, SDL_Screen);
539
540#if SDL_VIDEO_DRIVER_X11_XINERAMA
541 /* Query Xinerama extention */
542 if ( CheckXinerama(this, &xinerama_major, &xinerama_minor) ) {
543 /* Find out which screen is the desired one */
544 int desired = -1;
545 int screens;
546 int w, h;
547 SDL_NAME(XineramaScreenInfo) *xinerama;
548
549 const char *variable = SDL_getenv("SDL_VIDEO_FULLSCREEN_DISPLAY");
550 if ( !variable ) {
551 variable = SDL_getenv("SDL_VIDEO_FULLSCREEN_HEAD");
552 }
553 if ( variable ) {
554 desired = SDL_atoi(variable);
555 }
556#ifdef X11MODES_DEBUG
557 printf("X11 detected Xinerama:\n");
558#endif
559 xinerama = SDL_NAME(XineramaQueryScreens)(SDL_Display, &screens);
560 for ( i = 0; i < screens; i++ ) {
561#ifdef X11MODES_DEBUG
562 printf("xinerama %d: %dx%d+%d+%d\n",
563 xinerama[i].screen_number,
564 xinerama[i].width, xinerama[i].height,
565 xinerama[i].x_org, xinerama[i].y_org);
566#endif
567 if ( xinerama[i].screen_number == desired ) {
568 use_xinerama = 1;
569 xinerama_info = xinerama[i];
570 }
571 }
572 XFree(xinerama);
573
574 if ( use_xinerama ) {
575 SDL_modelist = (SDL_Rect **)SDL_malloc(3*sizeof(SDL_Rect *));
576 if ( !SDL_modelist ) {
577 SDL_OutOfMemory();
578 return -1;
579 }
580
581 /* Add the full xinerama mode */
582 n = 0;
583 w = xinerama_info.width;
584 h = xinerama_info.height;
585 if ( screen_w > w || screen_h > h) {
586 SDL_modelist[n] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect));
587 if ( SDL_modelist[n] ) {
588 SDL_modelist[n]->x = 0;
589 SDL_modelist[n]->y = 0;
590 SDL_modelist[n]->w = screen_w;
591 SDL_modelist[n]->h = screen_h;
592 ++n;
593 }
594 }
595
596 /* Add the head xinerama mode */
597 SDL_modelist[n] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect));
598 if ( SDL_modelist[n] ) {
599 SDL_modelist[n]->x = 0;
600 SDL_modelist[n]->y = 0;
601 SDL_modelist[n]->w = w;
602 SDL_modelist[n]->h = h;
603 ++n;
604 }
605 SDL_modelist[n] = NULL;
606 }
607 }
608#endif /* SDL_VIDEO_DRIVER_X11_XINERAMA */
609
610#if SDL_VIDEO_DRIVER_X11_XRANDR
611 /* XRandR */
612 /* require at least XRandR v1.0 (arbitrary) */
613 if ( CheckXRandR(this, &xrandr_major, &xrandr_minor) && (xrandr_major >= 1) )
614 {
615#ifdef X11MODES_DEBUG
616 fprintf(stderr, "XRANDR: XRRQueryVersion: V%d.%d\n",
617 xrandr_major, xrandr_minor);
618#endif
619
620 /* save the screen configuration since we must reference it
621 each time we toggle modes.
622 */
623 screen_config = XRRGetScreenInfo(SDL_Display, SDL_Root);
624
625 /* retrieve the list of resolution */
626 sizes = XRRConfigSizes(screen_config, &nsizes);
627 if (nsizes > 0) {
628 if ( SDL_modelist ) {
629 for ( i = 0; SDL_modelist[i]; ++i ) {
630 SDL_free(SDL_modelist[i]);
631 }
632 SDL_free(SDL_modelist);
633 }
634 SDL_modelist = (SDL_Rect **)malloc((nsizes+1)*sizeof(SDL_Rect *));
635 if ( !SDL_modelist ) {
636 SDL_OutOfMemory();
637 return -1;
638 }
639 for ( i=0; i < nsizes; i++ ) {
640 if ((SDL_modelist[i] =
641 (SDL_Rect *)malloc(sizeof(SDL_Rect))) == NULL)
642 break;
643#ifdef X11MODES_DEBUG
644 fprintf(stderr, "XRANDR: mode = %4d, w = %4d, h = %4d\n",
645 i, sizes[i].width, sizes[i].height);
646#endif
647
648 SDL_modelist[i]->x = 0;
649 SDL_modelist[i]->y = 0;
650 SDL_modelist[i]->w = sizes[i].width;
651 SDL_modelist[i]->h = sizes[i].height;
652
653 }
654 /* sort the mode list descending as SDL expects */
655 SDL_qsort(SDL_modelist, nsizes, sizeof *SDL_modelist, cmpmodelist);
656 SDL_modelist[i] = NULL; /* terminator */
657
658 use_xrandr = xrandr_major * 100 + xrandr_minor;
659 saved_size_id = XRRConfigCurrentConfiguration(screen_config, &saved_rotation);
660 }
661 }
662#endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
663
664#if SDL_VIDEO_DRIVER_X11_VIDMODE
665 /* XVidMode */
666 if ( !use_xrandr &&
667#if SDL_VIDEO_DRIVER_X11_XINERAMA
668 (!use_xinerama || xinerama_info.screen_number == -1) &&
669#endif
670 CheckVidMode(this, &vm_major, &vm_minor) &&
671 SDL_NAME(XF86VidModeGetAllModeLines)(SDL_Display, SDL_Screen,&nmodes,&modes) )
672 {
673#ifdef X11MODES_DEBUG
674 printf("VidMode modes: (unsorted)\n");
675 for ( i = 0; i < nmodes; ++i ) {
676 printf("Mode %d: %d x %d @ %d\n", i,
677 modes[i]->hdisplay, modes[i]->vdisplay,
678 (modes[i]->htotal && modes[i]->vtotal) ? (1000 * modes[i]->dotclock / (modes[i]->htotal * modes[i]->vtotal)) : 0 );
679 }
680#endif
681 if ( SDL_modelist ) {
682 for ( i = 0; SDL_modelist[i]; ++i ) {
683 SDL_free(SDL_modelist[i]);
684 }
685 SDL_free(SDL_modelist);
686 }
687 SDL_modelist = (SDL_Rect **)SDL_malloc((nmodes+2)*sizeof(SDL_Rect *));
688 if ( !SDL_modelist ) {
689 SDL_OutOfMemory();
690 return -1;
691 }
692 SDL_qsort(modes, nmodes, sizeof *modes, cmpmodes);
693 n = 0;
694 for ( i=0; i<nmodes; ++i ) {
695 int w, h;
696
697 /* Eliminate duplicate modes with different refresh rates */
698 if ( i > 0 &&
699 modes[i]->hdisplay == modes[i-1]->hdisplay &&
700 modes[i]->vdisplay == modes[i-1]->vdisplay ) {
701 continue;
702 }
703
704 /* Check to see if we should add the screen size (Xinerama) */
705 w = modes[i]->hdisplay;
706 h = modes[i]->vdisplay;
707 if ( (screen_w * screen_h) >= (w * h) ) {
708 if ( (screen_w != w) || (screen_h != h) ) {
709 SDL_modelist[n] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect));
710 if ( SDL_modelist[n] ) {
711 SDL_modelist[n]->x = 0;
712 SDL_modelist[n]->y = 0;
713 SDL_modelist[n]->w = screen_w;
714 SDL_modelist[n]->h = screen_h;
715 ++n;
716 }
717 }
718 screen_w = 0;
719 screen_h = 0;
720 }
721
722 /* Add the size from the video mode list */
723 SDL_modelist[n] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect));
724 if ( SDL_modelist[n] == NULL ) {
725 break;
726 }
727 SDL_modelist[n]->x = 0;
728 SDL_modelist[n]->y = 0;
729 SDL_modelist[n]->w = w;
730 SDL_modelist[n]->h = h;
731 ++n;
732 }
733 SDL_modelist[n] = NULL;
734 XFree(modes);
735
736 use_vidmode = vm_major * 100 + vm_minor;
737 save_mode(this);
738 }
739#endif /* SDL_VIDEO_DRIVER_X11_VIDMODE */
740
741#if SDL_VIDEO_DRIVER_X11_XME
742 /* XiG */
743 modelist = NULL;
744 /* first lets make sure we have the extension, and it's at least v2.0 */
745 if ( CheckXME(this, &xme_major, &xme_minor) && xme_major >= 2 &&
746 (nummodes = XiGMiscQueryResolutions(SDL_Display, SDL_Screen,
747 0, /* view */
748 &ractive, &modelist)) > 1 )
749 { /* then we actually have some */
750 int j;
751
752 /* We get the list already sorted in descending order.
753 We'll copy it in reverse order so SDL is happy */
754#ifdef X11MODES_DEBUG
755 fprintf(stderr, "XME: nummodes = %d, active mode = %d\n",
756 nummodes, ractive);
757#endif
758 if ( SDL_modelist ) {
759 for ( i = 0; SDL_modelist[i]; ++i ) {
760 SDL_free(SDL_modelist[i]);
761 }
762 SDL_free(SDL_modelist);
763 }
764 SDL_modelist = (SDL_Rect **)SDL_malloc((nummodes+1)*sizeof(SDL_Rect *));
765 if ( !SDL_modelist ) {
766 SDL_OutOfMemory();
767 return -1;
768 }
769 for ( i=0, j=nummodes-1; j>=0; i++, j-- ) {
770 if ((SDL_modelist[i] =
771 (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect))) == NULL)
772 break;
773#ifdef X11MODES_DEBUG
774 fprintf(stderr, "XME: mode = %4d, w = %4d, h = %4d\n",
775 i, modelist[i].width, modelist[i].height);
776#endif
777
778 SDL_modelist[i]->x = 0;
779 SDL_modelist[i]->y = 0;
780 SDL_modelist[i]->w = modelist[j].width;
781 SDL_modelist[i]->h = modelist[j].height;
782
783 }
784 SDL_modelist[i] = NULL; /* terminator */
785
786 use_xme = xme_major * 100 + xme_minor;
787 saved_res = modelist[ractive]; /* save the current resolution */
788 }
789 if ( modelist ) {
790 XFree(modelist);
791 }
792#endif /* SDL_VIDEO_DRIVER_X11_XME */
793
794 {
795 /* It's interesting to note that if we allow 32 bit depths,
796 we get a visual with an alpha mask on composite servers.
797 static int depth_list[] = { 32, 24, 16, 15, 8 };
798 */
799 static int depth_list[] = { 24, 16, 15, 8 };
800 int j, np;
801 int use_directcolor = 1;
802 XPixmapFormatValues *pf;
803
804 /* Search for the visuals in deepest-first order, so that the first
805 will be the richest one */
806 if ( SDL_getenv("SDL_VIDEO_X11_NODIRECTCOLOR") ) {
807 use_directcolor = 0;
808 }
809 this->hidden->nvisuals = 0;
810 if ( ! add_visual_byid(this, SDL_getenv("SDL_VIDEO_X11_VISUALID")) ) {
811 for ( i=0; i<SDL_arraysize(depth_list); ++i ) {
812 if ( depth_list[i] > 8 ) {
813 if ( use_directcolor ) {
814 add_visual(this, depth_list[i], DirectColor);
815 }
816 add_visual(this, depth_list[i], TrueColor);
817 } else {
818 add_visual(this, depth_list[i], PseudoColor);
819 add_visual(this, depth_list[i], StaticColor);
820 }
821 }
822 add_default_visual(this);
823 }
824 if ( this->hidden->nvisuals == 0 ) {
825 SDL_SetError("Found no sufficiently capable X11 visuals");
826 return -1;
827 }
828
829 /* look up the pixel quantum for each depth */
830 pf = XListPixmapFormats(SDL_Display, &np);
831 for(i = 0; i < this->hidden->nvisuals; i++) {
832 int d = this->hidden->visuals[i].depth;
833 for(j = 0; j < np; j++)
834 if(pf[j].depth == d)
835 break;
836 this->hidden->visuals[i].bpp = j < np ? pf[j].bits_per_pixel : d;
837 }
838
839 XFree(pf);
840 }
841
842 if ( SDL_modelist == NULL ) {
843 SDL_modelist = (SDL_Rect **)SDL_malloc((1+1)*sizeof(SDL_Rect *));
844 if ( !SDL_modelist ) {
845 SDL_OutOfMemory();
846 return -1;
847 }
848 n = 0;
849 SDL_modelist[n] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect));
850 if ( SDL_modelist[n] ) {
851 SDL_modelist[n]->x = 0;
852 SDL_modelist[n]->y = 0;
853 SDL_modelist[n]->w = screen_w;
854 SDL_modelist[n]->h = screen_h;
855 ++n;
856 }
857 SDL_modelist[n] = NULL;
858 }
859
860#ifdef X11MODES_DEBUG
861 if ( use_xinerama ) {
862 printf("Xinerama is enabled\n");
863 }
864
865 if ( use_xrandr ) {
866 printf("XRandR is enabled\n");
867 }
868
869 if ( use_vidmode ) {
870 printf("VidMode is enabled\n");
871 }
872
873 if ( use_xme ) {
874 printf("Xi Graphics XME fullscreen is enabled\n");
875 }
876
877 if ( SDL_modelist ) {
878 printf("X11 video mode list:\n");
879 for ( i=0; SDL_modelist[i]; ++i ) {
880 printf("\t%dx%d\n", SDL_modelist[i]->w, SDL_modelist[i]->h);
881 }
882 }
883#endif /* X11MODES_DEBUG */
884
885 return 0;
886}
887
888int X11_SupportedVisual(_THIS, SDL_PixelFormat *format)
889{
890 int i;
891 for(i = 0; i < this->hidden->nvisuals; i++)
892 if(this->hidden->visuals[i].bpp == format->BitsPerPixel)
893 return 1;
894 return 0;
895}
896
897SDL_Rect **X11_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
898{
899 if ( X11_SupportedVisual(this, format) ) {
900 if ( flags & SDL_FULLSCREEN ) {
901 return(SDL_modelist);
902 } else {
903 return((SDL_Rect **)-1);
904 }
905 } else {
906 return((SDL_Rect **)0);
907 }
908}
909
910void X11_FreeVideoModes(_THIS)
911{
912 int i;
913
914 if ( SDL_modelist ) {
915 for ( i=0; SDL_modelist[i]; ++i ) {
916 SDL_free(SDL_modelist[i]);
917 }
918 SDL_free(SDL_modelist);
919 SDL_modelist = NULL;
920 }
921
922#if SDL_VIDEO_DRIVER_X11_XRANDR
923 /* Free the Xrandr screen configuration */
924 if ( screen_config ) {
925 XRRFreeScreenConfigInfo(screen_config);
926 screen_config = NULL;
927 }
928#endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
929}
930
931int X11_ResizeFullScreen(_THIS)
932{
933 int x = 0, y = 0;
934 int real_w, real_h;
935 int screen_w;
936 int screen_h;
937
938 screen_w = DisplayWidth(SDL_Display, SDL_Screen);
939 screen_h = DisplayHeight(SDL_Display, SDL_Screen);
940
941#if SDL_VIDEO_DRIVER_X11_XINERAMA
942 if ( use_xinerama &&
943 window_w <= xinerama_info.width &&
944 window_h <= xinerama_info.height ) {
945 x = xinerama_info.x_org;
946 y = xinerama_info.y_org;
947 }
948#endif /* SDL_VIDEO_DRIVER_X11_XINERAMA */
949
950 if ( currently_fullscreen ) {
951 /* Switch resolution and cover it with the FSwindow */
952 move_cursor_to(this, x, y);
953 set_best_resolution(this, window_w, window_h);
954 move_cursor_to(this, x, y);
955 get_real_resolution(this, &real_w, &real_h);
956 if ( window_w > real_w ) {
957 real_w = MAX(real_w, screen_w);
958 }
959 if ( window_h > real_h ) {
960 real_h = MAX(real_h, screen_h);
961 }
962 XMoveResizeWindow(SDL_Display, FSwindow, x, y, real_w, real_h);
963 move_cursor_to(this, real_w/2, real_h/2);
964
965 /* Center and reparent the drawing window */
966 x = (real_w - window_w)/2;
967 y = (real_h - window_h)/2;
968 XReparentWindow(SDL_Display, SDL_Window, FSwindow, x, y);
969 /* FIXME: move the mouse to the old relative location */
970 XSync(SDL_Display, True); /* Flush spurious mode change events */
971 }
972 return(1);
973}
974
975void X11_QueueEnterFullScreen(_THIS)
976{
977 switch_waiting = 0x01 | SDL_FULLSCREEN;
978 switch_time = SDL_GetTicks() + 1500;
979#if 0 /* This causes a BadMatch error if the window is iconified (not needed) */
980 XSetInputFocus(SDL_Display, WMwindow, RevertToNone, CurrentTime);
981#endif
982}
983
984int X11_EnterFullScreen(_THIS)
985{
986 int okay;
987#if 0
988 Window tmpwin, *windows;
989 int i, nwindows;
990#endif
991 int x = 0, y = 0;
992 int real_w, real_h;
993 int screen_w;
994 int screen_h;
995
996 okay = 1;
997 if ( currently_fullscreen ) {
998 return(okay);
999 }
1000
1001 /* Ungrab the input so that we can move the mouse around */
1002 X11_GrabInputNoLock(this, SDL_GRAB_OFF);
1003
1004#if SDL_VIDEO_DRIVER_X11_XINERAMA
1005 if ( use_xinerama &&
1006 window_w <= xinerama_info.width &&
1007 window_h <= xinerama_info.height ) {
1008 x = xinerama_info.x_org;
1009 y = xinerama_info.y_org;
1010 }
1011#endif /* SDL_VIDEO_DRIVER_X11_XINERAMA */
1012
1013 /* Map the fullscreen window to blank the screen */
1014 screen_w = DisplayWidth(SDL_Display, SDL_Screen);
1015 screen_h = DisplayHeight(SDL_Display, SDL_Screen);
1016 get_real_resolution(this, &real_w, &real_h);
1017 real_w = MAX(window_w, MAX(real_w, screen_w));
1018 real_h = MAX(window_h, MAX(real_h, screen_h));
1019 XMoveResizeWindow(SDL_Display, FSwindow,
1020 x, y, real_w, real_h);
1021 XMapRaised(SDL_Display, FSwindow);
1022 X11_WaitMapped(this, FSwindow);
1023
1024#if 0 /* This seems to break WindowMaker in focus-follows-mouse mode */
1025 /* Make sure we got to the top of the window stack */
1026 if ( XQueryTree(SDL_Display, SDL_Root, &tmpwin, &tmpwin,
1027 &windows, &nwindows) && windows ) {
1028 /* If not, try to put us there - if fail... oh well */
1029 if ( windows[nwindows-1] != FSwindow ) {
1030 tmpwin = windows[nwindows-1];
1031 for ( i=0; i<nwindows; ++i ) {
1032 if ( windows[i] == FSwindow ) {
1033 SDL_memcpy(&windows[i], &windows[i+1],
1034 (nwindows-i-1)*sizeof(windows[i]));
1035 break;
1036 }
1037 }
1038 windows[nwindows-1] = FSwindow;
1039 XRestackWindows(SDL_Display, windows, nwindows);
1040 XSync(SDL_Display, False);
1041 }
1042 XFree(windows);
1043 }
1044#else
1045 XRaiseWindow(SDL_Display, FSwindow);
1046#endif
1047
1048#if SDL_VIDEO_DRIVER_X11_VIDMODE
1049 /* Save the current video mode */
1050 if ( use_vidmode ) {
1051 SDL_NAME(XF86VidModeLockModeSwitch)(SDL_Display, SDL_Screen, True);
1052 save_mode(this);
1053 }
1054#endif
1055 currently_fullscreen = 1;
1056
1057 /* Set the new resolution */
1058 okay = X11_ResizeFullScreen(this);
1059 if ( ! okay ) {
1060 X11_LeaveFullScreen(this);
1061 }
1062 /* Set the colormap */
1063 if ( SDL_XColorMap ) {
1064 XInstallColormap(SDL_Display, SDL_XColorMap);
1065 }
1066 if ( okay ) {
1067 X11_GrabInputNoLock(this, this->input_grab | SDL_GRAB_FULLSCREEN);
1068 }
1069
1070 /* We may need to refresh the screen at this point (no backing store)
1071 We also don't get an event, which is why we explicitly refresh. */
1072 if ( this->screen ) {
1073 if ( this->screen->flags & SDL_OPENGL ) {
1074 SDL_PrivateExpose();
1075 } else {
1076 X11_RefreshDisplay(this);
1077 }
1078 }
1079
1080 return(okay);
1081}
1082
1083int X11_LeaveFullScreen(_THIS)
1084{
1085 if ( currently_fullscreen ) {
1086 XReparentWindow(SDL_Display, SDL_Window, WMwindow, 0, 0);
1087#if SDL_VIDEO_DRIVER_X11_VIDMODE
1088 if ( use_vidmode ) {
1089 restore_mode(this);
1090 SDL_NAME(XF86VidModeLockModeSwitch)(SDL_Display, SDL_Screen, False);
1091 }
1092#endif
1093
1094#if SDL_VIDEO_DRIVER_X11_XME
1095 if ( use_xme ) {
1096 int rw, rh;
1097
1098 /* check current mode so we can avoid uneccessary mode changes */
1099 get_real_resolution(this, &rw, &rh);
1100
1101 if (rw != saved_res.width || rh != saved_res.height) {
1102 XiGMiscChangeResolution(SDL_Display,
1103 SDL_Screen,
1104 0, /* view */
1105 saved_res.width,
1106 saved_res.height,
1107 0);
1108 XSync(SDL_Display, False);
1109 }
1110 }
1111#endif
1112
1113#if SDL_VIDEO_DRIVER_X11_XRANDR
1114 if ( use_xrandr ) {
1115 XRRSetScreenConfig(SDL_Display, screen_config, SDL_Root,
1116 saved_size_id, saved_rotation, CurrentTime);
1117 }
1118#endif
1119
1120 XUnmapWindow(SDL_Display, FSwindow);
1121 X11_WaitUnmapped(this, FSwindow);
1122 XSync(SDL_Display, True); /* Flush spurious mode change events */
1123 currently_fullscreen = 0;
1124 }
1125 /* If we get popped out of fullscreen mode for some reason, input_grab
1126 will still have the SDL_GRAB_FULLSCREEN flag set, since this is only
1127 temporary. In this case, release the grab unless the input has been
1128 explicitly grabbed.
1129 */
1130 X11_GrabInputNoLock(this, this->input_grab & ~SDL_GRAB_FULLSCREEN);
1131
1132 /* We may need to refresh the screen at this point (no backing store)
1133 We also don't get an event, which is why we explicitly refresh. */
1134 if ( this->screen ) {
1135 if ( this->screen->flags & SDL_OPENGL ) {
1136 SDL_PrivateExpose();
1137 } else {
1138 X11_RefreshDisplay(this);
1139 }
1140 }
1141
1142 return(0);
1143}
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11modes_c.h b/apps/plugins/sdl/src/video/x11/SDL_x11modes_c.h
deleted file mode 100644
index f7780bf213..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11modes_c.h
+++ /dev/null
@@ -1,43 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* Utilities for getting and setting the X display mode */
25
26#include "SDL_x11video.h"
27
28/* Define this if you want to grab the keyboard in fullscreen mode.
29 If you do not define this, SDL will return from SDL_SetVideoMode()
30 immediately, but will not actually go fullscreen until the window
31 manager is idle.
32*/
33#define GRAB_FULLSCREEN
34
35extern int X11_GetVideoModes(_THIS);
36extern SDL_Rect **X11_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
37extern void X11_FreeVideoModes(_THIS);
38extern int X11_ResizeFullScreen(_THIS);
39extern void X11_WaitMapped(_THIS, Window win);
40extern void X11_WaitUnmapped(_THIS, Window win);
41extern void X11_QueueEnterFullScreen(_THIS);
42extern int X11_EnterFullScreen(_THIS);
43extern int X11_LeaveFullScreen(_THIS);
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11mouse.c b/apps/plugins/sdl/src/video/x11/SDL_x11mouse.c
deleted file mode 100644
index 16ad739195..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11mouse.c
+++ /dev/null
@@ -1,288 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <X11/Xlib.h>
25#include <X11/Xutil.h>
26
27#include "SDL_mouse.h"
28#include "../../events/SDL_events_c.h"
29#include "../SDL_cursor_c.h"
30#include "SDL_x11dga_c.h"
31#include "SDL_x11mouse_c.h"
32
33
34/* The implementation dependent data for the window manager cursor */
35struct WMcursor {
36 Cursor x_cursor;
37};
38
39
40void X11_FreeWMCursor(_THIS, WMcursor *cursor)
41{
42 if ( SDL_Display != NULL ) {
43 SDL_Lock_EventThread();
44 XFreeCursor(SDL_Display, cursor->x_cursor);
45 XSync(SDL_Display, False);
46 SDL_Unlock_EventThread();
47 }
48 SDL_free(cursor);
49}
50
51WMcursor *X11_CreateWMCursor(_THIS,
52 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
53{
54 WMcursor *cursor;
55 XGCValues GCvalues;
56 GC GCcursor;
57 XImage *data_image, *mask_image;
58 Pixmap data_pixmap, mask_pixmap;
59 int clen, i;
60 char *x_data, *x_mask;
61 static XColor black = { 0, 0, 0, 0 };
62 static XColor white = { 0xffff, 0xffff, 0xffff, 0xffff };
63
64 /* Allocate the cursor memory */
65 cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor));
66 if ( cursor == NULL ) {
67 SDL_OutOfMemory();
68 return(NULL);
69 }
70
71 /* Mix the mask and the data */
72 clen = (w/8)*h;
73 x_data = (char *)SDL_malloc(clen);
74 if ( x_data == NULL ) {
75 SDL_free(cursor);
76 SDL_OutOfMemory();
77 return(NULL);
78 }
79 x_mask = (char *)SDL_malloc(clen);
80 if ( x_mask == NULL ) {
81 SDL_free(cursor);
82 SDL_free(x_data);
83 SDL_OutOfMemory();
84 return(NULL);
85 }
86 for ( i=0; i<clen; ++i ) {
87 /* The mask is OR'd with the data to turn inverted color
88 pixels black since inverted color cursors aren't supported
89 under X11.
90 */
91 x_mask[i] = data[i] | mask[i];
92 x_data[i] = data[i];
93 }
94
95 /* Prevent the event thread from running while we use the X server */
96 SDL_Lock_EventThread();
97
98 /* Create the data image */
99 data_image = XCreateImage(SDL_Display,
100 DefaultVisual(SDL_Display, SDL_Screen),
101 1, XYBitmap, 0, x_data, w, h, 8, w/8);
102 data_image->byte_order = MSBFirst;
103 data_image->bitmap_bit_order = MSBFirst;
104 data_pixmap = XCreatePixmap(SDL_Display, SDL_Root, w, h, 1);
105
106 /* Create the data mask */
107 mask_image = XCreateImage(SDL_Display,
108 DefaultVisual(SDL_Display, SDL_Screen),
109 1, XYBitmap, 0, x_mask, w, h, 8, w/8);
110 mask_image->byte_order = MSBFirst;
111 mask_image->bitmap_bit_order = MSBFirst;
112 mask_pixmap = XCreatePixmap(SDL_Display, SDL_Root, w, h, 1);
113
114 /* Create the graphics context */
115 GCvalues.function = GXcopy;
116 GCvalues.foreground = ~0;
117 GCvalues.background = 0;
118 GCvalues.plane_mask = AllPlanes;
119 GCcursor = XCreateGC(SDL_Display, data_pixmap,
120 (GCFunction|GCForeground|GCBackground|GCPlaneMask),
121 &GCvalues);
122
123 /* Blit the images to the pixmaps */
124 XPutImage(SDL_Display, data_pixmap, GCcursor, data_image,
125 0, 0, 0, 0, w, h);
126 XPutImage(SDL_Display, mask_pixmap, GCcursor, mask_image,
127 0, 0, 0, 0, w, h);
128 XFreeGC(SDL_Display, GCcursor);
129 /* These free the x_data and x_mask memory pointers */
130 XDestroyImage(data_image);
131 XDestroyImage(mask_image);
132
133 /* Create the cursor */
134 cursor->x_cursor = XCreatePixmapCursor(SDL_Display, data_pixmap,
135 mask_pixmap, &black, &white, hot_x, hot_y);
136 XFreePixmap(SDL_Display, data_pixmap);
137 XFreePixmap(SDL_Display, mask_pixmap);
138
139 /* Release the event thread */
140 XSync(SDL_Display, False);
141 SDL_Unlock_EventThread();
142
143 return(cursor);
144}
145
146int X11_ShowWMCursor(_THIS, WMcursor *cursor)
147{
148 /* Don't do anything if the display is gone */
149 if ( SDL_Display == NULL ) {
150 return(0);
151 }
152
153 /* Set the X11 cursor cursor, or blank if cursor is NULL */
154 if ( SDL_Window ) {
155 SDL_Lock_EventThread();
156 if ( cursor == NULL ) {
157 if ( SDL_BlankCursor != NULL ) {
158 XDefineCursor(SDL_Display, SDL_Window,
159 SDL_BlankCursor->x_cursor);
160 }
161 } else {
162 XDefineCursor(SDL_Display, SDL_Window, cursor->x_cursor);
163 }
164 XSync(SDL_Display, False);
165 SDL_Unlock_EventThread();
166 }
167 return(1);
168}
169
170void X11_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
171{
172 if ( using_dga & DGA_MOUSE ) {
173 SDL_PrivateMouseMotion(0, 0, x, y);
174 } else if ( mouse_relative) {
175 /* RJR: March 28, 2000
176 leave physical cursor at center of screen if
177 mouse hidden and grabbed */
178 SDL_PrivateMouseMotion(0, 0, x, y);
179 } else {
180 SDL_Lock_EventThread();
181 XWarpPointer(SDL_Display, None, SDL_Window, 0, 0, 0, 0, x, y);
182 XSync(SDL_Display, False);
183 SDL_Unlock_EventThread();
184 }
185}
186
187/* Sets the mouse acceleration from a string of the form:
188 2/1/0
189 The first number is the numerator, followed by the acceleration
190 denumenator and threshold.
191*/
192static void SetMouseAccel(_THIS, const char *accel_param)
193{
194 int i;
195 size_t len;
196 int accel_value[3];
197 char *mouse_param, *mouse_param_buf, *pin;
198
199 len = SDL_strlen(accel_param)+1;
200 mouse_param_buf = SDL_stack_alloc(char, len);
201 if ( ! mouse_param_buf ) {
202 return;
203 }
204 SDL_strlcpy(mouse_param_buf, accel_param, len);
205 mouse_param = mouse_param_buf;
206
207 for ( i=0; (i < 3) && mouse_param; ++i ) {
208 pin = SDL_strchr(mouse_param, '/');
209 if ( pin ) {
210 *pin = '\0';
211 }
212 accel_value[i] = atoi(mouse_param);
213 if ( pin ) {
214 mouse_param = pin+1;
215 } else {
216 mouse_param = NULL;
217 }
218 }
219 if ( i == 3 ) {
220 XChangePointerControl(SDL_Display, True, True,
221 accel_value[0], accel_value[1], accel_value[2]);
222 }
223 SDL_stack_free(mouse_param_buf);
224}
225
226/* Check to see if we need to enter or leave mouse relative mode */
227void X11_CheckMouseModeNoLock(_THIS)
228{
229 const Uint8 full_focus = (SDL_APPACTIVE|SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS);
230 char *env_override;
231 int enable_relative = 1;
232
233 /* This happens when quiting after an xio error */
234 if ( SDL_Display == NULL )
235 return;
236
237 /* Allow the user to override the relative mouse mode.
238 They almost never want to do this, as it seriously affects
239 applications that rely on continuous relative mouse motion.
240 */
241 env_override = SDL_getenv("SDL_MOUSE_RELATIVE");
242 if ( env_override ) {
243 enable_relative = atoi(env_override);
244 }
245
246 /* If the mouse is hidden and input is grabbed, we use relative mode */
247 if ( enable_relative &&
248 !(SDL_cursorstate & CURSOR_VISIBLE) &&
249 (this->input_grab != SDL_GRAB_OFF) &&
250 (SDL_GetAppState() & full_focus) == full_focus ) {
251 if ( ! mouse_relative ) {
252 X11_EnableDGAMouse(this);
253 if ( ! (using_dga & DGA_MOUSE) ) {
254 char *xmouse_accel;
255
256 SDL_GetMouseState(&mouse_last.x, &mouse_last.y);
257 /* Use as raw mouse mickeys as possible */
258 XGetPointerControl(SDL_Display,
259 &mouse_accel.numerator,
260 &mouse_accel.denominator,
261 &mouse_accel.threshold);
262 xmouse_accel=SDL_getenv("SDL_VIDEO_X11_MOUSEACCEL");
263 if ( xmouse_accel ) {
264 SetMouseAccel(this, xmouse_accel);
265 }
266 }
267 mouse_relative = 1;
268 }
269 } else {
270 if ( mouse_relative ) {
271 if ( using_dga & DGA_MOUSE ) {
272 X11_DisableDGAMouse(this);
273 } else {
274 XChangePointerControl(SDL_Display, True, True,
275 mouse_accel.numerator,
276 mouse_accel.denominator,
277 mouse_accel.threshold);
278 }
279 mouse_relative = 0;
280 }
281 }
282}
283void X11_CheckMouseMode(_THIS)
284{
285 SDL_Lock_EventThread();
286 X11_CheckMouseModeNoLock(this);
287 SDL_Unlock_EventThread();
288}
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11mouse_c.h b/apps/plugins/sdl/src/video/x11/SDL_x11mouse_c.h
deleted file mode 100644
index 03d97d86f6..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11mouse_c.h
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_x11video.h"
25
26/* Functions to be exported */
27extern void X11_FreeWMCursor(_THIS, WMcursor *cursor);
28extern WMcursor *X11_CreateWMCursor(_THIS,
29 Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);
30extern int X11_ShowWMCursor(_THIS, WMcursor *cursor);
31extern void X11_WarpWMCursor(_THIS, Uint16 x, Uint16 y);
32extern void X11_CheckMouseModeNoLock(_THIS);
33extern void X11_CheckMouseMode(_THIS);
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11sym.h b/apps/plugins/sdl/src/video/x11/SDL_x11sym.h
deleted file mode 100644
index 4875b989c9..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11sym.h
+++ /dev/null
@@ -1,201 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22
23SDL_X11_MODULE(BASEXLIB)
24SDL_X11_SYM(XClassHint*,XAllocClassHint,(void),(),return)
25SDL_X11_SYM(Status,XAllocColor,(Display* a,Colormap b,XColor* c),(a,b,c),return)
26SDL_X11_SYM(XSizeHints*,XAllocSizeHints,(void),(),return)
27SDL_X11_SYM(XWMHints*,XAllocWMHints,(void),(),return)
28SDL_X11_SYM(int,XChangePointerControl,(Display* a,Bool b,Bool c,int d,int e,int f),(a,b,c,d,e,f),return)
29SDL_X11_SYM(int,XChangeProperty,(Display* a,Window b,Atom c,Atom d,int e,int f,_Xconst unsigned char* g,int h),(a,b,c,d,e,f,g,h),return)
30SDL_X11_SYM(int,XChangeWindowAttributes,(Display* a,Window b,unsigned long c,XSetWindowAttributes* d),(a,b,c,d),return)
31SDL_X11_SYM(Bool,XCheckTypedEvent,(Display* a,int b,XEvent* c),(a,b,c),return)
32SDL_X11_SYM(int,XClearWindow,(Display* a,Window b),(a,b),return)
33SDL_X11_SYM(int,XCloseDisplay,(Display* a),(a),return)
34SDL_X11_SYM(Colormap,XCreateColormap,(Display* a,Window b,Visual* c,int d),(a,b,c,d),return)
35SDL_X11_SYM(Cursor,XCreatePixmapCursor,(Display* a,Pixmap b,Pixmap c,XColor* d,XColor* e,unsigned int f,unsigned int g),(a,b,c,d,e,f,g),return)
36SDL_X11_SYM(GC,XCreateGC,(Display* a,Drawable b,unsigned long c,XGCValues* d),(a,b,c,d),return)
37SDL_X11_SYM(XImage*,XCreateImage,(Display* a,Visual* b,unsigned int c,int d,int e,char* f,unsigned int g,unsigned int h,int i,int j),(a,b,c,d,e,f,g,h,i,j),return)
38SDL_X11_SYM(Pixmap,XCreatePixmap,(Display* a,Drawable b,unsigned int c,unsigned int d,unsigned int e),(a,b,c,d,e),return)
39SDL_X11_SYM(Pixmap,XCreatePixmapFromBitmapData,(Display* a,Drawable b,char* c,unsigned int d,unsigned int e,unsigned long f,unsigned long g,unsigned int h),(a,b,c,d,e,f,g,h),return)
40SDL_X11_SYM(Window,XCreateSimpleWindow,(Display* a,Window b,int c,int d,unsigned int e,unsigned int f,unsigned int g,unsigned long h,unsigned long i),(a,b,c,d,e,f,g,h,i),return)
41SDL_X11_SYM(Window,XCreateWindow,(Display* a,Window b,int c,int d,unsigned int e,unsigned int f,unsigned int g,int h,unsigned int i,Visual* j,unsigned long k,XSetWindowAttributes* l),(a,b,c,d,e,f,g,h,i,j,k,l),return)
42SDL_X11_SYM(int,XDefineCursor,(Display* a,Window b,Cursor c),(a,b,c),return)
43SDL_X11_SYM(int,XDeleteProperty,(Display* a,Window b,Atom c),(a,b,c),return)
44SDL_X11_SYM(int,XDestroyWindow,(Display* a,Window b),(a,b),return)
45SDL_X11_SYM(char*,XDisplayName,(_Xconst char* a),(a),return)
46SDL_X11_SYM(int,XEventsQueued,(Display* a,int b),(a,b),return)
47SDL_X11_SYM(Bool,XFilterEvent,(XEvent *event, Window w),(event,w),return)
48SDL_X11_SYM(int,XFlush,(Display* a),(a),return)
49SDL_X11_SYM(int,XFree,(void*a),(a),return)
50SDL_X11_SYM(int,XFreeColormap,(Display* a,Colormap b),(a,b),return)
51SDL_X11_SYM(int,XFreeColors,(Display* a,Colormap b,unsigned long* c,int d,unsigned long e),(a,b,c,d,e),return)
52SDL_X11_SYM(int,XFreeCursor,(Display* a,Cursor b),(a,b),return)
53SDL_X11_SYM(int,XFreeGC,(Display* a,GC b),(a,b),return)
54SDL_X11_SYM(int,XFreeModifiermap,(XModifierKeymap* a),(a),return)
55SDL_X11_SYM(int,XFreePixmap,(Display* a,Pixmap b),(a,b),return)
56SDL_X11_SYM(int,XGetErrorDatabaseText,(Display* a,_Xconst char* b,_Xconst char* c,_Xconst char* d,char* e,int f),(a,b,c,d,e,f),return)
57SDL_X11_SYM(XModifierKeymap*,XGetModifierMapping,(Display* a),(a),return)
58SDL_X11_SYM(int,XGetPointerControl,(Display* a,int* b,int* c,int* d),(a,b,c,d),return)
59SDL_X11_SYM(XVisualInfo*,XGetVisualInfo,(Display* a,long b,XVisualInfo* c,int* d),(a,b,c,d),return)
60SDL_X11_SYM(XWMHints*,XGetWMHints,(Display* a,Window b),(a,b),return)
61SDL_X11_SYM(Status,XGetWindowAttributes,(Display* a,Window b,XWindowAttributes* c),(a,b,c),return)
62SDL_X11_SYM(int,XGrabKeyboard,(Display* a,Window b,Bool c,int d,int e,Time f),(a,b,c,d,e,f),return)
63SDL_X11_SYM(int,XGrabPointer,(Display* a,Window b,Bool c,unsigned int d,int e,int f,Window g,Cursor h,Time i),(a,b,c,d,e,f,g,h,i),return)
64SDL_X11_SYM(Status,XIconifyWindow,(Display* a,Window b,int c),(a,b,c),return)
65SDL_X11_SYM(int,XInstallColormap,(Display* a,Colormap b),(a,b),return)
66SDL_X11_SYM(KeyCode,XKeysymToKeycode,(Display* a,KeySym b),(a,b),return)
67SDL_X11_SYM(Atom,XInternAtom,(Display* a,_Xconst char* b,Bool c),(a,b,c),return)
68SDL_X11_SYM(XPixmapFormatValues*,XListPixmapFormats,(Display* a,int* b),(a,b),return)
69SDL_X11_SYM(int,XLookupString,(XKeyEvent* a,char* b,int c,KeySym* d,XComposeStatus* e),(a,b,c,d,e),return)
70SDL_X11_SYM(int,XMapRaised,(Display* a,Window b),(a,b),return)
71SDL_X11_SYM(int,XMapWindow,(Display* a,Window b),(a,b),return)
72SDL_X11_SYM(int,XMaskEvent,(Display* a,long b,XEvent* c),(a,b,c),return)
73SDL_X11_SYM(Status,XMatchVisualInfo,(Display* a,int b,int c,int d,XVisualInfo* e),(a,b,c,d,e),return)
74SDL_X11_SYM(int,XMissingExtension,(Display* a,_Xconst char* b),(a,b),return)
75SDL_X11_SYM(int,XMoveResizeWindow,(Display* a,Window b,int c,int d,unsigned int e,unsigned int f),(a,b,c,d,e,f),return)
76SDL_X11_SYM(int,XMoveWindow,(Display* a,Window b,int c,int d),(a,b,c,d),return)
77SDL_X11_SYM(int,XNextEvent,(Display* a,XEvent* b),(a,b),return)
78SDL_X11_SYM(Display*,XOpenDisplay,(_Xconst char* a),(a),return)
79SDL_X11_SYM(int,XPeekEvent,(Display* a,XEvent* b),(a,b),return)
80SDL_X11_SYM(int,XPending,(Display* a),(a),return)
81SDL_X11_SYM(int,XPutImage,(Display* a,Drawable b,GC c,XImage* d,int e,int f,int g,int h,unsigned int i,unsigned int j),(a,b,c,d,e,f,g,h,i,j),return)
82SDL_X11_SYM(int,XQueryColors,(Display* a,Colormap b,XColor* c,int d),(a,b,c,d),return)
83SDL_X11_SYM(int,XQueryKeymap,(Display* a,char *b),(a,b),return)
84SDL_X11_SYM(Bool,XQueryPointer,(Display* a,Window b,Window* c,Window* d,int* e,int* f,int* g,int* h,unsigned int* i),(a,b,c,d,e,f,g,h,i),return)
85SDL_X11_SYM(int,XRaiseWindow,(Display* a,Window b),(a,b),return)
86SDL_X11_SYM(int,XReparentWindow,(Display* a,Window b,Window c,int d,int e),(a,b,c,d,e),return)
87SDL_X11_SYM(int,XResetScreenSaver,(Display* a),(a),return)
88SDL_X11_SYM(int,XResizeWindow,(Display* a,Window b,unsigned int c,unsigned int d),(a,b,c,d),return)
89SDL_X11_SYM(int,XSelectInput,(Display* a,Window b,long c),(a,b,c),return)
90SDL_X11_SYM(Status,XSendEvent,(Display* a,Window b,Bool c,long d,XEvent* e),(a,b,c,d,e),return)
91SDL_X11_SYM(int,XSetClassHint,(Display* a,Window b,XClassHint* c),(a,b,c),return)
92SDL_X11_SYM(XErrorHandler,XSetErrorHandler,(XErrorHandler a),(a),return)
93SDL_X11_SYM(XIOErrorHandler,XSetIOErrorHandler,(XIOErrorHandler a),(a),return)
94SDL_X11_SYM(int,XSetTransientForHint,(Display* a,Window b,Window c),(a,b,c),return)
95SDL_X11_SYM(int,XSetWMHints,(Display* a,Window b,XWMHints* c),(a,b,c),return)
96SDL_X11_SYM(void,XSetTextProperty,(Display* a,Window b,XTextProperty* c,Atom d),(a,b,c,d),)
97SDL_X11_SYM(void,XSetWMNormalHints,(Display* a,Window b,XSizeHints* c),(a,b,c),)
98SDL_X11_SYM(Status,XSetWMProtocols,(Display* a,Window b,Atom* c,int d),(a,b,c,d),return)
99SDL_X11_SYM(int,XSetWindowBackground,(Display* a,Window b,unsigned long c),(a,b,c),return)
100SDL_X11_SYM(int,XSetWindowBackgroundPixmap,(Display* a,Window b,Pixmap c),(a,b,c),return)
101SDL_X11_SYM(int,XSetWindowColormap,(Display* a,Window b,Colormap c),(a,b,c),return)
102SDL_X11_SYM(int,XStoreColors,(Display* a,Colormap b,XColor* c,int d),(a,b,c,d),return)
103SDL_X11_SYM(Status,XStringListToTextProperty,(char** a,int b,XTextProperty* c),(a,b,c),return)
104SDL_X11_SYM(int,XSync,(Display* a,Bool b),(a,b),return)
105SDL_X11_SYM(int,XUngrabKeyboard,(Display* a,Time b),(a,b),return)
106SDL_X11_SYM(int,XUngrabPointer,(Display* a,Time b),(a,b),return)
107SDL_X11_SYM(int,XUnmapWindow,(Display* a,Window b),(a,b),return)
108SDL_X11_SYM(int,XWarpPointer,(Display* a,Window b,Window c,int d,int e,unsigned int f,unsigned int g,int h, int i),(a,b,c,d,e,f,g,h,i),return)
109SDL_X11_SYM(VisualID,XVisualIDFromVisual,(Visual* a),(a),return)
110SDL_X11_SYM(XExtDisplayInfo*,XextAddDisplay,(XExtensionInfo* a,Display* b,char* c,XExtensionHooks* d,int e,XPointer f),(a,b,c,d,e,f),return)
111SDL_X11_SYM(XExtensionInfo*,XextCreateExtension,(void),(),return)
112SDL_X11_SYM(void,XextDestroyExtension,(XExtensionInfo* a),(a),)
113SDL_X11_SYM(XExtDisplayInfo*,XextFindDisplay,(XExtensionInfo* a,Display* b),(a,b),return)
114SDL_X11_SYM(int,XextRemoveDisplay,(XExtensionInfo* a,Display* b),(a,b),return)
115SDL_X11_SYM(Bool,XQueryExtension,(Display* a,_Xconst char* b,int* c,int* d,int* e),(a,b,c,d,e),return)
116SDL_X11_SYM(char *,XDisplayString,(Display* a),(a),return)
117SDL_X11_SYM(int,XGetErrorText,(Display* a,int b,char* c,int d),(a,b,c,d),return)
118SDL_X11_SYM(void,_XEatData,(Display* a,unsigned long b),(a,b),)
119SDL_X11_SYM(void,_XFlush,(Display* a),(a),)
120SDL_X11_SYM(void,_XFlushGCCache,(Display* a,GC b),(a,b),)
121SDL_X11_SYM(int,_XRead,(Display* a,char* b,long c),(a,b,c),return)
122SDL_X11_SYM(void,_XReadPad,(Display* a,char* b,long c),(a,b,c),)
123SDL_X11_SYM(void,_XSend,(Display* a,_Xconst char* b,long c),(a,b,c),)
124SDL_X11_SYM(Status,_XReply,(Display* a,xReply* b,int c,Bool d),(a,b,c,d),return)
125SDL_X11_SYM(unsigned long,_XSetLastRequestRead,(Display* a,xGenericReply* b),(a,b),return)
126SDL_X11_SYM(SDL_X11_XSynchronizeRetType,XSynchronize,(Display* a,Bool b),(a,b),return)
127SDL_X11_SYM(SDL_X11_XESetWireToEventRetType,XESetWireToEvent,(Display* a,int b,SDL_X11_XESetWireToEventRetType c),(a,b,c),return)
128SDL_X11_SYM(SDL_X11_XESetEventToWireRetType,XESetEventToWire,(Display* a,int b,SDL_X11_XESetEventToWireRetType c),(a,b,c),return)
129SDL_X11_SYM(XExtensionErrorHandler,XSetExtensionErrorHandler,(XExtensionErrorHandler a),(a),return)
130
131#if NeedWidePrototypes
132SDL_X11_SYM(KeySym,XKeycodeToKeysym,(Display* a,unsigned int b,int c),(a,b,c),return)
133#else
134SDL_X11_SYM(KeySym,XKeycodeToKeysym,(Display* a,KeyCode b,int c),(a,b,c),return)
135#endif
136
137#ifdef X_HAVE_UTF8_STRING
138SDL_X11_MODULE(UTF8)
139SDL_X11_SYM(int,Xutf8TextListToTextProperty,(Display* a,char** b,int c,XICCEncodingStyle d,XTextProperty* e),(a,b,c,d,e),return)
140SDL_X11_SYM(int,Xutf8LookupString,(XIC a,XKeyPressedEvent* b,char* c,int d,KeySym* e,Status* f),(a,b,c,d,e,f),return)
141/*SDL_X11_SYM(XIC,XCreateIC,(XIM, ...),return) !!! ARGH! */
142SDL_X11_SYM(void,XDestroyIC,(XIC a),(a),)
143SDL_X11_SYM(void,XSetICFocus,(XIC a),(a),)
144SDL_X11_SYM(void,XUnsetICFocus,(XIC a),(a),)
145/*SDL_X11_SYM(char*,XGetICValues,(XIC a, ...),return)*/
146SDL_X11_SYM(XIM,XOpenIM,(Display* a,struct _XrmHashBucketRec* b,char* c,char* d),(a,b,c,d),return)
147SDL_X11_SYM(Status,XCloseIM,(XIM a),(a),return)
148SDL_X11_SYM(char*,XSetLocaleModifiers,(_Xconst char* a),(a),return)
149SDL_X11_SYM(int,XRefreshKeyboardMapping,(XMappingEvent* a),(a),return)
150SDL_X11_SYM(Display*,XDisplayOfIM,(XIM a),(a),return)
151#endif
152
153#ifndef NO_SHARED_MEMORY
154SDL_X11_MODULE(SHM)
155SDL_X11_SYM(Status,XShmAttach,(Display* a,XShmSegmentInfo* b),(a,b),return)
156SDL_X11_SYM(Status,XShmDetach,(Display* a,XShmSegmentInfo* b),(a,b),return)
157SDL_X11_SYM(Status,XShmPutImage,(Display* a,Drawable b,GC c,XImage* d,int e,int f,int g,int h,unsigned int i,unsigned int j,Bool k),(a,b,c,d,e,f,g,h,i,j,k),return)
158SDL_X11_SYM(XImage*,XShmCreateImage,(Display* a,Visual* b,unsigned int c,int d,char* e,XShmSegmentInfo* f,unsigned int g,unsigned int h),(a,b,c,d,e,f,g,h),return)
159SDL_X11_SYM(Bool,XShmQueryExtension,(Display* a),(a),return)
160#endif
161
162/*
163 * Not required...these only exist in code in headers on some 64-bit platforms,
164 * and are removed via macros elsewhere, so it's safe for them to be missing.
165 */
166#ifdef LONG64
167SDL_X11_MODULE(IO_32BIT)
168SDL_X11_SYM(int,_XData32,(Display *dpy,register long *data,unsigned len),(dpy,data,len),return)
169SDL_X11_SYM(void,_XRead32,(Display *dpy,register long *data,long len),(dpy,data,len),)
170#endif
171
172/*
173 * libX11 1.4.99.1 added _XGetRequest, and macros use it behind the scenes.
174 */
175SDL_X11_MODULE(XGETREQUEST)
176SDL_X11_SYM(void *,_XGetRequest,(Display* a,CARD8 b,size_t c),(a,b,c),return)
177
178/*
179 * These only show up on some variants of Unix.
180 */
181#if defined(__osf__)
182SDL_X11_MODULE(OSF_ENTRY_POINTS)
183SDL_X11_SYM(void,_SmtBufferOverflow,(Display *dpy,register smtDisplayPtr p),(dpy,p),)
184SDL_X11_SYM(void,_SmtIpError,(Display *dpy,register smtDisplayPtr p, int i),(dpy,p,i),)
185SDL_X11_SYM(int,ipAllocateData,(ChannelPtr a, IPCard b, IPDataPtr * c),(a,b,c),return)
186SDL_X11_SYM(int,ipUnallocateAndSendData,(ChannelPtr a, IPCard b),(a,b),return)
187#endif
188
189/* Xrandr support. */
190#if SDL_VIDEO_DRIVER_X11_XRANDR
191SDL_X11_MODULE(XRANDR)
192SDL_X11_SYM(Status,XRRQueryVersion,(Display *dpy,int *major_versionp,int *minor_versionp),(dpy,major_versionp,minor_versionp),return)
193SDL_X11_SYM(XRRScreenConfiguration *,XRRGetScreenInfo,(Display *dpy,Drawable draw),(dpy,draw),return)
194SDL_X11_SYM(SizeID,XRRConfigCurrentConfiguration,(XRRScreenConfiguration *config,Rotation *rotation),(config,rotation),return)
195SDL_X11_SYM(XRRScreenSize *,XRRConfigSizes,(XRRScreenConfiguration *config, int *nsizes),(config,nsizes),return)
196SDL_X11_SYM(Status,XRRSetScreenConfig,(Display *dpy, XRRScreenConfiguration *config, Drawable draw, int size_index, Rotation rotation, Time timestamp),(dpy,config,draw,size_index,rotation,timestamp),return)
197SDL_X11_SYM(void,XRRFreeScreenConfigInfo,(XRRScreenConfiguration *config),(config),)
198#endif
199
200/* end of SDL_x11sym.h ... */
201
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11video.c b/apps/plugins/sdl/src/video/x11/SDL_x11video.c
deleted file mode 100644
index f7d80732c0..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11video.c
+++ /dev/null
@@ -1,1571 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* X11 based SDL video driver implementation.
25 Note: This implementation does not currently need X11 thread locking,
26 since the event thread uses a separate X connection and any
27 additional locking necessary is handled internally. However,
28 if full locking is neccessary, take a look at XInitThreads().
29*/
30
31#include <unistd.h>
32#include <sys/ioctl.h>
33#ifdef MTRR_SUPPORT
34#include <asm/mtrr.h>
35#include <sys/fcntl.h>
36#endif
37
38#include "SDL_endian.h"
39#include "SDL_timer.h"
40#include "SDL_thread.h"
41#include "SDL_video.h"
42#include "SDL_mouse.h"
43#include "../SDL_sysvideo.h"
44#include "../SDL_pixels_c.h"
45#include "../../events/SDL_events_c.h"
46#include "SDL_x11video.h"
47#include "SDL_x11wm_c.h"
48#include "SDL_x11mouse_c.h"
49#include "SDL_x11events_c.h"
50#include "SDL_x11modes_c.h"
51#include "SDL_x11image_c.h"
52#include "SDL_x11yuv_c.h"
53#include "SDL_x11gl_c.h"
54#include "SDL_x11gamma_c.h"
55#include "../blank_cursor.h"
56
57#ifdef X_HAVE_UTF8_STRING
58#include <locale.h>
59#endif
60
61/* Initialization/Query functions */
62static int X11_VideoInit(_THIS, SDL_PixelFormat *vformat);
63static SDL_Surface *X11_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
64static int X11_ToggleFullScreen(_THIS, int on);
65static void X11_UpdateMouse(_THIS);
66static int X11_SetColors(_THIS, int firstcolor, int ncolors,
67 SDL_Color *colors);
68static int X11_SetGammaRamp(_THIS, Uint16 *ramp);
69static void X11_VideoQuit(_THIS);
70
71
72/* X11 driver bootstrap functions */
73
74static int X11_Available(void)
75{
76 Display *display = NULL;
77 if ( SDL_X11_LoadSymbols() ) {
78 display = XOpenDisplay(NULL);
79 if ( display != NULL ) {
80 XCloseDisplay(display);
81 }
82 SDL_X11_UnloadSymbols();
83 }
84 return(display != NULL);
85}
86
87static void X11_DeleteDevice(SDL_VideoDevice *device)
88{
89 if ( device ) {
90 if ( device->hidden ) {
91 SDL_free(device->hidden);
92 }
93 if ( device->gl_data ) {
94 SDL_free(device->gl_data);
95 }
96 SDL_free(device);
97 SDL_X11_UnloadSymbols();
98 }
99}
100
101static SDL_VideoDevice *X11_CreateDevice(int devindex)
102{
103 SDL_VideoDevice *device = NULL;
104
105 if ( SDL_X11_LoadSymbols() ) {
106 /* Initialize all variables that we clean on shutdown */
107 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
108 if ( device ) {
109 SDL_memset(device, 0, (sizeof *device));
110 device->hidden = (struct SDL_PrivateVideoData *)
111 SDL_malloc((sizeof *device->hidden));
112 device->gl_data = (struct SDL_PrivateGLData *)
113 SDL_malloc((sizeof *device->gl_data));
114 }
115 if ( (device == NULL) || (device->hidden == NULL) ||
116 (device->gl_data == NULL) ) {
117 SDL_OutOfMemory();
118 X11_DeleteDevice(device); /* calls SDL_X11_UnloadSymbols(). */
119 return(0);
120 }
121 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
122 SDL_memset(device->gl_data, 0, (sizeof *device->gl_data));
123
124#if SDL_VIDEO_OPENGL_GLX
125 device->gl_data->swap_interval = -1;
126#endif
127
128 /* Set the driver flags */
129 device->handles_any_size = 1;
130
131 /* Set the function pointers */
132 device->VideoInit = X11_VideoInit;
133 device->ListModes = X11_ListModes;
134 device->SetVideoMode = X11_SetVideoMode;
135 device->ToggleFullScreen = X11_ToggleFullScreen;
136 device->UpdateMouse = X11_UpdateMouse;
137#if SDL_VIDEO_DRIVER_X11_XV
138 device->CreateYUVOverlay = X11_CreateYUVOverlay;
139#endif
140 device->SetColors = X11_SetColors;
141 device->UpdateRects = NULL;
142 device->VideoQuit = X11_VideoQuit;
143 device->AllocHWSurface = X11_AllocHWSurface;
144 device->CheckHWBlit = NULL;
145 device->FillHWRect = NULL;
146 device->SetHWColorKey = NULL;
147 device->SetHWAlpha = NULL;
148 device->LockHWSurface = X11_LockHWSurface;
149 device->UnlockHWSurface = X11_UnlockHWSurface;
150 device->FlipHWSurface = X11_FlipHWSurface;
151 device->FreeHWSurface = X11_FreeHWSurface;
152 device->SetGamma = X11_SetVidModeGamma;
153 device->GetGamma = X11_GetVidModeGamma;
154 device->SetGammaRamp = X11_SetGammaRamp;
155 device->GetGammaRamp = NULL;
156#if SDL_VIDEO_OPENGL_GLX
157 device->GL_LoadLibrary = X11_GL_LoadLibrary;
158 device->GL_GetProcAddress = X11_GL_GetProcAddress;
159 device->GL_GetAttribute = X11_GL_GetAttribute;
160 device->GL_MakeCurrent = X11_GL_MakeCurrent;
161 device->GL_SwapBuffers = X11_GL_SwapBuffers;
162#endif
163 device->SetCaption = X11_SetCaption;
164 device->SetIcon = X11_SetIcon;
165 device->IconifyWindow = X11_IconifyWindow;
166 device->GrabInput = X11_GrabInput;
167 device->GetWMInfo = X11_GetWMInfo;
168 device->FreeWMCursor = X11_FreeWMCursor;
169 device->CreateWMCursor = X11_CreateWMCursor;
170 device->ShowWMCursor = X11_ShowWMCursor;
171 device->WarpWMCursor = X11_WarpWMCursor;
172 device->CheckMouseMode = X11_CheckMouseMode;
173 device->InitOSKeymap = X11_InitOSKeymap;
174 device->PumpEvents = X11_PumpEvents;
175
176 device->free = X11_DeleteDevice;
177 }
178
179 return device;
180}
181
182VideoBootStrap X11_bootstrap = {
183 "x11", "X Window System",
184 X11_Available, X11_CreateDevice
185};
186
187/* Normal X11 error handler routine */
188static int (*X_handler)(Display *, XErrorEvent *) = NULL;
189static int x_errhandler(Display *d, XErrorEvent *e)
190{
191#if SDL_VIDEO_DRIVER_X11_VIDMODE
192 extern int vm_error;
193#endif
194#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
195 extern int dga_error;
196#endif
197
198#if SDL_VIDEO_DRIVER_X11_VIDMODE
199 /* VidMode errors are non-fatal. :) */
200 /* Are the errors offset by one from the error base?
201 e.g. the error base is 143, the code is 148, and the
202 actual error is XF86VidModeExtensionDisabled (4) ?
203 */
204 if ( (vm_error >= 0) &&
205 (((e->error_code == BadRequest)&&(e->request_code == vm_error)) ||
206 ((e->error_code > vm_error) &&
207 (e->error_code <= (vm_error+XF86VidModeNumberErrors)))) ) {
208#ifdef X11_DEBUG
209{ char errmsg[1024];
210 XGetErrorText(d, e->error_code, errmsg, sizeof(errmsg));
211printf("VidMode error: %s\n", errmsg);
212}
213#endif
214 return(0);
215 }
216#endif /* SDL_VIDEO_DRIVER_X11_VIDMODE */
217
218#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
219 /* DGA errors can be non-fatal. :) */
220 if ( (dga_error >= 0) &&
221 ((e->error_code > dga_error) &&
222 (e->error_code <= (dga_error+XF86DGANumberErrors))) ) {
223#ifdef X11_DEBUG
224{ char errmsg[1024];
225 XGetErrorText(d, e->error_code, errmsg, sizeof(errmsg));
226printf("DGA error: %s\n", errmsg);
227}
228#endif
229 return(0);
230 }
231#endif /* SDL_VIDEO_DRIVER_X11_DGAMOUSE */
232
233 return(X_handler(d,e));
234}
235
236/* X11 I/O error handler routine */
237static int (*XIO_handler)(Display *) = NULL;
238static int xio_errhandler(Display *d)
239{
240 /* Ack! Lost X11 connection! */
241
242 /* We will crash if we try to clean up our display */
243 if ( SDL_VideoSurface && current_video->hidden->Ximage ) {
244 SDL_VideoSurface->pixels = NULL;
245 }
246 current_video->hidden->X11_Display = NULL;
247
248 /* Continue with the standard X11 error handler */
249 return(XIO_handler(d));
250}
251
252static int (*Xext_handler)(Display *, _Xconst char *, _Xconst char *) = NULL;
253static int xext_errhandler(Display *d, _Xconst char *ext, _Xconst char *reason)
254{
255#ifdef X11_DEBUG
256 printf("Xext error inside SDL (may be harmless):\n");
257 printf(" Extension \"%s\" %s on display \"%s\".\n",
258 ext, reason, XDisplayString(d));
259#endif
260
261 if (SDL_strcmp(reason, "missing") == 0) {
262 /*
263 * Since the query itself, elsewhere, can handle a missing extension
264 * and the default behaviour in Xlib is to write to stderr, which
265 * generates unnecessary bug reports, we just ignore these.
266 */
267 return 0;
268 }
269
270 /* Everything else goes to the default handler... */
271 return Xext_handler(d, ext, reason);
272}
273
274/* Find out what class name we should use */
275static char *get_classname(char *classname, int maxlen)
276{
277 char *spot;
278#if defined(__LINUX__) || defined(__FREEBSD__)
279 char procfile[1024];
280 char linkfile[1024];
281 int linksize;
282#endif
283
284 /* First allow environment variable override */
285 spot = SDL_getenv("SDL_VIDEO_X11_WMCLASS");
286 if ( spot ) {
287 SDL_strlcpy(classname, spot, maxlen);
288 return classname;
289 }
290
291 /* Next look at the application's executable name */
292#if defined(__LINUX__) || defined(__FREEBSD__)
293#if defined(__LINUX__)
294 SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/exe", getpid());
295#elif defined(__FREEBSD__)
296 SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/file", getpid());
297#else
298#error Where can we find the executable name?
299#endif
300 linksize = readlink(procfile, linkfile, sizeof(linkfile)-1);
301 if ( linksize > 0 ) {
302 linkfile[linksize] = '\0';
303 spot = SDL_strrchr(linkfile, '/');
304 if ( spot ) {
305 SDL_strlcpy(classname, spot+1, maxlen);
306 } else {
307 SDL_strlcpy(classname, linkfile, maxlen);
308 }
309 return classname;
310 }
311#endif /* __LINUX__ */
312
313 /* Finally use the default we've used forever */
314 SDL_strlcpy(classname, "SDL_App", maxlen);
315 return classname;
316}
317
318/* Create auxiliary (toplevel) windows with the current visual */
319static void create_aux_windows(_THIS)
320{
321 int x = 0, y = 0;
322 char classname[1024];
323 XSetWindowAttributes xattr;
324 XWMHints *hints;
325 unsigned long app_event_mask;
326 int def_vis = (SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen));
327
328 /* Look up some useful Atoms */
329 WM_DELETE_WINDOW = XInternAtom(SDL_Display, "WM_DELETE_WINDOW", False);
330
331 /* Don't create any extra windows if we are being managed */
332 if ( SDL_windowid ) {
333 FSwindow = 0;
334 WMwindow = SDL_strtol(SDL_windowid, NULL, 0);
335 return;
336 }
337
338 if(FSwindow)
339 XDestroyWindow(SDL_Display, FSwindow);
340
341#if SDL_VIDEO_DRIVER_X11_XINERAMA
342 if ( use_xinerama ) {
343 x = xinerama_info.x_org;
344 y = xinerama_info.y_org;
345 }
346#endif
347 xattr.override_redirect = True;
348 xattr.background_pixel = def_vis ? BlackPixel(SDL_Display, SDL_Screen) : 0;
349 xattr.border_pixel = 0;
350 xattr.colormap = SDL_XColorMap;
351
352 FSwindow = XCreateWindow(SDL_Display, SDL_Root,
353 x, y, 32, 32, 0,
354 this->hidden->depth, InputOutput, SDL_Visual,
355 CWOverrideRedirect | CWBackPixel | CWBorderPixel
356 | CWColormap,
357 &xattr);
358
359 XSelectInput(SDL_Display, FSwindow, StructureNotifyMask);
360
361 /* Tell KDE to keep the fullscreen window on top */
362 {
363 XEvent ev;
364 long mask;
365
366 SDL_memset(&ev, 0, sizeof(ev));
367 ev.xclient.type = ClientMessage;
368 ev.xclient.window = SDL_Root;
369 ev.xclient.message_type = XInternAtom(SDL_Display,
370 "KWM_KEEP_ON_TOP", False);
371 ev.xclient.format = 32;
372 ev.xclient.data.l[0] = FSwindow;
373 ev.xclient.data.l[1] = CurrentTime;
374 mask = SubstructureRedirectMask;
375 XSendEvent(SDL_Display, SDL_Root, False, mask, &ev);
376 }
377
378 hints = NULL;
379 if(WMwindow) {
380 /* All window attributes must survive the recreation */
381 hints = XGetWMHints(SDL_Display, WMwindow);
382 XDestroyWindow(SDL_Display, WMwindow);
383 }
384
385 /* Create the window for windowed management */
386 /* (reusing the xattr structure above) */
387 WMwindow = XCreateWindow(SDL_Display, SDL_Root,
388 x, y, 32, 32, 0,
389 this->hidden->depth, InputOutput, SDL_Visual,
390 CWBackPixel | CWBorderPixel | CWColormap,
391 &xattr);
392
393 /* Set the input hints so we get keyboard input */
394 if(!hints) {
395 hints = XAllocWMHints();
396 hints->input = True;
397 hints->flags = InputHint;
398 }
399 XSetWMHints(SDL_Display, WMwindow, hints);
400 XFree(hints);
401 X11_SetCaptionNoLock(this, this->wm_title, this->wm_icon);
402
403 app_event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
404 | PropertyChangeMask | StructureNotifyMask | KeymapStateMask;
405 XSelectInput(SDL_Display, WMwindow, app_event_mask);
406
407 /* Set the class hints so we can get an icon (AfterStep) */
408 get_classname(classname, sizeof(classname));
409 {
410 XClassHint *classhints;
411 classhints = XAllocClassHint();
412 if(classhints != NULL) {
413 classhints->res_name = classname;
414 classhints->res_class = classname;
415 XSetClassHint(SDL_Display, WMwindow, classhints);
416 XFree(classhints);
417 }
418 }
419
420 {
421 pid_t pid = getpid();
422 char hostname[256];
423
424 if (pid > 0 && gethostname(hostname, sizeof(hostname)) > -1) {
425 Atom _NET_WM_PID = XInternAtom(SDL_Display, "_NET_WM_PID", False);
426 Atom WM_CLIENT_MACHINE = XInternAtom(SDL_Display, "WM_CLIENT_MACHINE", False);
427
428 hostname[sizeof(hostname)-1] = '\0';
429 XChangeProperty(SDL_Display, WMwindow, _NET_WM_PID, XA_CARDINAL, 32,
430 PropModeReplace, (unsigned char *)&pid, 1);
431 XChangeProperty(SDL_Display, WMwindow, WM_CLIENT_MACHINE, XA_STRING, 8,
432 PropModeReplace, (unsigned char *)hostname, SDL_strlen(hostname));
433 }
434 }
435
436 /* Setup the communication with the IM server */
437 /* create_aux_windows may be called several times against the same
438 Display. We should reuse the SDL_IM if one has been opened for
439 the Display, so we should not simply reset SDL_IM here. */
440
441 #ifdef X_HAVE_UTF8_STRING
442 if (SDL_X11_HAVE_UTF8) {
443 /* Discard obsolete resources if any. */
444 if (SDL_IM != NULL && SDL_Display != XDisplayOfIM(SDL_IM)) {
445 /* Just a double check. I don't think this
446 code is ever executed. */
447 SDL_SetError("display has changed while an IM is kept");
448 if (SDL_IC) {
449 XUnsetICFocus(SDL_IC);
450 XDestroyIC(SDL_IC);
451 SDL_IC = NULL;
452 }
453 XCloseIM(SDL_IM);
454 SDL_IM = NULL;
455 }
456
457 /* Open an input method. */
458 if (SDL_IM == NULL) {
459 char *old_locale = NULL, *old_modifiers = NULL;
460 const char *p;
461 size_t n;
462 /* I'm not comfortable to do locale setup
463 here. However, we need C library locale
464 (and xlib modifiers) to be set based on the
465 user's preference to use XIM, and many
466 existing game programs doesn't take care of
467 users' locale preferences, so someone other
468 than the game program should do it.
469 Moreover, ones say that some game programs
470 heavily rely on the C locale behaviour,
471 e.g., strcol()'s, and we can't change the C
472 library locale. Given the situation, I
473 couldn't find better place to do the
474 job... */
475
476 /* Save the current (application program's)
477 locale settings. */
478 p = setlocale(LC_ALL, NULL);
479 if ( p ) {
480 n = SDL_strlen(p)+1;
481 old_locale = SDL_stack_alloc(char, n);
482 if ( old_locale ) {
483 SDL_strlcpy(old_locale, p, n);
484 }
485 }
486 p = XSetLocaleModifiers(NULL);
487 if ( p ) {
488 n = SDL_strlen(p)+1;
489 old_modifiers = SDL_stack_alloc(char, n);
490 if ( old_modifiers ) {
491 SDL_strlcpy(old_modifiers, p, n);
492 }
493 }
494
495 /* Fetch the user's preferences and open the
496 input method with them. */
497 setlocale(LC_ALL, "");
498 XSetLocaleModifiers("");
499 SDL_IM = XOpenIM(SDL_Display, NULL, classname, classname);
500
501 /* Restore the application's locale settings
502 so that we don't break the application's
503 expected behaviour. */
504 if ( old_locale ) {
505 /* We need to restore the C library
506 locale first, since the
507 interpretation of the X modifier
508 may depend on it. */
509 setlocale(LC_ALL, old_locale);
510 SDL_stack_free(old_locale);
511 }
512 if ( old_modifiers ) {
513 XSetLocaleModifiers(old_modifiers);
514 SDL_stack_free(old_modifiers);
515 }
516 }
517
518 /* Create a new input context for the new window just created. */
519 if (SDL_IM == NULL) {
520 SDL_SetError("no input method could be opened");
521 } else {
522 if (SDL_IC != NULL) {
523 /* Discard the old IC before creating new one. */
524 XUnsetICFocus(SDL_IC);
525 XDestroyIC(SDL_IC);
526 }
527 /* Theoretically we should check the current IM supports
528 PreeditNothing+StatusNothing style (i.e., root window method)
529 before creating the IC. However, it is the bottom line method,
530 and we supports any other options. If the IM didn't support
531 root window method, the following call fails, and SDL falls
532 back to pre-XIM keyboard handling. */
533 SDL_IC = pXCreateIC(SDL_IM,
534 XNClientWindow, WMwindow,
535 XNFocusWindow, WMwindow,
536 XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
537 XNResourceName, classname,
538 XNResourceClass, classname,
539 NULL);
540
541 if (SDL_IC == NULL) {
542 SDL_SetError("no input context could be created");
543 XCloseIM(SDL_IM);
544 SDL_IM = NULL;
545 } else {
546 /* We need to receive X events that an IM wants and to pass
547 them to the IM through XFilterEvent. The set of events may
548 vary depending on the IM implementation and the options
549 specified through various routes. Although unlikely, the
550 xlib specification allows IM to change the event requirement
551 with its own circumstances, it is safe to call SelectInput
552 whenever we re-create an IC. */
553 unsigned long mask = 0;
554 char *ret = pXGetICValues(SDL_IC, XNFilterEvents, &mask, NULL);
555 if (ret != NULL) {
556 XUnsetICFocus(SDL_IC);
557 XDestroyIC(SDL_IC);
558 SDL_IC = NULL;
559 SDL_SetError("no input context could be created");
560 XCloseIM(SDL_IM);
561 SDL_IM = NULL;
562 } else {
563 XSelectInput(SDL_Display, WMwindow, app_event_mask | mask);
564 XSetICFocus(SDL_IC);
565 }
566 }
567 }
568 }
569 #endif
570
571 /* Allow the window to be deleted by the window manager */
572 XSetWMProtocols(SDL_Display, WMwindow, &WM_DELETE_WINDOW, 1);
573}
574
575static int X11_VideoInit(_THIS, SDL_PixelFormat *vformat)
576{
577 const char *env;
578 char *display;
579 int i;
580
581 /* Open the X11 display */
582 display = NULL; /* Get it from DISPLAY environment variable */
583
584 if ( (SDL_strncmp(XDisplayName(display), ":", 1) == 0) ||
585 (SDL_strncmp(XDisplayName(display), "unix:", 5) == 0) ) {
586 local_X11 = 1;
587 } else {
588 local_X11 = 0;
589 }
590 SDL_Display = XOpenDisplay(display);
591#if defined(__osf__) && defined(SDL_VIDEO_DRIVER_X11_DYNAMIC)
592 /* On Tru64 if linking without -lX11, it fails and you get following message.
593 * Xlib: connection to ":0.0" refused by server
594 * Xlib: XDM authorization key matches an existing client!
595 *
596 * It succeeds if retrying 1 second later
597 * or if running xhost +localhost on shell.
598 *
599 */
600 if ( SDL_Display == NULL ) {
601 SDL_Delay(1000);
602 SDL_Display = XOpenDisplay(display);
603 }
604#endif
605 if ( SDL_Display == NULL ) {
606 SDL_SetError("Couldn't open X11 display");
607 return(-1);
608 }
609#ifdef X11_DEBUG
610 XSynchronize(SDL_Display, True);
611#endif
612
613 /* Create an alternate X display for graphics updates -- allows us
614 to do graphics updates in a separate thread from event handling.
615 Thread-safe X11 doesn't seem to exist.
616 */
617 GFX_Display = XOpenDisplay(display);
618 if ( GFX_Display == NULL ) {
619 XCloseDisplay(SDL_Display);
620 SDL_Display = NULL;
621 SDL_SetError("Couldn't open X11 display");
622 return(-1);
623 }
624
625 /* Set the normal X error handler */
626 X_handler = XSetErrorHandler(x_errhandler);
627
628 /* Set the error handler if we lose the X display */
629 XIO_handler = XSetIOErrorHandler(xio_errhandler);
630
631 /* Set the X extension error handler */
632 Xext_handler = XSetExtensionErrorHandler(xext_errhandler);
633
634 /* use default screen (from $DISPLAY) */
635 SDL_Screen = DefaultScreen(SDL_Display);
636
637#ifndef NO_SHARED_MEMORY
638 /* Check for MIT shared memory extension */
639 use_mitshm = 0;
640 if ( local_X11 ) {
641 use_mitshm = XShmQueryExtension(SDL_Display);
642 }
643#endif /* NO_SHARED_MEMORY */
644
645 /* Get the available video modes */
646 if(X11_GetVideoModes(this) < 0) {
647 XCloseDisplay(GFX_Display);
648 GFX_Display = NULL;
649 XCloseDisplay(SDL_Display);
650 SDL_Display = NULL;
651 return -1;
652 }
653
654 /* Determine the current screen size */
655 this->info.current_w = DisplayWidth(SDL_Display, SDL_Screen);
656 this->info.current_h = DisplayHeight(SDL_Display, SDL_Screen);
657
658 /* Determine the default screen depth:
659 Use the default visual (or at least one with the same depth) */
660 SDL_DisplayColormap = DefaultColormap(SDL_Display, SDL_Screen);
661 for(i = 0; i < this->hidden->nvisuals; i++)
662 if(this->hidden->visuals[i].depth == DefaultDepth(SDL_Display,
663 SDL_Screen))
664 break;
665 if(i == this->hidden->nvisuals) {
666 /* default visual was useless, take the deepest one instead */
667 i = 0;
668 }
669 SDL_Visual = this->hidden->visuals[i].visual;
670 if ( SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen) ) {
671 SDL_XColorMap = SDL_DisplayColormap;
672 } else {
673 SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
674 SDL_Visual, AllocNone);
675 }
676 this->hidden->depth = this->hidden->visuals[i].depth;
677 vformat->BitsPerPixel = this->hidden->visuals[i].bpp;
678 if ( vformat->BitsPerPixel > 8 ) {
679 vformat->Rmask = SDL_Visual->red_mask;
680 vformat->Gmask = SDL_Visual->green_mask;
681 vformat->Bmask = SDL_Visual->blue_mask;
682 }
683 if ( this->hidden->depth == 32 ) {
684 vformat->Amask = (0xFFFFFFFF & ~(vformat->Rmask|vformat->Gmask|vformat->Bmask));
685 }
686 X11_SaveVidModeGamma(this);
687
688 /* Allow environment override of screensaver disable. */
689 env = SDL_getenv("SDL_VIDEO_ALLOW_SCREENSAVER");
690 if ( env ) {
691 allow_screensaver = SDL_atoi(env);
692 } else {
693#ifdef SDL_VIDEO_DISABLE_SCREENSAVER
694 allow_screensaver = 0;
695#else
696 allow_screensaver = 1;
697#endif
698 }
699
700 /* See if we have been passed a window to use */
701 SDL_windowid = SDL_getenv("SDL_WINDOWID");
702
703 /* Create the fullscreen and managed windows */
704 create_aux_windows(this);
705
706 /* Create the blank cursor */
707 SDL_BlankCursor = this->CreateWMCursor(this, blank_cdata, blank_cmask,
708 BLANK_CWIDTH, BLANK_CHEIGHT,
709 BLANK_CHOTX, BLANK_CHOTY);
710
711 /* Fill in some window manager capabilities */
712 this->info.wm_available = 1;
713
714 /* We're done! */
715 XFlush(SDL_Display);
716 return(0);
717}
718
719static void X11_DestroyWindow(_THIS, SDL_Surface *screen)
720{
721 /* Clean up OpenGL */
722 if ( screen ) {
723 screen->flags &= ~(SDL_OPENGL|SDL_OPENGLBLIT);
724 }
725 X11_GL_Shutdown(this);
726
727 if ( ! SDL_windowid ) {
728 /* Hide the managed window */
729 if ( WMwindow ) {
730 XUnmapWindow(SDL_Display, WMwindow);
731 }
732 if ( screen && (screen->flags & SDL_FULLSCREEN) ) {
733 screen->flags &= ~SDL_FULLSCREEN;
734 X11_LeaveFullScreen(this);
735 }
736
737 /* Destroy the output window */
738 if ( SDL_Window ) {
739 XDestroyWindow(SDL_Display, SDL_Window);
740 }
741
742 /* Free the colormap entries */
743 if ( SDL_XPixels ) {
744 int numcolors;
745 unsigned long pixel;
746 numcolors = SDL_Visual->map_entries;
747 for ( pixel=0; pixel<numcolors; ++pixel ) {
748 while ( SDL_XPixels[pixel] > 0 ) {
749 XFreeColors(GFX_Display,
750 SDL_DisplayColormap,&pixel,1,0);
751 --SDL_XPixels[pixel];
752 }
753 }
754 SDL_free(SDL_XPixels);
755 SDL_XPixels = NULL;
756 }
757
758 /* Free the graphics context */
759 if ( SDL_GC ) {
760 XFreeGC(SDL_Display, SDL_GC);
761 SDL_GC = 0;
762 }
763 }
764}
765
766static SDL_bool X11_WindowPosition(_THIS, int *x, int *y, int w, int h)
767{
768 const char *window = SDL_getenv("SDL_VIDEO_WINDOW_POS");
769 const char *center = SDL_getenv("SDL_VIDEO_CENTERED");
770 if ( window ) {
771 if ( SDL_sscanf(window, "%d,%d", x, y) == 2 ) {
772 return SDL_TRUE;
773 }
774 if ( SDL_strcmp(window, "center") == 0 ) {
775 center = window;
776 }
777 }
778 if ( center ) {
779 *x = (DisplayWidth(SDL_Display, SDL_Screen) - w)/2;
780 *y = (DisplayHeight(SDL_Display, SDL_Screen) - h)/2;
781 return SDL_TRUE;
782 }
783 return SDL_FALSE;
784}
785
786static void X11_SetSizeHints(_THIS, int w, int h, Uint32 flags)
787{
788 XSizeHints *hints;
789
790 hints = XAllocSizeHints();
791 if ( hints ) {
792 if (!(flags & SDL_RESIZABLE)) {
793 hints->min_width = hints->max_width = w;
794 hints->min_height = hints->max_height = h;
795 hints->flags = PMaxSize | PMinSize;
796 }
797 if ( flags & SDL_FULLSCREEN ) {
798 hints->x = 0;
799 hints->y = 0;
800 hints->flags |= USPosition;
801 } else
802 /* Center it, if desired */
803 if ( X11_WindowPosition(this, &hints->x, &hints->y, w, h) ) {
804 hints->flags |= USPosition;
805
806 /* Hints must be set before moving the window, otherwise an
807 unwanted ConfigureNotify event will be issued */
808 XSetWMNormalHints(SDL_Display, WMwindow, hints);
809
810 XMoveWindow(SDL_Display, WMwindow, hints->x, hints->y);
811
812 /* Flush the resize event so we don't catch it later */
813 XSync(SDL_Display, True);
814 }
815 XSetWMNormalHints(SDL_Display, WMwindow, hints);
816 XFree(hints);
817 }
818
819 /* Respect the window caption style */
820 if ( flags & SDL_NOFRAME ) {
821 SDL_bool set;
822 Atom WM_HINTS;
823
824 /* We haven't modified the window manager hints yet */
825 set = SDL_FALSE;
826
827 /* First try to set MWM hints */
828 WM_HINTS = XInternAtom(SDL_Display, "_MOTIF_WM_HINTS", True);
829 if ( WM_HINTS != None ) {
830 /* Hints used by Motif compliant window managers */
831 struct {
832 unsigned long flags;
833 unsigned long functions;
834 unsigned long decorations;
835 long input_mode;
836 unsigned long status;
837 } MWMHints = { (1L << 1), 0, 0, 0, 0 };
838
839 XChangeProperty(SDL_Display, WMwindow,
840 WM_HINTS, WM_HINTS, 32,
841 PropModeReplace,
842 (unsigned char *)&MWMHints,
843 sizeof(MWMHints)/sizeof(long));
844 set = SDL_TRUE;
845 }
846 /* Now try to set KWM hints */
847 WM_HINTS = XInternAtom(SDL_Display, "KWM_WIN_DECORATION", True);
848 if ( WM_HINTS != None ) {
849 long KWMHints = 0;
850
851 XChangeProperty(SDL_Display, WMwindow,
852 WM_HINTS, WM_HINTS, 32,
853 PropModeReplace,
854 (unsigned char *)&KWMHints,
855 sizeof(KWMHints)/sizeof(long));
856 set = SDL_TRUE;
857 }
858 /* Now try to set GNOME hints */
859 WM_HINTS = XInternAtom(SDL_Display, "_WIN_HINTS", True);
860 if ( WM_HINTS != None ) {
861 long GNOMEHints = 0;
862
863 XChangeProperty(SDL_Display, WMwindow,
864 WM_HINTS, WM_HINTS, 32,
865 PropModeReplace,
866 (unsigned char *)&GNOMEHints,
867 sizeof(GNOMEHints)/sizeof(long));
868 set = SDL_TRUE;
869 }
870 /* Finally set the transient hints if necessary */
871 if ( ! set ) {
872 XSetTransientForHint(SDL_Display, WMwindow, SDL_Root);
873 }
874 } else {
875 SDL_bool set;
876 Atom WM_HINTS;
877
878 /* We haven't modified the window manager hints yet */
879 set = SDL_FALSE;
880
881 /* First try to unset MWM hints */
882 WM_HINTS = XInternAtom(SDL_Display, "_MOTIF_WM_HINTS", True);
883 if ( WM_HINTS != None ) {
884 XDeleteProperty(SDL_Display, WMwindow, WM_HINTS);
885 set = SDL_TRUE;
886 }
887 /* Now try to unset KWM hints */
888 WM_HINTS = XInternAtom(SDL_Display, "KWM_WIN_DECORATION", True);
889 if ( WM_HINTS != None ) {
890 XDeleteProperty(SDL_Display, WMwindow, WM_HINTS);
891 set = SDL_TRUE;
892 }
893 /* Now try to unset GNOME hints */
894 WM_HINTS = XInternAtom(SDL_Display, "_WIN_HINTS", True);
895 if ( WM_HINTS != None ) {
896 XDeleteProperty(SDL_Display, WMwindow, WM_HINTS);
897 set = SDL_TRUE;
898 }
899 /* Finally unset the transient hints if necessary */
900 if ( ! set ) {
901 XDeleteProperty(SDL_Display, WMwindow, XA_WM_TRANSIENT_FOR);
902 }
903 }
904}
905
906static int X11_CreateWindow(_THIS, SDL_Surface *screen,
907 int w, int h, int bpp, Uint32 flags)
908{
909 int i, depth;
910 Visual *vis;
911 int vis_change;
912 Uint32 Amask;
913
914 /* If a window is already present, destroy it and start fresh */
915 if ( SDL_Window ) {
916 X11_DestroyWindow(this, screen);
917 switch_waiting = 0; /* Prevent jump back to now-meaningless state. */
918 }
919
920 /* See if we have been given a window id */
921 if ( SDL_windowid ) {
922 SDL_Window = SDL_strtol(SDL_windowid, NULL, 0);
923 } else {
924 SDL_Window = 0;
925 }
926
927 /* find out which visual we are going to use */
928 if ( flags & SDL_OPENGL ) {
929 XVisualInfo *vi;
930
931 vi = X11_GL_GetVisual(this);
932 if( !vi ) {
933 return -1;
934 }
935 vis = vi->visual;
936 depth = vi->depth;
937 } else if ( SDL_windowid ) {
938 XWindowAttributes a;
939
940 XGetWindowAttributes(SDL_Display, SDL_Window, &a);
941 vis = a.visual;
942 depth = a.depth;
943 } else {
944 for ( i = 0; i < this->hidden->nvisuals; i++ ) {
945 if ( this->hidden->visuals[i].bpp == bpp )
946 break;
947 }
948 if ( i == this->hidden->nvisuals ) {
949 SDL_SetError("No matching visual for requested depth");
950 return -1; /* should never happen */
951 }
952 vis = this->hidden->visuals[i].visual;
953 depth = this->hidden->visuals[i].depth;
954 }
955#ifdef X11_DEBUG
956 printf("Choosing %s visual at %d bpp - %d colormap entries\n", vis->class == PseudoColor ? "PseudoColor" : (vis->class == TrueColor ? "TrueColor" : (vis->class == DirectColor ? "DirectColor" : "Unknown")), depth, vis->map_entries);
957#endif
958 vis_change = (vis != SDL_Visual);
959 SDL_Visual = vis;
960 this->hidden->depth = depth;
961
962 /* Allocate the new pixel format for this video mode */
963 if ( this->hidden->depth == 32 ) {
964 Amask = (0xFFFFFFFF & ~(vis->red_mask|vis->green_mask|vis->blue_mask));
965 } else {
966 Amask = 0;
967 }
968 if ( ! SDL_ReallocFormat(screen, bpp,
969 vis->red_mask, vis->green_mask, vis->blue_mask, Amask) ) {
970 return -1;
971 }
972
973 /* Create the appropriate colormap */
974 if ( SDL_XColorMap != SDL_DisplayColormap ) {
975 XFreeColormap(SDL_Display, SDL_XColorMap);
976 }
977 if ( SDL_Visual->class == PseudoColor ) {
978 int ncolors;
979
980 /* Allocate the pixel flags */
981 ncolors = SDL_Visual->map_entries;
982 SDL_XPixels = SDL_malloc(ncolors * sizeof(int));
983 if(SDL_XPixels == NULL) {
984 SDL_OutOfMemory();
985 return -1;
986 }
987 SDL_memset(SDL_XPixels, 0, ncolors * sizeof(*SDL_XPixels));
988
989 /* always allocate a private colormap on non-default visuals */
990 if ( SDL_Visual != DefaultVisual(SDL_Display, SDL_Screen) ) {
991 flags |= SDL_HWPALETTE;
992 }
993 if ( flags & SDL_HWPALETTE ) {
994 screen->flags |= SDL_HWPALETTE;
995 SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
996 SDL_Visual, AllocAll);
997 } else {
998 SDL_XColorMap = SDL_DisplayColormap;
999 }
1000 } else if ( SDL_Visual->class == DirectColor ) {
1001
1002 /* Create a colormap which we can manipulate for gamma */
1003 SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
1004 SDL_Visual, AllocAll);
1005 XSync(SDL_Display, False);
1006
1007 /* Initialize the colormap to the identity mapping */
1008 SDL_GetGammaRamp(0, 0, 0);
1009 this->screen = screen;
1010 X11_SetGammaRamp(this, this->gamma);
1011 this->screen = NULL;
1012 } else {
1013 /* Create a read-only colormap for our window */
1014 SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
1015 SDL_Visual, AllocNone);
1016 }
1017
1018 /* Recreate the auxiliary windows, if needed (required for GL) */
1019 if ( vis_change )
1020 create_aux_windows(this);
1021
1022 if(screen->flags & SDL_HWPALETTE) {
1023 /* Since the full-screen window might have got a nonzero background
1024 colour (0 is white on some displays), we should reset the
1025 background to 0 here since that is what the user expects
1026 with a private colormap */
1027 XSetWindowBackground(SDL_Display, FSwindow, 0);
1028 XClearWindow(SDL_Display, FSwindow);
1029 }
1030
1031 /* resize the (possibly new) window manager window */
1032 if( !SDL_windowid ) {
1033 X11_SetSizeHints(this, w, h, flags);
1034 window_w = w;
1035 window_h = h;
1036 XResizeWindow(SDL_Display, WMwindow, w, h);
1037 }
1038
1039 /* Create (or use) the X11 display window */
1040 if ( !SDL_windowid ) {
1041 if ( flags & SDL_OPENGL ) {
1042 if ( X11_GL_CreateWindow(this, w, h) < 0 ) {
1043 return(-1);
1044 }
1045 } else {
1046 XSetWindowAttributes swa;
1047
1048 swa.background_pixel = 0;
1049 swa.border_pixel = 0;
1050 swa.colormap = SDL_XColorMap;
1051 SDL_Window = XCreateWindow(SDL_Display, WMwindow,
1052 0, 0, w, h, 0, depth,
1053 InputOutput, SDL_Visual,
1054 CWBackPixel | CWBorderPixel
1055 | CWColormap, &swa);
1056 }
1057 /* Only manage our input if we own the window */
1058 XSelectInput(SDL_Display, SDL_Window,
1059 ( EnterWindowMask | LeaveWindowMask
1060 | ButtonPressMask | ButtonReleaseMask
1061 | PointerMotionMask | ExposureMask ));
1062 }
1063 /* Create the graphics context here, once we have a window */
1064 if ( flags & SDL_OPENGL ) {
1065 if ( X11_GL_CreateContext(this) < 0 ) {
1066 return(-1);
1067 } else {
1068 screen->flags |= SDL_OPENGL;
1069 }
1070 } else {
1071 XGCValues gcv;
1072
1073 gcv.graphics_exposures = False;
1074 SDL_GC = XCreateGC(SDL_Display, SDL_Window,
1075 GCGraphicsExposures, &gcv);
1076 if ( ! SDL_GC ) {
1077 SDL_SetError("Couldn't create graphics context");
1078 return(-1);
1079 }
1080 }
1081
1082 /* Set our colormaps when not setting a GL mode */
1083 if ( ! (flags & SDL_OPENGL) ) {
1084 XSetWindowColormap(SDL_Display, SDL_Window, SDL_XColorMap);
1085 if( !SDL_windowid ) {
1086 XSetWindowColormap(SDL_Display, FSwindow, SDL_XColorMap);
1087 XSetWindowColormap(SDL_Display, WMwindow, SDL_XColorMap);
1088 }
1089 }
1090
1091#if 0 /* This is an experiment - are the graphics faster now? - nope. */
1092 if ( SDL_getenv("SDL_VIDEO_X11_BACKINGSTORE") )
1093#endif
1094 /* Cache the window in the server, when possible */
1095 {
1096 Screen *xscreen;
1097 XSetWindowAttributes a;
1098
1099 xscreen = ScreenOfDisplay(SDL_Display, SDL_Screen);
1100 a.backing_store = DoesBackingStore(xscreen);
1101 if ( a.backing_store != NotUseful ) {
1102 XChangeWindowAttributes(SDL_Display, SDL_Window,
1103 CWBackingStore, &a);
1104 }
1105 }
1106
1107 /* Map them both and go fullscreen, if requested */
1108 if ( ! SDL_windowid ) {
1109 XMapWindow(SDL_Display, SDL_Window);
1110 XMapWindow(SDL_Display, WMwindow);
1111 X11_WaitMapped(this, WMwindow);
1112 if ( flags & SDL_FULLSCREEN ) {
1113 screen->flags |= SDL_FULLSCREEN;
1114 X11_EnterFullScreen(this);
1115 } else {
1116 screen->flags &= ~SDL_FULLSCREEN;
1117 }
1118 }
1119
1120 return(0);
1121}
1122
1123static int X11_ResizeWindow(_THIS,
1124 SDL_Surface *screen, int w, int h, Uint32 flags)
1125{
1126 if ( ! SDL_windowid ) {
1127 /* Resize the window manager window */
1128 X11_SetSizeHints(this, w, h, flags);
1129 window_w = w;
1130 window_h = h;
1131 XResizeWindow(SDL_Display, WMwindow, w, h);
1132
1133 /* Resize the fullscreen and display windows */
1134 if ( flags & SDL_FULLSCREEN ) {
1135 if ( screen->flags & SDL_FULLSCREEN ) {
1136 X11_ResizeFullScreen(this);
1137 } else {
1138 screen->flags |= SDL_FULLSCREEN;
1139 X11_EnterFullScreen(this);
1140 }
1141 } else {
1142 if ( screen->flags & SDL_FULLSCREEN ) {
1143 screen->flags &= ~SDL_FULLSCREEN;
1144 X11_LeaveFullScreen(this);
1145 }
1146 }
1147 XResizeWindow(SDL_Display, SDL_Window, w, h);
1148 }
1149 return(0);
1150}
1151
1152SDL_Surface *X11_SetVideoMode(_THIS, SDL_Surface *current,
1153 int width, int height, int bpp, Uint32 flags)
1154{
1155 Uint32 saved_flags;
1156
1157 /* Lock the event thread, in multi-threading environments */
1158 SDL_Lock_EventThread();
1159
1160 /* Check the combination of flags we were passed */
1161 if ( flags & SDL_FULLSCREEN ) {
1162 /* Clear fullscreen flag if not supported */
1163 if ( SDL_windowid ) {
1164 flags &= ~SDL_FULLSCREEN;
1165 }
1166 }
1167
1168 /* Flush any delayed updates */
1169 XSync(GFX_Display, False);
1170
1171 /* Set up the X11 window */
1172 saved_flags = current->flags;
1173 if ( (SDL_Window) && ((saved_flags&SDL_OPENGL) == (flags&SDL_OPENGL))
1174 && (bpp == current->format->BitsPerPixel)
1175 && ((saved_flags&SDL_NOFRAME) == (flags&SDL_NOFRAME)) ) {
1176 if (X11_ResizeWindow(this, current, width, height, flags) < 0) {
1177 current = NULL;
1178 goto done;
1179 }
1180 X11_PendingConfigureNotifyWidth = width;
1181 X11_PendingConfigureNotifyHeight = height;
1182 } else {
1183 if (X11_CreateWindow(this,current,width,height,bpp,flags) < 0) {
1184 current = NULL;
1185 goto done;
1186 }
1187 }
1188
1189 /* Update the internal keyboard state */
1190 X11_SetKeyboardState(SDL_Display, NULL);
1191
1192 /* When the window is first mapped, ignore non-modifier keys */
1193 if ( !current->w && !current->h ) {
1194 Uint8 *keys = SDL_GetKeyState(NULL);
1195 int i;
1196 for ( i = 0; i < SDLK_LAST; ++i ) {
1197 switch (i) {
1198 case SDLK_NUMLOCK:
1199 case SDLK_CAPSLOCK:
1200 case SDLK_LCTRL:
1201 case SDLK_RCTRL:
1202 case SDLK_LSHIFT:
1203 case SDLK_RSHIFT:
1204 case SDLK_LALT:
1205 case SDLK_RALT:
1206 case SDLK_LMETA:
1207 case SDLK_RMETA:
1208 case SDLK_MODE:
1209 break;
1210 default:
1211 keys[i] = SDL_RELEASED;
1212 break;
1213 }
1214 }
1215 }
1216
1217 /* Set up the new mode framebuffer */
1218 if ( ((current->w != width) || (current->h != height)) ||
1219 ((saved_flags&SDL_OPENGL) != (flags&SDL_OPENGL)) ) {
1220 current->w = width;
1221 current->h = height;
1222 current->pitch = SDL_CalculatePitch(current);
1223 if (X11_ResizeImage(this, current, flags) < 0) {
1224 current = NULL;
1225 goto done;
1226 }
1227 }
1228
1229 /* Clear these flags and set them only if they are in the new set. */
1230 current->flags &= ~(SDL_RESIZABLE|SDL_NOFRAME);
1231 current->flags |= (flags&(SDL_RESIZABLE|SDL_NOFRAME));
1232
1233 done:
1234 /* Release the event thread */
1235 XSync(SDL_Display, False);
1236 SDL_Unlock_EventThread();
1237
1238 /* We're done! */
1239 return(current);
1240}
1241
1242static int X11_ToggleFullScreen(_THIS, int on)
1243{
1244 Uint32 event_thread;
1245
1246 /* Don't switch if we don't own the window */
1247 if ( SDL_windowid ) {
1248 return(0);
1249 }
1250
1251 /* Don't lock if we are the event thread */
1252 event_thread = SDL_EventThreadID();
1253 if ( event_thread && (SDL_ThreadID() == event_thread) ) {
1254 event_thread = 0;
1255 }
1256 if ( event_thread ) {
1257 SDL_Lock_EventThread();
1258 }
1259 if ( on ) {
1260 this->screen->flags |= SDL_FULLSCREEN;
1261 X11_EnterFullScreen(this);
1262 } else {
1263 this->screen->flags &= ~SDL_FULLSCREEN;
1264 X11_LeaveFullScreen(this);
1265 }
1266 X11_RefreshDisplay(this);
1267 if ( event_thread ) {
1268 SDL_Unlock_EventThread();
1269 }
1270 SDL_ResetKeyboard();
1271 return(1);
1272}
1273
1274/* Update the current mouse state and position */
1275static void X11_UpdateMouse(_THIS)
1276{
1277 Window u1; int u2;
1278 Window current_win;
1279 int x, y;
1280 unsigned int mask;
1281
1282 /* Lock the event thread, in multi-threading environments */
1283 SDL_Lock_EventThread();
1284 if ( XQueryPointer(SDL_Display, SDL_Window, &u1, &current_win,
1285 &u2, &u2, &x, &y, &mask) ) {
1286 if ( (x >= 0) && (x < SDL_VideoSurface->w) &&
1287 (y >= 0) && (y < SDL_VideoSurface->h) ) {
1288 SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
1289 SDL_PrivateMouseMotion(0, 0, x, y);
1290 } else {
1291 SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
1292 }
1293 }
1294 SDL_Unlock_EventThread();
1295}
1296
1297/* simple colour distance metric. Supposed to be better than a plain
1298 Euclidian distance anyway. */
1299#define COLOUR_FACTOR 3
1300#define LIGHT_FACTOR 1
1301#define COLOUR_DIST(r1, g1, b1, r2, g2, b2) \
1302 (COLOUR_FACTOR * (abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2)) \
1303 + LIGHT_FACTOR * abs(r1 + g1 + b1 - (r2 + g2 + b2)))
1304
1305static void allocate_nearest(_THIS, SDL_Color *colors,
1306 SDL_Color *want, int nwant)
1307{
1308 /*
1309 * There is no way to know which ones to choose from, so we retrieve
1310 * the entire colormap and try the nearest possible, until we find one
1311 * that is shared.
1312 */
1313 XColor all[256];
1314 int i;
1315 for(i = 0; i < 256; i++)
1316 all[i].pixel = i;
1317 /*
1318 * XQueryColors sets the flags in the XColor struct, so we use
1319 * that to keep track of which colours are available
1320 */
1321 XQueryColors(GFX_Display, SDL_XColorMap, all, 256);
1322
1323 for(i = 0; i < nwant; i++) {
1324 XColor *c;
1325 int j;
1326 int best = 0;
1327 int mindist = 0x7fffffff;
1328 int ri = want[i].r;
1329 int gi = want[i].g;
1330 int bi = want[i].b;
1331 for(j = 0; j < 256; j++) {
1332 int rj, gj, bj, d2;
1333 if(!all[j].flags)
1334 continue; /* unavailable colour cell */
1335 rj = all[j].red >> 8;
1336 gj = all[j].green >> 8;
1337 bj = all[j].blue >> 8;
1338 d2 = COLOUR_DIST(ri, gi, bi, rj, gj, bj);
1339 if(d2 < mindist) {
1340 mindist = d2;
1341 best = j;
1342 }
1343 }
1344 if(SDL_XPixels[best])
1345 continue; /* already allocated, waste no more time */
1346 c = all + best;
1347 if(XAllocColor(GFX_Display, SDL_XColorMap, c)) {
1348 /* got it */
1349 colors[c->pixel].r = c->red >> 8;
1350 colors[c->pixel].g = c->green >> 8;
1351 colors[c->pixel].b = c->blue >> 8;
1352 ++SDL_XPixels[c->pixel];
1353 } else {
1354 /*
1355 * The colour couldn't be allocated, probably being
1356 * owned as a r/w cell by another client. Flag it as
1357 * unavailable and try again. The termination of the
1358 * loop is guaranteed since at least black and white
1359 * are always there.
1360 */
1361 c->flags = 0;
1362 i--;
1363 }
1364 }
1365}
1366
1367int X11_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
1368{
1369 int nrej = 0;
1370
1371 /* Check to make sure we have a colormap allocated */
1372 if ( SDL_XPixels == NULL ) {
1373 return(0);
1374 }
1375 if ( (this->screen->flags & SDL_HWPALETTE) == SDL_HWPALETTE ) {
1376 /* private writable colormap: just set the colours we need */
1377 XColor *xcmap;
1378 int i;
1379 xcmap = SDL_stack_alloc(XColor, ncolors);
1380 if(xcmap == NULL)
1381 return 0;
1382 for ( i=0; i<ncolors; ++i ) {
1383 xcmap[i].pixel = i + firstcolor;
1384 xcmap[i].red = (colors[i].r<<8)|colors[i].r;
1385 xcmap[i].green = (colors[i].g<<8)|colors[i].g;
1386 xcmap[i].blue = (colors[i].b<<8)|colors[i].b;
1387 xcmap[i].flags = (DoRed|DoGreen|DoBlue);
1388 }
1389 XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors);
1390 XSync(GFX_Display, False);
1391 SDL_stack_free(xcmap);
1392 } else {
1393 /*
1394 * Shared colormap: We only allocate read-only cells, which
1395 * increases the likelyhood of colour sharing with other
1396 * clients. The pixel values will almost certainly be
1397 * different from the requested ones, so the user has to
1398 * walk the colormap and see which index got what colour.
1399 *
1400 * We can work directly with the logical palette since it
1401 * has already been set when we get here.
1402 */
1403 SDL_Color *want, *reject;
1404 unsigned long *freelist;
1405 int i;
1406 int nfree = 0;
1407 int nc = this->screen->format->palette->ncolors;
1408 colors = this->screen->format->palette->colors;
1409 freelist = SDL_stack_alloc(unsigned long, nc);
1410 /* make sure multiple allocations of the same cell are freed */
1411 for(i = 0; i < ncolors; i++) {
1412 int pixel = firstcolor + i;
1413 while(SDL_XPixels[pixel]) {
1414 freelist[nfree++] = pixel;
1415 --SDL_XPixels[pixel];
1416 }
1417 }
1418 XFreeColors(GFX_Display, SDL_XColorMap, freelist, nfree, 0);
1419 SDL_stack_free(freelist);
1420
1421 want = SDL_stack_alloc(SDL_Color, ncolors);
1422 reject = SDL_stack_alloc(SDL_Color, ncolors);
1423 SDL_memcpy(want, colors + firstcolor, ncolors * sizeof(SDL_Color));
1424 /* make sure the user isn't fooled by her own wishes
1425 (black is safe, always available in the default colormap) */
1426 SDL_memset(colors + firstcolor, 0, ncolors * sizeof(SDL_Color));
1427
1428 /* now try to allocate the colours */
1429 for(i = 0; i < ncolors; i++) {
1430 XColor col;
1431 col.red = want[i].r << 8;
1432 col.green = want[i].g << 8;
1433 col.blue = want[i].b << 8;
1434 col.flags = DoRed | DoGreen | DoBlue;
1435 if(XAllocColor(GFX_Display, SDL_XColorMap, &col)) {
1436 /* We got the colour, or at least the nearest
1437 the hardware could get. */
1438 colors[col.pixel].r = col.red >> 8;
1439 colors[col.pixel].g = col.green >> 8;
1440 colors[col.pixel].b = col.blue >> 8;
1441 ++SDL_XPixels[col.pixel];
1442 } else {
1443 /*
1444 * no more free cells, add it to the list
1445 * of rejected colours
1446 */
1447 reject[nrej++] = want[i];
1448 }
1449 }
1450 if(nrej)
1451 allocate_nearest(this, colors, reject, nrej);
1452 SDL_stack_free(reject);
1453 SDL_stack_free(want);
1454 }
1455 return nrej == 0;
1456}
1457
1458int X11_SetGammaRamp(_THIS, Uint16 *ramp)
1459{
1460 int i, ncolors;
1461 XColor xcmap[256];
1462
1463 /* See if actually setting the gamma is supported */
1464 if ( SDL_Visual->class != DirectColor ) {
1465 SDL_SetError("Gamma correction not supported on this visual");
1466 return(-1);
1467 }
1468
1469 /* Calculate the appropriate palette for the given gamma ramp */
1470 ncolors = SDL_Visual->map_entries;
1471 for ( i=0; i<ncolors; ++i ) {
1472 Uint8 c = (256 * i / ncolors);
1473 xcmap[i].pixel = SDL_MapRGB(this->screen->format, c, c, c);
1474 xcmap[i].red = ramp[0*256+c];
1475 xcmap[i].green = ramp[1*256+c];
1476 xcmap[i].blue = ramp[2*256+c];
1477 xcmap[i].flags = (DoRed|DoGreen|DoBlue);
1478 }
1479 XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors);
1480 XSync(GFX_Display, False);
1481 return(0);
1482}
1483
1484/* Note: If we are terminated, this could be called in the middle of
1485 another SDL video routine -- notably UpdateRects.
1486*/
1487void X11_VideoQuit(_THIS)
1488{
1489 /* Shutdown everything that's still up */
1490 /* The event thread should be done, so we can touch SDL_Display */
1491 if ( SDL_Display != NULL ) {
1492 /* Flush any delayed updates */
1493 XSync(GFX_Display, False);
1494
1495 /* Close the connection with the IM server */
1496 #ifdef X_HAVE_UTF8_STRING
1497 if (SDL_IC != NULL) {
1498 XUnsetICFocus(SDL_IC);
1499 XDestroyIC(SDL_IC);
1500 SDL_IC = NULL;
1501 }
1502 if (SDL_IM != NULL) {
1503 XCloseIM(SDL_IM);
1504 SDL_IM = NULL;
1505 }
1506 #endif
1507
1508 /* Start shutting down the windows */
1509 X11_DestroyImage(this, this->screen);
1510 X11_DestroyWindow(this, this->screen);
1511 X11_FreeVideoModes(this);
1512 if ( SDL_XColorMap != SDL_DisplayColormap ) {
1513 XFreeColormap(SDL_Display, SDL_XColorMap);
1514 }
1515 if ( SDL_iconcolors ) {
1516 unsigned long pixel;
1517 Colormap dcmap = DefaultColormap(SDL_Display,
1518 SDL_Screen);
1519 for(pixel = 0; pixel < 256; ++pixel) {
1520 while(SDL_iconcolors[pixel] > 0) {
1521 XFreeColors(GFX_Display,
1522 dcmap, &pixel, 1, 0);
1523 --SDL_iconcolors[pixel];
1524 }
1525 }
1526 SDL_free(SDL_iconcolors);
1527 SDL_iconcolors = NULL;
1528 }
1529
1530 /* Restore gamma settings if they've changed */
1531 if ( SDL_GetAppState() & SDL_APPACTIVE ) {
1532 X11_SwapVidModeGamma(this);
1533 }
1534
1535 /* Free that blank cursor */
1536 if ( SDL_BlankCursor != NULL ) {
1537 this->FreeWMCursor(this, SDL_BlankCursor);
1538 SDL_BlankCursor = NULL;
1539 }
1540
1541 /* Close the X11 graphics connection */
1542 if ( GFX_Display != NULL ) {
1543 XCloseDisplay(GFX_Display);
1544 GFX_Display = NULL;
1545 }
1546
1547 /* Close the X11 display connection */
1548 XCloseDisplay(SDL_Display);
1549 SDL_Display = NULL;
1550
1551 /* Reset the X11 error handlers */
1552 if ( XIO_handler ) {
1553 XSetIOErrorHandler(XIO_handler);
1554 }
1555 if ( X_handler ) {
1556 XSetErrorHandler(X_handler);
1557 }
1558
1559 /* Unload GL library after X11 shuts down */
1560 X11_GL_UnloadLibrary(this);
1561 }
1562 if ( this->screen && (this->screen->flags & SDL_HWSURFACE) ) {
1563 /* Direct screen access, no memory buffer */
1564 this->screen->pixels = NULL;
1565 }
1566
1567#if SDL_VIDEO_DRIVER_X11_XME
1568 XiGMiscDestroy();
1569#endif
1570}
1571
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11video.h b/apps/plugins/sdl/src/video/x11/SDL_x11video.h
deleted file mode 100644
index f347560d6d..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11video.h
+++ /dev/null
@@ -1,214 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_x11video_h
25#define _SDL_x11video_h
26
27#include <X11/Xlib.h>
28#include <X11/Xutil.h>
29#include <X11/Xatom.h>
30
31#include "SDL_mouse.h"
32#include "../SDL_sysvideo.h"
33
34#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
35#include "../Xext/extensions/xf86dga.h"
36#endif
37#if SDL_VIDEO_DRIVER_X11_XINERAMA
38#include "../Xext/extensions/Xinerama.h"
39#endif
40#if SDL_VIDEO_DRIVER_X11_XRANDR
41#include <X11/extensions/Xrandr.h>
42#endif
43#if SDL_VIDEO_DRIVER_X11_VIDMODE
44#include "../Xext/extensions/xf86vmode.h"
45#endif
46#if SDL_VIDEO_DRIVER_X11_XME
47#include "../Xext/extensions/xme.h"
48#endif
49
50#include "SDL_x11dyn.h"
51
52/* Hidden "this" pointer for the video functions */
53#define _THIS SDL_VideoDevice *this
54
55/* Private display data */
56struct SDL_PrivateVideoData {
57 int local_X11; /* Flag: true if local display */
58 Display *X11_Display; /* Used for events and window management */
59 Display *GFX_Display; /* Used for graphics and colormap stuff */
60 Visual *SDL_Visual; /* The visual used by our window */
61 Window WMwindow; /* Input window, managed by window manager */
62 Window FSwindow; /* Fullscreen window, completely unmanaged */
63 Window SDL_Window; /* Shared by both displays (no X security?) */
64 Atom WM_DELETE_WINDOW; /* "close-window" protocol atom */
65 WMcursor *BlankCursor; /* The invisible cursor */
66 XIM X11_IM; /* Used to communicate with the input method (IM) server */
67 XIC X11_IC; /* Used for retaining the state, properties, and semantics of communication with the input method (IM) server */
68
69 char *SDL_windowid; /* Flag: true if we have been passed a window */
70
71 /* Direct Graphics Access extension information */
72 int using_dga;
73
74#ifndef NO_SHARED_MEMORY
75 /* MIT shared memory extension information */
76 int use_mitshm;
77 XShmSegmentInfo shminfo;
78#endif
79
80 /* The variables used for displaying graphics */
81 XImage *Ximage; /* The X image for our window */
82 GC gc; /* The graphic context for drawing */
83
84 /* The current width and height of the fullscreen mode */
85 int window_w;
86 int window_h;
87
88 /* Support for internal mouse warping */
89 struct {
90 int x;
91 int y;
92 } mouse_last;
93 struct {
94 int numerator;
95 int denominator;
96 int threshold;
97 } mouse_accel;
98 int mouse_relative;
99
100 /* The current list of available video modes */
101 SDL_Rect **modelist;
102
103 /* available visuals of interest to us, sorted deepest first */
104 struct {
105 Visual *visual;
106 int depth; /* number of significant bits/pixel */
107 int bpp; /* pixel quantum in bits */
108 } visuals[2*5]; /* at most 2 entries for 8, 15, 16, 24, 32 */
109 int nvisuals;
110
111 Visual *vis; /* current visual in use */
112 int depth; /* current visual depth (not bpp) */
113
114 /* Variables used by the X11 video mode code */
115#if SDL_VIDEO_DRIVER_X11_XINERAMA
116 SDL_NAME(XineramaScreenInfo) xinerama_info;
117#endif
118#if SDL_VIDEO_DRIVER_X11_XRANDR
119 XRRScreenConfiguration* screen_config;
120 int saved_size_id;
121 Rotation saved_rotation;
122#endif
123#if SDL_VIDEO_DRIVER_X11_VIDMODE
124 SDL_NAME(XF86VidModeModeInfo) saved_mode;
125 struct {
126 int x, y;
127 } saved_view;
128#endif
129#if SDL_VIDEO_DRIVER_X11_XME /* XiG XME fullscreen */
130 XiGMiscResolutionInfo saved_res;
131#endif
132
133 int use_xinerama;
134 int use_xrandr;
135 int use_vidmode;
136 int use_xme;
137 int currently_fullscreen;
138
139 /* Automatic mode switching support (entering/leaving fullscreen) */
140 Uint32 switch_waiting;
141 Uint32 switch_time;
142
143 /* Prevent too many XSync() calls */
144 int blit_queued;
145
146 /* Colormap handling */
147 Colormap DisplayColormap; /* The default display colormap */
148 Colormap XColorMap; /* The current window colormap */
149 int *XPixels; /* pixels value allocation counts */
150 float gamma_saved[3]; /* Saved gamma values for VidMode gamma */
151 int gamma_changed; /* flag: has VidMode gamma been modified? */
152
153 short *iconcolors; /* List of colors used by the icon */
154
155 /* Screensaver settings */
156 int allow_screensaver;
157};
158
159/* Old variable names */
160#define local_X11 (this->hidden->local_X11)
161#define SDL_Display (this->hidden->X11_Display)
162#define GFX_Display (this->hidden->GFX_Display)
163#define SDL_Screen DefaultScreen(this->hidden->X11_Display)
164#define SDL_Visual (this->hidden->vis)
165#define SDL_Root RootWindow(SDL_Display, SDL_Screen)
166#define WMwindow (this->hidden->WMwindow)
167#define FSwindow (this->hidden->FSwindow)
168#define SDL_Window (this->hidden->SDL_Window)
169#define WM_DELETE_WINDOW (this->hidden->WM_DELETE_WINDOW)
170#define SDL_BlankCursor (this->hidden->BlankCursor)
171#define SDL_IM (this->hidden->X11_IM)
172#define SDL_IC (this->hidden->X11_IC)
173#define SDL_windowid (this->hidden->SDL_windowid)
174#define using_dga (this->hidden->using_dga)
175#define use_mitshm (this->hidden->use_mitshm)
176#define shminfo (this->hidden->shminfo)
177#define SDL_Ximage (this->hidden->Ximage)
178#define SDL_GC (this->hidden->gc)
179#define window_w (this->hidden->window_w)
180#define window_h (this->hidden->window_h)
181#define mouse_last (this->hidden->mouse_last)
182#define mouse_accel (this->hidden->mouse_accel)
183#define mouse_relative (this->hidden->mouse_relative)
184#define SDL_modelist (this->hidden->modelist)
185#define xinerama_info (this->hidden->xinerama_info)
186#define saved_mode (this->hidden->saved_mode)
187#define saved_view (this->hidden->saved_view)
188#define saved_res (this->hidden->saved_res)
189#define screen_config (this->hidden->screen_config)
190#define saved_size_id (this->hidden->saved_size_id)
191#define saved_rotation (this->hidden->saved_rotation)
192#define use_xinerama (this->hidden->use_xinerama)
193#define use_vidmode (this->hidden->use_vidmode)
194#define use_xrandr (this->hidden->use_xrandr)
195#define use_xme (this->hidden->use_xme)
196#define currently_fullscreen (this->hidden->currently_fullscreen)
197#define switch_waiting (this->hidden->switch_waiting)
198#define switch_time (this->hidden->switch_time)
199#define blit_queued (this->hidden->blit_queued)
200#define SDL_DisplayColormap (this->hidden->DisplayColormap)
201#define SDL_PrivateColormap (this->hidden->PrivateColormap)
202#define SDL_XColorMap (this->hidden->XColorMap)
203#define SDL_XPixels (this->hidden->XPixels)
204#define gamma_saved (this->hidden->gamma_saved)
205#define gamma_changed (this->hidden->gamma_changed)
206#define SDL_iconcolors (this->hidden->iconcolors)
207#define allow_screensaver (this->hidden->allow_screensaver)
208
209/* Some versions of XFree86 have bugs - detect if this is one of them */
210#define BUGGY_XFREE86(condition, buggy_version) \
211((SDL_strcmp(ServerVendor(SDL_Display), "The XFree86 Project, Inc") == 0) && \
212 (VendorRelease(SDL_Display) condition buggy_version))
213
214#endif /* _SDL_x11video_h */
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11wm.c b/apps/plugins/sdl/src/video/x11/SDL_x11wm.c
deleted file mode 100644
index 14c816b942..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11wm.c
+++ /dev/null
@@ -1,434 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include <X11/Xlib.h>
25#include <X11/Xutil.h>
26
27#include "SDL_version.h"
28#include "SDL_timer.h"
29#include "SDL_video.h"
30#include "SDL_syswm.h"
31#include "../SDL_pixels_c.h"
32#include "../../events/SDL_events_c.h"
33#include "SDL_x11modes_c.h"
34#include "SDL_x11wm_c.h"
35
36static Uint8 reverse_byte(Uint8 x)
37{
38 x = (x & 0xaa) >> 1 | (x & 0x55) << 1;
39 x = (x & 0xcc) >> 2 | (x & 0x33) << 2;
40 x = (x & 0xf0) >> 4 | (x & 0x0f) << 4;
41 return x;
42}
43
44void X11_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
45{
46 SDL_Surface *sicon;
47 XWMHints *wmhints;
48 XImage *icon_image;
49 Pixmap icon_pixmap;
50 Pixmap mask_pixmap;
51 Window icon_window = None;
52 GC gc;
53 XGCValues GCvalues;
54 int i, dbpp;
55 SDL_Rect bounds;
56 Uint8 *LSBmask;
57 Visual *dvis;
58 char *p;
59 int masksize;
60
61 SDL_Lock_EventThread();
62
63 /* The icon must use the default visual, depth and colormap of the
64 screen, so it might need a conversion */
65 dvis = DefaultVisual(SDL_Display, SDL_Screen);
66 dbpp = DefaultDepth(SDL_Display, SDL_Screen);
67 for(i = 0; i < this->hidden->nvisuals; i++) {
68 if(this->hidden->visuals[i].visual == dvis) {
69 dbpp = this->hidden->visuals[i].bpp;
70 break;
71 }
72 }
73
74 /* The Visual struct is supposed to be opaque but we cheat a little */
75 sicon = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h,
76 dbpp,
77 dvis->red_mask, dvis->green_mask,
78 dvis->blue_mask, 0);
79 if ( sicon == NULL )
80 goto done;
81
82 if(dbpp == 8) {
83 /* Default visual is 8bit; we need to allocate colours from
84 the default colormap */
85 SDL_Color want[256], got[256];
86 int nwant;
87 Colormap dcmap;
88 int missing;
89 dcmap = DefaultColormap(SDL_Display, SDL_Screen);
90 if(icon->format->palette) {
91 /* The icon has a palette as well - we just have to
92 find those colours */
93 nwant = icon->format->palette->ncolors;
94 SDL_memcpy(want, icon->format->palette->colors,
95 nwant * sizeof want[0]);
96 } else {
97 /* try the standard 6x6x6 cube for lack of better
98 ideas */
99 int r, g, b, i;
100 for(r = i = 0; r < 256; r += 0x33)
101 for(g = 0; g < 256; g += 0x33)
102 for(b = 0; b < 256; b += 0x33, i++) {
103 want[i].r = r;
104 want[i].g = g;
105 want[i].b = b;
106 }
107 nwant = 216;
108 }
109 if(SDL_iconcolors) {
110 /* free already allocated colours first */
111 unsigned long freelist[512];
112 int nfree = 0;
113 for(i = 0; i < 256; i++) {
114 while(SDL_iconcolors[i]) {
115 freelist[nfree++] = i;
116 SDL_iconcolors[i]--;
117 }
118 }
119 XFreeColors(GFX_Display, dcmap, freelist, nfree, 0);
120 }
121 if(!SDL_iconcolors)
122 SDL_iconcolors = SDL_malloc(256 * sizeof *SDL_iconcolors);
123 SDL_memset(SDL_iconcolors, 0, 256 * sizeof *SDL_iconcolors);
124
125 /* try to allocate the colours */
126 SDL_memset(got, 0, sizeof got);
127 missing = 0;
128 for(i = 0; i < nwant; i++) {
129 XColor c;
130 c.red = want[i].r << 8;
131 c.green = want[i].g << 8;
132 c.blue = want[i].b << 8;
133 c.flags = DoRed | DoGreen | DoBlue;
134 if(XAllocColor(GFX_Display, dcmap, &c)) {
135 /* got the colour */
136 SDL_iconcolors[c.pixel]++;
137 got[c.pixel] = want[i];
138 } else {
139 missing = 1;
140 }
141 }
142 if(missing) {
143 /* Some colours were apparently missing, so we just
144 allocate all the rest as well */
145 XColor cols[256];
146 for(i = 0; i < 256; i++)
147 cols[i].pixel = i;
148 XQueryColors(GFX_Display, dcmap, cols, 256);
149 for(i = 0; i < 256; i++) {
150 got[i].r = cols[i].red >> 8;
151 got[i].g = cols[i].green >> 8;
152 got[i].b = cols[i].blue >> 8;
153 if(!SDL_iconcolors[i]) {
154 if(XAllocColor(GFX_Display, dcmap,
155 cols + i)) {
156 SDL_iconcolors[i] = 1;
157 } else {
158 /* index not available */
159 got[i].r = 0;
160 got[i].g = 0;
161 got[i].b = 0;
162 }
163 }
164 }
165 }
166
167 SDL_SetColors(sicon, got, 0, 256);
168 }
169
170 bounds.x = 0;
171 bounds.y = 0;
172 bounds.w = icon->w;
173 bounds.h = icon->h;
174 if ( SDL_LowerBlit(icon, &bounds, sicon, &bounds) < 0 )
175 goto done;
176
177 /* We need the mask as given, except in LSBfirst format instead of
178 MSBfirst. Reverse the bits in each byte. */
179 masksize = ((sicon->w + 7) >> 3) * sicon->h;
180 LSBmask = SDL_malloc(masksize);
181 if ( LSBmask == NULL ) {
182 goto done;
183 }
184 SDL_memset(LSBmask, 0, masksize);
185 for(i = 0; i < masksize; i++)
186 LSBmask[i] = reverse_byte(mask[i]);
187 mask_pixmap = XCreatePixmapFromBitmapData(SDL_Display, WMwindow,
188 (char *)LSBmask,
189 sicon->w, sicon->h,
190 1L, 0L, 1);
191
192 /* Transfer the image to an X11 pixmap */
193 icon_image = XCreateImage(SDL_Display,
194 DefaultVisual(SDL_Display, SDL_Screen),
195 DefaultDepth(SDL_Display, SDL_Screen),
196 ZPixmap, 0, sicon->pixels,
197 sicon->w, sicon->h,
198 32, 0);
199 icon_image->byte_order = (SDL_BYTEORDER == SDL_BIG_ENDIAN)
200 ? MSBFirst : LSBFirst;
201 icon_pixmap = XCreatePixmap(SDL_Display, SDL_Root, sicon->w, sicon->h,
202 DefaultDepth(SDL_Display, SDL_Screen));
203 gc = XCreateGC(SDL_Display, icon_pixmap, 0, &GCvalues);
204 XPutImage(SDL_Display, icon_pixmap, gc, icon_image,
205 0, 0, 0, 0, sicon->w, sicon->h);
206 XFreeGC(SDL_Display, gc);
207 XDestroyImage(icon_image);
208 SDL_free(LSBmask);
209 sicon->pixels = NULL;
210
211 /* Some buggy window managers (some versions of Enlightenment, it
212 seems) need an icon window *and* icon pixmap to work properly, while
213 it screws up others. The default is only to use a pixmap. */
214 p = SDL_getenv("SDL_VIDEO_X11_ICONWIN");
215 if(p && *p) {
216 icon_window = XCreateSimpleWindow(SDL_Display, SDL_Root,
217 0, 0, sicon->w, sicon->h, 0,
218 CopyFromParent,
219 CopyFromParent);
220 XSetWindowBackgroundPixmap(SDL_Display, icon_window,
221 icon_pixmap);
222 XClearWindow(SDL_Display, icon_window);
223 }
224
225 /* Set the window icon to the icon pixmap (and icon window) */
226 wmhints = XAllocWMHints();
227 wmhints->flags = (IconPixmapHint | IconMaskHint | InputHint);
228 wmhints->icon_pixmap = icon_pixmap;
229 wmhints->icon_mask = mask_pixmap;
230 wmhints->input = True;
231 if(icon_window != None) {
232 wmhints->flags |= IconWindowHint;
233 wmhints->icon_window = icon_window;
234 }
235 XSetWMHints(SDL_Display, WMwindow, wmhints);
236 XFree(wmhints);
237 XSync(SDL_Display, False);
238
239 done:
240 SDL_Unlock_EventThread();
241 SDL_FreeSurface(sicon);
242}
243
244void X11_SetCaptionNoLock(_THIS, const char *title, const char *icon)
245{
246 XTextProperty titleprop, iconprop;
247 Status status;
248
249#ifdef X_HAVE_UTF8_STRING
250 Atom _NET_WM_NAME = 0;
251 Atom _NET_WM_ICON_NAME = 0;
252
253 /* Look up some useful Atoms */
254 if (SDL_X11_HAVE_UTF8) {
255 _NET_WM_NAME = XInternAtom(SDL_Display, "_NET_WM_NAME", False);
256 _NET_WM_ICON_NAME = XInternAtom(SDL_Display, "_NET_WM_ICON_NAME", False);
257 }
258#endif
259
260 if ( title != NULL ) {
261 char *title_locale = SDL_iconv_utf8_locale(title);
262 if ( !title_locale ) {
263 SDL_OutOfMemory();
264 return;
265 }
266 status = XStringListToTextProperty(&title_locale, 1, &titleprop);
267 SDL_free(title_locale);
268 if ( status ) {
269 XSetTextProperty(SDL_Display, WMwindow, &titleprop, XA_WM_NAME);
270 XFree(titleprop.value);
271 }
272#ifdef X_HAVE_UTF8_STRING
273 if (SDL_X11_HAVE_UTF8) {
274 status = Xutf8TextListToTextProperty(SDL_Display,
275 (char **)&title, 1, XUTF8StringStyle, &titleprop);
276 if ( status == Success ) {
277 XSetTextProperty(SDL_Display, WMwindow, &titleprop, _NET_WM_NAME);
278 XFree(titleprop.value);
279 }
280 }
281#endif
282 }
283 if ( icon != NULL ) {
284 char *icon_locale = SDL_iconv_utf8_locale(icon);
285 if ( !icon_locale ) {
286 SDL_OutOfMemory();
287 return;
288 }
289 status = XStringListToTextProperty(&icon_locale, 1, &iconprop);
290 SDL_free(icon_locale);
291 if ( status ) {
292 XSetTextProperty(SDL_Display, WMwindow, &iconprop, XA_WM_ICON_NAME);
293 XFree(iconprop.value);
294 }
295#ifdef X_HAVE_UTF8_STRING
296 if (SDL_X11_HAVE_UTF8) {
297 status = Xutf8TextListToTextProperty(SDL_Display,
298 (char **)&icon, 1, XUTF8StringStyle, &iconprop);
299 if ( status == Success ) {
300 XSetTextProperty(SDL_Display, WMwindow, &iconprop, _NET_WM_ICON_NAME);
301 XFree(iconprop.value);
302 }
303 }
304#endif
305 }
306 XSync(SDL_Display, False);
307}
308
309void X11_SetCaption(_THIS, const char *title, const char *icon)
310{
311 SDL_Lock_EventThread();
312 X11_SetCaptionNoLock(this, title, icon);
313 SDL_Unlock_EventThread();
314}
315
316/* Iconify the window */
317int X11_IconifyWindow(_THIS)
318{
319 int result;
320
321 SDL_Lock_EventThread();
322 result = XIconifyWindow(SDL_Display, WMwindow, SDL_Screen);
323 XSync(SDL_Display, False);
324 SDL_Unlock_EventThread();
325 return(result);
326}
327
328SDL_GrabMode X11_GrabInputNoLock(_THIS, SDL_GrabMode mode)
329{
330 int result;
331
332 if ( this->screen == NULL || SDL_Display == NULL ) {
333 return(SDL_GRAB_OFF);
334 }
335 if ( ! SDL_Window ) {
336 return(mode); /* Will be set later on mode switch */
337 }
338 if ( mode == SDL_GRAB_OFF ) {
339 XUngrabPointer(SDL_Display, CurrentTime);
340 XUngrabKeyboard(SDL_Display, CurrentTime);
341 } else {
342 if ( this->screen->flags & SDL_FULLSCREEN ) {
343 /* Unbind the mouse from the fullscreen window */
344 XUngrabPointer(SDL_Display, CurrentTime);
345 }
346 /* Try to grab the mouse */
347#if 0 /* We'll wait here until we actually grab, otherwise behavior undefined */
348 for ( numtries = 0; numtries < 10; ++numtries ) {
349#else
350 for ( ; ; ) {
351#endif
352 result = XGrabPointer(SDL_Display, SDL_Window, True, 0,
353 GrabModeAsync, GrabModeAsync,
354 SDL_Window, None, CurrentTime);
355 if ( result == GrabSuccess ) {
356 break;
357 }
358 SDL_Delay(100);
359 }
360 if ( result != GrabSuccess ) {
361 /* Uh, oh, what do we do here? */ ;
362 }
363 /* Now grab the keyboard */
364 XGrabKeyboard(SDL_Display, WMwindow, True,
365 GrabModeAsync, GrabModeAsync, CurrentTime);
366
367 /* Raise the window if we grab the mouse */
368 if ( !(this->screen->flags & SDL_FULLSCREEN) )
369 XRaiseWindow(SDL_Display, WMwindow);
370
371 /* Make sure we register input focus */
372 SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS);
373 /* Since we grabbed the pointer, we have mouse focus, too. */
374 SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
375 }
376 XSync(SDL_Display, False);
377
378 return(mode);
379}
380
381SDL_GrabMode X11_GrabInput(_THIS, SDL_GrabMode mode)
382{
383 SDL_Lock_EventThread();
384 mode = X11_GrabInputNoLock(this, mode);
385 SDL_Unlock_EventThread();
386
387 return(mode);
388}
389
390/* If 'info' is the right version, this function fills it and returns 1.
391 Otherwise, in case of a version mismatch, it returns -1.
392*/
393static void lock_display(void)
394{
395 SDL_Lock_EventThread();
396}
397static void unlock_display(void)
398{
399 /* Make sure any X11 transactions are completed */
400 SDL_VideoDevice *this = current_video;
401 XSync(SDL_Display, False);
402 SDL_Unlock_EventThread();
403}
404
405#include <stdio.h>
406int X11_GetWMInfo(_THIS, SDL_SysWMinfo *info)
407{
408 if ( info->version.major <= SDL_MAJOR_VERSION ) {
409 info->subsystem = SDL_SYSWM_X11;
410 info->info.x11.display = SDL_Display;
411 info->info.x11.window = SDL_Window;
412 if ( SDL_VERSIONNUM(info->version.major,
413 info->version.minor,
414 info->version.patch) >= 1002 ) {
415 info->info.x11.fswindow = FSwindow;
416 info->info.x11.wmwindow = WMwindow;
417 }
418
419
420 if ( SDL_VERSIONNUM(info->version.major,
421 info->version.minor,
422 info->version.patch) >= 1212 ) {
423 info->info.x11.gfxdisplay = GFX_Display;
424 }
425
426 info->info.x11.lock_func = lock_display;
427 info->info.x11.unlock_func = unlock_display;
428 return(1);
429 } else {
430 SDL_SetError("Application not compiled with SDL %d.%d\n",
431 SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
432 return(-1);
433 }
434}
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11wm_c.h b/apps/plugins/sdl/src/video/x11/SDL_x11wm_c.h
deleted file mode 100644
index f85477bba1..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11wm_c.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#include "SDL_x11video.h"
25
26/* Functions to be exported */
27extern void X11_SetCaptionNoLock(_THIS, const char *title, const char *icon);
28extern void X11_SetCaption(_THIS, const char *title, const char *icon);
29extern void X11_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask);
30extern int X11_IconifyWindow(_THIS);
31extern SDL_GrabMode X11_GrabInputNoLock(_THIS, SDL_GrabMode mode);
32extern SDL_GrabMode X11_GrabInput(_THIS, SDL_GrabMode mode);
33extern int X11_GetWMInfo(_THIS, SDL_SysWMinfo *info);
34
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11yuv.c b/apps/plugins/sdl/src/video/x11/SDL_x11yuv.c
deleted file mode 100644
index 62698dfd9b..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11yuv.c
+++ /dev/null
@@ -1,538 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the XFree86 Xv extension implementation of YUV video overlays */
25
26#if SDL_VIDEO_DRIVER_X11_XV
27
28#include <X11/Xlib.h>
29#ifndef NO_SHARED_MEMORY
30#include <sys/ipc.h>
31#include <sys/shm.h>
32#include <X11/extensions/XShm.h>
33#endif
34#include "../Xext/extensions/Xvlib.h"
35
36#include "SDL_x11yuv_c.h"
37#include "../SDL_yuvfuncs.h"
38
39#define XFREE86_REFRESH_HACK
40#ifdef XFREE86_REFRESH_HACK
41#include "SDL_x11image_c.h"
42#endif
43
44/* Workaround when pitch != width */
45#define PITCH_WORKAROUND
46
47/* Workaround intel i810 video overlay waiting with failing until the
48 first Xv[Shm]PutImage call <sigh> */
49#define INTEL_XV_BADALLOC_WORKAROUND
50
51/* Fix for the NVidia GeForce 2 - use the last available adaptor */
52/*#define USE_LAST_ADAPTOR*/ /* Apparently the NVidia drivers are fixed */
53
54/* The functions used to manipulate software video overlays */
55static struct private_yuvhwfuncs x11_yuvfuncs = {
56 X11_LockYUVOverlay,
57 X11_UnlockYUVOverlay,
58 X11_DisplayYUVOverlay,
59 X11_FreeYUVOverlay
60};
61
62struct private_yuvhwdata {
63 int port;
64#ifndef NO_SHARED_MEMORY
65 int yuv_use_mitshm;
66 XShmSegmentInfo yuvshm;
67#endif
68 SDL_NAME(XvImage) *image;
69};
70
71
72static int (*X_handler)(Display *, XErrorEvent *) = NULL;
73
74#ifndef NO_SHARED_MEMORY
75/* Shared memory error handler routine */
76static int shm_error;
77static int shm_errhandler(Display *d, XErrorEvent *e)
78{
79 if ( e->error_code == BadAccess ) {
80 shm_error = True;
81 return(0);
82 } else
83 return(X_handler(d,e));
84}
85#endif /* !NO_SHARED_MEMORY */
86
87static int xv_error;
88static int xv_errhandler(Display *d, XErrorEvent *e)
89{
90 if ( e->error_code == BadMatch ) {
91 xv_error = True;
92 return(0);
93 } else
94 return(X_handler(d,e));
95}
96
97#ifdef INTEL_XV_BADALLOC_WORKAROUND
98static int intel_errhandler(Display *d, XErrorEvent *e)
99{
100 if ( e->error_code == BadAlloc ) {
101 xv_error = True;
102 return(0);
103 } else
104 return(X_handler(d,e));
105}
106
107static void X11_ClearYUVOverlay(SDL_Overlay *overlay)
108{
109 int x,y;
110
111 switch (overlay->format)
112 {
113 case SDL_YV12_OVERLAY:
114 case SDL_IYUV_OVERLAY:
115 for (y = 0; y < overlay->h; y++)
116 memset(overlay->pixels[0] + y * overlay->pitches[0],
117 0, overlay->w);
118
119 for (y = 0; y < (overlay->h / 2); y++)
120 {
121 memset(overlay->pixels[1] + y * overlay->pitches[1],
122 -128, overlay->w / 2);
123 memset(overlay->pixels[2] + y * overlay->pitches[2],
124 -128, overlay->w / 2);
125 }
126 break;
127 case SDL_YUY2_OVERLAY:
128 case SDL_YVYU_OVERLAY:
129 for (y = 0; y < overlay->h; y++)
130 {
131 for (x = 0; x < overlay->w; x += 2)
132 {
133 Uint8 *pixel_pair = overlay->pixels[0] +
134 y * overlay->pitches[0] + x * 2;
135 pixel_pair[0] = 0;
136 pixel_pair[1] = -128;
137 pixel_pair[2] = 0;
138 pixel_pair[3] = -128;
139 }
140 }
141 break;
142 case SDL_UYVY_OVERLAY:
143 for (y = 0; y < overlay->h; y++)
144 {
145 for (x = 0; x < overlay->w; x += 2)
146 {
147 Uint8 *pixel_pair = overlay->pixels[0] +
148 y * overlay->pitches[0] + x * 2;
149 pixel_pair[0] = -128;
150 pixel_pair[1] = 0;
151 pixel_pair[2] = -128;
152 pixel_pair[3] = 0;
153 }
154 }
155 break;
156 }
157}
158#endif
159
160SDL_Overlay *X11_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display)
161{
162 SDL_Overlay *overlay;
163 struct private_yuvhwdata *hwdata;
164 int xv_port;
165 unsigned int i, j, k;
166 unsigned int adaptors;
167 SDL_NAME(XvAdaptorInfo) *ainfo;
168 int bpp;
169#ifndef NO_SHARED_MEMORY
170 XShmSegmentInfo *yuvshm;
171#endif
172#ifdef INTEL_XV_BADALLOC_WORKAROUND
173 int intel_adapter = False;
174#endif
175
176 /* Look for the XVideo extension with a valid port for this format */
177 xv_port = -1;
178 if ( (Success == SDL_NAME(XvQueryExtension)(GFX_Display, &j, &j, &j, &j, &j)) &&
179 (Success == SDL_NAME(XvQueryAdaptors)(GFX_Display,
180 RootWindow(GFX_Display, SDL_Screen),
181 &adaptors, &ainfo)) ) {
182#ifdef USE_LAST_ADAPTOR
183 for ( i=0; i < adaptors; ++i )
184#else
185 for ( i=0; (i < adaptors) && (xv_port == -1); ++i )
186#endif /* USE_LAST_ADAPTOR */
187 {
188 /* Check to see if the visual can be used */
189 if ( BUGGY_XFREE86(<=, 4001) ) {
190 int visual_ok = 0;
191 for ( j=0; j<ainfo[i].num_formats; ++j ) {
192 if ( ainfo[i].formats[j].visual_id ==
193 SDL_Visual->visualid ) {
194 visual_ok = 1;
195 break;
196 }
197 }
198 if ( ! visual_ok ) {
199 continue;
200 }
201 }
202#ifdef INTEL_XV_BADALLOC_WORKAROUND
203 if ( !strcmp(ainfo[i].name, "Intel(R) Video Overla"))
204 intel_adapter = True;
205 else
206 intel_adapter = False;
207#endif
208 if ( (ainfo[i].type & XvInputMask) &&
209 (ainfo[i].type & XvImageMask) ) {
210 int num_formats;
211 SDL_NAME(XvImageFormatValues) *formats;
212 formats = SDL_NAME(XvListImageFormats)(GFX_Display,
213 ainfo[i].base_id, &num_formats);
214#ifdef USE_LAST_ADAPTOR
215 for ( j=0; j < num_formats; ++j )
216#else
217 for ( j=0; (j < num_formats) && (xv_port == -1); ++j )
218#endif /* USE_LAST_ADAPTOR */
219 {
220 if ( (Uint32)formats[j].id == format ) {
221 for ( k=0; k < ainfo[i].num_ports; ++k ) {
222 if ( Success == SDL_NAME(XvGrabPort)(GFX_Display, ainfo[i].base_id+k, CurrentTime) ) {
223 xv_port = ainfo[i].base_id+k;
224 break;
225 }
226 }
227 }
228 }
229 if ( formats ) {
230 XFree(formats);
231 }
232 }
233 }
234 SDL_NAME(XvFreeAdaptorInfo)(ainfo);
235 }
236
237 /* Precalculate the bpp for the pitch workaround below */
238 switch (format) {
239 /* Add any other cases we need to support... */
240 case SDL_YUY2_OVERLAY:
241 case SDL_UYVY_OVERLAY:
242 case SDL_YVYU_OVERLAY:
243 bpp = 2;
244 break;
245 default:
246 bpp = 1;
247 break;
248 }
249
250#if 0
251 /*
252 * !!! FIXME:
253 * "Here are some diffs for X11 and yuv. Note that the last part 2nd
254 * diff should probably be a new call to XvQueryAdaptorFree with ainfo
255 * and the number of adaptors, instead of the loop through like I did."
256 *
257 * ACHTUNG: This is broken! It looks like XvFreeAdaptorInfo does this
258 * for you, so we end up with a double-free. I need to look at this
259 * more closely... --ryan.
260 */
261 for ( i=0; i < adaptors; ++i ) {
262 if (ainfo[i].name != NULL) Xfree(ainfo[i].name);
263 if (ainfo[i].formats != NULL) Xfree(ainfo[i].formats);
264 }
265 Xfree(ainfo);
266#endif
267
268 if ( xv_port == -1 ) {
269 SDL_SetError("No available video ports for requested format");
270 return(NULL);
271 }
272
273 /* Enable auto-painting of the overlay colorkey */
274 {
275 static const char *attr[] = { "XV_AUTOPAINT_COLORKEY", "XV_AUTOPAINT_COLOURKEY" };
276 unsigned int i;
277
278 SDL_NAME(XvSelectPortNotify)(GFX_Display, xv_port, True);
279 X_handler = XSetErrorHandler(xv_errhandler);
280 for ( i=0; i < sizeof(attr)/(sizeof attr[0]); ++i ) {
281 Atom a;
282
283 xv_error = False;
284 a = XInternAtom(GFX_Display, attr[i], True);
285 if ( a != None ) {
286 SDL_NAME(XvSetPortAttribute)(GFX_Display, xv_port, a, 1);
287 XSync(GFX_Display, True);
288 if ( ! xv_error ) {
289 break;
290 }
291 }
292 }
293 XSetErrorHandler(X_handler);
294 SDL_NAME(XvSelectPortNotify)(GFX_Display, xv_port, False);
295 }
296
297 /* Create the overlay structure */
298 overlay = (SDL_Overlay *)SDL_malloc(sizeof *overlay);
299 if ( overlay == NULL ) {
300 SDL_NAME(XvUngrabPort)(GFX_Display, xv_port, CurrentTime);
301 SDL_OutOfMemory();
302 return(NULL);
303 }
304 SDL_memset(overlay, 0, (sizeof *overlay));
305
306 /* Fill in the basic members */
307 overlay->format = format;
308 overlay->w = width;
309 overlay->h = height;
310
311 /* Set up the YUV surface function structure */
312 overlay->hwfuncs = &x11_yuvfuncs;
313 overlay->hw_overlay = 1;
314
315 /* Create the pixel data and lookup tables */
316 hwdata = (struct private_yuvhwdata *)SDL_malloc(sizeof *hwdata);
317 overlay->hwdata = hwdata;
318 if ( hwdata == NULL ) {
319 SDL_NAME(XvUngrabPort)(GFX_Display, xv_port, CurrentTime);
320 SDL_OutOfMemory();
321 SDL_FreeYUVOverlay(overlay);
322 return(NULL);
323 }
324 hwdata->port = xv_port;
325#ifndef NO_SHARED_MEMORY
326 yuvshm = &hwdata->yuvshm;
327 SDL_memset(yuvshm, 0, sizeof(*yuvshm));
328 hwdata->image = SDL_NAME(XvShmCreateImage)(GFX_Display, xv_port, format,
329 0, width, height, yuvshm);
330#ifdef PITCH_WORKAROUND
331 if ( hwdata->image != NULL && hwdata->image->pitches[0] != (width*bpp) ) {
332 /* Ajust overlay width according to pitch */
333 width = hwdata->image->pitches[0] / bpp;
334 XFree(hwdata->image);
335 hwdata->image = SDL_NAME(XvShmCreateImage)(GFX_Display, xv_port, format,
336 0, width, height, yuvshm);
337 }
338#endif /* PITCH_WORKAROUND */
339 hwdata->yuv_use_mitshm = (hwdata->image != NULL);
340 if ( hwdata->yuv_use_mitshm ) {
341 yuvshm->shmid = shmget(IPC_PRIVATE, hwdata->image->data_size,
342 IPC_CREAT | 0777);
343 if ( yuvshm->shmid >= 0 ) {
344 yuvshm->shmaddr = (char *)shmat(yuvshm->shmid, 0, 0);
345 yuvshm->readOnly = False;
346 if ( yuvshm->shmaddr != (char *)-1 ) {
347 shm_error = False;
348 X_handler = XSetErrorHandler(shm_errhandler);
349 XShmAttach(GFX_Display, yuvshm);
350 XSync(GFX_Display, True);
351 XSetErrorHandler(X_handler);
352 if ( shm_error )
353 shmdt(yuvshm->shmaddr);
354 } else {
355 shm_error = True;
356 }
357 shmctl(yuvshm->shmid, IPC_RMID, NULL);
358 } else {
359 shm_error = True;
360 }
361 if ( shm_error ) {
362 XFree(hwdata->image);
363 hwdata->yuv_use_mitshm = 0;
364 } else {
365 hwdata->image->data = yuvshm->shmaddr;
366 }
367 }
368 if ( !hwdata->yuv_use_mitshm )
369#endif /* NO_SHARED_MEMORY */
370 {
371 hwdata->image = SDL_NAME(XvCreateImage)(GFX_Display, xv_port, format,
372 0, width, height);
373
374#ifdef PITCH_WORKAROUND
375 if ( hwdata->image != NULL && hwdata->image->pitches[0] != (width*bpp) ) {
376 /* Ajust overlay width according to pitch */
377 XFree(hwdata->image);
378 width = hwdata->image->pitches[0] / bpp;
379 hwdata->image = SDL_NAME(XvCreateImage)(GFX_Display, xv_port, format,
380 0, width, height);
381 }
382#endif /* PITCH_WORKAROUND */
383 if ( hwdata->image == NULL ) {
384 SDL_SetError("Couldn't create XVideo image");
385 SDL_FreeYUVOverlay(overlay);
386 return(NULL);
387 }
388 hwdata->image->data = SDL_malloc(hwdata->image->data_size);
389 if ( hwdata->image->data == NULL ) {
390 SDL_OutOfMemory();
391 SDL_FreeYUVOverlay(overlay);
392 return(NULL);
393 }
394 }
395
396 /* Find the pitch and offset values for the overlay */
397 overlay->planes = hwdata->image->num_planes;
398 overlay->pitches = (Uint16 *)SDL_malloc(overlay->planes * sizeof(Uint16));
399 overlay->pixels = (Uint8 **)SDL_malloc(overlay->planes * sizeof(Uint8 *));
400 if ( !overlay->pitches || !overlay->pixels ) {
401 SDL_OutOfMemory();
402 SDL_FreeYUVOverlay(overlay);
403 return(NULL);
404 }
405 for ( i=0; i<overlay->planes; ++i ) {
406 overlay->pitches[i] = hwdata->image->pitches[i];
407 overlay->pixels[i] = (Uint8 *)hwdata->image->data +
408 hwdata->image->offsets[i];
409 }
410
411#ifdef XFREE86_REFRESH_HACK
412 /* Work around an XFree86 X server bug (?)
413 We can't perform normal updates in windows that have video
414 being output to them. See SDL_x11image.c for more details.
415 */
416 X11_DisableAutoRefresh(this);
417#endif
418
419#ifdef INTEL_XV_BADALLOC_WORKAROUND
420 /* HACK, GRRR sometimes (i810) creating the overlay succeeds, but the
421 first call to XvShm[Put]Image to a mapped window fails with:
422 "BadAlloc (insufficient resources for operation)". This happens with
423 certain formats when the XvImage is too large to the i810's liking.
424
425 We work around this by doing a test XvShm[Put]Image with a black
426 Xv image, this may cause some flashing, so only do this check if we
427 are running on an intel Xv-adapter. */
428 if (intel_adapter)
429 {
430 xv_error = False;
431 X_handler = XSetErrorHandler(intel_errhandler);
432
433 X11_ClearYUVOverlay(overlay);
434
435 /* We set the destination height and width to 1 pixel to avoid
436 putting a large black rectangle over the screen, thus
437 strongly reducing possible flashing. */
438#ifndef NO_SHARED_MEMORY
439 if ( hwdata->yuv_use_mitshm ) {
440 SDL_NAME(XvShmPutImage)(GFX_Display, hwdata->port,
441 SDL_Window, SDL_GC,
442 hwdata->image,
443 0, 0, overlay->w, overlay->h,
444 0, 0, 1, 1, False);
445 }
446 else
447#endif
448 {
449 SDL_NAME(XvPutImage)(GFX_Display, hwdata->port,
450 SDL_Window, SDL_GC,
451 hwdata->image,
452 0, 0, overlay->w, overlay->h,
453 0, 0, 1, 1);
454 }
455 XSync(GFX_Display, False);
456 XSetErrorHandler(X_handler);
457
458 if (xv_error)
459 {
460 X11_FreeYUVOverlay(this, overlay);
461 return NULL;
462 }
463 /* Repair the (1 pixel worth of) damage we've just done */
464 X11_RefreshDisplay(this);
465 }
466#endif
467
468 /* We're all done.. */
469 return(overlay);
470}
471
472int X11_LockYUVOverlay(_THIS, SDL_Overlay *overlay)
473{
474 return(0);
475}
476
477void X11_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay)
478{
479 return;
480}
481
482int X11_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst)
483{
484 struct private_yuvhwdata *hwdata;
485
486 hwdata = overlay->hwdata;
487
488#ifndef NO_SHARED_MEMORY
489 if ( hwdata->yuv_use_mitshm ) {
490 SDL_NAME(XvShmPutImage)(GFX_Display, hwdata->port, SDL_Window, SDL_GC,
491 hwdata->image,
492 src->x, src->y, src->w, src->h,
493 dst->x, dst->y, dst->w, dst->h, False);
494 }
495 else
496#endif
497 {
498 SDL_NAME(XvPutImage)(GFX_Display, hwdata->port, SDL_Window, SDL_GC,
499 hwdata->image,
500 src->x, src->y, src->w, src->h,
501 dst->x, dst->y, dst->w, dst->h);
502 }
503 XSync(GFX_Display, False);
504 return(0);
505}
506
507void X11_FreeYUVOverlay(_THIS, SDL_Overlay *overlay)
508{
509 struct private_yuvhwdata *hwdata;
510
511 hwdata = overlay->hwdata;
512 if ( hwdata ) {
513 SDL_NAME(XvUngrabPort)(GFX_Display, hwdata->port, CurrentTime);
514#ifndef NO_SHARED_MEMORY
515 if ( hwdata->yuv_use_mitshm ) {
516 XShmDetach(GFX_Display, &hwdata->yuvshm);
517 shmdt(hwdata->yuvshm.shmaddr);
518 }
519#endif
520 if ( hwdata->image ) {
521 XFree(hwdata->image);
522 }
523 SDL_free(hwdata);
524 }
525 if ( overlay->pitches ) {
526 SDL_free(overlay->pitches);
527 overlay->pitches = NULL;
528 }
529 if ( overlay->pixels ) {
530 SDL_free(overlay->pixels);
531 overlay->pixels = NULL;
532 }
533#ifdef XFREE86_REFRESH_HACK
534 X11_EnableAutoRefresh(this);
535#endif
536}
537
538#endif /* SDL_VIDEO_DRIVER_X11_XV */
diff --git a/apps/plugins/sdl/src/video/x11/SDL_x11yuv_c.h b/apps/plugins/sdl/src/video/x11/SDL_x11yuv_c.h
deleted file mode 100644
index d297683c24..0000000000
--- a/apps/plugins/sdl/src/video/x11/SDL_x11yuv_c.h
+++ /dev/null
@@ -1,41 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This is the XFree86 Xv extension implementation of YUV video overlays */
25
26#include "SDL_video.h"
27#include "SDL_x11video.h"
28
29#if SDL_VIDEO_DRIVER_X11_XV
30
31extern SDL_Overlay *X11_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display);
32
33extern int X11_LockYUVOverlay(_THIS, SDL_Overlay *overlay);
34
35extern void X11_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay);
36
37extern int X11_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst);
38
39extern void X11_FreeYUVOverlay(_THIS, SDL_Overlay *overlay);
40
41#endif /* SDL_VIDEO_DRIVER_X11_XV */
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios.c b/apps/plugins/sdl/src/video/xbios/SDL_xbios.c
deleted file mode 100644
index 56bf6abd6f..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios.c
+++ /dev/null
@@ -1,1116 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 * Xbios SDL video driver
26 *
27 * Patrice Mandin
28 */
29
30#include <sys/stat.h>
31#include <unistd.h>
32
33/* Mint includes */
34#include <mint/cookie.h>
35#include <mint/osbind.h>
36#include <mint/falcon.h>
37
38#include "SDL_video.h"
39#include "SDL_mouse.h"
40#include "../SDL_sysvideo.h"
41#include "../SDL_pixels_c.h"
42#include "../../events/SDL_events_c.h"
43
44#include "../ataricommon/SDL_ataric2p_s.h"
45#include "../ataricommon/SDL_atarievents_c.h"
46#include "../ataricommon/SDL_atarimxalloc_c.h"
47#include "../ataricommon/SDL_atarigl_c.h"
48#include "SDL_xbios.h"
49#include "SDL_xbios_blowup.h"
50#include "SDL_xbios_centscreen.h"
51#include "SDL_xbios_sb3.h"
52#include "SDL_xbios_tveille.h"
53#include "SDL_xbios_milan.h"
54
55#define XBIOS_VID_DRIVER_NAME "xbios"
56
57#ifndef C_fVDI
58#define C_fVDI 0x66564449L
59#endif
60
61/* Debug print info */
62#if 0
63#define DEBUG_PRINT(what) \
64 { \
65 printf what; \
66 }
67#define DEBUG_VIDEO_XBIOS 1
68#else
69#define DEBUG_PRINT(what)
70#undef DEBUG_VIDEO_XBIOS
71#endif
72
73/* Initialization/Query functions */
74static int XBIOS_VideoInit(_THIS, SDL_PixelFormat *vformat);
75static SDL_Rect **XBIOS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags);
76static SDL_Surface *XBIOS_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
77static int XBIOS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
78static void XBIOS_VideoQuit(_THIS);
79
80/* Hardware surface functions */
81static int XBIOS_AllocHWSurface(_THIS, SDL_Surface *surface);
82static int XBIOS_LockHWSurface(_THIS, SDL_Surface *surface);
83static int XBIOS_FlipHWSurface(_THIS, SDL_Surface *surface);
84static void XBIOS_UnlockHWSurface(_THIS, SDL_Surface *surface);
85static void XBIOS_FreeHWSurface(_THIS, SDL_Surface *surface);
86static void XBIOS_UpdateRects(_THIS, int numrects, SDL_Rect *rects);
87
88#if SDL_VIDEO_OPENGL
89/* OpenGL functions */
90static void XBIOS_GL_SwapBuffers(_THIS);
91#endif
92
93/* To setup palette */
94
95static unsigned short TT_palette[256];
96static unsigned long F30_palette[256];
97
98/* Default list of video modes */
99
100static const xbiosmode_t stmodes[1]={
101 {ST_LOW>>8,320,200,4, XBIOSMODE_C2P}
102};
103
104static const xbiosmode_t ttmodes[2]={
105 {TT_LOW,320,480,8, XBIOSMODE_C2P},
106 {TT_LOW,320,240,8, XBIOSMODE_C2P|XBIOSMODE_DOUBLELINE}
107};
108
109static const xbiosmode_t falconrgbmodes[16]={
110 {BPS16|COL80|OVERSCAN|VERTFLAG,768,480,16,0},
111 {BPS16|COL80|OVERSCAN,768,240,16,0},
112 {BPS16|COL80|VERTFLAG,640,400,16,0},
113 {BPS16|COL80,640,200,16,0},
114 {BPS16|OVERSCAN|VERTFLAG,384,480,16,0},
115 {BPS16|OVERSCAN,384,240,16,0},
116 {BPS16|VERTFLAG,320,400,16,0},
117 {BPS16,320,200,16,0},
118 {BPS8|COL80|OVERSCAN|VERTFLAG,768,480,8,XBIOSMODE_C2P},
119 {BPS8|COL80|OVERSCAN,768,240,8,XBIOSMODE_C2P},
120 {BPS8|COL80|VERTFLAG,640,400,8,XBIOSMODE_C2P},
121 {BPS8|COL80,640,200,8,XBIOSMODE_C2P},
122 {BPS8|OVERSCAN|VERTFLAG,384,480,8,XBIOSMODE_C2P},
123 {BPS8|OVERSCAN,384,240,8,XBIOSMODE_C2P},
124 {BPS8|VERTFLAG,320,400,8,XBIOSMODE_C2P},
125 {BPS8,320,200,8,XBIOSMODE_C2P}
126};
127
128static const xbiosmode_t falconvgamodes[6]={
129 {BPS16,320,480,16,0},
130 {BPS16|VERTFLAG,320,240,16,0},
131 {BPS8|COL80,640,480,8,XBIOSMODE_C2P},
132 {BPS8|COL80|VERTFLAG,640,240,8,XBIOSMODE_C2P},
133 {BPS8,320,480,8,XBIOSMODE_C2P},
134 {BPS8|VERTFLAG,320,240,8,XBIOSMODE_C2P}
135};
136
137/* Xbios driver bootstrap functions */
138
139static int XBIOS_Available(void)
140{
141 long cookie_vdo, /*cookie_mil,*/ cookie_hade, cookie_scpn;
142 long cookie_fvdi;
143 const char *envr = SDL_getenv("SDL_VIDEODRIVER");
144
145 /* Milan/Hades Atari clones do not have an Atari video chip */
146 if ( /*(Getcookie(C__MIL, &cookie_mil) == C_FOUND) ||*/
147 (Getcookie(C_hade, &cookie_hade) == C_FOUND) ) {
148 return 0;
149 }
150
151 /* fVDI means graphic card, so no Xbios with it */
152 if (Getcookie(C_fVDI, &cookie_fvdi) == C_FOUND) {
153 if (!envr) {
154 return 0;
155 }
156 if (SDL_strcmp(envr, XBIOS_VID_DRIVER_NAME)!=0) {
157 return 0;
158 }
159 /* Except if we force Xbios usage, through env var */
160 }
161
162 /* Cookie _VDO present ? if not, assume ST machine */
163 if (Getcookie(C__VDO, &cookie_vdo) != C_FOUND) {
164 cookie_vdo = VDO_ST << 16;
165 }
166
167 /* Test if we have a monochrome monitor plugged in */
168 switch( cookie_vdo >>16) {
169 case VDO_ST:
170 case VDO_STE:
171 if ( Getrez() == (ST_HIGH>>8) )
172 return 0;
173 break;
174 case VDO_TT:
175 if ( (EgetShift() & ES_MODE) == TT_HIGH)
176 return 0;
177 break;
178 case VDO_F30:
179 if ( VgetMonitor() == MONITOR_MONO)
180 return 0;
181 if (Getcookie(C_SCPN, &cookie_scpn) == C_FOUND) {
182 if (!SDL_XBIOS_SB3Usable((scpn_cookie_t *)cookie_scpn)) {
183 return 0;
184 }
185 }
186 break;
187 case VDO_MILAN:
188 break;
189 default:
190 return 0;
191 }
192
193 return 1;
194}
195
196static void XBIOS_DeleteDevice(SDL_VideoDevice *device)
197{
198 SDL_free(device->hidden);
199 SDL_free(device);
200}
201
202static SDL_VideoDevice *XBIOS_CreateDevice(int devindex)
203{
204 SDL_VideoDevice *device;
205
206 /* Initialize all variables that we clean on shutdown */
207 device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
208 if ( device ) {
209 SDL_memset(device, 0, (sizeof *device));
210 device->hidden = (struct SDL_PrivateVideoData *)
211 SDL_malloc((sizeof *device->hidden));
212 device->gl_data = (struct SDL_PrivateGLData *)
213 SDL_malloc((sizeof *device->gl_data));
214 }
215 if ( (device == NULL) || (device->hidden == NULL) ) {
216 SDL_OutOfMemory();
217 if ( device ) {
218 SDL_free(device);
219 }
220 return(0);
221 }
222 SDL_memset(device->hidden, 0, (sizeof *device->hidden));
223 SDL_memset(device->gl_data, 0, sizeof(*device->gl_data));
224
225 /* Video functions */
226 device->VideoInit = XBIOS_VideoInit;
227 device->ListModes = XBIOS_ListModes;
228 device->SetVideoMode = XBIOS_SetVideoMode;
229 device->SetColors = XBIOS_SetColors;
230 device->UpdateRects = NULL;
231 device->VideoQuit = XBIOS_VideoQuit;
232 device->AllocHWSurface = XBIOS_AllocHWSurface;
233 device->LockHWSurface = XBIOS_LockHWSurface;
234 device->UnlockHWSurface = XBIOS_UnlockHWSurface;
235 device->FlipHWSurface = XBIOS_FlipHWSurface;
236 device->FreeHWSurface = XBIOS_FreeHWSurface;
237
238#if SDL_VIDEO_OPENGL
239 /* OpenGL functions */
240 device->GL_LoadLibrary = SDL_AtariGL_LoadLibrary;
241 device->GL_GetProcAddress = SDL_AtariGL_GetProcAddress;
242 device->GL_GetAttribute = SDL_AtariGL_GetAttribute;
243 device->GL_MakeCurrent = SDL_AtariGL_MakeCurrent;
244 device->GL_SwapBuffers = XBIOS_GL_SwapBuffers;
245#endif
246
247 /* Events */
248 device->InitOSKeymap = Atari_InitOSKeymap;
249 device->PumpEvents = Atari_PumpEvents;
250
251 device->free = XBIOS_DeleteDevice;
252
253 return device;
254}
255
256VideoBootStrap XBIOS_bootstrap = {
257 XBIOS_VID_DRIVER_NAME, "Atari Xbios driver",
258 XBIOS_Available, XBIOS_CreateDevice
259};
260
261void SDL_XBIOS_AddMode(_THIS, int actually_add, const xbiosmode_t *modeinfo)
262{
263 int i = 0;
264
265 switch(modeinfo->depth) {
266 case 15:
267 case 16:
268 i = 1;
269 break;
270 case 24:
271 i = 2;
272 break;
273 case 32:
274 i = 3;
275 break;
276 }
277
278 if ( actually_add ) {
279 SDL_Rect saved_rect[2];
280 xbiosmode_t saved_mode[2];
281 int b, j;
282
283 /* Add the mode, sorted largest to smallest */
284 b = 0;
285 j = 0;
286 while ( (SDL_modelist[i][j]->w > modeinfo->width) ||
287 (SDL_modelist[i][j]->h > modeinfo->height) ) {
288 ++j;
289 }
290 /* Skip modes that are already in our list */
291 if ( (SDL_modelist[i][j]->w == modeinfo->width) &&
292 (SDL_modelist[i][j]->h == modeinfo->height) ) {
293 return;
294 }
295 /* Insert the new mode */
296 saved_rect[b] = *SDL_modelist[i][j];
297 SDL_memcpy(&saved_mode[b], SDL_xbiosmode[i][j], sizeof(xbiosmode_t));
298 SDL_modelist[i][j]->w = modeinfo->width;
299 SDL_modelist[i][j]->h = modeinfo->height;
300 SDL_memcpy(SDL_xbiosmode[i][j], modeinfo, sizeof(xbiosmode_t));
301 /* Everybody scoot down! */
302 if ( saved_rect[b].w && saved_rect[b].h ) {
303 for ( ++j; SDL_modelist[i][j]->w; ++j ) {
304 saved_rect[!b] = *SDL_modelist[i][j];
305 memcpy(&saved_mode[!b], SDL_xbiosmode[i][j], sizeof(xbiosmode_t));
306 *SDL_modelist[i][j] = saved_rect[b];
307 SDL_memcpy(SDL_xbiosmode[i][j], &saved_mode[b], sizeof(xbiosmode_t));
308 b = !b;
309 }
310 *SDL_modelist[i][j] = saved_rect[b];
311 SDL_memcpy(SDL_xbiosmode[i][j], &saved_mode[b], sizeof(xbiosmode_t));
312 }
313 } else {
314 ++SDL_nummodes[i];
315 }
316}
317
318static void XBIOS_ListSTModes(_THIS, int actually_add)
319{
320 SDL_XBIOS_AddMode(this, actually_add, &stmodes[0]);
321}
322
323static void XBIOS_ListTTModes(_THIS, int actually_add)
324{
325 int i;
326
327 for (i=0; i<2; i++) {
328 SDL_XBIOS_AddMode(this, actually_add, &ttmodes[i]);
329 }
330}
331
332static void XBIOS_ListFalconRgbModes(_THIS, int actually_add)
333{
334 int i;
335
336 for (i=0; i<16; i++) {
337 xbiosmode_t modeinfo;
338
339 SDL_memcpy(&modeinfo, &falconrgbmodes[i], sizeof(xbiosmode_t));
340 modeinfo.number &= ~(VGA|PAL);
341 modeinfo.number |= XBIOS_oldvmode & (VGA|PAL);
342
343 SDL_XBIOS_AddMode(this, actually_add, &modeinfo);
344 }
345}
346
347static void XBIOS_ListFalconVgaModes(_THIS, int actually_add)
348{
349 int i;
350
351 for (i=0; i<6; i++) {
352 xbiosmode_t modeinfo;
353
354 SDL_memcpy(&modeinfo, &falconvgamodes[i], sizeof(xbiosmode_t));
355 modeinfo.number &= ~(VGA|PAL);
356 modeinfo.number |= XBIOS_oldvmode & (VGA|PAL);
357
358 SDL_XBIOS_AddMode(this, actually_add, &modeinfo);
359 }
360}
361
362static int XBIOS_VideoInit(_THIS, SDL_PixelFormat *vformat)
363{
364 int i;
365 long cookie_blow, cookie_scpn, cookie_cnts;
366
367 /* Initialize all variables that we clean on shutdown */
368 for ( i=0; i<NUM_MODELISTS; ++i ) {
369 SDL_nummodes[i] = 0;
370 SDL_modelist[i] = NULL;
371 SDL_xbiosmode[i] = NULL;
372 }
373
374 /* Cookie _VDO present ? if not, assume ST machine */
375 if (Getcookie(C__VDO, &XBIOS_cvdo) != C_FOUND) {
376 XBIOS_cvdo = VDO_ST << 16;
377 }
378
379 /* Allocate memory for old palette */
380 XBIOS_oldpalette = (void *)SDL_malloc(256*sizeof(long));
381 if ( !XBIOS_oldpalette ) {
382 SDL_SetError("Unable to allocate memory for old palette\n");
383 return(-1);
384 }
385
386 /* Initialize video mode list */
387 /* and save current screen status (palette, screen address, video mode) */
388 XBIOS_centscreen = SDL_FALSE;
389 XBIOS_oldvbase = Physbase();
390
391 /* Determine the current screen size */
392 this->info.current_w = 0;
393 this->info.current_h = 0;
394
395 /* Determine the screen depth (use default 8-bit depth) */
396 vformat->BitsPerPixel = 8;
397
398 /* First allocate room for needed video modes */
399 switch (XBIOS_cvdo >>16) {
400 case VDO_ST:
401 case VDO_STE:
402 {
403 short *oldpalette;
404
405 XBIOS_oldvmode=Getrez();
406 switch(XBIOS_oldvmode << 8) {
407 case ST_LOW:
408 XBIOS_oldnumcol=16;
409 break;
410 case ST_MED:
411 XBIOS_oldnumcol=4;
412 break;
413 case ST_HIGH:
414 XBIOS_oldnumcol=2;
415 break;
416 }
417
418 oldpalette= (short *) XBIOS_oldpalette;
419 for (i=0;i<XBIOS_oldnumcol;i++) {
420 *oldpalette++=Setcolor(i,-1);
421 }
422
423 XBIOS_ListSTModes(this, 0);
424 }
425 break;
426 case VDO_TT:
427 XBIOS_oldvmode=EgetShift();
428
429 switch(XBIOS_oldvmode & ES_MODE) {
430 case TT_LOW:
431 XBIOS_oldnumcol=256;
432 break;
433 case ST_LOW:
434 case TT_MED:
435 XBIOS_oldnumcol=16;
436 break;
437 case ST_MED:
438 XBIOS_oldnumcol=4;
439 break;
440 case ST_HIGH:
441 case TT_HIGH:
442 XBIOS_oldnumcol=2;
443 break;
444 }
445 if (XBIOS_oldnumcol) {
446 EgetPalette(0, XBIOS_oldnumcol, XBIOS_oldpalette);
447 }
448
449 XBIOS_ListTTModes(this, 0);
450 break;
451 case VDO_F30:
452 XBIOS_oldvmode=VsetMode(-1);
453
454 XBIOS_oldnumcol= 1<< (1 << (XBIOS_oldvmode & NUMCOLS));
455 if (XBIOS_oldnumcol > 256) {
456 XBIOS_oldnumcol = 0;
457 }
458 if (XBIOS_oldnumcol) {
459 VgetRGB(0, XBIOS_oldnumcol, XBIOS_oldpalette);
460 }
461
462 vformat->BitsPerPixel = 16;
463
464 /* ScreenBlaster 3 ? */
465 if (Getcookie(C_SCPN, &cookie_scpn) == C_FOUND) {
466 SDL_XBIOS_ListSB3Modes(this, 0, (scpn_cookie_t *)cookie_scpn);
467 } else
468 /* Centscreen ? */
469 if (Getcookie(C_CNTS, &cookie_cnts) == C_FOUND) {
470 XBIOS_oldvmode = SDL_XBIOS_ListCentscreenModes(this, 0);
471 XBIOS_centscreen = SDL_TRUE;
472 } else
473 /* Standard, with or without Blowup */
474 {
475 switch (VgetMonitor())
476 {
477 case MONITOR_RGB:
478 case MONITOR_TV:
479 XBIOS_ListFalconRgbModes(this, 0);
480 break;
481 case MONITOR_VGA:
482 XBIOS_ListFalconVgaModes(this, 0);
483 break;
484 }
485
486 if (Getcookie(C_BLOW, &cookie_blow) == C_FOUND) {
487 SDL_XBIOS_ListBlowupModes(this, 0, (blow_cookie_t *)cookie_blow);
488 }
489 }
490 break;
491 case VDO_MILAN:
492 {
493 SCREENINFO si;
494
495 /* Read infos about current mode */
496 VsetScreen(-1, &XBIOS_oldvmode, MI_MAGIC, CMD_GETMODE);
497
498 si.size = sizeof(SCREENINFO);
499 si.devID = XBIOS_oldvmode;
500 si.scrFlags = 0;
501 VsetScreen(-1, &si, MI_MAGIC, CMD_GETINFO);
502
503 this->info.current_w = si.scrWidth;
504 this->info.current_h = si.scrHeight;
505
506 XBIOS_oldnumcol = 0;
507 if (si.scrFlags & SCRINFO_OK) {
508 if (si.scrPlanes <= 8) {
509 XBIOS_oldnumcol = 1<<si.scrPlanes;
510 }
511 }
512 if (XBIOS_oldnumcol) {
513 VgetRGB(0, XBIOS_oldnumcol, XBIOS_oldpalette);
514 }
515
516 SDL_XBIOS_ListMilanModes(this, 0);
517 }
518 break;
519 }
520
521 for ( i=0; i<NUM_MODELISTS; ++i ) {
522 int j;
523
524 SDL_xbiosmode[i] = (xbiosmode_t **)
525 SDL_malloc((SDL_nummodes[i]+1)*sizeof(xbiosmode_t *));
526 if ( SDL_xbiosmode[i] == NULL ) {
527 SDL_OutOfMemory();
528 return(-1);
529 }
530 for ( j=0; j<SDL_nummodes[i]; ++j ) {
531 SDL_xbiosmode[i][j]=(xbiosmode_t *)SDL_malloc(sizeof(xbiosmode_t));
532 if ( SDL_xbiosmode[i][j] == NULL ) {
533 SDL_OutOfMemory();
534 return(-1);
535 }
536 SDL_memset(SDL_xbiosmode[i][j], 0, sizeof(xbiosmode_t));
537 }
538 SDL_xbiosmode[i][j] = NULL;
539
540 SDL_modelist[i] = (SDL_Rect **)
541 SDL_malloc((SDL_nummodes[i]+1)*sizeof(SDL_Rect *));
542 if ( SDL_modelist[i] == NULL ) {
543 SDL_OutOfMemory();
544 return(-1);
545 }
546 for ( j=0; j<SDL_nummodes[i]; ++j ) {
547 SDL_modelist[i][j]=(SDL_Rect *)SDL_malloc(sizeof(SDL_Rect));
548 if ( SDL_modelist[i][j] == NULL ) {
549 SDL_OutOfMemory();
550 return(-1);
551 }
552 SDL_memset(SDL_modelist[i][j], 0, sizeof(SDL_Rect));
553 }
554 SDL_modelist[i][j] = NULL;
555 }
556
557 /* Now fill the mode list */
558 switch (XBIOS_cvdo >>16) {
559 case VDO_ST:
560 case VDO_STE:
561 XBIOS_ListSTModes(this, 1);
562 break;
563 case VDO_TT:
564 XBIOS_ListTTModes(this, 1);
565 break;
566 case VDO_F30:
567 /* ScreenBlaster 3 ? */
568 if (Getcookie(C_SCPN, &cookie_scpn) == C_FOUND) {
569 SDL_XBIOS_ListSB3Modes(this, 1, (scpn_cookie_t *)cookie_scpn);
570 } else
571 /* Centscreen ? */
572 if (Getcookie(C_CNTS, &cookie_cnts) == C_FOUND) {
573 XBIOS_oldvmode = SDL_XBIOS_ListCentscreenModes(this, 1);
574 XBIOS_centscreen = SDL_TRUE;
575 } else
576 /* Standard, with or without Blowup */
577 {
578 switch (VgetMonitor())
579 {
580 case MONITOR_RGB:
581 case MONITOR_TV:
582 XBIOS_ListFalconRgbModes(this, 1);
583 break;
584 case MONITOR_VGA:
585 XBIOS_ListFalconVgaModes(this, 1);
586 break;
587 }
588
589 if (Getcookie(C_BLOW, &cookie_blow) == C_FOUND) {
590 SDL_XBIOS_ListBlowupModes(this, 1, (blow_cookie_t *)cookie_blow);
591 }
592 }
593 break;
594 case VDO_MILAN:
595 SDL_XBIOS_ListMilanModes(this, 1);
596 break;
597 }
598
599 XBIOS_screens[0]=NULL;
600 XBIOS_screens[1]=NULL;
601 XBIOS_shadowscreen=NULL;
602
603 /* Update hardware info */
604 this->info.hw_available = 1;
605 this->info.video_mem = (Uint32) Atari_SysMalloc(-1L, MX_STRAM);
606
607 /* Init chunky to planar routine */
608 SDL_Atari_C2pConvert = SDL_Atari_C2pConvert8;
609
610#if SDL_VIDEO_OPENGL
611 SDL_AtariGL_InitPointers(this);
612#endif
613
614 /* Disable screensavers */
615 if (SDL_XBIOS_TveillePresent(this)) {
616 SDL_XBIOS_TveilleDisable(this);
617 }
618
619 /* We're done! */
620 return(0);
621}
622
623static SDL_Rect **XBIOS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags)
624{
625 return(SDL_modelist[((format->BitsPerPixel+7)/8)-1]);
626}
627
628static void XBIOS_FreeBuffers(_THIS)
629{
630 int i;
631
632 for (i=0;i<2;i++) {
633 if (XBIOS_screensmem[i]!=NULL) {
634 if ((XBIOS_cvdo>>16) == VDO_MILAN) {
635 if (i==1) {
636 VsetScreen(-1, -1, MI_MAGIC, CMD_FREEPAGE);
637 }
638 } else {
639 Mfree(XBIOS_screensmem[i]);
640 }
641 XBIOS_screensmem[i]=NULL;
642 }
643 }
644
645 if (XBIOS_shadowscreen!=NULL) {
646 Mfree(XBIOS_shadowscreen);
647 XBIOS_shadowscreen=NULL;
648 }
649}
650
651static SDL_Surface *XBIOS_SetVideoMode(_THIS, SDL_Surface *current,
652 int width, int height, int bpp, Uint32 flags)
653{
654 int mode, new_depth;
655 int i, num_buffers;
656 xbiosmode_t *new_video_mode;
657 Uint32 new_screen_size;
658 Uint32 modeflags;
659
660 /* Free current buffers */
661 XBIOS_FreeBuffers(this);
662
663 /* Try to set the requested linear video mode */
664 bpp = (bpp+7)/8-1;
665 for ( mode=0; SDL_modelist[bpp][mode]; ++mode ) {
666 if ( (SDL_modelist[bpp][mode]->w == width) &&
667 (SDL_modelist[bpp][mode]->h == height) ) {
668 break;
669 }
670 }
671 if ( SDL_modelist[bpp][mode] == NULL ) {
672 SDL_SetError("Couldn't find requested mode in list");
673 return(NULL);
674 }
675 new_video_mode = SDL_xbiosmode[bpp][mode];
676
677 modeflags = SDL_FULLSCREEN | SDL_PREALLOC;
678
679 /* Allocate needed buffers: simple/double buffer and shadow surface */
680 new_depth = new_video_mode->depth;
681 if (new_depth == 4) {
682 SDL_Atari_C2pConvert = SDL_Atari_C2pConvert4;
683 new_depth=8;
684 modeflags |= SDL_SWSURFACE|SDL_HWPALETTE;
685 } else if (new_depth == 8) {
686 SDL_Atari_C2pConvert = SDL_Atari_C2pConvert8;
687 modeflags |= SDL_SWSURFACE|SDL_HWPALETTE;
688 } else {
689 modeflags |= SDL_HWSURFACE;
690 }
691
692 new_screen_size = width * height * ((new_depth)>>3);
693 new_screen_size += 256; /* To align on a 256 byte adress */
694
695 if (new_video_mode->flags & XBIOSMODE_C2P) {
696 XBIOS_shadowscreen = Atari_SysMalloc(new_screen_size, MX_PREFTTRAM);
697
698 if (XBIOS_shadowscreen == NULL) {
699 SDL_SetError("Can not allocate %d KB for shadow buffer", new_screen_size>>10);
700 return (NULL);
701 }
702 SDL_memset(XBIOS_shadowscreen, 0, new_screen_size);
703 }
704
705 /* Output buffer needs to be twice in size for the software double-line mode */
706 if (new_video_mode->flags & XBIOSMODE_DOUBLELINE) {
707 new_screen_size <<= 1;
708 }
709
710 /* Double buffer ? */
711 num_buffers = 1;
712
713#if SDL_VIDEO_OPENGL
714 if (flags & SDL_OPENGL) {
715 if (this->gl_config.double_buffer) {
716 flags |= SDL_DOUBLEBUF;
717 }
718 }
719#endif
720 if ((flags & SDL_DOUBLEBUF) && ((XBIOS_cvdo>>16) != VDO_MILAN)) {
721 num_buffers = 2;
722 modeflags |= SDL_DOUBLEBUF;
723 }
724
725 /* Allocate buffers */
726 for (i=0; i<num_buffers; i++) {
727 if ((XBIOS_cvdo>>16) == VDO_MILAN) {
728 if (i==0) {
729 XBIOS_screensmem[i] = XBIOS_oldvbase;
730 } else {
731 VsetScreen(-1, &XBIOS_screensmem[i], MI_MAGIC, CMD_ALLOCPAGE);
732 }
733 } else {
734 XBIOS_screensmem[i] = Atari_SysMalloc(new_screen_size, MX_STRAM);
735 }
736
737 if (XBIOS_screensmem[i]==NULL) {
738 XBIOS_FreeBuffers(this);
739 SDL_SetError("Can not allocate %d KB for buffer %d", new_screen_size>>10, i);
740 return (NULL);
741 }
742 SDL_memset(XBIOS_screensmem[i], 0, new_screen_size);
743
744 XBIOS_screens[i]=(void *) (( (long) XBIOS_screensmem[i]+256) & 0xFFFFFF00UL);
745 }
746
747 /* Allocate the new pixel format for the screen */
748 if ( ! SDL_ReallocFormat(current, new_depth, 0, 0, 0, 0) ) {
749 XBIOS_FreeBuffers(this);
750 SDL_SetError("Couldn't allocate new pixel format for requested mode");
751 return(NULL);
752 }
753
754 XBIOS_current = new_video_mode;
755 current->w = width;
756 current->h = height;
757 current->pitch = (width * new_depth)>>3;
758
759 /* this is for C2P conversion */
760 XBIOS_pitch = (new_video_mode->width * new_video_mode->depth)>>3;
761
762 if (new_video_mode->flags & XBIOSMODE_C2P)
763 current->pixels = XBIOS_shadowscreen;
764 else
765 current->pixels = XBIOS_screens[0];
766
767 XBIOS_fbnum = 0;
768
769#if SDL_VIDEO_OPENGL
770 if (flags & SDL_OPENGL) {
771 if (!SDL_AtariGL_Init(this, current)) {
772 XBIOS_FreeBuffers(this);
773 SDL_SetError("Can not create OpenGL context");
774 return NULL;
775 }
776
777 modeflags |= SDL_OPENGL;
778 }
779#endif
780
781 current->flags = modeflags;
782
783#ifndef DEBUG_VIDEO_XBIOS
784 /* Now set the video mode */
785 if ((XBIOS_cvdo>>16) == VDO_MILAN) {
786 VsetScreen(-1, XBIOS_screens[0], MI_MAGIC, CMD_SETADR);
787 } else {
788 Setscreen(-1,XBIOS_screens[0],-1);
789 }
790
791 switch(XBIOS_cvdo >> 16) {
792 case VDO_ST:
793 Setscreen(-1,-1,new_video_mode->number);
794
795 /* Reset palette */
796 for (i=0;i<16;i++) {
797 TT_palette[i]= ((i>>1)<<8) | (((i*8)/17)<<4) | (i>>1);
798 }
799 Setpalette(TT_palette);
800 break;
801 case VDO_STE:
802 Setscreen(-1,-1,new_video_mode->number);
803
804 /* Reset palette */
805 for (i=0;i<16;i++)
806 {
807 int c;
808
809 c=((i&1)<<3)|((i>>1)&7);
810 TT_palette[i]=(c<<8)|(c<<4)|c;
811 }
812 Setpalette(TT_palette);
813 break;
814 case VDO_TT:
815 EsetShift(new_video_mode->number);
816 break;
817 case VDO_F30:
818 if (XBIOS_centscreen) {
819 SDL_XBIOS_CentscreenSetmode(this, width, height, new_depth);
820 } else {
821 VsetMode(new_video_mode->number);
822 }
823
824 /* Set hardware palette to black in True Colour */
825 if (new_depth > 8) {
826 SDL_memset(F30_palette, 0, sizeof(F30_palette));
827 VsetRGB(0,256,F30_palette);
828 }
829 break;
830 case VDO_MILAN:
831 VsetScreen(-1, new_video_mode->number, MI_MAGIC, CMD_SETMODE);
832
833 /* Set hardware palette to black in True Colour */
834 if (new_depth > 8) {
835 SDL_memset(F30_palette, 0, sizeof(F30_palette));
836 VsetRGB(0,256,F30_palette);
837 }
838 break;
839 }
840
841 Vsync();
842#endif
843
844 this->UpdateRects = XBIOS_UpdateRects;
845
846 return (current);
847}
848
849/* We don't actually allow hardware surfaces other than the main one */
850static int XBIOS_AllocHWSurface(_THIS, SDL_Surface *surface)
851{
852 return(-1);
853}
854
855static void XBIOS_FreeHWSurface(_THIS, SDL_Surface *surface)
856{
857 return;
858}
859
860static int XBIOS_LockHWSurface(_THIS, SDL_Surface *surface)
861{
862 return(0);
863}
864
865static void XBIOS_UnlockHWSurface(_THIS, SDL_Surface *surface)
866{
867 return;
868}
869
870static void XBIOS_UpdateRects(_THIS, int numrects, SDL_Rect *rects)
871{
872 SDL_Surface *surface;
873
874 surface = this->screen;
875
876 if (XBIOS_current->flags & XBIOSMODE_C2P) {
877 int i;
878 int doubleline = (XBIOS_current->flags & XBIOSMODE_DOUBLELINE ? 1 : 0);
879
880 for (i=0;i<numrects;i++) {
881 void *source,*destination;
882 int x1,x2;
883
884 x1 = rects[i].x & ~15;
885 x2 = rects[i].x+rects[i].w;
886 if (x2 & 15) {
887 x2 = (x2 | 15) +1;
888 }
889
890 source = surface->pixels;
891 source += surface->pitch * rects[i].y;
892 source += x1;
893
894 destination = XBIOS_screens[XBIOS_fbnum];
895 destination += XBIOS_pitch * rects[i].y;
896 destination += x1;
897
898 /* Convert chunky to planar screen */
899 SDL_Atari_C2pConvert(
900 source,
901 destination,
902 x2-x1,
903 rects[i].h,
904 doubleline,
905 surface->pitch,
906 XBIOS_pitch
907 );
908 }
909 }
910
911#ifndef DEBUG_VIDEO_XBIOS
912 if ((XBIOS_cvdo>>16) == VDO_MILAN) {
913 VsetScreen(-1, XBIOS_screens[XBIOS_fbnum], MI_MAGIC, CMD_SETADR);
914 } else {
915 Setscreen(-1,XBIOS_screens[XBIOS_fbnum],-1);
916 }
917
918 Vsync();
919#endif
920
921 if ((surface->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) {
922 XBIOS_fbnum ^= 1;
923 if ((XBIOS_current->flags & XBIOSMODE_C2P) == 0) {
924 surface->pixels=XBIOS_screens[XBIOS_fbnum];
925 }
926 }
927}
928
929static int XBIOS_FlipHWSurface(_THIS, SDL_Surface *surface)
930{
931 if (XBIOS_current->flags & XBIOSMODE_C2P) {
932 void *destscr;
933 int destx;
934 int doubleline = (XBIOS_current->flags & XBIOSMODE_DOUBLELINE ? 1 : 0);
935
936 /* Center on destination screen */
937 destscr = XBIOS_screens[XBIOS_fbnum];
938 destscr += XBIOS_pitch * ((XBIOS_current->height - surface->h) >> 1);
939 destx = (XBIOS_current->width - surface->w) >> 1;
940 destx &= ~15;
941 destscr += destx;
942
943 /* Convert chunky to planar screen */
944 SDL_Atari_C2pConvert(
945 surface->pixels,
946 destscr,
947 surface->w,
948 surface->h,
949 doubleline,
950 surface->pitch,
951 XBIOS_pitch
952 );
953 }
954
955#ifndef DEBUG_VIDEO_XBIOS
956 if ((XBIOS_cvdo>>16) == VDO_MILAN) {
957 VsetScreen(-1, XBIOS_screens[XBIOS_fbnum], MI_MAGIC, CMD_SETADR);
958 } else {
959 Setscreen(-1,XBIOS_screens[XBIOS_fbnum],-1);
960 }
961
962 Vsync();
963#endif
964
965 if ((surface->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) {
966 XBIOS_fbnum ^= 1;
967 if ((XBIOS_current->flags & XBIOSMODE_C2P) == 0) {
968 surface->pixels=XBIOS_screens[XBIOS_fbnum];
969 }
970 }
971
972 return(0);
973}
974
975static int XBIOS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
976{
977#ifndef DEBUG_VIDEO_XBIOS
978 int i;
979 int r,v,b;
980
981 switch( XBIOS_cvdo >> 16) {
982 case VDO_ST:
983 case VDO_STE:
984 for (i=0;i<ncolors;i++)
985 {
986 r = colors[i].r;
987 v = colors[i].g;
988 b = colors[i].b;
989
990 TT_palette[firstcolor+i]=((r*30)+(v*59)+(b*11))/100;
991 }
992 SDL_Atari_C2pConvert4_pal(TT_palette); /* convert the lighting */
993 break;
994 case VDO_TT:
995 for(i = 0; i < ncolors; i++)
996 {
997 r = colors[i].r;
998 v = colors[i].g;
999 b = colors[i].b;
1000
1001 TT_palette[i]=((r>>4)<<8)|((v>>4)<<4)|(b>>4);
1002 }
1003 EsetPalette(firstcolor,ncolors,TT_palette);
1004 break;
1005 case VDO_F30:
1006 case VDO_MILAN:
1007 for(i = 0; i < ncolors; i++)
1008 {
1009 r = colors[i].r;
1010 v = colors[i].g;
1011 b = colors[i].b;
1012
1013 F30_palette[i]=(r<<16)|(v<<8)|b;
1014 }
1015 VsetRGB(firstcolor,ncolors,F30_palette);
1016 break;
1017 }
1018#endif
1019
1020 return(1);
1021}
1022
1023/* Note: If we are terminated, this could be called in the middle of
1024 another SDL video routine -- notably UpdateRects.
1025*/
1026static void XBIOS_VideoQuit(_THIS)
1027{
1028 int i,j;
1029
1030 Atari_ShutdownEvents();
1031
1032 /* Restore video mode and palette */
1033#ifndef DEBUG_VIDEO_XBIOS
1034 switch(XBIOS_cvdo >> 16) {
1035 case VDO_ST:
1036 case VDO_STE:
1037 Setscreen(-1,XBIOS_oldvbase,XBIOS_oldvmode);
1038 if (XBIOS_oldnumcol) {
1039 Setpalette(XBIOS_oldpalette);
1040 }
1041 break;
1042 case VDO_TT:
1043 Setscreen(-1,XBIOS_oldvbase,-1);
1044 EsetShift(XBIOS_oldvmode);
1045 if (XBIOS_oldnumcol) {
1046 EsetPalette(0, XBIOS_oldnumcol, XBIOS_oldpalette);
1047 }
1048 break;
1049 case VDO_F30:
1050 Setscreen(-1, XBIOS_oldvbase, -1);
1051 if (XBIOS_centscreen) {
1052 SDL_XBIOS_CentscreenRestore(this, XBIOS_oldvmode);
1053 } else {
1054 VsetMode(XBIOS_oldvmode);
1055 }
1056 if (XBIOS_oldnumcol) {
1057 VsetRGB(0, XBIOS_oldnumcol, XBIOS_oldpalette);
1058 }
1059 break;
1060 case VDO_MILAN:
1061 VsetScreen(-1, &XBIOS_oldvbase, MI_MAGIC, CMD_SETADR);
1062 VsetScreen(-1, &XBIOS_oldvmode, MI_MAGIC, CMD_SETMODE);
1063 if (XBIOS_oldnumcol) {
1064 VsetRGB(0, XBIOS_oldnumcol, XBIOS_oldpalette);
1065 }
1066 break;
1067 }
1068 Vsync();
1069#endif
1070
1071#if SDL_VIDEO_OPENGL
1072 if (gl_active) {
1073 SDL_AtariGL_Quit(this, SDL_TRUE);
1074 }
1075#endif
1076
1077 if (XBIOS_oldpalette) {
1078 SDL_free(XBIOS_oldpalette);
1079 XBIOS_oldpalette=NULL;
1080 }
1081 XBIOS_FreeBuffers(this);
1082
1083 /* Free mode list */
1084 for ( i=0; i<NUM_MODELISTS; ++i ) {
1085 if ( SDL_modelist[i] != NULL ) {
1086 for ( j=0; SDL_modelist[i][j]; ++j )
1087 SDL_free(SDL_modelist[i][j]);
1088 SDL_free(SDL_modelist[i]);
1089 SDL_modelist[i] = NULL;
1090 }
1091 if ( SDL_xbiosmode[i] != NULL ) {
1092 for ( j=0; SDL_xbiosmode[i][j]; ++j )
1093 SDL_free(SDL_xbiosmode[i][j]);
1094 SDL_free(SDL_xbiosmode[i]);
1095 SDL_xbiosmode[i] = NULL;
1096 }
1097 }
1098
1099 this->screen->pixels = NULL;
1100
1101 /* Restore screensavers */
1102 if (SDL_XBIOS_TveillePresent(this)) {
1103 SDL_XBIOS_TveilleEnable(this);
1104 }
1105}
1106
1107#if SDL_VIDEO_OPENGL
1108
1109static void XBIOS_GL_SwapBuffers(_THIS)
1110{
1111 SDL_AtariGL_SwapBuffers(this);
1112 XBIOS_FlipHWSurface(this, this->screen);
1113 SDL_AtariGL_MakeCurrent(this);
1114}
1115
1116#endif
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios.h b/apps/plugins/sdl/src/video/xbios/SDL_xbios.h
deleted file mode 100644
index 3ad6827153..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios.h
+++ /dev/null
@@ -1,111 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24#ifndef _SDL_xbios_h
25#define _SDL_xbios_h
26
27#include "SDL_stdinc.h"
28#include "../SDL_sysvideo.h"
29
30/* Hidden "this" pointer for the video functions */
31#define _THIS SDL_VideoDevice *this
32
33#define XBIOSMODE_DOUBLELINE (1<<0)
34#define XBIOSMODE_C2P (1<<1)
35
36typedef struct
37{
38 Uint16 number; /* Video mode number */
39 Uint16 width; /* Size */
40 Uint16 height;
41 Uint16 depth; /* bits per plane */
42 Uint16 flags;
43} xbiosmode_t;
44
45/* Private display data */
46#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */
47
48struct SDL_PrivateVideoData {
49 long cookie_vdo;
50 long old_video_mode; /* Old video mode before entering SDL */
51 void *old_video_base; /* Old pointer to screen buffer */
52 void *old_palette; /* Old palette */
53 Uint32 old_num_colors; /* Nb of colors in saved palette */
54
55 void *screens[2]; /* Pointers to aligned screen buffer */
56 void *screensmem[2]; /* Pointers to screen buffer */
57 void *shadowscreen; /* Shadow screen for c2p conversion */
58 int frame_number; /* Number of frame for double buffer */
59 int pitch; /* Destination line width for C2P */
60
61 SDL_bool centscreen; /* Centscreen extension present ? */
62
63 xbiosmode_t *current; /* Current set mode */
64 int SDL_nummodes[NUM_MODELISTS];
65 SDL_Rect **SDL_modelist[NUM_MODELISTS];
66 xbiosmode_t **SDL_xbiosmode[NUM_MODELISTS];
67};
68
69/* _VDO cookie values */
70enum {
71 VDO_ST=0,
72 VDO_STE,
73 VDO_TT,
74 VDO_F30,
75 VDO_MILAN
76};
77
78/* Monitor types */
79enum {
80 MONITOR_MONO=0,
81 MONITOR_TV,
82 MONITOR_VGA,
83 MONITOR_RGB
84};
85
86/* EgetShift masks */
87#define ES_MODE 0x0700
88
89/* Hidden structure -> variables names */
90#define SDL_nummodes (this->hidden->SDL_nummodes)
91#define SDL_modelist (this->hidden->SDL_modelist)
92#define SDL_xbiosmode (this->hidden->SDL_xbiosmode)
93#define XBIOS_mutex (this->hidden->mutex)
94#define XBIOS_cvdo (this->hidden->cookie_vdo)
95#define XBIOS_oldpalette (this->hidden->old_palette)
96#define XBIOS_oldnumcol (this->hidden->old_num_colors)
97#define XBIOS_oldvbase (this->hidden->old_video_base)
98#define XBIOS_oldvmode (this->hidden->old_video_mode)
99#define XBIOS_screens (this->hidden->screens)
100#define XBIOS_screensmem (this->hidden->screensmem)
101#define XBIOS_shadowscreen (this->hidden->shadowscreen)
102#define XBIOS_fbnum (this->hidden->frame_number)
103#define XBIOS_pitch (this->hidden->pitch)
104#define XBIOS_centscreen (this->hidden->centscreen)
105#define XBIOS_current (this->hidden->current)
106
107/*--- Functions prototypes ---*/
108
109void SDL_XBIOS_AddMode(_THIS, int actually_add, const xbiosmode_t *modeinfo);
110
111#endif /* _SDL_xbios_h */
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_blowup.c b/apps/plugins/sdl/src/video/xbios/SDL_xbios_blowup.c
deleted file mode 100644
index 2950b84f17..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_blowup.c
+++ /dev/null
@@ -1,77 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Blowup extension definitions
26
27 Patrice Mandin
28*/
29
30#include <mint/falcon.h>
31
32#include "SDL_xbios.h"
33#include "SDL_xbios_blowup.h"
34
35void SDL_XBIOS_ListBlowupModes(_THIS, int actually_add, blow_cookie_t *cookie_blow)
36{
37 int i, j, num_mode, bank;
38 blow_mode_t *blow_mode;
39 xbiosmode_t modeinfo;
40
41 if (actually_add) {
42 /* Set bit 15 for old modes */
43 for (i=0;i<NUM_MODELISTS;i++) {
44 if ( SDL_xbiosmode[i] != NULL ) {
45 for ( j=0; SDL_xbiosmode[i][j]; ++j ) {
46 SDL_xbiosmode[i][j]->number |= 1<<15;
47 }
48 }
49 }
50 }
51
52 /* Add Blowup modes for 8 and 16 bpp */
53 for (num_mode=3; num_mode<5; num_mode++) {
54 bank = cookie_blow->num_mode[num_mode];
55 blow_mode = &(cookie_blow->blowup_modes[num_mode+(bank*5)]);
56
57 /* Check extended mode enabled */
58 if (blow_mode->enabled == 0) {
59 /* Check monitor needed for this mode */
60 if ((blow_mode->monitor == cookie_blow->montype)
61 || ((blow_mode->monitor == MONITOR_TV)
62 && (cookie_blow->montype == MONITOR_RGB))
63 || ((blow_mode->monitor == MONITOR_RGB)
64 && (cookie_blow->montype == MONITOR_TV)))
65 {
66 /* we can use this extended mode */
67 modeinfo.number = (num_mode == 3 ? BPS8 : BPS16);
68 modeinfo.width = blow_mode->width + 1;
69 modeinfo.height = blow_mode->height + 1;
70 modeinfo.depth = (num_mode == 3 ? 8 : 16);
71 modeinfo.flags = (modeinfo.depth == 8 ? XBIOSMODE_C2P : 0);
72
73 SDL_XBIOS_AddMode(this, actually_add, &modeinfo);
74 }
75 }
76 }
77}
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_blowup.h b/apps/plugins/sdl/src/video/xbios/SDL_xbios_blowup.h
deleted file mode 100644
index 09a3651bdc..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_blowup.h
+++ /dev/null
@@ -1,86 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Blowup extension definitions
26
27 Patrice Mandin
28*/
29
30#ifndef _SDL_xbios_blowup_h
31#define _SDL_xbios_blowup_h
32
33#include "SDL_xbios.h"
34
35/*--- Types ---*/
36
37typedef struct {
38 /* 64 bytes */
39 unsigned short enabled; /* Extended mode enabled ? 0=yes, <>0=no */
40 unsigned short dummy10[6];
41 unsigned short registers_0E; /* value for register 0xffff820e */
42 unsigned short registers_10; /* value for register 0xffff8210 */
43 unsigned short dummy11[23];
44
45 /* 64 bytes */
46 unsigned short width; /* width-1 */
47 unsigned short height; /* height-1 */
48 unsigned short dummy20;
49 unsigned long screensize; /* screensize in bytes */
50 unsigned short dummy21[8];
51 unsigned short virtual; /* Virtual screen ? */
52 unsigned short virwidth; /* Virtual screen width */
53 unsigned short virheight; /* Virtual screen height */
54
55 unsigned short dummy22;
56 unsigned short monitor; /* Monitor defined for this mode */
57 unsigned short extension; /* Extended mode defined ? 0=yes, 1=no */
58 unsigned short dummy23[13];
59
60 /* 64 bytes */
61 unsigned short dummy30;
62 unsigned short registers_82[6]; /* values for registers 0xffff8282-8c */
63 unsigned short dummy31[9];
64
65 unsigned short dummy32;
66 unsigned short registers_A2[6]; /* values for registers 0xffff82a2-ac */
67 unsigned short dummy33[9];
68
69 /* 64 bytes */
70 unsigned short registers_C0; /* value for register 0xffff82c0 */
71 unsigned short registers_C2; /* value for register 0xffff82c2 */
72 unsigned short dummy40[30];
73} blow_mode_t;
74
75typedef struct {
76 blow_mode_t blowup_modes[10];
77 unsigned char num_mode[6];
78 unsigned long dummy;
79 unsigned short montype;
80} blow_cookie_t;
81
82/*--- Functions prototypes ---*/
83
84void SDL_XBIOS_ListBlowupModes(_THIS, int actually_add, blow_cookie_t *cookie_blow);
85
86#endif /* _SDL_xbios_blowup_h */
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_centscreen.c b/apps/plugins/sdl/src/video/xbios/SDL_xbios_centscreen.c
deleted file mode 100644
index 6daade2e5e..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_centscreen.c
+++ /dev/null
@@ -1,104 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Centscreen extension definitions
26
27 Patrice Mandin
28*/
29
30#include <mint/falcon.h>
31
32#include "SDL_xbios.h"
33#include "SDL_xbios_centscreen.h"
34
35int SDL_XBIOS_ListCentscreenModes(_THIS, int actually_add)
36{
37 centscreen_mode_t curmode, listedmode;
38 unsigned long result;
39 int cur_handle; /* Current Centscreen mode handle */
40
41 /* Add Centscreen modes */
42 Vread(&curmode);
43 cur_handle = curmode.handle;
44 curmode.mode = curmode.physx = curmode.physy = curmode.plan =
45 curmode.logx = curmode.logy = -1;
46
47 result = Vfirst(&curmode, &listedmode);
48 if (result==0) {
49 while (result==0) {
50 /* Don't add modes with virtual screen */
51 if ((listedmode.mode & CSCREEN_VIRTUAL)==0) {
52 /* Don't add modes with bpp<8 */
53 if (listedmode.plan>=8) {
54 xbiosmode_t modeinfo;
55
56 modeinfo.number = listedmode.mode;
57 modeinfo.width = listedmode.physx;
58 modeinfo.height = listedmode.physy;
59 modeinfo.depth = listedmode.plan;
60 modeinfo.flags = (modeinfo.depth == 8 ? XBIOSMODE_C2P : 0);
61
62 SDL_XBIOS_AddMode(this, actually_add, &modeinfo);
63 }
64 }
65 SDL_memcpy(&curmode, &listedmode, sizeof(centscreen_mode_t));
66 curmode.mode = curmode.physx = curmode.physy = curmode.plan =
67 curmode.logx = curmode.logy = -1;
68 result = Vnext(&curmode, &listedmode);
69 }
70 } else {
71 fprintf(stderr, "No suitable Centscreen modes\n");
72 }
73
74 return cur_handle;
75}
76
77void SDL_XBIOS_CentscreenSetmode(_THIS, int width, int height, int planes)
78{
79 centscreen_mode_t newmode, curmode;
80
81 newmode.handle = newmode.mode = newmode.logx = newmode.logy = -1;
82 newmode.physx = width;
83 newmode.physy = height;
84 newmode.plan = planes;
85 Vwrite(0, &newmode, &curmode);
86
87#ifdef SDL_VIDEO_DISABLE_SCREENSAVER
88 /* Disable screensaver */
89 Vread(&newmode);
90 newmode.mode &= ~(CSCREEN_SAVER|CSCREEN_ENERGYSTAR);
91 Vwrite(0, &newmode, &curmode);
92#endif /* SDL_VIDEO_DISABLE_SCREENSAVER */
93}
94
95void SDL_XBIOS_CentscreenRestore(_THIS, int prev_handle)
96{
97 centscreen_mode_t newmode, curmode;
98
99 /* Restore old video mode */
100 newmode.handle = prev_handle;
101 newmode.mode = newmode.physx = newmode.physy = newmode.plan =
102 newmode.logx = newmode.logy = -1;
103 Vwrite(0, &newmode, &curmode);
104}
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_centscreen.h b/apps/plugins/sdl/src/video/xbios/SDL_xbios_centscreen.h
deleted file mode 100644
index dfe88d9ea3..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_centscreen.h
+++ /dev/null
@@ -1,114 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Centscreen extension definitions
26
27 Patrice Mandin
28*/
29
30#ifndef _SDL_xbios_centscreen_h
31#define _SDL_xbios_centscreen_h
32
33#include <mint/falcon.h> /* for trap_14_xxx macros */
34
35#include "SDL_xbios.h"
36
37/*--- Defines ---*/
38
39#define CSCREEN_ENERGYSTAR (1<<9)
40#define CSCREEN_SAVER (1<<10)
41#define CSCREEN_VIRTUAL (1<<11)
42#define CSCREEN_EXTCLOCK_CT2 (1<<12)
43#define CSCREEN_EXTCLOCK (1<<13)
44#define CSCREEN_STANDARD (1<<14)
45#define CSCREEN_DEFAULT (1<<15)
46
47/*--- Structures ---*/
48
49typedef struct {
50 unsigned short handle; /* videomode handle */
51 unsigned short mode; /* Falcon videomode code */
52 unsigned short physx; /* visible width */
53 unsigned short physy; /* visible height */
54 unsigned short plan; /* bitplanes */
55 unsigned short logx; /* virtual width */
56 unsigned short logy; /* virtual height */
57 unsigned short eco; /* screen saver delay */
58 unsigned short eco2; /* energy star screen saver delay */
59 unsigned short wsize; /* screen width (mm) */
60 unsigned short hsize; /* screen height (mm) */
61 unsigned short dummy[21];
62 unsigned char name[32]; /* videomode name */
63} centscreen_mode_t;
64
65/*--- Functions prototypes ---*/
66
67#define Vread(current_mode) \
68 (void)trap_14_wl((short)0x41,(long)(current_mode))
69#define Vwrite(init_vdi, inparam, outparam) \
70 (long)trap_14_wwll((short)0x42,(short)(init_vdi),(long)(inparam),(long)(outparam))
71#define Vattrib(inparam, outparam) \
72 (void)trap_14_wll((short)0x43,(long)(inparam),(long)(outparam))
73#define Vcreate(inparam, outparam) \
74 (void)trap_14_wll((short)0x44,(long)(inparam),(long)(outparam))
75#define Vdelete(handle) \
76 (long)trap_14_ww((short)0x45,(short)(handle))
77#define Vfirst(mask,mode) \
78 (long)trap_14_wll((short)0x46,(long)(mask),(long)(mode))
79#define Vnext(mask,mode) \
80 (long)trap_14_wll((short)0x47,(long)(mask),(long)(mode))
81#define Vvalid(handle) \
82 (long)trap_14_ww((short)0x48,(short)(handle))
83#define Vload() \
84 (long)trap_14_w((short)0x49)
85#define Vsave() \
86 (long)trap_14_w((short)0x4a)
87#define Vopen() \
88 (long)trap_14_w((short)0x4b)
89#define Vclose() \
90 (long)trap_14_w((short)0x4c)
91#define Vscroll(scrollmode) \
92 (long)trap_14_ww((short)0x4d,(short)(scrollmode))
93#define Voffset() \
94 (long)trap_14_w((short)0x4e)
95#define Vseek() \
96 (long)trap_14_w((short)0x4f)
97#define Vlock(cmd) \
98 (long)trap_14_ww((short)0x50,(short)(cmd))
99#define SetMon(montype) \
100 (long)trap_14_ww((short)0x51,(short)(montype))
101#define MultiMon(cmd) \
102 (long)trap_14_ww((short)0x52,(short)(cmd))
103#define VSizeComp() \
104 (long)trap_14_w((short)0x53)
105#define Vsize(mode) \
106 (long)trap_14_wl((short)0x54,(long)(mode))
107
108/*--- Functions prototypes ---*/
109
110int SDL_XBIOS_ListCentscreenModes(_THIS, int actually_add);
111void SDL_XBIOS_CentscreenSetmode(_THIS, int width, int height, int planes);
112void SDL_XBIOS_CentscreenRestore(_THIS, int prev_handle);
113
114#endif /* _SDL_xbios_centscreen_h */
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_milan.c b/apps/plugins/sdl/src/video/xbios/SDL_xbios_milan.c
deleted file mode 100644
index a99ee18c5b..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_milan.c
+++ /dev/null
@@ -1,106 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Milan Xbios video functions
26
27 Patrice Mandin
28*/
29
30#include <mint/cookie.h>
31#include <mint/falcon.h>
32
33#include "SDL_xbios.h"
34#include "SDL_xbios_milan.h"
35
36#define NUM_PREDEFINED_MODES 7
37
38typedef struct {
39 Uint16 width, height;
40} predefined_mode_t;
41
42static const predefined_mode_t mode_list[NUM_PREDEFINED_MODES]={
43 {640,400},
44 {640,480},
45 {800,608},
46 {1024,768},
47 {1152,864},
48 {1280,1024},
49 {1600,1200}
50};
51
52static const Uint8 mode_bpp[4]={
53 8, 15, 16, 32
54};
55
56/*--- Variables ---*/
57
58static int enum_actually_add;
59static SDL_VideoDevice *enum_this;
60
61/*--- Functions ---*/
62
63static unsigned long /*cdecl*/ enumfunc(SCREENINFO *inf, unsigned long flag)
64{
65 xbiosmode_t modeinfo;
66
67 modeinfo.number = inf->devID;
68 modeinfo.width = inf->scrWidth;
69 modeinfo.height = inf->scrHeight;
70 modeinfo.depth = inf->scrPlanes;
71 modeinfo.flags = 0;
72
73 SDL_XBIOS_AddMode(enum_this, enum_actually_add, &modeinfo);
74
75 return ENUMMODE_CONT;
76}
77
78void SDL_XBIOS_ListMilanModes(_THIS, int actually_add)
79{
80 int i;
81
82 /* Read validated predefined modes */
83 for (i=0; i<NUM_PREDEFINED_MODES; i++) {
84 int j;
85 Uint16 deviceid = 0x1000 + (i<<4);
86
87 for (j=1; j<4; j++) {
88 if (Validmode(deviceid + j)) {
89 xbiosmode_t modeinfo;
90
91 modeinfo.number = deviceid + j;
92 modeinfo.width = mode_list[i].width;
93 modeinfo.height = mode_list[i].height;
94 modeinfo.depth = mode_bpp[j-1];
95 modeinfo.flags = 0;
96
97 SDL_XBIOS_AddMode(this, actually_add, &modeinfo);
98 }
99 }
100 }
101
102 /* Read custom created modes */
103 enum_this = this;
104 enum_actually_add = actually_add;
105 VsetScreen(-1, &enumfunc, MI_MAGIC, CMD_ENUMMODES);
106}
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_milan.h b/apps/plugins/sdl/src/video/xbios/SDL_xbios_milan.h
deleted file mode 100644
index bcf5c8a5bd..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_milan.h
+++ /dev/null
@@ -1,129 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Milan Xbios video functions
26
27 Patrice Mandin
28*/
29
30#ifndef _SDL_xbios_milan_h
31#define _SDL_xbios_milan_h
32
33#include "SDL_xbios.h"
34
35/*--- Defines ---*/
36
37/* Vsetscreen() parameters */
38#define MI_MAGIC 0x4D49
39
40enum {
41 CMD_GETMODE=0,
42 CMD_SETMODE,
43 CMD_GETINFO,
44 CMD_ALLOCPAGE,
45 CMD_FREEPAGE,
46 CMD_FLIPPAGE,
47 CMD_ALLOCMEM,
48 CMD_FREEMEM,
49 CMD_SETADR,
50 CMD_ENUMMODES
51};
52
53enum {
54 ENUMMODE_EXIT=0,
55 ENUMMODE_CONT
56};
57
58enum {
59 BLK_ERR=0,
60 BLK_OK,
61 BLK_CLEARED
62};
63
64/* scrFlags */
65#define SCRINFO_OK 1
66
67/* scrClut */
68#define NO_CLUT 0
69#define HARD_CLUT 1
70#define SOFT_CLUT 2
71
72/* scrFormat */
73#define INTERLEAVE_PLANES 0
74#define STANDARD_PLANES 1
75#define PACKEDPIX_PLANES 2
76
77/* bitFlags */
78#define STANDARD_BITS 1
79#define FALCON_BITS 2
80#define INTEL_BITS 8
81
82/*--- Structures ---*/
83
84typedef struct _scrblk {
85 unsigned long size; /* size of strukture */
86 unsigned long blk_status; /* status bits of blk */
87 unsigned long blk_start; /* Start Adress */
88 unsigned long blk_len; /* length of memblk */
89 unsigned long blk_x; /* x pos in total screen*/
90 unsigned long blk_y; /* y pos in total screen */
91 unsigned long blk_w; /* width */
92 unsigned long blk_h; /* height */
93 unsigned long blk_wrap; /* width in bytes */
94} SCRMEMBLK;
95
96typedef struct screeninfo {
97 unsigned long size; /* Size of structure */
98 unsigned long devID; /* device id number */
99 unsigned char name[64]; /* Friendly name of Screen */
100 unsigned long scrFlags; /* some Flags */
101 unsigned long frameadr; /* Adress of framebuffer */
102 unsigned long scrHeight; /* visible X res */
103 unsigned long scrWidth; /* visible Y res */
104 unsigned long virtHeight; /* virtual X res */
105 unsigned long virtWidth; /* virtual Y res */
106 unsigned long scrPlanes; /* color Planes */
107 unsigned long scrColors; /* # of colors */
108 unsigned long lineWrap; /* # of Bytes to next line */
109 unsigned long planeWarp; /* # of Bytes to next plane */
110 unsigned long scrFormat; /* screen Format */
111 unsigned long scrClut; /* type of clut */
112 unsigned long redBits; /* Mask of Red Bits */
113 unsigned long greenBits; /* Mask of Green Bits */
114 unsigned long blueBits; /* Mask of Blue Bits */
115 unsigned long alphaBits; /* Mask of Alpha Bits */
116 unsigned long genlockBits;/* Mask of Genlock Bits */
117 unsigned long unusedBits; /* Mask of unused Bits */
118 unsigned long bitFlags; /* Bits organisation flags */
119 unsigned long maxmem; /* max. memory in this mode */
120 unsigned long pagemem; /* needed memory for one page */
121 unsigned long max_x; /* max. possible width */
122 unsigned long max_y; /* max. possible heigth */
123} SCREENINFO;
124
125/*--- Functions prototypes ---*/
126
127void SDL_XBIOS_ListMilanModes(_THIS, int actually_add);
128
129#endif /* _SDL_xbios_milan_h */
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_sb3.c b/apps/plugins/sdl/src/video/xbios/SDL_xbios_sb3.c
deleted file mode 100644
index 8b0ed2c629..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_sb3.c
+++ /dev/null
@@ -1,83 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 ScreenBlaster 3 functions
26
27 Patrice Mandin
28*/
29
30/*--- Includes ---*/
31
32#include "SDL_stdinc.h"
33#include "SDL_xbios.h"
34#include "SDL_xbios_sb3.h"
35
36/*--- Defines ---*/
37
38const int SDL_XBIOS_scpn_planes_device[]={
39 SCPN_DEV_1BPP,
40 SCPN_DEV_4BPP,
41 SCPN_DEV_8BPP,
42 SCPN_DEV_16BPP,
43 SCPN_DEV_2BPP,
44 SCPN_DEV_4BPP,
45 SCPN_DEV_1BPP
46};
47
48/*--- Functions ---*/
49
50int SDL_XBIOS_SB3Usable(scpn_cookie_t *cookie_scpn)
51{
52 scpn_screeninfo_t *scrinfo;
53 int bpp;
54
55 /* Check if current SB3 mode is usable, i.e. 8 or 16bpp */
56 scrinfo = cookie_scpn->screen_info;
57 bpp = 1<<(SDL_XBIOS_scpn_planes_device[scrinfo->device]);
58
59 if ((bpp==8) || (bpp==16)) {
60 return 1;
61 }
62
63 return 0;
64}
65
66void SDL_XBIOS_ListSB3Modes(_THIS, int actually_add, scpn_cookie_t *cookie_scpn)
67{
68 scpn_screeninfo_t *scrinfo;
69 xbiosmode_t modeinfo;
70
71 scrinfo = cookie_scpn->screen_info;
72 if (actually_add) {
73 scrinfo->h_pos = scrinfo->v_pos = 0;
74 }
75
76 modeinfo.number = -1;
77 modeinfo.width = scrinfo->virtual_width;
78 modeinfo.height = scrinfo->virtual_height;
79 modeinfo.depth = 1<<(SDL_XBIOS_scpn_planes_device[scrinfo->device]);
80 modeinfo.flags = (modeinfo.depth == 8 ? XBIOSMODE_C2P : 0);
81
82 SDL_XBIOS_AddMode(this, actually_add, &modeinfo);
83}
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_sb3.h b/apps/plugins/sdl/src/video/xbios/SDL_xbios_sb3.h
deleted file mode 100644
index 3272c31349..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_sb3.h
+++ /dev/null
@@ -1,82 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 ScreenBlaster 3 definitions
26
27 Patrice Mandin
28*/
29
30#ifndef _SDL_xbios_sb3_h_
31#define _SDL_xbios_sb3_h_
32
33/*--- Defines ---*/
34
35#ifndef C_SCPN
36#define C_SCPN 0x5343504EL
37#endif
38
39#define SCPN_DEV_1BPP 0
40#define SCPN_DEV_2BPP 1
41#define SCPN_DEV_4BPP 2
42#define SCPN_DEV_8BPP 3
43#define SCPN_DEV_16BPP 4
44
45extern const int SDL_XBIOS_scpn_planes_device[];
46
47/*--- Types ---*/
48
49typedef struct {
50 unsigned short virtual_width; /* Virtual screen width */
51 unsigned short virtual_height; /* Virtual screen height */
52 unsigned short visible_width; /* Visible width */
53 unsigned short visible_height; /* Visible height */
54 unsigned short h_pos; /* Horizontal position in virtual screen */
55 unsigned short v_pos; /* Vertical position in virtual screen */
56 unsigned short dummy;
57 unsigned long size; /* Size of screen in bytes */
58 unsigned short device; /* Device number to find planes = getRez() */
59 /* = Index in scpn_planes_device[] */
60} scpn_screeninfo_t;
61
62typedef struct {
63 unsigned long magic; /* just a BRA assembler jump */
64 unsigned short version;
65 void *dummy1;
66 unsigned short ptsout0_1;
67 unsigned short ptsout0_2;
68 unsigned short dummy3;
69 unsigned char date[8]; /* Date of program build */
70 unsigned char asm_string[30]; /* 10 times the 'ASM' string */
71 unsigned short dummy4;
72 scpn_screeninfo_t *screen_info;
73 unsigned short dummy6;
74} scpn_cookie_t;
75
76/*--- Function prototypes ---*/
77
78int SDL_XBIOS_SB3Usable(scpn_cookie_t *cookie_scpn);
79
80void SDL_XBIOS_ListSB3Modes(_THIS, int actually_add, scpn_cookie_t *cookie_scpn);
81
82#endif /* _SDL_xbios_sb3_h_ */
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_tveille.c b/apps/plugins/sdl/src/video/xbios/SDL_xbios_tveille.c
deleted file mode 100644
index b0f8499197..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_tveille.c
+++ /dev/null
@@ -1,63 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Turbo veille screensaver
26
27 Patrice Mandin
28*/
29
30#include <mint/cookie.h>
31
32#include "SDL_xbios.h"
33#include "SDL_xbios_tveille.h"
34
35static tveille_t *cookie_veil = NULL;
36static int status;
37
38int SDL_XBIOS_TveillePresent(_THIS)
39{
40 long dummy;
41
42 cookie_veil = NULL;
43 if (Getcookie(C_VeiL, &dummy) == C_FOUND) {
44 cookie_veil = (tveille_t *) dummy;
45 }
46
47 return (cookie_veil != NULL);
48}
49
50void SDL_XBIOS_TveilleDisable(_THIS)
51{
52 if (cookie_veil) {
53 status = cookie_veil->enabled;
54 cookie_veil->enabled = 0xff;
55 }
56}
57
58void SDL_XBIOS_TveilleEnable(_THIS)
59{
60 if (cookie_veil) {
61 cookie_veil->enabled = status;
62 }
63}
diff --git a/apps/plugins/sdl/src/video/xbios/SDL_xbios_tveille.h b/apps/plugins/sdl/src/video/xbios/SDL_xbios_tveille.h
deleted file mode 100644
index 8a9cd7d46a..0000000000
--- a/apps/plugins/sdl/src/video/xbios/SDL_xbios_tveille.h
+++ /dev/null
@@ -1,64 +0,0 @@
1/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/*
25 Turbo veille screensaver
26
27 Patrice Mandin
28*/
29
30#ifndef _SDL_xbios_tveille_h
31#define _SDL_xbios_tveille_h
32
33#include "SDL_xbios.h"
34
35/*--- Structures ---*/
36
37typedef struct {
38 unsigned long version;
39 void (*prg_ptr)();
40 void (*kbd_ptr)();
41 void (*vbl_ptr)();
42 unsigned long vbl_count;
43 void (*oldkbd_ptr)();
44 unsigned long off_count;
45 unsigned long prg_size;
46 unsigned long dummy1[4];
47 unsigned char dummy2;
48 unsigned char status;
49 unsigned short freq;
50 unsigned short dummy3;
51 unsigned char clear_first;
52 unsigned char enabled; /* 0=enabled, 0xff=disabled */
53 unsigned char serial_redir;
54 unsigned char dummy4;
55 void (*oldserial_ptr)();
56} tveille_t;
57
58/*--- Functions prototypes ---*/
59
60int SDL_XBIOS_TveillePresent(_THIS);
61void SDL_XBIOS_TveilleDisable(_THIS);
62void SDL_XBIOS_TveilleEnable(_THIS);
63
64#endif /* _SDL_xbios_tveille_h */