KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > swt > widgets > Display


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.swt.widgets;
12
13
14 import org.eclipse.swt.internal.*;
15 import org.eclipse.swt.internal.win32.*;
16 import org.eclipse.swt.*;
17 import org.eclipse.swt.graphics.*;
18
19 /**
20  * Instances of this class are responsible for managing the
21  * connection between SWT and the underlying operating
22  * system. Their most important function is to implement
23  * the SWT event loop in terms of the platform event model.
24  * They also provide various methods for accessing information
25  * about the operating system, and have overall control over
26  * the operating system resources which SWT allocates.
27  * <p>
28  * Applications which are built with SWT will <em>almost always</em>
29  * require only a single display. In particular, some platforms
30  * which SWT supports will not allow more than one <em>active</em>
31  * display. In other words, some platforms do not support
32  * creating a new display if one already exists that has not been
33  * sent the <code>dispose()</code> message.
34  * <p>
35  * In SWT, the thread which creates a <code>Display</code>
36  * instance is distinguished as the <em>user-interface thread</em>
37  * for that display.
38  * </p>
39  * The user-interface thread for a particular display has the
40  * following special attributes:
41  * <ul>
42  * <li>
43  * The event loop for that display must be run from the thread.
44  * </li>
45  * <li>
46  * Some SWT API methods (notably, most of the public methods in
47  * <code>Widget</code> and its subclasses), may only be called
48  * from the thread. (To support multi-threaded user-interface
49  * applications, class <code>Display</code> provides inter-thread
50  * communication methods which allow threads other than the
51  * user-interface thread to request that it perform operations
52  * on their behalf.)
53  * </li>
54  * <li>
55  * The thread is not allowed to construct other
56  * <code>Display</code>s until that display has been disposed.
57  * (Note that, this is in addition to the restriction mentioned
58  * above concerning platform support for multiple displays. Thus,
59  * the only way to have multiple simultaneously active displays,
60  * even on platforms which support it, is to have multiple threads.)
61  * </li>
62  * </ul>
63  * Enforcing these attributes allows SWT to be implemented directly
64  * on the underlying operating system's event model. This has
65  * numerous benefits including smaller footprint, better use of
66  * resources, safer memory management, clearer program logic,
67  * better performance, and fewer overall operating system threads
68  * required. The down side however, is that care must be taken
69  * (only) when constructing multi-threaded applications to use the
70  * inter-thread communication mechanisms which this class provides
71  * when required.
72  * </p><p>
73  * All SWT API methods which may only be called from the user-interface
74  * thread are distinguished in their documentation by indicating that
75  * they throw the "<code>ERROR_THREAD_INVALID_ACCESS</code>"
76  * SWT exception.
77  * </p>
78  * <dl>
79  * <dt><b>Styles:</b></dt>
80  * <dd>(none)</dd>
81  * <dt><b>Events:</b></dt>
82  * <dd>Close, Dispose, Settings</dd>
83  * </dl>
84  * <p>
85  * IMPORTANT: This class is <em>not</em> intended to be subclassed.
86  * </p>
87  * @see #syncExec
88  * @see #asyncExec
89  * @see #wake
90  * @see #readAndDispatch
91  * @see #sleep
92  * @see Device#dispose
93  */

94
95 public class Display extends Device {
96
97     /**
98      * the handle to the OS message queue
99      * (Warning: This field is platform dependent)
100      * <p>
101      * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT
102      * public API. It is marked public only so that it can be shared
103      * within the packages provided by SWT. It is not available on all
104      * platforms and should never be accessed from application code.
105      * </p>
106      */

107     public MSG msg = new MSG ();
108     
109     /* Windows and Events */
110     Event [] eventQueue;
111     Callback windowCallback;
112     int windowProc, threadId;
113     TCHAR windowClass, windowShadowClass;
114     static int WindowClassCount;
115     static final String JavaDoc WindowName = "SWT_Window"; //$NON-NLS-1$
116
static final String JavaDoc WindowShadowName = "SWT_WindowShadow"; //$NON-NLS-1$
117
EventTable eventTable, filterTable;
118
119     /* Widget Table */
120     int [] indexTable;
121     Control lastControl, lastGetControl;
122     int freeSlot, lastHwnd, lastGetHwnd;
123     Control [] controlTable;
124     static final int GROW_SIZE = 1024;
125     static final int SWT_OBJECT_INDEX;
126     static final boolean USE_PROPERTY = !OS.IsWinCE;
127     static {
128         if (USE_PROPERTY) {
129             SWT_OBJECT_INDEX = OS.GlobalAddAtom (new TCHAR (0, "SWT_OBJECT_INDEX", true)); //$NON-NLS-1$
130
} else {
131             SWT_OBJECT_INDEX = 0;
132         }
133     }
134     
135     /* Startup info */
136     static STARTUPINFO lpStartupInfo;
137     static {
138         if (!OS.IsWinCE) {
139             lpStartupInfo = new STARTUPINFO ();
140             lpStartupInfo.cb = STARTUPINFO.sizeof;
141             OS.GetStartupInfo (lpStartupInfo);
142         }
143     }
144     
145     /* XP Themes */
146     int hButtonTheme, hEditTheme, hExplorerBarTheme, hScrollBarTheme, hTabTheme;
147     static final char [] BUTTON = new char [] {'B', 'U', 'T', 'T', 'O', 'N', 0};
148     static final char [] EDIT = new char [] {'E', 'D', 'I', 'T', 0};
149     static final char [] EXPLORER = new char [] {'E', 'X', 'P', 'L', 'O', 'R', 'E', 'R', 0};
150     static final char [] EXPLORERBAR = new char [] {'E', 'X', 'P', 'L', 'O', 'R', 'E', 'R', 'B', 'A', 'R', 0};
151     static final char [] SCROLLBAR = new char [] {'S', 'C', 'R', 'O', 'L', 'L', 'B', 'A', 'R', 0};
152     static final char [] LISTVIEW = new char [] {'L', 'I', 'S', 'T', 'V', 'I', 'E', 'W', 0};
153     static final char [] TAB = new char [] {'T', 'A', 'B', 0};
154     static final char [] TREEVIEW = new char [] {'T', 'R', 'E', 'E', 'V', 'I', 'E', 'W', 0};
155     
156     /* Focus */
157     int focusEvent;
158     Control focusControl;
159     
160     /* Menus */
161     Menu [] bars, popups;
162     MenuItem [] items;
163     
164     /*
165     * The start value for WM_COMMAND id's.
166     * Windows reserves the values 0..100.
167     *
168     * The SmartPhone SWT resource file reserves
169     * the values 101..107.
170     */

171     static final int ID_START = 108;
172     
173     /* Filter Hook */
174     Callback msgFilterCallback;
175     int msgFilterProc, filterHook;
176     MSG hookMsg = new MSG ();
177     boolean runDragDrop = true;
178     
179     /* Idle Hook */
180     Callback foregroundIdleCallback;
181     int foregroundIdleProc, idleHook;
182     
183     /* Message Hook and Embedding */
184     boolean ignoreNextKey;
185     Callback getMsgCallback, embeddedCallback;
186     int getMsgProc, msgHook, embeddedHwnd, embeddedProc;
187     static final String JavaDoc AWT_WINDOW_CLASS = "SunAwtWindow";
188     static final short [] ACCENTS = new short [] {'~', '`', '\'', '^', '"'};
189
190     /* Sync/Async Widget Communication */
191     Synchronizer synchronizer = new Synchronizer (this);
192     boolean runMessages = true, runMessagesInIdle = false;
193     static final String JavaDoc RUN_MESSAGES_IN_IDLE_KEY = "org.eclipse.swt.internal.win32.runMessagesInIdle"; //$NON-NLS-1$
194
Thread JavaDoc thread;
195
196     /* Display Shutdown */
197     Runnable JavaDoc [] disposeList;
198     
199     /* System Tray */
200     Tray tray;
201     int nextTrayId;
202     
203     /* Timers */
204     int [] timerIds;
205     Runnable JavaDoc [] timerList;
206     int nextTimerId = SETTINGS_ID + 1;
207     static final int SETTINGS_ID = 100;
208     static final int SETTINGS_DELAY = 2000;
209     
210     /* Keyboard and Mouse */
211     RECT clickRect;
212     int clickCount, lastTime, lastButton, lastClickHwnd;
213     int lastKey, lastAscii, lastMouse;
214     boolean lastVirtual, lastNull, lastDead;
215     byte [] keyboard = new byte [256];
216     boolean accelKeyHit, mnemonicKeyHit;
217     boolean lockActiveWindow, captureChanged, xMouse;
218     
219     /* Tool Tips */
220     int nextToolTipId;
221     
222     /* MDI */
223     boolean ignoreRestoreFocus;
224     Control lastHittestControl;
225     int lastHittest;
226     
227     /* Message Only Window */
228     Callback messageCallback;
229     int hwndMessage, messageProc;
230     
231     /* System Resources */
232     LOGFONT lfSystemFont;
233     Font systemFont;
234     Image errorImage, infoImage, questionImage, warningIcon;
235     Cursor [] cursors = new Cursor [SWT.CURSOR_HAND + 1];
236     Resource [] resources;
237     static final int RESOURCE_SIZE = 1 + 4 + SWT.CURSOR_HAND + 1;
238
239     /* ImageList Cache */
240     ImageList[] imageList, toolImageList, toolHotImageList, toolDisabledImageList;
241
242     /* Custom Colors for ChooseColor */
243     int lpCustColors;
244
245     /* Sort Indicators */
246     Image upArrow, downArrow;
247     
248     /* Table */
249     char [] tableBuffer;
250     
251     /* Display Data */
252     Object JavaDoc data;
253     String JavaDoc [] keys;
254     Object JavaDoc [] values;
255     
256     /* Key Mappings */
257     static final int [] [] KeyTable = {
258         
259         /* Keyboard and Mouse Masks */
260         {OS.VK_MENU, SWT.ALT},
261         {OS.VK_SHIFT, SWT.SHIFT},
262         {OS.VK_CONTROL, SWT.CONTROL},
263 // {OS.VK_????, SWT.COMMAND},
264

265         /* NOT CURRENTLY USED */
266 // {OS.VK_LBUTTON, SWT.BUTTON1},
267
// {OS.VK_MBUTTON, SWT.BUTTON3},
268
// {OS.VK_RBUTTON, SWT.BUTTON2},
269

270         /* Non-Numeric Keypad Keys */
271         {OS.VK_UP, SWT.ARROW_UP},
272         {OS.VK_DOWN, SWT.ARROW_DOWN},
273         {OS.VK_LEFT, SWT.ARROW_LEFT},
274         {OS.VK_RIGHT, SWT.ARROW_RIGHT},
275         {OS.VK_PRIOR, SWT.PAGE_UP},
276         {OS.VK_NEXT, SWT.PAGE_DOWN},
277         {OS.VK_HOME, SWT.HOME},
278         {OS.VK_END, SWT.END},
279         {OS.VK_INSERT, SWT.INSERT},
280
281         /* Virtual and Ascii Keys */
282         {OS.VK_BACK, SWT.BS},
283         {OS.VK_RETURN, SWT.CR},
284         {OS.VK_DELETE, SWT.DEL},
285         {OS.VK_ESCAPE, SWT.ESC},
286         {OS.VK_RETURN, SWT.LF},
287         {OS.VK_TAB, SWT.TAB},
288     
289         /* Functions Keys */
290         {OS.VK_F1, SWT.F1},
291         {OS.VK_F2, SWT.F2},
292         {OS.VK_F3, SWT.F3},
293         {OS.VK_F4, SWT.F4},
294         {OS.VK_F5, SWT.F5},
295         {OS.VK_F6, SWT.F6},
296         {OS.VK_F7, SWT.F7},
297         {OS.VK_F8, SWT.F8},
298         {OS.VK_F9, SWT.F9},
299         {OS.VK_F10, SWT.F10},
300         {OS.VK_F11, SWT.F11},
301         {OS.VK_F12, SWT.F12},
302         {OS.VK_F13, SWT.F13},
303         {OS.VK_F14, SWT.F14},
304         {OS.VK_F15, SWT.F15},
305         
306         /* Numeric Keypad Keys */
307         {OS.VK_MULTIPLY, SWT.KEYPAD_MULTIPLY},
308         {OS.VK_ADD, SWT.KEYPAD_ADD},
309         {OS.VK_RETURN, SWT.KEYPAD_CR},
310         {OS.VK_SUBTRACT, SWT.KEYPAD_SUBTRACT},
311         {OS.VK_DECIMAL, SWT.KEYPAD_DECIMAL},
312         {OS.VK_DIVIDE, SWT.KEYPAD_DIVIDE},
313         {OS.VK_NUMPAD0, SWT.KEYPAD_0},
314         {OS.VK_NUMPAD1, SWT.KEYPAD_1},
315         {OS.VK_NUMPAD2, SWT.KEYPAD_2},
316         {OS.VK_NUMPAD3, SWT.KEYPAD_3},
317         {OS.VK_NUMPAD4, SWT.KEYPAD_4},
318         {OS.VK_NUMPAD5, SWT.KEYPAD_5},
319         {OS.VK_NUMPAD6, SWT.KEYPAD_6},
320         {OS.VK_NUMPAD7, SWT.KEYPAD_7},
321         {OS.VK_NUMPAD8, SWT.KEYPAD_8},
322         {OS.VK_NUMPAD9, SWT.KEYPAD_9},
323 // {OS.VK_????, SWT.KEYPAD_EQUAL},
324

325         /* Other keys */
326         {OS.VK_CAPITAL, SWT.CAPS_LOCK},
327         {OS.VK_NUMLOCK, SWT.NUM_LOCK},
328         {OS.VK_SCROLL, SWT.SCROLL_LOCK},
329         {OS.VK_PAUSE, SWT.PAUSE},
330         {OS.VK_CANCEL, SWT.BREAK},
331         {OS.VK_SNAPSHOT, SWT.PRINT_SCREEN},
332 // {OS.VK_????, SWT.HELP},
333

334     };
335
336     /* Multiple Displays */
337     static Display Default;
338     static Display [] Displays = new Display [4];
339
340     /* Multiple Monitors */
341     Monitor[] monitors = null;
342     int monitorCount = 0;
343     
344     /* Modality */
345     Shell [] modalShells;
346     Shell modalDialogShell;
347     static boolean TrimEnabled = false;
348
349     /* Private SWT Window Messages */
350     static final int SWT_GETACCELCOUNT = OS.WM_APP;
351     static final int SWT_GETACCEL = OS.WM_APP + 1;
352     static final int SWT_KEYMSG = OS.WM_APP + 2;
353     static final int SWT_DESTROY = OS.WM_APP + 3;
354     static final int SWT_TRAYICONMSG = OS.WM_APP + 4;
355     static final int SWT_NULL = OS.WM_APP + 5;
356     static final int SWT_RUNASYNC = OS.WM_APP + 6;
357     static int SWT_TASKBARCREATED;
358     static int SWT_RESTORECARET;
359     
360     /* Workaround for Adobe Reader 7.0 */
361     int hitCount;
362     
363     /* Package Name */
364     static final String JavaDoc PACKAGE_PREFIX = "org.eclipse.swt.widgets."; //$NON-NLS-1$
365
/*
366     * This code is intentionally commented. In order
367     * to support CLDC, .class cannot be used because
368     * it does not compile on some Java compilers when
369     * they are targeted for CLDC.
370     */

371 // static {
372
// String name = Display.class.getName ();
373
// int index = name.lastIndexOf ('.');
374
// PACKAGE_PREFIX = name.substring (0, index + 1);
375
// }
376

377     /*
378     * TEMPORARY CODE. Install the runnable that
379     * gets the current display. This code will
380     * be removed in the future.
381     */

382     static {
383         DeviceFinder = new Runnable JavaDoc () {
384             public void run () {
385                 Device device = getCurrent ();
386                 if (device == null) {
387                     device = getDefault ();
388                 }
389                 setDevice (device);
390             }
391         };
392     }
393
394 /*
395 * TEMPORARY CODE.
396 */

397 static void setDevice (Device device) {
398     CurrentDevice = device;
399 }
400     
401 /**
402  * Constructs a new instance of this class.
403  * <p>
404  * Note: The resulting display is marked as the <em>current</em>
405  * display. If this is the first display which has been
406  * constructed since the application started, it is also
407  * marked as the <em>default</em> display.
408  * </p>
409  *
410  * @exception SWTException <ul>
411  * <li>ERROR_THREAD_INVALID_ACCESS - if called from a thread that already created an existing display</li>
412  * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
413  * </ul>
414  *
415  * @see #getCurrent
416  * @see #getDefault
417  * @see Widget#checkSubclass
418  * @see Shell
419  */

420 public Display () {
421     this (null);
422 }
423
424 /**
425  * Constructs a new instance of this class using the parameter.
426  *
427  * @param data the device data
428  */

429 public Display (DeviceData data) {
430     super (data);
431 }
432
433 Control _getFocusControl () {
434     return findControl (OS.GetFocus ());
435 }
436
437 void addBar (Menu menu) {
438     if (bars == null) bars = new Menu [4];
439     int length = bars.length;
440     for (int i=0; i<length; i++) {
441         if (bars [i] == menu) return;
442     }
443     int index = 0;
444     while (index < length) {
445         if (bars [index] == null) break;
446         index++;
447     }
448     if (index == length) {
449         Menu [] newBars = new Menu [length + 4];
450         System.arraycopy (bars, 0, newBars, 0, length);
451         bars = newBars;
452     }
453     bars [index] = menu;
454 }
455
456 void addControl (int handle, Control control) {
457     if (handle == 0) return;
458     if (freeSlot == -1) {
459         int length = (freeSlot = indexTable.length) + GROW_SIZE;
460         int [] newIndexTable = new int [length];
461         Control [] newControlTable = new Control [length];
462         System.arraycopy (indexTable, 0, newIndexTable, 0, freeSlot);
463         System.arraycopy (controlTable, 0, newControlTable, 0, freeSlot);
464         for (int i=freeSlot; i<length-1; i++) newIndexTable [i] = i + 1;
465         newIndexTable [length - 1] = -1;
466         indexTable = newIndexTable;
467         controlTable = newControlTable;
468     }
469     if (USE_PROPERTY) {
470         OS.SetProp (handle, SWT_OBJECT_INDEX, freeSlot + 1);
471     } else {
472         OS.SetWindowLong (handle, OS.GWL_USERDATA, freeSlot + 1);
473     }
474     int oldSlot = freeSlot;
475     freeSlot = indexTable [oldSlot];
476     indexTable [oldSlot] = -2;
477     controlTable [oldSlot] = control;
478 }
479
480 /**
481  * Adds the listener to the collection of listeners who will
482  * be notified when an event of the given type occurs anywhere
483  * in a widget. The event type is one of the event constants
484  * defined in class <code>SWT</code>. When the event does occur,
485  * the listener is notified by sending it the <code>handleEvent()</code>
486  * message.
487  * <p>
488  * Setting the type of an event to <code>SWT.None</code> from
489  * within the <code>handleEvent()</code> method can be used to
490  * change the event type and stop subsequent Java listeners
491  * from running. Because event filters run before other listeners,
492  * event filters can both block other listeners and set arbitrary
493  * fields within an event. For this reason, event filters are both
494  * powerful and dangerous. They should generally be avoided for
495  * performance, debugging and code maintenance reasons.
496  * </p>
497  *
498  * @param eventType the type of event to listen for
499  * @param listener the listener which should be notified when the event occurs
500  *
501  * @exception IllegalArgumentException <ul>
502  * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
503  * </ul>
504  * @exception SWTException <ul>
505  * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
506  * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
507  * </ul>
508  *
509  * @see Listener
510  * @see SWT
511  * @see #removeFilter
512  * @see #removeListener
513  *
514  * @since 3.0
515  */

516 public void addFilter (int eventType, Listener listener) {
517     checkDevice ();
518     if (listener == null) error (SWT.ERROR_NULL_ARGUMENT);
519     if (filterTable == null) filterTable = new EventTable ();
520     filterTable.hook (eventType, listener);
521 }
522
523 /**
524  * Adds the listener to the collection of listeners who will
525  * be notified when an event of the given type occurs. The event
526  * type is one of the event constants defined in class <code>SWT</code>.
527  * When the event does occur in the display, the listener is notified by
528  * sending it the <code>handleEvent()</code> message.
529  *
530  * @param eventType the type of event to listen for
531  * @param listener the listener which should be notified when the event occurs
532  *
533  * @exception IllegalArgumentException <ul>
534  * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
535  * </ul>
536  * @exception SWTException <ul>
537  * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
538  * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
539  * </ul>
540  *
541  * @see Listener
542  * @see SWT
543  * @see #removeListener
544  *
545  * @since 2.0
546  */

547 public void addListener (int eventType, Listener listener) {
548     checkDevice ();
549     if (listener == null) error (SWT.ERROR_NULL_ARGUMENT);
550     if (eventTable == null) eventTable = new EventTable ();
551     eventTable.hook (eventType, listener);
552 }
553
554 void addMenuItem (MenuItem item) {
555     if (items == null) items = new MenuItem [64];
556     for (int i=0; i<items.length; i++) {
557         if (items [i] == null) {
558             item.id = i + ID_START;
559             items [i] = item;
560             return;
561         }
562     }
563     item.id = items.length + ID_START;
564     MenuItem [] newItems = new MenuItem [items.length + 64];
565     newItems [items.length] = item;
566     System.arraycopy (items, 0, newItems, 0, items.length);
567     items = newItems;
568 }
569
570 void addPopup (Menu menu) {
571     if (popups == null) popups = new Menu [4];
572     int length = popups.length;
573     for (int i=0; i<length; i++) {
574         if (popups [i] == menu) return;
575     }
576     int index = 0;
577     while (index < length) {
578         if (popups [index] == null) break;
579         index++;
580     }
581     if (index == length) {
582         Menu [] newPopups = new Menu [length + 4];
583         System.arraycopy (popups, 0, newPopups, 0, length);
584         popups = newPopups;
585     }
586     popups [index] = menu;
587 }
588
589 int asciiKey (int key) {
590     if (OS.IsWinCE) return 0;
591     
592     /* Get the current keyboard. */
593     for (int i=0; i<keyboard.length; i++) keyboard [i] = 0;
594     if (!OS.GetKeyboardState (keyboard)) return 0;
595         
596     /* Translate the key to ASCII or UNICODE using the virtual keyboard */
597     if (OS.IsUnicode) {
598         char [] result = new char [1];
599         if (OS.ToUnicode (key, key, keyboard, result, 1, 0) == 1) return result [0];
600     } else {
601         short [] result = new short [1];
602         if (OS.ToAscii (key, key, keyboard, result, 0) == 1) return result [0];
603     }
604     return 0;
605 }
606
607 /**
608  * Causes the <code>run()</code> method of the runnable to
609  * be invoked by the user-interface thread at the next
610  * reasonable opportunity. The caller of this method continues
611  * to run in parallel, and is not notified when the
612  * runnable has completed. Specifying <code>null</code> as the
613  * runnable simply wakes the user-interface thread when run.
614  * <p>
615  * Note that at the time the runnable is invoked, widgets
616  * that have the receiver as their display may have been
617  * disposed. Therefore, it is necessary to check for this
618  * case inside the runnable before accessing the widget.
619  * </p>
620  *
621  * @param runnable code to run on the user-interface thread or <code>null</code>
622  *
623  * @exception SWTException <ul>
624  * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
625  * </ul>
626  *
627  * @see #syncExec
628  */

629 public void asyncExec (Runnable JavaDoc runnable) {
630     if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED);
631     synchronizer.asyncExec (runnable);
632 }
633
634 /**
635  * Causes the system hardware to emit a short sound
636  * (if it supports this capability).
637  *
638  * @exception SWTException <ul>
639  * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
640  * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
641  * </ul>
642  */

