FileDocCategorySizeDatePackage
Utils.javaAPI DocAzureus 3.0.3.439399Wed Sep 19 15:36:26 BST 2007org.gudy.azureus2.ui.swt

Utils

public class Utils extends Object
author
Olivier

Fields Summary
private static final String
GOOD_STRING
public static final boolean
isGTK
public static final boolean
LAST_TABLECOLUMN_EXPANDS
Some platforms expand the last column to fit the remaining width of the table.
public static final boolean
TABLE_GRIDLINE_IS_ALTERNATING_COLOR
GTK already handles alternating background for tables
private static final boolean
DIRECT_SETCHECKED
public static final boolean
SWT32_TABLEPAINT
private static final boolean
DEBUG_SWTEXEC
private static ArrayList
queue
private static AEDiagnosticsLogger
diag_logger
Constructors Summary
Methods Summary
public static voidaddListenerAndChildren(Composite area, int event, Listener listener)

param
area
param
event id
param
listener

		area.addListener(event, listener);
		Control[] children = area.getChildren();
		for (int i = 0; i < children.length; i++) {
			Control child = children[i];
			if (child instanceof Composite) {
				addListenerAndChildren((Composite)child, event, listener);
			} else {
				child.addListener(event, listener);
			}
		}
	
public static voidalternateRowBackground(TableItem item)

  	if (Utils.TABLE_GRIDLINE_IS_ALTERNATING_COLOR) {
  		if (!item.getParent().getLinesVisible())
  			item.getParent().setLinesVisible(true);
  		return;
  	}

  	if (item == null || item.isDisposed())
  		return;
  	Color[] colors = { item.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND),
        Colors.colorAltRow };
  	Color newColor = colors[ item.getParent().indexOf(item) % colors.length];
  	if (!item.getBackground().equals(newColor)) {
  		item.setBackground(newColor);
  	}
  
public static voidalternateTableBackground(Table table)

  	if (table == null || table.isDisposed())
  		return;

  	if (Utils.TABLE_GRIDLINE_IS_ALTERNATING_COLOR) {
  		if (!table.getLinesVisible())
  			table.setLinesVisible(true);
  		return;
  	}

  	int iTopIndex = table.getTopIndex();
  	int iBottomIndex = getTableBottomIndex(table, iTopIndex);

  	Color[] colors = { table.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND),
        Colors.colorAltRow };
  	int iFixedIndex = iTopIndex;
    for (int i = iTopIndex; i <= iBottomIndex; i++) {
      TableItem row = table.getItem(i);
      // Rows can be disposed!
      if (!row.isDisposed()) {
      	Color newColor = colors[iFixedIndex % colors.length];
      	iFixedIndex++;
      	if (!row.getBackground().equals(newColor)) {
//        System.out.println("setting "+rows[i].getBackground() +" to " + newColor);
      		row.setBackground(newColor);
      	}
      }
    }
  
public static voidbeep()

		execSWTThread(new AERunnable() {
			public void runSupport() {
				Display display = Display.getDefault();
				if (display != null) {
					display.beep();
				}
			}
		});
	
public static voidcenterWindowRelativeTo(Shell window, Control control)
Centers a window relative to a control. That is to say, the window will be located at the center of the control.

param
window
param
control

      final Rectangle bounds = control.getBounds();
      final Point shellSize = window.getSize();
      window.setLocation(
              bounds.x + (bounds.width / 2) - shellSize.x / 2,
              bounds.y + (bounds.height / 2) - shellSize.y / 2
      );
  
public static voidcentreWindow(Shell shell)

		Rectangle displayArea; // area to center in
		try {
			displayArea = shell.getMonitor().getClientArea();
		} catch (NoSuchMethodError e) {
			displayArea = shell.getDisplay().getClientArea();
		}

		Rectangle shellRect = shell.getBounds();

		if (shellRect.height > displayArea.height) {
			shellRect.height = displayArea.height;
		}
		if (shellRect.width > displayArea.width - 50) {
			shellRect.width = displayArea.width;
		}

		shellRect.x = displayArea.x
				+ (displayArea.width - shellRect.width) / 2;
		shellRect.y = displayArea.y
				+ (displayArea.height - shellRect.height) / 2;

		shell.setBounds(shellRect);
	
