Java Code Examples for org.eclipse.swt.widgets.Display#isDisposed()

The following examples show how to use org.eclipse.swt.widgets.Display#isDisposed() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Displays a dialog with a question as message.
 *
 * @param title
 *            The title to display
 * @param message
 *            The message to display
 * @return returns the result of the dialog
 */
private static boolean displayYesNoMessage(final String title, final String message) {
	final boolean[] result= { true};
	final Display display= PlatformUI.getWorkbench().getDisplay();
	if (display != null && !display.isDisposed()) {
		display.syncExec(new Runnable() {

			public final void run() {
				if (!display.isDisposed()) {
					final Shell shell= display.getActiveShell();
					if (shell != null && !shell.isDisposed())
						result[0]= MessageDialog.openQuestion(shell, title, message);
				}
			}
		});
	}
	return result[0];
}
 
Example 2
Source Project: neoscada   File: FactoryEditor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected void handleSetResult ( final FactoryInformation factory, final String connectionUri )
{
    final Display display = getSite ().getShell ().getDisplay ();
    if ( !display.isDisposed () )
    {
        display.asyncExec ( new Runnable () {

            @Override
            public void run ()
            {
                if ( !display.isDisposed () )
                {
                    setResult ( factory, connectionUri );
                }
            }
        } );
    }
}
 
Example 3
/**
 * Displays an appropriate error message for a specific problem.
 *
 * @param message
 *            The message to display
 */
private static void displayErrorMessage(final String message) {
	final Display display= PlatformUI.getWorkbench().getDisplay();
	if (display != null && !display.isDisposed()) {
		display.asyncExec(new Runnable() {

			public final void run() {
				if (!display.isDisposed()) {
					final Shell shell= display.getActiveShell();
					if (shell != null && !shell.isDisposed())
						MessageDialog.openError(shell, CorrectionMessages.SerialVersionHashOperation_dialog_error_caption, Messages.format(CorrectionMessages.SerialVersionHashOperation_dialog_error_message, message));
				}
			}
		});
	}
}
 
Example 4
/**
 * Runs the event loop for the given shell.
 * 
 * @param loopShell
 *            the shell
 */
private void runEventLoop(Shell loopShell)
{
	// Use the display provided by the shell if possible
	Display display = loopShell.getDisplay();
	while (!loopShell.isDisposed())
	{
		try
		{
			if (!display.readAndDispatch())
			{
				display.sleep();
			}
		}
		catch (Throwable e)
		{
			// FIXME Handle exception in some way
			// exceptionHandler.handleException(e);
		}
	}
	if (!display.isDisposed())
		display.update();
}
 
Example 5
Source Project: olca-app   File: Popup.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private static void show(Image image, String title, String text) {
	UIJob job = new UIJob("Open popup") {

		@Override
		public IStatus runInUIThread(IProgressMonitor monitor) {
			Display display = getDisplay();
			if (display == null || display.isDisposed())
				return Status.CANCEL_STATUS;
			Notifier.notify(
					image,
					title != null ? title : "?",
					text != null ? text : "?",
					NotifierTheme.YELLOW_THEME);
			return Status.OK_STATUS;
		}
	};
	job.schedule();
}
 
Example 6
private void resetView() {

        // Stop thread if needed
        fStopThread = true;

        // Remove all content in tables
        final Display display = Display.getDefault();
        if (display == null || display.isDisposed()) {
            return;
        }
        display.asyncExec(() -> {
            if (display.isDisposed()) {
                return;
            }
            Map<TmfPcapProtocol, Table> tableMap = fTableMap;
            if (tableMap == null) {
                return;
            }
            for (Table table : tableMap.values()) {
                if (!table.isDisposed()) {
                    table.removeAll();
                }
            }
        });
    }
 
Example 7
/**
 * Note that all parameters (x, y, shellTooltipArea) must be in display coordinates.
 * @param control 
 * @param display 
 */