643 public void beep () {
644     checkDevice ();
645     OS.MessageBeep (OS.MB_OK);
646 }
647
648 /**
649  * Checks that this class can be subclassed.
650  * <p>
651  * IMPORTANT: See the comment in <code>Widget.checkSubclass()</code>.
652  * </p>
653  *
654  * @exception SWTException <ul>
655  * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
656  * </ul>
657  *
658  * @see Widget#checkSubclass
659  */

660 protected void checkSubclass () {
661     if (!isValidClass (getClass ())) error (SWT.ERROR_INVALID_SUBCLASS);
662 }
663
664 protected void checkDevice () {
665     if (thread == null) error (SWT.ERROR_WIDGET_DISPOSED);
666     if (thread != Thread.currentThread ()) error (SWT.ERROR_THREAD_INVALID_ACCESS);
667     if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED);
668 }
669
670 static synchronized void checkDisplay (Thread JavaDoc thread, boolean multiple) {
671     for (int i=0; i<Displays.length; i++) {
672         if (Displays [i] != null) {
673             if (!multiple) SWT.error (SWT.ERROR_NOT_IMPLEMENTED, null, " [multiple displays]");
674             if (Displays [i].thread == thread) SWT.error (SWT.ERROR_THREAD_INVALID_ACCESS);
675         }
676     }
677 }
678
679 void clearModal (Shell shell) {
680     if (modalShells == null) return;
681     int index = 0, length = modalShells.length;
682     while (index < length) {
683         if (modalShells [index] == shell) break;
684         if (modalShells [index] == null) return;
685         index++;
686     }
687     if (index == length) return;
688     System.arraycopy (modalShells, index + 1, modalShells, index, --length - index);
689     modalShells [length] = null;
690     if (index == 0 && modalShells [0] == null) modalShells = null;
691     Shell [] shells = getShells ();
692     for (int i=0; i<shells.length; i++) shells [i].updateModal ();
693 }
694
695 int controlKey (int key) {
696     int upper = OS.CharUpper ((short) key);
697     if (64 <= upper && upper <= 95) return upper & 0xBF;
698     return key;
699 }
700
701 /**
702  * Requests that the connection between SWT and the underlying
703  * operating system be closed.
704  *
705  * @exception SWTException <ul>
706  * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
707  * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
708  * </ul>
709  *
710  * @see Device#dispose
711  *
712  * @since 2.0
713  */

714 public void close () {
715     checkDevice ();
716     Event event = new Event ();
717     sendEvent (SWT.Close, event);
718     if (event.doit) dispose ();
719 }
720
721 /**
722  * Creates the device in the operating system. If the device
723  * does not have a handle, this method may do nothing depending
724  * on the device.
725  * <p>
726  * This method is called before <code>init</code>.
727  * </p>
728  *
729  * @param data the DeviceData which describes the receiver
730  *
731  * @see #init
732  */

733 protected void create (DeviceData data) {
734     checkSubclass ();
735     checkDisplay (thread = Thread.currentThread (), true);
736     createDisplay (data);
737     register (this);
738     if (Default == null) Default = this;
739 }
740
741 void createDisplay (DeviceData data) {
742 }
743
744 static int create32bitDIB (Image image) {
745     int transparentPixel = -1, alpha = -1, hMask = 0, hBitmap = 0;
746     byte[] alphaData = null;
747     switch (image.type) {
748         case SWT.ICON:
749             ICONINFO info = new ICONINFO ();
750             OS.GetIconInfo (image.handle, info);
751             hBitmap = info.hbmColor;
752             hMask = info.hbmMask;
753             break;
754         case SWT.BITMAP:
755             ImageData data = image.getImageData ();
756             hBitmap = image.handle;
757             alpha = data.alpha;
758             alphaData = data.alphaData;
759             transparentPixel = data.transparentPixel;
760             break;
761     }
762     BITMAP bm = new BITMAP ();
763     OS.GetObject (hBitmap, BITMAP.sizeof, bm);
764     int imgWidth = bm.bmWidth;
765     int imgHeight = bm.bmHeight;
766     int hDC = OS.GetDC (0);
767     int srcHdc = OS.CreateCompatibleDC (hDC);
768     int oldSrcBitmap = OS.SelectObject (srcHdc, hBitmap);
769     int memHdc = OS.CreateCompatibleDC (hDC);
770     BITMAPINFOHEADER bmiHeader = new BITMAPINFOHEADER ();
771     bmiHeader.biSize = BITMAPINFOHEADER.sizeof;
772     bmiHeader.biWidth = imgWidth;
773     bmiHeader.biHeight = -imgHeight;
774     bmiHeader.biPlanes = 1;
775     bmiHeader.biBitCount = (short)32;
776     bmiHeader.biCompression = OS.BI_RGB;
777     byte [] bmi = new byte [BITMAPINFOHEADER.sizeof];
778     OS.MoveMemory (bmi, bmiHeader, BITMAPINFOHEADER.sizeof);
779     int [] pBits = new int [1];
780     int memDib = OS.CreateDIBSection (0, bmi, OS.DIB_RGB_COLORS, pBits, 0, 0);
781     if (memDib == 0) SWT.error (SWT.ERROR_NO_HANDLES);
782     int oldMemBitmap = OS.SelectObject (memHdc, memDib);
783     BITMAP dibBM = new BITMAP ();
784     OS.GetObject (memDib, BITMAP.sizeof, dibBM);
785     int sizeInBytes = dibBM.bmWidthBytes * dibBM.bmHeight;
786     OS.BitBlt (memHdc, 0, 0, imgWidth, imgHeight, srcHdc, 0, 0, OS.SRCCOPY);
787     byte red = 0, green = 0, blue = 0;
788     if (transparentPixel != -1) {
789         if (bm.bmBitsPixel <= 8) {
790             byte [] color = new byte [4];
791             OS.GetDIBColorTable (srcHdc, transparentPixel, 1, color);
792             blue = color [0];
793             green = color [1];
794             red = color [2];
795         } else {
796             switch (bm.bmBitsPixel) {
797                 case 16:
798                     blue = (byte)((transparentPixel & 0x1F) << 3);
799                     green = (byte)((transparentPixel & 0x3E0) >> 2);
800                     red = (byte)((transparentPixel & 0x7C00) >> 7);
801                     break;
802                 case 24:
803                     blue = (byte)((transparentPixel & 0xFF0000) >> 16);
804                     green = (byte)((transparentPixel & 0xFF00) >> 8);
805                     red = (byte)(transparentPixel & 0xFF);
806                     break;
807                 case 32:
808                     blue = (byte)((transparentPixel & 0xFF000000) >>> 24);
809                     green = (byte)((transparentPixel & 0xFF0000) >> 16);
810                     red = (byte)((transparentPixel & 0xFF00) >> 8);
811                     break;
812             }
813         }
814     }
815     byte [] srcData = new byte [sizeInBytes];
816     OS.MoveMemory (srcData, pBits [0], sizeInBytes);
817     if (hMask != 0) {
818         OS.SelectObject(srcHdc, hMask);
819         for (int y = 0, dp = 0; y < imgHeight; ++y) {
820             for (int x = 0; x < imgWidth; ++x) {
821                 if (OS.GetPixel(srcHdc, x, y) != 0) {
822                     srcData [dp + 0] = srcData [dp + 1] = srcData [dp + 2] = srcData[dp + 3] = (byte)0;
823                 } else {
824                     srcData[dp + 3] = (byte)0xFF;
825                 }
826                 dp += 4;
827             }
828         }
829     } else if (alpha != -1) {
830         for (int y = 0, dp = 0; y < imgHeight; ++y) {
831             for (int x = 0; x < imgWidth; ++x) {
832                 srcData [dp + 3] = (byte)alpha;
833                 if (srcData [dp + 3] == 0) srcData [dp + 0] = srcData [dp + 1] = srcData [dp + 2] = 0;
834                 dp += 4;
835             }
836         }
837     } else if (alphaData != null) {
838         for (int y = 0, dp = 0, ap = 0; y < imgHeight; ++y) {
839             for (int x = 0; x < imgWidth; ++x) {
840                 srcData [dp + 3] = alphaData [ap++];
841                 if (srcData [dp + 3] == 0) srcData [dp + 0] = srcData [dp + 1] = srcData [dp + 2] = 0;
842                 dp += 4;
843             }
844         }
845     } else if (transparentPixel != -1) {
846         for (int y = 0, dp = 0; y < imgHeight; ++y) {
847             for (int x = 0; x < imgWidth; ++x) {
848                 if (srcData [dp] == blue && srcData [dp + 1] == green && srcData [dp + 2] == red) {
849                     srcData [dp + 0] = srcData [dp + 1] = srcData [dp + 2] = srcData [dp + 3] = (byte)0;
850                 } else {
851                     srcData [dp + 3] = (byte)0xFF;
852                 }
853                 dp += 4;
854             }
855         }
856     } else {
857         for (int y = 0, dp = 0; y < imgHeight; ++y) {
858             for (int x = 0; x < imgWidth; ++x) {
859                 srcData [dp + 3] = (byte)0xFF;
860                 dp += 4;
861             }
862         }
863     }
864     OS.MoveMemory (pBits [0], srcData, sizeInBytes);
865     OS.SelectObject (srcHdc, oldSrcBitmap);
866     OS.SelectObject (memHdc, oldMemBitmap);
867     OS.DeleteObject (srcHdc);
868     OS.DeleteObject (memHdc);
869     OS.ReleaseDC (0, hDC);
870     if (hBitmap != image.handle && hBitmap != 0) OS.DeleteObject (hBitmap);
871     if (hMask != 0) OS.DeleteObject (hMask);
872     return memDib;
873 }
874
875 static int create32bitDIB (int hBitmap, int alpha, byte [] alphaData, int transparentPixel) {
876     BITMAP bm = new BITMAP ();
877     OS.GetObject (hBitmap, BITMAP.sizeof, bm);
878     int imgWidth = bm.bmWidth;
879     int imgHeight = bm.bmHeight;
880     int hDC = OS.GetDC (0);
881     int srcHdc = OS.CreateCompatibleDC (hDC);
882     int oldSrcBitmap = OS.SelectObject (srcHdc, hBitmap);
883     int memHdc = OS.CreateCompatibleDC (hDC);
884     BITMAPINFOHEADER bmiHeader = new BITMAPINFOHEADER ();
885     bmiHeader.biSize = BITMAPINFOHEADER.sizeof;
886     bmiHeader.biWidth = imgWidth;
887     bmiHeader.biHeight = -imgHeight;
888     bmiHeader.biPlanes = 1;
889     bmiHeader.biBitCount = (short)32;
890     bmiHeader.biCompression = OS.BI_RGB;
891     byte [] bmi = new byte [BITMAPINFOHEADER.sizeof];
892     OS.MoveMemory (bmi, bmiHeader, BITMAPINFOHEADER.sizeof);
893     int [] pBits = new int [1];
894     int memDib = OS.CreateDIBSection (0, bmi, OS.DIB_RGB_COLORS, pBits, 0, 0);
895     if (memDib == 0) SWT.error (SWT.ERROR_NO_HANDLES);
896     int oldMemBitmap = OS.SelectObject (memHdc, memDib);
897     BITMAP dibBM = new BITMAP ();
898     OS.GetObject (memDib, BITMAP.sizeof, dibBM);
899     int sizeInBytes = dibBM.bmWidthBytes * dibBM.bmHeight;
900     OS.BitBlt (memHdc, 0, 0, imgWidth, imgHeight, srcHdc, 0, 0, OS.SRCCOPY);
901     byte red = 0, green = 0, blue = 0;
902     if (transparentPixel != -1) {
903         if (bm.bmBitsPixel <= 8) {
904             byte [] color = new byte [4];
905             OS.GetDIBColorTable (srcHdc, transparentPixel, 1, color);
906             blue = color [0];
907             green = color [1];
908             red = color [2];
909         } else {
910             switch (bm.bmBitsPixel) {
911                 case 16:
912                     blue = (byte)((transparentPixel & 0x1F) << 3);
913                     green = (byte)((transparentPixel & 0x3E0) >> 2);
914                     red = (byte)((transparentPixel & 0x7C00) >> 7);
915                     break;
916                 case 24:
917                     blue = (byte)((transparentPixel & 0xFF0000) >> 16);
918                     green = (byte)((transparentPixel & 0xFF00) >> 8);
919                     red = (byte)(transparentPixel & 0xFF);
920                     break;
921                 case 32:
922                     blue = (byte)((transparentPixel & 0xFF000000) >>> 24);
923                     green = (byte)((transparentPixel & 0xFF0000) >> 16);
924                     red = (byte)((transparentPixel & 0xFF00) >> 8);
925                     break;
926             }
927         }
928     }
929     OS.SelectObject (srcHdc, oldSrcBitmap);
930     OS.SelectObject (memHdc, oldMemBitmap);
931     OS.DeleteObject (srcHdc);
932     OS.DeleteObject (memHdc);
933     OS.ReleaseDC (0, hDC);
934     byte [] srcData = new byte [sizeInBytes];
935     OS.MoveMemory (srcData, pBits [0], sizeInBytes);
936     if (alpha != -1) {
937         for (int y = 0, dp = 0; y < imgHeight; ++y) {
938             for (int x = 0; x < imgWidth; ++x) {
939                 srcData [dp + 3] = (byte)alpha;
940                 dp += 4;
941             }
942         }
943     } else if (alphaData != null) {
944         for (int y = 0, dp = 0, ap = 0; y < imgHeight; ++y) {
945             for (int x = 0; x < imgWidth; ++x) {
946                 srcData [dp + 3] = alphaData [ap++];
947                 dp += 4;
948             }
949         }
950     } else if (transparentPixel != -1) {
951         for (int y = 0, dp = 0; y < imgHeight; ++y) {
952             for (int x = 0; x < imgWidth; ++x) {
953                 if (srcData [dp] == blue && srcData [dp + 1] == green && srcData [dp + 2] == red) {
954                     srcData [dp + 3] = (byte)0;
955                 } else {
956                     srcData [dp + 3] = (byte)0xFF;
957                 }
958                 dp += 4;
959             }
960         }
961     }
962     OS.MoveMemory (pBits [0], srcData, sizeInBytes);
963     return memDib;
964 }
965
966 static Image createIcon (Image image) {
967     Device device = image.getDevice ();
968     ImageData data = image.getImageData ();
969     if (data.alpha == -1 && data.alphaData == null) {
970         ImageData mask = data.getTransparencyMask ();
971         return new Image (device, data, mask);
972     }
973     int width = data.width, height = data.height;
974     int hMask, hBitmap;
975     int hDC = device.internal_new_GC (null);
976     int dstHdc = OS.CreateCompatibleDC (hDC), oldDstBitmap;
977     if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (5, 1)) {
978         hBitmap = Display.create32bitDIB (image.handle, data.alpha, data.alphaData, data.transparentPixel);
979         hMask = OS.CreateBitmap (width, height, 1, 1, null);
980         oldDstBitmap = OS.SelectObject (dstHdc, hMask);
981         OS.PatBlt (dstHdc, 0, 0, width, height, OS.BLACKNESS);
982     } else {
983         hMask = Display.createMaskFromAlpha (data, width, height);
984         /* Icons need black pixels where the mask is transparent */
985         hBitmap = OS.CreateCompatibleBitmap (hDC, width, height);
986         oldDstBitmap = OS.SelectObject (dstHdc, hBitmap);
987         int srcHdc = OS.CreateCompatibleDC (hDC);
988         int oldSrcBitmap = OS.SelectObject (srcHdc, image.handle);
989         OS.PatBlt (dstHdc, 0, 0, width, height, OS.BLACKNESS);
990         OS.BitBlt (dstHdc, 0, 0, width, height, srcHdc, 0, 0, OS.SRCINVERT);
991         OS.SelectObject (srcHdc, hMask);
992         OS.BitBlt (dstHdc, 0, 0, width, height, srcHdc, 0, 0, OS.SRCAND);
993         OS.SelectObject (srcHdc, image.handle);
994         OS.BitBlt (dstHdc, 0, 0, width, height, srcHdc, 0, 0, OS.SRCINVERT);
995         OS.SelectObject (srcHdc, oldSrcBitmap);
996         OS.DeleteDC (srcHdc);
997     }
998     OS.SelectObject (dstHdc, oldDstBitmap);
999     OS.DeleteDC (dstHdc);
1000    device.internal_dispose_GC (hDC, null);
1001    ICONINFO info = new ICONINFO ();
1002    info.fIcon = true;
1003    info.hbmColor = hBitmap;
1004    info.hbmMask = hMask;
1005    int hIcon = OS.CreateIconIndirect (info);
1006    if (hIcon == 0) SWT.error(SWT.ERROR_NO_HANDLES);
1007    OS.DeleteObject (hBitmap);
1008    OS.DeleteObject (hMask);
1009    return Image.win32_new (device, SWT.ICON, hIcon);
1010}
1011
1012static int createMaskFromAlpha (ImageData data, int destWidth, int destHeight) {
1013    int srcWidth = data.width;
1014    int srcHeight = data.height;
1015    ImageData mask = ImageData.internal_new (srcWidth, srcHeight, 1,
1016            new PaletteData(new RGB [] {new RGB (0, 0, 0), new RGB (0xff, 0xff, 0xff)}),
1017            2, null, 1, null, null, -1, -1, -1, 0, 0, 0, 0);
1018    int ap = 0;
1019    for (int y = 0; y < mask.height; y++) {
1020        for (int x = 0; x < mask.width; x++) {
1021            mask.setPixel (x, y, (data.alphaData [ap++] & 0xff) <= 127 ? 1 : 0);
1022        }
1023    }
1024    int hMask = OS.CreateBitmap (srcWidth, srcHeight, 1, 1, mask.data);
1025    if (srcWidth != destWidth || srcHeight != destHeight) {
1026        int hdc = OS.GetDC (0);
1027        int hdc1 = OS.CreateCompatibleDC (hdc);
1028        OS.SelectObject (hdc1, hMask);
1029        int hdc2 = OS.CreateCompatibleDC (hdc);
1030        int hMask2 = OS.CreateBitmap (destWidth, destHeight, 1, 1, null);
1031        OS.SelectObject (hdc2, hMask2);
1032        if (!OS.IsWinCE) OS.SetStretchBltMode(hdc2, OS.COLORONCOLOR);
1033        OS.StretchBlt (hdc2, 0, 0, destWidth, destHeight, hdc1, 0, 0, srcWidth, srcHeight, OS.SRCCOPY);
1034        OS.DeleteDC (hdc1);
1035        OS.DeleteDC (hdc2);
1036        OS.ReleaseDC (0, hdc);
1037        OS.DeleteObject(hMask);
1038        hMask = hMask2;
1039    }
1040    return hMask;
1041}
1042
1043static synchronized void deregister (Display display) {
1044    for (int i=0; i<Displays.length; i++) {
1045        if (display == Displays [i]) Displays [i] = null;
1046    }
1047}
1048
1049/**
1050 * Destroys the device in the operating system and releases
1051 * the device's handle. If the device does not have a handle,
1052 * this method may do nothing depending on the device.
1053 * <p>
1054 * This method is called after <code>release</code>.
1055 * </p>
1056 * @see Device#dispose
1057 * @see #release
1058 */

1059protected void destroy () {
1060    if (this == Default) Default = null;
1061    deregister (this);
1062    destroyDisplay ();
1063}
1064
1065void destroyDisplay () {
1066}
1067
1068/**
1069 * Causes the <code>run()</code> method of the runnable to
1070 * be invoked by the user-interface thread just before the
1071 * receiver is disposed. Specifying a <code>null</code> runnable
1072 * is ignored.
1073 *
1074 * @param runnable code to run at dispose time.
1075 *
1076 * @exception SWTException <ul>
1077 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1078 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1079 * </ul>
1080 */