private static voidcreateDropTarget(Composite composite, boolean bAllowShareAdd, Text url, DropTargetListener dropTargetListener)

		
		Transfer[] transferList;
  	if (SWT.getVersion() >= 3107) {
  		transferList = new Transfer[] { HTMLTransfer.getInstance(),
					URLTransfer.getInstance(), FileTransfer.getInstance(),
					TextTransfer.getInstance() };
		} else {
			transferList = new Transfer[] { URLTransfer.getInstance(),
					FileTransfer.getInstance(), TextTransfer.getInstance() };
		}

		
		final DropTarget dropTarget = new DropTarget(composite, DND.DROP_DEFAULT
				| DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK | DND.DROP_TARGET_MOVE);
		dropTarget.setTransfer(transferList);
		dropTarget.addDropListener(dropTargetListener);
		// Note: DropTarget will dipose when the parent it's on diposes
		
		// On Windows, dropping on children moves up to parent
		// On OSX, each child needs it's own drop.
		if (Constants.isWindows)
			return;

		Control[] children = composite.getChildren();
		for (int i = 0; i < children.length; i++) {
			Control control = children[i];
			if (!control.isDisposed()) {
				if (control instanceof Composite) {
					createDropTarget((Composite) control, bAllowShareAdd, url,
							dropTargetListener);
				} else {
					final DropTarget dropTarget2 = new DropTarget(control,
							DND.DROP_DEFAULT | DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK
									| DND.DROP_TARGET_MOVE);
					dropTarget2.setTransfer(transferList);
					dropTarget2.addDropListener(dropTargetListener);
				}
			}
		}
	
private static voidcreateDropTarget(Composite composite, boolean bAllowShareAdd, Text url)

		
		URLDropTarget target = new URLDropTarget(url, bAllowShareAdd);
		createDropTarget(composite, bAllowShareAdd, url, target);
  
public static voidcreateTorrentDropTarget(Composite composite, boolean bAllowShareAdd)

  	try {
  		createDropTarget(composite, bAllowShareAdd, null);
  	} catch (Exception e) {
      Debug.out(e);
  	}
	
public static voidcreateURLDropTarget(Composite composite, Text url)

param
control the control (usually a Shell) to add the DropTarget
param
url the Text control where to set the link text
author
Rene Leonhardt

		try {
			createDropTarget(composite, false, url);
		} catch (Exception e) {
			Debug.out(e);
		}
	
public static voiddisposeComposite(Composite composite, boolean disposeSelf)

	
	 
		if (DEBUG_SWTEXEC) {
			queue = new ArrayList();
			diag_logger = AEDiagnostics.getLogger("swt");
			diag_logger.log("\n\nSWT Logging Starts");
		} else {
			queue = null;
			diag_logger = null;
		}
	
    if(composite == null || composite.isDisposed())
      return;
  Control[] controls = composite.getChildren();
  for(int i = 0 ; i < controls.length ; i++) {
    Control control = controls[i];                
    if(control != null && ! control.isDisposed()) {
      if(control instanceof Composite) {
        disposeComposite((Composite) control,true);
      }
      try {
        control.dispose();
      } catch (SWTException e) {
        Debug.printStackTrace( e );
      }
    }
  }
  // It's possible that the composite was destroyed by the child
  if (!composite.isDisposed() && disposeSelf)
    try {
      composite.dispose();
    } catch (SWTException e) {
      Debug.printStackTrace( e );
    }
  
public static voiddisposeComposite(Composite composite)

    disposeComposite(composite,true);
  
public static voiddisposeSWTObjects(java.util.List disposeList)
Dispose of a list of SWT objects

param
disposeList

  	disposeSWTObjects(disposeList.toArray());
		disposeList.clear();
  
