org.eclipse.swt.SWTException Java Examples

The following examples show how to use org.eclipse.swt.SWTException. 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
Source File: GUIException.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: CheckExtensionGenerator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
    }
  }
}
 
Example #3
Source File: CoreSwtbotTools.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #4
Source File: ProxyDialog.java    From http4e with Apache License 2.0 6 votes vote down vote up
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);
   }
}
 
Example #5
Source File: PlatformWin32GLCanvas.java    From lwjgl3-swt with MIT License 6 votes vote down vote up
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(canvas, finalContext);
                break;
            }
        }
    };
    canvas.addListener(SWT.Dispose, listener);
    return context;
}
 
Example #6
Source File: DerbyServerUtils.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
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);
   	}
   }
}
 
Example #7
Source File: DerbyServerUtils.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
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);
   	}
   }
}
 
Example #8
Source File: Utils.java    From BiglyBT with GNU General Public License v2.0 6 votes vote down vote up
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());
}
 
Example #9
Source File: ImageLoader.java    From BiglyBT with GNU General Public License v2.0 6 votes vote down vote up
public static String getBadDisposalDetails(Throwable e, Composite startAt) {
	try {
		if ((e instanceof SWTException)
			&& e.getMessage().equals("Graphic is disposed")) {
			if (startAt == null) {
				startAt = Utils.findAnyShell();
			}
			Object[] badBoys = ImageLoader.findWidgetWithDisposedImage(startAt);
			if (badBoys != null) {
				// breakpoint here to see if badBoys[1] has any getData to id the widget
				String imageID = ImageLoader.getInstance().findImageID((Image) badBoys[1]);
				return "Disposed Graphic id is "
					+ (imageID == null ? "(not found)" : imageID)
						+ ", parent is " + badBoys[0] + "; firstData="
						+ ((Widget) badBoys[0]).getData();
			}
		}
	} catch (Throwable ignore) {
	}
	return null;
}
 
Example #10
Source File: TabbedEntry.java    From BiglyBT with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void destroyEntry( boolean userInitiated ) {
	if (Utils.runIfNotSWTThread(()->destroyEntry(userInitiated))) {
		return;
	}

	if (swtItem == null) {
		return;
	}

	// Must make a copy of swtItem because swtItem.dispose will end up in
	// this method again, with swtItem.isDisposed() still false.
	CTabItem item = swtItem;
	swtItem = null;

	super.destroyEntry( userInitiated );

	try {
		if (!item.isDisposed()) {
			item.dispose();
		}
	}catch( SWTException e ){
		// getting internal 'Widget it disposed' here, ignore
	}
}
 
Example #11
Source File: GUIException.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: AbstractSWTTester.java    From ice with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #13
Source File: XMPPConnectionSupport.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/** Disconnects the currently connected account. */
public void disconnect() {
  if (Display.getCurrent() == null) throw new SWTException(SWT.ERROR_THREAD_INVALID_ACCESS);

  if (isConnecting || isDisconnecting) return;

  isDisconnecting = true;

  ThreadUtils.runSafeAsync(
      "disconnect-xmpp",
      log,
      () -> {
        try {
          connectionHandler.disconnect();
        } finally {
          isDisconnecting = false;
        }
      });
}
 
Example #14
Source File: CsvInputDialog.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
protected void asyncUpdatePreview() {

    Runnable update = new Runnable() {

      @Override
      public void run() {
        try {
          updatePreview();
        } catch ( SWTException e ) {
          // Ignore widget disposed errors
        }
      }
    };

    shell.getDisplay().asyncExec( update );
  }
 
Example #15
Source File: AdvancedGC.java    From swt-bling with MIT License 6 votes vote down vote up
public static void setAdvanced(GC gc, boolean targetSetting) {
    if (targetSetting) {
        try {
            gc.setAdvanced(true);
            gc.setAntialias(SWT.ON);
            gc.setTextAntialias(SWT.ON);
            gc.setInterpolation(SWT.HIGH);
        } catch (SWTException e) {
            if (!loggedAdvanced) {
                log.log(Level.WARNING, "Unable to set advanced drawing", e);
                loggedAdvanced = true;
            }
        }
    } else {
        gc.setAdvanced(false);
    }

}
 