1081public void disposeExec (Runnable JavaDoc runnable) {
1082    checkDevice ();
1083    if (disposeList == null) disposeList = new Runnable JavaDoc [4];
1084    for (int i=0; i<disposeList.length; i++) {
1085        if (disposeList [i] == null) {
1086            disposeList [i] = runnable;
1087            return;
1088        }
1089    }
1090    Runnable JavaDoc [] newDisposeList = new Runnable JavaDoc [disposeList.length + 4];
1091    System.arraycopy (disposeList, 0, newDisposeList, 0, disposeList.length);
1092    newDisposeList [disposeList.length] = runnable;
1093    disposeList = newDisposeList;
1094}
1095
1096void drawMenuBars () {
1097    if (bars == null) return;
1098    for (int i=0; i<bars.length; i++) {
1099        Menu menu = bars [i];
1100        if (menu != null && !menu.isDisposed ()) menu.update ();
1101    }
1102    bars = null;
1103}
1104
1105int embeddedProc (int hwnd, int msg, int wParam, int lParam) {
1106    switch (msg) {
1107        case SWT_KEYMSG: {
1108            MSG keyMsg = new MSG ();
1109            OS.MoveMemory (keyMsg, lParam, MSG.sizeof);
1110            OS.TranslateMessage (keyMsg);
1111            OS.DispatchMessage (keyMsg);
1112            int hHeap = OS.GetProcessHeap ();
1113            OS.HeapFree (hHeap, 0, lParam);
1114            break;
1115        }
1116        case SWT_DESTROY: {
1117            OS.DestroyWindow (hwnd);
1118            if (embeddedCallback != null) embeddedCallback.dispose ();
1119            if (getMsgCallback != null) getMsgCallback.dispose ();
1120            embeddedCallback = getMsgCallback = null;
1121            embeddedProc = getMsgProc = 0;
1122            break;
1123        }
1124    }
1125    return OS.DefWindowProc (hwnd, msg, wParam, lParam);
1126}
1127
1128/**
1129 * Does whatever display specific cleanup is required, and then
1130 * uses the code in <code>SWTError.error</code> to handle the error.
1131 *
1132 * @param code the descriptive error code
1133 *
1134 * @see SWT#error(int)
1135 */

1136void error (int code) {
1137    SWT.error (code);
1138}
1139
1140boolean filterEvent (Event event) {
1141    if (filterTable != null) filterTable.sendEvent (event);
1142    return false;
1143}
1144
1145boolean filters (int eventType) {
1146    if (filterTable == null) return false;
1147    return filterTable.hooks (eventType);
1148}
1149
1150boolean filterMessage (MSG msg) {
1151    int message = msg.message;
1152    if (OS.WM_KEYFIRST <= message && message <= OS.WM_KEYLAST) {
1153        Control control = findControl (msg.hwnd);
1154        if (control != null) {
1155            if (translateAccelerator (msg, control) || translateMnemonic (msg, control) || translateTraversal (msg, control)) {
1156                lastAscii = lastKey = 0;
1157                lastVirtual = lastNull = lastDead = false;
1158                return true;
1159            }
1160        }
1161    }
1162    return false;
1163}
1164
1165Control findControl (int handle) {
1166    if (handle == 0) return null;
1167    int hwndOwner = 0;
1168    do {
1169        Control control = getControl (handle);
1170        if (control != null) return control;
1171        hwndOwner = OS.GetWindow (handle, OS.GW_OWNER);
1172        handle = OS.GetParent (handle);
1173    } while (handle != 0 && handle != hwndOwner);
1174    return null;
1175}
1176
1177/**
1178 * Given the operating system handle for a widget, returns
1179 * the instance of the <code>Widget</code> subclass which
1180 * represents it in the currently running application, if
1181 * such exists, or null if no matching widget can be found.
1182 * <p>
1183 * <b>IMPORTANT:</b> This method should not be called from
1184 * application code. The arguments are platform-specific.
1185 * </p>
1186 *
1187 * @param handle the handle for the widget
1188 * @return the SWT widget that the handle represents
1189 *
1190 * @exception SWTException <ul>
1191 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1192 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1193 * </ul>
1194 */

1195public Widget findWidget (int handle) {
1196    checkDevice ();
1197    return getControl (handle);
1198}
1199
1200/**
1201 * Given the operating system handle for a widget,
1202 * and widget-specific id, returns the instance of
1203 * the <code>Widget</code> subclass which represents
1204 * the handle/id pair in the currently running application,
1205 * if such exists, or null if no matching widget can be found.
1206 * <p>
1207 * <b>IMPORTANT:</b> This method should not be called from
1208 * application code. The arguments are platform-specific.
1209 * </p>
1210 *
1211 * @param handle the handle for the widget
1212 * @param id the id for the subwidget (usually an item)
1213 * @return the SWT widget that the handle/id pair represents
1214 *
1215 * @exception SWTException <ul>
1216 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1217 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1218 * </ul>
1219 *
1220 * @since 3.1
1221 */

1222public Widget findWidget (int handle, int id) {
1223    checkDevice ();
1224    Control control = getControl (handle);
1225    return control != null ? control.findItem (id) : null;
1226}
1227
1228/**
1229 * Given a widget and a widget-specific id, returns the
1230 * instance of the <code>Widget</code> subclass which represents
1231 * the widget/id pair in the currently running application,
1232 * if such exists, or null if no matching widget can be found.
1233 *
1234 * @param widget the widget
1235 * @param id the id for the subwidget (usually an item)
1236 * @return the SWT subwidget (usually an item) that the widget/id pair represents
1237 *
1238 * @exception SWTException <ul>
1239 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1240 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1241 * </ul>
1242 *
1243 * @since 3.3
1244 */

1245public Widget findWidget (Widget widget, int id) {
1246    checkDevice ();
1247    if (widget instanceof Control) {
1248        return findWidget (((Control) widget).handle, id);
1249    }
1250    return null;
1251}
1252
1253int foregroundIdleProc (int code, int wParam, int lParam) {
1254    if (runMessages) {
1255        if (code >= 0) {
1256            if (getMessageCount () != 0) {
1257                if (runMessagesInIdle) {
1258                    OS.PostMessage (hwndMessage, SWT_RUNASYNC, 0, 0);
1259                }
1260                wakeThread ();
1261            }
1262        }
1263    }
1264    return OS.CallNextHookEx (idleHook, code, wParam, lParam);
1265}
1266
1267/**
1268 * Returns the display which the given thread is the
1269 * user-interface thread for, or null if the given thread
1270 * is not a user-interface thread for any display. Specifying
1271 * <code>null</code> as the thread will return <code>null</code>
1272 * for the display.
1273 *
1274 * @param thread the user-interface thread
1275 * @return the display for the given thread
1276 */

1277public static synchronized Display findDisplay (Thread JavaDoc thread) {
1278    for (int i=0; i<Displays.length; i++) {
1279        Display display = Displays [i];
1280        if (display != null && display.thread == thread) {
1281            return display;
1282        }
1283    }
1284    return null;
1285}
1286
1287/**
1288 * Returns the currently active <code>Shell</code>, or null
1289 * if no shell belonging to the currently running application
1290 * is active.
1291 *
1292 * @return the active shell or null
1293 *
1294 * @exception SWTException <ul>
1295 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1296 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1297 * </ul>
1298 */

1299public Shell getActiveShell () {
1300    checkDevice ();
1301    Control control = findControl (OS.GetActiveWindow ());
1302    return control != null ? control.getShell () : null;
1303}
1304
1305/**
1306 * Returns a rectangle describing the receiver's size and location.
1307 *
1308 * @return the bounding rectangle
1309 *
1310 * @exception SWTException <ul>
1311 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1312 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1313 * </ul>
1314 */

1315public Rectangle getBounds () {
1316    checkDevice ();
1317    if (OS.GetSystemMetrics (OS.SM_CMONITORS) < 2) {
1318        int width = OS.GetSystemMetrics (OS.SM_CXSCREEN);
1319        int height = OS.GetSystemMetrics (OS.SM_CYSCREEN);
1320        return new Rectangle (0, 0, width, height);
1321    }
1322    int x = OS.GetSystemMetrics (OS.SM_XVIRTUALSCREEN);
1323    int y = OS.GetSystemMetrics (OS.SM_YVIRTUALSCREEN);
1324    int width = OS.GetSystemMetrics (OS.SM_CXVIRTUALSCREEN);
1325    int height = OS.GetSystemMetrics (OS.SM_CYVIRTUALSCREEN);
1326    return new Rectangle (x, y, width, height);
1327}
1328
1329/**
1330 * Returns the display which the currently running thread is
1331 * the user-interface thread for, or null if the currently
1332 * running thread is not a user-interface thread for any display.
1333 *
1334 * @return the current display
1335 */

1336public static synchronized Display getCurrent () {
1337    return findDisplay (Thread.currentThread ());
1338}
1339
1340int getClickCount (int type, int button, int hwnd, int lParam) {
1341    switch (type) {
1342        case SWT.MouseDown:
1343            int doubleClick = OS.GetDoubleClickTime ();
1344            if (clickRect == null) clickRect = new RECT ();
1345            int deltaTime = Math.abs (lastTime - getLastEventTime ());
1346            POINT pt = new POINT ();
1347            pt.x = (short) (lParam & 0xFFFF);
1348            pt.y = (short) (lParam >> 16);
1349            if (lastClickHwnd == hwnd && lastButton == button && (deltaTime <= doubleClick) && OS.PtInRect (clickRect, pt)) {
1350                clickCount++;
1351            } else {
1352                clickCount = 1;
1353            }
1354            //FALL THROUGH
1355
case SWT.MouseDoubleClick:
1356            lastButton = button;
1357            lastClickHwnd = hwnd;
1358            lastTime = getLastEventTime ();
1359            int xInset = OS.GetSystemMetrics (OS.SM_CXDOUBLECLK) / 2;
1360            int yInset = OS.GetSystemMetrics (OS.SM_CYDOUBLECLK) / 2;
1361            int x = (short) (lParam & 0xFFFF), y = (short) (lParam >> 16);
1362            OS.SetRect (clickRect, x - xInset, y - yInset, x + xInset, y + yInset);
1363            //FALL THROUGH
1364
case SWT.MouseUp:
1365            return clickCount;
1366    }
1367    return 0;
1368}
1369
1370/**
1371 * Returns a rectangle which describes the area of the
1372 * receiver which is capable of displaying data.
1373 *
1374 * @return the client area
1375 *
1376 * @exception SWTException <ul>
1377 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1378 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1379 * </ul>
1380 *
1381 * @see #getBounds
1382 */

1383public Rectangle getClientArea () {
1384    checkDevice ();
1385    if (OS.GetSystemMetrics (OS.SM_CMONITORS) < 2) {
1386        RECT rect = new RECT ();
1387        OS.SystemParametersInfo (OS.SPI_GETWORKAREA, 0, rect, 0);
1388        int width = rect.right - rect.left;
1389        int height = rect.bottom - rect.top;
1390        return new Rectangle (rect.left, rect.top, width, height);
1391    }
1392    int x = OS.GetSystemMetrics (OS.SM_XVIRTUALSCREEN);
1393    int y = OS.GetSystemMetrics (OS.SM_YVIRTUALSCREEN);
1394    int width = OS.GetSystemMetrics (OS.SM_CXVIRTUALSCREEN);
1395    int height = OS.GetSystemMetrics (OS.SM_CYVIRTUALSCREEN);
1396    return new Rectangle (x, y, width, height);
1397}
1398
1399Control getControl (int handle) {
1400    if (handle == 0) return null;
1401    if (lastControl != null && lastHwnd == handle) {
1402        return lastControl;
1403    }
1404    if (lastGetControl != null && lastGetHwnd == handle) {
1405        return lastGetControl;
1406    }
1407    int index;
1408    if (USE_PROPERTY) {
1409        index = OS.GetProp (handle, SWT_OBJECT_INDEX) - 1;
1410    } else {
1411        index = OS.GetWindowLong (handle, OS.GWL_USERDATA) - 1;
1412    }
1413    if (0 <= index && index < controlTable.length) {
1414        Control control = controlTable [index];
1415        /*
1416        * Because GWL_USERDATA can be used by native widgets that
1417        * do not belong to SWT, it is possible that GWL_USERDATA
1418        * could return an index that is in the range of the table,
1419        * but was not put there by SWT. Therefore, it is necessary
1420        * to check the handle of the control that is in the table
1421        * against the handle that provided the GWL_USERDATA.
1422        */

1423        if (control != null && control.checkHandle (handle)) {
1424            lastGetHwnd = handle;
1425            lastGetControl = control;
1426            return control;
1427        }
1428    }
1429    return null;
1430}
1431
1432/**
1433 * Returns the control which the on-screen pointer is currently
1434 * over top of, or null if it is not currently over one of the
1435 * controls built by the currently running application.
1436 *
1437 * @return the control under the cursor
1438 *
1439 * @exception SWTException <ul>
1440 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1441 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1442 * </ul>
1443 */

1444public Control getCursorControl () {
1445    checkDevice ();
1446    POINT pt = new POINT ();
1447    if (!OS.GetCursorPos (pt)) return null;
1448    return findControl (OS.WindowFromPoint (pt));
1449}
1450
1451/**
1452 * Returns the location of the on-screen pointer relative
1453 * to the top left corner of the screen.
1454 *
1455 * @return the cursor location
1456 *
1457 * @exception SWTException <ul>
1458 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1459 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1460 * </ul>
1461 */

1462public Point getCursorLocation () {
1463    checkDevice ();
1464    POINT pt = new POINT ();
1465    OS.GetCursorPos (pt);
1466    return new Point (pt.x, pt.y);
1467}
1468
1469/**
1470 * Returns an array containing the recommended cursor sizes.
1471 *
1472 * @return the array of cursor sizes
1473 *
1474 * @exception SWTException <ul>
1475 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1476 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1477 * </ul>
1478 *
1479 * @since 3.0
1480 */

1481public Point [] getCursorSizes () {
1482    checkDevice ();
1483    return new Point [] {
1484        new Point (OS.GetSystemMetrics (OS.SM_CXCURSOR), OS.GetSystemMetrics (OS.SM_CYCURSOR))};
1485}
1486
1487/**
1488 * Returns the default display. One is created (making the
1489 * thread that invokes this method its user-interface thread)
1490 * if it did not already exist.
1491 *
1492 * @return the default display
1493 */

1494public static synchronized Display getDefault () {
1495    if (Default == null) Default = new Display ();
1496    return Default;
1497}
1498
1499static boolean isValidClass (Class JavaDoc clazz) {
1500    String JavaDoc name = clazz.getName ();
1501    int index = name.lastIndexOf ('.');
1502    return name.substring (0, index + 1).equals (PACKAGE_PREFIX);
1503}
1504
1505/**
1506 * Returns the application defined property of the receiver
1507 * with the specified name, or null if it has not been set.
1508 * <p>
1509 * Applications may have associated arbitrary objects with the
1510 * receiver in this fashion. If the objects stored in the
1511 * properties need to be notified when the display is disposed
1512 * of, it is the application's responsibility to provide a
1513 * <code>disposeExec()</code> handler which does so.
1514 * </p>
1515 *
1516 * @param key the name of the property
1517 * @return the value of the property or null if it has not been set
1518 *
1519 * @exception IllegalArgumentException <ul>
1520 * <li>ERROR_NULL_ARGUMENT - if the key is null</li>
1521 * </ul>
1522 * @exception SWTException <ul>
1523 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1524 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1525 * </ul>
1526 *
1527 * @see #setData(String, Object)
1528 * @see #disposeExec(Runnable)
1529 */

1530public Object JavaDoc getData (String JavaDoc key) {
1531    checkDevice ();
1532    if (key == null) error (SWT.ERROR_NULL_ARGUMENT);
1533    if (key.equals (RUN_MESSAGES_IN_IDLE_KEY)) {
1534        return new Boolean JavaDoc (runMessagesInIdle);
1535    }
1536    if (keys == null) return null;
1537    for (int i=0; i<keys.length; i++) {
1538        if (keys [i].equals (key)) return values [i];
1539    }
1540    return null;
1541}
1542
1543/**
1544 * Returns the application defined, display specific data
1545 * associated with the receiver, or null if it has not been
1546 * set. The <em>display specific data</em> is a single,
1547 * unnamed field that is stored with every display.
1548 * <p>
1549 * Applications may put arbitrary objects in this field. If
1550 * the object stored in the display specific data needs to
1551 * be notified when the display is disposed of, it is the
1552 * application's responsibility to provide a
1553 * <code>disposeExec()</code> handler which does so.
1554 * </p>
1555 *
1556 * @return the display specific data
1557 *
1558 * @exception SWTException <ul>
1559 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1560 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1561 * </ul>
1562 *
1563 * @see #setData(Object)
1564 * @see #disposeExec(Runnable)
1565 */

1566public Object JavaDoc getData () {
1567    checkDevice ();
1568    return data;
1569}
1570
1571/**
1572 * Returns the button dismissal alignment, one of <code>LEFT</code> or <code>RIGHT</code>.
1573 * The button dismissal alignment is the ordering that should be used when positioning the
1574 * default dismissal button for a dialog. For example, in a dialog that contains an OK and
1575 * CANCEL button, on platforms where the button dismissal alignment is <code>LEFT</code>, the
1576 * button ordering should be OK/CANCEL. When button dismissal alignment is <code>RIGHT</code>,
1577 * the button ordering should be CANCEL/OK.
1578 *
1579 * @return the button dismissal order
1580 *
1581 * @exception SWTException <ul>
1582 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1583 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1584 * </ul>
1585 *
1586 * @since 2.1
1587 */

1588public int getDismissalAlignment () {
1589    checkDevice ();
1590    return SWT.LEFT;
1591}
1592
1593
1594/**
1595 * Returns the longest duration, in milliseconds, between
1596 * two mouse button clicks that will be considered a
1597 * <em>double click</em> by the underlying operating system.
1598 *
1599 * @return the double click time
1600 *
1601 * @exception SWTException <ul>
1602 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1603 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1604 * </ul>
1605 */

1606public int getDoubleClickTime () {
1607    checkDevice ();
1608    return OS.GetDoubleClickTime ();
1609}
1610
1611/**
1612 * Returns the control which currently has keyboard focus,
1613 * or null if keyboard events are not currently going to
1614 * any of the controls built by the currently running
1615 * application.
1616 *
1617 * @return the control under the cursor
1618 *
1619 * @exception SWTException <ul>
1620 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1621 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1622 * </ul>
1623 */

1624public Control getFocusControl () {
1625    checkDevice ();
1626    if (focusControl != null && !focusControl.isDisposed ()) {
1627        return focusControl;
1628    }
1629    return _getFocusControl ();
1630}
1631
1632String JavaDoc getFontName (LOGFONT logFont) {
1633    char[] chars;
1634    if (OS.IsUnicode) {
1635        chars = ((LOGFONTW)logFont).lfFaceName;
1636    } else {
1637        chars = new char[OS.LF_FACESIZE];
1638        byte[] bytes = ((LOGFONTA)logFont).lfFaceName;
1639        OS.MultiByteToWideChar (OS.CP_ACP, OS.MB_PRECOMPOSED, bytes, bytes.length, chars, chars.length);
1640    }
1641    int index = 0;
1642    while (index < chars.length) {
1643        if (chars [index] == 0) break;
1644        index++;
1645    }
1646    return new String JavaDoc (chars, 0, index);
1647}
1648
1649/**
1650 * Returns true when the high contrast mode is enabled.
1651 * Otherwise, false is returned.
1652 * <p>
1653 * Note: This operation is a hint and is not supported on
1654 * platforms that do not have this concept.
1655 * </p>
1656 *
1657 * @return the high contrast mode
1658 *
1659 * @exception SWTException <ul>
1660 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1661 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1662 * </ul>
1663 *
1664 * @since 3.0
1665 */

1666public boolean getHighContrast () {
1667    checkDevice ();
1668    if (OS.IsWinCE) return false;
1669    HIGHCONTRAST pvParam = new HIGHCONTRAST ();
1670    pvParam.cbSize = HIGHCONTRAST.sizeof;
1671    OS.SystemParametersInfo (OS.SPI_GETHIGHCONTRAST, 0, pvParam, 0);
1672    return (pvParam.dwFlags & OS.HCF_HIGHCONTRASTON) != 0;
1673}
1674
1675/**
1676 * Returns the maximum allowed depth of icons on this display, in bits per pixel.
1677 * On some platforms, this may be different than the actual depth of the display.
1678 *
1679 * @return the maximum icon depth
1680 *
1681 * @exception SWTException <ul>
1682 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1683 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1684 * </ul>
1685 *
1686 * @see Device#getDepth
1687 */

1688public int getIconDepth () {
1689    checkDevice ();
1690    if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (5, 1)) {
1691        if (getDepth () >= 24) return 32;
1692    }
1693
1694    /* Use the character encoding for the default locale */
1695    TCHAR buffer1 = new TCHAR (0, "Control Panel\\Desktop\\WindowMetrics", true); //$NON-NLS-1$
1696