private boolean inKeepUpZone(int x, int y, Control control, Display display) {
    if (display.isDisposed()) {
        return true; //received something from a dead display? Let's keep on showing it... (not sure if this actually happens)
    }
    Point point = display.map(control, null, x, y);

    int margin = 20;
    //the bounds are in display coordinates
    Rectangle bounds = Geometry.copy(fShellTooltipArea);

    //expand so that we have some tolerance to keep it open 
    Geometry.expand(bounds, margin, margin, margin, margin);
    return bounds.contains(point.x, point.y);
}
 
Example 8
Source Project: hop   File: Translator.java    License: Apache License 2.0 5 votes vote down vote up
public static void main( String[] args ) throws Exception {

    if ( args.length != 2 ) {
      System.err.println( "Usage: Translator <translator.xml> <path-to-source>" );
      System.err.println( "Example:" );
      System.err.println( "sh hop-translator.sh translator.xml /home/john/git/hop/" );
      System.exit( 1 );
    }

    HopClientEnvironment.init();

    String configFile = args[ 0 ];
    String sourceFolder = args[ 1 ];

    Display display = new Display();
    ILogChannel log = new LogChannel( APP_NAME );

    HopNamespace.setNamespace( TRANSLATOR_NAMESPACE );

    Translator translator = new Translator( display );
    translator.loadConfiguration( configFile, sourceFolder );
    translator.open();

    try {
      while ( !display.isDisposed() ) {
        if ( !display.readAndDispatch() ) {
          display.sleep();
        }
      }
    } catch ( Throwable e ) {
      log.logError( BaseMessages.getString( PKG, "i18n.UnexpectedError", e.getMessage() ) );
      log.logError( Const.getStackTracker( e ) );
    }
  }
 
Example 9
protected final void fireChangeEvent ( final Collection<?> changes )
{

    final LabelProviderChangedEvent event = new LabelProviderChangedEvent ( ViewerLabelProvider.this, changes.toArray () );
    final ILabelProviderListener[] listenerArray = ViewerLabelProvider.this.listeners.toArray ( new ILabelProviderListener[ViewerLabelProvider.this.listeners.size ()] );

    final Display display = getDisplay ();
    if ( !display.isDisposed () )
    {
        display.asyncExec ( new Runnable () {

            public void run ()
            {
                for ( final ILabelProviderListener listener : listenerArray )
                {
                    try
                    {
                        listener.labelProviderChanged ( event );
                    }
                    catch ( final Exception e )
                    {
                        Policy.getLog ().log ( new Status ( IStatus.ERROR, Policy.JFACE_DATABINDING, e.getLocalizedMessage (), e ) );
                    }
                }

            }
        } );

    }
}
 
Example 10
private static boolean queryDialog(final Shell parent, final String title, final String message) {
	Display display= parent.getDisplay();
	if (display == null || display.isDisposed())
		return false;

	final boolean[] returnValue= new boolean[1];
	Runnable runnable= new Runnable() {
		public void run() {
			returnValue[0]= MessageDialog.openQuestion(parent, title, message);
		}
	};
	display.syncExec(runnable);

	return returnValue[0];
}
 
Example 11
Source Project: pentaho-kettle   File: Translator2.java    License: Apache License 2.0 5 votes vote down vote up
public static void main( String[] args ) throws Exception {

    if ( args.length != 2 ) {
      System.err.println( "Usage: Translator <translator.xml> <path-to-source>" );
      System.err.println( "Example:" );
      System.err.println( "sh translator.sh translator.xml ." );
      System.exit( 1 );
    }

    KettleClientEnvironment.init();

    String configFile = args[0];
    String sourceFolder = args[1];

    Display display = new Display();
    LogChannelInterface log = new LogChannel( APP_NAME );
    PropsUI.init( display, Props.TYPE_PROPERTIES_SPOON );

    Translator2 translator = new Translator2( display );
    translator.loadConfiguration( configFile, sourceFolder );
    translator.open();

    try {
      while ( !display.isDisposed() ) {
        if ( !display.readAndDispatch() ) {
          display.sleep();
        }
      }
    } catch ( Throwable e ) {
      log.logError( BaseMessages.getString( PKG, "i18n.UnexpectedError", e.getMessage() ) );
      log.logError( Const.getStackTracker( e ) );
    }
  }
 