Example #16
Source File: Avatar.java    From jdt-codemining with Eclipse Public License 1.0 6 votes vote down vote up
public ImageData getData() {
	if (this.data != null)
		return this.data;

	try {
		ImageData[] images = new ImageLoader()
				.load(new ByteArrayInputStream(byteArray));
		if (images.length > 0)
			this.data = images[0];
		else
			this.data = ImageDescriptor.getMissingImageDescriptor()
					.getImageData();
	} catch (SWTException exception) {
		this.data = ImageDescriptor.getMissingImageDescriptor()
				.getImageData();
	}
	return this.data;
}
 
Example #17
Source File: ExportToImageManager.java    From ermaster-b with Apache License 2.0 6 votes vote down vote up
private void writePNGorGIF(Image image, String saveFilePath,
		String formatName) throws IOException, InterruptedException {

	try {
		ImageLoader loader = new ImageLoader();
		loader.data = new ImageData[] { image.getImageData() };
		loader.save(saveFilePath, format);

	} catch (SWTException e) {
		// Eclipse 3.2 �ł́A PNG �� Unsupported or unrecognized format �ƂȂ邽�߁A
		// �ȉ��̑�֕��@���g�p����
		// �������A���̕��@�ł͏�肭�o�͂ł��Ȃ��‹�����

		e.printStackTrace();
		BufferedImage bufferedImage = new BufferedImage(
				image.getBounds().width, image.getBounds().height,
				BufferedImage.TYPE_INT_RGB);

		drawAtBufferedImage(bufferedImage, image, 0, 0);

		ImageIO.write(bufferedImage, formatName, new File(saveFilePath));
	}
}
 
Example #18
Source File: ReportElementEditPart.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected Image getBackImage(DesignElementHandle handle)
{
	String backGroundImage = getBackgroundImage( handle );

	if ( backGroundImage == null )
	{
		return null;
	}
	else
	{
		Image image = null;
		try
		{
			image = ImageManager.getInstance( )
					.getImage( getModelAdapter( ).getModuleHandle( ),
							backGroundImage );
		}
		catch ( SWTException e )
		{
			// Should not be ExceptionHandler.handle(e), see SCR#73730
			image = null;
		}

		return image;
	}

}
 
Example #19
Source File: PlatformWin32GLCanvas.java    From lwjgl3-swt with MIT License 5 votes vote down vote up
private void wglNvSwapGroupAndBarrier(GLData attribs, long bufferAddr, long hDC) throws SWTException {
    int success;
    long wglQueryMaxSwapGroupsNVAddr = WGL.wglGetProcAddress("wglQueryMaxSwapGroupsNV");
    success = JNI.callPPPI(hDC, bufferAddr, bufferAddr + 4, wglQueryMaxSwapGroupsNVAddr);
    int maxGroups = MemoryUtil.memGetInt(bufferAddr);
    if (maxGroups < attribs.swapGroupNV) {
        throw new SWTException("Swap group exceeds maximum group index");
    }
    int maxBarriers = MemoryUtil.memGetInt(bufferAddr + 4);
    if (maxBarriers < attribs.swapBarrierNV) {
        throw new SWTException("Swap barrier exceeds maximum barrier index");
    }
    if (attribs.swapGroupNV > 0) {
        long wglJoinSwapGroupNVAddr = WGL.wglGetProcAddress("wglJoinSwapGroupNV");
        if (wglJoinSwapGroupNVAddr == 0L) {
            throw new SWTException("WGL_NV_swap_group available but wglJoinSwapGroupNV is NULL");
        }
        success = JNI.callPI(hDC, attribs.swapGroupNV, wglJoinSwapGroupNVAddr);
        if (success == 0) {
            throw new SWTException("Failed to join swap group");
        }
        if (attribs.swapBarrierNV > 0) {
            long wglBindSwapBarrierNVAddr = WGL.wglGetProcAddress("wglBindSwapBarrierNV");
            if (wglBindSwapBarrierNVAddr == 0L) {
                throw new SWTException("WGL_NV_swap_group available but wglBindSwapBarrierNV is NULL");
            }
            success = JNI.callI(attribs.swapGroupNV, attribs.swapBarrierNV, wglBindSwapBarrierNVAddr);
            if (success == 0) {
                throw new SWTException("Failed to bind swap barrier. Probably no G-Sync card installed.");
            }
        }
    }
}
 