1697    int [] phkResult = new int [1];
1698    int result = OS.RegOpenKeyEx (OS.HKEY_CURRENT_USER, buffer1, 0, OS.KEY_READ, phkResult);
1699    if (result != 0) return 4;
1700    int depth = 4;
1701    int [] lpcbData = new int [1];
1702    
1703    /* Use the character encoding for the default locale */
1704    TCHAR buffer2 = new TCHAR (0, "Shell Icon BPP", true); //$NON-NLS-1$
1705
result = OS.RegQueryValueEx (phkResult [0], buffer2, 0, null, (TCHAR) null, lpcbData);
1706    if (result == 0) {
1707        TCHAR lpData = new TCHAR (0, lpcbData [0] / TCHAR.sizeof);
1708        result = OS.RegQueryValueEx (phkResult [0], buffer2, 0, null, lpData, lpcbData);
1709        if (result == 0) {
1710            try {
1711                depth = Integer.parseInt (lpData.toString (0, lpData.strlen ()));
1712            } catch (NumberFormatException JavaDoc e) {}
1713        }
1714    }
1715    OS.RegCloseKey (phkResult [0]);
1716    return depth;
1717}
1718
1719/**
1720 * Returns an array containing the recommended icon sizes.
1721 *
1722 * @return the array of icon sizes
1723 *
1724 * @exception SWTException <ul>
1725 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
1726 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
1727 * </ul>
1728 *
1729 * @see Decorations#setImages(Image[])
1730 *
1731 * @since 3.0
1732 */

1733public Point [] getIconSizes () {
1734    checkDevice ();
1735    return new Point [] {
1736        new Point (OS.GetSystemMetrics (OS.SM_CXSMICON), OS.GetSystemMetrics (OS.SM_CYSMICON)),
1737        new Point (OS.GetSystemMetrics (OS.SM_CXICON), OS.GetSystemMetrics (OS.SM_CYICON)),
1738    };
1739}
1740
1741ImageList getImageList (int style, int width, int height) {
1742    if (imageList == null) imageList = new ImageList [4];
1743    
1744    int i = 0;
1745    int length = imageList.length;
1746    while (i < length) {
1747        ImageList list = imageList [i];
1748        if (list == null) break;
1749        Point size = list.getImageSize();
1750        if (size.x == width && size.y == height) {
1751            if (list.getStyle () == style) {
1752                list.addRef();
1753                return list;
1754            }
1755        }
1756        i++;
1757    }
1758    
1759    if (i == length) {
1760        ImageList [] newList = new ImageList [length + 4];
1761        System.arraycopy (imageList, 0, newList, 0, length);
1762        imageList = newList;
1763    }
1764    
1765    ImageList list = new ImageList (style);
1766    imageList [i] = list;
1767    list.addRef();
1768    return list;
1769}
1770
1771ImageList getImageListToolBar (int style, int width, int height) {
1772    if (toolImageList == null) toolImageList = new ImageList [4];
1773    
1774    int i = 0;
1775    int length = toolImageList.length;
1776    while (i < length) {
1777        ImageList list = toolImageList [i];
1778        if (list == null) break;
1779        Point size = list.getImageSize();
1780        if (size.x == width && size.y == height) {
1781            if (list.getStyle () == style) {
1782                list.addRef();
1783                return list;
1784            }
1785        }
1786        i++;
1787    }
1788    
1789    if (i == length) {
1790        ImageList [] newList = new ImageList [length + 4];
1791        System.arraycopy (toolImageList, 0, newList, 0, length);
1792        toolImageList = newList;
1793    }
1794    
1795    ImageList list = new ImageList (style);
1796    toolImageList [i] = list;
1797    list.addRef();
1798    return list;
1799}
1800
1801ImageList getImageListToolBarDisabled (int style, int width, int height) {
1802    if (toolDisabledImageList == null) toolDisabledImageList = new ImageList [4];
1803    
1804    int i = 0;
1805    int length = toolDisabledImageList.length;
1806    while (i < length) {
1807        ImageList list = toolDisabledImageList [i];
1808        if (list == null) break;
1809        Point size = list.getImageSize();
1810        if (size.x == width && size.y == height) {
1811            if (list.getStyle () == style) {
1812                list.addRef();
1813                return list;
1814            }
1815        }
1816        i++;
1817    }
1818    
1819    if (i == length) {
1820        ImageList [] newList = new ImageList [length + 4];
1821        System.arraycopy (toolDisabledImageList, 0, newList, 0, length);
1822        toolDisabledImageList = newList;
1823    }
1824    
1825    ImageList list = new ImageList (style);
1826    toolDisabledImageList [i] = list;
1827    list.addRef();
1828    return list;
1829}
1830
1831ImageList getImageListToolBarHot (int style, int width, int height) {
1832    if (toolHotImageList == null) toolHotImageList = new ImageList [4];
1833    
1834    int i = 0;
1835    int length = toolHotImageList.length;
1836    while (i < length) {
1837        ImageList list = toolHotImageList [i];
1838        if (list == null) break;
1839        Point size = list.getImageSize();
1840        if (size.x == width && size.y == height) {
1841            if (list.getStyle () == style) {
1842                list.addRef();
1843                return list;
1844            }
1845        }
1846        i++;
1847    }
1848    
1849    if (i == length) {
1850        ImageList [] newList = new ImageList [length + 4];
1851        System.arraycopy (toolHotImageList, 0, newList, 0, length);
1852        toolHotImageList = newList;
1853    }
1854    
1855    ImageList list = new ImageList (style);
1856    toolHotImageList [i] = list;
1857    list.addRef();
1858    return list;
1859}
1860
1861int getLastEventTime () {
1862    return OS.IsWinCE ? OS.GetTickCount () : OS.GetMessageTime ();
1863}
1864
1865MenuItem getMenuItem (int id) {
1866    if (items == null) return null;
1867    id = id - ID_START;
1868    if (0 <= id && id < items.length) return items [id];
1869    return null;
1870}
1871
1872int getMessageCount () {
1873    return synchronizer.getMessageCount ();
1874}
1875
1876
1877Shell getModalShell () {
1878    if (modalShells == null) return null;
1879    int index = modalShells.length;
1880    while (--index >= 0) {
1881        Shell shell = modalShells [index];
1882        if (shell != null) return shell;
1883    }
1884    return null;
1885}
1886
1887Shell getModalDialogShell () {
1888    if (modalDialogShell != null && modalDialogShell.isDisposed ()) modalDialogShell = null;
1889    return modalDialogShell;
1890}
1891
1892/**
1893 * Returns an array of monitors attached to the device.
1894 *
1895 * @return the array of monitors
1896 *
1897 * @since 3.0
1898 */

1899public Monitor [] getMonitors () {
1900    checkDevice ();
1901    if (OS.IsWinCE || OS.WIN32_VERSION < OS.VERSION (4, 10)) {
1902        return new Monitor [] {getPrimaryMonitor ()};
1903    }
1904    monitors = new Monitor [4];
1905    Callback callback = new Callback (this, "monitorEnumProc", 4); //$NON-NLS-1$
1906
int lpfnEnum = callback.getAddress ();
1907    if (lpfnEnum == 0) SWT.error (SWT.ERROR_NO_MORE_CALLBACKS);
1908    OS.EnumDisplayMonitors (0, null, lpfnEnum, 0);
1909    callback.dispose ();
1910    Monitor [] result = new Monitor [monitorCount];
1911    System.arraycopy (monitors, 0, result, 0, monitorCount);
1912    monitors = null;
1913    monitorCount = 0;
1914    return result;
1915}
1916
1917int getMsgProc (int code, int wParam, int lParam) {
1918    if (embeddedHwnd == 0) {
1919        int hInstance = OS.GetModuleHandle (null);
1920        embeddedHwnd = OS.CreateWindowEx (0,
1921            windowClass,
1922            null,
1923            OS.WS_OVERLAPPED,
1924            0, 0, 0, 0,
1925            0,
1926            0,
1927            hInstance,
1928            null);
1929        embeddedCallback = new Callback (this, "embeddedProc", 4); //$NON-NLS-1$
1930
embeddedProc = embeddedCallback.getAddress ();
1931        if (embeddedProc == 0) error (SWT.ERROR_NO_MORE_CALLBACKS);
1932        OS.SetWindowLong (embeddedHwnd, OS.GWL_WNDPROC, embeddedProc);
1933    }
1934    if (code >= 0 && wParam != OS.PM_NOREMOVE) {
1935        MSG msg = new MSG ();
1936        OS.MoveMemory (msg, lParam, MSG.sizeof);
1937        switch (msg.message) {
1938            case OS.WM_KEYDOWN:
1939            case OS.WM_KEYUP:
1940            case OS.WM_SYSKEYDOWN:
1941            case OS.WM_SYSKEYUP: {
1942                Control control = findControl (msg.hwnd);
1943                if (control != null) {
1944                    int hHeap = OS.GetProcessHeap ();
1945                    int keyMsg = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, MSG.sizeof);
1946                    OS.MoveMemory (keyMsg, msg, MSG.sizeof);
1947                    OS.PostMessage (hwndMessage, SWT_KEYMSG, wParam, keyMsg);
1948                    msg.message = OS.WM_NULL;
1949                    OS.MoveMemory (lParam, msg, MSG.sizeof);
1950                }
1951            }
1952        }
1953    }
1954    return OS.CallNextHookEx (msgHook, code, wParam, lParam);
1955}
1956
1957/**
1958 * Returns the primary monitor for that device.
1959 *
1960 * @return the primary monitor
1961 *
1962 * @since 3.0
1963 */

1964public Monitor getPrimaryMonitor () {
1965    checkDevice ();
1966    if (OS.IsWinCE || OS.WIN32_VERSION < OS.VERSION (4, 10)) {
1967        Monitor monitor = new Monitor();
1968        int width = OS.GetSystemMetrics (OS.SM_CXSCREEN);
1969        int height = OS.GetSystemMetrics (OS.SM_CYSCREEN);
1970        monitor.width = width;
1971        monitor.height = height;
1972        RECT rect = new RECT ();
1973        OS.SystemParametersInfo (OS.SPI_GETWORKAREA, 0, rect, 0);
1974        monitor.clientX = rect.left;
1975        monitor.clientY = rect.top;
1976        monitor.clientWidth = rect.right - rect.left;
1977        monitor.clientHeight = rect.bottom - rect.top;
1978        return monitor;
1979    }
1980    monitors = new Monitor [4];
1981    Callback callback = new Callback (this, "monitorEnumProc", 4); //$NON-NLS-1$
1982
int lpfnEnum = callback.getAddress ();
1983    if (lpfnEnum == 0) SWT.error (SWT.ERROR_NO_MORE_CALLBACKS);
1984    OS.EnumDisplayMonitors (0, null, lpfnEnum, 0);
1985    callback.dispose ();
1986    Monitor result = null;
1987    MONITORINFO lpmi = new MONITORINFO ();
1988    lpmi.cbSize = MONITORINFO.sizeof;
1989    for (int i = 0; i < monitorCount; i++) {
1990        Monitor monitor = monitors [i];
1991        OS.GetMonitorInfo (monitors [i].handle, lpmi);
1992        if ((lpmi.dwFlags & OS.MONITORINFOF_PRIMARY) != 0) {
1993            result = monitor;
1994            break;
1995        }
1996    }
1997    monitors = null;
1998    monitorCount = 0;
1999    return result;
2000}
2001
2002/**
2003 * Returns a (possibly empty) array containing all shells which have
2004 * not been disposed and have the receiver as their display.
2005 *
2006 * @return the receiver's shells
2007 *
2008 * @exception SWTException <ul>
2009 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
2010 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2011 * </ul>
2012 */

2013public Shell [] getShells () {
2014    checkDevice ();
2015    int index = 0;
2016    Shell [] result = new Shell [16];
2017    for (int i = 0; i < controlTable.length; i++) {
2018        Control control = controlTable [i];
2019        if (control != null && control instanceof Shell) {
2020            int j = 0;
2021            while (j < index) {
2022                if (result [j] == control) break;
2023                j++;
2024            }
2025            if (j == index) {
2026                if (index == result.length) {
2027                    Shell [] newResult = new Shell [index + 16];
2028                    System.arraycopy (result, 0, newResult, 0, index);
2029                    result = newResult;
2030                }
2031                result [index++] = (Shell) control;
2032            }
2033        }
2034    }
2035    if (index == result.length) return result;
2036    Shell [] newResult = new Shell [index];
2037    System.arraycopy (result, 0, newResult, 0, index);
2038    return newResult;
2039}
2040
2041Image getSortImage (int direction) {
2042    switch (direction) {
2043        case SWT.UP: {
2044            if (upArrow != null) return upArrow;
2045            Color c1 = getSystemColor (SWT.COLOR_WIDGET_NORMAL_SHADOW);
2046            Color c2 = getSystemColor (SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW);
2047            Color c3 = getSystemColor (SWT.COLOR_WIDGET_BACKGROUND);
2048            PaletteData palette = new PaletteData(new RGB [] {c1.getRGB (), c2.getRGB (), c3.getRGB ()});
2049            ImageData imageData = new ImageData (8, 8, 4, palette);
2050            imageData.transparentPixel = 2;
2051            upArrow = new Image (this, imageData);
2052            GC gc = new GC (upArrow);
2053            gc.setBackground (c3);
2054            gc.fillRectangle (0, 0, 8, 8);
2055            gc.setForeground (c1);
2056            int [] line1 = new int [] {0,6, 1,6, 1,4, 2,4, 2,2, 3,2, 3,1};
2057            gc.drawPolyline (line1);
2058            gc.setForeground (c2);
2059            int [] line2 = new int [] {0,7, 7,7, 7,6, 6,6, 6,4, 5,4, 5,2, 4,2, 4,1};
2060            gc.drawPolyline (line2);
2061            gc.dispose ();
2062            return upArrow;
2063        }
2064        case SWT.DOWN: {
2065            if (downArrow != null) return downArrow;
2066            Color c1 = getSystemColor (SWT.COLOR_WIDGET_NORMAL_SHADOW);
2067            Color c2 = getSystemColor (SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW);
2068            Color c3 = getSystemColor (SWT.COLOR_WIDGET_BACKGROUND);
2069            PaletteData palette = new PaletteData (new RGB [] {c1.getRGB (), c2.getRGB (), c3.getRGB ()});
2070            ImageData imageData = new ImageData (8, 8, 4, palette);
2071            imageData.transparentPixel = 2;
2072            downArrow = new Image (this, imageData);
2073            GC gc = new GC (downArrow);
2074            gc.setBackground (c3);
2075            gc.fillRectangle (0, 0, 8, 8);
2076            gc.setForeground (c1);
2077            int [] line1 = new int [] {7,0, 0,0, 0,1, 1,1, 1,3, 2,3, 2,5, 3,5, 3,6};
2078            gc.drawPolyline (line1);
2079            gc.setForeground (c2);
2080            int [] line2 = new int [] {4,6, 4,5, 5,5, 5,3, 6,3, 6,1, 7,1};
2081            gc.drawPolyline (line2);
2082            gc.dispose ();
2083            return downArrow;
2084        }
2085    }
2086    return null;
2087}
2088
2089/**
2090 * Returns the thread that has invoked <code>syncExec</code>
2091 * or null if no such runnable is currently being invoked by
2092 * the user-interface thread.
2093 * <p>
2094 * Note: If a runnable invoked by asyncExec is currently
2095 * running, this method will return null.
2096 * </p>
2097 *
2098 * @return the receiver's sync-interface thread
2099 *
2100 * @exception SWTException <ul>
2101 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2102 * </ul>
2103 */

2104public Thread JavaDoc getSyncThread () {
2105    if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED);
2106    return synchronizer.syncThread;
2107}
2108
2109/**
2110 * Returns the matching standard color for the given
2111 * constant, which should be one of the color constants
2112 * specified in class <code>SWT</code>. Any value other
2113 * than one of the SWT color constants which is passed
2114 * in will result in the color black. This color should
2115 * not be free'd because it was allocated by the system,
2116 * not the application.
2117 *
2118 * @param id the color constant
2119 * @return the matching color
2120 *
2121 * @exception SWTException <ul>
2122 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
2123 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2124 * </ul>
2125 *
2126 * @see SWT
2127 */

2128public Color getSystemColor (int id) {
2129    checkDevice ();
2130    int pixel = 0x00000000;
2131    switch (id) {
2132        case SWT.COLOR_WIDGET_DARK_SHADOW: pixel = OS.GetSysColor (OS.COLOR_3DDKSHADOW); break;
2133        case SWT.COLOR_WIDGET_NORMAL_SHADOW: pixel = OS.GetSysColor (OS.COLOR_3DSHADOW); break;
2134        case SWT.COLOR_WIDGET_LIGHT_SHADOW: pixel = OS.GetSysColor (OS.COLOR_3DLIGHT); break;
2135        case SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW: pixel = OS.GetSysColor (OS.COLOR_3DHIGHLIGHT); break;
2136        case SWT.COLOR_WIDGET_BACKGROUND: pixel = OS.GetSysColor (OS.COLOR_3DFACE); break;
2137        case SWT.COLOR_WIDGET_BORDER: pixel = OS.GetSysColor (OS.COLOR_WINDOWFRAME); break;
2138        case SWT.COLOR_WIDGET_FOREGROUND:
2139        case SWT.COLOR_LIST_FOREGROUND: pixel = OS.GetSysColor (OS.COLOR_WINDOWTEXT); break;
2140        case SWT.COLOR_LIST_BACKGROUND: pixel = OS.GetSysColor (OS.COLOR_WINDOW); break;
2141        case SWT.COLOR_LIST_SELECTION: pixel = OS.GetSysColor (OS.COLOR_HIGHLIGHT); break;
2142        case SWT.COLOR_LIST_SELECTION_TEXT: pixel = OS.GetSysColor (OS.COLOR_HIGHLIGHTTEXT);break;
2143        case SWT.COLOR_INFO_FOREGROUND: pixel = OS.GetSysColor (OS.COLOR_INFOTEXT); break;
2144        case SWT.COLOR_INFO_BACKGROUND: pixel = OS.GetSysColor (OS.COLOR_INFOBK); break;
2145        case SWT.COLOR_TITLE_FOREGROUND: pixel = OS.GetSysColor (OS.COLOR_CAPTIONTEXT); break;
2146        case SWT.COLOR_TITLE_BACKGROUND: pixel = OS.GetSysColor (OS.COLOR_ACTIVECAPTION); break;
2147        case SWT.COLOR_TITLE_BACKGROUND_GRADIENT:
2148            pixel = OS.GetSysColor (OS.COLOR_GRADIENTACTIVECAPTION);
2149            if (pixel == 0) pixel = OS.GetSysColor (OS.COLOR_ACTIVECAPTION);
2150            break;
2151        case SWT.COLOR_TITLE_INACTIVE_FOREGROUND: pixel = OS.GetSysColor (OS.COLOR_INACTIVECAPTIONTEXT); break;
2152        case SWT.COLOR_TITLE_INACTIVE_BACKGROUND: pixel = OS.GetSysColor (OS.COLOR_INACTIVECAPTION); break;
2153        case SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT:
2154            pixel = OS.GetSysColor (OS.COLOR_GRADIENTINACTIVECAPTION);
2155            if (pixel == 0) pixel = OS.GetSysColor (OS.COLOR_INACTIVECAPTION);
2156            break;
2157        default:
2158            return super.getSystemColor (id);
2159    }
2160    return Color.win32_new (this, pixel);
2161}
2162
2163/**
2164 * Returns the matching standard platform cursor for the given
2165 * constant, which should be one of the cursor constants
2166 * specified in class <code>SWT</code>. This cursor should
2167 * not be free'd because it was allocated by the system,
2168 * not the application. A value of <code>null</code> will
2169 * be returned if the supplied constant is not an SWT cursor
2170 * constant.
2171 *
2172 * @param id the SWT cursor constant
2173 * @return the corresponding cursor or <code>null</code>
2174 *
2175 * @exception SWTException <ul>
2176 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
2177 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2178 * </ul>
2179 *
2180 * @see SWT#CURSOR_ARROW
2181 * @see SWT#CURSOR_WAIT
2182 * @see SWT#CURSOR_CROSS
2183 * @see SWT#CURSOR_APPSTARTING
2184 * @see SWT#CURSOR_HELP
2185 * @see SWT#CURSOR_SIZEALL
2186 * @see SWT#CURSOR_SIZENESW
2187 * @see SWT#CURSOR_SIZENS
2188 * @see SWT#CURSOR_SIZENWSE
2189 * @see SWT#CURSOR_SIZEWE
2190 * @see SWT#CURSOR_SIZEN
2191 * @see SWT#CURSOR_SIZES
2192 * @see SWT#CURSOR_SIZEE
2193 * @see SWT#CURSOR_SIZEW
2194 * @see SWT#CURSOR_SIZENE
2195 * @see SWT#CURSOR_SIZESE
2196 * @see SWT#CURSOR_SIZESW
2197 * @see SWT#CURSOR_SIZENW
2198 * @see SWT#CURSOR_UPARROW
2199 * @see SWT#CURSOR_IBEAM
2200 * @see SWT#CURSOR_NO
2201 * @see SWT#CURSOR_HAND
2202 *
2203 * @since 3.0
2204 */

2205public Cursor getSystemCursor (int id) {
2206    checkDevice ();
2207    if (!(0 <= id && id < cursors.length)) return null;
2208    if (cursors [id] == null) {
2209        cursors [id] = new Cursor (this, id);
2210    }
2211    return cursors [id];
2212}
2213
2214/**
2215 * Returns a reasonable font for applications to use.
2216 * On some platforms, this will match the "default font"
2217 * or "system font" if such can be found. This font
2218 * should not be free'd because it was allocated by the
2219 * system, not the application.
2220 * <p>
2221 * Typically, applications which want the default look
2222 * should simply not set the font on the widgets they
2223 * create. Widgets are always created with the correct
2224 * default font for the class of user-interface component
2225 * they represent.
2226 * </p>
2227 *
2228 * @return a font
2229 *
2230 * @exception SWTException <ul>
2231 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
2232 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2233 * </ul>
2234 */