public static voiddisposeSWTObjects(java.lang.Object[] disposeList)

  	boolean bResourceObjectExists = SWT.getVersion() >= 3129;
  	
		for (int i = 0; i < disposeList.length; i++) {
			Object o = disposeList[i];
			if (o instanceof Widget && !((Widget) o).isDisposed())
				((Widget) o).dispose();
			else if (bResourceObjectExists && (o instanceof Resource)
					&& !((Resource) o).isDisposed())
				((Resource) o).dispose();
			else {
				try {
					// For Pre-SWT 3.1
					if ((o instanceof Cursor) && !((Cursor)o).isDisposed()) {
						((Cursor)o).dispose();
					} else if ((o instanceof Font) && !((Font)o).isDisposed()) {
						((Font)o).dispose();
					} else if ((o instanceof GC) && !((GC)o).isDisposed()) {
						((GC)o).dispose();
					} else if ((o instanceof Image) && !((Image)o).isDisposed()) {
						((Image)o).dispose();
					} else if ((o instanceof Region) && !((Region)o).isDisposed()) {
						((Region)o).dispose();  // 3.0
					} else if ((o instanceof TextLayout) && !((TextLayout)o).isDisposed()) {
						((TextLayout) o).dispose(); // 3.0
					}
				} catch (NoClassDefFoundError e) {
					// ignore
				}
				// Path, Pattern, Transform are all 3.1, which will be instances of 
				// Resource
			}
		}
  
public static booleandrawImage(GC gc, Image image, Rectangle dstRect, Rectangle clipping, int hOffset, int vOffset, boolean clearArea)

		return drawImage(gc, image, new Point(0, 0), dstRect, clipping, hOffset,
				vOffset, clearArea);
	
public static booleandrawImage(GC gc, Image image, Rectangle dstRect, Rectangle clipping, int hOffset, int vOffset)

		return drawImage(gc, image, new Point(0, 0), dstRect, clipping, hOffset,
				vOffset, false);
	
public static booleandrawImage(GC gc, Image image, Point srcStart, Rectangle dstRect, Rectangle clipping, int hOffset, int vOffset, boolean clearArea)

		Rectangle srcRect;
		Point dstAdj;

		if (clipping == null) {
			dstAdj = new Point(0, 0);
			srcRect = new Rectangle(srcStart.x, srcStart.y, dstRect.width,
					dstRect.height);
		} else {
			if (!dstRect.intersects(clipping)) {
				return false;
			}

			dstAdj = new Point(Math.max(0, clipping.x - dstRect.x), Math.max(0,
					clipping.y - dstRect.y));

			srcRect = new Rectangle(0, 0, 0, 0);
			srcRect.x = srcStart.x + dstAdj.x;
			srcRect.y = srcStart.y + dstAdj.y;
			srcRect.width = Math.min(dstRect.width - dstAdj.x, clipping.x
					+ clipping.width - dstRect.x);
			srcRect.height = Math.min(dstRect.height - dstAdj.y, clipping.y
					+ clipping.height - dstRect.y);
		}

		if (!srcRect.isEmpty()) {
			try {
				if (clearArea) {
					gc.fillRectangle(dstRect.x + dstAdj.x + hOffset, dstRect.y + dstAdj.y
							+ vOffset, srcRect.width, srcRect.height);
				}
				gc.drawImage(image, srcRect.x, srcRect.y, srcRect.width,
						srcRect.height, dstRect.x + dstAdj.x + hOffset, dstRect.y
								+ dstAdj.y + vOffset, srcRect.width, srcRect.height);
			} catch (Exception e) {
				System.out.println("drawImage: " + e.getMessage() + ": " + image + ", " + srcRect
						+ ", " + (dstRect.x + dstAdj.y + hOffset) + ","
						+ (dstRect.y + dstAdj.y + vOffset) + "," + srcRect.width + ","
						+ srcRect.height + "; imageBounds = " + image.getBounds());
			}
		}

		return true;
	
public static booleanexecSWTThread(java.lang.Runnable code, boolean async)
Execute code in the Runnable object using SWT's thread. If current thread it already SWT's thread, the code will run immediately. If the current thread is not SWT's, code will be run either synchronously or asynchronously on SWT's thread at the next reasonable opportunity. This method does not catch any exceptions.