Example 12
Source Project: elexis-3-core   File: UiDesk.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Run a runnable asynchroneously in the UI Thread The method will immediately return (not wait
 * for the runnable to exit)
 */
public static void asyncExec(Runnable runnable){
	Display disp = getDisplay();
	if (!disp.isDisposed()) {
		disp.asyncExec(runnable);
	}
}
 
Example 13
Source Project: swt-bling   File: FontLoader.java    License: MIT License 5 votes vote down vote up
/**
 * Creates an instance of FontLoader with the specified Display
 *
 * @param display
 */
public FontLoader(Display display) {
  this.display = display;

  // Dispose all cached font resources on exit and clean up extracted files if possible
  if (display != null && !display.isDisposed()) {
    display.disposeExec(new Runnable() {
      @Override
      public void run() {
        deleteExtractedFiles();
      }
    });
  }
}
 
Example 14
Source Project: SWET   File: SWTUtil.java    License: MIT License 5 votes vote down vote up
public static void eventLoop() {
	Display dsp = getDisplay();
	while (!dsp.isDisposed()) {
		if (!dsp.readAndDispatch())
			dsp.sleep();
	}
}
 
Example 15
@Override
protected Point getInitialLocation(Point initialSize)
{
	Display display = getShell().getDisplay();
	if (display != null && !display.isDisposed())
	{
		return display.getCursorLocation();
	}
	return super.getInitialLocation(initialSize);
}
 
Example 16
protected Display getDisplay() {
	Shell shell = getSite().getShell();
	if (shell == null || shell.isDisposed()) {
		return null;
	}
	Display display = shell.getDisplay();
	if (display == null || display.isDisposed()) {
		return null;
	}
	return display;
}
 
Example 17
Source Project: tracecompass   File: SDWidget.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void run() {
    Display display = Display.getDefault();
    if ((display == null) || (display.isDisposed())) {
        return;
    }
    display.asyncExec(() -> {
        if (fSdWidget.isDisposed()) {
            return;
        }
        fSdWidget.fDragX += fDeltaX;
        fSdWidget.fDragY += fDeltaY;
        fSdWidget.scrollBy(fDeltaX, fDeltaY);
    });
}
 
Example 18
/**
 * Returns the change that will be executed when the proposal is applied.
 * This method calls {@link #createChange()} to compute the change.
 * 
 * @return the change for this proposal, can be <code>null</code> in rare cases if creation of
 *         the change failed
 * @throws CoreException when the change could not be created
 */
public final Change getChange() throws CoreException {
	if (Util.isGtk()) {
		// workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=293995 :
		// [Widgets] Deadlock while UI thread displaying/computing a change proposal and non-UI thread creating image
		
		// Solution is to create the change outside a 'synchronized' block.
		// Synchronization is achieved by polling fChange, using "fChange == COMPUTING_CHANGE" as barrier.
		// Timeout of 10s for safety reasons (should not be reached).
		long end= System.currentTimeMillis() + 10000;
		do {
			boolean computing;
			synchronized (this) {
				computing= fChange == COMPUTING_CHANGE;
			}
			if (computing) {
				try {
					Display display= Display.getCurrent();
					if (display != null) {
						while (! display.isDisposed() && display.readAndDispatch()) {
							// empty the display loop
						}
						display.sleep();
					} else {
						Thread.sleep(100);
					}
				} catch (InterruptedException e) {
					//continue
				}
			} else {
				synchronized (this) {
					if (fChange == COMPUTING_CHANGE) {
						continue;
					} else if (fChange != null) {
						return fChange;
					} else {
						fChange= COMPUTING_CHANGE;
					}
				}
				Change change= createChange();
				synchronized (this) {
					fChange= change;
				}
				return change;
			}
		} while (System.currentTimeMillis() < end);
		
		synchronized (this) {
			if (fChange == COMPUTING_CHANGE) {
				return null; //failed
			}
		}
		
	} else {
		synchronized (this) {
			if (fChange == null) {
				fChange= createChange();
			}
		}
	}
	return fChange;
}
 