2235public Font getSystemFont () {
2236    checkDevice ();
2237    if (systemFont != null) return systemFont;
2238    int hFont = 0;
2239    if (!OS.IsWinCE) {
2240        NONCLIENTMETRICS info = OS.IsUnicode ? (NONCLIENTMETRICS) new NONCLIENTMETRICSW () : new NONCLIENTMETRICSA ();
2241        info.cbSize = NONCLIENTMETRICS.sizeof;
2242        if (OS.SystemParametersInfo (OS.SPI_GETNONCLIENTMETRICS, 0, info, 0)) {
2243            LOGFONT logFont = OS.IsUnicode ? (LOGFONT) ((NONCLIENTMETRICSW)info).lfMessageFont : ((NONCLIENTMETRICSA)info).lfMessageFont;
2244            hFont = OS.CreateFontIndirect (logFont);
2245            lfSystemFont = hFont != 0 ? logFont : null;
2246        }
2247    }
2248    if (hFont == 0) hFont = OS.GetStockObject (OS.DEFAULT_GUI_FONT);
2249    if (hFont == 0) hFont = OS.GetStockObject (OS.SYSTEM_FONT);
2250    return systemFont = Font.win32_new (this, hFont);
2251}
2252
2253/**
2254 * Returns the matching standard platform image for the given
2255 * constant, which should be one of the icon constants
2256 * specified in class <code>SWT</code>. This image should
2257 * not be free'd because it was allocated by the system,
2258 * not the application. A value of <code>null</code> will
2259 * be returned either if the supplied constant is not an
2260 * SWT icon constant or if the platform does not define an
2261 * image that corresponds to the constant.
2262 *
2263 * @param id the SWT icon constant
2264 * @return the corresponding image or <code>null</code>
2265 *
2266 * @exception SWTException <ul>
2267 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
2268 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2269 * </ul>
2270 *
2271 * @see SWT#ICON_ERROR
2272 * @see SWT#ICON_INFORMATION
2273 * @see SWT#ICON_QUESTION
2274 * @see SWT#ICON_WARNING
2275 * @see SWT#ICON_WORKING
2276 *
2277 * @since 3.0
2278 */

2279public Image getSystemImage (int id) {
2280    checkDevice ();
2281    switch (id) {
2282        case SWT.ICON_ERROR: {
2283            if (errorImage != null) return errorImage;
2284            int hIcon = OS.LoadImage (0, OS.OIC_HAND, OS.IMAGE_ICON, 0, 0, OS.LR_SHARED);
2285            return errorImage = Image.win32_new (this, SWT.ICON, hIcon);
2286        }
2287        case SWT.ICON_WORKING:
2288        case SWT.ICON_INFORMATION: {
2289            if (infoImage != null) return infoImage;
2290            int hIcon = OS.LoadImage (0, OS.OIC_INFORMATION, OS.IMAGE_ICON, 0, 0, OS.LR_SHARED);
2291            return infoImage = Image.win32_new (this, SWT.ICON, hIcon);
2292        }
2293        case SWT.ICON_QUESTION: {
2294            if (questionImage != null) return questionImage;
2295            int hIcon = OS.LoadImage (0, OS.OIC_QUES, OS.IMAGE_ICON, 0, 0, OS.LR_SHARED);
2296            return questionImage = Image.win32_new (this, SWT.ICON, hIcon);
2297        }
2298        case SWT.ICON_WARNING: {
2299            if (warningIcon != null) return warningIcon;
2300            int hIcon = OS.LoadImage (0, OS.OIC_BANG, OS.IMAGE_ICON, 0, 0, OS.LR_SHARED);
2301            return warningIcon = Image.win32_new (this, SWT.ICON, hIcon);
2302        }
2303    }
2304    return null;
2305}
2306
2307/**
2308 * Returns the single instance of the system tray or null
2309 * when there is no system tray available for the platform.
2310 *
2311 * @return the system tray or <code>null</code>
2312 *
2313 * @exception SWTException <ul>
2314 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2315 * </ul>
2316 *
2317 * @since 3.0
2318 */

2319public Tray getSystemTray () {
2320    checkDevice ();
2321    if (tray != null) return tray;
2322    if (!OS.IsWinCE) tray = new Tray (this, SWT.NONE);
2323    return tray;
2324}
2325
2326/**
2327 * Returns the user-interface thread for the receiver.
2328 *
2329 * @return the receiver's user-interface thread
2330 *
2331 * @exception SWTException <ul>
2332 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2333 * </ul>
2334 */

2335public Thread JavaDoc getThread () {
2336    if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED);
2337    return thread;
2338}
2339
2340int hButtonTheme () {
2341    if (hButtonTheme != 0) return hButtonTheme;
2342    return hButtonTheme = OS.OpenThemeData (hwndMessage, BUTTON);
2343}
2344
2345int hEditTheme () {
2346    if (hEditTheme != 0) return hEditTheme;
2347    return hEditTheme = OS.OpenThemeData (hwndMessage, EDIT);
2348}
2349
2350int hExplorerBarTheme () {
2351    if (hExplorerBarTheme != 0) return hExplorerBarTheme;
2352    return hExplorerBarTheme = OS.OpenThemeData (hwndMessage, EXPLORERBAR);
2353}
2354
2355int hScrollBarTheme () {
2356    if (hScrollBarTheme != 0) return hScrollBarTheme;
2357    return hScrollBarTheme = OS.OpenThemeData (hwndMessage, SCROLLBAR);
2358}
2359
2360int hTabTheme () {
2361    if (hTabTheme != 0) return hTabTheme;
2362    return hTabTheme = OS.OpenThemeData (hwndMessage, TAB);
2363}
2364
2365/**
2366 * Invokes platform specific functionality to allocate a new GC handle.
2367 * <p>
2368 * <b>IMPORTANT:</b> This method is <em>not</em> part of the public
2369 * API for <code>Display</code>. It is marked public only so that it
2370 * can be shared within the packages provided by SWT. It is not
2371 * available on all platforms, and should never be called from
2372 * application code.
2373 * </p>
2374 *
2375 * @param data the platform specific GC data
2376 * @return the platform specific GC handle
2377 *
2378 * @exception SWTException <ul>
2379 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2380 * </ul>
2381 * @exception SWTError <ul>
2382 * <li>ERROR_NO_HANDLES if a handle could not be obtained for gc creation</li>
2383 * </ul>
2384 */

2385public int internal_new_GC (GCData data) {
2386    if (isDisposed()) SWT.error(SWT.ERROR_DEVICE_DISPOSED);
2387    int hDC = OS.GetDC (0);
2388    if (hDC == 0) SWT.error (SWT.ERROR_NO_HANDLES);
2389    if (data != null) {
2390        int mask = SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT;
2391        if ((data.style & mask) != 0) {
2392            data.layout = (data.style & SWT.RIGHT_TO_LEFT) != 0 ? OS.LAYOUT_RTL : 0;
2393        } else {
2394            data.style |= SWT.LEFT_TO_RIGHT;
2395        }
2396        data.device = this;
2397        data.hFont = getSystemFont ().handle;
2398    }
2399    return hDC;
2400}
2401
2402/**
2403 * Initializes any internal resources needed by the
2404 * device.
2405 * <p>
2406 * This method is called after <code>create</code>.
2407 * </p>
2408 *
2409 * @see #create
2410 */

2411protected void init () {
2412    super.init ();
2413        
2414    /* Create the callbacks */
2415    windowCallback = new Callback (this, "windowProc", 4); //$NON-NLS-1$
2416
windowProc = windowCallback.getAddress ();
2417    if (windowProc == 0) error (SWT.ERROR_NO_MORE_CALLBACKS);
2418    
2419    /* Remember the current thread id */
2420    threadId = OS.GetCurrentThreadId ();
2421    
2422    /* Use the character encoding for the default locale */
2423    windowClass = new TCHAR (0, WindowName + WindowClassCount, true);
2424    windowShadowClass = new TCHAR (0, WindowShadowName + WindowClassCount, true);
2425    WindowClassCount++;
2426
2427    /* Register the SWT window class */
2428    int hHeap = OS.GetProcessHeap ();
2429    int hInstance = OS.GetModuleHandle (null);
2430    WNDCLASS lpWndClass = new WNDCLASS ();
2431    lpWndClass.hInstance = hInstance;
2432    lpWndClass.lpfnWndProc = windowProc;
2433    lpWndClass.style = OS.CS_BYTEALIGNWINDOW | OS.CS_DBLCLKS;
2434    lpWndClass.hCursor = OS.LoadCursor (0, OS.IDC_ARROW);
2435    int byteCount = windowClass.length () * TCHAR.sizeof;
2436    lpWndClass.lpszClassName = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, byteCount);
2437    OS.MoveMemory (lpWndClass.lpszClassName, windowClass, byteCount);
2438    OS.RegisterClass (lpWndClass);
2439    OS.HeapFree (hHeap, 0, lpWndClass.lpszClassName);
2440
2441    /* Register the SWT drop shadow window class */
2442    if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (5, 1)) lpWndClass.style |= OS.CS_DROPSHADOW;
2443    byteCount = windowShadowClass.length () * TCHAR.sizeof;
2444    lpWndClass.lpszClassName = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, byteCount);
2445    OS.MoveMemory (lpWndClass.lpszClassName, windowShadowClass, byteCount);
2446    OS.RegisterClass (lpWndClass);
2447    OS.HeapFree (hHeap, 0, lpWndClass.lpszClassName);
2448    
2449    /* Create the message only HWND */
2450    hwndMessage = OS.CreateWindowEx (0,
2451        windowClass,
2452        null,
2453        OS.WS_OVERLAPPED,
2454        0, 0, 0, 0,
2455        0,
2456        0,
2457        hInstance,
2458        null);
2459    messageCallback = new Callback (this, "messageProc", 4); //$NON-NLS-1$
2460
messageProc = messageCallback.getAddress ();
2461    if (messageProc == 0) error (SWT.ERROR_NO_MORE_CALLBACKS);
2462    OS.SetWindowLong (hwndMessage, OS.GWL_WNDPROC, messageProc);
2463
2464    /* Create the filter hook */
2465    if (!OS.IsWinCE) {
2466        msgFilterCallback = new Callback (this, "msgFilterProc", 3); //$NON-NLS-1$
2467
msgFilterProc = msgFilterCallback.getAddress ();
2468        if (msgFilterProc == 0) error (SWT.ERROR_NO_MORE_CALLBACKS);
2469        filterHook = OS.SetWindowsHookEx (OS.WH_MSGFILTER, msgFilterProc, 0, threadId);
2470    }
2471    
2472    /* Create the idle hook */
2473    if (!OS.IsWinCE) {
2474        foregroundIdleCallback = new Callback (this, "foregroundIdleProc", 3); //$NON-NLS-1$
2475
foregroundIdleProc = foregroundIdleCallback.getAddress ();
2476        if (foregroundIdleProc == 0) error (SWT.ERROR_NO_MORE_CALLBACKS);
2477        idleHook = OS.SetWindowsHookEx (OS.WH_FOREGROUNDIDLE, foregroundIdleProc, 0, threadId);
2478    }
2479    
2480    /* Register custom messages message */
2481    SWT_TASKBARCREATED = OS.RegisterWindowMessage (new TCHAR (0, "TaskbarCreated", true));
2482    SWT_RESTORECARET = OS.RegisterWindowMessage (new TCHAR (0, "SWT_RESTORECARET", true));
2483
2484    /* Initialize OLE */
2485    if (!OS.IsWinCE) OS.OleInitialize (0);
2486    
2487    /* Initialize buffered painting */
2488    if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)){
2489        OS.BufferedPaintInit ();
2490    }
2491    
2492    /* Initialize the Widget Table */
2493    indexTable = new int [GROW_SIZE];
2494    controlTable = new Control [GROW_SIZE];
2495    for (int i=0; i<GROW_SIZE-1; i++) indexTable [i] = i + 1;
2496    indexTable [GROW_SIZE - 1] = -1;
2497}
2498
2499/**
2500 * Invokes platform specific functionality to dispose a GC handle.
2501 * <p>
2502 * <b>IMPORTANT:</b> This method is <em>not</em> part of the public
2503 * API for <code>Display</code>. It is marked public only so that it
2504 * can be shared within the packages provided by SWT. It is not
2505 * available on all platforms, and should never be called from
2506 * application code.
2507 * </p>
2508 *
2509 * @param hDC the platform specific GC handle
2510 * @param data the platform specific GC data
2511 */

2512public void internal_dispose_GC (int hDC, GCData data) {
2513    OS.ReleaseDC (0, hDC);
2514}
2515
2516boolean isXMouseActive () {
2517    /*
2518    * NOTE: X-Mouse is active when bit 1 of the UserPreferencesMask is set.
2519    */

2520    boolean xMouseActive = false;
2521    TCHAR key = new TCHAR (0, "Control Panel\\Desktop", true); //$NON-NLS-1$
2522
int [] phKey = new int [1];
2523    int result = OS.RegOpenKeyEx (OS.HKEY_CURRENT_USER, key, 0, OS.KEY_READ, phKey);
2524    if (result == 0) {
2525        TCHAR lpValueName = new TCHAR (0, "UserPreferencesMask", true); //$NON-NLS-1$
2526
int [] lpcbData = new int [] {4}, lpData = new int [1];
2527        result = OS.RegQueryValueEx (phKey [0], lpValueName, 0, null, lpData, lpcbData);
2528        if (result == 0) xMouseActive = (lpData [0] & 0x01) != 0;
2529        OS.RegCloseKey (phKey [0]);
2530    }
2531    return xMouseActive;
2532}
2533
2534boolean isValidThread () {
2535    return thread == Thread.currentThread ();
2536}
2537
2538/**
2539 * Maps a point from one coordinate system to another.
2540 * When the control is null, coordinates are mapped to
2541 * the display.
2542 * <p>
2543 * NOTE: On right-to-left platforms where the coordinate
2544 * systems are mirrored, special care needs to be taken
2545 * when mapping coordinates from one control to another
2546 * to ensure the result is correctly mirrored.
2547 *
2548 * Mapping a point that is the origin of a rectangle and
2549 * then adding the width and height is not equivalent to
2550 * mapping the rectangle. When one control is mirrored
2551 * and the other is not, adding the width and height to a
2552 * point that was mapped causes the rectangle to extend
2553 * in the wrong direction. Mapping the entire rectangle
2554 * instead of just one point causes both the origin and
2555 * the corner of the rectangle to be mapped.
2556 * </p>
2557 *
2558 * @param from the source <code>Control</code> or <code>null</code>
2559 * @param to the destination <code>Control</code> or <code>null</code>
2560 * @param point to be mapped
2561 * @return point with mapped coordinates
2562 *
2563 * @exception IllegalArgumentException <ul>
2564 * <li>ERROR_NULL_ARGUMENT - if the point is null</li>
2565 * <li>ERROR_INVALID_ARGUMENT - if the Control from or the Control to have been disposed</li>
2566 * </ul>
2567 * @exception SWTException <ul>
2568 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
2569 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2570 * </ul>
2571 *
2572 * @since 2.1.2
2573 */

2574public Point map (Control from, Control to, Point point) {
2575    checkDevice ();
2576    if (point == null) error (SWT.ERROR_NULL_ARGUMENT);
2577    return map (from, to, point.x, point.y);
2578}
2579
2580/**
2581 * Maps a point from one coordinate system to another.
2582 * When the control is null, coordinates are mapped to
2583 * the display.
2584 * <p>
2585 * NOTE: On right-to-left platforms where the coordinate
2586 * systems are mirrored, special care needs to be taken
2587 * when mapping coordinates from one control to another
2588 * to ensure the result is correctly mirrored.
2589 *
2590 * Mapping a point that is the origin of a rectangle and
2591 * then adding the width and height is not equivalent to
2592 * mapping the rectangle. When one control is mirrored
2593 * and the other is not, adding the width and height to a
2594 * point that was mapped causes the rectangle to extend
2595 * in the wrong direction. Mapping the entire rectangle
2596 * instead of just one point causes both the origin and
2597 * the corner of the rectangle to be mapped.
2598 * </p>
2599 *
2600 * @param from the source <code>Control</code> or <code>null</code>
2601 * @param to the destination <code>Control</code> or <code>null</code>
2602 * @param x coordinates to be mapped
2603 * @param y coordinates to be mapped
2604 * @return point with mapped coordinates
2605 *
2606 * @exception IllegalArgumentException <ul>
2607 * <li>ERROR_INVALID_ARGUMENT - if the Control from or the Control to have been disposed</li>
2608 * </ul>
2609 * @exception SWTException <ul>
2610 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
2611 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2612 * </ul>
2613 *
2614 * @since 2.1.2
2615 */

2616public Point map (Control from, Control to, int x, int y) {
2617    checkDevice ();
2618    if (from != null && from.isDisposed()) error (SWT.ERROR_INVALID_ARGUMENT);
2619    if (to != null && to.isDisposed()) error (SWT.ERROR_INVALID_ARGUMENT);
2620    if (from == to) return new Point (x, y);
2621    int hwndFrom = from != null ? from.handle : 0;
2622    int hwndTo = to != null ? to.handle : 0;
2623    POINT point = new POINT ();
2624    point.x = x;
2625    point.y = y;
2626    OS.MapWindowPoints (hwndFrom, hwndTo, point, 1);
2627    return new Point (point.x, point.y);
2628}
2629
2630/**
2631 * Maps a point from one coordinate system to another.
2632 * When the control is null, coordinates are mapped to
2633 * the display.
2634 * <p>
2635 * NOTE: On right-to-left platforms where the coordinate
2636 * systems are mirrored, special care needs to be taken
2637 * when mapping coordinates from one control to another
2638 * to ensure the result is correctly mirrored.
2639 *
2640 * Mapping a point that is the origin of a rectangle and
2641 * then adding the width and height is not equivalent to
2642 * mapping the rectangle. When one control is mirrored
2643 * and the other is not, adding the width and height to a
2644 * point that was mapped causes the rectangle to extend
2645 * in the wrong direction. Mapping the entire rectangle
2646 * instead of just one point causes both the origin and
2647 * the corner of the rectangle to be mapped.
2648 * </p>
2649 *
2650 * @param from the source <code>Control</code> or <code>null</code>
2651 * @param to the destination <code>Control</code> or <code>null</code>
2652 * @param rectangle to be mapped
2653 * @return rectangle with mapped coordinates
2654 *
2655 * @exception IllegalArgumentException <ul>
2656 * <li>ERROR_NULL_ARGUMENT - if the rectangle is null</li>
2657 * <li>ERROR_INVALID_ARGUMENT - if the Control from or the Control to have been disposed</li>
2658 * </ul>
2659 * @exception SWTException <ul>
2660 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
2661 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2662 * </ul>
2663 *
2664 * @since 2.1.2
2665 */

2666public Rectangle map (Control from, Control to, Rectangle rectangle) {
2667    checkDevice ();
2668    if (rectangle == null) error (SWT.ERROR_NULL_ARGUMENT);
2669    return map (from, to, rectangle.x, rectangle.y, rectangle.width, rectangle.height);
2670}
2671
2672/**
2673 * Maps a point from one coordinate system to another.
2674 * When the control is null, coordinates are mapped to
2675 * the display.
2676 * <p>
2677 * NOTE: On right-to-left platforms where the coordinate
2678 * systems are mirrored, special care needs to be taken
2679 * when mapping coordinates from one control to another
2680 * to ensure the result is correctly mirrored.
2681 *
2682 * Mapping a point that is the origin of a rectangle and
2683 * then adding the width and height is not equivalent to
2684 * mapping the rectangle. When one control is mirrored
2685 * and the other is not, adding the width and height to a
2686 * point that was mapped causes the rectangle to extend
2687 * in the wrong direction. Mapping the entire rectangle
2688 * instead of just one point causes both the origin and
2689 * the corner of the rectangle to be mapped.
2690 * </p>
2691 *
2692 * @param from the source <code>Control</code> or <code>null</code>
2693 * @param to the destination <code>Control</code> or <code>null</code>
2694 * @param x coordinates to be mapped
2695 * @param y coordinates to be mapped
2696 * @param width coordinates to be mapped
2697 * @param height coordinates to be mapped
2698 * @return rectangle with mapped coordinates
2699 *
2700 * @exception IllegalArgumentException <ul>
2701 * <li>ERROR_INVALID_ARGUMENT - if the Control from or the Control to have been disposed</li>
2702 * </ul>
2703 * @exception SWTException <ul>
2704 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
2705 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
2706 * </ul>
2707 *
2708 * @since 2.1.2
2709 */