param
code code to run
param
async true if SWT asyncExec, false if SWT syncExec
return
success

		SWTThread swt = SWTThread.getInstance();

		Display display;
		if (swt == null) {
			display = Display.getDefault();
			if (display == null) {
				System.err.println("SWT Thread not started yet!");
				return false;
			}
		} else {
			if (swt.isTerminated()) {
				return false;
			}
			display = swt.getDisplay();
		}

		if (display == null || display.isDisposed() || code == null)
			return false;

		if (display.getThread() == Thread.currentThread()) {
			if (queue == null) {
				code.run();
			} else {
				long lStartTimeRun = SystemTime.getCurrentTime();

				code.run();

				long wait = SystemTime.getCurrentTime() - lStartTimeRun;
				if (wait > 700) {
					diag_logger.log(SystemTime.getCurrentTime() + "] took " + wait
							+ "ms to run " + Debug.getCompressedStackTrace(4));
				}
			}
		} else if (async) {
			try {
				if (queue == null) {
					display.asyncExec(code);
				} else {
					queue.add(code);

					diag_logger.log(SystemTime.getCurrentTime() + "] + QUEUE. size= "
							+ queue.size() + "; add " + code + " via "
							+ Debug.getCompressedStackTrace(4));
					final long lStart = SystemTime.getCurrentTime();

					final Display fDisplay = display;
					display.asyncExec(new AERunnable() {
						public void runSupport() {
							long wait = SystemTime.getCurrentTime() - lStart;
							if (wait > 700) {
								diag_logger.log(SystemTime.getCurrentTime() + "] took " + wait
										+ "ms before SWT ran async code " + code);
							}
							long lStartTimeRun = SystemTime.getCurrentTime();
							
							if (fDisplay.isDisposed()) {
								Debug.out("Display disposed while trying to execSWTThread "
										+ code);
								// run anayway, except trap SWT error
								try {
									code.run();
								} catch (SWTException e) {
									Debug.out("Error while execSWTThread w/disposed Display", e);
								}
							} else {
								code.run();
							}

							wait = SystemTime.getCurrentTime() - lStartTimeRun;
							if (wait > 500) {
								diag_logger.log(SystemTime.getCurrentTime() + "] took " + wait
										+ "ms to run " + code);
							}

							diag_logger.log(SystemTime.getCurrentTime()
									+ "] - QUEUE. size=" + queue.size());
							queue.remove(code);
						}
					});
				}
			} catch (NullPointerException e) {
				// If the display is being disposed of, asyncExec may give a null
				// pointer error
				return false;
			}
		} else {
			display.syncExec(code);
		}

		return true;
	
public static booleanexecSWTThread(java.lang.Runnable code)
Execute code in the Runnable object using SWT's thread. If current thread it already SWT's thread, the code will run immediately. If the current thread is not SWT's, code will be run asynchronously on SWT's thread at the next reasonable opportunity. This method does not catch any exceptions.

param
code code to run
return
success

		return execSWTThread(code, true);
	
public static booleanexecSWTThreadWithBool(java.lang.String ID, AERunnableBoolean code)

		return execSWTThreadWithBool(ID, code, 0);
	
public static booleanexecSWTThreadWithBool(java.lang.String ID, AERunnableBoolean code, long millis)

		if (code == null) {
			return false;
		}

		final AESemaphore			sem 	= new AESemaphore(ID);
		boolean[] returnValueObject = { false };

		try{
			code.setupReturn(ID, returnValueObject, sem);
			
			if (!execSWTThread(code)) {
				// code never got run
				// XXX: throw instead?
				return false;
			}
		}catch( Throwable e ){
			Debug.out(ID, e);
			sem.release();
		}
		sem.reserve(millis);
	
		return returnValueObject[0];
	
public static java.lang.ObjectexecSWTThreadWithObject(java.lang.String ID, AERunnableObject code)

		return execSWTThreadWithObject(ID, code, 0);
	
