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