2710public Rectangle map (Control from, Control to, int x, int y, int width, int height) {
2711    checkDevice ();
2712    if (from != null && from.isDisposed()) error (SWT.ERROR_INVALID_ARGUMENT);
2713    if (to != null && to.isDisposed()) error (SWT.ERROR_INVALID_ARGUMENT);
2714    if (from == to) return new Rectangle (x, y, width, height);
2715    int hwndFrom = from != null ? from.handle : 0;
2716    int hwndTo = to != null ? to.handle : 0;
2717    RECT rect = new RECT ();
2718    rect.left = x;
2719    rect.top = y;
2720    rect.right = x + width;
2721    rect.bottom = y + height;
2722    OS.MapWindowPoints (hwndFrom, hwndTo, rect, 2);
2723    return new Rectangle (rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
2724}
2725
2726/*
2727 * Returns a single character, converted from the default
2728 * multi-byte character set (MBCS) used by the operating
2729 * system widgets to a wide character set (WCS) used by Java.
2730 *
2731 * @param ch the MBCS character
2732 * @return the WCS character
2733 */

2734static char mbcsToWcs (int ch) {
2735    return mbcsToWcs (ch, 0);
2736}
2737
2738/*
2739 * Returns a single character, converted from the specified
2740 * multi-byte character set (MBCS) used by the operating
2741 * system widgets to a wide character set (WCS) used by Java.
2742 *
2743 * @param ch the MBCS character
2744 * @param codePage the code page used to convert the character
2745 * @return the WCS character
2746 */

2747static char mbcsToWcs (int ch, int codePage) {
2748    if (OS.IsUnicode) return (char) ch;
2749    int key = ch & 0xFFFF;
2750    if (key <= 0x7F) return (char) ch;
2751    byte [] buffer;
2752    if (key <= 0xFF) {
2753        buffer = new byte [1];
2754        buffer [0] = (byte) key;
2755    } else {
2756        buffer = new byte [2];
2757        buffer [0] = (byte) ((key >> 8) & 0xFF);
2758        buffer [1] = (byte) (key & 0xFF);
2759    }
2760    char [] unicode = new char [1];
2761    int cp = codePage != 0 ? codePage : OS.CP_ACP;
2762    int count = OS.MultiByteToWideChar (cp, OS.MB_PRECOMPOSED, buffer, buffer.length, unicode, 1);
2763    if (count == 0) return 0;
2764    return unicode [0];
2765}
2766
2767int messageProc (int hwnd, int msg, int wParam, int lParam) {
2768    switch (msg) {
2769        case SWT_RUNASYNC: {
2770            if (runMessagesInIdle) runAsyncMessages (false);
2771            break;
2772        }
2773        case SWT_KEYMSG: {
2774            boolean consumed = false;
2775            MSG keyMsg = new MSG ();
2776            OS.MoveMemory (keyMsg, lParam, MSG.sizeof);
2777            Control control = findControl (keyMsg.hwnd);
2778            if (control != null) {
2779                /*
2780                * Feature in Windows. When the user types an accent key such
2781                * as ^ in order to get an accented character on a German keyboard,
2782                * calling TranslateMessage(), ToUnicode() or ToAscii() consumes
2783                * the key. This means that a subsequent call to TranslateMessage()
2784                * will see a regular key rather than the accented key. The fix
2785                * is to use MapVirtualKey() and VkKeyScan () to detect an accent
2786                * and avoid calls to TranslateMessage().
2787                */

2788                boolean accentKey = false;
2789                switch (keyMsg.message) {
2790                    case OS.WM_KEYDOWN:
2791                    case OS.WM_SYSKEYDOWN: {
2792                        if (!OS.IsWinCE) {
2793                            switch (keyMsg.wParam) {
2794                                case OS.VK_SHIFT:
2795                                case OS.VK_MENU:
2796                                case OS.VK_CONTROL:
2797                                case OS.VK_CAPITAL:
2798                                case OS.VK_NUMLOCK:
2799                                case OS.VK_SCROLL:
2800                                    break;
2801                                default: {
2802                                    /*
2803                                    * Bug in Windows. The high bit in the result of MapVirtualKey() on
2804                                    * Windows NT is bit 32 while the high bit on Windows 95 is bit 16.
2805                                    * They should both be bit 32. The fix is to test the right bit.
2806                                    */

2807                                    int mapKey = OS.MapVirtualKey (keyMsg.wParam, 2);
2808                                    if (mapKey != 0) {
2809                                        accentKey = (mapKey & (OS.IsWinNT ? 0x80000000 : 0x8000)) != 0;
2810                                        if (!accentKey) {
2811                                            for (int i=0; i<ACCENTS.length; i++) {
2812                                                int value = OS.VkKeyScan (ACCENTS [i]);
2813                                                if (value != -1 && (value & 0xFF) == keyMsg.wParam) {
2814                                                    int state = value >> 8;
2815                                                    if ((OS.GetKeyState (OS.VK_SHIFT) < 0) == ((state & 0x1) != 0) &&
2816                                                        (OS.GetKeyState (OS.VK_CONTROL) < 0) == ((state & 0x2) != 0) &&
2817                                                        (OS.GetKeyState (OS.VK_MENU) < 0) == ((state & 0x4) != 0)) {
2818                                                            if ((state & 0x7) != 0) accentKey = true;
2819                                                            break;
2820                                                    }
2821                                                }
2822                                            }
2823                                        }
2824                                    }
2825                                    break;
2826                                }
2827                            }
2828                        }
2829                        break;
2830                    }
2831                }
2832                if (!accentKey && !ignoreNextKey) {
2833                    keyMsg.hwnd = control.handle;
2834                    int flags = OS.PM_REMOVE | OS.PM_NOYIELD | OS.PM_QS_INPUT | OS.PM_QS_POSTMESSAGE;
2835                    do {
2836                        if (!(consumed |= filterMessage (keyMsg))) {
2837                            OS.TranslateMessage (keyMsg);
2838                            consumed |= OS.DispatchMessage (keyMsg) == 1;
2839                        }
2840                    } while (OS.PeekMessage (keyMsg, keyMsg.hwnd, OS.WM_KEYFIRST, OS.WM_KEYLAST, flags));
2841                }
2842                switch (keyMsg.message) {
2843                    case OS.WM_KEYDOWN:
2844                    case OS.WM_SYSKEYDOWN: {
2845                        switch (keyMsg.wParam) {
2846                            case OS.VK_SHIFT:
2847                            case OS.VK_MENU:
2848                            case OS.VK_CONTROL:
2849                            case OS.VK_CAPITAL:
2850                            case OS.VK_NUMLOCK:
2851                            case OS.VK_SCROLL:
2852                                break;
2853                            default: {
2854                                ignoreNextKey = accentKey;
2855                                break;
2856                            }
2857                        }
2858                    }
2859                }
2860            }
2861            if (consumed) {
2862                int hHeap = OS.GetProcessHeap ();
2863                OS.HeapFree (hHeap, 0, lParam);
2864            } else {
2865                OS.PostMessage (embeddedHwnd, SWT_KEYMSG, wParam, lParam);
2866            }
2867            return 0;
2868        }
2869        case SWT_TRAYICONMSG: {
2870            if (tray != null) {
2871                TrayItem [] items = tray.items;
2872                for (int i=0; i<items.length; i++) {
2873                    TrayItem item = items [i];
2874                    if (item != null && item.id == wParam) {
2875                        return item.messageProc (hwnd, msg, wParam, lParam);
2876                    }
2877                }
2878            }
2879            return 0;
2880        }
2881        case OS.WM_ACTIVATEAPP: {
2882            /*
2883            * Feature in Windows. When multiple shells are
2884            * disabled and one of the shells has an enabled
2885            * dialog child and the user selects a disabled
2886            * shell that does not have the enabled dialog
2887            * child using the Task bar, Windows brings the
2888            * disabled shell to the front. As soon as the
2889            * user clicks on the disabled shell, the enabled
2890            * dialog child comes to the front. This behavior
2891            * is unspecified and seems strange. Normally, a
2892            * disabled shell is frozen on the screen and the
2893            * user cannot change the z-order by clicking with
2894            * the mouse. The fix is to look for WM_ACTIVATEAPP
2895            * and force the enabled dialog child to the front.
2896            * This is typically what the user is expecting.
2897            *
2898            * NOTE: If the modal shell is disabled for any
2899            * reason, it should not be brought to the front.
2900            */

2901            if (wParam != 0) {
2902                if (!isXMouseActive ()) {
2903                    if (modalDialogShell != null && modalDialogShell.isDisposed ()) modalDialogShell = null;
2904                    Shell modal = modalDialogShell != null ? modalDialogShell : getModalShell ();
2905                    if (modal != null) {
2906                        int hwndModal = modal.handle;
2907                        if (OS.IsWindowEnabled (hwndModal)) {
2908                            modal.bringToTop ();
2909                            if (modal.isDisposed ()) break;
2910                        }
2911                        int hwndPopup = OS.GetLastActivePopup (hwndModal);
2912                        if (hwndPopup != 0 && hwndPopup != modal.handle) {
2913                            if (getControl (hwndPopup) == null) {
2914                                if (OS.IsWindowEnabled (hwndPopup)) {
2915                                    OS.SetActiveWindow (hwndPopup);
2916                                }
2917                            }
2918                        }
2919                    }
2920                }
2921            }
2922            break;
2923        }
2924        case OS.WM_ENDSESSION: {
2925            if (wParam != 0) {
2926                dispose ();
2927                /*
2928                * When the session is ending, no SWT program can continue
2929                * to run. In order to avoid running code after the display
2930                * has been disposed, exit from Java.
2931                */

2932                System.exit (0);
2933            }
2934            break;
2935        }
2936        case OS.WM_QUERYENDSESSION: {
2937            Event event = new Event ();
2938            sendEvent (SWT.Close, event);
2939            if (!event.doit) return 0;
2940            break;
2941        }
2942        case OS.WM_SETTINGCHANGE: {
2943            switch (wParam) {
2944                case 0:
2945                case 1:
2946                case OS.SPI_SETHIGHCONTRAST:
2947                    OS.SetTimer (hwndMessage, SETTINGS_ID, SETTINGS_DELAY, 0);
2948            }
2949            break;
2950        }
2951        case OS.WM_THEMECHANGED: {
2952            if (OS.COMCTL32_MAJOR >= 6) {
2953                if (hButtonTheme != 0) OS.CloseThemeData (hButtonTheme);
2954                if (hEditTheme != 0) OS.CloseThemeData (hEditTheme);
2955                if (hExplorerBarTheme != 0) OS.CloseThemeData (hExplorerBarTheme);
2956                if (hScrollBarTheme != 0) OS.CloseThemeData (hScrollBarTheme);
2957                if (hTabTheme != 0) OS.CloseThemeData (hTabTheme);
2958                hButtonTheme = hEditTheme = hExplorerBarTheme = hScrollBarTheme = hTabTheme = 0;
2959            }
2960            break;
2961        }
2962        case OS.WM_TIMER: {
2963            if (wParam == SETTINGS_ID) {
2964                OS.KillTimer (hwndMessage, SETTINGS_ID);
2965                runSettings ();
2966            } else {
2967                runTimer (wParam);
2968            }
2969            break;
2970        }
2971        default: {
2972            if (msg == SWT_TASKBARCREATED) {
2973                if (tray != null) {
2974                    TrayItem [] items = tray.items;
2975                    for (int i=0; i<items.length; i++) {
2976                        TrayItem item = items [i];
2977                        if (item != null) item.recreate ();
2978                    }
2979                }
2980            }
2981        }
2982    }
2983    return OS.DefWindowProc (hwnd, msg, wParam, lParam);
2984}
2985
2986int monitorEnumProc (int hmonitor, int hdc, int lprcMonitor, int dwData) {
2987    if (monitorCount >= monitors.length) {
2988        Monitor[] newMonitors = new Monitor [monitors.length + 4];
2989        System.arraycopy (monitors, 0, newMonitors, 0, monitors.length);
2990        monitors = newMonitors;
2991    }
2992    MONITORINFO lpmi = new MONITORINFO ();
2993    lpmi.cbSize = MONITORINFO.sizeof;
2994    OS.GetMonitorInfo (hmonitor, lpmi);
2995    Monitor monitor = new Monitor ();
2996    monitor.handle = hmonitor;
2997    monitor.x = lpmi.rcMonitor_left;
2998    monitor.y = lpmi.rcMonitor_top;
2999    monitor.width = lpmi.rcMonitor_right - lpmi.rcMonitor_left;
3000    monitor.height = lpmi.rcMonitor_bottom - lpmi.rcMonitor_top;
3001    monitor.clientX = lpmi.rcWork_left;
3002    monitor.clientY = lpmi.rcWork_top;
3003    monitor.clientWidth = lpmi.rcWork_right - lpmi.rcWork_left;
3004    monitor.clientHeight = lpmi.rcWork_bottom - lpmi.rcWork_top;
3005    monitors [monitorCount++] = monitor;
3006    return 1;
3007}
3008
3009int msgFilterProc (int code, int wParam, int lParam) {
3010    switch (code) {
3011        case OS.MSGF_COMMCTRL_BEGINDRAG: {
3012            if (!runDragDrop) {
3013                OS.MoveMemory (hookMsg, lParam, MSG.sizeof);
3014                if (hookMsg.message == OS.WM_MOUSEMOVE) {
3015                    OS.SendMessage (hookMsg.hwnd, OS.WM_CANCELMODE, 0, 0);
3016                }
3017            }
3018            break;
3019        }
3020        /*
3021        * Feature in Windows. For some reason, when the user clicks
3022        * a table or tree, the Windows hook WH_MSGFILTER is sent when
3023        * an input event from a dialog box, message box, menu, or scroll
3024        * bar did not occur, causing async messages to run at the wrong
3025        * time. The fix is to check the message filter code.
3026        */

3027        case OS.MSGF_DIALOGBOX:
3028        case OS.MSGF_MAINLOOP:
3029        case OS.MSGF_MENU:
3030        case OS.MSGF_MOVE:
3031        case OS.MSGF_MESSAGEBOX:
3032        case OS.MSGF_NEXTWINDOW:
3033        case OS.MSGF_SCROLLBAR:
3034        case OS.MSGF_SIZE: {
3035            if (runMessages) {
3036                OS.MoveMemory (hookMsg, lParam, MSG.sizeof);
3037                if (hookMsg.message == OS.WM_NULL) {
3038                    MSG msg = new MSG ();
3039                    int flags = OS.PM_NOREMOVE | OS.PM_NOYIELD | OS.PM_QS_INPUT | OS.PM_QS_POSTMESSAGE;
3040                    if (!OS.PeekMessage (msg, 0, 0, 0, flags)) {
3041                        if (runAsyncMessages (false)) wakeThread ();
3042                    }
3043                }
3044            }
3045            break;
3046        }
3047    }
3048    return OS.CallNextHookEx (filterHook, code, wParam, lParam);
3049}
3050
3051int numpadKey (int key) {
3052    switch (key) {
3053        case OS.VK_NUMPAD0: return '0';
3054        case OS.VK_NUMPAD1: return '1';
3055        case OS.VK_NUMPAD2: return '2';
3056        case OS.VK_NUMPAD3: return '3';
3057        case OS.VK_NUMPAD4: return '4';
3058        case OS.VK_NUMPAD5: return '5';
3059        case OS.VK_NUMPAD6: return '6';
3060        case OS.VK_NUMPAD7: return '7';
3061        case OS.VK_NUMPAD8: return '8';
3062        case OS.VK_NUMPAD9: return '9';
3063        case OS.VK_MULTIPLY: return '*';
3064        case OS.VK_ADD: return '+';
3065        case OS.VK_SEPARATOR: return '\0';
3066        case OS.VK_SUBTRACT: return '-';
3067        case OS.VK_DECIMAL: return '.';
3068        case OS.VK_DIVIDE: return '/';
3069    }
3070    return 0;
3071}
3072
3073/**
3074 * Generate a low level system event.
3075 *
3076 * <code>post</code> is used to generate low level keyboard
3077 * and mouse events. The intent is to enable automated UI
3078 * testing by simulating the input from the user. Most
3079 * SWT applications should never need to call this method.
3080 * <p>
3081 * Note that this operation can fail when the operating system
3082 * fails to generate the event for any reason. For example,
3083 * this can happen when there is no such key or mouse button
3084 * or when the system event queue is full.
3085 * </p>
3086 * <p>
3087 * <b>Event Types:</b>
3088 * <p>KeyDown, KeyUp
3089 * <p>The following fields in the <code>Event</code> apply:
3090 * <ul>
3091 * <li>(in) type KeyDown or KeyUp</li>
3092 * <p> Either one of:
3093 * <li>(in) character a character that corresponds to a keyboard key</li>
3094 * <li>(in) keyCode the key code of the key that was typed,
3095 * as defined by the key code constants in class <code>SWT</code></li>
3096 * </ul>
3097 * <p>MouseDown, MouseUp</p>
3098 * <p>The following fields in the <code>Event</code> apply:
3099 * <ul>
3100 * <li>(in) type MouseDown or MouseUp
3101 * <li>(in) button the button that is pressed or released
3102 * </ul>
3103 * <p>MouseMove</p>
3104 * <p>The following fields in the <code>Event</code> apply:
3105 * <ul>
3106 * <li>(in) type MouseMove
3107 * <li>(in) x the x coordinate to move the mouse pointer to in screen coordinates
3108 * <li>(in) y the y coordinate to move the mouse pointer to in screen coordinates
3109 * </ul>
3110 * </dl>
3111 *
3112 * @param event the event to be generated
3113 *
3114 * @return true if the event was generated or false otherwise
3115 *
3116 * @exception IllegalArgumentException <ul>
3117 * <li>ERROR_NULL_ARGUMENT - if the event is null</li>
3118 * </ul>
3119 * @exception SWTException <ul>
3120 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
3121 * </ul>
3122 *
3123 * @since 3.0
3124 *
3125 */

3126public boolean post (Event event) {
3127    if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED);
3128    if (event == null) error (SWT.ERROR_NULL_ARGUMENT);
3129    int type = event.type;
3130    switch (type){
3131        case SWT.KeyDown:
3132        case SWT.KeyUp: {
3133            KEYBDINPUT inputs = new KEYBDINPUT ();
3134            inputs.wVk = (short) untranslateKey (event.keyCode);
3135            if (inputs.wVk == 0) {
3136                char key = event.character;
3137                switch (key) {
3138                    case SWT.BS: inputs.wVk = (short) OS.VK_BACK; break;
3139                    case SWT.CR: inputs.wVk = (short) OS.VK_RETURN; break;
3140                    case SWT.DEL: inputs.wVk = (short) OS.VK_DELETE; break;
3141                    case SWT.ESC: inputs.wVk = (short) OS.VK_ESCAPE; break;
3142                    case SWT.TAB: inputs.wVk = (short) OS.VK_TAB; break;
3143                    /*
3144                    * Since there is no LF key on the keyboard, do not attempt
3145                    * to map LF to CR or attempt to post an LF key.
3146                    */

3147// case SWT.LF: inputs.wVk = (short) OS.VK_RETURN; break;
3148
case SWT.LF: return false;
3149                    default: {
3150                        if (OS.IsWinCE) {
3151                            inputs.wVk = OS.CharUpper ((short) key);
3152                        } else {
3153                            inputs.wVk = OS.VkKeyScan ((short) wcsToMbcs (key, 0));
3154                            if (inputs.wVk == -1) return false;
3155                            inputs.wVk &= 0xFF;
3156                        }
3157                    }
3158                }
3159            }
3160            inputs.dwFlags = type == SWT.KeyUp ? OS.KEYEVENTF_KEYUP : 0;
3161            int hHeap = OS.GetProcessHeap ();
3162            int pInputs = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, INPUT.sizeof);
3163            OS.MoveMemory(pInputs, new int[] {OS.INPUT_KEYBOARD}, 4);
3164            OS.MoveMemory (pInputs + 4, inputs, KEYBDINPUT.sizeof);
3165            boolean result = OS.SendInput (1, pInputs, INPUT.sizeof) != 0;
3166            OS.HeapFree (hHeap, 0, pInputs);
3167            return result;
3168        }
3169        case SWT.MouseDown:
3170        case SWT.MouseMove:
3171        case SWT.MouseUp:
3172        case SWT.MouseWheel: {
3173            MOUSEINPUT inputs = new MOUSEINPUT ();
3174            if (type == SWT.MouseMove){
3175                inputs.dwFlags = OS.MOUSEEVENTF_MOVE | OS.MOUSEEVENTF_ABSOLUTE;
3176                int x= 0, y = 0, width = 0, height = 0;
3177                if (OS.WIN32_VERSION >= OS.VERSION (5, 0)) {
3178                    inputs.dwFlags |= OS.MOUSEEVENTF_VIRTUALDESK;
3179                    x = OS.GetSystemMetrics (OS.SM_XVIRTUALSCREEN);
3180                    y = OS.GetSystemMetrics (OS.SM_YVIRTUALSCREEN);
3181                    width = OS.GetSystemMetrics (OS.SM_CXVIRTUALSCREEN);
3182                    height = OS.GetSystemMetrics (OS.SM_CYVIRTUALSCREEN);
3183                } else {
3184                    width = OS.GetSystemMetrics (OS.SM_CXSCREEN);
3185                    height = OS.GetSystemMetrics (OS.SM_CYSCREEN);
3186                }
3187                inputs.dx = ((event.x - x) * 65535 + width - 2) / (width - 1);
3188                inputs.dy = ((event.y - y) * 65535 + height - 2) / (height - 1);
3189            } else {
3190                if (type == SWT.MouseWheel) {
3191                    if (OS.WIN32_VERSION < OS.VERSION (5, 0)) return false;
3192                    inputs.dwFlags = OS.MOUSEEVENTF_WHEEL;
3193                    switch (event.detail) {
3194                        case SWT.SCROLL_PAGE:
3195                            inputs.mouseData = event.count * OS.WHEEL_DELTA;
3196                            break;
3197                        case SWT.SCROLL_LINE:
3198                            int [] value = new int [1];
3199                            OS.SystemParametersInfo (OS.SPI_GETWHEELSCROLLLINES, 0, value, 0);
3200                            inputs.mouseData = event.count * OS.WHEEL_DELTA / value [0];
3201                            break;
3202                        default: return false;
3203                    }
3204                } else {
3205                    switch (event.button) {
3206                        case 1: inputs.dwFlags = type == SWT.MouseDown ? OS.MOUSEEVENTF_LEFTDOWN : OS.MOUSEEVENTF_LEFTUP; break;
3207                        case 2: inputs.dwFlags = type == SWT.MouseDown ? OS.MOUSEEVENTF_MIDDLEDOWN : OS.MOUSEEVENTF_MIDDLEUP; break;
3208                        case 3: inputs.dwFlags = type == SWT.MouseDown ? OS.MOUSEEVENTF_RIGHTDOWN : OS.MOUSEEVENTF_RIGHTUP; break;
3209                        case 4: {
3210                            if (OS.WIN32_VERSION < OS.VERSION (5, 0)) return false;
3211                            inputs.dwFlags = type == SWT.MouseDown ? OS.MOUSEEVENTF_XDOWN : OS.MOUSEEVENTF_XUP;
3212                            inputs.mouseData = OS.XBUTTON1;
3213                            break;
3214                        }
3215                        case 5: {
3216                            if (OS.WIN32_VERSION < OS.VERSION (5, 0)) return false;
3217                            inputs.dwFlags = type == SWT.MouseDown ? OS.MOUSEEVENTF_XDOWN : OS.MOUSEEVENTF_XUP;
3218                            inputs.mouseData = OS.XBUTTON2;
3219                            break;
3220                        }
3221                        default: return false;
3222                    }
3223                }
3224            }
3225            int hHeap = OS.GetProcessHeap ();
3226            int pInputs = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, INPUT.sizeof);
3227            OS.MoveMemory(pInputs, new int[] {OS.INPUT_MOUSE}, 4);
3228            OS.MoveMemory (pInputs + 4, inputs, MOUSEINPUT.sizeof);
3229            boolean result = OS.SendInput (1, pInputs, INPUT.sizeof) != 0;
3230            OS.HeapFree (hHeap, 0, pInputs);
3231            return result;
3232        }
3233    }
3234    return false;
3235}
3236
3237void postEvent (Event event) {
3238    /*
3239    * Place the event at the end of the event queue.
3240    * This code is always called in the Display's
3241    * thread so it must be re-enterant but does not
3242    * need to be synchronized.
3243    */

3244    if (eventQueue == null) eventQueue = new Event [4];
3245    int index = 0;
3246    int length = eventQueue.length;
3247    while (index < length) {
3248        if (eventQueue [index] == null) break;
3249        index++;
3250    }
3251    if (index == length) {
3252        Event [] newQueue = new Event [length + 4];
3253        System.arraycopy (eventQueue, 0, newQueue, 0, length);
3254        eventQueue = newQueue;
3255    }
3256    eventQueue [index] = event;
3257}
3258
3259/**
3260 * Reads an event from the operating system's event queue,
3261 * dispatches it appropriately, and returns <code>true</code>
3262 * if there is potentially more work to do, or <code>false</code>
3263 * if the caller can sleep until another event is placed on
3264 * the event queue.
3265 * <p>
3266 * In addition to checking the system event queue, this method also
3267 * checks if any inter-thread messages (created by <code>syncExec()</code>
3268 * or <code>asyncExec()</code>) are waiting to be processed, and if
3269 * so handles them before returning.
3270 * </p>
3271 *
3272 * @return <code>false</code> if the caller can sleep upon return from this method
3273 *
3274 * @exception SWTException <ul>
3275 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
3276 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
3277 * <li>ERROR_FAILED_EXEC - if an exception occurred while running an inter-thread message</li>
3278 * </ul>
3279 *
3280 * @see #sleep
3281 * @see #wake
3282 */