public static java.lang.ObjectexecSWTThreadWithObject(java.lang.String ID, AERunnableObject code, long millis)

		if (code == null) {
			return null;
		}

		final AESemaphore			sem 	= new AESemaphore(ID);
		Object[] returnValueObject = { null };

		try{
			code.setupReturn(ID, returnValueObject, sem);
			
			if (!execSWTThread(code)) {
				// XXX: throw instead?
				return null;
			}
		}catch( Throwable e ){
			Debug.out(ID, e);
			sem.release();
		}
		sem.reserve(millis);
	
		return returnValueObject[0];
	
public static ShellfindAnyShell()

		// Pick the main shell if we can
		UIFunctionsSWT uiFunctions = UIFunctionsManagerSWT.getUIFunctionsSWT();
		if (uiFunctions != null) {
			Shell shell = uiFunctions.getMainShell();
			if (shell != null && !shell.isDisposed()) {
				return shell;
			}
		}

		// Get active shell from current display if we can
		Display current = Display.getCurrent();
		if (current == null) {
			return null;
		}
		Shell shell = current.getActiveShell();
		if (shell != null && !shell.isDisposed()) {
			return shell;
		}
		
		// Get first shell of current display if we can
		Shell[] shells = current.getShells();
		if (shells.length == 0) {
			return null;
		}
		
		if (shells[0] != null && !shells[0].isDisposed()) {
			return shells[0];
		}
		
		return null;
	
public static org.eclipse.swt.layout.FormDatagetFilledFormData()

		FormData formData = new FormData();
		formData.top = new FormAttachment(0, 0);
		formData.left = new FormAttachment(0, 0);
		formData.right = new FormAttachment(100, 0);
		formData.bottom = new FormAttachment(100, 0);
		
		return formData;
	
public static intgetFontHeightFromPX(Font baseFont, GC gc, int heightInPixels)

param
baseFont
param
gc Can be null
param
heightInPixels
return
since
3.0.0.7

		Font font = null;
		Device device = baseFont.getDevice();
		
		// hack..
		heightInPixels++;

		// This isn't accurate, but gets us close
		int size = Utils.pixelsToPoint(heightInPixels, device.getDPI().y) + 1;
		if (size <= 0) {
			return 0;
		}

		boolean bOurGC = gc == null || gc.isDisposed();
		try {
			if (bOurGC) {
				gc = new GC(device);
			}
			FontData[] fontData = baseFont.getFontData();

			do {
				if (font != null) {
					size--;
					font.dispose();
				}
				fontData[0].setHeight(size);

				font = new Font(device, fontData);

				gc.setFont(font);

			} while (font != null && gc.textExtent(GOOD_STRING).y > heightInPixels
					&& size > 1);

		} finally {
			if (bOurGC) {
				gc.dispose();
			}
		}
		return size;
	
public static intgetFontHeightFromPX(Device device, FontData[] fontData, GC gc, int heightInPixels)

		Font font = null;

		// hack..
		heightInPixels++;

		// This isn't accurate, but gets us close
		int size = Utils.pixelsToPoint(heightInPixels, device.getDPI().y) + 1;
		if (size <= 0) {
			return 0;
		}

		boolean bOurGC = gc == null || gc.isDisposed();
		try {
			if (bOurGC) {
				gc = new GC(device);
			}

			do {
				if (font != null) {
					size--;
					font.dispose();
				}
				fontData[0].setHeight(size);

				font = new Font(device, fontData);

				gc.setFont(font);

			} while (font != null && gc.textExtent(GOOD_STRING).y > heightInPixels
					&& size > 1);

		} finally {
			if (bOurGC) {
				gc.dispose();
			}
		}
		return size;
	
public static FontgetFontWithHeight(Font baseFont, GC gc, int heightInPixels)

		Font font = null;
		Device device = baseFont.getDevice();

		// hack..
		heightInPixels++;
		
		// This isn't accurate, but gets us close
		int size = Utils.pixelsToPoint(heightInPixels, device.getDPI().y) + 1;
		if (size <= 0) {
			size = 2;
		}

		boolean bOurGC = gc == null || gc.isDisposed();
		try {
			if (bOurGC) {
				gc = new GC(device);
			}
			FontData[] fontData = baseFont.getFontData();

			do {
				if (font != null) {
					size--;
					font.dispose();
				}
				fontData[0].setHeight(size);

				font = new Font(device, fontData);

				gc.setFont(font);

			} while (font != null && gc.textExtent(GOOD_STRING).y > heightInPixels
					&& size > 1);

		} finally {
			if (bOurGC) {
				gc.dispose();
			}
		}

		return font;
	
