1 /*
   2  * Copyright (c) 1996, 2016, 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 /* Use THIS_FILE when it is available. */
 137 #ifndef THIS_FILE
 138     #define THIS_FILE __FILE__
 139 #endif
 140 
 141 #define CRITICAL_SECTION_ENTER(cs) { \
 142     J2dTraceLn4(J2D_TRACE_VERBOSE2, \
 143                 "CS.Wait:  tid, cs, file, line = 0x%x, 0x%x, %s, %d", \
 144                 GetCurrentThreadId(), &(cs), THIS_FILE, __LINE__); \
 145     (cs).Enter(); \
 146     J2dTraceLn4(J2D_TRACE_VERBOSE2, \
 147                 "CS.Enter: tid, cs, file, line = 0x%x, 0x%x, %s, %d", \
 148                 GetCurrentThreadId(), &(cs), THIS_FILE, __LINE__); \
 149 }
 150 
 151 #define CRITICAL_SECTION_LEAVE(cs) { \
 152     J2dTraceLn4(J2D_TRACE_VERBOSE2, \
 153                 "CS.Leave: tid, cs, file, line = 0x%x, 0x%x, %s, %d", \
 154                 GetCurrentThreadId(), &(cs), THIS_FILE, __LINE__); \
 155     (cs).Leave(); \
 156     J2dTraceLn4(J2D_TRACE_VERBOSE2, \
 157                 "CS.Left:  tid, cs, file, line = 0x%x, 0x%x, %s, %d", \
 158                 GetCurrentThreadId(), &(cs), THIS_FILE, __LINE__); \
 159 }
 160 
 161 // Redefine WinAPI values related to touch input, if OS < Windows 7.
 162 #if (!defined(WINVER) || ((WINVER) < 0x0601))
 163     typedef UINT32 POINTER_FLAGS;
 164     typedef UINT32 TOUCH_FLAGS;
 165     typedef UINT32 TOUCH_MASK;
 166 
 167     #define GET_POINTERID_WPARAM(wParam) (LOWORD (wParam))
 168 
 169     #define WM_POINTERENTER                 0x0249
 170     #define WM_NCPOINTERDOWN                0x0242
 171     #define WM_NCPOINTERUP                  0x0243
 172     #define WM_NCPOINTERUPDATE              0x0241
 173     #define WM_POINTERACTIVATE              0x024B
 174     #define WM_POINTERCAPTURECHANGED        0x024C
 175     #define WM_POINTERDOWN                  0x0246
 176     #define WM_POINTERLEAVE                 0x024A
 177     #define WM_POINTERUP                    0x0247
 178     #define WM_POINTERUPDATE                0x0245
 179 
 180     typedef enum _POINTER_BUTTON_CHANGE_TYPE {
 181       POINTER_CHANGE_NONE               ,
 182       POINTER_CHANGE_FIRSTBUTTON_DOWN   ,
 183       POINTER_CHANGE_FIRSTBUTTON_UP     ,
 184       POINTER_CHANGE_SECONDBUTTON_DOWN  ,
 185       POINTER_CHANGE_SECONDBUTTON_UP    ,
 186       POINTER_CHANGE_THIRDBUTTON_DOWN   ,
 187       POINTER_CHANGE_THIRDBUTTON_UP     ,
 188       POINTER_CHANGE_FOURTHBUTTON_DOWN  ,
 189       POINTER_CHANGE_FOURTHBUTTON_UP    ,
 190       POINTER_CHANGE_FIFTHBUTTON_DOWN   ,
 191       POINTER_CHANGE_FIFTHBUTTON_UP     ,
 192       } POINTER_BUTTON_CHANGE_TYPE;
 193 
 194     typedef enum tagPOINTER_INPUT_TYPE {
 195       PT_POINTER   = 0x00000001,
 196       PT_TOUCH     = 0x00000002,
 197       PT_PEN       = 0x00000003,
 198       PT_MOUSE     = 0x00000004,
 199       PT_TOUCHPAD  = 0x00000005
 200     } POINTER_INPUT_TYPE;
 201 
 202     typedef struct tagPOINTER_INFO {
 203       POINTER_INPUT_TYPE         pointerType;
 204       UINT32                     pointerId;
 205       UINT32                     frameId;
 206       POINTER_FLAGS              pointerFlags;
 207       HANDLE                     sourceDevice;
 208       HWND                       hwndTarget;
 209       POINT                      ptPixelLocation;
 210       POINT                      ptHimetricLocation;
 211       POINT                      ptPixelLocationRaw;
 212       POINT                      ptHimetricLocationRaw;
 213       DWORD                      dwTime;
 214       UINT32                     historyCount;
 215       INT32                      inputData;
 216       DWORD                      dwKeyStates;
 217       UINT64                     PerformanceCount;
 218       POINTER_BUTTON_CHANGE_TYPE ButtonChangeType;
 219     } POINTER_INFO;
 220 #endif
 221 
 222 /************************************************************************
 223  * AwtToolkit class
 224  */
 225 
 226 class AwtToolkit {
 227 public:
 228     enum {
 229         KB_STATE_SIZE = 256
 230     };
 231 
 232     /* java.awt.Toolkit method ids */
 233     static jmethodID getDefaultToolkitMID;
 234     static jmethodID getFontMetricsMID;
 235     static jmethodID insetsMID;
 236 
 237     /* sun.awt.windows.WToolkit ids */
 238     static jmethodID windowsSettingChangeMID;
 239     static jmethodID displayChangeMID;
 240 
 241     static jmethodID userSessionMID;
 242     static jmethodID systemSleepMID;
 243 
 244     BOOL m_isDynamicLayoutSet;
 245 
 246     AwtToolkit();
 247     ~AwtToolkit();
 248 
 249     BOOL Initialize(BOOL localPump);
 250     BOOL Dispose();
 251 
 252     void SetDynamicLayout(BOOL dynamic);
 253     BOOL IsDynamicLayoutSet();
 254     BOOL IsDynamicLayoutSupported();
 255     BOOL IsDynamicLayoutActive();
 256     BOOL areExtraMouseButtonsEnabled();
 257     void setExtraMouseButtonsEnabled(BOOL enable);
 258     static UINT GetNumberOfButtons();
 259 
 260     BOOL TIGetPointerInfo(UINT32 pointerID, POINTER_INFO *pointerInfo);
 261 
 262     INLINE BOOL localPump() { return m_localPump; }
 263     INLINE BOOL VerifyComponents() { return FALSE; } // TODO: Use new DebugHelper class to set this flag
 264     INLINE HWND GetHWnd() { return m_toolkitHWnd; }
 265 
 266     INLINE HMODULE GetModuleHandle() { return m_dllHandle; }
 267     INLINE void SetModuleHandle(HMODULE h) { m_dllHandle = h; }
 268 
 269     INLINE static DWORD MainThread() { return GetInstance().m_mainThreadId; }
 270     INLINE void VerifyActive() throw (awt_toolkit_shutdown) {
 271         if (!m_isActive && m_mainThreadId != ::GetCurrentThreadId()) {
 272             throw awt_toolkit_shutdown();
 273         }
 274     }
 275     INLINE BOOL IsDisposed() { return m_isDisposed; }
 276     static UINT GetMouseKeyState();
 277     static void GetKeyboardState(PBYTE keyboardState);
 278 
 279     static ATOM RegisterClass();
 280     static void UnregisterClass();
 281     INLINE LRESULT SendMessage(UINT msg, WPARAM wParam=0, LPARAM lParam=0) {
 282         if (!m_isDisposed) {
 283             return ::SendMessage(GetHWnd(), msg, wParam, lParam);
 284         } else {
 285             return NULL;
 286         }
 287     }
 288     static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
 289                                     LPARAM lParam);
 290     static LRESULT CALLBACK GetMessageFilter(int code, WPARAM wParam,
 291                                              LPARAM lParam);
 292     static LRESULT CALLBACK ForegroundIdleFilter(int code, WPARAM wParam,
 293                                                  LPARAM lParam);
 294     static LRESULT CALLBACK MouseLowLevelHook(int code, WPARAM wParam,
 295             LPARAM lParam);
 296 
 297     INLINE static AwtToolkit& GetInstance() { return theInstance; }
 298     INLINE void SetPeer(JNIEnv *env, jobject wToolkit) {
 299         AwtToolkit &tk = AwtToolkit::GetInstance();
 300         if (tk.m_peer != NULL) {
 301             env->DeleteGlobalRef(tk.m_peer);
 302         }
 303         tk.m_peer = (wToolkit != NULL) ? env->NewGlobalRef(wToolkit) : NULL;
 304     }
 305 
 306     INLINE jobject GetPeer() {
 307         return m_peer;
 308     }
 309 
 310     // is this thread the main thread?
 311 
 312     INLINE static BOOL IsMainThread() {
 313         return GetInstance().m_mainThreadId == ::GetCurrentThreadId();
 314     }
 315 
 316     // post a message to the message pump thread
 317 
 318     INLINE BOOL PostMessage(UINT msg, WPARAM wp=0, LPARAM lp=0) {
 319         return ::PostMessage(GetHWnd(), msg, wp, lp);
 320     }
 321 
 322     // cause the message pump thread to call the function synchronously now!
 323 
 324     INLINE void * InvokeFunction(void*(*ftn)(void)) {
 325         return (void *)SendMessage(WM_AWT_INVOKE_VOID_METHOD, (WPARAM)ftn, 0);
 326     }
 327     INLINE void InvokeFunction(void (*ftn)(void)) {
 328         InvokeFunction((void*(*)(void))ftn);
 329     }
 330     INLINE void * InvokeFunction(void*(*ftn)(void *), void* param) {
 331         return (void *)SendMessage(WM_AWT_INVOKE_METHOD, (WPARAM)ftn,
 332                                    (LPARAM)param);
 333     }
 334     INLINE void InvokeFunction(void (*ftn)(void *), void* param) {
 335         InvokeFunction((void*(*)(void*))ftn, param);
 336     }
 337 
 338     INLINE CriticalSection &GetSyncCS() { return m_Sync; }
 339 
 340     void *SyncCall(void*(*ftn)(void *), void* param);
 341     void SyncCall(void (*ftn)(void *), void *param);
 342     void *SyncCall(void *(*ftn)(void));
 343     void SyncCall(void (*ftn)(void));
 344 
 345     // cause the message pump thread to call the function later ...
 346 
 347     INLINE void InvokeFunctionLater(void (*ftn)(void *), void* param) {
 348         if (!PostMessage(WM_AWT_INVOKE_METHOD, (WPARAM)ftn, (LPARAM)param)) {
 349             JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 350             JNU_ThrowInternalError(env, "Message not posted, native event queue may be full.");
 351         }
 352     }
 353 
 354    // cause the message pump thread to synchronously synchronize on the handle
 355 
 356     INLINE void WaitForSingleObject(HANDLE handle) {
 357         SendMessage(WM_AWT_WAIT_FOR_SINGLE_OBJECT, 0, (LPARAM)handle);
 358     }
 359 
 360     /*
 361      * Create an AwtXxxx C++ component using a given factory
 362      */
 363     typedef void (*ComponentFactory)(void*, void*);
 364     static void CreateComponent(void* hComponent, void* hParent,
 365                                 ComponentFactory compFactory, BOOL isParentALocalReference=TRUE);
 366 
 367     static void DestroyComponentHWND(HWND hwnd);
 368 
 369     // constants used to PostQuitMessage
 370 
 371     static const int EXIT_ENCLOSING_LOOP;
 372     static const int EXIT_ALL_ENCLOSING_LOOPS;
 373 
 374     // ...
 375 
 376     void QuitMessageLoop(int status);
 377 
 378     UINT MessageLoop(IDLEPROC lpIdleFunc, PEEKMESSAGEPROC lpPeekMessageFunc);
 379     BOOL PumpWaitingMessages(PEEKMESSAGEPROC lpPeekMessageFunc);
 380     void PumpToDestroy(class AwtComponent* p);
 381     void ProcessMsg(MSG& msg);
 382     BOOL PreProcessMsg(MSG& msg);
 383     BOOL PreProcessMouseMsg(class AwtComponent* p, MSG& msg);
 384     BOOL PreProcessKeyMsg(class AwtComponent* p, MSG& msg);
 385 
 386     /* Create an ID which maps to an AwtObject pointer, such as a menu. */
 387     UINT CreateCmdID(AwtObject* object);
 388 
 389     // removes cmd id mapping
 390     void RemoveCmdID(UINT id);
 391 
 392     /* Return the AwtObject associated with its ID. */
 393     AwtObject* LookupCmdID(UINT id);
 394 
 395     /* Return the current application icon. */
 396     HICON GetAwtIcon();
 397     HICON GetAwtIconSm();
 398 
 399     // Calculate a wave-like value out of the integer 'value' and
 400     // the specified period.
 401     // The argument 'value' is an integer 0, 1, 2, ... *infinity*.
 402     //
 403     // Examples:
 404     //    Period == 3
 405     //    Generated sequence: 0 1 2 1 0 .....
 406     //
 407     //    Period == 4
 408     //    Generated sequence: 0 1 2 3 2 1 0 .....
 409     static inline UINT CalculateWave(UINT value, const UINT period) {
 410         if (period < 2) {
 411             return 0;
 412         }
 413         // -2 is necessary to avoid repeating extreme values (0 and period-1)
 414         value %= period * 2 -2;
 415         if (value >= period) {
 416             value = period * 2 -2 - value;
 417         }
 418         return value;
 419     }
 420 
 421     HICON GetSecurityWarningIcon(UINT index, UINT w, UINT h);
 422 
 423     /* Turns on/off dialog modality for the system. */
 424     INLINE AwtDialog* SetModal(AwtDialog* frame) {
 425         AwtDialog* previousDialog = m_pModalDialog;
 426         m_pModalDialog = frame;
 427         return previousDialog;
 428     };
 429     INLINE void ResetModal(AwtDialog* oldFrame) { m_pModalDialog = oldFrame; };
 430     INLINE BOOL IsModal() { return (m_pModalDialog != NULL); };
 431     INLINE AwtDialog* GetModalDialog(void) { return m_pModalDialog; };
 432 
 433     /* Stops the current message pump (normally a modal dialog pump) */
 434     INLINE void StopMessagePump() { m_breakOnError = TRUE; }
 435 
 436     /* Debug settings */
 437     INLINE void SetVerbose(long flag)   { m_verbose = (flag != 0); }
 438     INLINE void SetVerify(long flag)    { m_verifyComponents = (flag != 0); }
 439     INLINE void SetBreak(long flag)     { m_breakOnError = (flag != 0); }
 440     INLINE void SetHeapCheck(long flag);
 441 
 442     static void SetBusy(BOOL busy);
 443 
 444     /* Set and get the default input method Window handler. */
 445     INLINE void SetInputMethodWindow(HWND inputMethodHWnd) { m_inputMethodHWnd = inputMethodHWnd; }
 446     INLINE HWND GetInputMethodWindow() { return m_inputMethodHWnd; }
 447 
 448     static VOID CALLBACK PrimaryIdleFunc();
 449     static VOID CALLBACK SecondaryIdleFunc();
 450     static BOOL CALLBACK CommonPeekMessageFunc(MSG& msg);
 451     static BOOL activateKeyboardLayout(HKL hkl);
 452 
 453     HANDLE m_waitEvent;
 454     volatile DWORD eventNumber;
 455     volatile BOOL isInDoDragDropLoop;
 456 private:
 457     HWND CreateToolkitWnd(LPCTSTR name);
 458 
 459     BOOL m_localPump;
 460     DWORD m_mainThreadId;
 461     HWND m_toolkitHWnd;
 462     HWND m_inputMethodHWnd;
 463     BOOL m_verbose;
 464     BOOL m_isActive; // set to FALSE at beginning of Dispose
 465     BOOL m_isDisposed; // set to TRUE at end of Dispose
 466     BOOL m_areExtraMouseButtonsEnabled;
 467 
 468     typedef BOOL (WINAPI *GetPointerInfoHandleFunc)(UINT32 pointerID, POINTER_INFO *pointerInfo);
 469 
 470     BOOL m_isWin8OrLater;
 471     GetPointerInfoHandleFunc m_pGetPointerInfoHandle;
 472 
 473     BOOL m_vmSignalled; // set to TRUE if QUERYENDSESSION has successfully
 474                         // raised SIGTERM
 475 
 476     BOOL m_verifyComponents;
 477     BOOL m_breakOnError;
 478 
 479     BOOL  m_breakMessageLoop;
 480     UINT  m_messageLoopResult;
 481 
 482     class AwtComponent* m_lastMouseOver;
 483     BOOL                m_mouseDown;
 484 
 485     HHOOK m_hGetMessageHook;
 486     HHOOK m_hMouseLLHook;
 487     UINT_PTR  m_timer;
 488 
 489     class AwtCmdIDList* m_cmdIDs;
 490     BYTE                m_lastKeyboardState[KB_STATE_SIZE];
 491     CriticalSection     m_lockKB;
 492 
 493     static AwtToolkit theInstance;
 494 
 495     /* The current modal dialog frame (normally NULL). */
 496     AwtDialog* m_pModalDialog;
 497 
 498     /* The WToolkit peer instance */
 499     jobject m_peer;
 500 
 501     HMODULE m_dllHandle;  /* The module handle. */
 502 
 503     CriticalSection m_Sync;
 504 
 505 /* track display changes - used by palette-updating code.
 506    This is a workaround for a windows bug that prevents
 507    WM_PALETTECHANGED event from occurring immediately after
 508    a WM_DISPLAYCHANGED event.
 509   */
 510 private:
 511     BOOL m_displayChanged;  /* Tracks displayChanged events */
 512     // 0 means we are not embedded.
 513     DWORD m_embedderProcessID;
 514 
 515 public:
 516     BOOL HasDisplayChanged() { return m_displayChanged; }
 517     void ResetDisplayChanged() { m_displayChanged = FALSE; }
 518     void RegisterEmbedderProcessId(HWND);
 519     BOOL IsEmbedderProcessId(const DWORD processID) const
 520     {
 521         return m_embedderProcessID && (processID == m_embedderProcessID);
 522     }
 523 
 524  private:
 525     static JNIEnv *m_env;
 526     static DWORD m_threadId;
 527  public:
 528     static void SetEnv(JNIEnv *env);
 529     static JNIEnv* GetEnv();
 530 
 531     static BOOL GetScreenInsets(int screenNum, RECT * rect);
 532 
 533     // If the DWM is active, this function uses
 534     // DwmGetWindowAttribute()/DWMWA_EXTENDED_FRAME_BOUNDS.
 535     // Otherwise, fall back to regular ::GetWindowRect().
 536     // See 6711576 for more details.
 537     static void GetWindowRect(HWND hWnd, LPRECT lpRect);
 538 
 539  private:
 540     // The window handle of a toplevel window last seen under the mouse cursor.
 541     // See MouseLowLevelHook() for details.
 542     HWND m_lastWindowUnderMouse;
 543  public:
 544     HWND GetWindowUnderMouse() { return m_lastWindowUnderMouse; }
 545 
 546     void InstallMouseLowLevelHook();
 547     void UninstallMouseLowLevelHook();
 548 
 549 
 550 /* AWT preloading (early Toolkit thread start)
 551  */
 552 public:
 553     /* Toolkit preload action class.
 554      * Preload actions should be registered with
 555      * AwtToolkit::getInstance().GetPreloadThread().AddAction().
 556      * AwtToolkit thread calls InitImpl method at the beghining
 557      * and CleanImpl(false) before exiting for all registered actions.
 558      * If an application provides own Toolkit thread
 559      * (sun.awt.windows.WToolkit.embeddedInit), the thread calls Clean(true)
 560      * for each action.
 561      */
 562     class PreloadThread;    // forward declaration
 563     class PreloadAction {
 564         friend class PreloadThread;
 565     public:
 566         PreloadAction() : initThreadId(0), pNext(NULL) {}
 567         virtual ~PreloadAction() {}
 568 
 569     protected:
 570         // called by PreloadThread or as result
 571         // of EnsureInited() call (on Toolkit thread!).
 572         virtual void InitImpl() = 0;
 573 
 574         // called by PreloadThread (before exiting).
 575         // reInit == false: normal shutdown;
 576         // reInit == true: PreloadThread is shutting down due external
 577         //   Toolkit thread was provided.
 578         virtual void CleanImpl(bool reInit) = 0;
 579 
 580     public:
 581         // Initialized the action on the Toolkit thread if not yet initialized.
 582         bool EnsureInited();
 583 
 584         // returns thread ID which the action was inited on (0 if not inited)
 585         DWORD GetInitThreadID();
 586 
 587         // Allows to deinitialize action earlier.
 588         // The method must be called on the Toolkit thread only.
 589         // returns true on success,
 590         //         false if the action was inited on other thread.
 591         bool Clean();
 592 
 593     private:
 594         unsigned initThreadId;
 595         // lock for Init/Clean
 596         CriticalSection initLock;
 597 
 598         // Chain support (for PreloadThread)
 599         PreloadAction *pNext;   // for action chain used by PreloadThread
 600         void SetNext(PreloadAction *pNext) { this->pNext = pNext; }
 601         PreloadAction *GetNext() { return pNext; }
 602 
 603         // wrapper for AwtToolkit::InvokeFunction
 604         static void InitWrapper(void *param);
 605 
 606         void Init();
 607         void Clean(bool reInit);
 608 
 609     };
 610 
 611     /** Toolkit preload thread class.
 612      */
 613     class PreloadThread {
 614     public:
 615         PreloadThread();
 616         ~PreloadThread();
 617 
 618         // adds action & start the thread if not yet started
 619         bool AddAction(PreloadAction *pAction);
 620 
 621         // sets termination flag; returns true if the thread is running.
 622         // wrongThread specifies cause of the termination:
 623         //   false means termination on the application shutdown;
 624         // wrongThread is used as reInit parameter for action cleanup.
 625         bool Terminate(bool wrongThread);
 626         bool InvokeAndTerminate(void(_cdecl *fn)(void *), void *param);
 627 
 628         // waits for the thread completion;
 629         // use the method after Terminate() only if Terminate() returned true
 630         INLINE void Wait4Finish() {
 631             ::WaitForSingleObject(hFinished, INFINITE);
 632         }
 633 
 634         INLINE unsigned GetThreadId() {
 635             CriticalSection::Lock lock(threadLock);
 636             return threadId;
 637         }
 638         INLINE bool IsWrongThread() {
 639             CriticalSection::Lock lock(threadLock);
 640             return wrongThread;
 641         }
 642         // returns true if the current thread is "preload" thread
 643         bool OnPreloadThread();
 644 
 645     private:
 646         // data access lock
 647         CriticalSection threadLock;
 648 
 649         // the thread status
 650         enum Status {
 651             None = -1,      // initial
 652             Preloading = 0, // preloading in progress
 653             RunningToolkit, // Running as Toolkit thread
 654             Cleaning,       // exited from Toolkit thread proc, cleaning
 655             Finished        //
 656         } status;
 657 
 658         // "wrong thread" flag
 659         bool wrongThread;
 660 
 661         // thread proc (calls (this)param->ThreadProc())
 662         static unsigned WINAPI StaticThreadProc(void *param);
 663         unsigned ThreadProc();
 664 
 665         INLINE void AwakeThread() {
 666             ::SetEvent(hAwake);
 667         }
 668 
 669         // if threadId != 0 -> we are running
 670         unsigned threadId;
 671         // ThreadProc sets the event on exit
 672         HANDLE hFinished;
 673         // ThreadProc waits on the event for NewAction/Terminate/InvokeAndTerminate
 674         HANDLE hAwake;
 675 
 676         // function/param to invoke (InvokeAndTerminate)
 677         // if execFunc == NULL => just terminate
 678         void(_cdecl *execFunc)(void *);
 679         void *execParam;
 680 
 681         // action chain
 682         PreloadAction *pActionChain;
 683         PreloadAction *pLastProcessedAction;
 684 
 685         // returns next action in the list (NULL if no more actions)
 686         PreloadAction* GetNextAction();
 687 
 688     };
 689 
 690     INLINE PreloadThread& GetPreloadThread() { return preloadThread; }
 691 
 692 private:
 693     PreloadThread preloadThread;
 694 
 695 };
 696 
 697 
 698 /*  creates an instance of T and assigns it to the argument, but only if
 699     the argument is initially NULL. Supposed to be thread-safe.
 700     returns the new value of the argument. I'm not using volatile here
 701     as InterlockedCompareExchange ensures volatile semantics
 702     and acquire/release.
 703     The function is useful when used with static POD NULL-initialized
 704     pointers, as they are guaranteed to be NULL before any dynamic
 705     initialization takes place. This function turns such a pointer
 706     into a thread-safe singleton, working regardless of dynamic
 707     initialization order. Destruction problem is not solved,
 708     we don't need it here.
 709 */
 710 
 711 template<typename T> inline T* SafeCreate(T* &pArg) {
 712     /*  this implementation has no locks, it just destroys the object if it
 713         fails to be the first to init. another way would be using a special
 714         flag pointer value to mark the pointer as "being initialized". */
 715     T* pTemp = (T*)InterlockedCompareExchangePointer((void**)&pArg, NULL, NULL);
 716     if (pTemp != NULL) return pTemp;
 717     T* pNew = new T;
 718     pTemp = (T*)InterlockedCompareExchangePointer((void**)&pArg, pNew, NULL);
 719     if (pTemp != NULL) {
 720         // we failed it - another thread has already initialized pArg
 721         delete pNew;
 722         return pTemp;
 723     } else {
 724         return pNew;
 725     }
 726 }
 727 
 728 #endif /* AWT_TOOLKIT_H */