3283public boolean readAndDispatch () {
3284    checkDevice ();
3285    lpStartupInfo = null;
3286    drawMenuBars ();
3287    runPopups ();
3288    if (OS.PeekMessage (msg, 0, 0, 0, OS.PM_REMOVE)) {
3289        if (!filterMessage (msg)) {
3290            OS.TranslateMessage (msg);
3291            OS.DispatchMessage (msg);
3292        }
3293        runDeferredEvents ();
3294        return true;
3295    }
3296    return runMessages && runAsyncMessages (false);
3297}
3298
3299static synchronized void register (Display display) {
3300    for (int i=0; i<Displays.length; i++) {
3301        if (Displays [i] == null) {
3302            Displays [i] = display;
3303            return;
3304        }
3305    }
3306    Display [] newDisplays = new Display [Displays.length + 4];
3307    System.arraycopy (Displays, 0, newDisplays, 0, Displays.length);
3308    newDisplays [Displays.length] = display;
3309    Displays = newDisplays;
3310}
3311
3312/**
3313 * Releases any internal resources back to the operating
3314 * system and clears all fields except the device handle.
3315 * <p>
3316 * Disposes all shells which are currently open on the display.
3317 * After this method has been invoked, all related related shells
3318 * will answer <code>true</code> when sent the message
3319 * <code>isDisposed()</code>.
3320 * </p><p>
3321 * When a device is destroyed, resources that were acquired
3322 * on behalf of the programmer need to be returned to the
3323 * operating system. For example, if the device allocated a
3324 * font to be used as the system font, this font would be
3325 * freed in <code>release</code>. Also,to assist the garbage
3326 * collector and minimize the amount of memory that is not
3327 * reclaimed when the programmer keeps a reference to a
3328 * disposed device, all fields except the handle are zero'd.
3329 * The handle is needed by <code>destroy</code>.
3330 * </p>
3331 * This method is called before <code>destroy</code>.
3332 *
3333 * @see Device#dispose
3334 * @see #destroy
3335 */

3336protected void release () {
3337    sendEvent (SWT.Dispose, new Event ());
3338    Shell [] shells = getShells ();
3339    for (int i=0; i<shells.length; i++) {
3340        Shell shell = shells [i];
3341        if (!shell.isDisposed ()) shell.dispose ();
3342    }
3343    if (tray != null) tray.dispose ();
3344    tray = null;
3345    while (readAndDispatch ()) {}
3346    if (disposeList != null) {
3347        for (int i=0; i<disposeList.length; i++) {
3348            if (disposeList [i] != null) disposeList [i].run ();
3349        }
3350    }
3351    disposeList = null;
3352    synchronizer.releaseSynchronizer ();
3353    synchronizer = null;
3354    releaseDisplay ();
3355    super.release ();
3356}
3357
3358void releaseDisplay () {
3359    if (embeddedHwnd != 0) {
3360        OS.PostMessage (embeddedHwnd, SWT_DESTROY, 0, 0);
3361    }
3362    
3363    /* Release XP Themes */
3364    if (OS.COMCTL32_MAJOR >= 6) {
3365        if (hButtonTheme != 0) OS.CloseThemeData (hButtonTheme);
3366        if (hEditTheme != 0) OS.CloseThemeData (hEditTheme);
3367        if (hExplorerBarTheme != 0) OS.CloseThemeData (hExplorerBarTheme);
3368        if (hScrollBarTheme != 0) OS.CloseThemeData (hScrollBarTheme);
3369        if (hTabTheme != 0) OS.CloseThemeData (hTabTheme);
3370        hButtonTheme = hEditTheme = hExplorerBarTheme = hScrollBarTheme = hTabTheme = 0;
3371    }
3372    
3373    /* Unhook the message hook */
3374    if (!OS.IsWinCE) {
3375        if (msgHook != 0) OS.UnhookWindowsHookEx (msgHook);
3376        msgHook = 0;
3377    }
3378
3379    /* Unhook the filter hook */
3380    if (!OS.IsWinCE) {
3381        if (filterHook != 0) OS.UnhookWindowsHookEx (filterHook);
3382        filterHook = 0;
3383        msgFilterCallback.dispose ();
3384        msgFilterCallback = null;
3385        msgFilterProc = 0;
3386    }
3387    
3388    /* Unhook the idle hook */
3389    if (!OS.IsWinCE) {
3390        if (idleHook != 0) OS.UnhookWindowsHookEx (idleHook);
3391        idleHook = 0;
3392        foregroundIdleCallback.dispose ();
3393        foregroundIdleCallback = null;
3394        foregroundIdleProc = 0;
3395    }
3396    
3397    /* Destroy the message only HWND */
3398    if (hwndMessage != 0) OS.DestroyWindow (hwndMessage);
3399    hwndMessage = 0;
3400    messageCallback.dispose ();
3401    messageCallback = null;
3402    messageProc = 0;
3403    
3404    /* Unregister the SWT window class */
3405    int hHeap = OS.GetProcessHeap ();
3406    int hInstance = OS.GetModuleHandle (null);
3407    OS.UnregisterClass (windowClass, hInstance);
3408    
3409    /* Unregister the SWT drop shadow window class */
3410    OS.UnregisterClass (windowShadowClass, hInstance);
3411    windowClass = windowShadowClass = null;
3412    windowCallback.dispose ();
3413    windowCallback = null;
3414    windowProc = 0;
3415    
3416    /* Release the System fonts */
3417    if (systemFont != null) systemFont.dispose ();
3418    systemFont = null;
3419    lfSystemFont = null;
3420    
3421    /* Release the System Images */
3422    if (errorImage != null) errorImage.dispose ();
3423    if (infoImage != null) infoImage.dispose ();
3424    if (questionImage != null) questionImage.dispose ();
3425    if (warningIcon != null) warningIcon.dispose ();
3426    errorImage = infoImage = questionImage = warningIcon = null;
3427    
3428    /* Release Sort Indicators */
3429    if (upArrow != null) upArrow.dispose ();
3430    if (downArrow != null) downArrow.dispose ();
3431    upArrow = downArrow = null;
3432    
3433    /* Release the System Cursors */
3434    for (int i = 0; i < cursors.length; i++) {
3435        if (cursors [i] != null) cursors [i].dispose ();
3436    }
3437    cursors = null;
3438
3439    /* Release Acquired Resources */
3440    if (resources != null) {
3441        for (int i=0; i<resources.length; i++) {
3442            if (resources [i] != null) resources [i].dispose ();
3443        }
3444        resources = null;
3445    }
3446
3447    /* Release Custom Colors for ChooseColor */
3448    if (lpCustColors != 0) OS.HeapFree (hHeap, 0, lpCustColors);
3449    lpCustColors = 0;
3450    
3451    /* Uninitialize OLE */
3452    if (!OS.IsWinCE) OS.OleUninitialize ();
3453
3454    /* Uninitialize buffered painting */
3455    if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) {
3456        OS.BufferedPaintUnInit ();
3457    }
3458    
3459    /* Release references */
3460    thread = null;
3461    msg = null;
3462    keyboard = null;
3463    modalDialogShell = null;
3464    modalShells = null;
3465    data = null;
3466    keys = null;
3467    values = null;
3468    bars = popups = null;
3469    indexTable = null;
3470    controlTable = null;
3471    lastControl = lastGetControl = lastHittestControl = null;
3472    imageList = toolImageList = toolHotImageList = toolDisabledImageList = null;
3473}
3474
3475void releaseImageList (ImageList list) {
3476    int i = 0;
3477    int length = imageList.length;
3478    while (i < length) {
3479        if (imageList [i] == list) {
3480            if (list.removeRef () > 0) return;
3481            list.dispose ();
3482            System.arraycopy (imageList, i + 1, imageList, i, --length - i);
3483            imageList [length] = null;
3484            for (int j=0; j<length; j++) {
3485                if (imageList [j] != null) return;
3486            }
3487            imageList = null;
3488            return;
3489        }
3490        i++;
3491    }
3492}
3493
3494void releaseToolImageList (ImageList list) {
3495    int i = 0;
3496    int length = toolImageList.length;
3497    while (i < length) {
3498        if (toolImageList [i] == list) {
3499            if (list.removeRef () > 0) return;
3500            list.dispose ();
3501            System.arraycopy (toolImageList, i + 1, toolImageList, i, --length - i);
3502            toolImageList [length] = null;
3503            for (int j=0; j<length; j++) {
3504                if (toolImageList [j] != null) return;
3505            }
3506            toolImageList = null;
3507            return;
3508        }
3509        i++;
3510    }
3511}
3512
3513void releaseToolHotImageList (ImageList list) {
3514    int i = 0;
3515    int length = toolHotImageList.length;
3516    while (i < length) {
3517        if (toolHotImageList [i] == list) {
3518            if (list.removeRef () > 0) return;
3519            list.dispose ();
3520            System.arraycopy (toolHotImageList, i + 1, toolHotImageList, i, --length - i);
3521            toolHotImageList [length] = null;
3522            for (int j=0; j<length; j++) {
3523                if (toolHotImageList [j] != null) return;
3524            }
3525            toolHotImageList = null;
3526            return;
3527        }
3528        i++;
3529    }
3530}
3531
3532void releaseToolDisabledImageList (ImageList list) {
3533    int i = 0;
3534    int length = toolDisabledImageList.length;
3535    while (i < length) {
3536        if (toolDisabledImageList [i] == list) {
3537            if (list.removeRef () > 0) return;
3538            list.dispose ();
3539            System.arraycopy (toolDisabledImageList, i + 1, toolDisabledImageList, i, --length - i);
3540            toolDisabledImageList [length] = null;
3541            for (int j=0; j<length; j++) {
3542                if (toolDisabledImageList [j] != null) return;
3543            }
3544            toolDisabledImageList = null;
3545            return;
3546        }
3547        i++;
3548    }
3549}
3550
3551/**
3552 * Removes the listener from the collection of listeners who will
3553 * be notified when an event of the given type occurs anywhere in
3554 * a widget. The event type is one of the event constants defined
3555 * in class <code>SWT</code>.
3556 *
3557 * @param eventType the type of event to listen for
3558 * @param listener the listener which should no longer be notified when the event occurs
3559 *
3560 * @exception IllegalArgumentException <ul>
3561 * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
3562 * </ul>
3563 * @exception SWTException <ul>
3564 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
3565 * </ul>
3566 *
3567 * @see Listener
3568 * @see SWT
3569 * @see #addFilter
3570 * @see #addListener
3571 *
3572 * @since 3.0
3573 */

3574public void removeFilter (int eventType, Listener listener) {
3575    checkDevice ();
3576    if (listener == null) error (SWT.ERROR_NULL_ARGUMENT);
3577    if (filterTable == null) return;
3578    filterTable.unhook (eventType, listener);
3579    if (filterTable.size () == 0) filterTable = null;
3580}
3581
3582/**
3583 * Removes the listener from the collection of listeners who will
3584 * be notified when an event of the given type occurs. The event type
3585 * is one of the event constants defined in class <code>SWT</code>.
3586 *
3587 * @param eventType the type of event to listen for
3588 * @param listener the listener which should no longer be notified when the event occurs
3589 *
3590 * @exception IllegalArgumentException <ul>
3591 * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
3592 * </ul>
3593 * @exception SWTException <ul>
3594 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
3595 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
3596 * </ul>
3597 *
3598 * @see Listener
3599 * @see SWT
3600 * @see #addListener
3601 *
3602 * @since 2.0
3603 */

3604public void removeListener (int eventType, Listener listener) {
3605    checkDevice ();
3606    if (listener == null) error (SWT.ERROR_NULL_ARGUMENT);
3607    if (eventTable == null) return;
3608    eventTable.unhook (eventType, listener);
3609}
3610
3611void removeBar (Menu menu) {
3612    if (bars == null) return;
3613    for (int i=0; i<bars.length; i++) {
3614        if (bars [i] == menu) {
3615            bars [i] = null;
3616            return;
3617        }
3618    }
3619}
3620
3621Control removeControl (int handle) {
3622    if (handle == 0) return null;
3623    lastControl = lastGetControl = null;
3624    Control control = null;
3625    int index;
3626    if (USE_PROPERTY) {
3627        index = OS.RemoveProp (handle, SWT_OBJECT_INDEX) - 1;
3628    } else {
3629        index = OS.GetWindowLong (handle, OS.GWL_USERDATA) - 1;
3630    }
3631    if (0 <= index && index < controlTable.length) {
3632        control = controlTable [index];
3633        controlTable [index] = null;
3634        indexTable [index] = freeSlot;
3635        freeSlot = index;
3636        if (!USE_PROPERTY) {
3637            OS.SetWindowLong (handle, OS.GWL_USERDATA, 0);
3638        }
3639    }
3640    return control;
3641}
3642
3643void removeMenuItem (MenuItem item) {
3644    if (items == null) return;
3645    items [item.id - ID_START] = null;
3646}
3647
3648void removePopup (Menu menu) {
3649    if (popups == null) return;
3650    for (int i=0; i<popups.length; i++) {
3651        if (popups [i] == menu) {
3652            popups [i] = null;
3653            return;
3654        }
3655    }
3656}
3657
3658boolean runAsyncMessages (boolean all) {
3659    return synchronizer.runAsyncMessages (all);
3660}
3661
3662boolean runDeferredEvents () {
3663    /*
3664    * Run deferred events. This code is always
3665    * called in the Display's thread so it must
3666    * be re-enterant but need not be synchronized.
3667    */

3668    while (eventQueue != null) {
3669        
3670        /* Take an event off the queue */
3671        Event event = eventQueue [0];
3672        if (event == null) break;
3673        int length = eventQueue.length;
3674        System.arraycopy (eventQueue, 1, eventQueue, 0, --length);
3675        eventQueue [length] = null;
3676
3677        /* Run the event */
3678        Widget widget = event.widget;
3679        if (widget != null && !widget.isDisposed ()) {
3680            Widget item = event.item;
3681            if (item == null || !item.isDisposed ()) {
3682                widget.sendEvent (event);
3683            }
3684        }
3685
3686        /*
3687        * At this point, the event queue could
3688        * be null due to a recursive invocation
3689        * when running the event.
3690        */

3691    }
3692
3693    /* Clear the queue */
3694    eventQueue = null;
3695    return true;
3696}
3697
3698boolean runPopups () {
3699    if (popups == null) return false;
3700    boolean result = false;
3701    while (popups != null) {
3702        Menu menu = popups [0];
3703        if (menu == null) break;
3704        int length = popups.length;
3705        System.arraycopy (popups, 1, popups, 0, --length);
3706        popups [length] = null;
3707        runDeferredEvents ();
3708        if (!menu.isDisposed ()) menu._setVisible (true);
3709        result = true;
3710    }
3711    popups = null;
3712    return result;
3713}
3714
3715void runSettings () {
3716    Font oldFont = getSystemFont ();
3717    saveResources ();
3718    updateImages ();
3719    sendEvent (SWT.Settings, null);
3720    Font newFont = getSystemFont ();
3721    boolean sameFont = oldFont.equals (newFont);
3722    Shell [] shells = getShells ();
3723    for (int i=0; i<shells.length; i++) {
3724        Shell shell = shells [i];
3725        if (!shell.isDisposed ()) {
3726            if (!sameFont) {
3727                shell.updateFont (oldFont, newFont);
3728            }
3729            /* This code is intentionally commented */
3730            //shell.redraw (true);
3731
shell.layout (true, true);
3732        }
3733    }
3734}
3735
3736boolean runTimer (int id) {
3737    if (timerList != null && timerIds != null) {
3738        int index = 0;
3739        while (index <timerIds.length) {
3740            if (timerIds [index] == id) {
3741                OS.KillTimer (hwndMessage, timerIds [index]);
3742                timerIds [index] = 0;
3743                Runnable JavaDoc runnable = timerList [index];
3744                timerList [index] = null;
3745                if (runnable != null) runnable.run ();
3746                return true;
3747            }
3748            index++;
3749        }
3750    }
3751    return false;
3752}
3753
3754void saveResources () {
3755    int resourceCount = 0;
3756    if (resources == null) {
3757        resources = new Resource [RESOURCE_SIZE];
3758    } else {
3759        resourceCount = resources.length;
3760        Resource [] newResources = new Resource [resourceCount + RESOURCE_SIZE];
3761        System.arraycopy (resources, 0, newResources, 0, resourceCount);
3762        resources = newResources;
3763    }
3764    if (systemFont != null) {
3765        if (!OS.IsWinCE) {
3766            NONCLIENTMETRICS info = OS.IsUnicode ? (NONCLIENTMETRICS) new NONCLIENTMETRICSW () : new NONCLIENTMETRICSA ();
3767            info.cbSize = NONCLIENTMETRICS.sizeof;
3768            if (OS.SystemParametersInfo (OS.SPI_GETNONCLIENTMETRICS, 0, info, 0)) {
3769                LOGFONT logFont = OS.IsUnicode ? (LOGFONT) ((NONCLIENTMETRICSW)info).lfMessageFont : ((NONCLIENTMETRICSA)info).lfMessageFont;
3770                if (lfSystemFont == null ||
3771                    logFont.lfCharSet != lfSystemFont.lfCharSet ||
3772                    logFont.lfHeight != lfSystemFont.lfHeight ||
3773                    logFont.lfWidth != lfSystemFont.lfWidth ||
3774                    logFont.lfEscapement != lfSystemFont.lfEscapement ||
3775                    logFont.lfOrientation != lfSystemFont.lfOrientation ||
3776                    logFont.lfWeight != lfSystemFont.lfWeight ||
3777                    logFont.lfItalic != lfSystemFont.lfItalic ||
3778                    logFont.lfUnderline != lfSystemFont.lfUnderline ||
3779                    logFont.lfStrikeOut != lfSystemFont.lfStrikeOut ||
3780                    logFont.lfCharSet != lfSystemFont.lfCharSet ||
3781                    logFont.lfOutPrecision != lfSystemFont.lfOutPrecision ||
3782                    logFont.lfClipPrecision != lfSystemFont.lfClipPrecision ||
3783                    logFont.lfQuality != lfSystemFont.lfQuality ||
3784                    logFont.lfPitchAndFamily != lfSystemFont.lfPitchAndFamily ||
3785                    !getFontName (logFont).equals (getFontName (lfSystemFont))) {
3786                        resources [resourceCount++] = systemFont;
3787                        lfSystemFont = logFont;
3788                        systemFont = null;
3789                }
3790            }
3791        }
3792    }
3793    if (errorImage != null) resources [resourceCount++] = errorImage;
3794    if (infoImage != null) resources [resourceCount++] = infoImage;
3795    if (questionImage != null) resources [resourceCount++] = questionImage;
3796    if (warningIcon != null) resources [resourceCount++] = warningIcon;
3797    errorImage = infoImage = questionImage = warningIcon = null;
3798    for (int i=0; i<cursors.length; i++) {
3799        if (cursors [i] != null) resources [resourceCount++] = cursors [i];
3800        cursors [i] = null;
3801    }
3802    if (resourceCount < RESOURCE_SIZE) {
3803        Resource [] newResources = new Resource [resourceCount];
3804        System.arraycopy (resources, 0, newResources, 0, resourceCount);
3805        resources = newResources;
3806    }
3807}
3808
3809void sendEvent (int eventType, Event event) {
3810    if (eventTable == null && filterTable == null) {
3811        return;
3812    }
3813    if (event == null) event = new Event ();
3814    event.display = this;
3815    event.type = eventType;
3816    if (event.time == 0) event.time = getLastEventTime ();
3817    if (!filterEvent (event)) {
3818        if (eventTable != null) eventTable.sendEvent (event);
3819    }
3820}
3821
3822/**
3823 * Sets the location of the on-screen pointer relative to the top left corner
3824 * of the screen. <b>Note: It is typically considered bad practice for a
3825 * program to move the on-screen pointer location.</b>
3826 *
3827 * @param x the new x coordinate for the cursor
3828 * @param y the new y coordinate for the cursor
3829 *
3830 * @exception SWTException <ul>
3831 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
3832 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
3833 * </ul>
3834 *
3835 * @since 2.1
3836 */