public static java.lang.StringgetLinkFromClipboard(Display display, boolean accept_magnets)

Gets an URL from the clipboard if a valid URL for downloading has been copied.

The supported protocols currently are http, https, and magnet.

param
display
param
accept_magnets
return
first valid link from clipboard, else "http://"

    final Clipboard cb = new Clipboard(display);
    final TextTransfer transfer = TextTransfer.getInstance();
    
    String data = (String)cb.getContents(transfer);
    
    String text = UrlUtils.parseTextForURL(data, accept_magnets);
    if (text == null) {
    	return "http://";
    }
    
    return text;
  
public static intgetTableBottomIndex(Table table, int iTopIndex)
Bottom Index may be negative

		// on Linux, getItemHeight is slow AND WRONG. so is getItem(x).getBounds().y 
		// getItem(Point) is slow on OSX

		int itemCount = table.getItemCount();
		if (!table.isVisible() || iTopIndex >= itemCount)
			return -1;
		
		if (Constants.isOSX) {
			try {
				TableItem item = table.getItem(iTopIndex);
				Rectangle bounds = item.getBounds();
				Rectangle clientArea = table.getClientArea();
	
				int itemHeight = table.getItemHeight();
				int iBottomIndex = Math.min(iTopIndex
						+ (clientArea.height + clientArea.y - bounds.y - 1) / itemHeight,
						itemCount - 1);
	
	//			System.out.println(bounds + ";" + clientArea + ";" + itemHeight + ";bi="
	//					+ iBottomIndex + ";ti=" + iTopIndex + ";"
	//					+ (clientArea.height + clientArea.y - bounds.y - 1));
				return iBottomIndex;
			} catch (NoSuchMethodError e) {
				// item.getBounds is 3.2
				return Math.min(iTopIndex
						+ ((table.getClientArea().height - table.getHeaderHeight() - 1) / 
								table.getItemHeight()) + 1, table.getItemCount() - 1);
			}
		}

		// getItem will return null if clientArea's height is smaller than
		// header height.
		int areaHeight = table.getClientArea().height;
		if (areaHeight <= table.getHeaderHeight())
			return -1;

		// 2 offset to be on the safe side
		TableItem bottomItem = table.getItem(new Point(2,
				table.getClientArea().height - 1));
  	int iBottomIndex = (bottomItem != null) ? table.indexOf(bottomItem) :
			itemCount - 1;
  	return iBottomIndex;
	
public static org.eclipse.swt.layout.GridDatagetWrappableLabelGridData(int hspan, int styles)

		GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | styles);
		gridData.horizontalSpan = hspan;
		gridData.widthHint = 0;
		return gridData;
	
public static booleanisThisThreadSWT()

    SWTThread swt = SWTThread.getInstance();
    
    if (swt == null) {
    	System.err.println("SWT Thread not started yet");
    	return false;
    }

    Display display = swt.getDisplay();

  	if (display == null || display.isDisposed())
			return false;

		return (display.getThread() == Thread.currentThread());
	
public static voidlaunch(java.lang.String sFile)

		if (sFile == null) {
			return;
		}

		if (SWT.getVersion() >= 3315 || SWT.getVersion() < 3300
				|| UrlUtils.isURL(sFile) || sFile.startsWith("mailto:")) {
			Program.launch(sFile);
		} else {
			if (Constants.isOSX) {
				Program.launch("file://" + sFile.replaceAll(" ", "%20"));
			} else {
				Program.launch(sFile);
			}
		}
	