Example 19
/**
 * Restores the code assist pop-up's size.
 * 
 * @return the stored size
 * @since 3.0
 */
protected Point restoreCompletionProposalPopupSize()
{
	if (fDialogSettings == null)
	{
		return null;
	}

	Point size = new Point(-1, -1);

	try
	{
		size.x = fDialogSettings.getInt(STORE_SIZE_X);
		size.y = fDialogSettings.getInt(STORE_SIZE_Y);
	}
	catch (NumberFormatException ex)
	{
		size.x = -1;
		size.y = -1;
	}

	// sanity check
	if (size.x == -1 && size.y == -1)
	{
		return null;
	}

	Rectangle maxBounds = null;
	if (fContentAssistSubjectControl != null && !fContentAssistSubjectControl.getControl().isDisposed())
	{
		maxBounds = fContentAssistSubjectControl.getControl().getDisplay().getBounds();
	}
	else
	{
		// fallback
		Display display = Display.getCurrent();
		if (display == null)
		{
			display = Display.getDefault();
		}
		if (display != null && !display.isDisposed())
		{
			maxBounds = display.getBounds();
		}
	}

	if (size.x > -1 && size.y > -1)
	{
		if (maxBounds != null)
		{
			size.x = Math.min(size.x, maxBounds.width);
			size.y = Math.min(size.y, maxBounds.height);
		}

		// Enforce an absolute minimal size
		size.x = Math.max(size.x, 30);
		size.y = Math.max(size.y, 30);
	}

	return size;
}
 
Example 20
Source Project: saros   File: Saros.java    License: GNU General Public License v2.0 4 votes vote down vote up
/** Stops the Saros Eclipse life cycle. */
private void stopLifeCycle() {

  log.debug("stopping lifecycle...");

  if (!isLifecycleStarted) {
    log.debug("lifecycle is already stopped");
    return;
  }

  isLifecycleStarted = false;

  final AtomicBoolean isLifeCycleStopped = new AtomicBoolean(false);
  final AtomicBoolean isTimeout = new AtomicBoolean(false);

  final Display display = Display.getCurrent();

  final Thread shutdownThread =
      ThreadUtils.runSafeAsync(
          "shutdown", //$NON-NLS-1$
          log,
          () -> {
            try {
              lifecycle.stop();
            } finally {
              isLifeCycleStopped.set(true);

              if (display != null) {
                try {
                  display.wake();
                } catch (SWTException ignore) {
                  // NOP
                }
              }
            }
          });

  int threadTimeout = 10000;

  // must run the event loop or stopping the lifecycle will timeout
  if (display != null && !display.isDisposed()) {

    display.timerExec(
        threadTimeout,
        () -> {
          isTimeout.set(true);
          display.wake();
        });

    while (!isLifeCycleStopped.get() && !isTimeout.get()) {
      if (!display.readAndDispatch()) display.sleep();
    }

    if (!isLifeCycleStopped.get()) threadTimeout = 1;

    /*
     * fall through to log an error or wait until the thread terminated
     * even it already signal that the life cycle was stopped
     */
  }

  try {
    shutdownThread.join(threadTimeout);
  } catch (InterruptedException e) {
    log.warn("interrupted while waiting for the current lifecycle to stop");
    Thread.currentThread().interrupt();
  }

  if (shutdownThread.isAlive()) log.error("timeout while stopping lifecycle");

  log.debug("lifecycle stopped");
}