3837public void setCursorLocation (int x, int y) {
3838    checkDevice ();
3839    OS.SetCursorPos (x, y);
3840}
3841
3842/**
3843 * Sets the location of the on-screen pointer relative to the top left corner
3844 * of the screen. <b>Note: It is typically considered bad practice for a
3845 * program to move the on-screen pointer location.</b>
3846 *
3847 * @param point new position
3848 *
3849 * @exception SWTException <ul>
3850 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
3851 * <li>ERROR_NULL_ARGUMENT - if the point is null
3852 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
3853 * </ul>
3854 *
3855 * @since 2.0
3856 */

3857public void setCursorLocation (Point point) {
3858    checkDevice ();
3859    if (point == null) error (SWT.ERROR_NULL_ARGUMENT);
3860    setCursorLocation (point.x, point.y);
3861}
3862
3863/**
3864 * Sets the application defined property of the receiver
3865 * with the specified name to the given argument.
3866 * <p>
3867 * Applications may have associated arbitrary objects with the
3868 * receiver in this fashion. If the objects stored in the
3869 * properties need to be notified when the display is disposed
3870 * of, it is the application's responsibility provide a
3871 * <code>disposeExec()</code> handler which does so.
3872 * </p>
3873 *
3874 * @param key the name of the property
3875 * @param value the new value for the property
3876 *
3877 * @exception IllegalArgumentException <ul>
3878 * <li>ERROR_NULL_ARGUMENT - if the key is null</li>
3879 * </ul>
3880 * @exception SWTException <ul>
3881 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
3882 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
3883 * </ul>
3884 *
3885 * @see #getData(String)
3886 * @see #disposeExec(Runnable)
3887 */

3888public void setData (String JavaDoc key, Object JavaDoc value) {
3889    checkDevice ();
3890    if (key == null) error (SWT.ERROR_NULL_ARGUMENT);
3891
3892    if (key.equals (RUN_MESSAGES_IN_IDLE_KEY)) {
3893        Boolean JavaDoc data = (Boolean JavaDoc) value;
3894        runMessagesInIdle = data != null && data.booleanValue ();
3895        return;
3896    }
3897    
3898    /* Remove the key/value pair */
3899    if (value == null) {
3900        if (keys == null) return;
3901        int index = 0;
3902        while (index < keys.length && !keys [index].equals (key)) index++;
3903        if (index == keys.length) return;
3904        if (keys.length == 1) {
3905            keys = null;
3906            values = null;
3907        } else {
3908            String JavaDoc [] newKeys = new String JavaDoc [keys.length - 1];
3909            Object JavaDoc [] newValues = new Object JavaDoc [values.length - 1];
3910            System.arraycopy (keys, 0, newKeys, 0, index);
3911            System.arraycopy (keys, index + 1, newKeys, index, newKeys.length - index);
3912            System.arraycopy (values, 0, newValues, 0, index);
3913            System.arraycopy (values, index + 1, newValues, index, newValues.length - index);
3914            keys = newKeys;
3915            values = newValues;
3916        }
3917        return;
3918    }
3919    
3920    /* Add the key/value pair */
3921    if (keys == null) {
3922        keys = new String JavaDoc [] {key};
3923        values = new Object JavaDoc [] {value};
3924        return;
3925    }
3926    for (int i=0; i<keys.length; i++) {
3927        if (keys [i].equals (key)) {
3928            values [i] = value;
3929            return;
3930        }
3931    }
3932    String JavaDoc [] newKeys = new String JavaDoc [keys.length + 1];
3933    Object JavaDoc [] newValues = new Object JavaDoc [values.length + 1];
3934    System.arraycopy (keys, 0, newKeys, 0, keys.length);
3935    System.arraycopy (values, 0, newValues, 0, values.length);
3936    newKeys [keys.length] = key;
3937    newValues [values.length] = value;
3938    keys = newKeys;
3939    values = newValues;
3940}
3941
3942/**
3943 * Sets the application defined, display specific data
3944 * associated with the receiver, to the argument.
3945 * The <em>display specific data</em> is a single,
3946 * unnamed field that is stored with every display.
3947 * <p>
3948 * Applications may put arbitrary objects in this field. If
3949 * the object stored in the display specific data needs to
3950 * be notified when the display is disposed of, it is the
3951 * application's responsibility provide a
3952 * <code>disposeExec()</code> handler which does so.
3953 * </p>
3954 *
3955 * @param data the new display specific data
3956 *
3957 * @exception SWTException <ul>
3958 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
3959 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
3960 * </ul>
3961 *
3962 * @see #getData()
3963 * @see #disposeExec(Runnable)
3964 */

3965public void setData (Object JavaDoc data) {
3966    checkDevice ();
3967    this.data = data;
3968}
3969
3970/**
3971 * On platforms which support it, sets the application name
3972 * to be the argument. On Motif, for example, this can be used
3973 * to set the name used for resource lookup. Specifying
3974 * <code>null</code> for the name clears it.
3975 *
3976 * @param name the new app name or <code>null</code>
3977 */

3978public static void setAppName (String JavaDoc name) {
3979    /* Do nothing */
3980}
3981
3982void setModalDialogShell (Shell modalDailog) {
3983    if (modalDialogShell != null && modalDialogShell.isDisposed ()) modalDialogShell = null;
3984    this.modalDialogShell = modalDailog;
3985    Shell [] shells = getShells ();
3986    for (int i=0; i<shells.length; i++) shells [i].updateModal ();
3987}
3988
3989void setModalShell (Shell shell) {
3990    if (modalShells == null) modalShells = new Shell [4];
3991    int index = 0, length = modalShells.length;
3992    while (index < length) {
3993        if (modalShells [index] == shell) return;
3994        if (modalShells [index] == null) break;
3995        index++;
3996    }
3997    if (index == length) {
3998        Shell [] newModalShells = new Shell [length + 4];
3999        System.arraycopy (modalShells, 0, newModalShells, 0, length);
4000        modalShells = newModalShells;
4001    }
4002    modalShells [index] = shell;
4003    Shell [] shells = getShells ();
4004    for (int i=0; i<shells.length; i++) shells [i].updateModal ();
4005}
4006
4007/**
4008 * Sets the synchronizer used by the display to be
4009 * the argument, which can not be null.
4010 *
4011 * @param synchronizer the new synchronizer for the display (must not be null)
4012 *
4013 * @exception IllegalArgumentException <ul>
4014 * <li>ERROR_NULL_ARGUMENT - if the synchronizer is null</li>
4015 * </ul>
4016 * @exception SWTException <ul>
4017 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
4018 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
4019 * <li>ERROR_FAILED_EXEC - if an exception occurred while running an inter-thread message</li>
4020 * </ul>
4021 */

4022public void setSynchronizer (Synchronizer synchronizer) {
4023    checkDevice ();
4024    if (synchronizer == null) error (SWT.ERROR_NULL_ARGUMENT);
4025    if (this.synchronizer != null) {
4026        this.synchronizer.runAsyncMessages(true);
4027    }
4028    this.synchronizer = synchronizer;
4029}
4030
4031int shiftedKey (int key) {
4032    if (OS.IsWinCE) return 0;
4033    
4034    /* Clear the virtual keyboard and press the shift key */
4035    for (int i=0; i<keyboard.length; i++) keyboard [i] = 0;
4036    keyboard [OS.VK_SHIFT] |= 0x80;
4037
4038    /* Translate the key to ASCII or UNICODE using the virtual keyboard */
4039    if (OS.IsUnicode) {
4040        char [] result = new char [1];
4041        if (OS.ToUnicode (key, key, keyboard, result, 1, 0) == 1) return result [0];
4042    } else {
4043        short [] result = new short [1];
4044        if (OS.ToAscii (key, key, keyboard, result, 0) == 1) return result [0];
4045    }
4046    return 0;
4047}
4048
4049/**
4050 * Causes the user-interface thread to <em>sleep</em> (that is,
4051 * to be put in a state where it does not consume CPU cycles)
4052 * until an event is received or it is otherwise awakened.
4053 *
4054 * @return <code>true</code> if an event requiring dispatching was placed on the queue.
4055 *
4056 * @exception SWTException <ul>
4057 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
4058 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
4059 * </ul>
4060 *
4061 * @see #wake
4062 */

4063public boolean sleep () {
4064    checkDevice ();
4065    if (runMessages && getMessageCount () != 0) return true;
4066    if (OS.IsWinCE) {
4067        OS.MsgWaitForMultipleObjectsEx (0, 0, OS.INFINITE, OS.QS_ALLINPUT, OS.MWMO_INPUTAVAILABLE);
4068        return true;
4069    }
4070    return OS.WaitMessage ();
4071}
4072
4073/**
4074 * Causes the <code>run()</code> method of the runnable to
4075 * be invoked by the user-interface thread at the next
4076 * reasonable opportunity. The thread which calls this method
4077 * is suspended until the runnable completes. Specifying <code>null</code>
4078 * as the runnable simply wakes the user-interface thread.
4079 * <p>
4080 * Note that at the time the runnable is invoked, widgets
4081 * that have the receiver as their display may have been
4082 * disposed. Therefore, it is necessary to check for this
4083 * case inside the runnable before accessing the widget.
4084 * </p>
4085 *
4086 * @param runnable code to run on the user-interface thread or <code>null</code>
4087 *
4088 * @exception SWTException <ul>
4089 * <li>ERROR_FAILED_EXEC - if an exception occurred when executing the runnable</li>
4090 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
4091 * </ul>
4092 *
4093 * @see #asyncExec
4094 */

4095public void syncExec (Runnable JavaDoc runnable) {
4096    if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED);
4097    synchronizer.syncExec (runnable);
4098}
4099
4100/**
4101 * Causes the <code>run()</code> method of the runnable to
4102 * be invoked by the user-interface thread after the specified
4103 * number of milliseconds have elapsed. If milliseconds is less
4104 * than zero, the runnable is not executed.
4105 * <p>
4106 * Note that at the time the runnable is invoked, widgets
4107 * that have the receiver as their display may have been
4108 * disposed. Therefore, it is necessary to check for this
4109 * case inside the runnable before accessing the widget.
4110 * </p>
4111 *
4112 * @param milliseconds the delay before running the runnable
4113 * @param runnable code to run on the user-interface thread
4114 *
4115 * @exception IllegalArgumentException <ul>
4116 * <li>ERROR_NULL_ARGUMENT - if the runnable is null</li>
4117 * </ul>
4118 * @exception SWTException <ul>
4119 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
4120 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
4121 * </ul>
4122 *
4123 * @see #asyncExec
4124 */

4125public void timerExec (int milliseconds, Runnable JavaDoc runnable) {
4126    checkDevice ();
4127    if (runnable == null) error (SWT.ERROR_NULL_ARGUMENT);
4128    if (timerList == null) timerList = new Runnable JavaDoc [4];
4129    if (timerIds == null) timerIds = new int [4];
4130    int index = 0;
4131    while (index < timerList.length) {
4132        if (timerList [index] == runnable) break;
4133        index++;
4134    }
4135    int timerId = 0;
4136    if (index != timerList.length) {
4137        timerId = timerIds [index];
4138        if (milliseconds < 0) {
4139            OS.KillTimer (hwndMessage, timerId);
4140            timerList [index] = null;
4141            timerIds [index] = 0;
4142            return;
4143        }
4144    } else {
4145        if (milliseconds < 0) return;
4146        index = 0;
4147        while (index < timerList.length) {
4148            if (timerList [index] == null) break;
4149            index++;
4150        }
4151        timerId = nextTimerId++;
4152        if (index == timerList.length) {
4153            Runnable JavaDoc [] newTimerList = new Runnable JavaDoc [timerList.length + 4];
4154            System.arraycopy (timerList, 0, newTimerList, 0, timerList.length);
4155            timerList = newTimerList;
4156            int [] newTimerIds = new int [timerIds.length + 4];
4157            System.arraycopy (timerIds, 0, newTimerIds, 0, timerIds.length);
4158            timerIds = newTimerIds;
4159        }
4160    }
4161    int newTimerID = OS.SetTimer (hwndMessage, timerId, milliseconds, 0);
4162    if (newTimerID != 0) {
4163        timerList [index] = runnable;
4164        timerIds [index] = newTimerID;
4165    }
4166}
4167
4168boolean translateAccelerator (MSG msg, Control control) {
4169    accelKeyHit = true;
4170    boolean result = control.translateAccelerator (msg);
4171    accelKeyHit = false;
4172    return result;
4173}
4174
4175static int translateKey (int key) {
4176    for (int i=0; i<KeyTable.length; i++) {
4177        if (KeyTable [i] [0] == key) return KeyTable [i] [1];
4178    }
4179    return 0;
4180}
4181
4182boolean translateMnemonic (MSG msg, Control control) {
4183    switch (msg.message) {
4184        case OS.WM_CHAR:
4185        case OS.WM_SYSCHAR:
4186            return control.translateMnemonic (msg);
4187    }
4188    return false;
4189}
4190
4191boolean translateTraversal (MSG msg, Control control) {
4192    switch (msg.message) {
4193        case OS.WM_KEYDOWN:
4194            switch (msg.wParam) {
4195                case OS.VK_RETURN:
4196                case OS.VK_ESCAPE:
4197                case OS.VK_TAB:
4198                case OS.VK_UP:
4199                case OS.VK_DOWN:
4200                case OS.VK_LEFT:
4201                case OS.VK_RIGHT:
4202                case OS.VK_PRIOR:
4203                case OS.VK_NEXT:
4204                    return control.translateTraversal (msg);
4205            }
4206            break;
4207        case OS.WM_SYSKEYDOWN:
4208            switch (msg.wParam) {
4209                case OS.VK_MENU:
4210                    return control.translateTraversal (msg);
4211            }
4212            break;
4213    }
4214    return false;
4215}
4216
4217static int untranslateKey (int key) {
4218    for (int i=0; i<KeyTable.length; i++) {
4219        if (KeyTable [i] [1] == key) return KeyTable [i] [0];
4220    }
4221    return 0;
4222}
4223
4224/**
4225 * Forces all outstanding paint requests for the display
4226 * to be processed before this method returns.
4227 *
4228 * @exception SWTException <ul>
4229 * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
4230 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
4231 * </ul>
4232 *
4233 * @see Control#update()
4234 */

4235public void update() {
4236    checkDevice ();
4237    /*
4238    * Feature in Windows. When an application does not remove
4239    * events from the event queue for some time, Windows assumes
4240    * the application is not responding and no longer sends paint
4241    * events to the application. The fix is to detect that the
4242    * application is not responding and call PeekMessage() with
4243    * PM_REMOVE to tell Windows that the application is ready
4244    * to dispatch events. Note that the message does not have
4245    * to be found or dispatched in order to wake Windows up.
4246    *
4247    * NOTE: This allows other cross thread messages to be delivered,
4248    * most notably WM_ACTIVATE.
4249    */

4250    if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (4, 10)) {
4251        if (OS.IsHungAppWindow (hwndMessage)) {
4252            MSG msg = new MSG ();
4253            int flags = OS.PM_REMOVE | OS.PM_NOYIELD;
4254            OS.PeekMessage (msg, hwndMessage, SWT_NULL, SWT_NULL, flags);
4255        }
4256    }
4257    Shell[] shells = getShells ();
4258    for (int i=0; i<shells.length; i++) {
4259        Shell shell = shells [i];
4260        if (!shell.isDisposed ()) shell.update (true);
4261    }
4262}
4263
4264void updateImages () {
4265    if (upArrow != null) upArrow.dispose ();
4266    if (downArrow != null) downArrow.dispose ();
4267    upArrow = downArrow = null;
4268    for (int i=0; i<controlTable.length; i++) {
4269        Control control = controlTable [i];
4270        if (control != null) control.updateImages ();
4271    }
4272}
4273
4274/**
4275 * If the receiver's user-interface thread was <code>sleep</code>ing,
4276 * causes it to be awakened and start running again. Note that this
4277 * method may be called from any thread.
4278 *
4279 * @exception SWTException <ul>
4280 * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li>
4281 * </ul>
4282 *
4283 * @see #sleep
4284 */

4285public void wake () {
4286    if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED);
4287    if (thread == Thread.currentThread ()) return;
4288    wakeThread ();
4289}
4290
4291void wakeThread () {
4292    if (OS.IsWinCE) {
4293        OS.PostMessage (hwndMessage, OS.WM_NULL, 0, 0);
4294    } else {
4295        OS.PostThreadMessage (threadId, OS.WM_NULL, 0, 0);
4296    }
4297}
4298
4299/*
4300 * Returns a single character, converted from the wide
4301 * character set (WCS) used by Java to the specified
4302 * multi-byte character set used by the operating system
4303 * widgets.
4304 *
4305 * @param ch the WCS character
4306 * @param codePage the code page used to convert the character
4307 * @return the MBCS character
4308 */

4309static int wcsToMbcs (char ch, int codePage) {
4310    if (OS.IsUnicode) return ch;
4311    if (ch <= 0x7F) return ch;
4312    TCHAR buffer = new TCHAR (codePage, ch, false);
4313    return buffer.tcharAt (0);
4314}
4315
4316/*
4317 * Returns a single character, converted from the wide
4318 * character set (WCS) used by Java to the default
4319 * multi-byte character set used by the operating system
4320 * widgets.
4321 *
4322 * @param ch the WCS character
4323 * @return the MBCS character
4324 */

4325static int wcsToMbcs (char ch) {
4326    return wcsToMbcs (ch, 0);
4327}
4328
4329int windowProc (int hwnd, int msg, int wParam, int lParam) {
4330    /*
4331    * Bug in Adobe Reader 7.0. For some reason, when Adobe
4332    * Reader 7.0 is deactivated from within Internet Explorer,
4333    * it sends thousands of consecutive WM_NCHITTEST messages
4334    * to the control that is under the cursor. It seems that
4335    * if the control takes some time to respond to the message,
4336    * Adobe stops sending them. The fix is to detect this case
4337    * and sleep.
4338    *
4339    * NOTE: Under normal circumstances, Windows will never send
4340    * consecutive WM_NCHITTEST messages to the same control without
4341    * another message (normally WM_SETCURSOR) in between.
4342    */

4343    if (msg == OS.WM_NCHITTEST) {
4344        if (hitCount++ >= 1024) {
4345            try {Thread.sleep (1);} catch (Throwable JavaDoc t) {}
4346        }
4347    } else {
4348        hitCount = 0;
4349    }
4350    if (lastControl != null && lastHwnd == hwnd) {
4351        return lastControl.windowProc (hwnd, msg, wParam, lParam);
4352    }
4353    int index;
4354    if (USE_PROPERTY) {
4355        index = OS.GetProp (hwnd, SWT_OBJECT_INDEX) - 1;
4356    } else {
4357        index = OS.GetWindowLong (hwnd, OS.GWL_USERDATA) - 1;
4358    }
4359    if (0 <= index && index < controlTable.length) {
4360        Control control = controlTable [index];
4361        if (control != null) {
4362            lastHwnd = hwnd;
4363            lastControl = control;
4364            return control.windowProc (hwnd, msg, wParam, lParam);
4365        }
4366    }
4367    return OS.DefWindowProc (hwnd, msg, wParam, lParam);
4368}
4369
4370static String JavaDoc withCrLf (String JavaDoc string) {
4371
4372    /* If the string is empty, return the string. */
4373    int length = string.length ();
4374    if (length == 0) return string;
4375    
4376    /*
4377    * Check for an LF or CR/LF and assume the rest of
4378    * the string is formated that way. This will not
4379    * work if the string contains mixed delimiters.
4380    */

4381    int i = string.indexOf ('\n', 0);
4382    if (i == -1) return string;
4383    if (i > 0 && string.charAt (i - 1) == '\r') {
4384        return string;
4385    }
4386
4387    /*
4388    * The string is formatted with LF. Compute the
4389    * number of lines and the size of the buffer
4390    * needed to hold the result
4391    */

4392    i++;
4393    int count = 1;
4394    while (i < length) {
4395        if ((i = string.indexOf ('\n', i)) == -1) break;
4396        count++; i++;
4397    }
4398    count += length;
4399
4400    /* Create a new string with the CR/LF line terminator. */
4401    i = 0;
4402    StringBuffer JavaDoc result = new StringBuffer JavaDoc (count);
4403    while (i < length) {
4404        int j = string.indexOf ('\n', i);
4405        if (j == -1) j = length;
4406        result.append (string.substring (i, j));
4407        if ((i = j) < length) {
4408            result.append ("\r\n"); //$NON-NLS-1$
4409
i++;
4410        }
4411    }
4412    return result.toString ();
4413}
4414
4415}
4416
Popular Tags