public static booleanlinkShellMetricsToConfig(Shell shell, java.lang.String sConfigPrefix)

		String windowRectangle = COConfigurationManager.getStringParameter(
				sConfigPrefix + ".rectangle", null);
		boolean bDidResize = false;
		if (null != windowRectangle) {
			int i = 0;
			int[] values = new int[4];
			StringTokenizer st = new StringTokenizer(windowRectangle, ",");
			try {
				while (st.hasMoreTokens() && i < 4) {
					values[i++] = Integer.valueOf(st.nextToken()).intValue();
				}
				if (i == 4) {
					Rectangle shellBounds = new Rectangle(values[0], values[1],
							values[2], values[3]);
					shell.setBounds(shellBounds);
					verifyShellRect(shell, true);
					bDidResize = true;
				}
			} catch (Exception e) {
			}
		}

		boolean isMaximized = COConfigurationManager.getBooleanParameter(
				sConfigPrefix + ".maximized") && !Constants.isOSX;
		shell.setMaximized(isMaximized);

		new ShellMetricsResizeListener(shell, sConfigPrefix);
		
		return bDidResize;
	
public static intopenMessageBox(Shell parent, int style, java.lang.String keyPrefix, java.lang.String[] textParams)
Open a messagebox using resource keys for title/text

param
parent Parent shell for messagebox
param
style SWT styles for messagebox
param
keyPrefix message bundle key prefix used to get title and text. Title will be keyPrefix + ".title", and text will be set to keyPrefix + ".text"
param
textParams any parameters for text
return
what the messagebox returns

		MessageBox mb = new MessageBox(parent, style);
		mb.setMessage(MessageText.getString(keyPrefix + ".text", textParams));
		mb.setText(MessageText.getString(keyPrefix + ".title"));
		return mb.open();
	
public static intopenMessageBox(Shell parent, int style, java.lang.String title, java.lang.String text)
Open a messagebox with actual title and text

param
parent
param
style
param
title
param
text
return

		MessageBox mb = new MessageBox(parent, style);
		mb.setMessage(text);
		mb.setText(title);
		return mb.open();
	
public static intpixelsToPoint(int pixels, int dpi)

    int ret = (int) Math.round((pixels * 72.0) / dpi);
    return ret;
	
public static intpixelsToPoint(double pixels, int dpi)

    int ret = (int) Math.round((pixels * 72.0) / dpi);
    return ret;
	
public static voidrelayout(Control control)
Relayout all composites up from control until there's enough room for the control to fit

param
control Control that had it's sized changed and needs more room

		relayout(control, false);
	
public static voidrelayout(Control control, boolean expandOnly)
Relayout all composites up from control until there's enough room for the control to fit

param
control Control that had it's sized changed and needs more room

		if (control == null || control.isDisposed()) {
			return;
		}
		
		Composite parent = control.getParent();
		Point targetSize = control.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
		Point size = control.getSize();
		if (size.y == targetSize.y && size.x == targetSize.x) {
			return;
		}
		
		if (expandOnly && size.y >= targetSize.y && size.x >= targetSize.x) {
			parent.layout();
			return;
		}
		
		while (parent != null) {
			parent.layout(true, true);
			parent = parent.getParent();

			Point newSize = control.getSize();
			
			//System.out.println("new=" + newSize + ";target=" + targetSize);
			
			if (newSize.y >= targetSize.y && newSize.x >= targetSize.x) {
				break;
			}
		}
		
		if (parent != null) {
			parent.layout();
		}
	
public static voidsetCheckedInSetData(TableItem item, boolean checked)
Sets the checkbox in a Virtual Table while inside a SWT.SetData listener trigger. SWT 3.1 has an OSX bug that needs working around.

param
item
param
checked

		if (DIRECT_SETCHECKED) {
			item.setChecked(checked);
		} else {
			item.setChecked(!checked);
			item.getDisplay().asyncExec(new AERunnable() {
				public void runSupport() {
					item.setChecked(checked);
				}
			});
		}

		if (Constants.isWindowsXP || isGTK) {
			Rectangle r = item.getBounds(0);
			Table table = item.getParent();
			Rectangle rTable = table.getClientArea();
			
			r.y += VerticalAligner.getTableAdjustVerticalBy(table);
			table.redraw(0, r.y, rTable.width, r.height, true);
		}
	
