| 1 |
{%MainUnit ../castlewindow.pas} |
| 2 |
{ |
| 3 |
Copyright 2001-2024 Michalis Kamburelis. |
| 4 |
|
| 5 |
This file is part of "Castle Game Engine". |
| 6 |
|
| 7 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 8 |
included in this distribution, for details about the copyright. |
| 9 |
|
| 10 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 |
|
| 14 |
---------------------------------------------------------------------------- |
| 15 |
} |
| 16 |
|
| 17 |
{ CastleWindow backend using WinAPI, Windows-only. |
| 18 |
|
| 19 |
TODO: |
| 20 |
|
| 21 |
- Alt key presses are not perfectly detected. |
| 22 |
Is it even possible to cleanly catch VK_Alt key press in WinAPI? |
| 23 |
We would have to catch sys_keydown message but then we also |
| 24 |
block using standard Alt+F4 or Alt+Space? Another trouble: |
| 25 |
if you enter system menu by Alt+Down, we will not get Alt+Up? |
| 26 |
|
| 27 |
- Implement MainMenu.Enabled. |
| 28 |
|
| 29 |
Note: We use Unicode version of WinAPI (W suffix) throughout the code. |
| 30 |
|
| 31 |
- Why? |
| 32 |
Following https://stackoverflow.com/questions/33714546/winapi-unicode-and-ansi-functions , |
| 33 |
this is available on all Windowses after Windows 95, 98 and ME, |
| 34 |
and it is advised to use now (as the "A" routines just call "W" routines doing conversion underneath), |
| 35 |
and using it is easier on Delphi (where String = UnicodeString), |
| 36 |
and using it with both FPC and Delphi makes code simpler. |
| 37 |
|
| 38 |
- Note: LCL win32 widgetset (used on 64-bit Windows too) still uses ANSI. |
| 39 |
} |
| 40 |
|
| 41 |
{$ifdef USE_EGL} |
| 42 |
{$I castlewindow_egl.inc} |
| 43 |
{$else} |
| 44 |
{$I castlewindow_wgl.inc} |
| 45 |
{$endif} |
| 46 |
|
| 47 |
{$ifdef read_interface_uses} |
| 48 |
{ note: this unit's definitions conflict with other definitions used in this file |
| 49 |
But we need it for RegisterDeviceNotification, therefore adding it to the very |
| 50 |
first position in the uses list to be overwritten by subsequent used units } |
| 51 |
{$ifdef FPC} |
| 52 |
JwaWinUser, JwaDbt, |
| 53 |
{$else} |
| 54 |
Winapi.Messages, Character, |
| 55 |
{$endif} |
| 56 |
Imm, |
| 57 |
{ /note } |
| 58 |
Windows, CommDlg, |
| 59 |
{$endif} |
| 60 |
|
| 61 |
{$ifdef read_implementation_uses} |
| 62 |
CastleInternalWindowModes, CastleMessages, CastleJoysticks, CastleUnicode, |
| 63 |
CastleInternalFileMonitor, |
| 64 |
{$endif} |
| 65 |
|
| 66 |
{$ifdef read_window_interface} |
| 67 |
private |
| 68 |
h_Dc: HDC; |
| 69 |
h_Wnd: HWND; |
| 70 |
{ InCloseBackend = true means we are currently inside CloseBackend call. |
| 71 |
Useful -- see at WM_ACTIVATE. } |
| 72 |
InCloseBackend: boolean; |
| 73 |
|
| 74 |
EnableUpdatesFromWindowProc, DisableUpdatesFromWindowProc: Cardinal; |
| 75 |
|
| 76 |
VK_LeftBracket_Exists, |
| 77 |
VK_RightBracket_Exists, |
| 78 |
VK_Apostrophe_Exists, |
| 79 |
VK_Semicolon_Exists, |
| 80 |
VK_Slash_Exists, |
| 81 |
VK_BackQuote_Exists, |
| 82 |
VK_BackSlash_Exists: boolean; |
| 83 |
VK_LeftBracket, |
| 84 |
VK_RightBracket, |
| 85 |
VK_Apostrophe, |
| 86 |
VK_Semicolon, |
| 87 |
VK_Slash, |
| 88 |
VK_BackQuote, |
| 89 |
VK_BackSlash: Byte; |
| 90 |
|
| 91 |
function WindowProc(uMsg: UINT; wParm: WPARAM; lParm: LPARAM): LRESULT; |
| 92 |
|
| 93 |
{ convert virtual key code (VK_xxx) to TKey. Returns keyNone if no conversion |
| 94 |
available. } |
| 95 |
function VirtualKeyToKey(VirtualKey: Byte): TKey; |
| 96 |
{$endif read_window_interface} |
| 97 |
|
| 98 |
{$ifdef read_application_interface} |
| 99 |
private |
| 100 |
{ Should we do ChangeDisplaySettings(nil, 0) when Destroy? } |
| 101 |
DisplaySettingsChanged: boolean; |
| 102 |
WndClassName: UnicodeString; |
| 103 |
|
| 104 |
{ A private array, initialized in CreateBackend. |
| 105 |
Having all cursor handles loaded makes sure that WM_SETCURSOR is able to |
| 106 |
use predefined HCURSOR values and so is fast. SetCursor is guaranteed |
| 107 |
by WinAPI to return fast if called with already used cursor. |
| 108 |
|
| 109 |
For mcDefault, value in this array is undefined. |
| 110 |
(but 0 in practice, for now). |
| 111 |
|
| 112 |
For mcNone and CursorHandles, CursorHandle is guaranteed 0 |
| 113 |
(this is what SetCursor always accepts as invisible cursor). } |
| 114 |
CursorHandles: array [TMouseCursor] of record |
| 115 |
Handle: HCURSOR; |
| 116 |
end; |
| 117 |
|
| 118 |
fappActive: boolean; |
| 119 |
procedure SetAppActive(value: boolean); |
| 120 |
property appActive: boolean read fappActive write SetAppActive; |
| 121 |
{$endif read_application_interface} |
| 122 |
|
| 123 |
{$ifdef read_implementation} |
| 124 |
|
| 125 |
{$I castlewindow_winapi_menu.inc} |
| 126 |
{$I castlewindow_winapi_sendinput.inc} |
| 127 |
|
| 128 |
{ Describe ChangeDisplaySettings result. } |
| 129 |
function DispChangeToStr(L: LongInt): String; |
| 130 |
begin |
| 131 |
case L of |
| 132 |
DISP_CHANGE_SUCCESSFUL: Result := 'DISP_CHANGE_SUCCESSFUL'; |
| 133 |
DISP_CHANGE_RESTART: Result := 'DISP_CHANGE_RESTART'; |
| 134 |
DISP_CHANGE_BADFLAGS: Result := 'DISP_CHANGE_BADFLAGS'; |
| 135 |
DISP_CHANGE_FAILED: Result := 'DISP_CHANGE_FAILED'; |
| 136 |
DISP_CHANGE_BADMODE: Result := 'DISP_CHANGE_BADMODE'; |
| 137 |
DISP_CHANGE_NOTUPDATED: Result := 'DISP_CHANGE_NOTUPDATED'; |
| 138 |
else Result := IntToStr(L); |
| 139 |
end; |
| 140 |
end; |
| 141 |
|
| 142 |
{ WMSizing ------------------------------------------------------------------- } |
| 143 |
|
| 144 |
type |
| 145 |
{ Handling WMSizing message is a way to force minimum/maximum form |
| 146 |
sizes under WinAPI. } |
| 147 |
TWMSizing = record |
| 148 |
Msg: Cardinal; {< wm_SIZING } |
| 149 |
fwSide: Longint; {< const WMSZ_xxx } |
| 150 |
lprc: PRect; {< rectangle with window sizes } |
| 151 |
Result: LongBool; {< should return longbool(true) } |
| 152 |
end; |
| 153 |
|
| 154 |
procedure WMSizingHandler(var Msg:TWMSizing; |
| 155 |
const minWidth, minHeight, maxWidth, maxHeight:integer); overload; |
| 156 |
var |
| 157 |
w, h:integer; |
| 158 |
begin |
| 159 |
assert(minWidth<=maxWidth); |
| 160 |
assert(minHeight<=maxHeight); |
| 161 |
with msg.lprc^ do |
| 162 |
begin |
| 163 |
w := right-left; |
| 164 |
if w<minWidth then right := left+minWidth else |
| 165 |
if w>maxWidth then right := left+maxWidth; |
| 166 |
h := bottom-top; |
| 167 |
if h<minHeight then bottom := top+minHeight else |
| 168 |
if h>maxHeight then bottom := top+maxHeight; |
| 169 |
end; |
| 170 |
msg.result := true; |
| 171 |
end; |
| 172 |
|
| 173 |
function WMSizingHandler(const lParm:LPARAM; const wParm:WPARAM; |
| 174 |
const minWidth, minHeight, maxWidth, maxHeight:integer):LRESULT; overload; |
| 175 |
var |
| 176 |
msg: TWMSizing; |
| 177 |
begin |
| 178 |
msg.Msg := WM_SIZING; |
| 179 |
msg.fwSide := wParm; |
| 180 |
msg.lprc := PRect(lParm); |
| 181 |
WMSizingHandler(msg, minWidth, minHeight, maxWidth, maxHeight); |
| 182 |
result := LRESULT(msg.Result); |
| 183 |
end; |
| 184 |
|
| 185 |
{ TCastleWindow ------------------------------------------------- } |
| 186 |
|
| 187 |
const |
| 188 |
{ Some constants missing from FPC's Windows unit. } |
| 189 |
VK_OEM_1 = $BA; |
| 190 |
VK_OEM_PLUS = $BB; |
| 191 |
VK_OEM_COMMA = $BC; |
| 192 |
VK_OEM_MINUS = $BD; |
| 193 |
VK_OEM_PERIOD = $BE; |
| 194 |
VK_OEM_2 = $BF; |
| 195 |
VK_OEM_3 = $C0; |
| 196 |
VK_OEM_4 = $DB; |
| 197 |
VK_OEM_5 = $DC; |
| 198 |
VK_OEM_6 = $DD; |
| 199 |
VK_OEM_7 = $DE; |
| 200 |
VK_OEM_8 = $DF; |
| 201 |
VK_OEM_102 = $E2; |
| 202 |
|
| 203 |
{ convert virtual key code (VK_xxx) to TKey. Returns keyNone if no conversion |
| 204 |
available. } |
| 205 |
function TCastleWindow.VirtualKeyToKey(VirtualKey: Byte): TKey; |
| 206 |
var |
| 207 |
VirtualKeyToKeyResult: TKey absolute Result; |
| 208 |
|
| 209 |
function VK_Stored(VK_Exists: boolean; VK_Value: Byte; KeyValue: TKey): boolean; |
| 210 |
begin |
| 211 |
Result := VK_Exists and (VirtualKey = VK_Value); |
| 212 |
if Result then |
| 213 |
VirtualKeyToKeyResult := KeyValue; |
| 214 |
end; |
| 215 |
|
| 216 |
begin |
| 217 |
{ Tests: InfoWrite(Format('key %d', [VirtualKey])); } |
| 218 |
|
| 219 |
case VirtualKey of |
| 220 |
VK_BACK: Result := keyBackSpace; |
| 221 |
VK_TAB: Result := keyTab; |
| 222 |
VK_RETURN: Result := keyEnter; |
| 223 |
VK_SHIFT: Result := keyShift; |
| 224 |
VK_CONTROL: Result := keyCtrl; |
| 225 |
VK_MENU: Result := keyAlt; |
| 226 |
VK_ESCAPE: Result := keyEscape; |
| 227 |
VK_SPACE: Result := keySpace; |
| 228 |
VK_PRIOR: Result := keyPageUp; |
| 229 |
VK_NEXT: Result := keyPageDown; |
| 230 |
VK_END: Result := keyEnd; |
| 231 |
VK_HOME: Result := keyHome; |
| 232 |
VK_LEFT: Result := keyArrowLeft; |
| 233 |
VK_UP: Result := keyArrowUp; |
| 234 |
VK_RIGHT: Result := keyArrowRight; |
| 235 |
VK_DOWN: Result := keyArrowDown; |
| 236 |
VK_INSERT: Result := keyInsert; |
| 237 |
VK_DELETE: Result := keyDelete; |
| 238 |
VK_ADD: Result := keyNumpadPlus; |
| 239 |
VK_SUBTRACT: Result := keyNumpadMinus; |
| 240 |
VK_SNAPSHOT: Result := keyPrintScreen; |
| 241 |
VK_NUMLOCK: Result := keyNumLock; |
| 242 |
VK_SCROLL: Result := keyScrollLock; |
| 243 |
VK_CAPITAL: Result := keyCapsLock; |
| 244 |
VK_PAUSE: Result := keyPause; |
| 245 |
VK_OEM_COMMA: Result := keyComma; |
| 246 |
VK_OEM_PERIOD: Result := keyPeriod; |
| 247 |
VK_NUMPAD0: Result := keyNumpad0; |
| 248 |
VK_NUMPAD1: Result := keyNumpad1; |
| 249 |
VK_NUMPAD2: Result := keyNumpad2; |
| 250 |
VK_NUMPAD3: Result := keyNumpad3; |
| 251 |
VK_NUMPAD4: Result := keyNumpad4; |
| 252 |
VK_NUMPAD5: Result := keyNumpad5; |
| 253 |
VK_NUMPAD6: Result := keyNumpad6; |
| 254 |
VK_NUMPAD7: Result := keyNumpad7; |
| 255 |
VK_NUMPAD8: Result := keyNumpad8; |
| 256 |
VK_NUMPAD9: Result := keyNumpad9; |
| 257 |
VK_CLEAR: Result := keyNumpadBegin; |
| 258 |
VK_MULTIPLY: Result := keyNumpadMultiply; |
| 259 |
VK_DIVIDE: Result := keyNumpadDivide; |
| 260 |
VK_OEM_MINUS: Result := keyMinus; |
| 261 |
VK_OEM_PLUS: Result := keyPlus; |
| 262 |
|
| 263 |
Ord('0') .. Ord('9'): Result := TKey(Ord(key0) + Ord(VirtualKey) - Ord('0')); |
| 264 |
Ord('A') .. Ord('Z'): Result := TKey(Ord(keyA) + Ord(VirtualKey) - Ord('A')); |
| 265 |
VK_F1 .. VK_F12 : Result := TKey(Ord(keyF1) + Ord(VirtualKey) - Ord(VK_F1)); |
| 266 |
else |
| 267 |
if not VK_Stored(VK_LeftBracket_Exists , VK_LeftBracket , keyLeftBracket ) then |
| 268 |
if not VK_Stored(VK_RightBracket_Exists, VK_RightBracket, keyRightBracket) then |
| 269 |
if not VK_Stored(VK_Apostrophe_Exists , VK_Apostrophe , keyApostrophe ) then |
| 270 |
if not VK_Stored(VK_Semicolon_Exists , VK_Semicolon , keySemicolon ) then |
| 271 |
if not VK_Stored(VK_Slash_Exists , VK_Slash , keySlash ) then |
| 272 |
if not VK_Stored(VK_BackQuote_Exists , VK_BackQuote , keyBackQuote ) then |
| 273 |
if not VK_Stored(VK_BackSlash_Exists , VK_BackSlash , keyBackSlash ) then |
| 274 |
Result := keyNone; |
| 275 |
end; |
| 276 |
|
| 277 |
{ Note that CastleWindow WinAPI will never generate Press/Release with these keys: |
| 278 |
keyNumpadEnd; |
| 279 |
keyNumpadDown; |
| 280 |
keyNumpadPageDown; |
| 281 |
keyNumpadLeft; |
| 282 |
keyNumpadRight; |
| 283 |
keyNumpadHome; |
| 284 |
keyNumpadUp; |
| 285 |
keyNumpadPageUp; |
| 286 |
keyNumpadInsert; |
| 287 |
keyNumpadDelete; |
| 288 |
keyNumpadEnter; |
| 289 |
because (as far as I can see) they are undistinguishable from normal, |
| 290 |
non-numpad key codes under WinAPI. |
| 291 |
|
| 292 |
Note that it seems that VK_SNAPSHOT (keyPrintScreen) is never passed to |
| 293 |
WM_KEYDOWN (although it's passed to WM_KEYUP; but there we ignore it, |
| 294 |
because in our Keys[] table it's already up). |
| 295 |
So you will never get KeyDown/Up with keyPrintScreen. } |
| 296 |
end; |
| 297 |
|
| 298 |
function TryHandlingMessage(hWnd: HWND; uMsg: UINT; wParm: WPARAM; lParm: LPARAM): boolean; |
| 299 |
var |
| 300 |
Window: TCastleWindow; |
| 301 |
begin |
| 302 |
Window := TCastleWindow(GetWindowLongPtr(hWnd, GWL_USERDATA)); |
| 303 |
Result := Application.FindWindow(Window) >= 0; |
| 304 |
if Result then |
| 305 |
Window.WindowProc(uMsg, wParm, lParm); |
| 306 |
end; |
| 307 |
|
| 308 |
function WndProc(hWnd: HWND; uMsg: UINT; wParm: WPARAM; lParm: LPARAM) :LRESULT; stdcall; |
| 309 |
var |
| 310 |
Window: TCastleWindow; |
| 311 |
begin |
| 312 |
Window := TCastleWindow(GetWindowLongPtr(hWnd, GWL_USERDATA)); |
| 313 |
{ Wszystkie hwnd jakie tu beda wpadac to beda nasze okna |
| 314 |
(it's only different for a plugin, but right now the plugin uses only TryHandlingMessage, |
| 315 |
not this). Ale zanim |
| 316 |
ustawimy oknu SetWindowLongPtr (GetWindowLongPtr bedzie do tego czasu zwracac 0) |
| 317 |
ono juz dostaje jakies messagy - WM_CREATE i inne. |
| 318 |
Mozemy je spokojnie zignorowac. |
| 319 |
|
| 320 |
Co wiecej jednak, moze tak byc ze Window <> nil ale wskazuje na okienko |
| 321 |
ktore juz jest zamkniete (a moze nawet na obiekt ktory juz zostal |
| 322 |
zwolniony z pamieci !). Dlaczego tak jest, patrz komentarz na poczatku |
| 323 |
castlewindow_winsystem.inc. Wiec sprawdzamy tutaj czy Window jest na liscie |
| 324 |
Application.OpenWindows . |
| 325 |
|
| 326 |
Moreover, temporary windows created by CreateTemporaryWindow in |
| 327 |
SetPixelFormat_WGLChoose also get here (as they use our |
| 328 |
Application.wndClassName). They don't set Get/SetWindowLongPtr, so Window here |
| 329 |
will be @nil in this case. } |
| 330 |
if Application.FindWindow(Window) >= 0 then |
| 331 |
result := Window.WindowProc(uMsg, wParm, lParm) |
| 332 |
else |
| 333 |
result := DefWindowProcW(hWnd, uMsg, wParm, lParm); |
| 334 |
end; |
| 335 |
|
| 336 |
function TCastleWindow.WindowProc(uMsg: UINT; wParm: WPARAM; lParm: LPARAM): LRESULT; |
| 337 |
|
| 338 |
{ Note: the following Windows events may be called from CloseBackend |
| 339 |
(so they probably should check InCloseBackend): |
| 340 |
WM_WINDOWPOSCHANGING |
| 341 |
WM_WINDOWPOSCHANGED |
| 342 |
WM_NCACTIVATE |
| 343 |
WM_ACTIVATE |
| 344 |
WM_ACTIVATEAPP |
| 345 |
WM_KILLFOCUS |
| 346 |
WM_DESTROY |
| 347 |
WM_NCDESTROY |
| 348 |
|
| 349 |
WM_SIZE (yes, tested on Windows 2000 Prof, when running my progs |
| 350 |
with --fullscreen-custom, e.g. glinformation --fullscreen-custom 640x480 |
| 351 |
or glplotter --fullscreen-custom 640x480) |
| 352 |
} |
| 353 |
|
| 354 |
procedure MaybeCapture; |
| 355 |
{ mouse down occurred; so capture the mouse if it's not captured already } |
| 356 |
begin |
| 357 |
if GetCapture <> H_Wnd then SetCapture(H_Wnd); |
| 358 |
end; |
| 359 |
|
| 360 |
procedure MaybeRelease; |
| 361 |
{ mouse up occurred; release capture if all mouse buttons are now up } |
| 362 |
begin |
| 363 |
if (mousePressed=[]) and (GetCapture = H_Wnd) then ReleaseCapture; |
| 364 |
end; |
| 365 |
|
| 366 |
type |
| 367 |
{ This is useful to deconstruct WParam and LParam. |
| 368 |
It will work faster than any LoWord/HiWord functions in Windows unit, |
| 369 |
it avoids any range-check errors, |
| 370 |
it allows to specify signedness of values as you wish. } |
| 371 |
TWinParam = packed record |
| 372 |
case Integer of |
| 373 |
0:(Signed: LongInt {$if defined(cpu64)}; Dummy: UInt32 {$endif}); |
| 374 |
1:(LoWord, HiWord: Word); |
| 375 |
2:(LoSmallint, HiSmallint: Smallint); |
| 376 |
3:(LowestByte, LowerByte, HigherByte, HighestByte: byte); |
| 377 |
end; |
| 378 |
|
| 379 |
function InterceptedSystemKey(key: integer): boolean; |
| 380 |
begin |
| 381 |
Result := { TODO-alt: (key = VK_Alt) or }(key = VK_F10) |
| 382 |
end; |
| 383 |
|
| 384 |
{ Convert WM_CHAR's wParam value to a String in UTF-8 encoding, |
| 385 |
corresponding to key pressed. Empty if none. } |
| 386 |
function ConvertWmCharToString(const CharMsgWParam: WPARAM): String; |
| 387 |
begin |
| 388 |
{ According to WM_CHAR docs, wParam is already a single character in UTF-16 encoding. |
| 389 |
This is true if we peeked it using PeekMessageW, not PeekMessage. |
| 390 |
So just convert it using UTF8Encode. |
| 391 |
|
| 392 |
Notes: |
| 393 |
|
| 394 |
- Doing "Exit(UnicodeCharToString(WParm))" also seems to work for Polish chars. |
| 395 |
But it's not necessarily correct, I think: UTF-16 character number |
| 396 |
is not necessarily equal to just Unicode number. |
| 397 |
|
| 398 |
- At one point we did here |
| 399 |
|
| 400 |
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, @CharMsgWParam, SizeOf(CharMsgWParam), ...) |
| 401 |
|
| 402 |
But this was a hack: we treated CharMsgWParam as string |
| 403 |
(4 bytes, so 2 characters) in local Windows ANSI code page. |
| 404 |
We then hackishly ignored MultiByteToWideChar result, |
| 405 |
and used first returned WideChar. |
| 406 |
} |
| 407 |
{$ifdef FPC} |
| 408 |
Exit(UTF8Encode(WideChar(CharMsgWParam))); |
| 409 |
{$else} |
| 410 |
Exit(WideChar(CharMsgWParam)); |
| 411 |
{$endif} |
| 412 |
end; |
| 413 |
|
| 414 |
{ Handle WinAPI WM_KEYDOWN message by calling DoKeyDown method. |
| 415 |
We also handle (peek and remove) WM_CHAR message here. } |
| 416 |
procedure Handle_WM_KEYDOWN; |
| 417 |
|
| 418 |
{ Note that WM_KEYDOWN is repeated when the user holds the key down. |
| 419 |
The frequency of "key repeat" depends on user settings. |
| 420 |
|
| 421 |
And... that's completely OK. We still pass each WM_KEYDOWN to DoKeyDown. |
| 422 |
This way our API (TCastleUserInterface.Press, TCastleWindow.OnPress) |
| 423 |
will generate repeated key presses. |
| 424 |
This is documented and desired (e.g. for implementing UI like edit box). |
| 425 |
User can check TInputPressRelease.KeyRepeated that is calculated |
| 426 |
elsewhere. (We could also calculate TInputPressRelease.KeyRepeated here, |
| 427 |
looking at KEY_ALREADY_DOWN bit in lParm, but it's not needed for now.) |
| 428 |
} |
| 429 |
|
| 430 |
var |
| 431 |
Key: TKey; |
| 432 |
CharMsg: TMsg; |
| 433 |
KeyString: String; |
| 434 |
begin |
| 435 |
{ WM_CHAR is placed in our message queue by TranslateMessage. |
| 436 |
Always in WM_KEYDOWN we do this PeekMessageW(..., WM_CHAR, WM_CHAR, PM_REMOVE). |
| 437 |
This means that now we have |
| 438 |
1. no WM_CHAR messages in our message queue (which means that this |
| 439 |
WM_KEYDOWN message is not translatable as WM_CHAR) OR |
| 440 |
2. we have exactly one WM_CHAR message in our queue, and this is WM_CHAR |
| 441 |
message corresponding to current WM_KEYDOWN message. |
| 442 |
|
| 443 |
Note PeekMessageW, not PeekMessage. |
| 444 |
This is necessary to receive UTF-16 for e.g. Polish chars. |
| 445 |
Otherwise WM_CHAR gets characters in ANSI encoding. |
| 446 |
} |
| 447 |
|
| 448 |
if PeekMessageW({$ifdef FPC}@{$endif}CharMsg, h_Wnd, WM_CHAR, WM_CHAR, PM_REMOVE) then |
| 449 |
KeyString := ConvertWmCharToString(CharMsg.wParam) |
| 450 |
else |
| 451 |
KeyString := ''; |
| 452 |
|
| 453 |
Key := VirtualKeyToKey(wParm); |
| 454 |
|
| 455 |
{ We cannot depend that VK_OEM_4 is always "[" and VK_OEM_6 is always "]", |
| 456 |
see http://www.tronan.com/macromachine/scripthelp/VK.htm. |
| 457 |
On non-US keyboards, other keys may correspond to them. |
| 458 |
|
| 459 |
So below we do a little trick: we check which virtual key corresponds to |
| 460 |
left/right brackets, and we remember it. If my VirtualKeyToKey returned |
| 461 |
keyNone for this virtual key, then we can safely assume that in the future |
| 462 |
(e.g. for next WM_KEYUP for this key) this virtual key always corresponds |
| 463 |
to left/right bracket. } |
| 464 |
if Key = keyNone then |
| 465 |
begin |
| 466 |
if KeyString = '[' then |
| 467 |
begin VK_LeftBracket_Exists := true; VK_LeftBracket := wParm; Key := keyLeftBracket ; end |
| 468 |
else if KeyString = ']' then |
| 469 |
begin VK_RightBracket_Exists := true; VK_RightBracket := wParm; Key := keyRightBracket; end |
| 470 |
else if KeyString = '''' then |
| 471 |
begin VK_Apostrophe_Exists := true; VK_Apostrophe := wParm; Key := keyApostrophe ; end |
| 472 |
else if KeyString = ';' then |
| 473 |
begin VK_Semicolon_Exists := true; VK_Semicolon := wParm; Key := keySemicolon ; end |
| 474 |
else if KeyString = '/' then |
| 475 |
begin VK_Slash_Exists := true; VK_Slash := wParm; Key := keySlash ; end |
| 476 |
else if KeyString = '`' then |
| 477 |
begin VK_BackQuote_Exists := true; VK_BackQuote := wParm; Key := keyBackQuote ; end |
| 478 |
else if KeyString = '\' then |
| 479 |
begin VK_BackSlash_Exists := true; VK_BackSlash := wParm; Key := keyBackSlash ; end; |
| 480 |
end; |
| 481 |
|
| 482 |
{ Fix some cases when KeyString should better correspond to Key } |
| 483 |
if (KeyString = '') and (Key = keyDelete) then |
| 484 |
KeyString := CharDelete; |
| 485 |
|
| 486 |
if (Key <> keyNone) or (KeyString <> '') then DoKeyDown(Key, KeyString); |
| 487 |
end; |
| 488 |
|
| 489 |
{ Handle WinAPI WM_KEYUP message by calling DoKeyUp method. } |
| 490 |
procedure Handle_WM_KEYUP; |
| 491 |
var |
| 492 |
Key: TKey; |
| 493 |
begin |
| 494 |
Key := VirtualKeyToKey(wParm); |
| 495 |
if Key <> keyNone then DoKeyUp(Key); |
| 496 |
end; |
| 497 |
|
| 498 |
{ Handle WM_CHAR that arrived without WM_KEYDOWN. |
| 499 |
|
| 500 |
- In case of input in Western languages (English, Polish etc.): |
| 501 |
|
| 502 |
This should never happen. |
| 503 |
|
| 504 |
The only way we can get WM_CHAR message is when we get WM_KEYDOWN |
| 505 |
message and TranslateMessage (called from castlewindow_winsystem.inc) |
| 506 |
translates it to WM_CHAR message. |
| 507 |
But actually always in WM_KEYDOWN handler we do |
| 508 |
PeekMessageW(..., WM_CHAR, WM_CHAR, PM_REMOVE) so all WM_CHAR messages |
| 509 |
are removed from queue immediately after they are put there by TranslateMessage. |
| 510 |
|
| 511 |
So no WM_CHAR message should be ever dispatched by DispatchMessage. |
| 512 |
So no WM_CHAR message should ever get here. |
| 513 |
|
| 514 |
- In case of Chinese, where input arrives only through WM_CHAR, |
| 515 |
this can definitely happen. |
| 516 |
|
| 517 |
For Chinese you have a special window that allows to compose Chinese characters. |
| 518 |
Looks like they don't result in WM_KEYDOWN, only WM_CHAR. |
| 519 |
Tested with simplified Chinese input on Windows 10. |
| 520 |
Note: It does *not* make WM_UNICHAR (regardless if we register using RegisterClassW or ANSI version). |
| 521 |
|
| 522 |
- A minor thing about Wine compatibility: |
| 523 |
It seems wine-1.5.30-1 lets WM_CHAR arrive without WM_KEYDOWN |
| 524 |
in one special case too: when pressing escape to unfocus menu bar. |
| 525 |
} |
| 526 |
procedure Handle_WM_CHAR; |
| 527 |
var |
| 528 |
KeyString: String; |
| 529 |
begin |
| 530 |
KeyString := ConvertWmCharToString(WParm); |
| 531 |
if KeyString <> '' then |
| 532 |
DoKeyDown(keyNone, KeyString); |
| 533 |
end; |
| 534 |
|
| 535 |
{ Handle WM_UNICHAR that reports a key press as 32-bit Unicode character. |
| 536 |
|
| 537 |
WM_UNICHAR seems to never happen in practice. |
| 538 |
|
| 539 |
See also |
| 540 |
https://stackoverflow.com/questions/378296/why-is-my-wm-unichar-handler-never-called |
| 541 |
https://stackoverflow.com/questions/5844689/winapi-how-to-process-keyboard-input-in-custom-edit-control |
| 542 |
|
| 543 |
""" |
| 544 |
- WM_KEYDOWN is sent to the window with the focus when a non-system key has been pressed. When the message is translated by the TranslateMessage function, a WM_CHAR message is sent to the window. |
| 545 |
- WM_CHAR uses UTF-16. |
| 546 |
- WM_UNICHAR is similat to WM_CHAR, except that it uses UTF-32. |
| 547 |
|
| 548 |
It's purpose is to send/post Unicode characters to ANSI windows. |
| 549 |
If the window is ANSI (created with CreateWindowA), when WM_CHAR is generated. |
| 550 |
If it is Unicode (created with CreateWindowW) then WM_UNICHAR is generated. |
| 551 |
|
| 552 |
So your control should probably handle both. |
| 553 |
Other applications can send us WM_UNICHAR, according to WinAPI docs. |
| 554 |
""" |
| 555 |
|
| 556 |
Testing in practice: I didn't find a way to cause WM_UNICHAR in either |
| 557 |
ANSI or Unicode window (created with CreateWindowExW). |
| 558 |
} |
| 559 |
procedure Handle_WM_UNICHAR; |
| 560 |
var |
| 561 |
KeyString: String; |
| 562 |
begin |
| 563 |
WritelnLog('Received WM_UNICHAR. This may work but is UNTESTED in CGE (please post a report if you know how to cause this message). Test information for https://github.com/castle-engine/castle-engine/issues/159 : WParam ' + IntToStr(WParm)); |
| 564 |
if wParm <> UNICODE_NOCHAR then // ignore UNICODE_NOCHAR, which is used only to test do we handle WM_UNICHAR |
| 565 |
begin |
| 566 |
{ Treat UTF-32 character code as just Unicode code. |
| 567 |
This is the same: https://en.wikipedia.org/wiki/UTF-32, |
| 568 |
"""Each 32-bit value in UTF-32 represents one Unicode code point and is exactly equal to that code point's numerical value. """ |
| 569 |
} |
| 570 |
KeyString := UnicodeCharToString(WParm); |
| 571 |
if KeyString <> '' then |
| 572 |
DoKeyDown(keyNone, KeyString); |
| 573 |
end; |
| 574 |
end; |
| 575 |
|
| 576 |
function Handle_IME: Boolean; |
| 577 |
|
| 578 |
function ToPoint(const V: TVector2): TPoint; |
| 579 |
begin |
| 580 |
Result.X := Floor(V.X); |
| 581 |
Result.Y := Floor(Container.PixelsHeight - V.Y); |
| 582 |
end; |
| 583 |
|
| 584 |
function GetCaretPos(var CaretPos: TPoint): Boolean; |
| 585 |
var |
| 586 |
CastleEdit: TCastleEdit; |
| 587 |
CaretShift: Single; |
| 588 |
S: String; |
| 589 |
begin |
| 590 |
Result := false; |
| 591 |
{ TODO: Handles all input controls, not just TCastleEdit } |
| 592 |
if Container.FocusFront is TCastleEdit then |
| 593 |
begin |
| 594 |
CastleEdit := Container.FocusFront as TCastleEdit; |
| 595 |
S := CastleEdit.Text; |
| 596 |
if CastleEdit.PasswordChar <> #0 then |
| 597 |
S := StringOfChar(CastleEdit.PasswordChar, Length(S)); |
| 598 |
CaretShift := CastleEdit.Font.TextWidth(S); |
| 599 |
CaretPos := ToPoint(CastleEdit.LocalToContainerPosition(Vector2(CaretShift / CastleEdit.UIScale, 0))); |
| 600 |
Result := true; |
| 601 |
end; |
| 602 |
end; |
| 603 |
|
| 604 |
var |
| 605 |
vhIMC: HIMC; |
| 606 |
vSize: Integer; |
| 607 |
vBuffer: TBytes; |
| 608 |
KeyString: UnicodeString; |
| 609 |
//vLogFont: TLogFont; |
| 610 |
vCF: TCompositionForm; |
| 611 |
Pt: TPoint; |
| 612 |
begin |
| 613 |
Result := false; |
| 614 |
case uMsg of |
| 615 |
WM_IME_STARTCOMPOSITION, WM_IME_ENDCOMPOSITION: |
| 616 |
begin |
| 617 |
{ adjusted composition window's position and font/caret size } |
| 618 |
vhIMC := ImmGetContext(h_Wnd); |
| 619 |
if vhIMC = 0 then Exit; |
| 620 |
try |
| 621 |
ImmSetOpenStatus(vhIMC, true); |
| 622 |
{ TODO: Set the LogFont size } |
| 623 |
{ |
| 624 |
ImmGetCompositionFont(vhIMC, @vLogFont); |
| 625 |
vLogFont.lfHeight := Font.Height; |
| 626 |
ImmSetCompositionFont(vhIMC, @vLogFont); |
| 627 |
} |
| 628 |
if not GetCaretPos(Pt) then |
| 629 |
begin |
| 630 |
GetCursorPos(Pt); |
| 631 |
ScreenToClient(h_Wnd, Pt); |
| 632 |
Pt.Offset(0, 25); |
| 633 |
end; |
| 634 |
vCF.ptCurrentPos := Pt; |
| 635 |
vCF.dwStyle := CFS_RECT; |
| 636 |
vCF.rcArea := TRect.Create(0, 0, Width, Height); |
| 637 |
ImmSetCompositionWindow(vhIMC, @vCF); |
| 638 |
finally |
| 639 |
ImmReleaseContext(h_Wnd, vhIMC); |
| 640 |
end; |
| 641 |
|
| 642 |
{ About return value: |
| 643 |
Note that WM_IME_STARTCOMPOSITION, WM_IME_ENDCOMPOSITION must return false. |
| 644 |
Because we do not implement the IME input window by itself, we return false to let the system IME handle it by itself. |
| 645 |
We only tell the system where the IME window needs to be displayed, font information, etc. |
| 646 |
|
| 647 |
Why do we handle WM_IME_ENDCOMPOSITION at all (that is usually when IME window is hidden)? |
| 648 |
Since the IME can be developed by any company, sometimes the IME window will appear prematurely at the last closed position. |
| 649 |
So deal with WM_IME_ENDCOMPOSITION to avoid This case. |
| 650 |
} |
| 651 |
end; |
| 652 |
WM_IME_COMPOSITION: |
| 653 |
begin |
| 654 |
if (LParm and GCS_RESULTSTR) <> 0 then |
| 655 |
begin |
| 656 |
vhIMC := ImmGetContext(h_Wnd); |
| 657 |
if vhIMC = 0 then Exit; |
| 658 |
try |
| 659 |
vSize := ImmGetCompositionStringW(vhIMC, GCS_RESULTSTR, nil, 0); |
| 660 |
if vSize > 0 then |
| 661 |
begin |
| 662 |
SetLength(vBuffer, vSize); |
| 663 |
ImmGetCompositionStringW(vhIMC, GCS_RESULTSTR, @vBuffer[0], vSize); |
| 664 |
KeyString := WideStringOf(vBuffer); |
| 665 |
if KeyString <> '' then |
| 666 |
begin |
| 667 |
DoKeyDown(keyNone, Utf16ToString(KeyString)); |
| 668 |
end; |
| 669 |
end; |
| 670 |
finally |
| 671 |
ImmReleaseContext(h_Wnd, vhIMC); |
| 672 |
end; |
| 673 |
Result := true; |
| 674 |
end; |
| 675 |
end; |
| 676 |
end; |
| 677 |
end; |
| 678 |
|
| 679 |
procedure HandleMouseDown(const Button: TCastleMouseButton); |
| 680 |
begin |
| 681 |
MaybeCapture; |
| 682 |
DoMouseDown(LeftTopToCastle( |
| 683 |
TWinParam(lParm).LoSmallint, |
| 684 |
TWinParam(lParm).HiSmallint), Button, 0); |
| 685 |
end; |
| 686 |
|
| 687 |
procedure HandleMouseUp(const Button: TCastleMouseButton); |
| 688 |
begin |
| 689 |
DoMouseUp(LeftTopToCastle( |
| 690 |
TWinParam(lParm).LoSmallint, |
| 691 |
TWinParam(lParm).HiSmallint), Button, 0); |
| 692 |
MaybeRelease; |
| 693 |
end; |
| 694 |
|
| 695 |
var |
| 696 |
DoEnableUpdatesFromWindowProc, DoDisableUpdatesFromWindowProc: boolean; |
| 697 |
begin |
| 698 |
Result := 0; |
| 699 |
|
| 700 |
{ generalnie chcemy przepuszczac SYSKEY* do DefaultWndProc ktore moze |
| 701 |
wtedy np. na Alt+F4 zrobic nam close albo na Alt+spacja otworzyc |
| 702 |
nam system menu itp. To wszystko sa fajne rzeczy i nie chce ich blokowac |
| 703 |
przechwytujac zawsze zdarzenia SYSKEY*, tym samym rezygnuje z przetwarzania |
| 704 |
kiedywkolwiek sekwencji klawiszy w rodzaju Alt+F4. |
| 705 |
|
| 706 |
Ale jednak czasem chce przechwycic zdarzenia SYSKEY* zeby obsluzyc wlasne |
| 707 |
klawisze. Wiec niektore klawisze przechwytujemy od systemu operacyjnego. |
| 708 |
(normalnie Alt i F10 powoduja wejscie w menu). Wiec wtedy zmieniam uMsg z |
| 709 |
SYSKEY* na KEY* (korzystajac z tego ze te zdarzenia maja taki sam format |
| 710 |
dla wParm i lParm). } |
| 711 |
if (uMsg = WM_SYSKEYDOWN) and InterceptedSystemKey(wParm) then uMsg := WM_KEYDOWN; |
| 712 |
if (uMsg = WM_SYSKEYUP) and InterceptedSystemKey(wParm) then uMsg := WM_KEYUP; |
| 713 |
|
| 714 |
case uMsg of |
| 715 |
WM_ACTIVATE: |
| 716 |
if not InCloseBackend then |
| 717 |
if TWinParam(wParm).LoWord = WA_INACTIVE then |
| 718 |
{ When user switches to another program, fake that we release all keys/mouse. |
| 719 |
Otherwise we could miss some key up / mouse up, when user releases it over |
| 720 |
another program/window. |
| 721 |
Do not do this when InCloseBackend, as ReleaseAllKeysAndMouse causes |
| 722 |
some DoKeyUp/DoMouseUp (and these even cause BackendMakeCurrent), and no DoXxx |
| 723 |
should be done when the window is closing and releasing it's resources. } |
| 724 |
ReleaseAllKeysAndMouse; |
| 725 |
{ Don't Exit, let control flow to DefWindowProcW. } |
| 726 |
WM_ACTIVATEAPP: |
| 727 |
begin |
| 728 |
Application.appActive := longbool(wParm); |
| 729 |
if Application.appActive then |
| 730 |
FileMonitor.CheckChanges; |
| 731 |
{exit; <- allow DefWindowProcW handle WM_ACTIVETAPP too, |
| 732 |
since you can't say "we surely handled everything that should be done in |
| 733 |
reaction for this message"} |
| 734 |
end; |
| 735 |
WM_CLOSE: begin DoCloseQuery; Exit end; |
| 736 |
|
| 737 |
WM_KEYDOWN: begin Handle_WM_KEYDOWN; Exit end; |
| 738 |
WM_KEYUP: begin Handle_WM_KEYUP; Exit end; |
| 739 |
WM_CHAR: begin Handle_WM_CHAR; Exit end; |
| 740 |
WM_IME_STARTCOMPOSITION, |
| 741 |
WM_IME_ENDCOMPOSITION, |
| 742 |
WM_IME_COMPOSITION: |
| 743 |
begin |
| 744 |
if Handle_IME then Exit(0); |
| 745 |
end; |
| 746 |
// WM_UNICHAR answers true, and doesn't call DefWindowProcW, because we handled the message |
| 747 |
WM_UNICHAR: begin Handle_WM_UNICHAR; Exit(1); end; |
| 748 |
|
| 749 |
WM_SIZE: |
| 750 |
if not InCloseBackend then |
| 751 |
begin |
| 752 |
{ Note: Window class has (VREDRAW or HREDRAW), so Windows will automatically |
| 753 |
take care of requesting window redraw after window resize. } |
| 754 |
if (wParm = SIZE_MAXIMIZED) or (wParm = SIZE_RESTORED) then |
| 755 |
DoResize(TWinParam(lParm).LoWord, TWinParam(lParm).HiWord, false); |
| 756 |
Exit; |
| 757 |
end; |
| 758 |
WM_MOVE: |
| 759 |
{ For some reason, you need to call glViewport at WM_MOVE |
| 760 |
(when window moved) on Windows. |
| 761 |
Otherwise moving a window, and doing glRedPixels, reads pixels |
| 762 |
at *old window placement*. } |
| 763 |
begin |
| 764 |
fLeft := TWinParam(lParm).LoSmallint; |
| 765 |
fTop := TWinParam(lParm).HiSmallint; |
| 766 |
|
| 767 |
{ We need a hack in case of FullScreen and menu. |
| 768 |
|
| 769 |
We want to update Left and Top below to the position |
| 770 |
on the screen of our client area. "Client area" means tha place where OpenGL |
| 771 |
context is --- it's the window without the border, title bar and menu bar |
| 772 |
(if MainMenu <> nil). We need this, because |
| 773 |
|
| 774 |
1. Left and Top are said in unit's interface to work like that |
| 775 |
|
| 776 |
2. SetMousePosition requires this. Otherwise positions |
| 777 |
set by SetMousePosition and read by MousePosition properties |
| 778 |
would be slightly different. |
| 779 |
And there are cases when it is important that they use |
| 780 |
exactly the same coordinate systems --- e.g. mouse look handling. |
| 781 |
|
| 782 |
When the window is not FullScreen, WinAPI behaves nice, |
| 783 |
and Left and Top as recorded in lParm are exactly what I want. |
| 784 |
|
| 785 |
But when the window is FullScreen, Left and Top |
| 786 |
are always 0, 0 --- which means that they don't take menu bar height into |
| 787 |
account. The effect: mouse look + menu bar + fullscreen mode don't work. |
| 788 |
|
| 789 |
We workaround this by adding CYMENU. This is not perfect, as this assumes |
| 790 |
that menu bar will always be a single line. |
| 791 |
(This is also non-perfect anyway, because WM_MOVE message may not get to |
| 792 |
FullScreen window at all, so in OpenBackend I also do this trick.) } |
| 793 |
if FullScreen and (MainMenu <> nil) and MainMenuVisible then |
| 794 |
FTop := FTop + GetSystemMetrics(SM_CYMENU); |
| 795 |
|
| 796 |
{ TODO: Only position actually changed, not size. |
| 797 |
Do we really need to call DoResize, OnResize? |
| 798 |
Maybe we should just call only glViewport, |
| 799 |
using current RenderContext.Viewport? } |
| 800 |
DoResize(fRealWidth, fRealHeight, false); |
| 801 |
Exit; |
| 802 |
end; |
| 803 |
WM_SIZING: |
| 804 |
begin |
| 805 |
result := WMSizingHandler(lParm, wParm, minWidth, minHeight, maxWidth, maxHeight); |
| 806 |
Exit; |
| 807 |
end; |
| 808 |
{ We do not capture WM_PAINT, let WM_PAINT fallback to DefWindowProcW. |
| 809 |
WM_PAINT occurs also when there's a need to redraw window frame |
| 810 |
(which we don't care about, we don't draw custom window frame). |
| 811 |
|
| 812 |
If there's a need to actually redraw window contents, |
| 813 |
then WM_PAINT will cause (immediately, it seems that DefWindowProcW |
| 814 |
will just call WndProc) WM_ERASEBKGND, and we want to capture WM_ERASEBKGND. } |
| 815 |
WM_ERASEBKGND: |
| 816 |
begin |
| 817 |
if IsWindowEnabled(H_Wnd) then |
| 818 |
Invalidate else |
| 819 |
{ If not IsWindowEnabled then we have a modal window blocking our window. |
| 820 |
Like a Windows.MessageBox. In this case, our Application.ProcessMessage |
| 821 |
may not be continuously called, so we cannot use normal Invalidate |
| 822 |
and depend that window will be repainted soon. |
| 823 |
|
| 824 |
IOW, right now we're in WindowProc but not because of calling |
| 825 |
DispatchMessage from Application.ProcessMessage. Instead Windows |
| 826 |
modal boxes makes artificial call to cause our redraw, |
| 827 |
e.g. because user moves the modal window over our window. |
| 828 |
So just redraw right now. } |
| 829 |
DoRender; |
| 830 |
Result := 1; |
| 831 |
Exit; |
| 832 |
end; |
| 833 |
|
| 834 |
{ This is needed so that our window properly redraws itself when user |
| 835 |
activates menu from menu bar. If this is not present then when user |
| 836 |
activates our menu bar for the FIRST time (I don't know why only the |
| 837 |
first ?) and then opens some drop-drop menu 1, then switches to |
| 838 |
another drop-down menu 2, then we have problem: drop-down menu 1 contents |
| 839 |
are still partially visible (but only drop-down menu 2 contents should |
| 840 |
be visible now !). So our program must come and draw itself, so that |
| 841 |
drop-down menu 1 contents are not visible anymore. |
| 842 |
|
| 843 |
Note that this occurs when the user activates our menu bar for the first time. |
| 844 |
If he will close the menu and then open it again then Windows will properly |
| 845 |
handle everything and drop-down menu 1 contents will not be visible when |
| 846 |
drop-down menu 2 is open. (Windows can do this using saved image of our |
| 847 |
window, because activating menu under Windows essentially blocks our program |
| 848 |
anyway (look at comments at WM_INITMENU)). |
| 849 |
|
| 850 |
I don't know why Windows can't handle this itself when the menu is open |
| 851 |
for the first time. So maybe I'm actually fixing a Windows bug by handling |
| 852 |
this WM_ENTERIDLE below ? All of this tested on Windows 2000 Prof. } |
| 853 |
WM_ENTERIDLE: begin DoRender; Exit end; |
| 854 |
|
| 855 |
WM_INITMENU: |
| 856 |
begin |
| 857 |
{ We must call ReleaseAllKeysAndMouse when menu is activated. |
| 858 |
Even though the application message |
| 859 |
loop is blocked while we are in menu (menu under Windows work like modal |
| 860 |
windows that block activity of main window, the only way we can do some |
| 861 |
action when the menu is open is to handle some messages here like |
| 862 |
WM_ENTERIDLE or WM_INITMENU; those messages do NOT come from |
| 863 |
castlewindow_winsystem.inc DispatchMessage call, our WndProc is instead |
| 864 |
called directly by WinAPI). |
| 865 |
|
| 866 |
Still the problem remains: when someone presses a key (we get DoKeyDown) |
| 867 |
and then enters menu and then releases a key (we don't get DoKeyUp) and then |
| 868 |
leaves menu -- we have KeysDown[SomeKey] = true where it should be false. |
| 869 |
|
| 870 |
That's why we need this ReleaseAllKeysAndMouse below. } |
| 871 |
ReleaseAllKeysAndMouse; |
| 872 |
|
| 873 |
{ Windows blocks our program when user enters a menu bar. |
| 874 |
Essentially, this means that window will not receive normal events, |
| 875 |
will not process OnUpdate and such during the time menu bar is open. |
| 876 |
So menu bar is like a modal dialog box. |
| 877 |
So Fps.SecondsPassed at next Update is irrelevant, just like at the end of TGLMode. |
| 878 |
Fixes e.g. CameraTransitions when choosing viewpoint from castle-model-viewer menu. |
| 879 |
|
| 880 |
We would like to call this always when user leaves the menu, but it seems |
| 881 |
there's no WinAPI event for this. But we can as well call this when user enters |
| 882 |
the menu, because of blocking above --- it will have the same effect, since |
| 883 |
DoUpdate is not called inside the menu. } |
| 884 |
Fps.ZeroNextSecondsPassed; |
| 885 |
|
| 886 |
Exit; |
| 887 |
end; |
| 888 |
|
| 889 |
WM_MOUSEMOVE: |
| 890 |
begin |
| 891 |
{ We could refresh FMousePressed now: |
| 892 |
FMousePressed := []; |
| 893 |
if (MK_LBUTTON and wParm) <> 0 then Include(FMousePressed, buttonLeft); |
| 894 |
if (MK_MBUTTON and wParm) <> 0 then Include(FMousePressed, buttonMiddle); |
| 895 |
if (MK_RBUTTON and wParm) <> 0 then Include(FMousePressed, buttonRight); |
| 896 |
but it's not needed (we keep it current anyway in mousedown/up events). } |
| 897 |
DoMotion(InputMotion(MousePosition, LeftTopToCastle( |
| 898 |
TWinParam(lParm).LoSmallint, |
| 899 |
TWinParam(lParm).HiSmallint), |
| 900 |
MousePressed, 0)); |
| 901 |
Exit; |
| 902 |
end; |
| 903 |
WM_LBUTTONDOWN: begin HandleMouseDown(buttonLeft ); Exit end; |
| 904 |
WM_MBUTTONDOWN: begin HandleMouseDown(buttonMiddle); Exit end; |
| 905 |
WM_RBUTTONDOWN: begin HandleMouseDown(buttonRight ); Exit end; |
| 906 |
WM_LBUTTONUP : begin HandleMouseUp(buttonLeft ); Exit end; |
| 907 |
WM_MBUTTONUP : begin HandleMouseUp(buttonMiddle); Exit end; |
| 908 |
WM_RBUTTONUP : begin HandleMouseUp(buttonRight ); Exit end; |
| 909 |
WM_COMMAND : |
| 910 |
{ If this comes from a menu item, call DoMenuClick } |
| 911 |
if TWinParam(wParm).HiWord = 0 then |
| 912 |
begin |
| 913 |
DoMenuClick(MenuItemFromSmallId(TWinParam(wParm).LoWord)); |
| 914 |
Exit; |
| 915 |
end; |
| 916 |
|
| 917 |
{ On Windows, we have to change cursor in each WM_SETCURSOR (called on each |
| 918 |
mouse move (when mouse not captured), we also manually call it after each |
| 919 |
Cursor property change). |
| 920 |
|
| 921 |
That's because Windows internally doesn't have any "cursor" property associated |
| 922 |
with h_Wnd --- instead, it has only SetCursor that changes cursor globally, |
| 923 |
for everyone. Changing cursor on each WM_SETCURSOR seems to be the solution to |
| 924 |
enable / disable our private Cursor value when appropriate, so as not to change |
| 925 |
cursor look for other programs. This is also what glut for win32 does, so thanks |
| 926 |
go to glut win32 author, Nate Robins, for showing how it's done. |
| 927 |
|
| 928 |
There's some uncertainty whether doing SetCursor calls so often (each WM_SETCURSOR, |
| 929 |
each mouse move !) will not decrease performance --- but, well, there seems to be |
| 930 |
no other way, and SetCursor docs guarantee that SetCursor checks whether cursor |
| 931 |
changes. If no change, SetCursor returns immediately. So, we feel a little safer |
| 932 |
that we use CursorHandles[Cursor].Handle, so when Cursor stays the same, SetCursor |
| 933 |
is called with exactly the same arguments. } |
| 934 |
WM_SETCURSOR: |
| 935 |
begin |
| 936 |
if (WParm = h_Wnd) and |
| 937 |
( (InternalCursor in [mcNone, mcForceNone]) or |
| 938 |
(Application.CursorHandles[InternalCursor].Handle <> 0) ) then |
| 939 |
begin |
| 940 |
Windows.SetCursor(Application.CursorHandles[InternalCursor].Handle); |
| 941 |
Exit(1); |
| 942 |
end; |
| 943 |
{ Otherwise we fall back on DefWindowProcW. |
| 944 |
It will install our window class cursor (or parent cursor) |
| 945 |
if in client area, or just do the right thing if outside client area. |
| 946 |
So it's suitable when wParm <> h_Wnd, |
| 947 |
or we want mcDefault. } |
| 948 |
end; |
| 949 |
|
| 950 |
WM_MOUSEWHEEL, WM_MOUSEHWHEEL: |
| 951 |
begin |
| 952 |
if TWinParam(WParm).HiSmallInt <> 0 then |
| 953 |
DoMouseWheel(TWinParam(WParm).HiSmallInt / 120, uMsg = WM_MOUSEWHEEL); |
| 954 |
Exit; |
| 955 |
end; |
| 956 |
|
| 957 |
{ Event received when something in Windows configuration had been changed, |
| 958 |
most often this means connecting/disconnecting plug-n-play devices. |
| 959 |
Here we use it to detect DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE events |
| 960 |
which correspond to adding or removing devices and suggest those are |
| 961 |
caused by connecting/disconnecting a Joystick from the system. } |
| 962 |
WM_DEVICECHANGE: |
| 963 |
begin |
| 964 |
case WParm of |
| 965 |
{ A device has been sucessfully added to the system } |
| 966 |
DBT_DEVICEARRIVAL: |
| 967 |
begin |
| 968 |
WriteLnLog('Event WM_DEVICECHANGE + DBT_DEVICEARRIVAL, possibly a joystick connected'); |
| 969 |
//it might be a joystick, therefore |
| 970 |
Joysticks.InternalConnected; |
| 971 |
end; |
| 972 |
{ A device has been successfully removed from the system. |
| 973 |
Currently we more reliably handle this case in Joystick backend Poll |
| 974 |
because DBT_DEVICEREMOVECOMPLETE is sent by many different devices |
| 975 |
e.g. such as USB flash drive and it isn't right to treat all of these |
| 976 |
as disconnected joysticks. E.g. according to Steam recommendations |
| 977 |
the game should be set to pause when the joystick is disconnected, |
| 978 |
but forcing pause mode every time some arbitrary device has disconnected |
| 979 |
may be inconsistent and look like a bug to the user. |
| 980 |
The backend does this job better: |
| 981 |
1. The InternalDisconnected is sent immediately after the joystick has |
| 982 |
been disconnected, while WinAPI message comes with a delay ~0.5 seconds. |
| 983 |
2. Backend Poll guarantees that disconnect event comes from a previously |
| 984 |
connected joystick, not from any device. |
| 985 |
3. Backend Poll guarantees to send the InternalDisconnected event when |
| 986 |
joystick stopped working properly, while WinAPI behavior may depend |
| 987 |
on joystick driver implementation. } |
| 988 |
{DBT_DEVICEREMOVECOMPLETE: |
| 989 |
begin |
| 990 |
WriteLnLog('Received a WM_DEVICECHANGE event with DBT_DEVICEREMOVECOMPLETE'); |
| 991 |
//it might be a joystick, therefore |
| 992 |
Joysticks.InternalDisconnected; |
| 993 |
end;} |
| 994 |
{ Something unspecified has changed in the system devices configuration |
| 995 |
We don't need to handle this case because we are subscribed to more specific |
| 996 |
joystick connect/disconnect events through RegisterDeviceNotification. } |
| 997 |
//DBT_DEVNODES_CHANGED: WriteLnLog('Received a WM_DEVICECHANGE event with DBT_DEVNODES_CHANGED'); |
| 998 |
end; |
| 999 |
Exit(1); |
| 1000 |
end; |
| 1001 |
end; |
| 1002 |
|
| 1003 |
{ The DefWindowProcW may enter a modal loop in some cases, e.g. when |
| 1004 |
WM_NCLBUTTONDOWN initializes window resizing operation. |
| 1005 |
|
| 1006 |
This makes our normal message loop not working (although application |
| 1007 |
is working, but methods like ProcessMessage are not called in a loop anymore, |
| 1008 |
instead we "hang" in a DispatchMessage call in top-level ProcessMessage). |
| 1009 |
WinAPI will directly call WindowProc, creating a recursion. |
| 1010 |
See See http://stackoverflow.com/questions/3102074/win32-my-application-freezes-while-the-user-resizes-the-window |
| 1011 |
|
| 1012 |
So to keep receiving update/timer/redraws, we simply call |
| 1013 |
UpdateAndRenderEverything manually here. |
| 1014 |
|
| 1015 |
A simple solution was to just call it always when recursion here is detected. |
| 1016 |
But this seems unexpected to WinAPI in many situations, causing |
| 1017 |
|
| 1018 |
1. crashes, when this is done from some messages. |
| 1019 |
2. slowdown at initialization (castle-model-viewer main menu blinks for some |
| 1020 |
time, with "busy" cursor, before it becomes responsive). |
| 1021 |
|
| 1022 |
So the solution now is to activate it only for certain commands, |
| 1023 |
and moreover deactivate inside certain other commands. } |
| 1024 |
//Writeln('Got message ', uMsg, |
| 1025 |
// ', UpdatesFromWindowProc: Enable: ', EnableUpdatesFromWindowProc, |
| 1026 |
// ', Disable: ', DisableUpdatesFromWindowProc); |
| 1027 |
|
| 1028 |
if (EnableUpdatesFromWindowProc <> 0) and |
| 1029 |
(DisableUpdatesFromWindowProc = 0) and |
| 1030 |
(not Closed) then |
| 1031 |
Application.UpdateAndRenderEverything; |
| 1032 |
|
| 1033 |
DoEnableUpdatesFromWindowProc := uMsg = WM_NCLBUTTONDOWN; |
| 1034 |
DoDisableUpdatesFromWindowProc := |
| 1035 |
// user closes window by clicking on close button |
| 1036 |
((uMsg = WM_SYSCOMMAND) and (wParm = SC_CLOSE)) or |
| 1037 |
// we close the window by code |
| 1038 |
(uMsg = WM_NCACTIVATE) or |
| 1039 |
// we recreate the window as fullscreen |
| 1040 |
(uMsg = WM_IME_SETCONTEXT) or |
| 1041 |
// we recreate the window as windowed? |
| 1042 |
(uMsg = WM_ACTIVATE); |
| 1043 |
|
| 1044 |
if DoEnableUpdatesFromWindowProc then Inc(EnableUpdatesFromWindowProc); |
| 1045 |
if DoDisableUpdatesFromWindowProc then Inc(DisableUpdatesFromWindowProc); |
| 1046 |
try |
| 1047 |
{ Note: It is extremely important to use here DefWindowProcW. |
| 1048 |
If you use (ANSI, in FPC) DefWindowProc, then Windows will detect that |
| 1049 |
we want to use ANSI API (with 8-bit strings, not 16-bit) |
| 1050 |
which will make caption provided to CreateWindowExW expected to be encoded |
| 1051 |
as 8-bit (passing there a pointer to UTF-16 will be interpreted wrong, |
| 1052 |
as just 1 single letter). } |
| 1053 |
Result := DefWindowProcW(h_Wnd, uMsg, wParm, lParm); |
| 1054 |
finally |
| 1055 |
if DoEnableUpdatesFromWindowProc then Dec(EnableUpdatesFromWindowProc); |
| 1056 |
if DoDisableUpdatesFromWindowProc then Dec(DisableUpdatesFromWindowProc); |
| 1057 |
end; |
| 1058 |
end; |
| 1059 |
|
| 1060 |
function TCastleWindow.RedirectKeyDownToMenuClick: boolean; |
| 1061 |
begin |
| 1062 |
Result := true; |
| 1063 |
end; |
| 1064 |
|
| 1065 |
procedure TCastleWindow.BackendMenuFinalize; |
| 1066 |
var |
| 1067 |
Old_H_Menu: HMenu; |
| 1068 |
begin |
| 1069 |
Old_H_Menu := GetMenu(H_Wnd); |
| 1070 |
OSCheck( DestroyMenu(Old_H_Menu), 'DestroyMenu(Old_H_Menu)'); |
| 1071 |
{ for now, Handle of our menu items are always zero. |
| 1072 |
But do this for the future. } |
| 1073 |
MainMenu.ClearHandles; |
| 1074 |
end; |
| 1075 |
|
| 1076 |
procedure TCastleWindow.BackendMenuInitialize; |
| 1077 |
begin |
| 1078 |
OSCheck( SetMenu(H_Wnd, MakeWinapiMenu(MainMenu, true)), 'SetMenu'); |
| 1079 |
end; |
| 1080 |
|
| 1081 |
procedure TCastleWindow.MenuUpdateCaption(Entry: TMenuEntryWithCaption); |
| 1082 |
begin |
| 1083 |
MenuFinalize; |
| 1084 |
MenuInitialize; |
| 1085 |
end; |
| 1086 |
|
| 1087 |
procedure TCastleWindow.MenuUpdateEnabled(Entry: TMenuEntryWithCaption); |
| 1088 |
begin |
| 1089 |
MenuFinalize; |
| 1090 |
MenuInitialize; |
| 1091 |
end; |
| 1092 |
|
| 1093 |
procedure TCastleWindow.MenuUpdateChecked(Entry: TMenuItemChecked); |
| 1094 |
begin |
| 1095 |
MenuFinalize; |
| 1096 |
MenuInitialize; |
| 1097 |
end; |
| 1098 |
|
| 1099 |
function TCastleWindow.MenuUpdateCheckedFast: boolean; |
| 1100 |
begin |
| 1101 |
Result := false; |
| 1102 |
end; |
| 1103 |
|
| 1104 |
procedure TCastleWindow.MenuInsert(const Parent: TMenu; |
| 1105 |
const ParentPosition: Integer; const Entry: TMenuEntry); |
| 1106 |
begin |
| 1107 |
{ TODO: unoptimal } |
| 1108 |
MenuFinalize; |
| 1109 |
MenuInitialize; |
| 1110 |
end; |
| 1111 |
|
| 1112 |
procedure TCastleWindow.MenuDelete(const Parent: TMenu; |
| 1113 |
const ParentPosition: Integer; const Entry: TMenuEntry); |
| 1114 |
begin |
| 1115 |
{ TODO: unoptimal } |
| 1116 |
MenuFinalize; |
| 1117 |
MenuInitialize; |
| 1118 |
end; |
| 1119 |
|
| 1120 |
procedure TCastleWindow.OpenBackend; |
| 1121 |
|
| 1122 |
// Get initial MousePosition, even before the first mouse move/down event. |
| 1123 |
procedure GetInitialCursorPos(const ClientRect: TRect); |
| 1124 |
var |
| 1125 |
InitialCursorPos: Windows.TPoint; |
| 1126 |
begin |
| 1127 |
if GetCursorPos({$ifdef FPC}@{$endif}InitialCursorPos) then |
| 1128 |
begin |
| 1129 |
FMousePosition := LeftTopToCastle( |
| 1130 |
InitialCursorPos.X - ClientRect.Left, |
| 1131 |
InitialCursorPos.Y - ClientRect.Top); |
| 1132 |
end; |
| 1133 |
end; |
| 1134 |
|
| 1135 |
procedure InitializeDpi; |
| 1136 |
var |
| 1137 |
NewDpi: Single; |
| 1138 |
begin |
| 1139 |
NewDpi := GetDeviceCaps(h_Dc, LOGPIXELSX); |
| 1140 |
// Too verbose by default, UpdateUIScale will show it if UIScaling is usDpiScale. |
| 1141 |
// WritelnLog('WinAPI', 'Dots (pixels) per inch is %f (%f * default %f)', |
| 1142 |
// [NewDpi, NewDpi / DefaultDpi, DefaultDpi]); |
| 1143 |
Container.Dpi := NewDpi; |
| 1144 |
end; |
| 1145 |
|
| 1146 |
{ Request WinAPI to send DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE events |
| 1147 |
when new Joysticks have been connected to the system } |
| 1148 |
procedure RegisterForJoystickEvents; |
| 1149 |
var |
| 1150 |
BroadcastDeviceInterface: DEV_BROADCAST_DEVICEINTERFACE; |
| 1151 |
GUID_DEVINTERFACE_HID: TGuid; |
| 1152 |
DeviceNotification: Pointer; // HDEVNOTIFY; |
| 1153 |
begin |
| 1154 |
{ Construct GUID that corresponds to Joysticks/controllers devices |
| 1155 |
The values have been taken from SDL2 SDL_windowsjoystick.c } |
| 1156 |
GUID_DEVINTERFACE_HID.D1 := $4D1E55B2; |
| 1157 |
GUID_DEVINTERFACE_HID.D2 := $F16F; |
| 1158 |
GUID_DEVINTERFACE_HID.D3 := $11CF; |
| 1159 |
GUID_DEVINTERFACE_HID.D4[0] := $88; |
| 1160 |
GUID_DEVINTERFACE_HID.D4[1] := $CB; |
| 1161 |
GUID_DEVINTERFACE_HID.D4[2] := 0; |
| 1162 |
GUID_DEVINTERFACE_HID.D4[3] := $11; |
| 1163 |
GUID_DEVINTERFACE_HID.D4[4] := $11; |
| 1164 |
GUID_DEVINTERFACE_HID.D4[5] := 0; |
| 1165 |
GUID_DEVINTERFACE_HID.D4[6] := 0; |
| 1166 |
GUID_DEVINTERFACE_HID.D4[7] := $30; |
| 1167 |
|
| 1168 |
//construct BroadcastDeviceInterface record |
| 1169 |
FillChar(BroadcastDeviceInterface, SizeOf(BroadcastDeviceInterface), 0); |
| 1170 |
BroadcastDeviceInterface.dbcc_size := sizeof(DEV_BROADCAST_DEVICEINTERFACE); |
| 1171 |
BroadcastDeviceInterface.dbcc_devicetype := DBT_DEVTYP_DEVICEINTERFACE; |
| 1172 |
BroadcastDeviceInterface.dbcc_classguid := GUID_DEVINTERFACE_HID; |
| 1173 |
{ Ask WinAPI to send DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE events |
| 1174 |
for the requested GUID } |
| 1175 |
DeviceNotification := RegisterDeviceNotification(h_Wnd, @BroadcastDeviceInterface, DEVICE_NOTIFY_WINDOW_HANDLE); |
| 1176 |
if not Assigned(DeviceNotification) then |
| 1177 |
WriteLnWarning('Unable to RegisterDeviceNotification. Connecting/disconnecting joysticks will not be reported.'); |
| 1178 |
end; |
| 1179 |
|
| 1180 |
var |
| 1181 |
dwExStyle, dwStyle: dword; |
| 1182 |
WindowRect: TRect; |
| 1183 |
H_Menu: HMenu; |
| 1184 |
ClientRect: TRect; |
| 1185 |
begin |
| 1186 |
{ optionally hide mouse in FullScreem, |
| 1187 |
set dwStyle and dwExStyle for our window } |
| 1188 |
if FullScreen then |
| 1189 |
begin |
| 1190 |
WindowRect := Bounds(0, 0, Application.ScreenWidth, Application.ScreenHeight); |
| 1191 |
dwExStyle := WS_EX_APPWINDOW; |
| 1192 |
dwStyle := DWord(WS_POPUP); { glut daje tutaj tez WS_MAXIMIZE; bez znaczenia, jak sadze; } |
| 1193 |
end else |
| 1194 |
begin |
| 1195 |
WindowRect := Bounds(fleft, ftop, fwidth, fheight); |
| 1196 |
dwExStyle := WS_EX_APPWINDOW or WS_EX_WINDOWEDGE; |
| 1197 |
if ResizeAllowed = raAllowed then |
| 1198 |
begin |
| 1199 |
dwStyle := WS_OVERLAPPEDWINDOW; |
| 1200 |
end else |
| 1201 |
{ Just like WS_OVERLAPPEDWINDOW, but without flags that would allow to resize the window). } |
| 1202 |
dwStyle := WS_OVERLAPPEDWINDOW and not (WS_THICKFRAME or WS_MAXIMIZEBOX); |
| 1203 |
|
| 1204 |
{ Adjust WindowRect - so that ClientRect will hold the requested size and |
| 1205 |
position. Whole WindowRect will be a bit larger (depends on dwStyle, |
| 1206 |
dwExStyle). |
| 1207 |
|
| 1208 |
Note that when FullScreen = true there is no need to do this - the intention |
| 1209 |
of FullScreen is that whole window (with menu) covers whole screen and |
| 1210 |
window has no frame. So WindowRect should be (0, 0, Application.ScreenWidth, |
| 1211 |
Application.ScreenHeight) and this is done set. I could write it like that: |
| 1212 |
AdjustWindowRectEx(WindowRect, dwStyle, |
| 1213 |
(not FullScreen) and (MainMenu <> nil), dwExStyle); |
| 1214 |
but it's more clear to just omit AdjustWindowRectEx call when FullScreen. |
| 1215 |
|
| 1216 |
Note the (documented) WinAPI bug here: AdjustWindowRectEx cannot take |
| 1217 |
into account if the menu bar wraps (in two or more rows). This wrapping |
| 1218 |
happens, depending on menu contents and user fonts. But AdjustWindowRectEx |
| 1219 |
has to way to account for it: it only knows if the menu exists at all. |
| 1220 |
Documented in MSDN explicitly: "The AdjustWindowRectEx function does not add |
| 1221 |
extra space when a menu bar wraps to two or more rows.", with no workaround |
| 1222 |
pointed... |
| 1223 |
|
| 1224 |
This means that actual OpenGL area size may be different than |
| 1225 |
requested (OnResize will report it corectly, eventually lying, honoring |
| 1226 |
ResizeAllowed properrty). Happened e.g. when castle-image-viewer allowed minimal |
| 1227 |
window size = 200, and default welcome image had 256x256 pixels. |
| 1228 |
When you opened castle-image-viewer with no params in directory with no images, |
| 1229 |
then OpenGL area of size 256x256 was requested, which was so narrow that |
| 1230 |
menu bar wrapped. Which made OpenGL area not tall enough for 256 pixels, |
| 1231 |
and castle-image-viewer had to add a vertical scrollbar to display welcome image. |
| 1232 |
} |
| 1233 |
AdjustWindowRectEx(WindowRect, dwStyle, |
| 1234 |
(MainMenu <> nil) and MainMenuVisible, dwExStyle); |
| 1235 |
end; |
| 1236 |
dwStyle := dwStyle or WS_CLIPSIBLINGS or WS_CLIPCHILDREN; |
| 1237 |
|
| 1238 |
{ calculate H_Menu } |
| 1239 |
if (MainMenu <> nil) and MainMenuVisible then |
| 1240 |
H_Menu := MakeWinapiMenu(MainMenu, true) |
| 1241 |
else |
| 1242 |
H_Menu := 0; |
| 1243 |
|
| 1244 |
{ main point : create the window } |
| 1245 |
H_wnd := CreateWindowExW(dwExStyle, |
| 1246 |
PWideChar(Application.WndClassName), |
| 1247 |
PWideChar(StringToUtf16(GetWholeCaption)), |
| 1248 |
dwStyle, |
| 1249 |
windowRect.left, windowRect.top, |
| 1250 |
windowRect.right-windowRect.left, windowRect.Bottom-windowRect.top, |
| 1251 |
0 { no parent window }, H_Menu, hInstance, |
| 1252 |
nil { don't pass anything to WM_CREATE } ); |
| 1253 |
|
| 1254 |
Check(h_Wnd <> 0, 'Creating window (CreateWindowExW) failed'); |
| 1255 |
|
| 1256 |
{ calculate correct Left and Top, required e.g. by SetCursorPos } |
| 1257 |
if FullScreen then |
| 1258 |
begin |
| 1259 |
FLeft := 0; |
| 1260 |
FTop := 0; |
| 1261 |
end; |
| 1262 |
{ See WM_MOVE handling comments why this is needed to make Top correct. } |
| 1263 |
if FullScreen and (MainMenu <> nil) and MainMenuVisible then |
| 1264 |
FTop := FTop + GetSystemMetrics(SM_CYMENU); |
| 1265 |
|
| 1266 |
SetWindowLongPtr(h_Wnd, GWL_USERDATA, PtrUInt(Self)); |
| 1267 |
|
| 1268 |
{ get h_DC and set pixel format } |
| 1269 |
|
| 1270 |
h_Dc := GetDC(h_Wnd); |
| 1271 |
Check ( h_Dc <> 0, 'GetDC failed'); |
| 1272 |
|
| 1273 |
ContextCreate(h_Wnd); |
| 1274 |
|
| 1275 |
MakeCurrent; |
| 1276 |
|
| 1277 |
{ robimy OpenWindowsAdd PRZED ShowWindow bo ShowWindow wywoluje WinProc |
| 1278 |
z message'm kazacym nam sie odmalowac. Wiec zeby przetworzyc tego messaga |
| 1279 |
(ktory powoduje po prostu Invalidate) nasze okienko musi byc |
| 1280 |
zarejestrowane w Application.OpenWindows. Dlaczego nie zrobic po prostu Invalidate ? |
| 1281 |
Tak jest porzadniej, no i w ten sposob wiem DLACZEGO to dziala, a nie tylko |
| 1282 |
ze "dziala kiedy wywolamy Invalidate". } |
| 1283 |
Application.OpenWindowsAdd(Self); |
| 1284 |
|
| 1285 |
if Visible then |
| 1286 |
begin |
| 1287 |
ShowWindow(h_Wnd, SW_SHOW); |
| 1288 |
SetForegroundWindow(h_Wnd); |
| 1289 |
SetFocus(h_Wnd); |
| 1290 |
end; |
| 1291 |
|
| 1292 |
OSCheck(GetClientRect(h_Wnd, ClientRect), 'GetClientRect'); |
| 1293 |
|
| 1294 |
{ Windows does not send us WM_SIZE messages when FullScreen (that's probably |
| 1295 |
caused by our special dwStyle and dwStyleEx for FullScreen, probably |
| 1296 |
by the lack of WS_OVERLAPPED in dwStyle). So we should simulate it here, |
| 1297 |
because we actually "manualy" changed the size (to screen size) by applying FullScreen. |
| 1298 |
Also, MainMenu may take some space, so our size is not even precisely |
| 1299 |
Application.ScreenWidth / Application.ScreenHeight. |
| 1300 |
So we check client rect size explicitly, with GetClientRect, and call DoResize |
| 1301 |
(we don't care here about ResizeAllowed, DoResize will take care of averything). } |
| 1302 |
if FullScreen then |
| 1303 |
begin |
| 1304 |
DoResize(ClientRect.Right - ClientRect.Left, |
| 1305 |
ClientRect.Bottom - ClientRect.Top, false); |
| 1306 |
end; |
| 1307 |
|
| 1308 |
GetInitialCursorPos(ClientRect); |
| 1309 |
InitializeDpi; |
| 1310 |
|
| 1311 |
RegisterForJoystickEvents; |
| 1312 |
end; |
| 1313 |
|
| 1314 |
procedure TCastleWindow.SetCursor(const Value: TMouseCursor); |
| 1315 |
var |
| 1316 |
Point: Windows.TPoint; |
| 1317 |
begin |
| 1318 |
if FCursor <> Value then |
| 1319 |
begin |
| 1320 |
FCursor := Value; |
| 1321 |
|
| 1322 |
{ We reinstall the cursor on each WM_SETCURSOR call, that's the proper |
| 1323 |
place to do it. Right now, we want to force this reinstallation, |
| 1324 |
since FCursor changed (normally WM_SETCURSOR will be called only when |
| 1325 |
mouse will be moved). So we call PostMessage, if current position is |
| 1326 |
within the window. |
| 1327 |
|
| 1328 |
This is similar to what glut for Win32 does in glutSetCursor. } |
| 1329 |
GetCursorPos({$ifdef FPC}@{$endif}Point); |
| 1330 |
if h_Wnd = WindowFromPoint(Point) then |
| 1331 |
PostMessage(h_Wnd, WM_SETCURSOR, h_Wnd, 0 { not important}); |
| 1332 |
end; |
| 1333 |
end; |
| 1334 |
|
| 1335 |
procedure TCastleWindow.SetMousePosition(const Value: TVector2); |
| 1336 |
|
| 1337 |
{ Perform similar function as WinAPI SetCursorPos (set cursor position, |
| 1338 |
given absolute screen coordinates), but using SendInput WinAPI call. |
| 1339 |
This is more reliable, which can be observed when using MouseLook. |
| 1340 |
|
| 1341 |
Testcase: dragging_test, if we would use SetCursorPos then: |
| 1342 |
|
| 1343 |
- TCastleContainer.MouseLookDelta doesn't set FMouseLookWaitingForMiddle to true: |
| 1344 |
then we have problems due to occasional rect jump, when moving mouse slowly |
| 1345 |
(because we need to set FMouseLookWaitingForMiddle to true!). |
| 1346 |
|
| 1347 |
- TCastleContainer.MouseLookDelta sets FMouseLookWaitingForMiddle to true: |
| 1348 |
then we have occasional "blocks" when moving mouse very fast |
| 1349 |
(like from edge to edge of the screen). Experimenting, we just |
| 1350 |
cannot reliably capture "the end of FMouseLookWaitingForMiddle", |
| 1351 |
no matter how small/large margin in ValidArea we use. |
| 1352 |
|
| 1353 |
Info about SendInput: |
| 1354 |
|
| 1355 |
- https://social.msdn.microsoft.com/Forums/sqlserver/en-US/72d2c30e-0689-4c80-bf02-dcbc33b7b7de/problems-with-getcursorpos-and-setcursorpos-when-running-directx11-on-windows-10 |
| 1356 |
https://docs.microsoft.com/pl-pl/windows/win32/api/winuser/ns-winuser-mouseinput |
| 1357 |
|
| 1358 |
- Possibly related: |
| 1359 |
https://github.com/gottebp/windows10-setcursorpos-bug-demonstration |
| 1360 |
http://www.cplusplus.com/forum/general/101920/ |
| 1361 |
} |
| 1362 |
procedure SetCursorPosBySendInput(const X, Y: Integer); |
| 1363 |
var |
| 1364 |
I: TInput; |
| 1365 |
begin |
| 1366 |
FillChar(I, SizeOf(I), 0); |
| 1367 |
I.InputType := INPUT_MOUSE; |
| 1368 |
I.Mi.Flags := MOUSEEVENTF_MOVE or MOUSEEVENTF_ABSOLUTE; |
| 1369 |
I.Mi.Dx := (X * 65535) div Application.ScreenWidth; |
| 1370 |
I.Mi.Dy := (Y * 65535) div Application.ScreenHeight; |
| 1371 |
if SendInput(1, @I, SizeOf(I)) <> 1 then |
| 1372 |
WritelnWarning('Could not set mouse position with SendInput, WinAPI error'); |
| 1373 |
end; |
| 1374 |
|
| 1375 |
var |
| 1376 |
P: TVector2Integer; |
| 1377 |
begin |
| 1378 |
if not Closed then |
| 1379 |
begin |
| 1380 |
|
| 1381 |
{ Do not set Mouse.CursorPos to the same value, to make sure we don't cause |
| 1382 |
unnecessary OnMotion on some systems while actual MousePosition didn't change. } |
| 1383 |
if TVector2.PerfectlyEquals(Value, FMousePosition) then Exit; |
| 1384 |
|
| 1385 |
P := CastleToLeftTopInt(Value); |
| 1386 |
SetCursorPosBySendInput(Left + P.X, Top + P.Y); |
| 1387 |
end; |
| 1388 |
end; |
| 1389 |
|
| 1390 |
procedure TCastleWindow.CloseBackend; |
| 1391 |
begin |
| 1392 |
InCloseBackend := true; |
| 1393 |
try |
| 1394 |
ContextDestroy; |
| 1395 |
|
| 1396 |
if (h_Dc <> 0) and (ReleaseDC(h_Wnd, h_Dc) = 0) then |
| 1397 |
WritelnWarning('WinAPI', 'Releasing device context (ReleaseDC) failed.'); |
| 1398 |
h_Dc := 0; |
| 1399 |
if (h_Wnd <> 0) and (not DestroyWindow(h_Wnd))then |
| 1400 |
WritelnWarning('WinAPI', 'Destroying window (DestroyWindow) failed.'); |
| 1401 |
h_Wnd := 0; |
| 1402 |
finally InCloseBackend := false; end; |
| 1403 |
end; |
| 1404 |
|
| 1405 |
procedure TCastleWindow.SetCaption(const Part: TCaptionPart; const Value: String); |
| 1406 |
begin |
| 1407 |
FCaption[Part] := Value; |
| 1408 |
if h_Wnd <> 0 then |
| 1409 |
begin |
| 1410 |
SetWindowTextW(h_Wnd, PWideChar(StringToUtf16(GetWholeCaption))); |
| 1411 |
end; |
| 1412 |
end; |
| 1413 |
|
| 1414 |
procedure TCastleWindow.CreateBackend; |
| 1415 |
begin |
| 1416 |
end; |
| 1417 |
|
| 1418 |
function TCastleWindow.BackendFileDialog(const Title: String; var FileName: String; |
| 1419 |
OpenDialog: boolean; FileFilters: TFileFilterList): boolean; |
| 1420 |
|
| 1421 |
{ Make path absolute. Same as ExpandFileName, but knows that |
| 1422 |
FilePath contains only a path and will always work as it should. |
| 1423 |
(Delphi's and FPC's do not guarantee correct ExpandFileName result |
| 1424 |
for paths ended with PathDelim.) |
| 1425 |
|
| 1426 |
FilePath may, but doesn't have to, end with PathDelim. |
| 1427 |
Result will always end with PathDelim. |
| 1428 |
|
| 1429 |
Note: '' is treated as current dir (as it always should be, because |
| 1430 |
ExtractFilePath('file') = '' and 'file' is in current dir). } |
| 1431 |
function ExpandFilePath(const FilePath: String): String; |
| 1432 |
begin |
| 1433 |
if FilePath = '' then |
| 1434 |
Result := InclPathDelim(GetCurrentDir) else |
| 1435 |
Result := ExtractFilePath( ExpandFileName(InclPathDelim(FilePath) + |
| 1436 |
'dummy_file_name' )); |
| 1437 |
|
| 1438 |
{ note : doing here something like |
| 1439 |
ExtractFilePath( ExpandFileName(ExclPathDelim(FilePath)) ) |
| 1440 |
(i.e., pretending that FilePath points to a file, not directory) |
| 1441 |
would not be safe, because we don't know what ExpandFileName |
| 1442 |
will do with 'c:' } |
| 1443 |
end; |
| 1444 |
|
| 1445 |
{ Prepare string with encoded filter names and patterns, as specified |
| 1446 |
in WinAPI OPENFILENAME reference. |
| 1447 |
|
| 1448 |
Note that Windows encoding of OpenFileName has limitations here, since all filters |
| 1449 |
are passed in a string: pattern cannot contain ';', and WinAPI reference |
| 1450 |
says that it also cannot contain a space. } |
| 1451 |
function MakeStrFilter(FileFilters: TFileFilterList): String; |
| 1452 |
var |
| 1453 |
I, J: Integer; |
| 1454 |
Filter: TFileFilter; |
| 1455 |
begin |
| 1456 |
Result := ''; |
| 1457 |
for I := 0 to FileFilters.Count - 1 do |
| 1458 |
begin |
| 1459 |
Filter := FileFilters[I]; |
| 1460 |
|
| 1461 |
Result := Result + Filter.Name + #0; |
| 1462 |
|
| 1463 |
for J := 0 to Filter.Patterns.Count - 1 do |
| 1464 |
begin |
| 1465 |
if J <> 0 then Result := Result + ';'; |
| 1466 |
Result := Result + Filter.Patterns[J]; |
| 1467 |
end; |
| 1468 |
|
| 1469 |
Result := Result + #0; |
| 1470 |
end; |
| 1471 |
|
| 1472 |
Result := Result + #0; |
| 1473 |
end; |
| 1474 |
|
| 1475 |
function SearchFirstPatternWithExtension(const Ext: String): Integer; |
| 1476 |
var |
| 1477 |
I: Integer; |
| 1478 |
begin |
| 1479 |
Result := -1; |
| 1480 |
|
| 1481 |
{ Look only at extensions '.' + something non-empty. |
| 1482 |
Don't even bother looking at special extensions '' and '.', |
| 1483 |
or things wihout a leading '.', they will not |
| 1484 |
work with our trick anyway, see comments where I use |
| 1485 |
SearchFirstPatternWithExtension. } |
| 1486 |
if (Length(Ext) >= 2) and (Ext[1] = '.') then |
| 1487 |
begin |
| 1488 |
for I := 0 to FileFilters.Count - 1 do |
| 1489 |
if SameText(FileFilters[I].Patterns[0], '*' + Ext) then |
| 1490 |
begin |
| 1491 |
if (Result = -1) or |
| 1492 |
{ If we're lucky enough to have more than one match (this may happen |
| 1493 |
e.g. for our "all images" filters that list the sum of other filters) |
| 1494 |
then choose more specific (with less patterns) filter. } |
| 1495 |
(FileFilters[I].Patterns.Count < FileFilters[Result].Patterns.Count) then |
| 1496 |
Result := I; |
| 1497 |
end; |
| 1498 |
end; |
| 1499 |
end; |
| 1500 |
|
| 1501 |
var |
| 1502 |
Struct: TOpenFileNameW; |
| 1503 |
FileNameBuffer: array [0..6000] of widechar; |
| 1504 |
{$ifndef FPC}FileNameString: String;{$endif} |
| 1505 |
FilePath: String; |
| 1506 |
Mode: TGLModeFrozenScreen; |
| 1507 |
CurrentFileNameExt: String; |
| 1508 |
CurrentFormatIndex: Integer; |
| 1509 |
begin |
| 1510 |
FillChar(Struct, SizeOf(Struct), 0); |
| 1511 |
Struct.lStructSize := SizeOf(Struct); |
| 1512 |
Struct.hwndOwner := H_Wnd; |
| 1513 |
|
| 1514 |
{$ifdef FPC} |
| 1515 |
FileNameBuffer := ExtractFileName(FileName); |
| 1516 |
{$else} |
| 1517 |
StrPLCopy(FileNameBuffer, ExtractFileName(FileName), High(FileNameBuffer)); |
| 1518 |
{$endif} |
| 1519 |
Struct.lpstrFile := @FileNameBuffer; |
| 1520 |
|
| 1521 |
{ As for FileNameBuffer size: |
| 1522 |
we just hope that FileNameBuffer will be ALWAYS sufficiently large. |
| 1523 |
This seems to be the only reasonable way to deal with this. |
| 1524 |
Checking CommDlgExtendedError for BUFFER_TOO_SMALL and then decoding |
| 1525 |
required length from lpstrFile is pretty pointless (after all, you will know |
| 1526 |
the required length, but then how can you ask GetXxxFileName to return again |
| 1527 |
the same filename, without displaying dialog once again?). } |
| 1528 |
Struct.nMaxFile := SizeOf(FileNameBuffer); |
| 1529 |
|
| 1530 |
{ We're storing result of ExtractFilePath in FilePath, because pointer |
| 1531 |
Struct.lpstrInitialDir must be valid when I call GetOpenFileName } |
| 1532 |
FilePath := ExtractFilePath(FileName); |
| 1533 |
{ In WinAPI help they say that when lpstrInitialDir = nil it uses current dir. |
| 1534 |
But that's not true, it uses some other dir (last dir of open dialog box ?). |
| 1535 |
So I have to fix this here, correcting FilePath from '' to GetCurrentDir. |
| 1536 |
In fact, it seems that GetOpen/SaveFileName can't understand relative paths, |
| 1537 |
in the form 'subdir1/file' or './subdir1/file' (maybe it does not understand |
| 1538 |
that those paths are relative to current dir ??), so I'm always expanding paths. } |
| 1539 |
FilePath := ExpandFilePath(FilePath); |
| 1540 |
Struct.lpstrInitialDir := PWideCharOrNil(StringToUtf16(FilePath)); |
| 1541 |
|
| 1542 |
{ tests: |
| 1543 |
InfoWrite('current dir : "' + GetCurrentDir + '"'); |
| 1544 |
InfoWrite('dialog box InitialDir : "' + FilePath + '"');} |
| 1545 |
|
| 1546 |
Struct.lpstrTitle := PWideCharOrNil(StringToUtf16(Title)); |
| 1547 |
Struct.Flags := OFN_NOCHANGEDIR or OFN_HIDEREADONLY; |
| 1548 |
if OpenDialog then |
| 1549 |
Struct.Flags := Struct.Flags or OFN_FILEMUSTEXIST else |
| 1550 |
Struct.Flags := Struct.Flags or OFN_OVERWRITEPROMPT or OFN_PATHMUSTEXIST; |
| 1551 |
|
| 1552 |
if FileFilters <> nil then |
| 1553 |
begin |
| 1554 |
Struct.lpstrFilter := PWideCharOrNil(StringToUtf16(MakeStrFilter(FileFilters))); |
| 1555 |
Struct.nFilterIndex := FileFilters.DefaultFilter + 1; |
| 1556 |
|
| 1557 |
if not OpenDialog then |
| 1558 |
begin |
| 1559 |
{ Note that GetSaveFileName is brain-dead and |
| 1560 |
works really correct only if you pass filename without |
| 1561 |
extension, and user doesn't type any extension. Then GetSaveFileName appends |
| 1562 |
to the output filename the extension from current filter, or lpstrDefExt |
| 1563 |
if current filter doesn't contain any extension (e.g. if current filter has '*' |
| 1564 |
as all files). And then it works Ok. |
| 1565 |
|
| 1566 |
It fails tragically if user types some extension. Basically, GetSaveFileName |
| 1567 |
will not change filename extension then, but standard behavior expects that you |
| 1568 |
should save the file with format chosen in filters, that is "save as type" label. |
| 1569 |
So you probably save a file with data format and filename extension totally |
| 1570 |
uncorelated. |
| 1571 |
|
| 1572 |
Yes, this stupidity actually happens --- e.g. in M$ Outlook (it's made my M$, |
| 1573 |
so it's supposed to reflect some "standard" usage, right?) saving the email |
| 1574 |
(there are two filters, one is Email (*.eml) and the other HTML (*.htm, *.html)): |
| 1575 |
if you type a.html, and press Enter (leaving data format as Email)... |
| 1576 |
the data format is Email but it's saved to filename named a.html. |
| 1577 |
|
| 1578 |
This means that if user types an extension or application proposes an extension |
| 1579 |
then the bad things happen. |
| 1580 |
(Like FireFox: it proposes filename with extension a.htm, so when user changes |
| 1581 |
data format to "text file (*.txt)" the file gets saved to a.htm with text (not direct |
| 1582 |
HTML tags) format)) . Program must (by standard) |
| 1583 |
use data format chosen in the dialog and filename as given --- so they are totally |
| 1584 |
unrelated. |
| 1585 |
|
| 1586 |
This also means that it's difficult for user to sensibly save file with extension |
| 1587 |
that is not the 1st pattern of some filter. GetSaveFileName appends only the 1st pattern |
| 1588 |
of current filter, and if you just type the extension then you probably forget to |
| 1589 |
change combo box "save as type". |
| 1590 |
|
| 1591 |
What can I do? I want to avoid WinAPI stupidity, and I do not want to return |
| 1592 |
a separate parameter specifying which filter was chosen (to keep interface simple), |
| 1593 |
so I want the filename to be related with data format. |
| 1594 |
I can do one thing: if there exists a filter |
| 1595 |
with current filename extension as it's 1st pattern then I can remove it from |
| 1596 |
filename and set this filter as default. So in typical case things will work Ok, |
| 1597 |
as much as they can, assumig that one of your filters matches your current extension. |
| 1598 |
|
| 1599 |
In other cases, "save as type" of my |
| 1600 |
WinAPI dialogs will just be useless, but there's nothing I can do: I have to |
| 1601 |
keep filename with extension in lpstrFile then, and GetSaveFileName will |
| 1602 |
not correlate this with format chosen by combo box "save as type". |
| 1603 |
So I will simply ignore combo box "save as type" (while Windows standard says |
| 1604 |
to ignore extension then; either way, both exits are wrong, since user can very |
| 1605 |
easily save a file with data format and extension not related). |
| 1606 |
} |
| 1607 |
CurrentFileNameExt := ExtractFileExt(Utf16ToString(FileNameBuffer)); |
| 1608 |
CurrentFormatIndex := SearchFirstPatternWithExtension(CurrentFileNameExt); |
| 1609 |
if CurrentFormatIndex <> -1 then |
| 1610 |
begin |
| 1611 |
{ We can use workaround described above. } |
| 1612 |
{$ifdef FPC} |
| 1613 |
FileNameBuffer := DeleteFileExt(FileNameBuffer); |
| 1614 |
{$else} |
| 1615 |
if StrLen(FileNameBuffer) > 0 then |
| 1616 |
SetString(FileNameString, PWideChar(@FileNameBuffer[0]), StrLen(FileNameBuffer)) |
| 1617 |
else |
| 1618 |
FileNameString := ''; |
| 1619 |
|
| 1620 |
FileNameString := DeleteFileExt(FileNameString); |
| 1621 |
StrPLCopy(FileNameBuffer, ExtractFileName(FileNameString), High(FileNameBuffer)); |
| 1622 |
{$endif} |
| 1623 |
Struct.nFilterIndex := CurrentFormatIndex + 1; |
| 1624 |
|
| 1625 |
{ If user selects something like "all files" then also append this extension. |
| 1626 |
|
| 1627 |
I pass here CurrentFileNameExt without leading dot (since |
| 1628 |
SearchFirstPatternWithExtension returned something <> -1, I know there's |
| 1629 |
a leading dot). |
| 1630 |
|
| 1631 |
Note: only first three characters of lpstrDefExt extension are taken |
| 1632 |
into account, according to WinAPI reference. (and WTF can I do about it?) |
| 1633 |
|
| 1634 |
Also note that unregistered extensions are treated somewhat differently. |
| 1635 |
Unfortunately, lpstrDefExt will append then, instead of leaving filename alone. } |
| 1636 |
Struct.lpstrDefExt := PWideCharOrNil(StringToUtf16(SEnding(CurrentFileNameExt, 2))); |
| 1637 |
end; |
| 1638 |
end; |
| 1639 |
end; |
| 1640 |
|
| 1641 |
Mode := TGLModeFrozenScreen.Create(Self); |
| 1642 |
try |
| 1643 |
if OpenDialog then |
| 1644 |
Result := GetOpenFileNameW({$ifdef FPC}@{$endif}Struct) else |
| 1645 |
Result := GetSaveFileNameW({$ifdef FPC}@{$endif}Struct); |
| 1646 |
finally Mode.Free end; |
| 1647 |
|
| 1648 |
if Result then |
| 1649 |
FileName := Utf16ToString(FileNameBuffer) else |
| 1650 |
begin |
| 1651 |
if CommDlgExtendedError <> 0 then |
| 1652 |
raise Exception.CreateFmt('GetOpen/SaveFileName failed with error %d', |
| 1653 |
[CommDlgExtendedError]); |
| 1654 |
end; |
| 1655 |
end; |
| 1656 |
|
| 1657 |
function TCastleWindow.ColorDialog(var Color: TCastleColor): Boolean; |
| 1658 |
|
| 1659 |
function Vector3ToColorRef(const Value: TVector3): TColorRef; |
| 1660 |
begin |
| 1661 |
Result := Windows.RGB(Clamped(Round(Value.X*High(Byte)), 0, High(Byte)), |
| 1662 |
Clamped(Round(Value.Y*High(Byte)), 0, High(Byte)), |
| 1663 |
Clamped(Round(Value.Z*High(Byte)), 0, High(Byte)) ); |
| 1664 |
end; |
| 1665 |
|
| 1666 |
function ColorRefToVector3(const Value: TColorRef): TVector3; |
| 1667 |
begin |
| 1668 |
Result.X := GetRValue(Value)/High(Byte); |
| 1669 |
Result.Y := GetGValue(Value)/High(Byte); |
| 1670 |
Result.Z := GetBValue(Value)/High(Byte); |
| 1671 |
end; |
| 1672 |
|
| 1673 |
var |
| 1674 |
Struct: TChooseColor; |
| 1675 |
CustomColors: array [0..15] of TColorRef; |
| 1676 |
Mode: TGLModeFrozenScreen; |
| 1677 |
begin |
| 1678 |
{ init CustomColors to all blacks; TODO: I should use a static table for this |
| 1679 |
(and put a comment in CastleWindow to say that custom colors are preserved in win dialog) } |
| 1680 |
FillChar(CustomColors, SizeOf(CustomColors), 0); |
| 1681 |
|
| 1682 |
{ init Struct } |
| 1683 |
FillChar(Struct, SizeOf(Struct), 0); |
| 1684 |
Struct.lStructSize := SizeOf(Struct); |
| 1685 |
Struct.hwndOwner := H_Wnd; |
| 1686 |
Struct.rgbResult := Vector3ToColorRef(Color.RGB); |
| 1687 |
Struct.lpCustColors := @CustomColors; |
| 1688 |
{ Give CC_FULLOPEN since this is intended to give user a free choice from RGB |
| 1689 |
colors. So we suggest user to choose any RGB color freely, instead of using |
| 1690 |
only the predefined ones. } |
| 1691 |
Struct.Flags := CC_FULLOPEN or CC_RGBINIT; |
| 1692 |
|
| 1693 |
Mode := TGLModeFrozenScreen.Create(Self); |
| 1694 |
try |
| 1695 |
Result := ChooseColor({$ifdef FPC}@{$endif}Struct); |
| 1696 |
finally Mode.Free end; |
| 1697 |
|
| 1698 |
if Result then |
| 1699 |
Color := Vector4(ColorRefToVector3(Struct.rgbResult), Color.W); |
| 1700 |
end; |
| 1701 |
|
| 1702 |
(* |
| 1703 |
const |
| 1704 |
MessageTypeToWin: array [TWindowMessageType] of UInt32 = |
| 1705 |
( MB_ICONINFORMATION, |
| 1706 |
MB_ICONWARNING, |
| 1707 |
MB_ICONQUESTION, |
| 1708 |
MB_ICONERROR, |
| 1709 |
0 ); |
| 1710 |
|
| 1711 |
MessageTypeToCaption: array [TWindowMessageType] of string = |
| 1712 |
( 'Information', |
| 1713 |
'Warning', |
| 1714 |
'Question', |
| 1715 |
'Error', |
| 1716 |
'Information'); |
| 1717 |
*) |
| 1718 |
|
| 1719 |
procedure TCastleWindow.MessageOK(const S: String; const MessageType: TWindowMessageType); |
| 1720 |
begin |
| 1721 |
CastleMessages.MessageOK(Self, S); |
| 1722 |
|
| 1723 |
// WinAPI MessageBox is unreliable to display over a fullscreen window. |
| 1724 |
// See also e.g. https://gamedev.stackexchange.com/questions/892/display-a-message-box-over-a-full-screen-directx-application |
| 1725 |
(* |
| 1726 |
MessageBox(H_Wnd, PChar(S), |
| 1727 |
{ Always pass meaningfull caption. Passing nil here causes Windows to |
| 1728 |
always display localized "Error" on caption, which looks nonsensible |
| 1729 |
on boxes with warnings or questions. } |
| 1730 |
PChar(MessageTypeToCaption[MessageType]), |
| 1731 |
MB_OK or MessageTypeToWin[MessageType] or |
| 1732 |
{ MB_APPLMODAL is actually the default. MB_TASKMODAL would also be suitable |
| 1733 |
probably, as we always pass non-nil H_Wnd. } |
| 1734 |
MB_APPLMODAL); |
| 1735 |
*) |
| 1736 |
end; |
| 1737 |
|
| 1738 |
function TCastleWindow.MessageYesNo(const S: String; |
| 1739 |
const MessageType: TWindowMessageType): boolean; |
| 1740 |
begin |
| 1741 |
Result := CastleMessages.MessageYesNo(Self, S); |
| 1742 |
|
| 1743 |
// WinAPI MessageBox is unreliable to display over a fullscreen window. |
| 1744 |
// See also e.g. https://gamedev.stackexchange.com/questions/892/display-a-message-box-over-a-full-screen-directx-application |
| 1745 |
(* |
| 1746 |
Result := MessageBox(H_Wnd, PChar(S), |
| 1747 |
PChar(MessageTypeToCaption[MessageType]), |
| 1748 |
MB_YESNO or MessageTypeToWin[MessageType] or |
| 1749 |
{ MB_APPLMODAL is actually the default. MB_TASKMODAL would also be suitable |
| 1750 |
probably, as we always pass non-nil H_Wnd. } |
| 1751 |
MB_APPLMODAL) = IDYES; |
| 1752 |
*) |
| 1753 |
end; |
| 1754 |
|
| 1755 |
procedure TCastleWindow.UpdateFullScreenBackend; |
| 1756 |
begin |
| 1757 |
SimpleUpdateFullScreenBackend; |
| 1758 |
end; |
| 1759 |
|
| 1760 |
procedure TCastleWindow.BackendInsideUpdate; |
| 1761 |
begin |
| 1762 |
end; |
| 1763 |
|
| 1764 |
{ TWinApiClipboard ----------------------------------------------------------- } |
| 1765 |
|
| 1766 |
{ Clipboard operations using WinAPI based on: |
| 1767 |
- http://msdn.microsoft.com/en-us/library/windows/desktop/ms649016%28v=vs.85%29.aspx |
| 1768 |
- LCL implementation: TWin32WidgetSet.ClipboardGetOwnerShip (set) |
| 1769 |
and ClipboardGetData (get) in lcl/interfaces/win32/win32winapi.inc |
| 1770 |
} |
| 1771 |
|
| 1772 |
type |
| 1773 |
TWinApiClipboard = class(TCastleClipboard) |
| 1774 |
protected |
| 1775 |
const |
| 1776 |
{ We use CF_UNICODETEXT (16-bit Unicode) with both FPC and Delphi. |
| 1777 |
On Delphi, it matches default String type. |
| 1778 |
On FPC, it matches UTF-16 UnicodeString type. |
| 1779 |
|
| 1780 |
We never use CF_TEXT (8-bit ANSI), even with FPC, as it has ANSI encoding |
| 1781 |
while we want UTF-8. } |
| 1782 |
StringClipboardFormat = CF_UNICODETEXT; |
| 1783 |
type |
| 1784 |
{ Matching above CF_UNICODETEXT, we use 16-bit UnicodeString and |
| 1785 |
matching UnicodeChar to deal with clipboard on both FPC and Delphi. |
| 1786 |
|
| 1787 |
Note: We don't use WideString, UnicodeString is "ref-counted 16-bit String |
| 1788 |
equivalent to 8-bit AnsiString", |
| 1789 |
https://stackoverflow.com/questions/374446/is-widestring-identical-to-string-in-delphi-2009 |
| 1790 |
https://docwiki.embarcadero.com/RADStudio/Sydney/en/String_Types_(Delphi) |
| 1791 |
https://forum.lazarus.freepascal.org/index.php?topic=22464.0 } |
| 1792 |
TClipboardChar = WideChar; // UnicodeChar is only defined by FPC |
| 1793 |
TClipboardString = UnicodeString; |
| 1794 |
function GetAsText: String; override; |
| 1795 |
procedure SetAsText(const Value: String); override; |
| 1796 |
end; |
| 1797 |
|
| 1798 |
function TWinApiClipboard.GetAsText: String; |
| 1799 |
var |
| 1800 |
DataHandle: Windows.HGLOBAL; |
| 1801 |
Data: Pointer; |
| 1802 |
ByteSize, CharSize: Integer; |
| 1803 |
ResultUnicode: TClipboardString; |
| 1804 |
begin |
| 1805 |
Result := ''; |
| 1806 |
|
| 1807 |
if IsClipboardFormatAvailable(StringClipboardFormat) then |
| 1808 |
begin |
| 1809 |
if not Windows.OpenClipboard(Windows.HWND(nil)) then Exit; |
| 1810 |
try |
| 1811 |
DataHandle := Windows.GetClipboardData(StringClipboardFormat); |
| 1812 |
if DataHandle = 0 then Exit; |
| 1813 |
|
| 1814 |
ByteSize := Windows.GlobalSize(DataHandle); |
| 1815 |
CharSize := ByteSize div SizeOf(TClipboardChar); |
| 1816 |
if ByteSize mod SizeOf(TClipboardChar) <> 0 then |
| 1817 |
WritelnWarning('WinAPI', 'Clipboard data size is not a multiple of SizeOf(TClipboardChar)'); |
| 1818 |
|
| 1819 |
if CharSize > 1 then |
| 1820 |
begin |
| 1821 |
Dec(CharSize); // do not copy trailing #0 |
| 1822 |
Assert(CharSize > 0); |
| 1823 |
Data := Windows.GlobalLock(DataHandle); |
| 1824 |
try |
| 1825 |
SetLength(ResultUnicode, CharSize); |
| 1826 |
Move(Data^, ResultUnicode[1], ByteSize); |
| 1827 |
Result := Utf16ToString(ResultUnicode); |
| 1828 |
finally Windows.GlobalUnlock(DataHandle) end; |
| 1829 |
end; |
| 1830 |
finally Windows.CloseClipboard end; |
| 1831 |
end; |
| 1832 |
end; |
| 1833 |
|
| 1834 |
procedure TWinApiClipboard.SetAsText(const Value: String); |
| 1835 |
var |
| 1836 |
DataHandle : Windows.HGLOBAL; |
| 1837 |
Data: Pointer; |
| 1838 |
ByteSize, CharSize: Integer; |
| 1839 |
ValueUnicode: TClipboardString; |
| 1840 |
begin |
| 1841 |
if not Windows.OpenClipboard(Windows.HWND(nil)) then Exit; |
| 1842 |
try |
| 1843 |
if not Windows.EmptyClipboard then Exit; |
| 1844 |
|
| 1845 |
if Value <> '' then |
| 1846 |
begin |
| 1847 |
ValueUnicode := StringToUtf16(Value); |
| 1848 |
|
| 1849 |
CharSize := Length(ValueUnicode) + 1; // copy to Windows with trailing #0 |
| 1850 |
ByteSize := CharSize * SizeOf(TClipboardChar); |
| 1851 |
|
| 1852 |
DataHandle := Windows.GlobalAlloc(Windows.GMEM_MOVEABLE, ByteSize); |
| 1853 |
if DataHandle = 0 then Exit; |
| 1854 |
|
| 1855 |
Data := GlobalLock(DataHandle); |
| 1856 |
try |
| 1857 |
Move(ValueUnicode[1], Data^, ByteSize); |
| 1858 |
finally Windows.GlobalUnlock(DataHandle) end; |
| 1859 |
Windows.SetClipboardData(StringClipboardFormat, DataHandle); |
| 1860 |
end; |
| 1861 |
finally Windows.CloseClipboard end; |
| 1862 |
end; |
| 1863 |
|
| 1864 |
{ TCastleApplication ----------------------------------------------- } |
| 1865 |
|
| 1866 |
procedure TCastleApplication.CreateBackend; |
| 1867 |
const |
| 1868 |
WinCursorNameFromCastle: array [mcStandard .. High(TMouseCursor)] of LPCWSTR = ( |
| 1869 |
PWideChar(IDC_ARROW), // mcStandard |
| 1870 |
PWideChar(IDC_WAIT), // mcWait |
| 1871 |
PWideChar(IDC_IBEAM), // mcText |
| 1872 |
PWideChar(IDC_HAND), // mcHand |
| 1873 |
PWideChar(IDC_SIZENS), // mcResizeVertical |
| 1874 |
PWideChar(IDC_SIZEWE), // mcResizeHorizontal |
| 1875 |
PWideChar(IDC_SIZENWSE), // no IDC_SIZENW in Windows, // mcResizeTopLeft |
| 1876 |
PWideChar(IDC_SIZENS), // no IDC_SIZEN in Windows, // mcResizeTop |
| 1877 |
PWideChar(IDC_SIZENESW), // no IDC_SIZENE in Windows, // mcResizeTopRight |
| 1878 |
PWideChar(IDC_SIZEWE), // no IDC_SIZEW in Windows, // mcResizeLeft |
| 1879 |
PWideChar(IDC_SIZEWE), // no IDC_SIZEE in Windows, // mcResizeRight |
| 1880 |
PWideChar(IDC_SIZENESW), // no IDC_SIZESW in Windows, // mcResizeBottomLeft |
| 1881 |
PWideChar(IDC_SIZENS), // no IDC_SIZES in Windows, // mcResizeBottom |
| 1882 |
PWideChar(IDC_SIZENWSE) // no IDC_SIZESE in Windows, // mcResizeBottomRight |
| 1883 |
); |
| 1884 |
var |
| 1885 |
WindowClass: TWndClassW; |
| 1886 |
C: TMouseCursor; |
| 1887 |
begin |
| 1888 |
RegisterClipboard(TWinApiClipboard.Create); |
| 1889 |
|
| 1890 |
appActive := true; |
| 1891 |
|
| 1892 |
{ Initialize CursorHandles. |
| 1893 |
We depend on the fact that CursorHandles is initially filled with zero, |
| 1894 |
so Handle remains nil for the rest of TMouseCursor values |
| 1895 |
(not in WinCursorNameFromCastle). } |
| 1896 |
for C := Low(WinCursorNameFromCastle) to High(WinCursorNameFromCastle) do |
| 1897 |
CursorHandles[C].Handle := LoadCursorW(0, WinCursorNameFromCastle[C]); |
| 1898 |
|
| 1899 |
{ create window class (WindowClass) } |
| 1900 |
|
| 1901 |
{ no need to worry about multiple applications |
| 1902 |
registering same WndClassName because window classes are |
| 1903 |
process-specific (so, if other process registers another |
| 1904 |
CastleWindow class, it will be just a different class - |
| 1905 |
distinguished by the hInstance parameter of TWndClass and |
| 1906 |
CreateWindowEx). } |
| 1907 |
WndClassName := 'CastleWindow'; |
| 1908 |
|
| 1909 |
FillChar(WindowClass, SizeOf(WindowClass), 0); |
| 1910 |
{ style : redraw on size, own DC for window } |
| 1911 |
WindowClass.style := CS_HREDRAW or CS_VREDRAW or CS_OWNDC; |
| 1912 |
WindowClass.lpfnWndProc := @WndProc; |
| 1913 |
WindowClass.hInstance := hInstance; |
| 1914 |
{ sprobuj zaladowac ikone z pliku EXE, tzn. z naszego resource; |
| 1915 |
w ten sposob mozesz ja latwo zmieniac w IDE delphi a mozesz sam stworzyc |
| 1916 |
odpowiedni resource przez windres, no i twoja ikona bedzie widoczna dla innych |
| 1917 |
programow. |
| 1918 |
Jesli nie znajdzie ikonki w resource to zaladuj ikone ze zbioru Windowsa |
| 1919 |
idi_application. } |
| 1920 |
WindowClass.hIcon := LoadIconW(hInstance, 'MAINICON'); |
| 1921 |
if WindowClass.hIcon = 0 then |
| 1922 |
WindowClass.hIcon := LoadIconW(0, PWideChar(IDI_APPLICATION)); |
| 1923 |
WindowClass.hCursor := CursorHandles[mcStandard].Handle; |
| 1924 |
WindowClass.lpszClassName := PWideChar(WndClassName); |
| 1925 |
OSCheck( Windows.RegisterClassW(WindowClass) <> 0, 'RegisterClassW'); |
| 1926 |
end; |
| 1927 |
|
| 1928 |
procedure TCastleApplication.DestroyBackend; |
| 1929 |
begin |
| 1930 |
OSCheck( Windows.UnregisterClassW(PWideChar(WndClassName), hInstance), 'UnregisterClassW'); |
| 1931 |
end; |
| 1932 |
|
| 1933 |
procedure TCastleApplication.VideoReset; |
| 1934 |
begin |
| 1935 |
{ switch back to the desktop mode } |
| 1936 |
if DisplaySettingsChanged then |
| 1937 |
ChangeDisplaySettings({$ifdef FPC}nil{$else}TDeviceMode(nil^){$endif}, 0); |
| 1938 |
end; |
| 1939 |
|
| 1940 |
function TCastleApplication.TryVideoChange: boolean; |
| 1941 |
|
| 1942 |
{$ifdef VER1_9_6} |
| 1943 |
{ This is to workaround a bug in FPC 1.9.6. |
| 1944 |
Already fixed in FPC 1.9.7. } |
| 1945 |
type |
| 1946 |
{ Copied from FPC 1.9.7 from 2005-01-18 } |
| 1947 |
DEVMODE = record |
| 1948 |
dmDeviceName : array[0..(CCHDEVICENAME)-1] of BCHAR; |
| 1949 |
dmSpecVersion : WORD; |
| 1950 |
dmDriverVersion : WORD; |
| 1951 |
dmSize : WORD; |
| 1952 |
dmDriverExtra : WORD; |
| 1953 |
dmFields : DWORD; |
| 1954 |
case byte of |
| 1955 |
1: (dmOrientation : SmallInt; |
| 1956 |
dmPaperSize : SmallInt; |
| 1957 |
dmPaperLength : SmallInt; |
| 1958 |
dmPaperWidth : SmallInt; |
| 1959 |
dmScale : SmallInt; |
| 1960 |
dmCopies : SmallInt; |
| 1961 |
dmDefaultSource : SmallInt; |
| 1962 |
dmPrintQuality : SmallInt; |
| 1963 |
dmColor : SmallInt; |
| 1964 |
dmDuplex : SmallInt; |
| 1965 |
dmYResolution : SmallInt; |
| 1966 |
dmTTOption : SmallInt; |
| 1967 |
dmCollate : SmallInt; |
| 1968 |
dmFormName : array[0..(CCHFORMNAME)-1] of BCHAR; |
| 1969 |
dmLogPixels : WORD; |
| 1970 |
dmBitsPerPel : DWORD; |
| 1971 |
dmPelsWidth : DWORD; |
| 1972 |
dmPelsHeight : DWORD; |
| 1973 |
dmDisplayFlags : DWORD; |
| 1974 |
dmDisplayFrequency : DWORD; |
| 1975 |
dmICMMethod : DWORD; |
| 1976 |
dmICMIntent : DWORD; |
| 1977 |
dmMediaType : DWORD; |
| 1978 |
dmDitherType : DWORD; |
| 1979 |
dmICCManufacturer : DWORD; |
| 1980 |
dmICCModel : DWORD |
| 1981 |
); |
| 1982 |
2: (dmPosition: POINTL; |
| 1983 |
dmDisplayOrientation: DWORD; |
| 1984 |
dmDisplayFixedOutput: DWORD; |
| 1985 |
); |
| 1986 |
end; |
| 1987 |
{$endif} |
| 1988 |
|
| 1989 |
var |
| 1990 |
dmScreenSettings: Devmode; |
| 1991 |
ChangeResult: Windows.LONG; |
| 1992 |
begin |
| 1993 |
VideoReset; { reset normal screen settings if we called TryVideoChange more than once } |
| 1994 |
|
| 1995 |
{ optionally adjust screen to our fullscreen mode (do ChangeDisplaySettings) } |
| 1996 |
with dmScreenSettings do |
| 1997 |
begin |
| 1998 |
dmFields := 0; |
| 1999 |
|
| 2000 |
if VideoColorBits <> 0 then |
| 2001 |
begin |
| 2002 |
dmBitsPerPel := VideoColorBits; |
| 2003 |
dmFields := dmFields or DM_BITSPERPEL; |
| 2004 |
end; |
| 2005 |
|
| 2006 |
if VideoResize then |
| 2007 |
begin |
| 2008 |
dmPelsWidth := VideoResizeWidth; |
| 2009 |
dmPelsHeight := VideoResizeHeight; |
| 2010 |
dmFields := dmFields or DM_PELSWIDTH or DM_PELSHEIGHT; |
| 2011 |
end; |
| 2012 |
|
| 2013 |
if VideoFrequency <> 0 then |
| 2014 |
begin |
| 2015 |
dmDisplayFrequency := VideoFrequency; |
| 2016 |
dmFields := dmFields or DM_DISPLAYFREQUENCY; |
| 2017 |
end; |
| 2018 |
|
| 2019 |
if dmFields <> 0 then { then TRY to change screen size and/or resolution } |
| 2020 |
begin |
| 2021 |
dmSize := sizeof(dmScreenSettings); |
| 2022 |
|
| 2023 |
{ Reading ChangeDisplaySettings docs |
| 2024 |
(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/devcons_7gz7.asp): |
| 2025 |
The dmDriverExtra member of DEVMODE must be initialized to indicate |
| 2026 |
the number of bytes of private driver data following the |
| 2027 |
DEVMODE structure. |
| 2028 |
|
| 2029 |
So I guess that I should just set this to 0 ? } |
| 2030 |
dmDriverExtra := 0; |
| 2031 |
|
| 2032 |
ChangeResult := ChangeDisplaySettings({$ifdef FPC}@{$endif}dmScreenSettings, CDS_FullScreen); |
| 2033 |
Result := ChangeResult = DISP_CHANGE_SUCCESSFUL; |
| 2034 |
{ tests: InfoWrite('ChangeResult = '+ DispChangeToStr(ChangeResult)); } |
| 2035 |
if Result then DisplaySettingsChanged := true; |
| 2036 |
end else |
| 2037 |
Result := true; { we didn't do anything - well, then we succeded, right ? } |
| 2038 |
end; |
| 2039 |
end; |
| 2040 |
|
| 2041 |
procedure TCastleApplication.SetAppActive(value: boolean); |
| 2042 |
begin |
| 2043 |
{ ponizej : gdy fappActive zmienia sie z true na false musimy |
| 2044 |
wykonac ChangeDisplaySettings(nil, 0) bez wzgledu na to czy |
| 2045 |
DisplaySettingsChanged. W ten sposob unikamy bledu Windowsa |
| 2046 |
z zostawaniem przycisku po oknie fullscreen na pasku zadan. |
| 2047 |
W rezultacie musimy tez odnawiac nasz Video mode jesli potem |
| 2048 |
wracamy do naszej aplikacji. } |
| 2049 |
if value and not appActive then |
| 2050 |
begin |
| 2051 |
if DisplaySettingsChanged then VideoChange(true); |
| 2052 |
end else |
| 2053 |
if appActive and not value then |
| 2054 |
ChangeDisplaySettings({$ifdef FPC}nil{$else}TDeviceMode(nil^){$endif} , 0); |
| 2055 |
|
| 2056 |
fappActive := value; |
| 2057 |
|
| 2058 |
{ in this simple case, this can just control Container.Focused } |
| 2059 |
if OpenWindowsCount = 1 then |
| 2060 |
begin |
| 2061 |
OpenWindows[0].FFocused := Value; |
| 2062 |
{ right after changing Focused, it's safest to consider mouse position |
| 2063 |
not suitable for mouse look } |
| 2064 |
OpenWindows[0].Container.MouseLookIgnoreNextMotion; |
| 2065 |
end; |
| 2066 |
end; |
| 2067 |
|
| 2068 |
function TCastleApplication.ScreenWidth: integer; |
| 2069 |
begin |
| 2070 |
if DisplaySettingsChanged and VideoResize then |
| 2071 |
result := VideoResizeWidth else |
| 2072 |
result := GetSystemMetrics(SM_CXSCREEN); |
| 2073 |
end; |
| 2074 |
|
| 2075 |
function TCastleApplication.ScreenHeight: integer; |
| 2076 |
begin |
| 2077 |
if DisplaySettingsChanged and VideoResize then |
| 2078 |
result := VideoResizeHeight else |
| 2079 |
result := GetSystemMetrics(SM_CYSCREEN); |
| 2080 |
end; |
| 2081 |
|
| 2082 |
function TCastleApplication.BackendName: String; |
| 2083 |
begin |
| 2084 |
Result := 'WinAPI'; |
| 2085 |
end; |
| 2086 |
|
| 2087 |
{ TWindowContainer ----------------------------------------------------------- } |
| 2088 |
|
| 2089 |
function TWindowContainer.SettingMousePositionCausesMotion: Boolean; |
| 2090 |
begin |
| 2091 |
{ Confirmed using window_events example that it is "true" for GTK |
| 2092 |
(press "5", OnMotion is generated). } |
| 2093 |
Result := true; |
| 2094 |
end; |
| 2095 |
|
| 2096 |
{$endif read_implementation} |