1 /* 2 * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * The Toolkit class has two functions: it instantiates the AWT 28 * ToolkitPeer's native methods, and provides the DLL's core functions. 29 * 30 * There are two ways this DLL can be used: either as a dynamically- 31 * loaded Java native library from the interpreter, or by a Windows- 32 * specific app. The first manner requires that the Toolkit provide 33 * all support needed so the app can function as a first-class Windows 34 * app, while the second assumes that the app will provide that 35 * functionality. Which mode this DLL functions in is determined by 36 * which initialization paradigm is used. If the Toolkit is constructed 37 * normally, then the Toolkit will have its own pump. If it is explicitly 38 * initialized for an embedded environment (via a static method on 39 * sun.awt.windows.WToolkit), then it will rely on an external message 40 * pump. 41 * 42 * The most basic functionality needed is a Windows message pump (also 43 * known as a message loop). When an Java app is started as a console 44 * app by the interpreter, the Toolkit needs to provide that message 45 * pump if the AWT is dynamically loaded. 46 */ 47 48 #ifndef AWT_TOOLKIT_H 49 #define AWT_TOOLKIT_H 50 51 #include "awt.h" 52 #include "awtmsg.h" 53 #include "Trace.h" 54 55 #include "sun_awt_windows_WToolkit.h" 56 57 class AwtObject; 58 class AwtDialog; 59 class AwtDropTarget; 60 61 typedef VOID (CALLBACK* IDLEPROC)(VOID); 62 typedef BOOL (CALLBACK* PEEKMESSAGEPROC)(MSG&); 63 64 // Struct for _WInputMethod_enable|disableNativeIME method 65 struct EnableNativeIMEStruct { 66 jobject self; 67 jobject peer; 68 jint context; 69 jboolean useNativeCompWindow; 70 }; 71 72 /* 73 * class JNILocalFrame 74 * Push/PopLocalFrame helper 75 */ 76 class JNILocalFrame { 77 public: 78 INLINE JNILocalFrame(JNIEnv *env, int size) { 79 m_env = env; 80 int result = m_env->PushLocalFrame(size); 81 if (result < 0) { 82 DASSERT(FALSE); 83 throw std::bad_alloc(); 84 } 85 } 86 INLINE ~JNILocalFrame() { m_env->PopLocalFrame(NULL); } 87 private: 88 JNIEnv* m_env; 89 }; 90 91 /* 92 * class CriticalSection 93 * ~~~~~ ~~~~~~~~~~~~~~~~ 94 * Lightweight intra-process thread synchronization. Can only be used with 95 * other critical sections, and only within the same process. 96 */ 97 class CriticalSection { 98 public: 99 INLINE CriticalSection() { ::InitializeCriticalSection(&rep); } 100 INLINE ~CriticalSection() { ::DeleteCriticalSection(&rep); } 101 102 class Lock { 103 public: 104 INLINE Lock(const CriticalSection& cs) : critSec(cs) { 105 (const_cast<CriticalSection &>(critSec)).Enter(); 106 } 107 INLINE ~Lock() { 108 (const_cast<CriticalSection &>(critSec)).Leave(); 109 } 110 private: 111 const CriticalSection& critSec; 112 }; 113 friend class Lock; 114 115 private: 116 CRITICAL_SECTION rep; 117 118 CriticalSection(const CriticalSection&); 119 const CriticalSection& operator =(const CriticalSection&); 120 121 public: 122 virtual void Enter() { 123 ::EnterCriticalSection(&rep); 124 } 125 virtual BOOL TryEnter() { 126 return ::TryEnterCriticalSection(&rep); 127 } 128 virtual void Leave() { 129 ::LeaveCriticalSection(&rep); 130 } 131 }; 132 133 // Macros for using CriticalSection objects that help trace 134 // lock/unlock actions 135 136 #define CRITICAL_SECTION_ENTER(cs) { \ 137 J2dTraceLn4(J2D_TRACE_VERBOSE2, \ 138 "CS.Wait: tid, cs, file, line = 0x%x, 0x%x, %s, %d", \ 139 GetCurrentThreadId(), &(cs), __FILE__, __LINE__); \ 140 (cs).Enter(); \ 141 J2dTraceLn4(J2D_TRACE_VERBOSE2, \ 142 "CS.Enter: tid, cs, file, line = 0x%x, 0x%x, %s, %d", \ 143 GetCurrentThreadId(), &(cs), __FILE__, __LINE__); \ 144 } 145 146 #define CRITICAL_SECTION_LEAVE(cs) { \ 147 J2dTraceLn4(J2D_TRACE_VERBOSE2, \ 148 "CS.Leave: tid, cs, file, line = 0x%x, 0x%x, %s, %d", \ 149 GetCurrentThreadId(), &(cs), __FILE__, __LINE__); \ 150 (cs).Leave(); \ 151 J2dTraceLn4(J2D_TRACE_VERBOSE2, \ 152 "CS.Left: tid, cs, file, line = 0x%x, 0x%x, %s, %d", \ 153 GetCurrentThreadId(), &(cs), __FILE__, __LINE__); \ 154 } 155 156 // Redefine WinAPI values related to touch input, if OS < Windows 7. 157 #if (!defined(WINVER) || ((WINVER) < 0x0601)) 158 /* 159 * RegisterTouchWindow flag values 160 */ 161 #define TWF_FINETOUCH (0x00000001) 162 #define TWF_WANTPALM (0x00000002) 163 164 #define WM_TOUCH 0x0240 165 166 /* 167 * Touch input handle 168 */ 169 typedef HANDLE HTOUCHINPUT; 170 171 typedef struct tagTOUCHINPUT { 172 LONG x; 173 LONG y; 174 HANDLE hSource; 175 DWORD dwID; 176 DWORD dwFlags; 177 DWORD dwMask; 178 DWORD dwTime; 179 ULONG_PTR dwExtraInfo; 180 DWORD cxContact; 181 DWORD cyContact; 182 } TOUCHINPUT, *PTOUCHINPUT; 183 typedef TOUCHINPUT const * PCTOUCHINPUT; 184 185 /* 186 * Touch input flag values (TOUCHINPUT.dwFlags) 187 */ 188 #define TOUCHEVENTF_MOVE 0x0001 189 #define TOUCHEVENTF_DOWN 0x0002 190 #define TOUCHEVENTF_UP 0x0004 191 #define TOUCHEVENTF_INRANGE 0x0008 192 #define TOUCHEVENTF_PRIMARY 0x0010 193 #define TOUCHEVENTF_NOCOALESCE 0x0020 194 #define TOUCHEVENTF_PEN 0x0040 195 #define TOUCHEVENTF_PALM 0x0080 196 #endif 197 198 /************************************************************************ 199 * AwtToolkit class 200 */ 201 202 class AwtToolkit { 203 public: 204 enum { 205 KB_STATE_SIZE = 256 206 }; 207 208 /* java.awt.Toolkit method ids */ 209 static jmethodID getDefaultToolkitMID; 210 static jmethodID getFontMetricsMID; 211 static jmethodID insetsMID; 212 213 /* sun.awt.windows.WToolkit ids */ 214 static jmethodID windowsSettingChangeMID; 215 static jmethodID displayChangeMID; 216 217 static jmethodID userSessionMID; 218 static jmethodID systemSleepMID; 219 220 BOOL m_isDynamicLayoutSet; 221 222 AwtToolkit(); 223 ~AwtToolkit(); 224 225 BOOL Initialize(BOOL localPump); 226 BOOL Dispose(); 227 228 void SetDynamicLayout(BOOL dynamic); 229 BOOL IsDynamicLayoutSet(); 230 BOOL IsDynamicLayoutSupported(); 231 BOOL IsDynamicLayoutActive(); 232 BOOL areExtraMouseButtonsEnabled(); 233 void setExtraMouseButtonsEnabled(BOOL enable); 234 static UINT GetNumberOfButtons(); 235 236 bool IsWin8OrLater(); 237 bool IsTouchKeyboardAutoShowEnabled(); 238 bool IsAnyKeyboardAttached(); 239 bool IsTouchKeyboardAutoShowSystemEnabled(); 240 void ShowTouchKeyboard(); 241 void HideTouchKeyboard(); 242 BOOL TIRegisterTouchWindow(HWND hWnd, ULONG ulFlags); 243 BOOL TIGetTouchInputInfo(HTOUCHINPUT hTouchInput, 244 UINT cInputs, PTOUCHINPUT pInputs, int cbSize); 245 BOOL TICloseTouchInputHandle(HTOUCHINPUT hTouchInput); 246 247 INLINE BOOL localPump() { return m_localPump; } 248 INLINE BOOL VerifyComponents() { return FALSE; } // TODO: Use new DebugHelper class to set this flag 249 INLINE HWND GetHWnd() { return m_toolkitHWnd; } 250 251 INLINE HMODULE GetModuleHandle() { return m_dllHandle; } 252 INLINE void SetModuleHandle(HMODULE h) { m_dllHandle = h; } 253 254 INLINE static DWORD MainThread() { return GetInstance().m_mainThreadId; } 255 INLINE void VerifyActive() throw (awt_toolkit_shutdown) { 256 if (!m_isActive && m_mainThreadId != ::GetCurrentThreadId()) { 257 throw awt_toolkit_shutdown(); 258 } 259 } 260 INLINE BOOL IsDisposed() { return m_isDisposed; } 261 static UINT GetMouseKeyState(); 262 static void GetKeyboardState(PBYTE keyboardState); 263 264 static ATOM RegisterClass(); 265 static void UnregisterClass(); 266 INLINE LRESULT SendMessage(UINT msg, WPARAM wParam=0, LPARAM lParam=0) { 267 if (!m_isDisposed) { 268 return ::SendMessage(GetHWnd(), msg, wParam, lParam); 269 } else { 270 return NULL; 271 } 272 } 273 static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, 274 LPARAM lParam); 275 static LRESULT CALLBACK GetMessageFilter(int code, WPARAM wParam, 276 LPARAM lParam); 277 static LRESULT CALLBACK ForegroundIdleFilter(int code, WPARAM wParam, 278 LPARAM lParam); 279 static LRESULT CALLBACK MouseLowLevelHook(int code, WPARAM wParam, 280 LPARAM lParam); 281 282 INLINE static AwtToolkit& GetInstance() { return theInstance; } 283 INLINE void SetPeer(JNIEnv *env, jobject wToolkit) { 284 AwtToolkit &tk = AwtToolkit::GetInstance(); 285 if (tk.m_peer != NULL) { 286 env->DeleteGlobalRef(tk.m_peer); 287 } 288 tk.m_peer = (wToolkit != NULL) ? env->NewGlobalRef(wToolkit) : NULL; 289 } 290 291 INLINE jobject GetPeer() { 292 return m_peer; 293 } 294 295 // is this thread the main thread? 296 297 INLINE static BOOL IsMainThread() { 298 return GetInstance().m_mainThreadId == ::GetCurrentThreadId(); 299 } 300 301 // post a message to the message pump thread 302 303 INLINE BOOL PostMessage(UINT msg, WPARAM wp=0, LPARAM lp=0) { 304 return ::PostMessage(GetHWnd(), msg, wp, lp); 305 } 306 307 // cause the message pump thread to call the function synchronously now! 308 309 INLINE void * InvokeFunction(void*(*ftn)(void)) { 310 return (void *)SendMessage(WM_AWT_INVOKE_VOID_METHOD, (WPARAM)ftn, 0); 311 } 312 INLINE void InvokeFunction(void (*ftn)(void)) { 313 InvokeFunction((void*(*)(void))ftn); 314 } 315 INLINE void * InvokeFunction(void*(*ftn)(void *), void* param) { 316 return (void *)SendMessage(WM_AWT_INVOKE_METHOD, (WPARAM)ftn, 317 (LPARAM)param); 318 } 319 INLINE void InvokeFunction(void (*ftn)(void *), void* param) { 320 InvokeFunction((void*(*)(void*))ftn, param); 321 } 322 323 INLINE CriticalSection &GetSyncCS() { return m_Sync; } 324 325 void *SyncCall(void*(*ftn)(void *), void* param); 326 void SyncCall(void (*ftn)(void *), void *param); 327 void *SyncCall(void *(*ftn)(void)); 328 void SyncCall(void (*ftn)(void)); 329 330 // cause the message pump thread to call the function later ... 331 332 INLINE void InvokeFunctionLater(void (*ftn)(void *), void* param) { 333 if (!PostMessage(WM_AWT_INVOKE_METHOD, (WPARAM)ftn, (LPARAM)param)) { 334 JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); 335 JNU_ThrowInternalError(env, "Message not posted, native event queue may be full."); 336 } 337 } 338 339 // cause the message pump thread to synchronously synchronize on the handle 340 341 INLINE void WaitForSingleObject(HANDLE handle) { 342 SendMessage(WM_AWT_WAIT_FOR_SINGLE_OBJECT, 0, (LPARAM)handle); 343 } 344 345 /* 346 * Create an AwtXxxx C++ component using a given factory 347 */ 348 typedef void (*ComponentFactory)(void*, void*); 349 static void CreateComponent(void* hComponent, void* hParent, 350 ComponentFactory compFactory, BOOL isParentALocalReference=TRUE); 351 352 static void DestroyComponentHWND(HWND hwnd); 353 354 // constants used to PostQuitMessage 355 356 static const int EXIT_ENCLOSING_LOOP; 357 static const int EXIT_ALL_ENCLOSING_LOOPS; 358 359 // ... 360 361 void QuitMessageLoop(int status); 362 363 UINT MessageLoop(IDLEPROC lpIdleFunc, PEEKMESSAGEPROC lpPeekMessageFunc); 364 BOOL PumpWaitingMessages(PEEKMESSAGEPROC lpPeekMessageFunc); 365 void PumpToDestroy(class AwtComponent* p); 366 void ProcessMsg(MSG& msg); 367 BOOL PreProcessMsg(MSG& msg); 368 BOOL PreProcessMouseMsg(class AwtComponent* p, MSG& msg); 369 BOOL PreProcessKeyMsg(class AwtComponent* p, MSG& msg); 370 371 /* Checks that an free ID exists. */ 372 jboolean isFreeIDAvailable(); 373 /* Create an ID which maps to an AwtObject pointer, such as a menu. */ 374 UINT CreateCmdID(AwtObject* object); 375 376 // removes cmd id mapping 377 void RemoveCmdID(UINT id); 378 379 /* Return the AwtObject associated with its ID. */ 380 AwtObject* LookupCmdID(UINT id); 381 382 /* Return the current application icon. */ 383 HICON GetAwtIcon(); 384 HICON GetAwtIconSm(); 385 386 // Calculate a wave-like value out of the integer 'value' and 387 // the specified period. 388 // The argument 'value' is an integer 0, 1, 2, ... *infinity*. 389 // 390 // Examples: 391 // Period == 3 392 // Generated sequence: 0 1 2 1 0 ..... 393 // 394 // Period == 4 395 // Generated sequence: 0 1 2 3 2 1 0 ..... 396 static inline UINT CalculateWave(UINT value, const UINT period) { 397 if (period < 2) { 398 return 0; 399 } 400 // -2 is necessary to avoid repeating extreme values (0 and period-1) 401 value %= period * 2 -2; 402 if (value >= period) { 403 value = period * 2 -2 - value; 404 } 405 return value; 406 } 407 408 HICON GetSecurityWarningIcon(UINT index, UINT w, UINT h); 409 410 /* Turns on/off dialog modality for the system. */ 411 INLINE AwtDialog* SetModal(AwtDialog* frame) { 412 AwtDialog* previousDialog = m_pModalDialog; 413 m_pModalDialog = frame; 414 return previousDialog; 415 }; 416 INLINE void ResetModal(AwtDialog* oldFrame) { m_pModalDialog = oldFrame; }; 417 INLINE BOOL IsModal() { return (m_pModalDialog != NULL); }; 418 INLINE AwtDialog* GetModalDialog(void) { return m_pModalDialog; }; 419 420 /* Stops the current message pump (normally a modal dialog pump) */ 421 INLINE void StopMessagePump() { m_breakOnError = TRUE; } 422 423 /* Debug settings */ 424 INLINE void SetVerbose(long flag) { m_verbose = (flag != 0); } 425 INLINE void SetVerify(long flag) { m_verifyComponents = (flag != 0); } 426 INLINE void SetBreak(long flag) { m_breakOnError = (flag != 0); } 427 INLINE void SetHeapCheck(long flag); 428 429 static void SetBusy(BOOL busy); 430 431 /* Set and get the default input method Window handler. */ 432 INLINE void SetInputMethodWindow(HWND inputMethodHWnd) { m_inputMethodHWnd = inputMethodHWnd; } 433 INLINE HWND GetInputMethodWindow() { return m_inputMethodHWnd; } 434 435 static VOID CALLBACK PrimaryIdleFunc(); 436 static VOID CALLBACK SecondaryIdleFunc(); 437 static BOOL CALLBACK CommonPeekMessageFunc(MSG& msg); 438 static BOOL activateKeyboardLayout(HKL hkl); 439 440 HANDLE m_waitEvent; 441 volatile DWORD eventNumber; 442 volatile BOOL isInDoDragDropLoop; 443 private: 444 HWND CreateToolkitWnd(LPCTSTR name); 445 446 void InitTouchKeyboardExeFilePath(); 447 HWND GetTouchKeyboardWindow(); 448 449 BOOL m_localPump; 450 DWORD m_mainThreadId; 451 HWND m_toolkitHWnd; 452 HWND m_inputMethodHWnd; 453 BOOL m_verbose; 454 BOOL m_isActive; // set to FALSE at beginning of Dispose 455 BOOL m_isDisposed; // set to TRUE at end of Dispose 456 BOOL m_areExtraMouseButtonsEnabled; 457 458 typedef BOOL (WINAPI *RegisterTouchWindowFunc)(HWND hWnd, ULONG ulFlags); 459 typedef BOOL (WINAPI *GetTouchInputInfoFunc)(HTOUCHINPUT hTouchInput, 460 UINT cInputs, PTOUCHINPUT pInputs, int cbSize); 461 typedef BOOL (WINAPI *CloseTouchInputHandleFunc)(HTOUCHINPUT hTouchInput); 462 463 BOOL m_isWin8OrLater; 464 BOOL m_touchKbrdAutoShowIsEnabled; 465 TCHAR* m_touchKbrdExeFilePath; 466 RegisterTouchWindowFunc m_pRegisterTouchWindow; 467 GetTouchInputInfoFunc m_pGetTouchInputInfo; 468 CloseTouchInputHandleFunc m_pCloseTouchInputHandle; 469 470 BOOL m_vmSignalled; // set to TRUE if QUERYENDSESSION has successfully 471 // raised SIGTERM 472 473 BOOL m_verifyComponents; 474 BOOL m_breakOnError; 475 476 BOOL m_breakMessageLoop; 477 UINT m_messageLoopResult; 478 479 class AwtComponent* m_lastMouseOver; 480 BOOL m_mouseDown; 481 482 HHOOK m_hGetMessageHook; 483 HHOOK m_hMouseLLHook; 484 UINT_PTR m_timer; 485 486 class AwtCmdIDList* m_cmdIDs; 487 BYTE m_lastKeyboardState[KB_STATE_SIZE]; 488 CriticalSection m_lockKB; 489 490 static AwtToolkit theInstance; 491 492 /* The current modal dialog frame (normally NULL). */ 493 AwtDialog* m_pModalDialog; 494 495 /* The WToolkit peer instance */ 496 jobject m_peer; 497 498 HMODULE m_dllHandle; /* The module handle. */ 499 500 CriticalSection m_Sync; 501 502 /* track display changes - used by palette-updating code. 503 This is a workaround for a windows bug that prevents 504 WM_PALETTECHANGED event from occurring immediately after 505 a WM_DISPLAYCHANGED event. 506 */ 507 private: 508 BOOL m_displayChanged; /* Tracks displayChanged events */ 509 // 0 means we are not embedded. 510 DWORD m_embedderProcessID; 511 512 public: 513 BOOL HasDisplayChanged() { return m_displayChanged; } 514 void ResetDisplayChanged() { m_displayChanged = FALSE; } 515 void RegisterEmbedderProcessId(HWND); 516 BOOL IsEmbedderProcessId(const DWORD processID) const 517 { 518 return m_embedderProcessID && (processID == m_embedderProcessID); 519 } 520 521 private: 522 static JNIEnv *m_env; 523 static DWORD m_threadId; 524 public: 525 static void SetEnv(JNIEnv *env); 526 static JNIEnv* GetEnv(); 527 528 static BOOL GetScreenInsets(int screenNum, RECT * rect); 529 530 // If the DWM is active, this function uses 531 // DwmGetWindowAttribute()/DWMWA_EXTENDED_FRAME_BOUNDS. 532 // Otherwise, fall back to regular ::GetWindowRect(). 533 // See 6711576 for more details. 534 static void GetWindowRect(HWND hWnd, LPRECT lpRect); 535 536 private: 537 // The window handle of a toplevel window last seen under the mouse cursor. 538 // See MouseLowLevelHook() for details. 539 HWND m_lastWindowUnderMouse; 540 public: 541 HWND GetWindowUnderMouse() { return m_lastWindowUnderMouse; } 542 543 void InstallMouseLowLevelHook(); 544 void UninstallMouseLowLevelHook(); 545 546 547 /* AWT preloading (early Toolkit thread start) 548 */ 549 public: 550 /* Toolkit preload action class. 551 * Preload actions should be registered with 552 * AwtToolkit::getInstance().GetPreloadThread().AddAction(). 553 * AwtToolkit thread calls InitImpl method at the beghining 554 * and CleanImpl(false) before exiting for all registered actions. 555 * If an application provides own Toolkit thread 556 * (sun.awt.windows.WToolkit.embeddedInit), the thread calls Clean(true) 557 * for each action. 558 */ 559 class PreloadThread; // forward declaration 560 class PreloadAction { 561 friend class PreloadThread; 562 public: 563 PreloadAction() : initThreadId(0), pNext(NULL) {} 564 virtual ~PreloadAction() {} 565 566 protected: 567 // called by PreloadThread or as result 568 // of EnsureInited() call (on Toolkit thread!). 569 virtual void InitImpl() = 0; 570 571 // called by PreloadThread (before exiting). 572 // reInit == false: normal shutdown; 573 // reInit == true: PreloadThread is shutting down due external 574 // Toolkit thread was provided. 575 virtual void CleanImpl(bool reInit) = 0; 576 577 public: 578 // Initialized the action on the Toolkit thread if not yet initialized. 579 bool EnsureInited(); 580 581 // returns thread ID which the action was inited on (0 if not inited) 582 DWORD GetInitThreadID(); 583 584 // Allows to deinitialize action earlier. 585 // The method must be called on the Toolkit thread only. 586 // returns true on success, 587 // false if the action was inited on other thread. 588 bool Clean(); 589 590 private: 591 unsigned initThreadId; 592 // lock for Init/Clean 593 CriticalSection initLock; 594 595 // Chain support (for PreloadThread) 596 PreloadAction *pNext; // for action chain used by PreloadThread 597 void SetNext(PreloadAction *pNext) { this->pNext = pNext; } 598 PreloadAction *GetNext() { return pNext; } 599 600 // wrapper for AwtToolkit::InvokeFunction 601 static void InitWrapper(void *param); 602 603 void Init(); 604 void Clean(bool reInit); 605 606 }; 607 608 /** Toolkit preload thread class. 609 */ 610 class PreloadThread { 611 public: 612 PreloadThread(); 613 ~PreloadThread(); 614 615 // adds action & start the thread if not yet started 616 bool AddAction(PreloadAction *pAction); 617 618 // sets termination flag; returns true if the thread is running. 619 // wrongThread specifies cause of the termination: 620 // false means termination on the application shutdown; 621 // wrongThread is used as reInit parameter for action cleanup. 622 bool Terminate(bool wrongThread); 623 bool InvokeAndTerminate(void(_cdecl *fn)(void *), void *param); 624 625 // waits for the thread completion; 626 // use the method after Terminate() only if Terminate() returned true 627 INLINE void Wait4Finish() { 628 ::WaitForSingleObject(hFinished, INFINITE); 629 } 630 631 INLINE unsigned GetThreadId() { 632 CriticalSection::Lock lock(threadLock); 633 return threadId; 634 } 635 INLINE bool IsWrongThread() { 636 CriticalSection::Lock lock(threadLock); 637 return wrongThread; 638 } 639 // returns true if the current thread is "preload" thread 640 bool OnPreloadThread(); 641 642 private: 643 // data access lock 644 CriticalSection threadLock; 645 646 // the thread status 647 enum Status { 648 None = -1, // initial 649 Preloading = 0, // preloading in progress 650 RunningToolkit, // Running as Toolkit thread 651 Cleaning, // exited from Toolkit thread proc, cleaning 652 Finished // 653 } status; 654 655 // "wrong thread" flag 656 bool wrongThread; 657 658 // thread proc (calls (this)param->ThreadProc()) 659 static unsigned WINAPI StaticThreadProc(void *param); 660 unsigned ThreadProc(); 661 662 INLINE void AwakeThread() { 663 ::SetEvent(hAwake); 664 } 665 666 // if threadId != 0 -> we are running 667 unsigned threadId; 668 // ThreadProc sets the event on exit 669 HANDLE hFinished; 670 // ThreadProc waits on the event for NewAction/Terminate/InvokeAndTerminate 671 HANDLE hAwake; 672 673 // function/param to invoke (InvokeAndTerminate) 674 // if execFunc == NULL => just terminate 675 void(_cdecl *execFunc)(void *); 676 void *execParam; 677 678 // action chain 679 PreloadAction *pActionChain; 680 PreloadAction *pLastProcessedAction; 681 682 // returns next action in the list (NULL if no more actions) 683 PreloadAction* GetNextAction(); 684 685 }; 686 687 INLINE PreloadThread& GetPreloadThread() { return preloadThread; } 688 689 private: 690 PreloadThread preloadThread; 691 692 }; 693 694 695 /* creates an instance of T and assigns it to the argument, but only if 696 the argument is initially NULL. Supposed to be thread-safe. 697 returns the new value of the argument. I'm not using volatile here 698 as InterlockedCompareExchange ensures volatile semantics 699 and acquire/release. 700 The function is useful when used with static POD NULL-initialized 701 pointers, as they are guaranteed to be NULL before any dynamic 702 initialization takes place. This function turns such a pointer 703 into a thread-safe singleton, working regardless of dynamic 704 initialization order. Destruction problem is not solved, 705 we don't need it here. 706 */ 707 708 template<typename T> inline T* SafeCreate(T* &pArg) { 709 /* this implementation has no locks, it just destroys the object if it 710 fails to be the first to init. another way would be using a special 711 flag pointer value to mark the pointer as "being initialized". */ 712 T* pTemp = (T*)InterlockedCompareExchangePointer((void**)&pArg, NULL, NULL); 713 if (pTemp != NULL) return pTemp; 714 T* pNew = new T; 715 pTemp = (T*)InterlockedCompareExchangePointer((void**)&pArg, pNew, NULL); 716 if (pTemp != NULL) { 717 // we failed it - another thread has already initialized pArg 718 delete pNew; 719 return pTemp; 720 } else { 721 return pNew; 722 } 723 } 724 725 #endif /* AWT_TOOLKIT_H */