public static org.eclipse.swt.layout.GridDatasetGridData(Composite composite, int gridStyle, Control ctrlBestSize, int maxHeight)

		GridData gridData = new GridData(gridStyle);
		gridData.heightHint = ctrlBestSize.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
		if (gridData.heightHint > maxHeight && maxHeight > 0)
			gridData.heightHint = maxHeight;
		composite.setLayoutData(gridData);

		return gridData;
	
public static voidsetMenuItemImage(MenuItem item, java.lang.String repoKey)

Set a MenuItem's image with the given ImageRepository key. In compliance with platform human interface guidelines, the images are not set under Mac OS X.

param
item SWT MenuItem
param
repoKey ImageRepository image key
see
Apple HIG

      if(!Constants.isOSX)
          item.setImage(ImageRepository.getImage(repoKey));
  
public static voidsetMenuItemImage(MenuItem item, Image image)

      if(!Constants.isOSX)
          item.setImage(image);
  
public static voidsetShellIcon(Shell shell)
Sets the shell's Icon(s) to the default Azureus icon. OSX doesn't require an icon, so they are skipped

param
shell

		final String[] sImageNames = { "azureus", "azureus32", "azureus64",
				"azureus128" };

		if (Constants.isOSX)
			return;

		try {
			ArrayList list = new ArrayList();
			Image[] images = new Image[] { ImageRepository.getImage("azureus"),
					ImageRepository.getImage("azureus32"),
					ImageRepository.getImage("azureus64"),
					ImageRepository.getImage("azureus128") };

			for (int i = 0; i < images.length; i++) {
				Image image = ImageRepository.getImage(sImageNames[i]);
				if (image != null)
					list.add(image);
			}

			if (list.size() == 0)
				return;

			shell.setImages((Image[]) list.toArray(new Image[0]));
		} catch (NoSuchMethodError e) {
			// SWT < 3.0
			Image image = ImageRepository.getImage(sImageNames[0]);
			if (image != null)
				shell.setImage(image);
		}
	
public static voidsetTextLinkFromClipboard(Shell shell, Text url, boolean accept_magnets)
Initializes the URL dialog with http:// If a valid link is found in the clipboard, it will be inserted and the size (and location) of the dialog is adjusted.

param
shell to set the dialog location if needed
param
url the URL text control
param
accept_magnets
author
Rene Leonhardt

    String link = getLinkFromClipboard(shell.getDisplay(),accept_magnets);
    if (link != null)
    	url.setText(link);
  
public static booleanverifyShellRect(Shell shell, boolean bAdjustIfInvalid)

param
listener

		boolean bMetricsOk;
		try {
			bMetricsOk = false;
			Point ptTopLeft = shell.getLocation();

			Monitor[] monitors = shell.getDisplay().getMonitors();
			for (int j = 0; j < monitors.length && !bMetricsOk; j++) {
				Rectangle bounds = monitors[j].getBounds();
				bMetricsOk = bounds.contains(ptTopLeft);
			}
		} catch (NoSuchMethodError e) {
			Rectangle bounds = shell.getDisplay().getBounds();
			bMetricsOk = shell.getBounds().intersects(bounds);
		}
		if (!bMetricsOk && bAdjustIfInvalid) {
			centreWindow(shell);
		}
		return bMetricsOk;
	
public static voidwaitForModals()
Waits until modal dialogs are disposed. Assumes we are one SWT thread

since
3.0.1.3

		SWTThread swt = SWTThread.getInstance();

		Display display;
		if (swt == null) {
			display = Display.getDefault();
			if (display == null) {
				System.err.println("SWT Thread not started yet!");
				return;
			}
		} else {
			if (swt.isTerminated()) {
				return;
			}
			display = swt.getDisplay();
		}

		if (display == null || display.isDisposed()) {
			return;
		}

		Shell[] shells = display.getShells();
		Shell modalShell = null;
		for (int i = 0; i < shells.length; i++) {
			Shell shell = shells[i];
			if ((shell.getStyle() & SWT.APPLICATION_MODAL) > 0) {
				modalShell = shell;
				break;
			}
		}

		if (modalShell != null) {
			while (!modalShell.isDisposed()) {
				if (!display.readAndDispatch()) {
					display.sleep();
				}
			}
		}