Example #20
Source File: SWTUtils.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Run the given runnable in the SWT-Thread and log any RuntimeExceptions to the given log.
 *
 * @nonBlocking
 */
public static void runSafeSWTAsync(final Logger log, final Runnable runnable) {
  try {
    getDisplay().asyncExec(ThreadUtils.wrapSafe(log, runnable));
  } catch (SWTException e) {
    if (!PlatformUI.getWorkbench().isClosing()) throw e;

    log.warn(
        "could not execute runnable " + runnable + ", UI thread is not available",
        new StackTrace());
  }
}
 
Example #21
Source File: ExportToImageManager.java    From erflute with Apache License 2.0 5 votes vote down vote up
private void writePNGorGIF(Image image, String saveFilePath, String formatName) throws IOException, InterruptedException {
    try {
        final ImageLoader loader = new ImageLoader();
        loader.data = new ImageData[] { image.getImageData() };
        loader.save(saveFilePath, format);
    } catch (final SWTException e) {
        e.printStackTrace();
        final BufferedImage bufferedImage =
                new BufferedImage(image.getBounds().width, image.getBounds().height, BufferedImage.TYPE_INT_RGB);
        drawAtBufferedImage(bufferedImage, image, 0, 0);
        ImageIO.write(bufferedImage, formatName, new File(saveFilePath));
    }
}
 
Example #22
Source File: SWTUtils.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Run the given runnable in the SWT-Thread, log any RuntimeExceptions to the given log and block
 * until the runnable returns.
 *
 * @blocking
 */
public static void runSafeSWTSync(final Logger log, final Runnable runnable) {
  try {
    getDisplay().syncExec(ThreadUtils.wrapSafe(log, runnable));
  } catch (SWTException e) {
    if (!PlatformUI.getWorkbench().isClosing()) throw e;

    log.warn(
        "could not execute runnable " + runnable + ", UI thread is not available",
        new StackTrace());
  }
}
 
Example #23
Source File: EclipseSWTSynchronizer.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private void exec(Runnable runnable, boolean async) {
  try {
    Display display = getDisplay();

    /*
     * this will not work, although the chance is really small, it is
     * possible that the device is disposed after this check and before
     * the a(sync)Exec call
     */
    // if (display.isDisposed())
    // return;

    if (async) display.asyncExec(runnable);
    else display.syncExec(runnable);

  } catch (SWTException e) {

    if (PlatformUI.getWorkbench().isClosing()) {
      log.warn(
          "could not execute runnable " + runnable + ", UI thread is not available",
          new StackTrace());
    } else {
      log.error(
          "could not execute runnable "
              + runnable
              + ", workbench display was disposed before workbench shutdown",
          e);
    }
  }
}
 
Example #24
Source File: CustomColorPalettePopup.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates and returns a new SWT image for this image descriptor. The
 * returned image must be explicitly disposed using the image's dispose
 * call. The image will not be automatically garbage collected. In the
 * even of an error, a default image is returned if
 * <code>returnMissingImageOnError</code> is true, otherwise
 * <code>null</code> is returned.
 * <p>
 * Note: Even if <code>returnMissingImageOnError</code> is true, it is
 * still possible for this method to return <code>null</code> in
 * extreme cases, for example if SWT runs out of image handles.
 * </p>
 * 
 * @return a new image or <code>null</code> if the image could not be
 *         created
 * 
 */
public Image createImage() {

	Device device = Display.getCurrent();
	ImageData data = getImageData();
	if (data == null)
		data = DEFAULT_IMAGE_DATA;

	/*
	 * Try to create the supplied image. If there is an SWT Exception
	 * try and create the default image if that was requested. Return
	 * null if this fails.
	 */

	try {
		if (data.transparentPixel >= 0) {
			ImageData maskData = data.getTransparencyMask();
			return new Image(device, data, maskData);
		}
		return new Image(device, data);
	} catch (SWTException exception) {

		try {
			return new Image(device, DEFAULT_IMAGE_DATA);
		} catch (SWTException nextException) {
			return null;
		}

	}
}
 
