@Override public boolean close(boolean forceClose) { // triggerCloseListener if (!super.close(forceClose)) { return false; } Utils.execSWTThread(new SWTRunnable() { @Override public void runWithDisplay(Display display) { if (swtItem != null && !swtItem.isDisposed()) { // this will triggerCloseListeners try { swtItem.dispose(); }catch( SWTException e ){ // getting internal 'Widget it disposed' here, ignore } swtItem = null; } } }); return true; }
public static boolean isThisThreadSWT() { SWTThread swt = SWTThread.getInstance(); if (swt == null) { //System.err.println("WARNING: SWT Thread not started yet"); } Display display = (swt == null) ? Display.getCurrent() : swt.getDisplay(); if (display == null) { return false; } // This will throw if we are disposed or on the wrong thread // Much better that display.getThread() as that one locks Device.class // and may end up causing sync lock when disposing try { display.getWarnings(); } catch (SWTException e) { return false; } return (display.getThread() == Thread.currentThread()); }
public void resourceChanged(IResourceChangeEvent event){ if(event.getType()==IResourceChangeEvent.PRE_CLOSE){ try{ if(event.getResource().getProject().isNatureEnabled(CommonNames.DERBY_NATURE)){ if(getRunning(event.getResource().getProject())){ stopDerbyServer(event.getResource().getProject()); } } }catch(SWTException swe){ //The SWTException is thrown during the Shell creation //Logger.log("Exception shutting down "+swe,IStatus.ERROR); //e.printStackTrace(); }catch(Exception e){ Logger.log("Exception shutting down "+e,IStatus.ERROR); } } }
public void populate(){ CoreContext ctx = CoreContext.getContext(); ProxyItem item = (ProxyItem) ctx.getObject(CoreObjects.PROXY_ITEM); try { if (item != null) { this.proxyItem = item; hostBox.setText(BaseUtils.noNull(item.getHost())); portBox.setText("" + item.getPort()); enabledCheck.setSelection(item.isProxy()); } else { this.proxyItem = new ProxyItem(); } } catch (SWTException e) { // dispose exception ExceptionHandler.handle(e); } }
private ImageData loadImageData() { ImageData[] imageDatas; try { imageDatas = new ImageLoader().load(new ByteArrayInputStream(favIconBytes)); } catch (SWTException e) { return null; } Optional<ImageData> optionalImageData = Arrays.stream(imageDatas).sorted((imageData1, imageData2) -> distanceFrom16x16ImageData(imageData1) - distanceFrom16x16ImageData(imageData2)) .findFirst(); if (!optionalImageData.isPresent()) { return null; } ImageData imageData = optionalImageData.get(); if (imageData.width <= 16 && imageData.height <= 16) { return imageData; } return imageData.scaledTo(16, 16); }
/** * Performs some weird initialization steps needed to run the tests. * * @param bot * to work with, must not be {@code null} */ public static void initializeWorkbench(final SwtWorkbenchBot bot) { Assert.isNotNull(bot, ARGUMENT_BOT); // Move mouse outside client area (to prevent problems with context menus) PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { try { final Robot robot = new Robot(); robot.mouseMove(MOUSE_POSITION_X, MOUSE_POSITION_Y); } catch (SWTException | AWTException wte) { throw new WrappedException("Error during initialisation SWT mouse", wte); } } }); // The welcome page must be closed before resetting the workbench to avoid trashing the UI: bot.closeWelcomePage(); bot.resetActivePerspective(); }
/** * Performs modifications to the Plugin Model. * * @param modification * a modification * @param monitor * progress monitor */ public void modifyModel(final ModelModification modification, final IProgressMonitor monitor) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } try { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { PDEModelUtility.modifyModel(modification, monitor); } }); } catch (SWTException e) { // If the build was cancelled while in syncExec() it will throw an SWTException if (monitor.isCanceled()) { throw new OperationCanceledException(); } else { throw e; } } }
/** * This can be used to verify an exception that is thrown on the UI thread. * * @param runnable * The runnable that would normally be sent to * {@link Display#syncExec(Runnable)}. * @return The first {@link SWTException} that was thrown, or {@code null} * if one was not thrown. */ protected SWTException catchSWTException(final Runnable runnable) { // Use an AtomicReference to catch the exception. final AtomicReference<SWTException> exceptionRef; exceptionRef = new AtomicReference<SWTException>(); // Run the runnable synchronously, but try to catch the SWTException. getDisplay().syncExec(new Runnable() { @Override public void run() { try { runnable.run(); } catch (SWTException e) { exceptionRef.set(e); } } }); // Return any SWTException that was thrown from the specified runnable. return exceptionRef.get(); }
/** * Enable or disable the ui. Can be called from non ui threads. * @param enabled */ private void enable(final boolean enabled) { try { Display d = mParent.getDisplay(); d.asyncExec(new Runnable() { @Override public void run() { if (mParent.isDisposed() == false) { doEnable(enabled); } } }); } catch (SWTException e) { // disposed. do nothing } }
/** * Processes the result of a command sent to the console. * @param result the result of the command. */ private boolean processCommandResult(final String result) { if (result != EmulatorConsole.RESULT_OK) { try { mParent.getDisplay().asyncExec(new Runnable() { @Override public void run() { if (mParent.isDisposed() == false) { MessageDialog.openError(mParent.getShell(), "Emulator Console", result); } } }); } catch (SWTException e) { // we're quitting, just ignore } return false; } return true; }
/** * Sent when an existing client information changed. * <p/> * This is sent from a non UI thread. * @param client the updated client. * @param changeMask the bit mask describing the changed properties. It can contain * any of the following values: {@link Client#CHANGE_INFO}, {@link Client#CHANGE_NAME} * {@link Client#CHANGE_DEBUGGER_STATUS}, {@link Client#CHANGE_THREAD_MODE}, * {@link Client#CHANGE_THREAD_DATA}, {@link Client#CHANGE_HEAP_MODE}, * {@link Client#CHANGE_HEAP_DATA}, {@link Client#CHANGE_NATIVE_HEAP_DATA} * * @see IClientChangeListener#clientChanged(Client, int) */ @Override public void clientChanged(final Client client, int changeMask) { if (client == getCurrentClient()) { if ((changeMask & Client.CHANGE_HEAP_MODE) == Client.CHANGE_HEAP_MODE || (changeMask & Client.CHANGE_HEAP_DATA) == Client.CHANGE_HEAP_DATA) { try { mTop.getDisplay().asyncExec(new Runnable() { @Override public void run() { clientSelected(); } }); } catch (SWTException e) { // display is disposed (app is quitting most likely), we do nothing. } } } }
/** * Opens the option panel. * </p> * <b>This must be called from the UI thread</b> */ @UiThread public void openOptionPanel() { try { EventDisplayOptions dialog = new EventDisplayOptions(mParent.getShell()); if (dialog.open(mCurrentEventLogParser, mEventDisplays, mEvents)) { synchronized (mLock) { // get the new EventDisplay list mEventDisplays.clear(); mEventDisplays.addAll(dialog.getEventDisplays()); // since the list of EventDisplay changed, we store it. saveEventDisplays(); rebuildUi(); } } } catch (SWTException e) { Log.e("EventLog", e); //$NON-NLS-1$ } }
private void resetUI(boolean inUiThread) { mEvents.clear(); // the ui is static we just empty it. if (inUiThread) { resetUiFromUiThread(); } else { try { Display d = mBottomParentPanel.getDisplay(); // run sync as we need to update right now. d.syncExec(new Runnable() { @Override public void run() { if (mBottomParentPanel.isDisposed() == false) { resetUiFromUiThread(); } } }); } catch (SWTException e) { // display is disposed, we're quitting. Do nothing. } } }
/** * Schedules the UI thread to execute a {@link Runnable} calling {@link #displayNewEvents()}. */ private void scheduleUIEventHandler() { try { Display d = mBottomParentPanel.getDisplay(); d.asyncExec(new Runnable() { @Override public void run() { if (mBottomParentPanel.isDisposed() == false) { if (mCurrentEventLogParser != null) { displayNewEvents(); } } } }); } catch (SWTException e) { // if the ui is disposed, do nothing } }
public void run() { setBlockOnOpen(true); try { open(); } catch (SWTException e) { // Ignore "widget disposed" errors after we closed. if (!getShell().isDisposed()) { throw e; } } TreeViewModel.getModel().removeTreeChangeListener(mTreeChangeListener); PixelPerfectModel.getModel().removeImageChangeListener(mImageChangeListener); ImageLoader.dispose(); mDirector.stopListenForDevices(); mDirector.stopDebugBridge(); mDirector.terminate(); }
public void loadOverlay(final Shell shell) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { FileDialog fileDialog = new FileDialog(shell, SWT.OPEN); fileDialog.setFilterExtensions(new String[] { "*.jpg;*.jpeg;*.png;*.gif;*.bmp" //$NON-NLS-1$ }); fileDialog.setFilterNames(new String[] { "Image (*.jpg, *.jpeg, *.png, *.gif, *.bmp)" }); fileDialog.setText("Choose an overlay image"); String fileName = fileDialog.open(); if (fileName != null) { try { Image image = new Image(Display.getDefault(), fileName); PixelPerfectModel.getModel().setOverlayImage(image); } catch (SWTException e) { Log.e(TAG, "Unable to load image from " + fileName); } } } }); }
public long create(GLCanvas canvas, GLData attribs, GLData effective) { Canvas dummycanvas = new Canvas(canvas.getParent(), checkStyle(canvas.getParent(), canvas.getStyle())); long context = 0L; MemoryStack stack = MemoryStack.stackGet(); int ptr = stack.getPointer(); try { context = create(canvas.handle, dummycanvas.handle, attribs, effective); } catch (SWTException e) { stack.setPointer(ptr); SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH, e); } final long finalContext = context; dummycanvas.dispose(); Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Dispose: deleteContext(finalContext); break; } } }; canvas.addListener(SWT.Dispose, listener); return context; }
public void showBalloonToolTip(final Map<Threshold, String> thresholdsReached) { if (configuration.getBoolean("gui.tray.tooltip", Defaults.GUI_TRAY_TOOLTIP) && showToolTip && thresholdsReached != null && !thresholdsReached.isEmpty() && toolTip != null && trayItem != null && gui != null && gui.getShell() != null && !gui.getShell().isDisposed() && !trayItem.isDisposed() && !toolTip.isDisposed()) { final StringBuilder message = new StringBuilder(); for (final Entry<Threshold, String> entry : thresholdsReached.entrySet()) { message.append(entry.getKey().getKey()).append('=').append(entry.getValue()).append(NewLine.SYSTEM_LINE_SEPARATOR); } try { trayItem.getDisplay().syncExec(new Runnable() { @Override public void run() { if (configuration.getBoolean("gui.tray.tooltip", Defaults.GUI_TRAY_TOOLTIP) && showToolTip && toolTip != null && trayItem != null && gui != null && gui.getShell() != null && !gui.getShell().isDisposed() && !trayItem.isDisposed() && !toolTip.isDisposed() && trayItem.getVisible() && !gui.getShell().getVisible()) { toolTip.setMessage(message.toString().trim()); toolTip.setVisible(true); showToolTip = false; } } }); } catch (final SWTException e) { logger.log(Level.FINE, e.toString(), e); } } }
/** * Queues a runnable for later {@link Display#asyncExec(Runnable)} on the {@link Display} of the passed {@link Widget}. * Essentially this ensures that the runnable will be asyncExec'ed and put on the runnable queue no matter what. It will NOT run * immediately if the invoking thread is already the UI thread--for that behavior use * {@link #runInDisplayThread(Widget, Runnable)}. * * @param widget * the widget associated with this task. It will be checked for disposal prior to the runnable being executed. * @param runnable * the task to carry out. */ public static void runLaterInDisplayThread(final Widget widget, final Runnable runnable) { if (widget == null || widget.isDisposed()) return; Display controlDisplay = null; try { controlDisplay = widget.getDisplay(); } catch (SWTException e) { return; } if (controlDisplay.isDisposed()) return; controlDisplay.asyncExec(new Runnable() { @Override public void run() { // check the widget for validity before running the posted runnable if (!widget.isDisposed()) { runnable.run(); } } }); }
private void refresh(boolean repopulateCombo) { if (combo == null || combo.isDisposed()) return; // $TODO GTK workaround try { if (zoomManager == null) { combo.setEnabled(false); combo.setText(""); //$NON-NLS-1$ } else { if (repopulateCombo) combo.setItems(getZoomManager().getZoomLevelsAsText()); String zoom = getZoomManager().getZoomAsText(); int index = combo.indexOf(zoom); if (index == -1 || forceSetText) combo.setText(zoom); else combo.select(index); combo.setEnabled(true); } } catch (SWTException exception) { if (!SWT.getPlatform().equals("gtk")) //$NON-NLS-1$ throw exception; } }
/** * @see IFigure#setBackgroundColor(Color) */ public void setBackgroundColor(Color bg) { // Set background color to bg unless in high contrast mode. // In that case, get the color from system if (bgColor != null && bgColor.equals(bg)) return; Display display = Display.getCurrent(); if (display == null) { display = Display.getDefault(); } Color highContrastClr = null; try { if (display.getHighContrast()) { highContrastClr = display .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); } } catch (SWTException e) { highContrastClr = null; } bgColor = highContrastClr == null ? bg : highContrastClr; repaint(); }
/** * @see IFigure#setForegroundColor(Color) */ public void setForegroundColor(Color fg) { // Set foreground color to fg unless in high contrast mode. // In that case, get the color from system if (fgColor != null && fgColor.equals(fg)) return; Display display = Display.getCurrent(); if (display == null) { display = Display.getDefault(); } Color highContrastClr = null; try { if (display.getHighContrast()) { highContrastClr = display .getSystemColor(SWT.COLOR_WIDGET_FOREGROUND); } } catch (SWTException e) { highContrastClr = null; } fgColor = highContrastClr == null ? fg : highContrastClr; repaint(); }
public Image createImage(boolean returnMissingImageOnError, Device device) { Image img = ImageDescriptorHelper.getInstance() .getImage(location, name); if (img != null) { return img; } String path = getFilePath(); if (path == null) return createDefaultImage(returnMissingImageOnError, device); try { return new Image(device, path); } catch (SWTException exception) { // if we fail try the default way using a stream } return super.createImage(returnMissingImageOnError, device); }
@Override protected void reactOnChange(Notification notification) { // We don't want to use defaultDisplay() but the appropriate display. Unfortunately we // can not know whether the control is disposed or not (race conditions might occur // between checking and using the getDisplay() method). So, we simply catch an occurring // exception. Display viewerDisplay; try { viewerDisplay = viewer.getControl().getDisplay(); } catch (SWTException e) { return; } viewerDisplay.syncExec(new Runnable() { @Override public void run() { if (!viewer.getControl().isDisposed()) { viewer.refresh(); } } }); }
/** * Creates a new instance of GUI exception * * @param pluginId * the id of the plugin * @param cause * the cause which invoked the exception * * @return the GUIException created */ public static GUIException createGUIException( String pluginId, Throwable cause ) { String errorCode = GUI_ERROR_CODE_UNEXPECTED; if ( cause instanceof IOException ) { errorCode = GUI_ERROR_CODE_IO; } else if ( cause instanceof OutOfMemoryError ) { errorCode = GUI_ERROR_CODE_OUT_OF_MEMORY; } else if ( cause instanceof SWTException ) { errorCode = GUI_ERROR_CODE_SWT; } GUIException ex = new GUIException( pluginId, errorCode, cause ); if ( errorCode != GUI_ERROR_CODE_UNEXPECTED ) { ex.setSeverity( BirtException.INFO | BirtException.ERROR ); } return ex; }
/** * Returns the reason for error status * * @return the reason */ public String getReason( ) { String reason = null; if ( getCause( ) instanceof OutOfMemoryError ) { reason = MSG_OUT_OF_MEMORY; } else if ( getCause( ) instanceof IOException || getCause( ) instanceof SWTException ) { reason = getLocalizedMessage( ); } else { reason = MSG_UNEXPECTED_EXCEPTION_OCURR; } return reason; }
/** * Checks whether the image is corrupt. * * @param path * path to the image * @return true if the image is corrupt and should not be exported, false otherwise. */ private static boolean isImageCorrupt( String path ) { Image image = null; try { image = new Image( UIUtils.getDisplay(), path ); } catch ( SWTException e ) { if ( e.getCause() instanceof FileNotFoundException == false ) { log.warn( String.format( "Image '%s' is corrupt and will not be exported.", path ) ); return true; } } finally { if ( image != null ) image.dispose(); } return false; }
/** * Converts the image to <code>ImageData</code>. Expects the * <code>DirectColorModel</code>. * * @param bufferedImage * the image to convert * @return the extracted image data */ public static ImageData convertToImageData(BufferedImage bufferedImage) { if (!(bufferedImage.getColorModel() instanceof DirectColorModel)) { throw new SWTException(SWT.ERROR_UNSUPPORTED_FORMAT); } DirectColorModel colorModel = (DirectColorModel) bufferedImage.getColorModel(); PaletteData palette = new PaletteData(colorModel.getRedMask(), colorModel.getGreenMask(), colorModel.getBlueMask()); ImageData data = new ImageData(bufferedImage.getWidth(), bufferedImage.getHeight(), colorModel.getPixelSize(), palette); WritableRaster raster = bufferedImage.getRaster(); int components = colorModel.getComponentSize().length; int[] pixels = new int[components]; for (int x = 0; x < data.width; x++) { for (int y = 0; y < data.height; y++) { raster.getPixel(x, y, pixels); int pixel = palette.getPixel(new RGB(pixels[0], pixels[1], pixels[2])); data.setPixel(x, y, pixel); } } return data; }
/** * Causes the <code>run()</code> method of the runnable to be invoked * synchronously on the UI-thread using the main control's display but only * if neither the main control nor the attached display are disposed. Any * SWTException in the runnable will terminate the runnable but further will * only be logged. * * @param controlWidget * the main control widget whose display will be used * @param runnable * the runnable to invoke */ public static void submitSyncExecIgnoreDisposed(final Widget controlWidget, final Runnable runnable) { final Display display = controlWidget != null ? controlWidget.getDisplay() : null; Runnable safeRunnable = new Runnable() { @Override public void run() { try { boolean isControlValid = controlWidget != null && !controlWidget.isDisposed(); boolean isDisplayValid = !display.isDisposed(); boolean isSafeToRun = isDisplayValid && isControlValid; if (isSafeToRun) { runnable.run(); } } catch (SWTException e) { LOGGER.debug("runnable terminated due to SWTException", e); } } }; if (display != null && !display.isDisposed()) { display.syncExec(safeRunnable); } }
private void asyncUpdatePreview() { Runnable update = new Runnable() { @Override public void run() { try { updatePreview(); } catch(SWTException e) { // Ignore widget disposed errors } } }; shell.getDisplay().asyncExec(update); }
public void run(Injector uiInjector) { startGui(); executorService.submit(() -> Main.finishStartup(uiInjector)); while (!display.isDisposed()) { try { if (!display.readAndDispatch()) { display.sleep(); } } catch (SWTException ex) { ex.printStackTrace(); } } disposeGui(); executorService.shutdown(); }