org.eclipse.swt.widgets.Display Maven / Gradle / Ivy
Show all versions of org.eclipse.swt.gtk.linux.ppc64le Show documentation
/******************************************************************************* * Copyright (c) 2000, 2022 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation * Christoph Läubrich - Issue #64 - Integration with java.util.concurrent framework *******************************************************************************/ package org.eclipse.swt.widgets; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.Map.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.function.*; import java.util.regex.*; import java.util.regex.Pattern; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.internal.*; import org.eclipse.swt.internal.GDBus.*; import org.eclipse.swt.internal.cairo.*; import org.eclipse.swt.internal.gtk.*; import org.eclipse.swt.internal.gtk3.*; import org.eclipse.swt.internal.gtk4.*; /** * Instances of this class are responsible for managing the * connection between SWT and the underlying operating * system. Their most important function is to implement * the SWT event loop in terms of the platform event model. * They also provide various methods for accessing information * about the operating system, and have overall control over * the operating system resources which SWT allocates. *
method of the runnable to * be invoked by the user-interface thread just before the * receiver is disposed. Specifying a* Applications which are built with SWT will almost always * require only a single display. In particular, some platforms * which SWT supports will not allow more than one active * display. In other words, some platforms do not support * creating a new display if one already exists that has not been * sent the
dispose()
message. ** In SWT, the thread which creates a
* The user-interface thread for a particular display has the * following special attributes: *Display
* instance is distinguished as the user-interface thread * for that display. **
*- * The event loop for that display must be run from the thread. *
*- * Some SWT API methods (notably, most of the public methods in *
*Widget
and its subclasses), may only be called * from the thread. (To support multi-threaded user-interface * applications, classDisplay
provides inter-thread * communication methods which allow threads other than the * user-interface thread to request that it perform operations * on their behalf.) *- * The thread is not allowed to construct other *
*Display
s until that display has been disposed. * (Note that, this is in addition to the restriction mentioned * above concerning platform support for multiple displays. Thus, * the only way to have multiple simultaneously active displays, * even on platforms which support it, is to have multiple threads.) ** Enforcing these attributes allows SWT to be implemented directly * on the underlying operating system's event model. This has * numerous benefits including smaller footprint, better use of * resources, safer memory management, clearer program logic, * better performance, and fewer overall operating system threads * required. The down side however, is that care must be taken * (only) when constructing multi-threaded applications to use the * inter-thread communication mechanisms which this class provides * when required. *
* All SWT API methods which may only be called from the user-interface * thread are distinguished in their documentation by indicating that * they throw the "
*ERROR_THREAD_INVALID_ACCESS
" * SWT exception. **
*- Styles:
*- (none)
*- Events:
*- Close, Dispose, OpenDocument, Settings, Skin
** IMPORTANT: This class is not intended to be subclassed. *
* @see #syncExec * @see #asyncExec * @see #wake * @see #readAndDispatch * @see #sleep * @see Device#dispose * @see Display snippets * @see Sample code and further information * @noextend This class is not intended to be subclassed by clients. */ public class Display extends Device implements Executor { static boolean strictChecks = System.getProperty("org.eclipse.swt.internal.gtk.enableStrictChecks") != null; private static final int SLOT_IN_USE = -2; private static final int LAST_TABLE_INDEX = -1; /* Events Dispatching and Callback */ int gdkEventCount; long [] gdkEvents; Widget [] gdkEventWidgets; int [] dispatchEvents; Event [] eventQueue; long fds; int allocated_nfds; boolean wake; boolean windowSizeSet; int [] max_priority = new int [1], timeout = new int [1]; Callback eventCallback; long eventProc, windowProc2, windowProc3, windowProc4, windowProc5, windowProc6; long changeValueProc; long snapshotDrawProc, keyPressReleaseProc, focusProc, windowActiveProc, enterMotionProc, leaveProc, scrollProc, resizeProc, activateProc, gesturePressReleaseProc; long notifyProc; long computeSizeProc; Callback windowCallback2, windowCallback3, windowCallback4, windowCallback5, windowCallback6; Callback changeValue; Callback snapshotDraw, keyPressReleaseCallback, focusCallback, windowActiveCallback, enterMotionCallback, computeSizeCallback, scrollCallback, leaveCallback, resizeCallback, activateCallback, gesturePressReleaseCallback; Callback notifyCallback; EventTable eventTable, filterTable; static String APP_NAME = "SWT"; //$NON-NLS-1$ static String APP_VERSION = ""; //$NON-NLS-1$ static final String DISPATCH_EVENT_KEY = "org.eclipse.swt.internal.gtk.dispatchEvent"; //$NON-NLS-1$ static final String ADD_WIDGET_KEY = "org.eclipse.swt.internal.addWidget"; //$NON-NLS-1$ static final String EXTERNAL_EVENT_LOOP_KEY = "org.eclipse.swt.internal.gtk.externalEventLoop"; //$NON-NLS-1$ long [] closures, closuresProc; int [] closuresCount; int [] signalIds; long shellMapProcClosure; boolean externalEventLoop; // events are dispatched outside SWT, e.g. when system dialog is open /* Widget Table */ int [] indexTable; int freeSlot; long lastHandle; Widget lastWidget; Widget [] widgetTable; final static int GROW_SIZE = 1024; static final int SWT_OBJECT_INDEX; static final int SWT_OBJECT_INDEX1; static final int SWT_OBJECT_INDEX2; static { byte [] buffer = Converter.wcsToMbcs ("SWT_OBJECT_INDEX", true); //$NON-NLS-1$ SWT_OBJECT_INDEX = OS.g_quark_from_string (buffer); buffer = Converter.wcsToMbcs ("SWT_OBJECT_INDEX1", true); //$NON-NLS-1$ SWT_OBJECT_INDEX1 = OS.g_quark_from_string (buffer); buffer = Converter.wcsToMbcs ("SWT_OBJECT_INDEX2", true); //$NON-NLS-1$ SWT_OBJECT_INDEX2 = OS.g_quark_from_string (buffer); } /* Modality */ Shell [] modalShells; Dialog modalDialog; static final String GET_MODAL_DIALOG = "org.eclipse.swt.internal.gtk.getModalDialog"; //$NON-NLS-1$ static final String SET_MODAL_DIALOG = "org.eclipse.swt.internal.gtk.setModalDialog"; //$NON-NLS-1$ /* Focus */ int focusEvent; Control focusControl; Shell activeShell; boolean activePending; boolean ignoreActivate, ignoreFocus; Tracker tracker; /* Input method resources */ Control imControl; long preeditWindow, preeditLabel; /* Sync/Async Widget Communication */ Synchronizer synchronizer = new Synchronizer (this); ConsumerruntimeExceptionHandler = DefaultExceptionHandler.RUNTIME_EXCEPTION_HANDLER; Consumer errorHandler = DefaultExceptionHandler.RUNTIME_ERROR_HANDLER; Thread thread; /* Display Shutdown */ private class SessionManagerListener implements SessionManagerDBus.IListener { Display parent; public SessionManagerListener(Display parent) { this.parent = parent; } @Override public boolean isReadyToExit() { Event event = new Event (); parent.sendEvent(SWT.Close, event); return event.doit; } @Override public void stop() { parent.dispose(); } } SessionManagerDBus sessionManagerDBus; SessionManagerListener sessionManagerListener; Runnable [] disposeList; /* Deferred Layout list */ Composite[] layoutDeferred; int layoutDeferredCount; /* System Tray */ Tray tray; TrayItem currentTrayItem; /* Timers */ int [] timerIds; Runnable [] timerList; Callback timerCallback; long timerProc; Callback windowTimerCallback; long windowTimerProc; /* Caret */ Caret currentCaret; Callback caretCallback; int caretId; long caretProc; /* Mnemonics */ Control mnemonicControl; /* Mouse hover */ int mouseHoverId; long mouseHoverHandle, mouseHoverProc; Callback mouseHoverCallback; /* Tooltip size allocate callback */ long sizeAllocateProc; Callback sizeAllocateCallback; long sizeRequestProc; Callback sizeRequestCallback; /* Shell map callback */ long shellMapProc; Callback shellMapCallback; /* Idle proc callback */ long idleProc; int idleHandle; Callback idleCallback; static final String ADD_IDLE_PROC_KEY = "org.eclipse.swt.internal.gtk.addIdleProc"; //$NON-NLS-1$ static final String REMOVE_IDLE_PROC_KEY = "org.eclipse.swt.internal.gtk.removeIdleProc"; //$NON-NLS-1$ Object idleLock = new Object(); boolean idleNeeded; /* GtkTreeView callbacks */ long cellDataProc; Callback cellDataCallback; /* Set direction callback */ long setDirectionProc; Callback setDirectionCallback; static final String GET_DIRECTION_PROC_KEY = "org.eclipse.swt.internal.gtk.getDirectionProc"; //$NON-NLS-1$ /* Set emissionProc callback */ long emissionProc; Callback emissionProcCallback; static final String GET_EMISSION_PROC_KEY = "org.eclipse.swt.internal.gtk.getEmissionProc"; //$NON-NLS-1$ /* Get all children callback */ long allChildrenProc, allChildren; Callback allChildrenCallback; /* Settings callbacks */ long signalProc; Callback signalCallback; long shellHandle; boolean settingsChanged, runSettings; static final int STYLE_UPDATED = 1; /* Entry focus behaviour */ boolean entrySelectOnFocus; /* Enter/Exit events */ Control currentControl; /* Flush exposes */ long checkIfEventProc; Callback checkIfEventCallback; long flushWindow; boolean flushAll; GdkRectangle flushRect = new GdkRectangle (); XExposeEvent exposeEvent = new XExposeEvent (); long [] flushData = new long [1]; /* System Resources */ Image errorImage, infoImage, questionImage, warningImage; Cursor [] cursors = new Cursor [SWT.CURSOR_HAND + 1]; Resource [] resources; static final int RESOURCE_SIZE = 1 + 4 + SWT.CURSOR_HAND + 1; /* Colors, GTK3 */ GdkRGBA COLOR_WIDGET_DARK_SHADOW_RGBA, COLOR_WIDGET_NORMAL_SHADOW_RGBA, COLOR_WIDGET_LIGHT_SHADOW_RGBA; GdkRGBA COLOR_WIDGET_HIGHLIGHT_SHADOW_RGBA, COLOR_WIDGET_BACKGROUND_RGBA, COLOR_WIDGET_FOREGROUND_RGBA, COLOR_WIDGET_BORDER_RGBA; GdkRGBA COLOR_LIST_FOREGROUND_RGBA, COLOR_LIST_BACKGROUND_RGBA, COLOR_LIST_SELECTION_RGBA, COLOR_LIST_SELECTION_TEXT_RGBA; GdkRGBA COLOR_LIST_SELECTION_INACTIVE_RGBA, COLOR_LIST_SELECTION_TEXT_INACTIVE_RGBA; GdkRGBA COLOR_INFO_BACKGROUND_RGBA, COLOR_INFO_FOREGROUND_RGBA, COLOR_LINK_FOREGROUND_RGBA; GdkRGBA COLOR_TITLE_FOREGROUND_RGBA, COLOR_TITLE_BACKGROUND_RGBA, COLOR_TITLE_BACKGROUND_GRADIENT_RGBA; GdkRGBA COLOR_TITLE_INACTIVE_FOREGROUND_RGBA, COLOR_TITLE_INACTIVE_BACKGROUND_RGBA, COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT_RGBA; GdkRGBA COLOR_WIDGET_DISABLED_FOREGROUND_RGBA, COLOR_TEXT_DISABLED_BACKGROUND_RGBA; GdkRGBA COLOR_TOGGLE_BUTTON_FOREGROUND_RGBA; /* Initialize color list */ ArrayList colorList; /* Placeholder color ints since SWT system colors is missing them */ final int SWT_COLOR_LIST_SELECTION_TEXT_INACTIVE = 38; final int SWT_COLOR_LIST_SELECTION_INACTIVE = 39; /* Theme related */ /** The name of the current theme, including the theme named by GTK_THEME. */ static String themeName; /** True if the current theme is dark. This includes the theme set in GTK_THEME. */ static boolean themeDark; private final static Pattern colorPattern = Pattern.compile("[^-]color: (rgba?\\((?:\\d+(?:,\\s?)?){3,4}\\))"); /* Popup Menus */ Menu [] popups; /* Click count*/ int clickCount = 1; /* Entry inner border */ static final int INNER_BORDER = 2; /* Timestamp of the Last Received Events */ int lastEventTime, lastUserEventTime; /* Pango layout constructor */ long pangoLayoutNewProc; long pangoFontFamilyNewProc; long pangoFontFaceNewProc; /* IM Context constructor */ long imContextNewProc; /* GtkPrinterOptionWidget constructor */ long printerOptionWidgetNewProc; /* Custom Resize */ double resizeLocationX, resizeLocationY; int resizeBoundsX, resizeBoundsY, resizeBoundsWidth, resizeBoundsHeight; int resizeMode; /* Fixed Subclass */ static long fixed_type; /* Renderer Subclass */ static long text_renderer_type, pixbuf_renderer_type, toggle_renderer_type; static long text_renderer_info_ptr, pixbuf_renderer_info_ptr, toggle_renderer_info_ptr; static Callback rendererClassInitCallback, rendererRenderCallback, rendererSnapshotCallback; static Callback rendererGetPreferredWidthCallback; static long rendererClassInitProc, rendererRenderProc, rendererSnapshotProc; static long rendererGetPreferredWidthProc; /* Key Mappings */ static final int [] [] KeyTable = { /* Keyboard and Mouse Masks */ {GDK.GDK_Alt_L, SWT.ALT}, {GDK.GDK_Alt_R, SWT.ALT}, {GDK.GDK_Meta_L, SWT.ALT}, {GDK.GDK_Meta_R, SWT.ALT}, {GDK.GDK_Shift_L, SWT.SHIFT}, {GDK.GDK_Shift_R, SWT.SHIFT}, {GDK.GDK_Control_L, SWT.CONTROL}, {GDK.GDK_Control_R, SWT.CONTROL}, {GDK.GDK_ISO_Level3_Shift, SWT.ALT_GR}, // {OS.GDK_????, SWT.COMMAND}, // {OS.GDK_????, SWT.COMMAND}, /* Non-Numeric Keypad Keys */ {GDK.GDK_Up, SWT.ARROW_UP}, {GDK.GDK_KP_Up, SWT.ARROW_UP}, {GDK.GDK_Down, SWT.ARROW_DOWN}, {GDK.GDK_KP_Down, SWT.ARROW_DOWN}, {GDK.GDK_Left, SWT.ARROW_LEFT}, {GDK.GDK_KP_Left, SWT.ARROW_LEFT}, {GDK.GDK_Right, SWT.ARROW_RIGHT}, {GDK.GDK_KP_Right, SWT.ARROW_RIGHT}, {GDK.GDK_Page_Up, SWT.PAGE_UP}, {GDK.GDK_KP_Page_Up, SWT.PAGE_UP}, {GDK.GDK_Page_Down, SWT.PAGE_DOWN}, {GDK.GDK_KP_Page_Down, SWT.PAGE_DOWN}, {GDK.GDK_Home, SWT.HOME}, {GDK.GDK_KP_Home, SWT.HOME}, {GDK.GDK_End, SWT.END}, {GDK.GDK_KP_End, SWT.END}, {GDK.GDK_Insert, SWT.INSERT}, {GDK.GDK_KP_Insert, SWT.INSERT}, /* Virtual and Ascii Keys */ {GDK.GDK_BackSpace, SWT.BS}, {GDK.GDK_Return, SWT.CR}, {GDK.GDK_Delete, SWT.DEL}, {GDK.GDK_KP_Delete, SWT.DEL}, {GDK.GDK_Escape, SWT.ESC}, {GDK.GDK_Linefeed, SWT.LF}, {GDK.GDK_Tab, SWT.TAB}, {GDK.GDK_ISO_Left_Tab, SWT.TAB}, /* Functions Keys */ {GDK.GDK_F1, SWT.F1}, {GDK.GDK_F2, SWT.F2}, {GDK.GDK_F3, SWT.F3}, {GDK.GDK_F4, SWT.F4}, {GDK.GDK_F5, SWT.F5}, {GDK.GDK_F6, SWT.F6}, {GDK.GDK_F7, SWT.F7}, {GDK.GDK_F8, SWT.F8}, {GDK.GDK_F9, SWT.F9}, {GDK.GDK_F10, SWT.F10}, {GDK.GDK_F11, SWT.F11}, {GDK.GDK_F12, SWT.F12}, {GDK.GDK_F13, SWT.F13}, {GDK.GDK_F14, SWT.F14}, {GDK.GDK_F15, SWT.F15}, {GDK.GDK_F16, SWT.F16}, {GDK.GDK_F17, SWT.F17}, {GDK.GDK_F18, SWT.F18}, {GDK.GDK_F19, SWT.F19}, {GDK.GDK_F20, SWT.F20}, /* Numeric Keypad Keys */ {GDK.GDK_KP_Multiply, SWT.KEYPAD_MULTIPLY}, {GDK.GDK_KP_Add, SWT.KEYPAD_ADD}, {GDK.GDK_KP_Enter, SWT.KEYPAD_CR}, {GDK.GDK_KP_Subtract, SWT.KEYPAD_SUBTRACT}, {GDK.GDK_KP_Decimal, SWT.KEYPAD_DECIMAL}, {GDK.GDK_KP_Divide, SWT.KEYPAD_DIVIDE}, {GDK.GDK_KP_0, SWT.KEYPAD_0}, {GDK.GDK_KP_1, SWT.KEYPAD_1}, {GDK.GDK_KP_2, SWT.KEYPAD_2}, {GDK.GDK_KP_3, SWT.KEYPAD_3}, {GDK.GDK_KP_4, SWT.KEYPAD_4}, {GDK.GDK_KP_5, SWT.KEYPAD_5}, {GDK.GDK_KP_6, SWT.KEYPAD_6}, {GDK.GDK_KP_7, SWT.KEYPAD_7}, {GDK.GDK_KP_8, SWT.KEYPAD_8}, {GDK.GDK_KP_9, SWT.KEYPAD_9}, {GDK.GDK_KP_Equal, SWT.KEYPAD_EQUAL}, /* Other keys */ {GDK.GDK_Caps_Lock, SWT.CAPS_LOCK}, {GDK.GDK_Num_Lock, SWT.NUM_LOCK}, {GDK.GDK_Scroll_Lock, SWT.SCROLL_LOCK}, {GDK.GDK_Pause, SWT.PAUSE}, {GDK.GDK_Break, SWT.BREAK}, {GDK.GDK_Print, SWT.PRINT_SCREEN}, {GDK.GDK_Help, SWT.HELP}, }; /* Cache pressed modifier state. See Bug 537025. */ int cachedModifierState = 0; /* Latin layout key group */ private int latinKeyGroup; /* Mapping from layout key group to number of Latin alphabet keys. See Bug 533395, Bug 61190. */ Map groupKeysCount; /* Keymap "keys-changed" callback */ long keysChangedProc; Callback keysChangedCallback; /* Multiple Displays. */ static Display Default; static Display [] Displays = new Display [1]; /* Skinning support */ Widget [] skinList = new Widget [GROW_SIZE]; int skinCount; /* Package name */ static final String PACKAGE_PREFIX = "org.eclipse.swt.widgets."; //$NON-NLS-1$ /* This code is intentionally commented. * ".class" can not be used on CLDC. */ // static { // String name = Display.class.getName (); // int index = name.lastIndexOf ('.'); // PACKAGE_NAME = name.substring (0, index + 1); // } /* Minimum GTK version requirement */ static final int GTK3_MAJOR = 3; static final int GTK3_MINOR = 22; static final int GTK3_MICRO = 0; /* Latest GTK version support */ static final int GTK4_MAJOR = 4; static final int GTK4_MINOR = 0; static final int GTK4_MICRO = 0; /* Display Data */ Object data; String [] keys; Object [] values; /* Initial Guesses for Shell Trimmings. */ static final int TRIM_NONE = 0; static final int TRIM_BORDER = 1; static final int TRIM_RESIZE = 2; static final int TRIM_TITLE_BORDER = 3; static final int TRIM_TITLE_RESIZE = 4; static final int TRIM_TITLE = 5; int [] trimWidths = new int [6]; int [] trimHeights = new int [6]; { trimWidths [TRIM_NONE] = 0; trimHeights [TRIM_NONE] = 0; trimWidths [TRIM_BORDER] = 4; trimHeights [TRIM_BORDER] = 4; trimWidths [TRIM_RESIZE] = 6; trimHeights [TRIM_RESIZE] = 6; trimWidths [TRIM_TITLE_BORDER] = 5; trimHeights [TRIM_TITLE_BORDER] = 28; trimWidths [TRIM_TITLE_RESIZE] = 6; trimHeights [TRIM_TITLE_RESIZE] = 29; trimWidths [TRIM_TITLE] = 0; trimHeights [TRIM_TITLE] = 23; String path = System.getProperty ("user.home"); //$NON-NLS-1$ if (path != null) { File file = new File (path, ".swt/trims.prefs"); if (file.exists () && file.isFile ()) { Properties props = new Properties (); try (FileInputStream fis = new FileInputStream (file)) { props.load (fis); String trimWidthsString = props.getProperty ("trimWidths"); String trimHeightsString = props.getProperty ("trimHeights"); if (trimWidthsString != null && trimHeightsString != null) { StringTokenizer tok = new StringTokenizer (trimWidthsString); for (int i = 0; i < trimWidths.length && tok.hasMoreTokens (); i++) { trimWidths [i] = Integer.parseInt (tok.nextToken ()); } tok = new StringTokenizer (trimHeightsString); for (int i = 0; i < trimHeights.length && tok.hasMoreTokens (); i++) { trimHeights [i] = Integer.parseInt (tok.nextToken ()); } } } catch (IOException | NumberFormatException e) { // use default values } } } } boolean ignoreTrim; /* Window Manager */ String windowManager; /* * TEMPORARY CODE. Install the runnable that * gets the current display. This code will * be removed in the future. */ static { DeviceFinder = () -> { Device device = getCurrent (); if (device == null) { device = getDefault (); } setDevice (device); }; } /* * TEMPORARY CODE. */ static void setDevice (Device device) { CurrentDevice = device; } /** * Constructs a new instance of this class. * * Note: The resulting display is marked as the current * display. If this is the first display which has been * constructed since the application started, it is also * marked as the default display. *
* * @exception SWTException*
* * @see #getCurrent * @see #getDefault * @see Widget#checkSubclass * @see Shell */ public Display () { this (null); } /** * Constructs a new instance of this class using the parameter. * * @param data the device data */ public Display (DeviceData data) { super (data); } /** * Adds the listener to the collection of listeners who will * be notified when an event of the given type occurs anywhere * in a widget. The event type is one of the event constants * defined in class- ERROR_THREAD_INVALID_ACCESS - if called from a thread that already created an existing display
*- ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass
*SWT
. When the event does occur, * the listener is notified by sending it thehandleEvent()
* message. ** Setting the type of an event to
* * @param eventType the type of event to listen for * @param listener the listener which should be notified when the event occurs * * @exception IllegalArgumentExceptionSWT.None
from * within thehandleEvent()
method can be used to * change the event type and stop subsequent Java listeners * from running. Because event filters run before other listeners, * event filters can both block other listeners and set arbitrary * fields within an event. For this reason, event filters are both * powerful and dangerous. They should generally be avoided for * performance, debugging and code maintenance reasons. **
* @exception SWTException- ERROR_NULL_ARGUMENT - if the listener is null
**
* * @see Listener * @see SWT * @see #removeFilter * @see #removeListener * * @since 3.0 */ public void addFilter (int eventType, Listener listener) { checkDevice (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (filterTable == null) filterTable = new EventTable (); filterTable.hook (eventType, listener); } void addLayoutDeferred (Composite comp) { if (layoutDeferred == null) layoutDeferred = new Composite [64]; if (layoutDeferredCount == layoutDeferred.length) { Composite [] temp = new Composite [layoutDeferred.length + 64]; System.arraycopy (layoutDeferred, 0, temp, 0, layoutDeferred.length); layoutDeferred = temp; } layoutDeferred[layoutDeferredCount++] = comp; } void addGdkEvent (long event) { if (gdkEvents == null) { int length = GROW_SIZE; gdkEvents = new long [length]; gdkEventWidgets = new Widget [length]; gdkEventCount = 0; } if (gdkEventCount == gdkEvents.length) { int length = gdkEventCount + GROW_SIZE; long [] newEvents = new long [length]; System.arraycopy (gdkEvents, 0, newEvents, 0, gdkEventCount); gdkEvents = newEvents; Widget [] newWidgets = new Widget [length]; System.arraycopy (gdkEventWidgets, 0, newWidgets, 0, gdkEventCount); gdkEventWidgets = newWidgets; } Widget widget = null; long handle = GTK3.gtk_get_event_widget (event); if (handle != 0) { do { widget = getWidget (handle); } while (widget == null && (handle = GTK.gtk_widget_get_parent (handle)) != 0); } gdkEvents [gdkEventCount] = event; gdkEventWidgets [gdkEventCount] = widget; gdkEventCount++; } void addIdleProc() { synchronized (idleLock){ this.idleNeeded = true; if (idleHandle == 0) { if (GTK.GTK4) { idleHandle = OS.g_idle_add (idleProc, 0); } else { idleHandle = GDK.gdk_threads_add_idle (idleProc, 0); } } } } /** * Adds the listener to the collection of listeners who will * be notified when an event of the given type occurs. The event * type is one of the event constants defined in class- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
*- ERROR_DEVICE_DISPOSED - if the receiver has been disposed
*SWT
. * When the event does occur in the display, the listener is notified by * sending it thehandleEvent()
message. * * @param eventType the type of event to listen for * @param listener the listener which should be notified when the event occurs * * @exception IllegalArgumentException*
* @exception SWTException- ERROR_NULL_ARGUMENT - if the listener is null
**
* * @see Listener * @see SWT * @see #removeListener * * @since 2.0 */ public void addListener (int eventType, Listener listener) { checkDevice (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) eventTable = new EventTable (); if (eventType == SWT.OpenDocument || eventType == SWT.OpenUrl) { gdbus_init_methods(); } eventTable.hook (eventType, listener); } /** * Handle gdbus on 'org.eclipse.swt' DBus session. * E.g equinox launcher passes files/urls to SWT via gdbus. "./eclipse myFile" or "./eclipse http://www.google.com" * * Only one SWT instance can hold the unique and well-known name at one time. * We construct the name as org.eclipse.swt.NAME (e.g. org.eclipse.swt.Eclipse), * where NAME is derived from the application executable but may be changed * using the command-line argument -name. * * For equinox launcher, See eclipseGtk.c:gtkPlatformJavaSystemProperties */ private void gdbus_init_methods() { GDBusMethod[] methods = { new GDBusMethod( // FileOpen call can be reached via: // gdbus call --session --dest org.eclipse.swt.Eclipse --object-path /org/eclipse/swt --method org.eclipse.swt.FileOpen "['/tmp/hi','http://www.eclipse.org']" // See Bug525305_Browser_OpenUrl.java test snippet for testing/verification. // In a child eclipse, this will open the files in a new editor. // This is reached by equinox launcher from eclipseGtk.c. Look for "g_dbus_proxy_call_sync" "FileOpen", new String [][] {{OS.DBUS_TYPE_STRING_ARRAY,"A String array containing file paths or URLs for OpenDocument/OpenUrl signal"}}, new String [0][0], (args) -> { String[] fileNames = (String[]) args[0]; for (int i = 0; i < fileNames.length; i++) { Event event = new Event (); event.text = fileNames[i]; try { if (new URI (fileNames[i]).getScheme() != null) { // For specs, see: https://docs.oracle.com/javase/8/docs/api/java/net/URI.html // E.g: eclipse http://www.google.com sendEvent (SWT.OpenUrl, event); } else { throw new URISyntaxException(fileNames[i], "Not a valid Url. Probably file."); } } catch (URISyntaxException e) { // E.g eclipse /tmp/myfile (absolute) or eclipse myfile (relative) sendEvent (SWT.OpenDocument, event); } } return null; }) }; GDBus.init(methods, getAppName()); } long allChildrenProc (long widget, long recurse) { allChildren = OS.g_list_append (allChildren, widget); if (recurse != 0 && GTK.GTK_IS_CONTAINER (widget)) { GTK3.gtk_container_forall (widget, allChildrenProc, recurse); } return 0; } void addMouseHoverTimeout (long handle) { if (mouseHoverId != 0) OS.g_source_remove (mouseHoverId); if (GTK.GTK4) { mouseHoverId = OS.g_timeout_add (400, mouseHoverProc, handle); } else { mouseHoverId = GDK.gdk_threads_add_timeout (400, mouseHoverProc, handle); } mouseHoverHandle = handle; } void addPopup (Menu menu) { if (popups == null) popups = new Menu [4]; int length = popups.length; for (int i=0; i- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
*- ERROR_DEVICE_DISPOSED - if the receiver has been disposed
*= skinList.length) { Widget[] newSkinWidgets = new Widget [(skinList.length + 1) * 3 / 2]; System.arraycopy (skinList, 0, newSkinWidgets, 0, skinList.length); skinList = newSkinWidgets; } skinList [skinCount++] = widget; } void addWidget (long handle, Widget widget) { if (handle == 0) return; // Last element in the indexTable is -1, so if freeSlot == -1 we have no place anymore if (freeSlot == LAST_TABLE_INDEX) { int length = (freeSlot = indexTable.length) + GROW_SIZE; int[] newIndexTable = new int[length]; Widget[] newWidgetTable = new Widget [length]; System.arraycopy (indexTable, 0, newIndexTable, 0, freeSlot); System.arraycopy (widgetTable, 0, newWidgetTable, 0, freeSlot); for (int i = freeSlot; i < length - 1; i++) { newIndexTable[i] = i + 1; } // mark last slot as "need resize" newIndexTable[length - 1] = LAST_TABLE_INDEX; indexTable = newIndexTable; widgetTable = newWidgetTable; } int index = freeSlot + 1; if(strictChecks) { long data = OS.g_object_get_qdata (handle, SWT_OBJECT_INDEX); if(data > 0 && data != index) { SWT.error(SWT.ERROR_INVALID_ARGUMENT, null, ". Potential leak of " + widget + debugInfoForIndex(data - 1)); } } OS.g_object_set_qdata (handle, SWT_OBJECT_INDEX, index); int oldSlot = freeSlot; freeSlot = indexTable[oldSlot]; // Mark old index slot as used indexTable [oldSlot] = SLOT_IN_USE; if(widgetTable [oldSlot] != null) { SWT.error(SWT.ERROR_INVALID_ARGUMENT, null, ". Trying to override non empty slot with " + widget + debugInfoForIndex(oldSlot)); } widgetTable [oldSlot] = widget; } /** * Causes the run()
method of the runnable to * be invoked by the user-interface thread at the next * reasonable opportunity. The caller of this method continues * to run in parallel, and is not notified when the * runnable has completed. Specifyingnull
as the * runnable simply wakes the user-interface thread when run. ** Note that at the time the runnable is invoked, widgets * that have the receiver as their display may have been * disposed. Therefore, it is necessary to check for this * case inside the runnable before accessing the widget. *
* * @param runnable code to run on the user-interface thread ornull
* * @exception SWTException*
* * @see #syncExec */ public void asyncExec (Runnable runnable) { synchronized (Device.class) { if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED); synchronized (idleLock) { if (idleNeeded && idleHandle == 0) { if (GTK.GTK4) { idleHandle = OS.g_idle_add (idleProc, 0); } else { idleHandle = GDK.gdk_threads_add_idle (idleProc, 0); } } } synchronizer.asyncExec (runnable); } } /** * Executes the given runnable in the user-interface thread of this Display. *- ERROR_DEVICE_DISPOSED - if the receiver has been disposed
**
*- If the calling thread is the user-interface thread of this display it is * executed immediately and the method returns after the command has run, as with * the method {@link Display#syncExec(Runnable)}.
*- In all other cases the
*run()
method of the runnable is * asynchronously executed as with the method * {@link Display#asyncExec(Runnable)} at the next reasonable opportunity. The * caller of this method continues to run in parallel, and is not notified when * the runnable has completed.* This can be used in cases where one want to execute some piece of code that * should be guaranteed to run in the user-interface thread regardless of the * current thread. *
* ** Note that at the time the runnable is invoked, widgets that have the receiver * as their display may have been disposed. Therefore, it is advised to check * for this case inside the runnable before accessing the widget. *
* * @param runnable the runnable to execute in the user-interface thread, never *null
* @throws RejectedExecutionException if this task cannot be accepted for * execution * @throws NullPointerException if runnable is null */ @Override public void execute(Runnable runnable) { Objects.requireNonNull(runnable); if (isDisposed()) { throw new RejectedExecutionException(new SWTException (SWT.ERROR_WIDGET_DISPOSED, null)); } if (thread == Thread.currentThread()) { syncExec(runnable); } else { asyncExec(runnable); } } /** * Causes the system hardware to emit a short sound * (if it supports this capability). * * @exception SWTException*
*/ public void beep () { if (!isValidThread ()) error (SWT.ERROR_THREAD_INVALID_ACCESS); GDK.gdk_display_beep(GDK.gdk_display_get_default()); } long cellDataProc (long tree_column, long cell, long tree_model, long iter, long data) { Widget widget = getWidget (data); if (widget == null) return 0; return widget.cellDataProc (tree_column, cell, tree_model, iter, data); } @Override protected void checkDevice () { if (thread == null) error (SWT.ERROR_WIDGET_DISPOSED); if (thread != Thread.currentThread ()) error (SWT.ERROR_THREAD_INVALID_ACCESS); if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED); } static void checkDisplay (Thread thread, boolean multiple) { synchronized (Device.class) { for (int i=0; i- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
*- ERROR_DEVICE_DISPOSED - if the receiver has been disposed
** IMPORTANT: See the comment in Widget.checkSubclass()
. * * * @exception SWTException*
* * @see Widget#checkSubclass */ protected void checkSubclass () { if (!isValidClass (getClass ())) error (SWT.ERROR_INVALID_SUBCLASS); } void clearModal (Shell shell) { if (modalShells == null) return; int index = 0, length = modalShells.length; while (index < length) { if (modalShells [index] == shell) break; if (modalShells [index] == null) return; index++; } if (index == length) return; System.arraycopy (modalShells, index + 1, modalShells, index, --length - index); modalShells [length] = null; if (index == 0 && modalShells [0] == null) modalShells = null; Shell [] shells = getShells (); for (int i=0; i- ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass
** ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *ERROR_DEVICE_DISPOSED - if the receiver has been disposed * * * @see Device#dispose * * @since 2.0 */ public void close () { checkDevice (); Event event = new Event (); sendEvent (SWT.Close, event); if (event.doit) dispose (); } /** * Creates the device in the operating system. If the device * does not have a handle, this method may do nothing depending * on the device. ** This method is called before
* * @param data the DeviceData which describes the receiver * * @see #init */ @Override protected void create (DeviceData data) { checkSubclass (); checkDisplay(thread = Thread.currentThread (), false); createDisplay (data); register (this); if (Default == null) Default = this; } /** * Check if the XIM module is present and generates a warning for potential graphical issues * if GTK_IM_MODULE=xim is detected. See Bug 517671. * * Additionally, this method enforces IBus as the input method for SWT-GTK on GNOME. * This is because GNOME forces IBus by default, so any discrepancy can cause crashes on newer * versions of GTK3. */ void checkIMModule () { Mapinit
. *env = System.getenv(); String module = env.get("GTK_IM_MODULE"); if (module != null && module.equals("xim")) { System.err.println("***WARNING: Detected: GTK_IM_MODULE=xim. This input method is unsupported and can cause graphical issues."); System.err.println("***WARNING: Unset GTK_IM_MODULE or set GTK_IM_MODULE=ibus if flicking is experienced. "); } // Enforce ibus as the input module on GNOME if (OS.isGNOME) { long settings = GTK.gtk_settings_get_default (); byte[] ibus = Converter.wcsToMbcs ("ibus", true); if (settings != 0) OS.g_object_set (settings, GTK.gtk_im_module, ibus, 0); } } /** * Sets the org.eclipse.swt.internal.gtk.theme value with the current * GTK theme name. Checks if the current theme SWT is running with * is dark or not. This includes checking the GTK_THEME environment * variable, the theme name, and GSettings. * * @param themeName the full name of the current theme SWT is running with * @return true if the current theme is dark */ boolean checkAndSetThemeDetails (String themeName) { if (themeName.endsWith("-dark") || themeName.endsWith(":dark")) { System.setProperty("org.eclipse.swt.internal.gtk.theme", themeName); return true; } long settings = GTK.gtk_settings_get_default (); int [] darkThemePreferred = new int [1]; OS.g_object_get(settings, GTK.gtk_application_prefer_dark_theme, darkThemePreferred, 0); if (darkThemePreferred[0] != 0) { /* * When 'gtk-application-prefer-dark-theme' is set to true, GTK uses the 'dark' * variant of the theme specified in the system settings -- see 'get_theme_name' * in the GtkSettings source code for more context. */ System.setProperty("org.eclipse.swt.internal.gtk.theme", themeName.concat(":dark")); } else { System.setProperty("org.eclipse.swt.internal.gtk.theme", themeName); } return darkThemePreferred[0] != 0; } void createDisplay (DeviceData data) { if (!GTK.GTK4) { /* * AWT/Swing components always use GDK lock when calling GTK functions. * To allow them to be created on the main thread, GDK lock has to be reentrant. * This call replaces the standard GDK lock (GMutex) with GRecMutex. */ OS.swt_set_lock_functions (); GDK.gdk_threads_init (); GDK.gdk_threads_enter (); } boolean init; windowSizeSet = false; if (GTK.GTK4) { init = GTK4.gtk_init_check(); } else { init = GTK3.gtk_init_check(new long[]{0}, null); } if (!init) SWT.error(SWT.ERROR_NO_HANDLES, null, " [gtk_init_check() failed]"); //$NON-NLS-1$ checkIMModule(); //set GTK+ Theme name as property for introspection purposes themeName = OS.GTK_THEME_SET ? OS.GTK_THEME_SET_NAME : OS.getThemeName(); themeDark = checkAndSetThemeDetails(themeName); if (OS.isX11()) { xDisplay = GTK.GTK4 ? 0 : GDK.gdk_x11_get_default_xdisplay(); // set GDK backend if we are on X11 System.setProperty("org.eclipse.swt.internal.gdk.backend", "x11"); } if (OS.SWT_DEBUG) Device.DEBUG = true; long ptr = GTK.gtk_check_version (GTK3_MAJOR, GTK3_MINOR, GTK3_MICRO); if (ptr != 0) { int length = C.strlen (ptr); byte [] buffer = new byte [length]; C.memmove (buffer, ptr, length); System.out.println ("***WARNING: " + new String (Converter.mbcsToWcs (buffer))); //$NON-NLS-1$ System.out.println ("***WARNING: SWT requires GTK " + GTK3_MAJOR+ "." + GTK3_MINOR + "." + GTK3_MICRO); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ int major = GTK.gtk_get_major_version(), minor = GTK.gtk_get_minor_version (), micro = GTK.gtk_get_micro_version (); System.out.println ("***WARNING: Detected: " + major + "." + minor + "." + micro); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } fixed_type = OS.swt_fixed_get_type(); if (rendererClassInitProc == 0) { rendererClassInitCallback = new Callback (getClass (), "rendererClassInitProc", 2); //$NON-NLS-1$ rendererClassInitProc = rendererClassInitCallback.getAddress (); } if (GTK.GTK4) { if (rendererSnapshotProc == 0) { rendererSnapshotCallback = new Callback (getClass (), "rendererSnapshotProc", 6); //$NON-NLS-1$ rendererSnapshotProc = rendererSnapshotCallback.getAddress (); } } else { if (rendererRenderProc == 0) { rendererRenderCallback = new Callback (getClass (), "rendererRenderProc", 6); //$NON-NLS-1$ rendererRenderProc = rendererRenderCallback.getAddress (); } } if (rendererGetPreferredWidthProc == 0) { rendererGetPreferredWidthCallback = new Callback (getClass (), "rendererGetPreferredWidthProc", 4); //$NON-NLS-1$ rendererGetPreferredWidthProc = rendererGetPreferredWidthCallback.getAddress (); } if (text_renderer_type == 0) { GTypeInfo renderer_info = new GTypeInfo (); renderer_info.class_size = (short) GTK.GtkCellRendererTextClass_sizeof (); renderer_info.class_init = rendererClassInitProc; renderer_info.instance_size = (short) GTK.GtkCellRendererText_sizeof (); text_renderer_info_ptr = OS.g_malloc (GTypeInfo.sizeof); OS.memmove (text_renderer_info_ptr, renderer_info, GTypeInfo.sizeof); byte [] type_name = Converter.wcsToMbcs ("SwtTextRenderer", true); //$NON-NLS-1$ text_renderer_type = OS.g_type_register_static (GTK.GTK_TYPE_CELL_RENDERER_TEXT (), type_name, text_renderer_info_ptr, 0); } /* * In GTK4, GtkCellRendererPixbuf & GtkCellRendererToggle are final structs, and * we no longer have access to them in order to register our own type. */ if (!GTK.GTK4) { if (pixbuf_renderer_type == 0) { GTypeInfo renderer_info = new GTypeInfo(); renderer_info.class_size = (short) GTK.GtkCellRendererPixbufClass_sizeof(); renderer_info.class_init = rendererClassInitProc; renderer_info.instance_size = (short) GTK.GtkCellRendererPixbuf_sizeof(); pixbuf_renderer_info_ptr = OS.g_malloc(GTypeInfo.sizeof); OS.memmove(pixbuf_renderer_info_ptr, renderer_info, GTypeInfo.sizeof); byte[] type_name = Converter.wcsToMbcs("SwtPixbufRenderer", true); //$NON-NLS-1$ pixbuf_renderer_type = OS.g_type_register_static(GTK.GTK_TYPE_CELL_RENDERER_PIXBUF(), type_name, pixbuf_renderer_info_ptr, 0); } if (toggle_renderer_type == 0) { GTypeInfo renderer_info = new GTypeInfo(); renderer_info.class_size = (short) GTK.GtkCellRendererToggleClass_sizeof(); renderer_info.class_init = rendererClassInitProc; renderer_info.instance_size = (short) GTK.GtkCellRendererToggle_sizeof(); toggle_renderer_info_ptr = OS.g_malloc(GTypeInfo.sizeof); OS.memmove(toggle_renderer_info_ptr, renderer_info, GTypeInfo.sizeof); byte[] type_name = Converter.wcsToMbcs("SwtToggleRenderer", true); //$NON-NLS-1$ toggle_renderer_type = OS.g_type_register_static(GTK.GTK_TYPE_CELL_RENDERER_TOGGLE (), type_name, toggle_renderer_info_ptr, 0); } } GTK.gtk_widget_set_default_direction (GTK.GTK_TEXT_DIR_LTR); byte [] buffer = Converter.wcsToMbcs (APP_NAME, true); OS.g_set_prgname (buffer); if (OS.isX11() && !GTK.GTK4) { GDK.gdk_set_program_class (buffer); } /* Initialize the hidden shell */ if (GTK.GTK4) { shellHandle = GTK4.gtk_window_new(); } else { shellHandle = GTK3.gtk_window_new (GTK.GTK_WINDOW_TOPLEVEL); } if (shellHandle == 0) error (SWT.ERROR_NO_HANDLES); GTK.gtk_widget_realize (shellHandle); /* Initialize the filter and event callback */ eventCallback = new Callback (this, "eventProc", 2); //$NON-NLS-1$ eventProc = eventCallback.getAddress (); GDK.gdk_event_handler_set (eventProc, 0, 0); signalCallback = new Callback (this, "signalProc", 3); //$NON-NLS-1$ signalProc = signalCallback.getAddress (); if (!GTK.GTK4) { byte[] atomName = Converter.wcsToMbcs ("SWT_Window_" + APP_NAME, true); //$NON-NLS-1$ long atom = GDK.gdk_atom_intern(atomName, false); GDK.gdk_selection_owner_set(GTK3.gtk_widget_get_window(shellHandle), atom, OS.CurrentTime, false); GDK.gdk_selection_owner_get(atom); } latinKeyGroup = findLatinKeyGroup (); keysChangedCallback = new Callback (this, "keysChangedProc", 2); //$NON-NLS-1$ keysChangedProc = keysChangedCallback.getAddress (); long keymap; long display = GDK.gdk_display_get_default(); if (GTK.GTK4) { long keyboardDevice = GDK.gdk_seat_get_keyboard(GDK.gdk_display_get_default_seat(display)); OS.g_signal_connect (keyboardDevice, OS.changed, keysChangedProc, 0); } else { keymap = GDK.gdk_keymap_get_for_display(display); OS.g_signal_connect (keymap, OS.keys_changed, keysChangedProc, 0); } } /** * Determine key group of Latin layout, and update the layout group to key count map. * If there are multiple Latin keyboard layout group, return the first one. * * @return the most Latin keyboard layout group (i.e. group holding the max number of Latin alphabet keys) */ private int findLatinKeyGroup () { int result = 0; groupKeysCount = new HashMap<> (); long display = GDK.gdk_display_get_default(); // count all key groups for Latin alphabet for (int keyval = GDK.GDK_KEY_a; keyval <= GDK.GDK_KEY_z; keyval++) { long [] keys = new long [1]; int [] n_keys = new int [1]; boolean foundKeys; if (GTK.GTK4) { foundKeys = GDK.gdk_display_map_keyval(display, keyval, keys, n_keys); } else { long keymap = GDK.gdk_keymap_get_for_display(display); foundKeys = GDK.gdk_keymap_get_entries_for_keyval (keymap, keyval, keys, n_keys); } if (foundKeys) { GdkKeymapKey key_entry = new GdkKeymapKey (); for (int key = 0; key < n_keys [0]; key++) { OS.memmove (key_entry, keys [0] + key * GdkKeymapKey.sizeof, GdkKeymapKey.sizeof); Integer keys_count = (Integer) groupKeysCount.get (key_entry.group); if (keys_count != null) { keys_count++; } else { keys_count = 1; } groupKeysCount.put (key_entry.group, keys_count); } OS.g_free (keys [0]); } } // group with maximum keys count is Latin int max_keys_count = 0; for (Map.Entry entry : groupKeysCount.entrySet()) { Integer group = entry.getKey (); Integer keys_count = entry.getValue (); if (keys_count > max_keys_count) { result = group; max_keys_count = keys_count; } } return result; } /** * Return the most Latin keyboard layout group. */ int getLatinKeyGroup () { return latinKeyGroup; } /** * Return a mapping from layout group to the number of Latin alphabet (a-z) in each group */ Map getGroupKeysCount () { return groupKeysCount; } /** * 'keys-changed' event handler. * Updates the most Latin keyboard layout group field. */ long keysChangedProc (long keymap, long user_data) { latinKeyGroup = findLatinKeyGroup (); return 0; } Image createImage (String name) { byte[] buffer = Converter.wcsToMbcs(name, true); long pixbuf; if (GTK.GTK4) { long iconTheme = GTK4.gtk_icon_theme_get_for_display(GDK.gdk_display_get_default()); long paintable = GTK4.gtk_icon_theme_lookup_icon(iconTheme, buffer, 0, 48, 1, GTK.GTK_TEXT_DIR_LTR, GTK.GTK_ICON_LOOKUP_FORCE_REGULAR); long file = GTK4.gtk_icon_paintable_get_file(paintable); long texture = GDK.gdk_texture_new_from_file(file, 0); pixbuf = GDK.gdk_pixbuf_get_from_texture(texture); OS.g_object_unref(texture); OS.g_object_unref(file); OS.g_object_unref(paintable); } else { long iconTheme = GTK3.gtk_icon_theme_get_default(); pixbuf = GTK3.gtk_icon_theme_load_icon(iconTheme, buffer, 48, GTK.GTK_ICON_LOOKUP_FORCE_SIZE|GTK.GTK_ICON_LOOKUP_FORCE_REGULAR, 0); } if (pixbuf == 0) return null; int width = GDK.gdk_pixbuf_get_width (pixbuf); int height = GDK.gdk_pixbuf_get_height (pixbuf); int stride = GDK.gdk_pixbuf_get_rowstride (pixbuf); boolean hasAlpha = GDK.gdk_pixbuf_get_has_alpha (pixbuf); long pixels = GDK.gdk_pixbuf_get_pixels (pixbuf); byte [] data = new byte [stride * height]; C.memmove (data, pixels, data.length); OS.g_object_unref (pixbuf); ImageData imageData = null; if (hasAlpha) { PaletteData palette = new PaletteData (0xFF000000, 0xFF0000, 0xFF00); imageData = new ImageData (width, height, 32, palette); byte [] alpha = new byte [stride * height]; for (int y=0; y * This method is called after release
. * * @see Device#dispose * @see #release */ @Override protected void destroy () { if (this == Default) Default = null; deregister (this); destroyDisplay (); } void destroyDisplay () { if (!GTK.GTK4) GDK.gdk_threads_leave (); } long emissionProc (long ihint, long n_param_values, long param_values, long data) { long topLevel; if (GTK.GTK4) { topLevel = GTK4.gtk_widget_get_native (OS.g_value_peek_pointer(param_values)); } else { topLevel = GTK3.gtk_widget_get_toplevel (OS.g_value_peek_pointer(param_values)); } if (topLevel == data) { GTK.gtk_widget_set_direction (OS.g_value_peek_pointer(param_values), GTK.GTK_TEXT_DIR_RTL); } return 1; } /** * Returns the display which the given thread is the * user-interface thread for, or null if the given thread * is not a user-interface thread for any display. Specifying *null
as the thread will returnnull
* for the display. * * @param thread the user-interface thread * @return the display for the given thread */ public static Display findDisplay (Thread thread) { synchronized (Device.class) { for (int i=0; irun() null
runnable * is ignored. * * @param runnable code to run at dispose time. * * @exception SWTException
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
Widget
subclass which
* represents it in the currently running application, if
* such exists, or null if no matching widget can be found.
* * IMPORTANT: This method should not be called from * application code. The arguments are platform-specific. *
* * @param handle the handle for the widget * @return the SWT widget that the handle represents * * @exception SWTException-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
Widget
subclass which represents
* the handle/id pair in the currently running application,
* if such exists, or null if no matching widget can be found.
* * IMPORTANT: This method should not be called from * application code. The arguments are platform-specific. *
* * @param handle the handle for the widget * @param id the id for the subwidget (usually an item) * @return the SWT widget that the handle/id pair represents * * @exception SWTException-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
Widget
subclass which represents
* the widget/id pair in the currently running application,
* if such exists, or null if no matching widget can be found.
*
* @param widget the widget
* @param id the id for the subwidget (usually an item)
* @return the SWT subwidget (usually an item) that the widget/id pair represents
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
Shell
, or null
* if no shell belonging to the currently running application
* is active.
*
* @return the active shell or null
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
null
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* Applications may have associated arbitrary objects with the
* receiver in this fashion. If the objects stored in the
* properties need to be notified when the display is disposed
* of, it is the application's responsibility to provide a
* disposeExec()
handler which does so.
*
-
*
- ERROR_NULL_ARGUMENT - if the key is null *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* Applications may put arbitrary objects in this field. If
* the object stored in the display specific data needs to
* be notified when the display is disposed of, it is the
* application's responsibility to provide a
* disposeExec()
handler which does so.
*
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
null
if there is no application menu bar for the platform.
*
* @return the application menu bar, or null
*
* @exception SWTException -
*
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
LEFT
or RIGHT
.
* The button dismissal alignment is the ordering that should be used when positioning the
* default dismissal button for a dialog. For example, in a dialog that contains an OK and
* CANCEL button, on platforms where the button dismissal alignment is LEFT
, the
* button ordering should be OK/CANCEL. When button dismissal alignment is RIGHT
,
* the button ordering should be CANCEL/OK.
*
* @return the button dismissal order
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
null
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* Note: This operation is a hint and is not supported on * platforms that do not have this concept. *
* * @return the high contrast mode * * @exception SWTException-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
true
if the current OS theme has a dark appearance, else
* returns false
.
* * Note: This operation is a hint and is not supported on platforms that do not * have this concept. *
** Note: Windows 10 onwards users can separately configure the theme for OS and * Application level and this can be read from the Windows registry. Since the * application needs to honor the application level theme, this API reads the * Application level theme setting. *
* * @returntrue
if the current OS theme has a dark appearance, else
* returns false
.
*
* @since 3.112
*/
public static boolean isSystemDarkTheme () {
return themeDark;
}
int getLastEventTime () {
return lastEventTime;
}
Dialog getModalDialog () {
return modalDialog;
}
/**
* Returns the work area, an EWMH property to store the size
* and position of the screen not covered by dock and panel
* windows. See http://freedesktop.org/Standards/wm-spec.
*/
Rectangle getWorkArea() {
byte[] name = Converter.wcsToMbcs ("_NET_WORKAREA", true); //$NON-NLS-1$
long atom = GDK.gdk_atom_intern (name, true);
if (atom == GDK.GDK_NONE) return null;
long [] actualType = new long [1];
int[] actualFormat = new int[1];
int[] actualLength = new int[1];
long [] data = new long [1];
if (!GDK.gdk_property_get (GDK.gdk_get_default_root_window(), atom, GDK.GDK_NONE, 0, 16, 0, actualType, actualFormat, actualLength, data)) {
return null;
}
Rectangle result = null;
if (data [0] != 0) {
if (actualLength [0] == 16) {
int[] values = new int [4];
C.memmove (values, data[0], 16);
result = new Rectangle (values [0],values [1],values [2],values [3]);
} else if (actualLength [0] == 32) {
long[] values = new long [4];
C.memmove (values, data[0], 32);
result = new Rectangle ((int)values [0],(int)values [1],(int)values [2],(int)values [3]);
}
OS.g_free (data [0]);
}
return result;
}
/**
* Returns an array of monitors attached to the device.
*
* @return the array of monitors
*
* @since 3.0
*/
public Monitor[] getMonitors() {
checkDevice();
Monitor[] monitors = null;
Rectangle workArea = DPIUtil.autoScaleDown(getWorkArea ());
long display = GDK.gdk_display_get_default();
if (display != 0) {
int monitorCount;
long monitorList = 0;
if (GTK.GTK4) {
monitorList = GDK.gdk_display_get_monitors(display);
monitorCount = OS.g_list_model_get_n_items(monitorList);
} else {
monitorCount = GDK.gdk_display_get_n_monitors(display);
}
if (monitorCount > 0) {
monitors = new Monitor[monitorCount];
GdkRectangle geometry = new GdkRectangle();
for (int i = 0; i < monitorCount; i++) {
long gdkMonitor = GTK.GTK4 ? OS.g_list_model_get_item(monitorList, i) : GDK.gdk_display_get_monitor(display, i);
GDK.gdk_monitor_get_geometry(gdkMonitor, geometry);
Monitor monitor = new Monitor();
monitor.handle = gdkMonitor;
monitor.x = DPIUtil.autoScaleDown(geometry.x);
monitor.y = DPIUtil.autoScaleDown(geometry.y);
monitor.width = DPIUtil.autoScaleDown(geometry.width);
monitor.height = DPIUtil.autoScaleDown(geometry.height);
if (!OS.isX11()) {
int scaleFactor = (int) GDK.gdk_monitor_get_scale_factor(gdkMonitor);
monitor.zoom = scaleFactor * 100;
} else {
monitor.zoom = Display._getDeviceZoom(monitor.handle);
}
/* workarea was defined in GTK 3.4. If present, it will return the best results
* since it takes into account per-monitor trim. Not available in GTK4.
*/
if (!GTK.GTK4) GDK.gdk_monitor_get_workarea(gdkMonitor, geometry);
monitor.clientX = DPIUtil.autoScaleDown(geometry.x);
monitor.clientY = DPIUtil.autoScaleDown(geometry.y);
monitor.clientWidth = DPIUtil.autoScaleDown(geometry.width);
monitor.clientHeight = DPIUtil.autoScaleDown(geometry.height);
monitors[i] = monitor;
}
}
}
if (monitors == null) {
/* No multimonitor support detected, default to one monitor */
Monitor monitor = new Monitor();
Rectangle bounds = getBounds();
monitor.x = bounds.x;
monitor.y = bounds.y;
monitor.width = bounds.width;
monitor.height = bounds.height;
if (workArea != null) {
monitor.clientX = workArea.x;
monitor.clientY = workArea.y;
monitor.clientWidth = workArea.width;
monitor.clientHeight = workArea.height;
} else {
monitor.clientX = monitor.x;
monitor.clientY = monitor.y;
monitor.clientWidth = monitor.width;
monitor.clientHeight = monitor.height;
}
monitors = new Monitor[] { monitor };
}
return monitors;
}
/**
* Returns the primary monitor for that device.
*
* @return the primary monitor
*
* @since 3.0
*/
public Monitor getPrimaryMonitor() {
//Developer note, for testing see:
//org.eclipse.swt.tests.junit.Test_org_eclipse_swt_widgets_Display.test_getPrimaryMonitor()
checkDevice();
Monitor[] monitors = getMonitors();
int primaryMonitorIndex = 0;
if (GTK.GTK4) {
primaryMonitorIndex = 0;
} else {
//attempt to find actual primary monitor if one is configured:
long display = GDK.gdk_display_get_default();
long monitor = GDK.gdk_display_get_primary_monitor(display);
for (int i = 0; i < monitors.length; i++) {
long toCompare = GDK.gdk_display_get_monitor(display, i);
if (toCompare == monitor) {
primaryMonitorIndex = i;
break;
}
}
}
return monitors[primaryMonitorIndex];
}
/**
* Returns a (possibly empty) array containing all shells which have
* not been disposed and have the receiver as their display.
*
* @return the receiver's shells
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
syncExec
* or null if no such runnable is currently being invoked by
* the user-interface thread.
* * Note: If a runnable invoked by asyncExec is currently * running, this method will return null. *
* * @return the receiver's sync-interface thread * * @exception SWTException-
*
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
SWT
. Any value other
* than one of the SWT color constants which is passed
* in will result in the color black. This color should
* not be free'd because it was allocated by the system,
* not the application.
*
* @param id the color constant
* @return the matching color
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
SWT
. This cursor should
* not be free'd because it was allocated by the system,
* not the application. A value of null
will
* be returned if the supplied constant is not an SWT cursor
* constant.
*
* @param id the SWT cursor constant
* @return the corresponding cursor or null
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
SWT
. This image should
* not be free'd because it was allocated by the system,
* not the application. A value of null
will
* be returned either if the supplied constant is not an
* SWT icon constant or if the platform does not define an
* image that corresponds to the constant.
*
* @param id the SWT icon constant
* @return the corresponding image or null
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
null
on platforms where no menu is provided for the application.
*
* @return the system menu, or null
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
null
*
* @exception SWTException -
*
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
null
*
* @exception SWTException -
*
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
true
if a touch-aware input device is detected, or false
otherwise
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* This method is called after create
.
*
Display
. It is marked public only so that it
* can be shared within the packages provided by SWT. It is not
* available on all platforms, and should never be called from
* application code.
*
*
* @param hDC the platform specific GC handle
* @param data the platform specific GC data
*
* @noreference This method is not intended to be referenced by clients.
*/
@Override
public void internal_dispose_GC (long hDC, GCData data) {
Cairo.cairo_destroy (hDC);
}
/**
* Invokes platform specific functionality to allocate a new GC handle.
*
* IMPORTANT: This method is not part of the public
* API for Display
. It is marked public only so that it
* can be shared within the packages provided by SWT. It is not
* available on all platforms, and should never be called from
* application code.
*
-
*
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_NO_HANDLES if a handle could not be obtained for gc creation *
* NOTE: On right-to-left platforms where the coordinate * systems are mirrored, special care needs to be taken * when mapping coordinates from one control to another * to ensure the result is correctly mirrored. * * Mapping a point that is the origin of a rectangle and * then adding the width and height is not equivalent to * mapping the rectangle. When one control is mirrored * and the other is not, adding the width and height to a * point that was mapped causes the rectangle to extend * in the wrong direction. Mapping the entire rectangle * instead of just one point causes both the origin and * the corner of the rectangle to be mapped. *
* * @param from the sourceControl
or null
* @param to the destination Control
or null
* @param point to be mapped
* @return point with mapped coordinates
*
* @exception IllegalArgumentException -
*
- ERROR_NULL_ARGUMENT - if the point is null *
- ERROR_INVALID_ARGUMENT - if the Control from or the Control to have been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* NOTE: On right-to-left platforms where the coordinate * systems are mirrored, special care needs to be taken * when mapping coordinates from one control to another * to ensure the result is correctly mirrored. * * Mapping a point that is the origin of a rectangle and * then adding the width and height is not equivalent to * mapping the rectangle. When one control is mirrored * and the other is not, adding the width and height to a * point that was mapped causes the rectangle to extend * in the wrong direction. Mapping the entire rectangle * instead of just one point causes both the origin and * the corner of the rectangle to be mapped. *
* * @param from the sourceControl
or null
* @param to the destination Control
or null
* @param x coordinates to be mapped
* @param y coordinates to be mapped
* @return point with mapped coordinates
*
* @exception IllegalArgumentException -
*
- ERROR_INVALID_ARGUMENT - if the Control from or the Control to have been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* NOTE: On right-to-left platforms where the coordinate * systems are mirrored, special care needs to be taken * when mapping coordinates from one control to another * to ensure the result is correctly mirrored. * * Mapping a point that is the origin of a rectangle and * then adding the width and height is not equivalent to * mapping the rectangle. When one control is mirrored * and the other is not, adding the width and height to a * point that was mapped causes the rectangle to extend * in the wrong direction. Mapping the entire rectangle * instead of just one point causes both the origin and * the corner of the rectangle to be mapped. *
* * @param from the sourceControl
or null
* @param to the destination Control
or null
* @param rectangle to be mapped
* @return rectangle with mapped coordinates
*
* @exception IllegalArgumentException -
*
- ERROR_NULL_ARGUMENT - if the rectangle is null *
- ERROR_INVALID_ARGUMENT - if the Control from or the Control to have been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* NOTE: On right-to-left platforms where the coordinate * systems are mirrored, special care needs to be taken * when mapping coordinates from one control to another * to ensure the result is correctly mirrored. * * Mapping a point that is the origin of a rectangle and * then adding the width and height is not equivalent to * mapping the rectangle. When one control is mirrored * and the other is not, adding the width and height to a * point that was mapped causes the rectangle to extend * in the wrong direction. Mapping the entire rectangle * instead of just one point causes both the origin and * the corner of the rectangle to be mapped. *
* * @param from the sourceControl
or null
* @param to the destination Control
or null
* @param x coordinates to be mapped
* @param y coordinates to be mapped
* @param width coordinates to be mapped
* @param height coordinates to be mapped
* @return rectangle with mapped coordinates
*
* @exception IllegalArgumentException -
*
- ERROR_INVALID_ARGUMENT - if the Control from or the Control to have been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
post
is used to generate low level keyboard
* and mouse events. The intent is to enable automated UI
* testing by simulating the input from the user. Most
* SWT applications should never need to call this method.
* * Note that this operation can fail when the operating system * fails to generate the event for any reason. For example, * this can happen when there is no such key or mouse button * or when the system event queue is full. *
** Event Types: *
KeyDown, KeyUp *
The following fields in the Event
apply:
*
-
*
- (in) type KeyDown or KeyUp
Either one of:
*- (in) character a character that corresponds to a keyboard key *
- (in) keyCode the key code of the key that was typed,
* as defined by the key code constants in class
SWT
Optional (on some platforms):
*- (in) stateMask the state of the keyboard modifier,
* as defined by the key code constants in class
SWT
*
*
MouseDown, MouseUp
*The following fields in the Event
apply:
*
-
*
- (in) type MouseDown or MouseUp *
- (in) button the button that is pressed or released *
MouseMove
*The following fields in the Event
apply:
*
-
*
- (in) type MouseMove *
- (in) x the x coordinate to move the mouse pointer to in screen coordinates *
- (in) y the y coordinate to move the mouse pointer to in screen coordinates *
MouseWheel
*The following fields in the Event
apply:
-
*
- (in) type MouseWheel *
- (in) detail either SWT.SCROLL_LINE or SWT.SCROLL_PAGE *
- (in) count the number of lines or pages to scroll *
-
*
- ERROR_NULL_ARGUMENT - if the event is null *
-
*
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
true
* if there is potentially more work to do, or false
* if the caller can sleep until another event is placed on
* the event queue.
*
* In addition to checking the system event queue, this method also
* checks if any inter-thread messages (created by syncExec()
* or asyncExec()
) are waiting to be processed, and if
* so handles them before returning.
*
false
if the caller can sleep upon return from this method
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
- ERROR_FAILED_EXEC - if an exception occurred while running an inter-thread message *
true
when sent the message
* isDisposed()
.
*
* When a device is destroyed, resources that were acquired
* on behalf of the programmer need to be returned to the
* operating system. For example, if the device allocated a
* font to be used as the system font, this font would be
* freed in release
. Also,to assist the garbage
* collector and minimize the amount of memory that is not
* reclaimed when the programmer keeps a reference to a
* disposed device, all fields except the handle are zero'd.
* The handle is needed by destroy
.
*
destroy
.
*
* @see Device#dispose
* @see #destroy
*/
@Override
protected void release () {
try (ExceptionStash exceptions = new ExceptionStash ()) {
try {
sendEvent (SWT.Dispose, new Event ());
} catch (Error | RuntimeException ex) {
exceptions.stash (ex);
}
for (Shell shell : getShells ()) {
try {
if (!shell.isDisposed ()) shell.dispose ();
} catch (Error | RuntimeException ex) {
exceptions.stash (ex);
}
}
try {
if (tray != null) tray.dispose ();
} catch (Error | RuntimeException ex) {
exceptions.stash (ex);
}
tray = null;
for (;;) {
try {
if (!readAndDispatch ()) break;
} catch (Error | RuntimeException ex) {
exceptions.stash (ex);
}
}
if (disposeList != null) {
for (Runnable next : disposeList) {
if (next == null) continue;
try {
next.run ();
} catch (Error | RuntimeException ex) {
exceptions.stash (ex);
}
}
}
disposeList = null;
synchronizer.releaseSynchronizer ();
synchronizer = null;
releaseSessionManager ();
releaseDisplay ();
super.release ();
}
}
void releaseDisplay () {
windowCallback2.dispose (); windowCallback2 = null;
windowCallback3.dispose (); windowCallback3 = null;
windowCallback4.dispose (); windowCallback4 = null;
windowCallback5.dispose (); windowCallback5 = null;
if (windowCallback6 != null) {
windowCallback6.dispose (); windowCallback6 = null;
}
windowProc2 = windowProc3 = windowProc4 = windowProc5 = windowProc6 = 0;
if (changeValue != null) {
changeValue.dispose(); changeValue = null;
}
changeValueProc = 0;
if (GTK.GTK4) {
keyPressReleaseCallback.dispose();
keyPressReleaseCallback = null;
keyPressReleaseProc = 0;
focusCallback.dispose();
focusCallback = null;
focusProc = 0;
windowActiveCallback.dispose();
windowActiveCallback = null;
windowActiveProc = 0;
enterMotionCallback.dispose();
enterMotionCallback = null;
enterMotionProc = 0;
scrollCallback.dispose();
scrollCallback = null;
scrollProc = 0;
leaveCallback.dispose();
leaveCallback = null;
leaveProc = 0;
resizeCallback.dispose();
resizeCallback = null;
resizeProc = 0;
activateCallback.dispose();
activateCallback = null;
activateProc = 0;
gesturePressReleaseCallback.dispose();
gesturePressReleaseCallback = null;
gesturePressReleaseProc = 0;
snapshotDraw.dispose();
snapshotDraw = null;
snapshotDrawProc = 0;
}
notifyCallback.dispose();
notifyCallback = null;
notifyProc = 0;
/* Dispose checkIfEvent callback */
checkIfEventCallback.dispose(); checkIfEventCallback = null;
checkIfEventProc = 0;
/* Dispose preedit window */
if (preeditWindow != 0) {
if (GTK.GTK4) {
GTK4.gtk_window_destroy(preeditWindow);
} else {
GTK3.gtk_widget_destroy(preeditWindow);
}
}
preeditWindow = 0;
imControl = null;
/* Dispose the tooltip map callback */
sizeAllocateCallback.dispose (); sizeAllocateCallback = null;
sizeAllocateProc = 0;
sizeRequestCallback.dispose (); sizeRequestCallback = null;
sizeRequestProc = 0;
/* Dispose the shell map callback */
shellMapCallback.dispose (); shellMapCallback = null;
shellMapProc = 0;
/* Dispose the run async messages callback */
idleCallback.dispose (); idleCallback = null;
idleProc = 0;
if (idleHandle != 0) OS.g_source_remove (idleHandle);
idleHandle = 0;
/* Dispose GtkTreeView callbacks */
cellDataCallback.dispose (); cellDataCallback = null;
cellDataProc = 0;
/* Dispose the set direction callback */
setDirectionCallback.dispose (); setDirectionCallback = null;
setDirectionProc = 0;
/* Dispose the emission proc callback */
emissionProcCallback.dispose (); emissionProcCallback = null;
emissionProc = 0;
/* Dispose the set direction callback */
allChildrenCallback.dispose (); allChildrenCallback = null;
allChildrenProc = 0;
/* Dispose the caret callback */
if (caretId != 0) OS.g_source_remove (caretId);
caretId = 0;
caretProc = 0;
caretCallback.dispose ();
caretCallback = null;
/* Release closures */
for (int i = 0; i < Widget.LAST_SIGNAL; i++) {
if (closures [i] != 0) OS.g_closure_unref (closures [i]);
}
if (shellMapProcClosure != 0) OS.g_closure_unref (shellMapProcClosure);
/* Dispose the timer callback */
if (timerIds != null) {
for (int i=0; i-
*
- ERROR_NULL_ARGUMENT - if the listener is null *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
SWT
.
*
* @param eventType the type of event to listen for
* @param listener the listener which should no longer be notified
*
* @exception IllegalArgumentException -
*
- ERROR_NULL_ARGUMENT - if the listener is null *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* The application name can be used in several ways, * depending on the platform and tools being used. * Accessibility tools could ask for the application * name. On Windows, if the application name is set * to any value other than "SWT" (case insensitive), * it is used to set the application user model ID * which is used by the OS for taskbar grouping. *
*
* Specifying null
for the name clears it.
*
null
*/
public static void setAppName (String name) {
APP_NAME = name;
}
/**
* Sets the application version to the argument.
*
* @param version the new app version
*
* @since 3.6
*/
public static void setAppVersion (String version) {
APP_VERSION = version;
}
/**
* Sets the location of the on-screen pointer relative to the top left corner
* of the screen. Note: It is typically considered bad practice for a
* program to move the on-screen pointer location.
*
* @param x the new x coordinate for the cursor
* @param y the new y coordinate for the cursor
*
* @exception SWTException -
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_NULL_ARGUMENT - if the point is null *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* Applications may have associated arbitrary objects with the
* receiver in this fashion. If the objects stored in the
* properties need to be notified when the display is disposed
* of, it is the application's responsibility provide a
* disposeExec()
handler which does so.
*
-
*
- ERROR_NULL_ARGUMENT - if the key is null *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
* Applications may put arbitrary objects in this field. If
* the object stored in the display specific data needs to
* be notified when the display is disposed of, it is the
* application's responsibility provide a
* disposeExec()
handler which does so.
*
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
-
*
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
- ERROR_DEVICE_DISPOSED - if the receiver has been disposed *
- ERROR_FAILED_EXEC - if an exception occurred while running an inter-thread message *
* The default SWT error handling policy is to rethrow exceptions.
*
* @param runtimeExceptionHandler new exception handler to be registered.
* @since 3.106
*/
public final void setRuntimeExceptionHandler (Consumer
* The default SWT error handling policy is to rethrow exceptions.
*
* @param errorHandler new error handler to be registered.
* @since 3.106
*/
public final void setErrorHandler (Consumer
* Note that at the time the runnable is invoked, widgets
* that have the receiver as their display may have been
* disposed. Therefore, it is necessary to check for this
* case inside the runnable before accessing the widget.
*
* Note that at the time the runnable is invoked, widgets
* that have the receiver as their display may have been
* disposed. Therefore, it is necessary to check for this
* case inside the runnable before accessing the widget.
*
* Note that at the time the callable is invoked, widgets that have the receiver
* as their display may have been disposed. Therefore, it is necessary to check
* for this case inside the callable before accessing the widget.
*
* Any exception that is thrown from the callable is re-thrown in the calling
* thread. Note: The exception retains its original stack trace from the
* throwing thread. The call to {@code syncCall} will not be present in the
* stack trace.
*
* Note: This functionality is only available on Windows. Calling this
* method on other operating system will always return false.
*
* @since 3.127
*/
public boolean isRescalingAtRuntime() {
return false;
}
/**
* Activates or deactivates rescaling of shells at runtime whenever the DPI
* scaling of the shell's monitor changes. This is only safe to call as long as
* no shell has been created for this display. When changing the value after a
* shell has been created for this display, the effect is undefined.
*
* Note: This functionality is only available on Windows. Calling this
* method on other operating system will have no effect.
*
* @param activate whether rescaling shall be activated or deactivated
* @return whether activating or deactivating the rescaling was successful
* @since 3.127
*/
public boolean setRescalingAtRuntime(boolean activate) {
// not implemented for GTK
return false;
}
}
null
.
* @since 3.106
*/
public final Consumernull
.
* @since 3.106
*/
public final Consumertrue
if an event requiring dispatching was placed on the queue.
*
* @exception SWTException
*
*
* @see #wake
*/
public boolean sleep () {
checkDevice ();
if (gdkEventCount == 0) {
gdkEvents = null;
gdkEventWidgets = null;
}
if (settingsChanged) {
settingsChanged = false;
runSettings = true;
return false;
}
if (!synchronizer.isMessagesEmpty()) return true;
sendPreExternalEventDispatchEvent ();
if (!GTK.GTK4) GDK.gdk_threads_leave ();
/*
* The code below replicates event waiting behavior of g_main_context_iteration
* but leaves out event dispatch.
*/
if (fds == 0) {
allocated_nfds = 2;
fds = OS.g_malloc (OS.GPollFD_sizeof () * allocated_nfds);
}
max_priority [0] = timeout [0] = 0;
long context = OS.g_main_context_default ();
boolean result = false;
do {
if (OS.g_main_context_acquire (context)) {
result = OS.g_main_context_prepare (context, max_priority);
int nfds;
while ((nfds = OS.g_main_context_query (context, max_priority [0], timeout, fds, allocated_nfds)) > allocated_nfds) {
OS.g_free (fds);
allocated_nfds = nfds;
fds = OS.g_malloc (OS.GPollFD_sizeof() * allocated_nfds);
}
long poll = OS.g_main_context_get_poll_func (context);
if (poll != 0) {
if (nfds > 0 || timeout [0] != 0) {
/*
* Bug in GTK. For some reason, g_main_context_wakeup() may
* fail to wake up the UI thread from the polling function.
* The fix is to sleep for a maximum of 50 milliseconds.
*/
if (timeout [0] < 0) timeout [0] = 50;
wake = false;
OS.Call (poll, fds, nfds, timeout [0]);
}
}
OS.g_main_context_check (context, max_priority [0], fds, nfds);
OS.g_main_context_release (context);
}
} while (!result && synchronizer.isMessagesEmpty() && !wake);
wake = false;
if (!GTK.GTK4) GDK.gdk_threads_enter ();
sendPostExternalEventDispatchEvent ();
return true;
}
/**
* Causes the run()
method of the runnable to
* be invoked by the user-interface thread after the specified
* number of milliseconds have elapsed. If milliseconds is less
* than zero, the runnable is not executed.
*
*
* @exception SWTException
*
*
* @see #asyncExec
*/
public void timerExec (int milliseconds, Runnable runnable) {
checkDevice ();
if (runnable == null) error (SWT.ERROR_NULL_ARGUMENT);
if (timerList == null) timerList = new Runnable [4];
if (timerIds == null) timerIds = new int [4];
int index = 0;
while (index < timerList.length) {
if (timerList [index] == runnable) break;
index++;
}
if (index != timerList.length) {
OS.g_source_remove (timerIds [index]);
timerList [index] = null;
timerIds [index] = 0;
if (milliseconds < 0) return;
} else {
if (milliseconds < 0) return;
index = 0;
while (index < timerList.length) {
if (timerList [index] == null) break;
index++;
}
if (index == timerList.length) {
Runnable [] newTimerList = new Runnable [timerList.length + 4];
System.arraycopy (timerList, 0, newTimerList, 0, timerList.length);
timerList = newTimerList;
int [] newTimerIds = new int [timerIds.length + 4];
System.arraycopy (timerIds, 0, newTimerIds, 0, timerIds.length);
timerIds = newTimerIds;
}
}
int timerId;
if (GTK.GTK4) {
timerId = OS.g_timeout_add (milliseconds, timerProc, index);
} else {
timerId = GDK.gdk_threads_add_timeout (milliseconds, timerProc, index);
}
if (timerId != 0) {
timerIds [index] = timerId;
timerList [index] = runnable;
}
}
long timerProc (long i) {
if (timerList == null) return 0;
int index = (int)i;
if (0 <= index && index < timerList.length) {
Runnable runnable = timerList [index];
timerList [index] = null;
timerIds [index] = 0;
if (runnable != null) {
try {
runnable.run ();
} catch (RuntimeException exception) {
runtimeExceptionHandler.accept (exception);
} catch (Error exception) {
errorHandler.accept (exception);
}
}
}
return 0;
}
long caretProc (long clientData) {
caretId = 0;
if (currentCaret == null) {
return 0;
}
if (currentCaret.blinkCaret()) {
int blinkRate = currentCaret.blinkRate;
if (blinkRate == 0) return 0;
/*
* blink is set to true so that when gtk_draw() is called, we know it is the correct
* state to draw/redraw the caret. See Bug 517487.
*/
currentCaret.getParent().blink = true;
if (GTK.GTK4) {
caretId = OS.g_timeout_add (blinkRate, caretProc, 0);
} else {
caretId = GDK.gdk_threads_add_timeout (blinkRate, caretProc, 0);
}
} else {
currentCaret = null;
}
return 0;
}
/*
* Causes the caretProc method timing interval to be reset. This is useful as the blink rate
* intervals should always reset when the caret is moved. See Bug 517487.
*/
void resetCaretTiming() {
if (caretId != 0) {
OS.g_source_remove(caretId);
if (GTK.GTK4) {
caretId = OS.g_timeout_add (currentCaret.blinkRate, caretProc, 0);
} else {
caretId = GDK.gdk_threads_add_timeout (currentCaret.blinkRate, caretProc, 0);
}
}
}
long sizeAllocateProc (long handle, long arg0, long user_data) {
Widget widget = getWidget (user_data);
if (widget == null) return 0;
return widget.sizeAllocateProc (handle, arg0, user_data);
}
long sizeRequestProc (long handle, long arg0, long user_data) {
Widget widget = getWidget (user_data);
if (widget == null) return 0;
return widget.sizeRequestProc (handle, arg0, user_data);
}
void saveResources () {
int resourceCount = 0;
if (resources == null) {
resources = new Resource [RESOURCE_SIZE];
} else {
resourceCount = resources.length;
Resource [] newResources = new Resource [resourceCount + RESOURCE_SIZE];
System.arraycopy (resources, 0, newResources, 0, resourceCount);
resources = newResources;
}
if (errorImage != null) resources [resourceCount++] = errorImage;
if (infoImage != null) resources [resourceCount++] = infoImage;
if (questionImage != null) resources [resourceCount++] = questionImage;
if (warningImage != null) resources [resourceCount++] = warningImage;
errorImage = infoImage = questionImage = warningImage = null;
for (int i=0; inull
* as the runnable simply wakes the user-interface thread.
* null
*
* @exception SWTException
*
*
* @see #asyncExec
*/
public void syncExec (Runnable runnable) {
Synchronizer synchronizer;
synchronized (Device.class) {
if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED);
synchronizer = this.synchronizer;
synchronized (idleLock) {
if (idleNeeded && idleHandle == 0) {
if (GTK.GTK4) {
idleHandle = OS.g_idle_add (idleProc, 0);
} else {
idleHandle = GDK.gdk_threads_add_idle (idleProc, 0);
}
}
}
}
synchronizer.syncExec (runnable);
}
/**
* Calls the callable on the user-interface thread at the next reasonable
* opportunity, and returns the its result from this method. The thread which
* calls this method is suspended until the callable completes.
* ERROR_DEVICE_DISPOSED
- if the receiver
* has been disposed
* @exception E An exception that is thrown by the callable on the
* user-interface thread, and re-thrown on the calling
* thread
*
* @see #syncExec(Runnable)
* @see SwtCallable#call()
* @since 3.118
*/
public sleep
ing,
* causes it to be awakened and start running again. Note that this
* method may be called from any thread.
*
* @exception SWTException
*
*
* @see #sleep
*/
public void wake () {
synchronized (Device.class) {
if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED);
if (thread == Thread.currentThread ()) return;
wakeThread ();
}
}
void wakeThread () {
OS.g_main_context_wakeup (0);
wake = true;
}
void enterMotionProc(long controller, double x, double y, long user_data) {
long handle = GTK.gtk_event_controller_get_widget(controller);
Widget widget = getWidget(handle);
if (widget != null) widget.enterMotionProc(controller, x, y, user_data);
}
boolean scrollProc(long controller, double dx, double dy, long user_data) {
long handle = GTK.gtk_event_controller_get_widget(controller);
Widget widget = getWidget(handle);
if (widget != null) return widget.scrollProc(controller, dx, dy, user_data);
return false;
}
void focusProc(long controller, long user_data) {;
long handle = GTK.gtk_event_controller_get_widget(controller);
Widget widget = getWidget(handle);
if (widget != null) widget.focusProc(controller, user_data);
}
void windowActiveProc(long handle, long user_data) {;
Widget widget = getWidget(handle);
if (widget != null) widget.windowActiveProc(handle, user_data);
}
boolean keyPressReleaseProc(long controller, int keyval, int keycode, int state, long user_data) {
long handle = GTK.gtk_event_controller_get_widget(controller);
Widget widget = getWidget(handle);
if (widget == null) return false;
return widget.keyPressReleaseProc(controller, keyval, keycode, state, user_data);
}
void gesturePressReleaseProc(long gesture, int n_press, double x, double y, long user_data) {
long handle = GTK.gtk_event_controller_get_widget(gesture);
Widget widget = getWidget(handle);
if (widget != null) widget.gesturePressReleaseProc(gesture, n_press, x, y, user_data);
}
void leaveProc(long controller, long user_data) {
long handle = GTK.gtk_event_controller_get_widget(controller);
Widget widget = getWidget(handle);
if (widget != null) widget.leaveProc(controller, handle, user_data);
}
void computeSizeProc(long toplevel, long size, long user_data) {
//TODO: GTK4 - Could be needed for minimum Size, signal remains connected
}
void activateProc(long action, long parameter, long user_data) {
Widget widget = getWidget(user_data);
if(widget == null) return;
widget.gtk_activate(user_data);
}
void resizeProc(long handle, int width, int height) {
Widget widget = getWidget(handle);
if (widget != null) widget.gtk_size_allocate(handle, 0);
}
long notifyProc (long object, long param_spec, long user_data) {
Widget widget = getWidget (object);
if (widget == null) {
widget = getWidget (user_data);
if (widget == null) {
return 0;
} else {
/*
* There is a corner case where the connected handle is actually
* a GdkSurface.
*/
return widget.notifyProc(object, param_spec, Widget.NOTIFY_STATE);
}
}
return widget.notifyProc(object, param_spec, user_data);
}
boolean changeValue (long handle, int scroll, double value, long user_data) {
Widget widget = getWidget (handle);
if (widget == null) return false;
return widget.gtk_change_value(handle, scroll, value, user_data);
}
long windowProc (long handle, long user_data) {
Widget widget = getWidget (handle);
if (widget == null) return 0;
return widget.windowProc (handle, user_data);
}
long windowProc (long handle, long arg0, long user_data) {
Widget widget = getWidget (handle);
if (widget == null) return 0;
return widget.windowProc (handle, arg0, user_data);
}
long windowProc (long handle, long arg0, long arg1, long user_data) {
Widget widget = getWidget (handle);
if (widget == null) return 0;
return widget.windowProc (handle, arg0, arg1, user_data);
}
long windowProc (long handle, long arg0, long arg1, long arg2, long user_data) {
Widget widget = getWidget (handle);
if (widget == null) return 0;
return widget.windowProc (handle, arg0, arg1, arg2, user_data);
}
long windowProc (long handle, long arg0, long arg1, long arg2, long arg3, long user_data) {
Widget widget = getWidget (handle);
if (widget == null) return 0;
return widget.windowProc (handle, arg0, arg1, arg2, arg3, user_data);
}
long windowTimerProc (long handle) {
Widget widget = getWidget (handle);
if (widget == null) return 0;
return widget.timerProc (handle);
}
/**
* Gets the current cursor position relative to the upper left corner of the window.
* Available to GTK3 implementations only.
*
* @return the cursor position to x & y. Return value of the function is the window pointer underneath the cursor, can be NULL.
*/
long getWindowPointerPosition(long window, int[] x, int[] y, int[] mask) {
long display = 0;
if (window != 0) {
display = GDK.gdk_window_get_display(window);
} else {
window = GDK.gdk_get_default_root_window();
display = GDK.gdk_window_get_display(window);
}
long pointer = GDK.gdk_get_pointer(display);
if (OS.isWayland()) {
// Read the current mask value, but not the position. The position is not reliable on Wayland because
// the origin of the coordinates returned may change depending on the currently focused window.
// For instance, if a popup window is currently focused and this method is called with a window outside
// of the popup window, the returned coordinates are in relation to the root coordinate system of the
// popup (possibly negative values). See also issue GH-177.
GDK.gdk_window_get_device_position(window, pointer, null, null, mask);
var windowAtPosition = GDK.gdk_device_get_window_at_position(pointer, x, y);
if (windowAtPosition != 0 && windowAtPosition != window) {
int[] origin_x = new int[1], origin_y = new int[1];
GDK.gdk_window_get_origin(windowAtPosition, origin_x, origin_y);
x[0] += origin_x[0];
y[0] += origin_y[0];
GDK.gdk_window_get_origin(window, origin_x, origin_y);
x[0] -= origin_x[0];
y[0] -= origin_y[0];
}
return windowAtPosition;
} else {
return GDK.gdk_window_get_device_position(window, pointer, x, y, mask);
}
}
/**
* Gets the current cursor position relative to the upper left corner of the surface.
* Available to GTK4 implementations only.
*/
void getPointerPosition(double[] x, double[] y) {
long display = GDK.gdk_display_get_default();
long seat = GDK.gdk_display_get_default_seat(display);
long pointer = GDK.gdk_seat_get_pointer(seat);
GDK.gdk_device_get_surface_at_position(pointer, x, y);
}
long gdk_device_get_window_at_position (int[] win_x, int[] win_y) {
long display = GDK.gdk_display_get_default ();
long device = GDK.gdk_get_pointer(display);
return GDK.gdk_device_get_window_at_position (device, win_x, win_y);
}
long gdk_device_get_surface_at_position (double[] win_x, double[] win_y) {
long display = GDK.gdk_display_get_default ();
long device = GDK.gdk_get_pointer(display);
return GDK.gdk_device_get_surface_at_position (device, win_x, win_y);
}
static int _getDeviceZoom (long monitor_num) {
/*
* We can hard-code 96 as gdk_screen_get_resolution will always return -1
* if gdk_screen_set_resolution has not been called.
*/
int dpi = 96;
long display = GDK.gdk_display_get_default();
long monitor = GDK.gdk_display_get_monitor_at_point(display, 0, 0);
int scale = GDK.gdk_monitor_get_scale_factor(monitor);
dpi = dpi * scale;
return DPIUtil.mapDPIToZoom (dpi);
}
static boolean isActivateShellOnForceFocus() {
return "true".equals(System.getProperty("org.eclipse.swt.internal.activateShellOnForceFocus", "true")); //$NON-NLS-1$
}
/**
* {@return whether rescaling of shells at runtime when the DPI scaling of a
* shell's monitor changes is activated for this device}
*