Example #25
Source File: UiDBImage.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
public UiDBImage(String prefix, final String name, final InputStream source){
	this.dbImage = new DBImage(prefix, name);
	try {
		ImageLoader iml = new ImageLoader();
		iml.load(source);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		iml.save(baos, SWT.IMAGE_PNG);
		dbImage.setBinary(DBImage.FLD_IMAGE, baos.toByteArray());
	} catch (IllegalArgumentException | SWTException e) {
		log.error("Error setting image object on DBImage " + dbImage.getLabel(), e);
	}
}
 
Example #26
Source File: PlatformWin32VKCanvas.java    From lwjgl3-swt with MIT License 5 votes vote down vote up
@Override
public long create(Composite composite, VKData data) {
    VkWin32SurfaceCreateInfoKHR sci = VkWin32SurfaceCreateInfoKHR.callocStack()
      .sType(VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR)
      .hinstance(OS.GetModuleHandle(null))
      .hwnd(composite.handle);
    LongBuffer pSurface = stackMallocLong(1);
    int err = vkCreateWin32SurfaceKHR(data.instance, sci, null, pSurface);
    long surface = pSurface.get(0);
    if (err != VK_SUCCESS) {
        throw new SWTException("Calling vkCreateWin32SurfaceKHR failed with error: " + err);
    }
    return surface;
}
 
Example #27
Source File: AuthDialog.java    From http4e with Apache License 2.0 5 votes vote down vote up
public void populate(){
   CoreContext ctx = CoreContext.getContext();
   AuthItem item = (AuthItem) ctx.getObject(CoreObjects.AUTH_ITEM);
   try {
      if (item != null) {
         this.authItem = item;
         basicCheck.setSelection(item.isBasic());
         digestCheck.setSelection(item.isDigest());
         preemptiveCheck.setSelection(item.isPreemtptive());
         usernameBox.setText(item.getUsername());
         passBox.setText(item.getPass());
         hostBox.setText(item.getHost());
         portBox.setText(item.getPort());
         realmBox.setText(item.getRealm());

         if (isEnabled()) {
            okBtn.setEnabled(true);
            usernameBox.setEnabled(true);
            passBox.setEnabled(true);
            hostBox.setEnabled(true);
            portBox.setEnabled(true);
            realmBox.setEnabled(true);
         }
      } else {
         this.authItem = new AuthItem();
      }
   } catch (SWTException e) {
      // dispose exception
      ExceptionHandler.handle(e);
   }
}
 
Example #28
Source File: CsvInputDialog.java    From hop with Apache License 2.0 5 votes vote down vote up
protected void asyncUpdatePreview() {

    Runnable update = () -> {
      try {
        updatePreview();
      } catch ( SWTException e ) {
        // Ignore widget disposed errors
      }
    };

    shell.getDisplay().asyncExec( update );
  }
 
Example #29
Source File: XViewerTextWidget.java    From nebula with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String getXmlData() {
   if (sText == null || sText.isDisposed()) {
      return XmlUtil.textToXml(text);
   } else {
      try {
         return XmlUtil.textToXml(sText.getText());
      } catch (SWTException e) {
         return XmlUtil.textToXml(text);
      }
   }
}
 
Example #30
Source File: ChoicesDialog.java    From SWET with MIT License 5 votes vote down vote up
private void checkStyle(int style) {
	if ((style & ~(SWT.APPLICATION_MODAL | SWT.PRIMARY_MODAL | SWT.SYSTEM_MODAL
			| SWT.MODELESS)) != 0) {
		throw new SWTException("Unsupported style");
	}
	if (Integer.bitCount(style) > 1) {
		throw new SWTException(
				"Unsupports only one of APPLICATION_MODAL, PRIMARY_MODAL, SYSTEM_MODAL or SWT.MODELESS");
	}
}