diff options
Diffstat (limited to 'bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics')
12 files changed, 11719 insertions, 0 deletions
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Color.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Color.java new file mode 100755 index 0000000000..b202ed4fa5 --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Color.java @@ -0,0 +1,339 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +import org.eclipse.swt.internal.motif.*; +import org.eclipse.swt.*; + +/** + * Instances of this class manage the operating system resources that + * implement SWT's RGB color model. To create a color you can either + * specify the individual color components as integers in the range + * 0 to 255 or provide an instance of an <code>RGB</code>. + * <p> + * Application code must explicitly invoke the <code>Color.dispose()</code> + * method to release the operating system resources managed by each instance + * when those instances are no longer required. + * </p> + * + * @see RGB + * @see Device#getSystemColor + * @see <a href="http://www.eclipse.org/swt/snippets/#color">Color and RGB snippets</a> + * @see <a href="http://www.eclipse.org/swt/examples.php">SWT Example: PaintExample</a> + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + */ +public final class Color extends Resource { + /** + * the handle to the OS color resource + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public XColor handle; + +Color(Device device) { + super(device); +} +/** + * Constructs a new instance of this class given a device and the + * desired red, green and blue values expressed as ints in the range + * 0 to 255 (where 0 is black and 255 is full brightness). On limited + * color devices, the color instance created by this call may not have + * the same RGB values as the ones specified by the arguments. The + * RGB values on the returned instance will be the color values of + * the operating system color. + * <p> + * You must dispose the color when it is no longer required. + * </p> + * + * @param device the device on which to allocate the color + * @param red the amount of red in the color + * @param green the amount of green in the color + * @param blue the amount of blue in the color + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_INVALID_ARGUMENT - if the red, green or blue argument is not between 0 and 255</li> + * </ul> + * + * @see #dispose + */ +public Color (Device device, int red, int green, int blue) { + super(device); + init(red, green, blue); + init(); +} +/** + * Constructs a new instance of this class given a device and an + * <code>RGB</code> describing the desired red, green and blue values. + * On limited color devices, the color instance created by this call + * may not have the same RGB values as the ones specified by the + * argument. The RGB values on the returned instance will be the color + * values of the operating system color. + * <p> + * You must dispose the color when it is no longer required. + * </p> + * + * @param device the device on which to allocate the color + * @param rgb the RGB values of the desired color + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the rgb argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the red, green or blue components of the argument are not between 0 and 255</li> + * </ul> + * + * @see #dispose + */ +public Color (Device device, RGB rgb) { + super(device); + if (rgb == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(rgb.red, rgb.green, rgb.blue); + init(); +} +void destroy() { + int xDisplay = device.xDisplay; + int pixel = handle.pixel; + if (device.colorRefCount != null) { + /* If this was the last reference, remove the color from the list */ + if (--device.colorRefCount[pixel] == 0) { + device.xcolors[pixel] = null; + } + } + int colormap = OS.XDefaultColormap(xDisplay, OS.XDefaultScreen(xDisplay)); + OS.XFreeColors(xDisplay, colormap, new int[] { pixel }, 1, 0); + handle = null; +} +/** + * Compares the argument to the receiver, and returns true + * if they represent the <em>same</em> object using a class + * specific comparison. + * + * @param object the object to compare with this object + * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise + * + * @see #hashCode + */ +public boolean equals (Object object) { + if (object == this) return true; + if (!(object instanceof Color)) return false; + Color color = (Color)object; + XColor xColor = color.handle; + if (handle == xColor) return true; + return device == color.device && handle.red == xColor.red && + handle.green == xColor.green && handle.blue == xColor.blue; +} +/** + * Returns the amount of blue in the color, from 0 to 255. + * + * @return the blue component of the color + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getBlue () { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return (handle.blue >> 8) & 0xFF; +} +/** + * Returns the amount of green in the color, from 0 to 255. + * + * @return the green component of the color + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getGreen () { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return (handle.green >> 8) & 0xFF; +} +/** + * Returns the amount of red in the color, from 0 to 255. + * + * @return the red component of the color + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getRed () { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return (handle.red >> 8) & 0xFF; +} +/** + * Returns an <code>RGB</code> representing the receiver. + * + * @return the RGB for the color + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public RGB getRGB () { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return new RGB((handle.red >> 8) & 0xFF, (handle.green >> 8) & 0xFF, (handle.blue >> 8) & 0xFF); +} +/** + * Returns an integer hash code for the receiver. Any two + * objects that return <code>true</code> when passed to + * <code>equals</code> must return the same value for this + * method. + * + * @return the receiver's hash + * + * @see #equals + */ +public int hashCode () { + if (isDisposed()) return 0; + return handle.red ^ handle.green ^ handle.blue; +} +void init(int red, int green, int blue) { + if ((red > 255) || (red < 0) || + (green > 255) || (green < 0) || + (blue > 255) || (blue < 0)) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + XColor xColor = new XColor(); + xColor.red = (short)((red & 0xFF) | ((red & 0xFF) << 8)); + xColor.green = (short)((green & 0xFF) | ((green & 0xFF) << 8)); + xColor.blue = (short)((blue & 0xFF) | ((blue & 0xFF) << 8)); + handle = xColor; + int xDisplay = device.xDisplay; + int screen = OS.XDefaultScreen(xDisplay); + int colormap = OS.XDefaultColormap(xDisplay, screen); + /* 1. Try to allocate the color */ + if (OS.XAllocColor(xDisplay, colormap, xColor) != 0) { + if (device.colorRefCount != null) { + /* Make a copy of the color to put in the colors array */ + XColor colorCopy = new XColor(); + colorCopy.red = xColor.red; + colorCopy.green = xColor.green; + colorCopy.blue = xColor.blue; + colorCopy.pixel = xColor.pixel; + device.xcolors[colorCopy.pixel] = colorCopy; + device.colorRefCount[xColor.pixel]++; + } + return; + } + /* + * 2. Allocation failed. Query the entire colormap and + * find the closest match which can be allocated. + * This should never occur on a truecolor display. + */ + Visual visual = new Visual(); + OS.memmove(visual, OS.XDefaultVisual(xDisplay, screen), Visual.sizeof); + int mapEntries = visual.map_entries; + XColor[] queried = new XColor[mapEntries]; + int[] distances = new int[mapEntries]; + /* + * Query all colors in the colormap and calculate the distance + * from each to the desired color. + */ + for (int i = 0; i < mapEntries; i++) { + XColor color = new XColor(); + color.pixel = i; + queried[i] = color; + OS.XQueryColor(xDisplay, colormap, color); + int r = red - ((color.red >> 8) & 0xFF); + int g = green - ((color.green >> 8) & 0xFF); + int b = blue - ((color.blue >> 8) & 0xFF); + distances[i] = r*r + g*g + b*b; + } + /* + * Try to allocate closest matching queried color. + * The allocation can fail if the closest matching + * color is allocated privately, so go through them + * in order of increasing distance. + */ + for (int i = 0; i < mapEntries; i++) { + int minDist = 0x30000; + int minIndex = 0; + for (int j = 0; j < mapEntries; j++) { + if (distances[j] < minDist) { + minDist = distances[j]; + minIndex = j; + } + } + XColor queriedColor = queried[minIndex]; + XColor osColor = new XColor(); + osColor.red = queriedColor.red; + osColor.green = queriedColor.green; + osColor.blue = queriedColor.blue; + if (OS.XAllocColor(xDisplay, colormap, osColor) != 0) { + /* Allocation succeeded. Copy the fields into the handle */ + xColor.red = osColor.red; + xColor.green = osColor.green; + xColor.blue = osColor.blue; + xColor.pixel = osColor.pixel; + if (device.colorRefCount != null) { + /* Put osColor in the colors array */ + device.xcolors[osColor.pixel] = osColor; + device.colorRefCount[osColor.pixel]++; + } + return; + } + /* The allocation failed; matching color is allocated privately */ + distances[minIndex] = 0x30000; + } + /* + * 3. Couldn't allocate any of the colors in the colormap. + * This means all colormap entries were allocated privately + * by other applications. Give up and allocate black. + */ + XColor osColor = new XColor(); + OS.XAllocColor(xDisplay, colormap, osColor); + /* Copy the fields into the handle */ + xColor.red = osColor.red; + xColor.green = osColor.green; + xColor.blue = osColor.blue; + xColor.pixel = osColor.pixel; + if (device.colorRefCount != null) { + /* Put osColor in the colors array */ + device.xcolors[osColor.pixel] = osColor; + device.colorRefCount[osColor.pixel]++; + } +} +/** + * Returns <code>true</code> if the color has been disposed, + * and <code>false</code> otherwise. + * <p> + * This method gets the dispose state for the color. + * When a color has been disposed, it is an error to + * invoke any other method using the color. + * + * @return <code>true</code> when the color is disposed and <code>false</code> otherwise + */ +public boolean isDisposed() { + return handle == null; +} +public static Color motif_new(Device device, XColor xColor) { + Color color = new Color(device); + color.handle = xColor; + return color; +} +/** + * Returns a string containing a concise, human-readable + * description of the receiver. + * + * @return a string representation of the receiver + */ +public String toString () { + if (isDisposed()) return "Color {*DISPOSED*}"; + return "Color {" + getRed() + ", " + getGreen() + ", " + getBlue() + "}"; +} +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Cursor.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Cursor.java new file mode 100755 index 0000000000..cc3c048e0f --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Cursor.java @@ -0,0 +1,441 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +import org.eclipse.swt.internal.motif.*; +import org.eclipse.swt.*; + +/** + * Instances of this class manage operating system resources that + * specify the appearance of the on-screen pointer. To create a + * cursor you specify the device and either a simple cursor style + * describing one of the standard operating system provided cursors + * or the image and mask data for the desired appearance. + * <p> + * Application code must explicitly invoke the <code>Cursor.dispose()</code> + * method to release the operating system resources managed by each instance + * when those instances are no longer required. + * </p> + * <dl> + * <dt><b>Styles:</b></dt> + * <dd> + * CURSOR_ARROW, CURSOR_WAIT, CURSOR_CROSS, CURSOR_APPSTARTING, CURSOR_HELP, + * CURSOR_SIZEALL, CURSOR_SIZENESW, CURSOR_SIZENS, CURSOR_SIZENWSE, CURSOR_SIZEWE, + * CURSOR_SIZEN, CURSOR_SIZES, CURSOR_SIZEE, CURSOR_SIZEW, CURSOR_SIZENE, CURSOR_SIZESE, + * CURSOR_SIZESW, CURSOR_SIZENW, CURSOR_UPARROW, CURSOR_IBEAM, CURSOR_NO, CURSOR_HAND + * </dd> + * </dl> + * <p> + * Note: Only one of the above styles may be specified. + * </p> + * + * @see <a href="http://www.eclipse.org/swt/snippets/#cursor">Cursor snippets</a> + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + */ +public final class Cursor extends Resource { + /** + * the handle to the OS cursor resource + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int handle; + + static final byte[] APPSTARTING_SRC = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x0c, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, + 0x7c, 0x00, 0x00, 0x00, (byte)0xfc, 0x00, 0x00, 0x00, (byte)0xfc, 0x01, 0x00, 0x00, + (byte)0xfc, 0x3b, 0x00, 0x00, 0x7c, 0x38, 0x00, 0x00, 0x6c, 0x54, 0x00, 0x00, + (byte)0xc4, (byte)0xdc, 0x00, 0x00, (byte)0xc0, 0x44, 0x00, 0x00, (byte)0x80, 0x39, 0x00, 0x00, + (byte)0x80, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + + static final byte[] APPSTARTING_MASK = { + 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, + 0x1e, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, + (byte)0xfe, 0x00, 0x00, 0x00, (byte)0xfe, 0x01, 0x00, 0x00, (byte)0xfe, 0x3b, 0x00, 0x00, + (byte)0xfe, 0x7f, 0x00, 0x00, (byte)0xfe, 0x7f, 0x00, 0x00, (byte)0xfe, (byte)0xfe, 0x00, 0x00, + (byte)0xee, (byte)0xff, 0x01, 0x00, (byte)0xe4, (byte)0xff, 0x00, 0x00, (byte)0xc0, 0x7f, 0x00, 0x00, + (byte)0xc0, 0x7f, 0x00, 0x00, (byte)0x80, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +Cursor (Device device) { + super(device); +} +/** + * Constructs a new cursor given a device and a style + * constant describing the desired cursor appearance. + * <p> + * You must dispose the cursor when it is no longer required. + * </p> + * + * @param device the device on which to allocate the cursor + * @param style the style of cursor to allocate + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_INVALID_ARGUMENT - when an unknown style is specified</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES - if a handle could not be obtained for cursor creation</li> + * </ul> + * + * @see SWT#CURSOR_ARROW + * @see SWT#CURSOR_WAIT + * @see SWT#CURSOR_CROSS + * @see SWT#CURSOR_APPSTARTING + * @see SWT#CURSOR_HELP + * @see SWT#CURSOR_SIZEALL + * @see SWT#CURSOR_SIZENESW + * @see SWT#CURSOR_SIZENS + * @see SWT#CURSOR_SIZENWSE + * @see SWT#CURSOR_SIZEWE + * @see SWT#CURSOR_SIZEN + * @see SWT#CURSOR_SIZES + * @see SWT#CURSOR_SIZEE + * @see SWT#CURSOR_SIZEW + * @see SWT#CURSOR_SIZENE + * @see SWT#CURSOR_SIZESE + * @see SWT#CURSOR_SIZESW + * @see SWT#CURSOR_SIZENW + * @see SWT#CURSOR_UPARROW + * @see SWT#CURSOR_IBEAM + * @see SWT#CURSOR_NO + * @see SWT#CURSOR_HAND + */ +public Cursor (Device device, int style) { + super(device); + int shape = 0; + switch (style) { + case SWT.CURSOR_APPSTARTING: break; + case SWT.CURSOR_ARROW: shape = OS.XC_left_ptr; break; + case SWT.CURSOR_WAIT: shape = OS.XC_watch; break; + case SWT.CURSOR_HAND: shape = OS.XC_hand2; break; + case SWT.CURSOR_CROSS: shape = OS.XC_cross; break; + case SWT.CURSOR_HELP: shape = OS.XC_question_arrow; break; + case SWT.CURSOR_SIZEALL: shape = OS.XC_fleur; break; + case SWT.CURSOR_SIZENESW: shape = OS.XC_sizing; break; + case SWT.CURSOR_SIZENS: shape = OS.XC_double_arrow; break; + case SWT.CURSOR_SIZENWSE: shape = OS.XC_sizing; break; + case SWT.CURSOR_SIZEWE: shape = OS.XC_sb_h_double_arrow; break; + case SWT.CURSOR_SIZEN: shape = OS.XC_top_side; break; + case SWT.CURSOR_SIZES: shape = OS.XC_bottom_side; break; + case SWT.CURSOR_SIZEE: shape = OS.XC_right_side; break; + case SWT.CURSOR_SIZEW: shape = OS.XC_left_side; break; + case SWT.CURSOR_SIZENE: shape = OS.XC_top_right_corner; break; + case SWT.CURSOR_SIZESE: shape = OS.XC_bottom_right_corner; break; + case SWT.CURSOR_SIZESW: shape = OS.XC_bottom_left_corner; break; + case SWT.CURSOR_SIZENW: shape = OS.XC_top_left_corner; break; + case SWT.CURSOR_UPARROW: shape = OS.XC_sb_up_arrow; break; + case SWT.CURSOR_IBEAM: shape = OS.XC_xterm; break; + case SWT.CURSOR_NO: shape = OS.XC_X_cursor; break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + if (shape == 0 && style == SWT.CURSOR_APPSTARTING) { + handle = createCursor(APPSTARTING_SRC, APPSTARTING_MASK, 32, 32, 2, 2, true); + } else { + handle = OS.XCreateFontCursor(this.device.xDisplay, shape); + } + if (handle == 0) SWT.error(SWT.ERROR_NO_HANDLES); + init(); +} +/** + * Constructs a new cursor given a device, image and mask + * data describing the desired cursor appearance, and the x + * and y coordinates of the <em>hotspot</em> (that is, the point + * within the area covered by the cursor which is considered + * to be where the on-screen pointer is "pointing"). + * <p> + * The mask data is allowed to be null, but in this case the source + * must be an ImageData representing an icon that specifies both + * color data and mask data. + * <p> + * You must dispose the cursor when it is no longer required. + * </p> + * + * @param device the device on which to allocate the cursor + * @param source the color data for the cursor + * @param mask the mask data for the cursor (or null) + * @param hotspotX the x coordinate of the cursor's hotspot + * @param hotspotY the y coordinate of the cursor's hotspot + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the source is null</li> + * <li>ERROR_NULL_ARGUMENT - if the mask is null and the source does not have a mask</li> + * <li>ERROR_INVALID_ARGUMENT - if the source and the mask are not the same + * size, or if the hotspot is outside the bounds of the image</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES - if a handle could not be obtained for cursor creation</li> + * </ul> + */ +public Cursor (Device device, ImageData source, ImageData mask, int hotspotX, int hotspotY) { + super(device); + if (source == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (mask == null) { + if (source.getTransparencyType() != SWT.TRANSPARENCY_MASK) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + mask = source.getTransparencyMask(); + } + /* Check the bounds. Mask must be the same size as source */ + if (mask.width != source.width || mask.height != source.height) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + /* Check the hotspots */ + if (hotspotX >= source.width || hotspotX < 0 || + hotspotY >= source.height || hotspotY < 0) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + /* Convert depth to 1 */ + source = ImageData.convertMask(source); + mask = ImageData.convertMask(mask); + byte[] sourceData = new byte[source.data.length]; + byte[] maskData = new byte[mask.data.length]; + /* Swap the bits in each byte and convert to appropriate scanline pad */ + byte[] data = source.data; + for (int i = 0; i < data.length; i++) { + byte s = data[i]; + sourceData[i] = (byte)(((s & 0x80) >> 7) | + ((s & 0x40) >> 5) | + ((s & 0x20) >> 3) | + ((s & 0x10) >> 1) | + ((s & 0x08) << 1) | + ((s & 0x04) << 3) | + ((s & 0x02) << 5) | + ((s & 0x01) << 7)); + sourceData[i] = (byte) ~sourceData[i]; + } + sourceData = ImageData.convertPad(sourceData, source.width, source.height, source.depth, source.scanlinePad, 1); + data = mask.data; + for (int i = 0; i < data.length; i++) { + byte s = data[i]; + maskData[i] = (byte)(((s & 0x80) >> 7) | + ((s & 0x40) >> 5) | + ((s & 0x20) >> 3) | + ((s & 0x10) >> 1) | + ((s & 0x08) << 1) | + ((s & 0x04) << 3) | + ((s & 0x02) << 5) | + ((s & 0x01) << 7)); + maskData[i] = (byte) ~maskData[i]; + } + maskData = ImageData.convertPad(maskData, mask.width, mask.height, mask.depth, mask.scanlinePad, 1); + /* Note that the mask and source are reversed */ + handle = createCursor(maskData, sourceData, source.width, source.height, hotspotX, hotspotY, true); + if (handle == 0) SWT.error(SWT.ERROR_NO_HANDLES); + init(); +} +/** + * Constructs a new cursor given a device, image data describing + * the desired cursor appearance, and the x and y coordinates of + * the <em>hotspot</em> (that is, the point within the area + * covered by the cursor which is considered to be where the + * on-screen pointer is "pointing"). + * <p> + * You must dispose the cursor when it is no longer required. + * </p> + * + * @param device the device on which to allocate the cursor + * @param source the image data for the cursor + * @param hotspotX the x coordinate of the cursor's hotspot + * @param hotspotY the y coordinate of the cursor's hotspot + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the image is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the hotspot is outside the bounds of the + * image</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES - if a handle could not be obtained for cursor creation</li> + * </ul> + * + * @since 3.0 + */ +public Cursor(Device device, ImageData source, int hotspotX, int hotspotY) { + super(device); + if (source == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (hotspotX >= source.width || hotspotX < 0 || + hotspotY >= source.height || hotspotY < 0) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + ImageData mask = source.getTransparencyMask(); + + /* Ensure depth is equal to 1 */ + if (source.depth > 1) { + /* Create a destination image with no data */ + ImageData newSource = new ImageData( + source.width, source.height, 1, ImageData.bwPalette(), + 1, null, 0, null, null, -1, -1, 0, 0, 0, 0, 0); + + byte[] newReds = new byte[]{0, (byte)255}, newGreens = newReds, newBlues = newReds; + + /* Convert the source to a black and white image of depth 1 */ + PaletteData palette = source.palette; + if (palette.isDirect) { + ImageData.blit(ImageData.BLIT_SRC, + source.data, source.depth, source.bytesPerLine, source.getByteOrder(), 0, 0, source.width, source.height, palette.redMask, palette.greenMask, palette.blueMask, + ImageData.ALPHA_OPAQUE, null, 0, 0, 0, + newSource.data, newSource.depth, newSource.bytesPerLine, newSource.getByteOrder(), 0, 0, newSource.width, newSource.height, newReds, newGreens, newBlues, + false, false); + } else { + RGB[] rgbs = palette.getRGBs(); + int length = rgbs.length; + byte[] srcReds = new byte[length]; + byte[] srcGreens = new byte[length]; + byte[] srcBlues = new byte[length]; + for (int i = 0; i < rgbs.length; i++) { + RGB rgb = rgbs[i]; + if (rgb == null) continue; + srcReds[i] = (byte)rgb.red; + srcGreens[i] = (byte)rgb.green; + srcBlues[i] = (byte)rgb.blue; + } + ImageData.blit(ImageData.BLIT_SRC, + source.data, source.depth, source.bytesPerLine, source.getByteOrder(), 0, 0, source.width, source.height, srcReds, srcGreens, srcBlues, + ImageData.ALPHA_OPAQUE, null, 0, 0, 0, + newSource.data, newSource.depth, newSource.bytesPerLine, newSource.getByteOrder(), 0, 0, newSource.width, newSource.height, newReds, newGreens, newBlues, + false, false); + } + source = newSource; + } + + /* Swap the bits in each byte and convert to appropriate scanline pad */ + byte[] sourceData = new byte[source.data.length]; + byte[] maskData = new byte[mask.data.length]; + byte[] data = source.data; + for (int i = 0; i < data.length; i++) { + byte s = data[i]; + sourceData[i] = (byte)(((s & 0x80) >> 7) | + ((s & 0x40) >> 5) | + ((s & 0x20) >> 3) | + ((s & 0x10) >> 1) | + ((s & 0x08) << 1) | + ((s & 0x04) << 3) | + ((s & 0x02) << 5) | + ((s & 0x01) << 7)); + } + sourceData = ImageData.convertPad(sourceData, source.width, source.height, source.depth, source.scanlinePad, 1); + data = mask.data; + for (int i = 0; i < data.length; i++) { + byte s = data[i]; + maskData[i] = (byte)(((s & 0x80) >> 7) | + ((s & 0x40) >> 5) | + ((s & 0x20) >> 3) | + ((s & 0x10) >> 1) | + ((s & 0x08) << 1) | + ((s & 0x04) << 3) | + ((s & 0x02) << 5) | + ((s & 0x01) << 7)); + } + maskData = ImageData.convertPad(maskData, mask.width, mask.height, mask.depth, mask.scanlinePad, 1); + handle = createCursor(sourceData, maskData, source.width, source.height, hotspotX, hotspotY, false); + if (handle == 0) SWT.error(SWT.ERROR_NO_HANDLES); + init(); +} +int createCursor(byte[] sourceData, byte[] maskData, int width, int height, int hotspotX, int hotspotY, boolean reverse) { + int xDisplay = device.xDisplay; + int drawable = OS.XDefaultRootWindow(xDisplay); + int sourcePixmap = OS.XCreateBitmapFromData(xDisplay, drawable, sourceData, width, height); + int maskPixmap = OS.XCreateBitmapFromData(xDisplay, drawable, maskData, width, height); + int cursor = 0; + if (sourcePixmap != 0 && maskPixmap != 0) { + int screenNum = OS.XDefaultScreen(xDisplay); + XColor foreground = new XColor(); + foreground.pixel = !reverse ? OS.XWhitePixel(xDisplay, screenNum) : OS.XBlackPixel(xDisplay, screenNum); + if (!reverse) foreground.red = foreground.green = foreground.blue = (short)0xFFFF; + XColor background = new XColor(); + background.pixel = reverse ? OS.XWhitePixel(xDisplay, screenNum) : OS.XBlackPixel(xDisplay, screenNum); + if (reverse) background.red = background.green = background.blue = (short)0xFFFF; + cursor = OS.XCreatePixmapCursor(xDisplay, sourcePixmap, maskPixmap, foreground, background, hotspotX, hotspotY); + } + if (sourcePixmap != 0) OS.XFreePixmap(xDisplay, sourcePixmap); + if (maskPixmap != 0) OS.XFreePixmap(xDisplay, maskPixmap); + return cursor; +} +void destroy() { + OS.XFreeCursor(device.xDisplay, handle); + handle = 0; +} +/** + * Compares the argument to the receiver, and returns true + * if they represent the <em>same</em> object using a class + * specific comparison. + * + * @param object the object to compare with this object + * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise + * + * @see #hashCode + */ +public boolean equals (Object object) { + if (object == this) return true; + if (!(object instanceof Cursor)) return false; + Cursor cursor = (Cursor)object; + return device == cursor.device && handle == cursor.handle; +} +/** + * Returns an integer hash code for the receiver. Any two + * objects that return <code>true</code> when passed to + * <code>equals</code> must return the same value for this + * method. + * + * @return the receiver's hash + * + * @see #equals + */ +public int hashCode () { + return handle; +} +/** + * Returns <code>true</code> if the cursor has been disposed, + * and <code>false</code> otherwise. + * <p> + * This method gets the dispose state for the cursor. + * When a cursor has been disposed, it is an error to + * invoke any other method using the cursor. + * + * @return <code>true</code> when the cursor is disposed and <code>false</code> otherwise + */ +public boolean isDisposed() { + return handle == 0; +} +public static Cursor motif_new(Device device, int handle) { + Cursor cursor = new Cursor(device); + cursor.handle = handle; + return cursor; +} +/** + * Returns a string containing a concise, human-readable + * description of the receiver. + * + * @return a string representation of the receiver + */ +public String toString () { + if (isDisposed()) return "Cursor {*DISPOSED*}"; + return "Cursor {" + handle + "}"; +} +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Device.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Device.java new file mode 100755 index 0000000000..4587d5ffe2 --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Device.java @@ -0,0 +1,1021 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +import org.eclipse.swt.*; +import org.eclipse.swt.internal.*; +import org.eclipse.swt.internal.motif.*; + +/** + * This class is the abstract superclass of all device objects, + * such as the Display device and the Printer device. Devices + * can have a graphics context (GC) created for them, and they + * can be drawn on by sending messages to the associated GC. + * + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + */ +public abstract class Device implements Drawable { + /** + * the handle to the X Display + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int xDisplay; + + /** + * whether the XLFD resolution should match the + * resolution of the device when fonts are created + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + // TEMPORARY CODE + public boolean setDPI; + + /* Debugging */ + public static boolean DEBUG; + boolean debug = DEBUG; + boolean tracking = DEBUG; + Error [] errors; + Object [] objects; + Object trackingLock; + + /* Arguments for XtOpenDisplay */ + String display_name; + String application_name; + String application_class; + + /* Colormap and reference count for this display */ + XColor [] xcolors; + int [] colorRefCount; + + /* System Colors */ + Color COLOR_BLACK, COLOR_DARK_RED, COLOR_DARK_GREEN, COLOR_DARK_YELLOW, COLOR_DARK_BLUE; + Color COLOR_DARK_MAGENTA, COLOR_DARK_CYAN, COLOR_GRAY, COLOR_DARK_GRAY, COLOR_RED; + Color COLOR_GREEN, COLOR_YELLOW, COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE; + + /* System Font */ + Font systemFont; + + int shellHandle; + + boolean useXRender; + + static boolean CAIRO_LOADED; + + /* Parsing Tables */ + int tabPointer, crPointer; + /** + * parse table mappings for tab and cr + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + // TEMPORARY CODE + public int tabMapping, crMapping; + + /* Xt Warning and Error Handlers */ + boolean warnings = true; + Callback xtWarningCallback, xtErrorCallback; + int xtWarningProc, xtErrorProc, xtNullWarningProc, xtNullErrorProc; + + /* X Warning and Error Handlers */ + static Callback XErrorCallback, XIOErrorCallback; + static int XErrorProc, XIOErrorProc, XNullErrorProc, XNullIOErrorProc; + static Device[] Devices = new Device[4]; + + /* Initialize X and Xt */ + static { + /* + * This code is intentionally commented. + */ +// OS.XInitThreads (); +// OS.XtToolkitThreadInitialize (); + OS.XtToolkitInitialize (); + } + + /* + * TEMPORARY CODE. When a graphics object is + * created and the device parameter is null, + * the current Display is used. This presents + * a problem because SWT graphics does not + * reference classes in SWT widgets. The correct + * fix is to remove this feature. Unfortunately, + * too many application programs rely on this + * feature. + */ + protected static Device CurrentDevice; + protected static Runnable DeviceFinder; + static { + try { + Class.forName ("org.eclipse.swt.widgets.Display"); + } catch (ClassNotFoundException e) {} + } + +/* +* TEMPORARY CODE +*/ +static synchronized Device getDevice () { + if (DeviceFinder != null) DeviceFinder.run(); + Device device = CurrentDevice; + CurrentDevice = null; + return device; +} + +/** + * Constructs a new instance of this class. + * <p> + * You must dispose the device when it is no longer required. + * </p> + * + * @see #create + * @see #init + * + * @since 3.1 + */ +public Device() { + this(null); +} + +/** + * Constructs a new instance of this class. + * <p> + * You must dispose the device when it is no longer required. + * </p> + * + * @param data the DeviceData which describes the receiver + * + * @see #create + * @see #init + * @see DeviceData + */ +public Device(DeviceData data) { + synchronized (Device.class) { + if (data != null) { + display_name = data.display_name; + application_name = data.application_name; + application_class = data.application_class; + tracking = data.tracking; + debug = data.debug; + } + if (tracking) { + errors = new Error [128]; + objects = new Object [128]; + trackingLock = new Object (); + } + create (data); + init (); + register (this); + + /* Initialize the system font slot */ + systemFont = getSystemFont (); + } +} + +void checkCairo() { + if (CAIRO_LOADED) return; + try { + /* Check if cairo is available on the system */ + byte[] buffer = Converter.wcsToMbcs(null, "libcairo.so.2", true); + int /*long*/ libcairo = OS.dlopen(buffer, OS.RTLD_LAZY); + if (libcairo != 0) { + OS.dlclose(libcairo); + } else { + try { + System.loadLibrary("cairo-swt"); + } catch (UnsatisfiedLinkError e) { + /* Ignore problems loading the fallback library */ + } + } + Class.forName("org.eclipse.swt.internal.cairo.Cairo"); + CAIRO_LOADED = true; + } catch (Throwable t) { + SWT.error(SWT.ERROR_NO_GRAPHICS_LIBRARY, t, " [Cairo required]"); + } +} + +/** + * Throws an <code>SWTException</code> if the receiver can not + * be accessed by the caller. This may include both checks on + * the state of the receiver and more generally on the entire + * execution context. This method <em>should</em> be called by + * device implementors to enforce the standard SWT invariants. + * <p> + * Currently, it is an error to invoke any method (other than + * <code>isDisposed()</code> and <code>dispose()</code>) on a + * device that has had its <code>dispose()</code> method called. + * </p><p> + * In future releases of SWT, there may be more or fewer error + * checks and exceptions may be thrown for different reasons. + * <p> + * + * @exception SWTException <ul> + * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +protected void checkDevice () { + if (xDisplay == 0) SWT.error (SWT.ERROR_DEVICE_DISPOSED); +} + +/** + * Creates the device in the operating system. If the device + * does not have a handle, this method may do nothing depending + * on the device. + * <p> + * This method is called before <code>init</code>. + * </p><p> + * Subclasses are supposed to reimplement this method and not + * call the <code>super</code> implementation. + * </p> + * + * @param data the DeviceData which describes the receiver + * + * @see #init + */ +protected void create (DeviceData data) { +} + +synchronized static void deregister (Device device) { + for (int i=0; i<Devices.length; i++) { + if (device == Devices [i]) Devices [i] = null; + } +} + +/** + * Destroys the device in the operating system and releases + * the device's handle. If the device does not have a handle, + * this method may do nothing depending on the device. + * <p> + * This method is called after <code>release</code>. + * </p><p> + * Subclasses are supposed to reimplement this method and not + * call the <code>super</code> implementation. + * </p> + * + * @see #dispose + * @see #release + */ +protected void destroy () { +} + +/** + * Disposes of the operating system resources associated with + * the receiver. After this method has been invoked, the receiver + * will answer <code>true</code> when sent the message + * <code>isDisposed()</code>. + * + * @see #release + * @see #destroy + * @see #checkDevice + */ +public void dispose () { + synchronized (Device.class) { + if (isDisposed()) return; + checkDevice (); + release (); + destroy (); + deregister (this); + xDisplay = 0; + if (tracking) { + synchronized (trackingLock) { + objects = null; + errors = null; + trackingLock = null; + } + } + } +} + +void dispose_Object (Object object) { + synchronized (trackingLock) { + for (int i=0; i<objects.length; i++) { + if (objects [i] == object) { + objects [i] = null; + errors [i] = null; + return; + } + } + } +} + +static synchronized Device findDevice (int xDisplay) { + for (int i=0; i<Devices.length; i++) { + Device device = Devices [i]; + if (device != null && device.xDisplay == xDisplay) { + return device; + } + } + return null; +} + +/** + * Returns a rectangle describing the receiver's size and location. + * + * @return the bounding rectangle + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Rectangle getBounds () { + checkDevice (); + int screen = OS.XDefaultScreen (xDisplay); + int width = OS.XDisplayWidth (xDisplay, screen); + int height = OS.XDisplayHeight (xDisplay, screen); + return new Rectangle (0, 0, width, height); +} + +/** + * Returns a rectangle which describes the area of the + * receiver which is capable of displaying data. + * + * @return the client area + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getBounds + */ +public Rectangle getClientArea () { + return getBounds (); +} + +/** + * Returns the bit depth of the screen, which is the number of + * bits it takes to represent the number of unique colors that + * the screen is currently capable of displaying. This number + * will typically be one of 1, 8, 15, 16, 24 or 32. + * + * @return the depth of the screen + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getDepth () { + checkDevice (); + int xScreenPtr = OS.XDefaultScreenOfDisplay (xDisplay); + return OS.XDefaultDepthOfScreen (xScreenPtr); +} + +/** + * Returns a <code>DeviceData</code> based on the receiver. + * Modifications made to this <code>DeviceData</code> will not + * affect the receiver. + * + * @return a <code>DeviceData</code> containing the device's data and attributes + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see DeviceData + */ +public DeviceData getDeviceData () { + checkDevice (); + DeviceData data = new DeviceData (); + data.display_name = display_name; + data.application_name = application_name; + data.application_class = application_class; + data.debug = debug; + data.tracking = tracking; + if (tracking) { + synchronized (trackingLock) { + int count = 0, length = objects.length; + for (int i=0; i<length; i++) { + if (objects [i] != null) count++; + } + int index = 0; + data.objects = new Object [count]; + data.errors = new Error [count]; + for (int i=0; i<length; i++) { + if (objects [i] != null) { + data.objects [index] = objects [i]; + data.errors [index] = errors [i]; + index++; + } + } + } + } else { + data.objects = new Object [0]; + data.errors = new Error [0]; + } + return data; +} + +/** + * Returns a point whose x coordinate is the horizontal + * dots per inch of the display, and whose y coordinate + * is the vertical dots per inch of the display. + * + * @return the horizontal and vertical DPI + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Point getDPI () { + checkDevice (); + int xScreenNum = OS.XDefaultScreen (xDisplay); + int width = OS.XDisplayWidth (xDisplay, xScreenNum); + int height = OS.XDisplayHeight (xDisplay, xScreenNum); + int mmX = OS.XDisplayWidthMM (xDisplay, xScreenNum); + int mmY = OS.XDisplayHeightMM (xDisplay, xScreenNum); + /* 0.03937 mm/inch */ + double inchesX = mmX * 0.03937; + double inchesY = mmY * 0.03937; + int x = (int)((width / inchesX) + 0.5); + int y = (int)((height / inchesY) + 0.5); + return new Point (x, y); +} + +/** + * Returns <code>FontData</code> objects which describe + * the fonts that match the given arguments. If the + * <code>faceName</code> is null, all fonts will be returned. + * + * @param faceName the name of the font to look for, or null + * @param scalable if true only scalable fonts are returned, otherwise only non-scalable fonts are returned. + * @return the matching font data + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public FontData [] getFontList (String faceName, boolean scalable) { + checkDevice (); + String xlfd; + if (faceName == null) { + xlfd = "-*-*-*-*-*-*-*-*-*-*-*-*-*-*"; + } else { + int dashIndex = faceName.indexOf('-'); + if (dashIndex < 0) { + xlfd = "-*-" + faceName + "-*-*-*-*-*-*-*-*-*-*-*-*"; + } else { + xlfd = "-" + faceName + "-*-*-*-*-*-*-*-*-*-*-*-*"; + } + } + /* Use the character encoding for the default locale */ + byte [] buffer1 = Converter.wcsToMbcs (null, xlfd, true); + int [] ret = new int [1]; + int listPtr = OS.XListFonts (xDisplay, buffer1, 65535, ret); + int ptr = listPtr; + int [] intBuf = new int [1]; + FontData [] fd = new FontData [ret [0]]; + int fdIndex = 0; + for (int i = 0; i < ret [0]; i++) { + OS.memmove (intBuf, ptr, 4); + int charPtr = intBuf [0]; + int length = OS.strlen (charPtr); + byte [] buffer2 = new byte [length]; + OS.memmove (buffer2, charPtr, length); + /* Use the character encoding for the default locale */ + char [] chars = Converter.mbcsToWcs (null, buffer2); + try { + FontData data = FontData.motif_new (new String (chars)); + boolean isScalable = data.averageWidth == 0 && data.pixels == 0 && data.points == 0; + if (isScalable == scalable) { + fd [fdIndex++] = data; + } + } catch (Exception e) { + /* do not add the font to the list */ + } + ptr += 4; + } + OS.XFreeFontNames (listPtr); + if (fdIndex == ret [0]) return fd; + FontData [] result = new FontData [fdIndex]; + System.arraycopy (fd, 0, result, 0, fdIndex); + return result; +} + +/** + * Returns the matching standard color for the given + * constant, which should be one of the color constants + * specified in class <code>SWT</code>. 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 freed because it was allocated by the system, + * not the application. + * + * @param id the color constant + * @return the matching color + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see SWT + */ +public Color getSystemColor (int id) { + checkDevice (); + switch (id) { + case SWT.COLOR_BLACK: return COLOR_BLACK; + case SWT.COLOR_DARK_RED: return COLOR_DARK_RED; + case SWT.COLOR_DARK_GREEN: return COLOR_DARK_GREEN; + case SWT.COLOR_DARK_YELLOW: return COLOR_DARK_YELLOW; + case SWT.COLOR_DARK_BLUE: return COLOR_DARK_BLUE; + case SWT.COLOR_DARK_MAGENTA: return COLOR_DARK_MAGENTA; + case SWT.COLOR_DARK_CYAN: return COLOR_DARK_CYAN; + case SWT.COLOR_GRAY: return COLOR_GRAY; + case SWT.COLOR_DARK_GRAY: return COLOR_DARK_GRAY; + case SWT.COLOR_RED: return COLOR_RED; + case SWT.COLOR_GREEN: return COLOR_GREEN; + case SWT.COLOR_YELLOW: return COLOR_YELLOW; + case SWT.COLOR_BLUE: return COLOR_BLUE; + case SWT.COLOR_MAGENTA: return COLOR_MAGENTA; + case SWT.COLOR_CYAN: return COLOR_CYAN; + case SWT.COLOR_WHITE: return COLOR_WHITE; + } + return COLOR_BLACK; +} + +/** + * Returns a reasonable font for applications to use. + * On some platforms, this will match the "default font" + * or "system font" if such can be found. This font + * should not be freed because it was allocated by the + * system, not the application. + * <p> + * Typically, applications which want the default look + * should simply not set the font on the widgets they + * create. Widgets are always created with the correct + * default font for the class of user-interface component + * they represent. + * </p> + * + * @return a font + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Font getSystemFont () { + checkDevice (); + return systemFont; +} + +/** + * Returns <code>true</code> if the underlying window system prints out + * warning messages on the console, and <code>setWarnings</code> + * had previously been called with <code>true</code>. + * + * @return <code>true</code>if warnings are being handled, and <code>false</code> otherwise + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public boolean getWarnings () { + checkDevice (); + return _getWarnings(); +} + +boolean _getWarnings () { + return warnings; +} + +/** + * Initializes any internal resources needed by the + * device. + * <p> + * This method is called after <code>create</code>. + * </p><p> + * If subclasses reimplement this method, they must + * call the <code>super</code> implementation. + * </p> + * + * @see #create + */ +protected void init () { + if (debug) OS.XSynchronize (xDisplay, true); + + int[] event_basep = new int[1], error_basep = new int [1]; + if (OS.XRenderQueryExtension (xDisplay, event_basep, error_basep)) { + int[] major_versionp = new int[1], minor_versionp = new int [1]; + OS.XRenderQueryVersion (xDisplay, major_versionp, minor_versionp); + useXRender = major_versionp[0] > 0 || (major_versionp[0] == 0 && minor_versionp[0] >= 8); + } + + /* Create the warning and error callbacks */ + Class clazz = getClass (); + synchronized (clazz) { + if (XErrorCallback == null) { + XErrorCallback = new Callback (clazz, "XErrorProc", 2); + XNullErrorProc = XErrorCallback.getAddress (); + if (XNullErrorProc == 0) SWT.error (SWT.ERROR_NO_MORE_CALLBACKS); + XErrorProc = OS.XSetErrorHandler (XNullErrorProc); + } + if (XIOErrorCallback == null) { + XIOErrorCallback = new Callback (clazz, "XIOErrorProc", 1); + XNullIOErrorProc = XIOErrorCallback.getAddress (); + if (XNullIOErrorProc == 0) SWT.error (SWT.ERROR_NO_MORE_CALLBACKS); + XIOErrorProc = OS.XSetIOErrorHandler (XNullIOErrorProc); + } + } + xtWarningCallback = new Callback (this, "xtWarningProc", 1); + xtNullWarningProc = xtWarningCallback.getAddress (); + if (xtNullWarningProc == 0) SWT.error (SWT.ERROR_NO_MORE_CALLBACKS); + xtErrorCallback = new Callback (this, "xtErrorProc", 1); + xtNullErrorProc = xtErrorCallback.getAddress (); + if (xtNullErrorProc == 0) SWT.error (SWT.ERROR_NO_MORE_CALLBACKS); + int xtContext = OS.XtDisplayToApplicationContext (xDisplay); + xtWarningProc = OS.XtAppSetWarningHandler (xtContext, xtNullWarningProc); + xtErrorProc = OS.XtAppSetErrorHandler (xtContext, xtNullErrorProc); + + /* Only use palettes for <= 8 bpp default visual */ + int xScreenPtr = OS.XDefaultScreenOfDisplay (xDisplay); + int defaultDepth = OS.XDefaultDepthOfScreen (xScreenPtr); + if (defaultDepth <= 8) { + int numColors = 1 << defaultDepth; + colorRefCount = new int [numColors]; + xcolors = new XColor [numColors]; + } + + /* + * The following colors are listed in the Windows + * Programmer's Reference as the colors in the default + * palette. + */ + COLOR_BLACK = new Color (this, 0,0,0); + COLOR_DARK_RED = new Color (this, 0x80,0,0); + COLOR_DARK_GREEN = new Color (this, 0,0x80,0); + COLOR_DARK_YELLOW = new Color (this, 0x80,0x80,0); + COLOR_DARK_BLUE = new Color (this, 0,0,0x80); + COLOR_DARK_MAGENTA = new Color (this, 0x80,0,0x80); + COLOR_DARK_CYAN = new Color (this, 0,0x80,0x80); + COLOR_GRAY = new Color (this, 0xC0,0xC0,0xC0); + COLOR_DARK_GRAY = new Color (this, 0x80,0x80,0x80); + COLOR_RED = new Color (this, 0xFF,0,0); + COLOR_GREEN = new Color (this, 0,0xFF,0); + COLOR_YELLOW = new Color (this, 0xFF,0xFF,0); + COLOR_BLUE = new Color (this, 0,0,0xFF); + COLOR_MAGENTA = new Color (this, 0xFF,0,0xFF); + COLOR_CYAN = new Color (this, 0,0xFF,0xFF); + COLOR_WHITE = new Color (this, 0xFF,0xFF,0xFF); + + int widgetClass = OS.topLevelShellWidgetClass (); + shellHandle = OS.XtAppCreateShell (null, null, widgetClass, xDisplay, null, 0); + if (shellHandle == 0) SWT.error(SWT.ERROR_NO_HANDLES); + + /* Create the parsing tables */ + byte[] tabBuffer = {(byte) '\t', 0}; + tabPointer = OS.XtMalloc (tabBuffer.length); + OS.memmove (tabPointer, tabBuffer, tabBuffer.length); + int tabString = OS.XmStringComponentCreate(OS.XmSTRING_COMPONENT_TAB, 0, null); + int [] argList = { + OS.XmNpattern, tabPointer, + OS.XmNsubstitute, tabString, + }; + tabMapping = OS.XmParseMappingCreate(argList, argList.length / 2); + OS.XmStringFree(tabString); + byte[] crBuffer = {(byte) '\n', 0}; + crPointer = OS.XtMalloc (crBuffer.length); + OS.memmove (crPointer, crBuffer, crBuffer.length); + int crString = OS.XmStringComponentCreate(OS.XmSTRING_COMPONENT_SEPARATOR, 0, null); + argList = new int[] { + OS.XmNpattern, crPointer, + OS.XmNsubstitute, crString, + }; + crMapping = OS.XmParseMappingCreate(argList, argList.length / 2); + OS.XmStringFree(crString); +} + +/** + * Invokes platform specific functionality to allocate a new GC handle. + * <p> + * <b>IMPORTANT:</b> This method is <em>not</em> part of the public + * API for <code>Device</code>. 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. + * </p> + * + * @param data the platform specific GC data + * @return the platform specific GC handle + */ +public abstract int internal_new_GC (GCData data); + +/** + * Invokes platform specific functionality to dispose a GC handle. + * <p> + * <b>IMPORTANT:</b> This method is <em>not</em> part of the public + * API for <code>Device</code>. 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. + * </p> + * + * @param hDC the platform specific GC handle + * @param data the platform specific GC data + */ +public abstract void internal_dispose_GC (int handle, GCData data); + +/** + * Returns <code>true</code> if the device has been disposed, + * and <code>false</code> otherwise. + * <p> + * This method gets the dispose state for the device. + * When a device has been disposed, it is an error to + * invoke any other method using the device. + * + * @return <code>true</code> when the device is disposed and <code>false</code> otherwise + */ +public boolean isDisposed () { + synchronized (Device.class) { + return xDisplay == 0; + } +} + +/** + * Loads the font specified by a file. The font will be + * present in the list of fonts available to the application. + * + * @param path the font file path + * @return whether the font was successfully loaded + * + * @exception SWTException <ul> + * <li>ERROR_NULL_ARGUMENT - if path is null</li> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see Font + * + * @since 3.3 + */ +public boolean loadFont (String path) { + checkDevice(); + if (path == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + //TEMPORARY CODE + /*if (true)*/ return false; +// int index = path.lastIndexOf ("/"); +// if (index != -1) path = path.substring (0, index); +// int [] ndirs = new int [1]; +// int dirs = OS.XGetFontPath (xDisplay, ndirs); +// int [] ptr = new int [1]; +// for (int i = 0; i < ndirs [0]; i++) { +// OS.memmove (ptr, dirs + (i * 4), 4); +// int length = OS.strlen (ptr [0]); +// byte [] buffer = new byte [length]; +// OS.memmove (buffer, ptr [0], length); +// if (Converter.mbcsToWcs (null, buffer).equals (path)) { +// OS.XFreeFontPath (dirs); +// return true; +// } +// } +// int newDirs = OS.XtMalloc ((ndirs [0] + 1) * 4); +// int[] dirsBuffer = new int [ndirs [0] + 1]; +// OS.memmove (dirsBuffer, dirs, ndirs [0] * 4); +// byte[] buffer = Converter.wcsToMbcs (null, path, true); +// int pathPtr = OS.XtMalloc (buffer.length); +// OS.memmove (pathPtr, buffer, buffer.length); +// dirsBuffer [dirsBuffer.length - 1] = pathPtr; +// OS.memmove (newDirs, dirsBuffer, dirsBuffer.length * 4); +// OS.XSetFontPath (xDisplay, newDirs, dirsBuffer.length); +// OS.XFreeFontPath (dirs); +// OS.XFree (newDirs); +// OS.XFree (pathPtr); +// return true; +} + +void new_Object (Object object) { + synchronized (trackingLock) { + for (int i=0; i<objects.length; i++) { + if (objects [i] == null) { + objects [i] = object; + errors [i] = new Error (); + return; + } + } + Object [] newObjects = new Object [objects.length + 128]; + System.arraycopy (objects, 0, newObjects, 0, objects.length); + newObjects [objects.length] = object; + objects = newObjects; + Error [] newErrors = new Error [errors.length + 128]; + System.arraycopy (errors, 0, newErrors, 0, errors.length); + newErrors [errors.length] = new Error (); + errors = newErrors; + } +} + +static synchronized void register (Device device) { + for (int i=0; i<Devices.length; i++) { + if (Devices [i] == null) { + Devices [i] = device; + return; + } + } + Device [] newDevices = new Device [Devices.length + 4]; + System.arraycopy (Devices, 0, newDevices, 0, Devices.length); + newDevices [Devices.length] = device; + Devices = newDevices; +} + +/** + * Releases any internal resources back to the operating + * system and clears all fields except the device handle. + * <p> + * 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 <code>release</code>. 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 <code>destroy</code>. + * </p> + * This method is called before <code>destroy</code>. + * </p><p> + * If subclasses reimplement this method, they must + * call the <code>super</code> implementation. + * </p> + * + * @see #dispose + * @see #destroy + */ +protected void release () { + /* Free the parsing tables */ + OS.XtFree(tabPointer); + OS.XtFree(crPointer); + OS.XmParseMappingFree(tabMapping); + OS.XmParseMappingFree(crMapping); + tabPointer = crPointer = tabMapping = crMapping = 0; + + if (shellHandle != 0) OS.XtDestroyWidget (shellHandle); + shellHandle = 0; + + /* + * Free the palette. Note that this disposes all colors on + * the display that were allocated using the Color constructor. + */ + if (xcolors != null) { + int xScreen = OS.XDefaultScreen (xDisplay); + int xColormap = OS.XDefaultColormap (xDisplay, xScreen); + int [] pixel = new int [1]; + for (int i = 0; i < xcolors.length; i++) { + XColor color = xcolors [i]; + if (color != null) { + pixel [0] = color.pixel; + while (colorRefCount [i] > 0) { + OS.XFreeColors (xDisplay, xColormap, pixel, 1, 0); + --colorRefCount [i]; + } + } + } + } + xcolors = null; + colorRefCount = null; + + if (COLOR_BLACK != null) COLOR_BLACK.dispose(); + if (COLOR_DARK_RED != null) COLOR_DARK_RED.dispose(); + if (COLOR_DARK_GREEN != null) COLOR_DARK_GREEN.dispose(); + if (COLOR_DARK_YELLOW != null) COLOR_DARK_YELLOW.dispose(); + if (COLOR_DARK_BLUE != null) COLOR_DARK_BLUE.dispose(); + if (COLOR_DARK_MAGENTA != null) COLOR_DARK_MAGENTA.dispose(); + if (COLOR_DARK_CYAN != null) COLOR_DARK_CYAN.dispose(); + if (COLOR_GRAY != null) COLOR_GRAY.dispose(); + if (COLOR_DARK_GRAY != null) COLOR_DARK_GRAY.dispose(); + if (COLOR_RED != null) COLOR_RED.dispose(); + if (COLOR_GREEN != null) COLOR_GREEN.dispose(); + if (COLOR_YELLOW != null) COLOR_YELLOW.dispose(); + if (COLOR_BLUE != null) COLOR_BLUE.dispose(); + if (COLOR_MAGENTA != null) COLOR_MAGENTA.dispose(); + if (COLOR_CYAN != null) COLOR_CYAN.dispose(); + if (COLOR_WHITE != null) COLOR_WHITE.dispose(); + COLOR_BLACK = COLOR_DARK_RED = COLOR_DARK_GREEN = COLOR_DARK_YELLOW = + COLOR_DARK_BLUE = COLOR_DARK_MAGENTA = COLOR_DARK_CYAN = COLOR_GRAY = COLOR_DARK_GRAY = COLOR_RED = + COLOR_GREEN = COLOR_YELLOW = COLOR_BLUE = COLOR_MAGENTA = COLOR_CYAN = COLOR_WHITE = null; + + /* Free the Xt error handler */ + int xtContext = OS.XtDisplayToApplicationContext (xDisplay); + OS.XtAppSetErrorHandler (xtContext, xtErrorProc); + xtErrorCallback.dispose (); xtErrorCallback = null; + xtNullErrorProc = xtErrorProc = 0; + + /* Free the Xt Warning handler */ + OS.XtAppSetWarningHandler (xtContext, xtWarningProc); + xtWarningCallback.dispose (); xtWarningCallback = null; + xtNullWarningProc = xtWarningProc = 0; + + int count = 0; + for (int i = 0; i < Devices.length; i++){ + if (Devices [i] != null) count++; + } + if (count == 1) { + /* Free the X IO error handler */ + OS.XSetIOErrorHandler (XIOErrorProc); + XIOErrorCallback.dispose (); XIOErrorCallback = null; + XNullIOErrorProc = XIOErrorProc = 0; + + /* Free the X error handler */ + /* + * Bug in Motif. For some reason, when a pixmap is + * set into a button or label, despite the fact that + * the pixmap is cleared from the widget before it + * is disposed, Motif still references the pixmap + * and attempts to dispose it in XtDestroyApplicationContext(). + * The fix is to avoid warnings by leaving our handler + * and settings warnings to false. + * + * NOTE: The warning callback is leaked. + */ + warnings = false; +// OS.XSetErrorHandler (XErrorProc); +// XErrorCallback.dispose (); XErrorCallback = null; +// XNullErrorProc = XErrorProc = 0; + } +} + +/** + * If the underlying window system supports printing warning messages + * to the console, setting warnings to <code>false</code> prevents these + * messages from being printed. If the argument is <code>true</code> then + * message printing is not blocked. + * + * @param warnings <code>true</code>if warnings should be printed, and <code>false</code> otherwise + * + * @exception SWTException <ul> + * <li>ERROR_DEVICE_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setWarnings (boolean warnings) { + checkDevice (); + _setWarnings(warnings); +} + +void _setWarnings (boolean warnings) { + this.warnings = warnings; +} + +static int XErrorProc (int xDisplay, int xErrorEvent) { + Device device = findDevice (xDisplay); + if (device != null) { + if (device.warnings) { + if (DEBUG || device.debug) { + new SWTError ().printStackTrace (); + } + OS.Call (XErrorProc, xDisplay, xErrorEvent); + } + } else { + if (DEBUG) new SWTError ().printStackTrace (); + OS.Call (XErrorProc, xDisplay, xErrorEvent); + } + return 0; +} + +static int XIOErrorProc (int xDisplay) { + Device device = findDevice (xDisplay); + if (device != null) { + if (DEBUG || device.debug) { + new SWTError ().printStackTrace (); + } + } else { + if (DEBUG) new SWTError ().printStackTrace (); + } + OS.Call (XIOErrorProc, xDisplay, 0); + return 0; +} + +int xtErrorProc (int message) { + if (DEBUG || debug) { + new SWTError ().printStackTrace (); + } + OS.Call (xtErrorProc, message, 0); + return 0; +} + +int xtWarningProc (int message) { + if (warnings) { + if (DEBUG || debug) { + new SWTError ().printStackTrace (); + } + OS.Call (xtWarningProc, message, 0); + } + return 0; +} + +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/DeviceData.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/DeviceData.java new file mode 100755 index 0000000000..ac1c73cf34 --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/DeviceData.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * Copyright (c) 2000, 2005 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +public class DeviceData { + /* + * Motif only fields. + */ + public String display_name; + public String application_name; + public String application_class; + + /* + * Debug fields - may not be honoured + * on some SWT platforms. + */ + public boolean debug; + public boolean tracking; + public Error [] errors; + public Object [] objects; +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Font.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Font.java new file mode 100755 index 0000000000..d5b38499bd --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Font.java @@ -0,0 +1,536 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +import org.eclipse.swt.internal.*; +import org.eclipse.swt.internal.motif.*; +import org.eclipse.swt.*; + +/** + * Instances of this class manage operating system resources that + * define how text looks when it is displayed. Fonts may be constructed + * by providing a device and either name, size and style information + * or a <code>FontData</code> object which encapsulates this data. + * <p> + * Application code must explicitly invoke the <code>Font.dispose()</code> + * method to release the operating system resources managed by each instance + * when those instances are no longer required. + * </p> + * + * @see FontData + * @see <a href="http://www.eclipse.org/swt/snippets/#font">Font snippets</a> + * @see <a href="http://www.eclipse.org/swt/examples.php">SWT Examples: GraphicsExample, PaintExample</a> + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + */ +public final class Font extends Resource { + /** + * the handle to the OS font resource + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int handle; + + /** + * the code page of the font + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + * + * @since 2.0 + */ + public String codePage; + +Font (Device device) { + super(device); +} + +/** + * Constructs a new font given a device and font data + * which describes the desired font's appearance. + * <p> + * You must dispose the font when it is no longer required. + * </p> + * + * @param device the device to create the font on + * @param fd the FontData that describes the desired font (must not be null) + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the fd argument is null</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES - if a font could not be created from the given font data</li> + * </ul> + */ +public Font (Device device, FontData fd) { + super(device); + if (fd == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(new FontData[] {fd}); + init(); +} + +/** + * Constructs a new font given a device and an array + * of font data which describes the desired font's + * appearance. + * <p> + * You must dispose the font when it is no longer required. + * </p> + * + * @param device the device to create the font on + * @param fds the array of FontData that describes the desired font (must not be null) + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the fds argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the length of fds is zero</li> + * <li>ERROR_NULL_ARGUMENT - if any fd in the array is null</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES - if a font could not be created from the given font data</li> + * </ul> + * + * @since 2.1 + */ +public Font (Device device, FontData[] fds) { + super(device); + if (fds == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (fds.length == 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + for (int i=0; i<fds.length; i++) { + if (fds[i] == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + } + init(fds); + init(); +} + +/** + * Constructs a new font given a device, a font name, + * the height of the desired font in points, and a font + * style. + * <p> + * You must dispose the font when it is no longer required. + * </p> + * + * @param device the device to create the font on + * @param name the name of the font (must not be null) + * @param height the font height in points + * @param style a bit or combination of NORMAL, BOLD, ITALIC + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the name argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the height is negative</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES - if a font could not be created from the given arguments</li> + * </ul> + */ +public Font (Device device, String name, int height, int style) { + super(device); + if (name == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(new FontData[]{new FontData(name, height, style)}); + init(); +} + +/*public*/ Font (Device device, String name, float height, int style) { + super(device); + if (name == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(new FontData[]{new FontData(name, height, style)}); + init(); +} + +void destroy() { + if (handle == device.systemFont.handle) return; + OS.XmFontListFree (handle); + handle = 0; +} + +/** + * Compares the argument to the receiver, and returns true + * if they represent the <em>same</em> object using a class + * specific comparison. + * + * @param object the object to compare with this object + * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise + * + * @see #hashCode + */ +public boolean equals (Object object) { + if (object == this) return true; + if (!(object instanceof Font)) return false; + Font font = (Font)object; + return device == font.device && handle == font.handle; +} + +/** + * Returns the code page for the specified font list. + * + * @return the code page for the font list + */ +static String getCodePage (int xDisplay, int fontList) { + int[] buffer = new int[1]; + if (!OS.XmFontListInitFontContext(buffer, fontList)) return null; + int context = buffer[0]; + XFontStruct fontStruct = new XFontStruct(); + int fontListEntry; + String codePage = null; + /* Go through each entry in the font list */ + while ((fontListEntry = OS.XmFontListNextEntry(context)) != 0) { + int fontPtr = OS.XmFontListEntryGetFont(fontListEntry, buffer); + if (buffer[0] == OS.XmFONT_IS_FONT) { + /* FontList contains a single font */ + OS.memmove(fontStruct,fontPtr,20 * 4); + int propPtr = fontStruct.properties; + for (int i = 0; i < fontStruct.n_properties; i++) { + /* Look through properties for XAFONT */ + int[] prop = new int[2]; + OS.memmove(prop, propPtr, 8); + if (prop[0] == OS.XA_FONT) { + /* Found it, prop[1] points to the string */ + int ptr = OS.XmGetAtomName(xDisplay, prop[1]); + int length = OS.strlen(ptr); + byte[] nameBuf = new byte[length]; + OS.memmove(nameBuf, ptr, length); + /* Use the character encoding for the default locale */ + String xlfd = new String(Converter.mbcsToWcs(null, nameBuf)).toLowerCase(); + int start = xlfd.lastIndexOf ('-'); + if (start != -1 && start > 0) { + start = xlfd.lastIndexOf ('-', start - 1); + if (start != -1) { + codePage = xlfd.substring (start + 1, xlfd.length ()); + if (codePage.indexOf ("iso") == 0) { + if (OS.IsLinux) { + codePage = "ISO-" + codePage.substring (3, codePage.length ()); + } + if (OS.IsAIX) { + codePage = "ISO" + codePage.substring (3, codePage.length ()); + } + if (OS.IsHPUX) { + start = codePage.lastIndexOf('-'); + if (start != -1) { + codePage = codePage.substring (0, start) + codePage.substring (start + 1, codePage.length ()); + } + } + } + } + } + OS.XtFree(ptr); + break; + } + propPtr += 8; + } + } + else { + /* FontList contains a fontSet */ + + /* Get the font set locale */ + int localePtr = OS.XLocaleOfFontSet(fontPtr); + int length = OS.strlen (localePtr); + byte [] locale = new byte [length + 1]; + OS.memmove (locale, localePtr, length); + + /* Get code page for the font set locale */ + OS.setlocale (OS.LC_CTYPE, locale); + int codesetPtr = OS.nl_langinfo (OS.CODESET); + length = OS.strlen (codesetPtr); + byte [] codeset = new byte [length]; + OS.memmove (codeset, codesetPtr, length); + codePage = new String(Converter.mbcsToWcs(null, codeset)); + + /* Reset the locale */ + OS.setlocale (OS.LC_CTYPE, new byte[1]); + } + } + OS.XmFontListFreeFontContext(context); + return codePage; +} + +/** + * Returns an array of <code>FontData</code>s representing the receiver. + * On Windows, only one FontData will be returned per font. On X however, + * a <code>Font</code> object <em>may</em> be composed of multiple X + * fonts. To support this case, we return an array of font data objects. + * + * @return an array of font data objects describing the receiver + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public FontData[] getFontData() { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + int xDisplay = device.xDisplay; + /* + * Create a font context to iterate over each element in the font list. + */ + int[] buffer = new int[1]; + if (!OS.XmFontListInitFontContext(buffer, handle)) { + SWT.error (SWT.ERROR_INVALID_FONT); + } + int context = buffer[0]; + XFontStruct fontStruct = new XFontStruct(); + int fontListEntry; + int[] fontStructPtr = new int[1]; + int[] fontNamePtr = new int[1]; + FontData[] data = new FontData[0]; + try { + /* Go through each entry in the font list */ + while ((fontListEntry = OS.XmFontListNextEntry(context)) != 0) { + int fontPtr = OS.XmFontListEntryGetFont(fontListEntry, buffer); + if (buffer[0] == OS.XmFONT_IS_FONT) { + /* FontList contains a single font */ + OS.memmove(fontStruct,fontPtr,20 * 4); + int propPtr = fontStruct.properties; + for (int i = 0; i < fontStruct.n_properties; i++) { + /* Look through properties for XAFONT */ + int[] prop = new int[2]; + OS.memmove(prop, propPtr, 8); + if (prop[0] == OS.XA_FONT) { + /* Found it, prop[1] points to the string */ + int ptr = OS.XmGetAtomName(xDisplay, prop[1]); + int length = OS.strlen(ptr); + byte[] nameBuf = new byte[length]; + OS.memmove(nameBuf, ptr, length); + OS.XtFree(ptr); + /* Use the character encoding for the default locale */ + String xlfd = new String(Converter.mbcsToWcs(null, nameBuf)).toLowerCase(); + /* Add the xlfd to the array */ + FontData[] newData = new FontData[data.length + 1]; + System.arraycopy(data, 0, newData, 0, data.length); + newData[newData.length - 1] = FontData.motif_new(xlfd); + data = newData; + break; + } + propPtr += 8; + } + } + else { + /* FontList contains a fontSet */ + int nFonts = OS.XFontsOfFontSet(fontPtr,fontStructPtr,fontNamePtr); + int [] fontStructs = new int[nFonts]; + OS.memmove(fontStructs,fontStructPtr[0],nFonts * 4); + for (int i = 0; i < nFonts; i++) { // Go through each fontStruct in the font set. + OS.memmove(fontStruct,fontStructs[i],20 * 4); + int propPtr = fontStruct.properties; + for (int j = 0; j < fontStruct.n_properties; j++) { + // Look through properties for XAFONT + int[] prop = new int[2]; + OS.memmove(prop, propPtr, 8); + if (prop[0] == OS.XA_FONT) { + /* Found it, prop[1] points to the string */ + int ptr = OS.XmGetAtomName(xDisplay, prop[1]); + int length = OS.strlen(ptr); + byte[] nameBuf = new byte[length]; + OS.memmove(nameBuf, ptr, length); + OS.XFree(ptr); + String xlfd = new String(Converter.mbcsToWcs(null, nameBuf)).toLowerCase(); + /* Add the xlfd to the array */ + FontData[] newData = new FontData[data.length + 1]; + System.arraycopy(data, 0, newData, 0, data.length); + try { + newData[newData.length - 1] = FontData.motif_new(xlfd); + } catch (Exception e) { + /* + * Some font servers, for example, xfstt, do not pass + * reasonable font properties to the client, so we + * cannot construct a FontData for these. Try to use + * the font name instead. + */ + int[] fontName = new int[1]; + OS.memmove(fontName, fontNamePtr [0] + (i * 4), 4); + ptr = fontName[0]; + if (ptr != 0) { + length = OS.strlen(ptr); + nameBuf = new byte[length]; + OS.memmove(nameBuf, ptr, length); + xlfd = new String(Converter.mbcsToWcs(null, nameBuf)).toLowerCase(); + newData[newData.length - 1] = FontData.motif_new(xlfd); + } + } + data = newData; + break; + } + propPtr += 8; + } + } + } + } + if (data.length == 0) SWT.error (SWT.ERROR_INVALID_FONT); + } catch (Exception e) { + /* + * Some font servers, for example, xfstt, do not pass + * reasonable font properties to the client, so we + * cannot construct a FontData for these. + */ + SWT.error (SWT.ERROR_INVALID_FONT); + } finally { + OS.XmFontListFreeFontContext(context); + } + return data; +} + +/** + * Returns an integer hash code for the receiver. Any two + * objects that return <code>true</code> when passed to + * <code>equals</code> must return the same value for this + * method. + * + * @return the receiver's hash + * + * @see #equals + */ +public int hashCode () { + return handle; +} + +void init (FontData[] fds) { + /* Change current locale if needed. Note: only the first font data is used */ + FontData firstFd = fds[0]; + if (firstFd.lang != null) { + String lang = firstFd.lang; + String country = firstFd.country; + String variant = firstFd.variant; + String osLocale = lang; + if (country != null) osLocale += "_" + country; + if (variant != null) osLocale += "." + variant; + int length = osLocale.length(); + byte [] buffer = new byte[length + 1]; + for (int i=0; i<length; i++) { + buffer[i] = (byte)osLocale.charAt(i); + } + OS.setlocale (OS.LC_CTYPE, buffer); + } + + int fontType = OS.XmFONT_IS_FONTSET; + /* + * Bug in HPUX. If the locale is "C" then FontSets do not work + * properly. The fix is to detect this case and use a Font struct + * instead. + */ + if (OS.IsHPUX) { + int localePtr = OS.setlocale(OS.LC_CTYPE, null); + int length = OS.strlen(localePtr); + byte[] buffer = new byte[length]; + OS.memmove(buffer, localePtr, length); + if ("C".equals(new String(Converter.mbcsToWcs(null, buffer)))) { + fontType = OS.XmFONT_IS_FONT; + } + } + + /* Generate desire font name */ + Point dpi = null; + if (device.setDPI) dpi = device.getDPI(); + StringBuffer stringBuffer = new StringBuffer(); + for (int i = 0; i < fds.length; i++) { + if (i != 0) stringBuffer.append(','); + FontData fd = fds[i]; + int hRes = fd.horizontalResolution, vRes = fd.verticalResolution; + if (dpi != null) { + fd.horizontalResolution = dpi.x; + fd.verticalResolution = dpi.y; + } + stringBuffer.append(fd.getXlfd()); + fd.horizontalResolution = hRes; + fd.verticalResolution = vRes; + } + + /* Append simplified font name */ + FontData newFd = new FontData(); + newFd.points = firstFd.points; + /* + * Bug in Motif. In Japanese AIX only, in some cases loading a bold Japanese + * font takes a very long time (10 minutes) when there are no Japanese bold + * fonts available. The fix is to wildcard the field weight. + */ + if (fontType == OS.XmFONT_IS_FONTSET) { + if (OS.IsAIX && OS.IsDBLocale) { + stringBuffer.append(','); + stringBuffer.append(newFd.getXlfd()); + } else { + newFd.weight = firstFd.weight; + newFd.slant = firstFd.slant; + stringBuffer.append(','); + stringBuffer.append(newFd.getXlfd()); + newFd.weight = null; + newFd.slant = null; + stringBuffer.append(','); + stringBuffer.append(newFd.getXlfd()); + } + } + + /* Load font list entry */ + boolean warnings = device._getWarnings (); + device._setWarnings (false); + byte[] buffer = Converter.wcsToMbcs(null, stringBuffer.toString() , true); + int fontListEntry = OS.XmFontListEntryLoad(device.xDisplay, buffer, fontType, OS.XmFONTLIST_DEFAULT_TAG); + device._setWarnings (warnings); + if (fontListEntry != 0) { + handle = OS.XmFontListAppendEntry(0, fontListEntry); + OS.XmFontListEntryFree(new int[]{fontListEntry}); + int codesetPtr = OS.nl_langinfo(OS.CODESET); + int length = OS.strlen(codesetPtr); + buffer = new byte[length]; + OS.memmove(buffer, codesetPtr, length); + codePage = new String(Converter.mbcsToWcs(null, buffer)); + } else { + Font systemFont = device.systemFont; + handle = systemFont.handle; + codePage = systemFont.codePage; + } + + /* Reset current locale if needed */ + if (firstFd.lang != null) OS.setlocale(OS.LC_CTYPE, new byte[0]); + + if (handle == 0) SWT.error(SWT.ERROR_NO_HANDLES); +} + +/** + * Returns <code>true</code> if the font has been disposed, + * and <code>false</code> otherwise. + * <p> + * This method gets the dispose state for the font. + * When a font has been disposed, it is an error to + * invoke any other method using the font. + * + * @return <code>true</code> when the font is disposed and <code>false</code> otherwise + */ +public boolean isDisposed() { + return handle == 0; +} + +public static Font motif_new(Device device, int handle) { + Font font = new Font(device); + font.handle = handle; + font.codePage = getCodePage(device.xDisplay, handle); + return font; +} + +/** + * Returns a string containing a concise, human-readable + * description of the receiver. + * + * @return a string representation of the receiver + */ +public String toString () { + if (isDisposed()) return "Font {*DISPOSED*}"; + return "Font {" + handle + "}"; +} +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/FontData.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/FontData.java new file mode 100755 index 0000000000..6f50eb10b8 --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/FontData.java @@ -0,0 +1,669 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +import org.eclipse.swt.*; + +/** + * Instances of this class describe operating system fonts. + * <p> + * For platform-independent behaviour, use the get and set methods + * corresponding to the following properties: + * <dl> + * <dt>height</dt><dd>the height of the font in points</dd> + * <dt>name</dt><dd>the face name of the font, which may include the foundry</dd> + * <dt>style</dt><dd>A bitwise combination of NORMAL, ITALIC and BOLD</dd> + * </dl> + * If extra, platform-dependent functionality is required: + * <ul> + * <li>On <em>Windows</em>, the data member of the <code>FontData</code> + * corresponds to a Windows <code>LOGFONT</code> structure whose fields + * may be retrieved and modified.</li> + * <li>On <em>X</em>, the fields of the <code>FontData</code> correspond + * to the entries in the font's XLFD name and may be retrieved and modified. + * </ul> + * Application code does <em>not</em> need to explicitly release the + * resources managed by each instance when those instances are no longer + * required, and thus no <code>dispose()</code> method is provided. + * + * @see Font + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + */ +public final class FontData { + /** + * The company that produced the font + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public String foundry; + /** + * The common name of the font + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public String fontFamily; + /** + * The weight ("medium", "bold") + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public String weight; + /** + * The slant ("o" for oblique, "i" for italic) + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public String slant; + /** + * The set width of the font + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public String setWidth; + /** + * Additional font styles + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public String addStyle; + /** + * The height of the font in pixels + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int pixels; + /** + * The height of the font in tenths of a point + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int points; + /** + * The horizontal screen resolution for which the font was designed + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int horizontalResolution; + /** + * The vertical screen resolution for which the font was designed + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int verticalResolution; + /** + * The font spacing ("m" for monospace, "p" for proportional) + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public String spacing; + /** + * The average character width for the font + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int averageWidth; + /** + * The ISO character set registry + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public String characterSetRegistry; + /** + * The ISO character set name + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public String characterSetName; + + /** + * The locales of the font + */ + String lang, country, variant; +/** + * Constructs a new uninitialized font data. + */ +public FontData () { +} +/** + * Constructs a new FontData given a string representation + * in the form generated by the <code>FontData.toString</code> + * method. + * <p> + * Note that the representation varies between platforms, + * and a FontData can only be created from a string that was + * generated on the same platform. + * </p> + * + * @param string the string representation of a <code>FontData</code> (must not be null) + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the argument does not represent a valid description</li> + * </ul> + * + * @see #toString + */ +public FontData(String string) { + if (string == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int start = 0; + int end = string.indexOf('|'); + if (end == -1) SWT.error(SWT.ERROR_NULL_ARGUMENT); + String version1 = string.substring(start, end); + try { + if (Integer.parseInt(version1) != 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } catch (NumberFormatException e) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + + start = end + 1; + end = string.indexOf('|', start); + if (end == -1) SWT.error(SWT.ERROR_NULL_ARGUMENT); + String name = string.substring(start, end); + + start = end + 1; + end = string.indexOf('|', start); + if (end == -1) SWT.error(SWT.ERROR_NULL_ARGUMENT); + float height = 0; + try { + height = Float.parseFloat(string.substring(start, end)); + } catch (NumberFormatException e) { + SWT.error(SWT.ERROR_NULL_ARGUMENT); + } + + start = end + 1; + end = string.indexOf('|', start); + if (end == -1) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int style = 0; + try { + style = Integer.parseInt(string.substring(start, end)); + } catch (NumberFormatException e) { + SWT.error(SWT.ERROR_NULL_ARGUMENT); + } + + start = end + 1; + end = string.indexOf('|', start); + if (end == -1) { + setName(name); + setHeight(height); + setStyle(style); + return; + } + String platform = string.substring(start, end); + + start = end + 1; + end = string.indexOf('|', start); + if (end == -1) { + setName(name); + setHeight(height); + setStyle(style); + return; + } + String version2 = string.substring(start, end); + + if (platform.equals("MOTIF") && version2.equals("1")) { + start = end + 1; + end = string.length(); + if (end == -1) { + setName(name); + setHeight(height); + setStyle(style); + return; + } + String xlfd = string.substring(start, end); + setXlfd(xlfd); + return; + } + setName(name); + setHeight(height); + setStyle(style); +} +/** + * Constructs a new font data given a font name, + * the height of the desired font in points, + * and a font style. + * + * @param name the name of the font (must not be null) + * @param height the font height in points + * @param style a bit or combination of NORMAL, BOLD, ITALIC + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - when the font name is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the height is negative</li> + * </ul> + */ +public FontData (String name, int height, int style) { + if (name == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + int dash = name.indexOf('-'); + if (dash != -1) { + foundry = name.substring(0, dash); + fontFamily = name.substring(dash + 1); + } else { + fontFamily = name; + } + points = height * 10; + weight = (style & SWT.BOLD) != 0 ? "bold" : "medium"; + slant = (style & SWT.ITALIC) != 0 ? "i" : "r"; +} +/*public*/ FontData (String name, float height, int style) { + if (name == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + int dash = name.indexOf('-'); + if (dash != -1) { + foundry = name.substring(0, dash); + fontFamily = name.substring(dash + 1); + } else { + fontFamily = name; + } + points = (int)(height * 10); + weight = (style & SWT.BOLD) != 0 ? "bold" : "medium"; + slant = (style & SWT.ITALIC) != 0 ? "i" : "r"; +} +/** + * Compares the argument to the receiver, and returns true + * if they represent the <em>same</em> object using a class + * specific comparison. + * + * @param object the object to compare with this object + * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise + * + * @see #hashCode + */ +public boolean equals (Object object) { + return (object == this) || ((object instanceof FontData) && + getXlfd().equals(((FontData)object).getXlfd())); +} +/** + * Returns the height of the receiver in points. + * + * @return the height of this FontData + * + * @see #setHeight(int) + */ +public int getHeight() { + return points / 10; +} +/*public*/ float getHeightF() { + return points / 10f; +} +/** + * Returns the locale of the receiver. + * <p> + * The locale determines which platform character set this + * font is going to use. Widgets and graphics operations that + * use this font will convert UNICODE strings to the platform + * character set of the specified locale. + * </p> + * <p> + * On platforms where there are multiple character sets for a + * given language/country locale, the variant portion of the + * locale will determine the character set. + * </p> + * + * @return the <code>String</code> representing a Locale object + * @since 3.0 + */ +public String getLocale () { + StringBuffer buffer = new StringBuffer (); + char sep = '_'; + if (lang != null) { + buffer.append (lang); + buffer.append (sep); + } + if (country != null) { + buffer.append (country); + buffer.append (sep); + } + if (variant != null) { + buffer.append (variant); + } + + String result = buffer.toString (); + int length = result.length (); + if (length > 0) { + if (result.charAt (length - 1) == sep) { + result = result.substring (0, length - 1); + } + } + return result; +} +/** + * Returns the name of the receiver. + * On platforms that support font foundries, the return value will + * be the foundry followed by a dash ("-") followed by the face name. + * + * @return the name of this <code>FontData</code> + * + * @see #setName + */ +public String getName() { + StringBuffer buffer = new StringBuffer(); + if (foundry != null) { + buffer.append(foundry); + buffer.append("-"); + } + if (fontFamily != null) buffer.append(fontFamily); + return buffer.toString(); +} +/** + * Returns the style of the receiver which is a bitwise OR of + * one or more of the <code>SWT</code> constants NORMAL, BOLD + * and ITALIC. + * + * @return the style of this <code>FontData</code> + * + * @see #setStyle + */ +public int getStyle() { + int style = 0; + if (weight != null && weight.equals("bold")) style |= SWT.BOLD; + if (slant != null && slant.equals("i")) style |= SWT.ITALIC; + return style; +} +String getXlfd() { + String s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14; + s1 = s2 = s3 = s4 = s5 = s6 = s7 = s8 = s9 = s10 = s11 = s12 = s13 = s14 = "*"; + + if (foundry != null) s1 = foundry; + if (fontFamily != null) s2 = fontFamily; + if (weight != null) s3 = weight; + if (slant != null) s4 = slant; + if (setWidth != null) s5 = setWidth; + if (addStyle != null) s6 = addStyle; + if (pixels != 0) s7 = Integer.toString(pixels); + if (points != 0) s8 = Integer.toString(points); + if (horizontalResolution != 0) s9 = Integer.toString(horizontalResolution); + if (verticalResolution != 0) s10 = Integer.toString(verticalResolution); + if (spacing != null) s11 = spacing; + if (averageWidth != 0) s12 = Integer.toString(averageWidth); + if (characterSetRegistry != null) s13 = characterSetRegistry; + if (characterSetName != null) s14 = characterSetName; + + return "-" + s1+ "-" + s2 + "-" + s3 + "-" + s4 + "-" + s5 + "-" + s6 + "-" + s7 + "-" + s8 + "-" + + s9 + "-" + s10 + "-" + s11 + "-" + s12 + "-" + s13 + "-" + s14; +} +/** + * Returns an integer hash code for the receiver. Any two + * objects that return <code>true</code> when passed to + * <code>equals</code> must return the same value for this + * method. + * + * @return the receiver's hash + * + * @see #equals + */ +public int hashCode () { + return getXlfd().hashCode(); +} +public static FontData motif_new(String xlfd) { + FontData fontData = new FontData(); + fontData.setXlfd(xlfd); + return fontData; +} +/** + * Sets the height of the receiver. The parameter is + * specified in terms of points, where a point is one + * seventy-second of an inch. + * + * @param height the height of the <code>FontData</code> + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the height is negative</li> + * </ul> + * + * @see #getHeight + */ +public void setHeight(int height) { + if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + points = height * 10; +} +/*public*/ void setHeight(float height) { + if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + points = (int)(height * 10); +} +/** + * Sets the name of the receiver. + * <p> + * Some platforms support font foundries. On these platforms, the name + * of the font specified in setName() may have one of the following forms: + * <ol> + * <li>a face name (for example, "courier")</li> + * <li>a foundry followed by a dash ("-") followed by a face name (for example, "adobe-courier")</li> + * </ol> + * In either case, the name returned from getName() will include the + * foundry. + * </p> + * <p> + * On platforms that do not support font foundries, only the face name + * (for example, "courier") is used in <code>setName()</code> and + * <code>getName()</code>. + * </p> + * + * @param name the name of the font data (must not be null) + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - when the font name is null</li> + * </ul> + * + * @see #getName + */ +public void setName(String name) { + if (name == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int dash = name.indexOf('-'); + if (dash != -1) { + foundry = name.substring(0, dash); + fontFamily = name.substring(dash + 1); + } else { + fontFamily = name; + } +} +/** + * Sets the locale of the receiver. + * <p> + * The locale determines which platform character set this + * font is going to use. Widgets and graphics operations that + * use this font will convert UNICODE strings to the platform + * character set of the specified locale. + * </p> + * <p> + * On platforms where there are multiple character sets for a + * given language/country locale, the variant portion of the + * locale will determine the character set. + * </p> + * + * @param locale the <code>String</code> representing a Locale object + * @see java.util.Locale#toString + */ +public void setLocale(String locale) { + lang = country = variant = null; + if (locale != null) { + char sep = '_'; + int length = locale.length(); + int firstSep, secondSep; + + firstSep = locale.indexOf(sep); + if (firstSep == -1) { + firstSep = secondSep = length; + } else { + secondSep = locale.indexOf(sep, firstSep + 1); + if (secondSep == -1) secondSep = length; + } + if (firstSep > 0) lang = locale.substring(0, firstSep); + if (secondSep > firstSep + 1) country = locale.substring(firstSep + 1, secondSep); + if (length > secondSep + 1) variant = locale.substring(secondSep + 1); + } +} +/** + * Sets the style of the receiver to the argument which must + * be a bitwise OR of one or more of the <code>SWT</code> + * constants NORMAL, BOLD and ITALIC. All other style bits are + * ignored. + * + * @param style the new style for this <code>FontData</code> + * + * @see #getStyle + */ +public void setStyle(int style) { + weight = (style & SWT.BOLD) != 0 ? "bold" : "medium"; + slant = (style & SWT.ITALIC) != 0 ? "i" : "r"; + averageWidth = 0; +} +void setXlfd(String xlfd) { + int start, stop; + start = 1; + stop = xlfd.indexOf ("-", start); + foundry = xlfd.substring(start, stop); + if (foundry.equals("*")) foundry = null; + start = stop + 1; + stop = xlfd.indexOf ("-", start); + fontFamily = xlfd.substring(start, stop); + if (fontFamily.equals("*")) fontFamily = null; + start = stop + 1; + stop = xlfd.indexOf ("-", start); + weight = xlfd.substring(start, stop); + if (weight.equals("*")) weight = null; + start = stop + 1; + stop = xlfd.indexOf ("-", start); + slant = xlfd.substring(start, stop); + if (slant.equals("*")) slant = null; + start = stop + 1; + stop = xlfd.indexOf ("-", start); + setWidth = xlfd.substring(start, stop); + if (setWidth.equals("*")) setWidth = null; + start = stop + 1; + stop = xlfd.indexOf ("-", start); + addStyle = xlfd.substring(start, stop); + if (addStyle.equals("*")) addStyle = null; + start = stop + 1; + stop = xlfd.indexOf ("-", start); + String s = xlfd.substring(start, stop); + if (!s.equals("") && !s.equals("*")) + pixels = Integer.parseInt(s); + start = stop + 1; + stop = xlfd.indexOf ("-", start); + s = xlfd.substring(start, stop); + if (!s.equals("") && !s.equals("*")) + points = Integer.parseInt(s); + start = stop + 1; + stop = xlfd.indexOf ("-", start); + s = xlfd.substring(start, stop); + if (!s.equals("") && !s.equals("*")) + horizontalResolution = Integer.parseInt(s); + start = stop + 1; + stop = xlfd.indexOf ("-", start); + s = xlfd.substring(start, stop); + if (!s.equals("") && !s.equals("*")) + verticalResolution = Integer.parseInt(s); + start = stop + 1; + stop = xlfd.indexOf ("-", start); + spacing = xlfd.substring(start, stop); + start = stop + 1; + stop = xlfd.indexOf ("-", start); + s = xlfd.substring(start, stop); + if (!s.equals("") && !s.equals("*")) { + if (s.startsWith ("~")) { + s = "-" + s.substring(1); + } + averageWidth = Integer.parseInt(s); + } + start = stop + 1; + stop = xlfd.indexOf ("-", start); + characterSetRegistry = xlfd.substring(start, stop); + if (characterSetRegistry.equals("*")) characterSetRegistry = null; + start = stop + 1; + stop = xlfd.indexOf ("-", start); + characterSetName = xlfd.substring(start); + if (characterSetName.equals("*")) characterSetName = null; +} +/** + * Returns a string representation of the receiver which is suitable + * for constructing an equivalent instance using the + * <code>FontData(String)</code> constructor. + * + * @return a string representation of the FontData + * + * @see FontData + */ +public String toString() { + return "1|" + fontFamily + "|" + getHeightF() + "|" + getStyle() + "|" + + "MOTIF|1|" + getXlfd(); +} +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/FontMetrics.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/FontMetrics.java new file mode 100755 index 0000000000..83b12e5bcb --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/FontMetrics.java @@ -0,0 +1,123 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +/** + * Instances of this class provide measurement information + * about fonts including ascent, descent, height, leading + * space between rows, and average character width. + * <code>FontMetrics</code> are obtained from <code>GC</code>s + * using the <code>getFontMetrics()</code> method. + * + * @see GC#getFontMetrics + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + */ +public final class FontMetrics { + int ascent, descent, averageCharWidth, leading, height; +FontMetrics() { +} +/** + * Compares the argument to the receiver, and returns true + * if they represent the <em>same</em> object using a class + * specific comparison. + * + * @param object the object to compare with this object + * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise + * + * @see #hashCode + */ +public boolean equals (Object object) { + if (object == this) return true; + if (!(object instanceof FontMetrics)) return false; + FontMetrics metrics = (FontMetrics)object; + return ascent == metrics.ascent && descent == metrics.descent && + averageCharWidth == metrics.averageCharWidth && leading == metrics.leading && + height == metrics.height; +} +/** + * Returns the ascent of the font described by the receiver. A + * font's <em>ascent</em> is the distance from the baseline to the + * top of actual characters, not including any of the leading area, + * measured in pixels. + * + * @return the ascent of the font + */ +public int getAscent() { + return ascent; +} +/** + * Returns the average character width, measured in pixels, + * of the font described by the receiver. + * + * @return the average character width of the font + */ +public int getAverageCharWidth() { + return averageCharWidth; +} +/** + * Returns the descent of the font described by the receiver. A + * font's <em>descent</em> is the distance from the baseline to the + * bottom of actual characters, not including any of the leading area, + * measured in pixels. + * + * @return the descent of the font + */ +public int getDescent() { + return descent; +} +/** + * Returns the height of the font described by the receiver, + * measured in pixels. A font's <em>height</em> is the sum of + * its ascent, descent and leading area. + * + * @return the height of the font + * + * @see #getAscent + * @see #getDescent + * @see #getLeading + */ +public int getHeight() { + return height; +} +/** + * Returns the leading area of the font described by the + * receiver. A font's <em>leading area</em> is the space + * above its ascent which may include accents or other marks. + * + * @return the leading space of the font + */ +public int getLeading() { + return leading; +} +/** + * Returns an integer hash code for the receiver. Any two + * objects that return <code>true</code> when passed to + * <code>equals</code> must return the same value for this + * method. + * + * @return the receiver's hash + * + * @see #equals + */ +public int hashCode() { + return ascent ^ descent ^ averageCharWidth ^ leading ^ height; +} +public static FontMetrics motif_new(int ascent, int descent, int averageCharWidth, int leading, int height) { + FontMetrics fontMetrics = new FontMetrics(); + fontMetrics.ascent = ascent; + fontMetrics.descent = descent; + fontMetrics.averageCharWidth = averageCharWidth; + fontMetrics.leading = leading; + fontMetrics.height = height; + return fontMetrics; +} +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/GC.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/GC.java new file mode 100755 index 0000000000..e5e3c8ca44 --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/GC.java @@ -0,0 +1,4568 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +import org.eclipse.swt.internal.*; +import org.eclipse.swt.internal.cairo.*; +import org.eclipse.swt.internal.motif.*; +import org.eclipse.swt.*; + +/** + * Class <code>GC</code> is where all of the drawing capabilities that are + * supported by SWT are located. Instances are used to draw on either an + * <code>Image</code>, a <code>Control</code>, or directly on a <code>Display</code>. + * <dl> + * <dt><b>Styles:</b></dt> + * <dd>LEFT_TO_RIGHT, RIGHT_TO_LEFT</dd> + * </dl> + * + * <p> + * The SWT drawing coordinate system is the two-dimensional space with the origin + * (0,0) at the top left corner of the drawing area and with (x,y) values increasing + * to the right and downward respectively. + * </p> + * + * <p> + * The result of drawing on an image that was created with an indexed + * palette using a color that is not in the palette is platform specific. + * Some platforms will match to the nearest color while other will draw + * the color itself. This happens because the allocated image might use + * a direct palette on platforms that do not support indexed palette. + * </p> + * + * <p> + * Application code must explicitly invoke the <code>GC.dispose()</code> + * method to release the operating system resources managed by each instance + * when those instances are no longer required. This is <em>particularly</em> + * important on Windows95 and Windows98 where the operating system has a limited + * number of device contexts available. + * </p> + * + * <p> + * Note: Only one of LEFT_TO_RIGHT and RIGHT_TO_LEFT may be specified. + * </p> + * + * @see org.eclipse.swt.events.PaintEvent + * @see <a href="http://www.eclipse.org/swt/snippets/#gc">GC snippets</a> + * @see <a href="http://www.eclipse.org/swt/examples.php">SWT Examples: GraphicsExample, PaintExample</a> + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + */ +public final class GC extends Resource { + /** + * the handle to the OS device context + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int handle; + + Drawable drawable; + GCData data; + + final static int FOREGROUND = 1 << 0; + final static int BACKGROUND = 1 << 1; + final static int FONT = 1 << 2; + final static int LINE_STYLE = 1 << 3; + final static int LINE_CAP = 1 << 4; + final static int LINE_JOIN = 1 << 5; + final static int LINE_WIDTH = 1 << 6; + final static int LINE_MITERLIMIT = 1 << 7; + final static int BACKGROUND_BG = 1 << 8; + final static int FOREGROUND_RGB = 1 << 9; + final static int BACKGROUND_RGB = 1 << 10; + final static int DRAW_OFFSET = 1 << 11; + final static int DRAW = FOREGROUND | LINE_WIDTH | LINE_STYLE | LINE_CAP | LINE_JOIN | LINE_MITERLIMIT | DRAW_OFFSET; + final static int FILL = BACKGROUND; + + static final float[] LINE_DOT = new float[]{1, 1}; + static final float[] LINE_DASH = new float[]{3, 1}; + static final float[] LINE_DASHDOT = new float[]{3, 1, 1, 1}; + static final float[] LINE_DASHDOTDOT = new float[]{3, 1, 1, 1, 1, 1}; + static final float[] LINE_DOT_ZERO = new float[]{3, 3}; + static final float[] LINE_DASH_ZERO = new float[]{18, 6}; + static final float[] LINE_DASHDOT_ZERO = new float[]{9, 6, 3, 6}; + static final float[] LINE_DASHDOTDOT_ZERO = new float[]{9, 3, 3, 3, 3, 3}; + +GC() { +} +/** + * Constructs a new instance of this class which has been + * configured to draw on the specified drawable. Sets the + * foreground color, background color and font in the GC + * to match those in the drawable. + * <p> + * You must dispose the graphics context when it is no longer required. + * </p> + * @param drawable the drawable to draw on + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the drawable is null</li> + * <li>ERROR_NULL_ARGUMENT - if there is no current device</li> + * <li>ERROR_INVALID_ARGUMENT + * - if the drawable is an image that is not a bitmap or an icon + * - if the drawable is an image or printer that is already selected + * into another graphics context</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for GC creation</li> + * <li>ERROR_THREAD_INVALID_ACCESS if not called from the thread that created the drawable</li> + * </ul> + */ +public GC(Drawable drawable) { + this(drawable, 0); +} +/** + * Constructs a new instance of this class which has been + * configured to draw on the specified drawable. Sets the + * foreground color, background color and font in the GC + * to match those in the drawable. + * <p> + * You must dispose the graphics context when it is no longer required. + * </p> + * + * @param drawable the drawable to draw on + * @param style the style of GC to construct + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the drawable is null</li> + * <li>ERROR_NULL_ARGUMENT - if there is no current device</li> + * <li>ERROR_INVALID_ARGUMENT + * - if the drawable is an image that is not a bitmap or an icon + * - if the drawable is an image or printer that is already selected + * into another graphics context</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for GC creation</li> + * <li>ERROR_THREAD_INVALID_ACCESS if not called from the thread that created the drawable</li> + * </ul> + * + * @since 2.1.2 + */ +public GC(Drawable drawable, int style) { + if (drawable == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + GCData data = new GCData(); + data.style = checkStyle(style); + int xGC = drawable.internal_new_GC(data); + Device device = data.device; + if (device == null) device = Device.getDevice(); + if (device == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = data.device = device; + init(drawable, data, xGC); + init(); +} +static void addCairoString(int cairo, String string, float x, float y, Font font) { + byte[] buffer = Converter.wcsToMbcs(null, string, true); + GC.setCairoFont(cairo, font); + cairo_font_extents_t extents = new cairo_font_extents_t(); + Cairo.cairo_font_extents(cairo, extents); + double baseline = y + extents.ascent; + Cairo.cairo_move_to(cairo, x, baseline); + Cairo.cairo_text_path(cairo, buffer); +} +static int checkStyle (int style) { + if ((style & SWT.LEFT_TO_RIGHT) != 0) style &= ~SWT.RIGHT_TO_LEFT; + return style & (SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT); +} + +void checkGC (int mask) { + int state = data.state; + if ((state & mask) == mask) return; + state = (state ^ mask) & mask; + data.state |= mask; + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + if ((state & (BACKGROUND | FOREGROUND)) != 0) { + XColor color; + Pattern pattern; + if ((state & FOREGROUND) != 0) { + color = data.foreground; + if ((data.state & FOREGROUND_RGB) == 0) { + OS.XQueryColor (data.display, data.colormap, color); + data.state |= FOREGROUND_RGB; + } + pattern = data.foregroundPattern; + data.state &= ~BACKGROUND; + } else { + color = data.background; + if ((data.state & BACKGROUND_RGB) == 0) { + OS.XQueryColor (data.display, data.colormap, color); + data.state |= BACKGROUND_RGB; + } + pattern = data.backgroundPattern; + data.state &= ~FOREGROUND; + } + if (pattern != null) { + Cairo.cairo_set_source(cairo, pattern.handle); + } else { + Cairo.cairo_set_source_rgba(cairo, (color.red & 0xFFFF) / (float)0xFFFF, (color.green & 0xFFFF) / (float)0xFFFF, (color.blue & 0xFFFF) / (float)0xFFFF, data.alpha / (float)0xFF); + } + } + if ((state & FONT) != 0) { + setCairoFont(cairo, data.font); + } + if ((state & LINE_CAP) != 0) { + int cap_style = 0; + switch (data.lineCap) { + case SWT.CAP_ROUND: cap_style = Cairo.CAIRO_LINE_CAP_ROUND; break; + case SWT.CAP_FLAT: cap_style = Cairo.CAIRO_LINE_CAP_BUTT; break; + case SWT.CAP_SQUARE: cap_style = Cairo.CAIRO_LINE_CAP_SQUARE; break; + } + Cairo.cairo_set_line_cap(cairo, cap_style); + } + if ((state & LINE_JOIN) != 0) { + int join_style = 0; + switch (data.lineJoin) { + case SWT.JOIN_MITER: join_style = Cairo.CAIRO_LINE_JOIN_MITER; break; + case SWT.JOIN_ROUND: join_style = Cairo.CAIRO_LINE_JOIN_ROUND; break; + case SWT.JOIN_BEVEL: join_style = Cairo.CAIRO_LINE_JOIN_BEVEL; break; + } + Cairo.cairo_set_line_join(cairo, join_style); + } + if ((state & LINE_WIDTH) != 0) { + Cairo.cairo_set_line_width(cairo, data.lineWidth == 0 ? 1 : data.lineWidth); + switch (data.lineStyle) { + case SWT.LINE_DOT: + case SWT.LINE_DASH: + case SWT.LINE_DASHDOT: + case SWT.LINE_DASHDOTDOT: + state |= LINE_STYLE; + } + } + if ((state & LINE_STYLE) != 0) { + float dashesOffset = 0; + float[] dashes = null; + float width = data.lineWidth; + switch (data.lineStyle) { + case SWT.LINE_SOLID: break; + case SWT.LINE_DASH: dashes = width != 0 ? LINE_DASH : LINE_DASH_ZERO; break; + case SWT.LINE_DOT: dashes = width != 0 ? LINE_DOT : LINE_DOT_ZERO; break; + case SWT.LINE_DASHDOT: dashes = width != 0 ? LINE_DASHDOT : LINE_DASHDOT_ZERO; break; + case SWT.LINE_DASHDOTDOT: dashes = width != 0 ? LINE_DASHDOTDOT : LINE_DASHDOTDOT_ZERO; break; + case SWT.LINE_CUSTOM: dashes = data.lineDashes; break; + } + if (dashes != null) { + dashesOffset = data.lineDashesOffset; + double[] cairoDashes = new double[dashes.length]; + for (int i = 0; i < cairoDashes.length; i++) { + cairoDashes[i] = width == 0 || data.lineStyle == SWT.LINE_CUSTOM ? dashes[i] : dashes[i] * width; + } + Cairo.cairo_set_dash(cairo, cairoDashes, cairoDashes.length, dashesOffset); + } else { + Cairo.cairo_set_dash(cairo, null, 0, 0); + } + } + if ((state & LINE_MITERLIMIT) != 0) { + Cairo.cairo_set_miter_limit(cairo, data.lineMiterLimit); + } + if ((state & DRAW_OFFSET) != 0) { + data.cairoXoffset = data.cairoYoffset = 0; + double[] matrix = new double[6]; + Cairo.cairo_get_matrix(cairo, matrix); + double[] dx = new double[]{1}; + double[] dy = new double[]{1}; + Cairo.cairo_user_to_device_distance(cairo, dx, dy); + double scaling = dx[0]; + if (scaling < 0) scaling = -scaling; + double strokeWidth = data.lineWidth * scaling; + if (strokeWidth == 0 || ((int)strokeWidth % 2) == 1) { + data.cairoXoffset = 0.5 / scaling; + } + scaling = dy[0]; + if (scaling < 0) scaling = -scaling; + strokeWidth = data.lineWidth * scaling; + if (strokeWidth == 0 || ((int)strokeWidth % 2) == 1) { + data.cairoYoffset = 0.5 / scaling; + } + } + return; + } + int xDisplay = data.display; + if ((state & (BACKGROUND | FOREGROUND)) != 0) { + XColor foreground; + if ((state & FOREGROUND) != 0) { + foreground = data.foreground; + data.state &= ~BACKGROUND; + } else { + foreground = data.background; + data.state &= ~FOREGROUND; + } + OS.XSetForeground (xDisplay, handle, foreground.pixel); + } + if ((state & BACKGROUND_BG) != 0) { + XColor background = data.background; + OS.XSetBackground(xDisplay, handle, background.pixel); + } + if ((state & (LINE_CAP | LINE_JOIN | LINE_STYLE | LINE_WIDTH)) != 0) { + int cap_style = 0; + int join_style = 0; + int width = (int)data.lineWidth; + int line_style = 0; + float[] dashes = null; + switch (data.lineCap) { + case SWT.CAP_ROUND: cap_style = OS.CapRound; break; + case SWT.CAP_FLAT: cap_style = OS.CapButt; break; + case SWT.CAP_SQUARE: cap_style = OS.CapProjecting; break; + } + switch (data.lineJoin) { + case SWT.JOIN_ROUND: join_style = OS.JoinRound; break; + case SWT.JOIN_MITER: join_style = OS.JoinMiter; break; + case SWT.JOIN_BEVEL: join_style = OS.JoinBevel; break; + } + switch (data.lineStyle) { + case SWT.LINE_SOLID: break; + case SWT.LINE_DASH: dashes = width != 0 ? LINE_DASH : LINE_DASH_ZERO; break; + case SWT.LINE_DOT: dashes = width != 0 ? LINE_DOT : LINE_DOT_ZERO; break; + case SWT.LINE_DASHDOT: dashes = width != 0 ? LINE_DASHDOT : LINE_DASHDOT_ZERO; break; + case SWT.LINE_DASHDOTDOT: dashes = width != 0 ? LINE_DASHDOTDOT : LINE_DASHDOTDOT_ZERO; break; + case SWT.LINE_CUSTOM: dashes = data.lineDashes; break; + } + if (dashes != null) { + if ((state & LINE_STYLE) != 0) { + byte[] dash_list = new byte[dashes.length]; + for (int i = 0; i < dash_list.length; i++) { + dash_list[i] = (byte)(width == 0 || data.lineStyle == SWT.LINE_CUSTOM ? dashes[i] : dashes[i] * width); + } + OS.XSetDashes(xDisplay, handle, 0, dash_list, dash_list.length); + } + line_style = OS.LineOnOffDash; + } else { + line_style = OS.LineSolid; + } + OS.XSetLineAttributes(xDisplay, handle, width, line_style, cap_style, join_style); + } +} +int convertRgn(int rgn, double[] matrix) { + int /*long*/ newRgn = OS.XCreateRegion(); + //TODO - get rectangles from region instead of clip box + XRectangle rect = new XRectangle(); + OS.XClipBox(rgn, rect); + short[] pointArray = new short[8]; + double[] x = new double[1], y = new double[1]; + x[0] = rect.x; + y[0] = rect.y; + Cairo.cairo_matrix_transform_point(matrix, x, y); + pointArray[0] = (short)x[0]; + pointArray[1] = (short)y[0]; + x[0] = rect.x + rect.width; + y[0] = rect.y; + Cairo.cairo_matrix_transform_point(matrix, x, y); + pointArray[2] = (short)Math.round(x[0]); + pointArray[3] = (short)y[0]; + x[0] = rect.x + rect.width; + y[0] = rect.y + rect.height; + Cairo.cairo_matrix_transform_point(matrix, x, y); + pointArray[4] = (short)Math.round(x[0]); + pointArray[5] = (short)Math.round(y[0]); + x[0] = rect.x; + y[0] = rect.y + rect.height; + Cairo.cairo_matrix_transform_point(matrix, x, y); + pointArray[6] = (short)x[0]; + pointArray[7] = (short)Math.round(y[0]); + int /*long*/ polyRgn = OS.XPolygonRegion(pointArray, pointArray.length / 2, OS.EvenOddRule); + OS.XUnionRegion(newRgn, polyRgn, newRgn); + OS.XDestroyRegion(polyRgn); + return newRgn; +} +/** + * Copies a rectangular area of the receiver at the source + * position onto the receiver at the destination position. + * + * @param srcX the x coordinate in the receiver of the area to be copied + * @param srcY the y coordinate in the receiver of the area to be copied + * @param width the width of the area to copy + * @param height the height of the area to copy + * @param destX the x coordinate in the receiver of the area to copy to + * @param destY the y coordinate in the receiver of the area to copy to + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void copyArea(int x, int y, int width, int height, int destX, int destY) { + copyArea(x, y, width, height, destX, destY, true); +} +/** + * Copies a rectangular area of the receiver at the source + * position onto the receiver at the destination position. + * + * @param srcX the x coordinate in the receiver of the area to be copied + * @param srcY the y coordinate in the receiver of the area to be copied + * @param width the width of the area to copy + * @param height the height of the area to copy + * @param destX the x coordinate in the receiver of the area to copy to + * @param destY the y coordinate in the receiver of the area to copy to + * @param paint if <code>true</code> paint events will be generated for old and obscured areas + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void copyArea(int x, int y, int width, int height, int destX, int destY, boolean paint) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width <= 0 || height <= 0) return; + int deltaX = destX - x, deltaY = destY - y; + if (deltaX == 0 && deltaY == 0) return; + int xDisplay = data.display; + int xDrawable = data.drawable; + if (data.backgroundImage != null && paint) { + OS.XClearArea (xDisplay, xDrawable, x, y, width, height, true); + OS.XClearArea (xDisplay, xDrawable, destX, destY, width, height, true); + return; + } + if (data.image == null && paint) OS.XSetGraphicsExposures (xDisplay, handle, true); + OS.XCopyArea(xDisplay, xDrawable, xDrawable, handle, x, y, width, height, destX, destY); + if (data.image == null && paint) { + OS.XSetGraphicsExposures (xDisplay, handle, false); + boolean disjoint = (destX + width < x) || (x + width < destX) || (destY + height < y) || (y + height < destY); + if (disjoint) { + OS.XClearArea (xDisplay, xDrawable, x, y, width, height, true); + } else { + if (deltaX != 0) { + int newX = destX - deltaX; + if (deltaX < 0) newX = destX + width; + OS.XClearArea (xDisplay, xDrawable, newX, y, Math.abs (deltaX), height, true); + } + if (deltaY != 0) { + int newY = destY - deltaY; + if (deltaY < 0) newY = destY + height; + OS.XClearArea (xDisplay, xDrawable, x, newY, width, Math.abs (deltaY), true); + } + } + } +} +/** + * Copies a rectangular area of the receiver at the specified + * position into the image, which must be of type <code>SWT.BITMAP</code>. + * + * @param image the image to copy into + * @param x the x coordinate in the receiver of the area to be copied + * @param y the y coordinate in the receiver of the area to be copied + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the image is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the image is not a bitmap or has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void copyArea(Image image, int x, int y) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (image == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (image.type != SWT.BITMAP || image.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + Rectangle rect = image.getBounds(); + int xDisplay = data.display; + int xGC = OS.XCreateGC(xDisplay, image.pixmap, 0, null); + if (xGC == 0) SWT.error(SWT.ERROR_NO_HANDLES); + OS.XSetSubwindowMode (xDisplay, xGC, OS.IncludeInferiors); + OS.XCopyArea(xDisplay, data.drawable, image.pixmap, xGC, x, y, rect.width, rect.height, 0, 0); + OS.XFreeGC(xDisplay, xGC); +} +void destroy() { + int /*long*/ cairo = data.cairo; + if (cairo != 0) Cairo.cairo_destroy(cairo); + data.cairo = 0; + + /* Free resources */ + int clipRgn = data.clipRgn; + if (clipRgn != 0) OS.XDestroyRegion(clipRgn); + Image image = data.image; + if (image != null) { + image.memGC = null; + if (image.transparentPixel != -1) image.createMask(); + } + + int renderTable = data.renderTable; + if (renderTable != 0) OS.XmRenderTableFree(renderTable); + int xmString = data.xmString; + if (xmString != 0) OS.XmStringFree (xmString); + int xmText = data.xmText; + if (xmText != 0) OS.XmStringFree (xmText); + int xmMnemonic = data.xmMnemonic; + if (xmMnemonic != 0) OS.XmStringFree (xmMnemonic); + + /* Dispose the GC */ + if (drawable != null) drawable.internal_dispose_GC(handle, data); + + data.display = data.drawable = data.colormap = + data.clipRgn = data.renderTable = data.xmString = data.xmText = + data.xmMnemonic = 0; + data.font = null; + drawable = null; + handle = 0; + data.image = null; + data = null; +} +/** + * Draws the outline of a circular or elliptical arc + * within the specified rectangular area. + * <p> + * The resulting arc begins at <code>startAngle</code> and extends + * for <code>arcAngle</code> degrees, using the current color. + * Angles are interpreted such that 0 degrees is at the 3 o'clock + * position. A positive value indicates a counter-clockwise rotation + * while a negative value indicates a clockwise rotation. + * </p><p> + * The center of the arc is the center of the rectangle whose origin + * is (<code>x</code>, <code>y</code>) and whose size is specified by the + * <code>width</code> and <code>height</code> arguments. + * </p><p> + * The resulting arc covers an area <code>width + 1</code> pixels wide + * by <code>height + 1</code> pixels tall. + * </p> + * + * @param x the x coordinate of the upper-left corner of the arc to be drawn + * @param y the y coordinate of the upper-left corner of the arc to be drawn + * @param width the width of the arc to be drawn + * @param height the height of the arc to be drawn + * @param startAngle the beginning angle + * @param arcAngle the angular extent of the arc, relative to the start angle + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + if (width == 0 || height == 0 || arcAngle == 0) return; + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + if (width == height) { + if (arcAngle >= 0) { + Cairo.cairo_arc_negative(cairo, x + xOffset + width / 2f, y + yOffset + height / 2f, width / 2f, -startAngle * (float)Compatibility.PI / 180, -(startAngle + arcAngle) * (float)Compatibility.PI / 180); + } else { + Cairo.cairo_arc(cairo, x + xOffset + width / 2f, y + yOffset + height / 2f, width / 2f, -startAngle * (float)Compatibility.PI / 180, -(startAngle + arcAngle) * (float)Compatibility.PI / 180); + } + } else { + Cairo.cairo_save(cairo); + Cairo.cairo_translate(cairo, x + xOffset + width / 2f, y + yOffset + height / 2f); + Cairo.cairo_scale(cairo, width / 2f, height / 2f); + if (arcAngle >= 0) { + Cairo.cairo_arc_negative(cairo, 0, 0, 1, -startAngle * (float)Compatibility.PI / 180, -(startAngle + arcAngle) * (float)Compatibility.PI / 180); + } else { + Cairo.cairo_arc(cairo, 0, 0, 1, -startAngle * (float)Compatibility.PI / 180, -(startAngle + arcAngle) * (float)Compatibility.PI / 180); + } + Cairo.cairo_restore(cairo); + } + Cairo.cairo_stroke(cairo); + return; + } + OS.XDrawArc(data.display, data.drawable, handle, x, y, width, height, startAngle * 64, arcAngle * 64); +} +/** + * Draws a rectangle, based on the specified arguments, which has + * the appearance of the platform's <em>focus rectangle</em> if the + * platform supports such a notion, and otherwise draws a simple + * rectangle in the receiver's foreground color. + * + * @param x the x coordinate of the rectangle + * @param y the y coordinate of the rectangle + * @param width the width of the rectangle + * @param height the height of the rectangle + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #drawRectangle(int, int, int, int) + */ +public void drawFocus (int x, int y, int width, int height) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + /* + * When the drawable is not a widget, the highlight + * color is zero. + */ + int xDisplay = data.display; + int xDrawable = data.drawable; + int highlightColor = 0; + int widget = OS.XtWindowToWidget (xDisplay, xDrawable); + if (widget != 0) { + int [] argList = {OS.XmNhighlightColor, 0}; + OS.XtGetValues (widget, argList, argList.length / 2); + highlightColor = argList [1]; + } + + /* Draw the focus rectangle */ + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + int cairo = data.cairo; + if (cairo != 0) { + int lineWidth = 1; + Cairo.cairo_save(cairo); + Cairo.cairo_set_line_width(cairo, lineWidth); + XColor color = new XColor(); + color.pixel = highlightColor; + OS.XQueryColor (data.display, data.colormap, color); + Cairo.cairo_set_source_rgba(cairo, (color.red & 0xFFFF) / (float)0xFFFF, (color.green & 0xFFFF) / (float)0xFFFF, (color.blue & 0xFFFF) / (float)0xFFFF, 1); + Cairo.cairo_rectangle(cairo, x + lineWidth / 2f, y + lineWidth / 2f, width, height); + Cairo.cairo_stroke(cairo); + Cairo.cairo_restore(cairo); + return; + } + OS.XSetForeground (xDisplay, handle, highlightColor); + OS.XDrawRectangle (xDisplay, xDrawable, handle, x, y, width - 1, height - 1); + data.state &= ~(BACKGROUND | FOREGROUND); +} +/** + * Draws the given image in the receiver at the specified + * coordinates. + * + * @param image the image to draw + * @param x the x coordinate of where to draw + * @param y the y coordinate of where to draw + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the image is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li> + * <li>ERROR_INVALID_ARGUMENT - if the given coordinates are outside the bounds of the image</li> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES - if no handles are available to perform the operation</li> + * </ul> + */ +public void drawImage(Image image, int x, int y) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (image == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (image.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + drawImage(image, 0, 0, -1, -1, x, y, -1, -1, true); +} + +/** + * Copies a rectangular area from the source image into a (potentially + * different sized) rectangular area in the receiver. If the source + * and destination areas are of differing sizes, then the source + * area will be stretched or shrunk to fit the destination area + * as it is copied. The copy fails if any part of the source rectangle + * lies outside the bounds of the source image, or if any of the width + * or height arguments are negative. + * + * @param image the source image + * @param srcX the x coordinate in the source image to copy from + * @param srcY the y coordinate in the source image to copy from + * @param srcWidth the width in pixels to copy from the source + * @param srcHeight the height in pixels to copy from the source + * @param destX the x coordinate in the destination to copy to + * @param destY the y coordinate in the destination to copy to + * @param destWidth the width in pixels of the destination rectangle + * @param destHeight the height in pixels of the destination rectangle + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the image is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li> + * <li>ERROR_INVALID_ARGUMENT - if any of the width or height arguments are negative. + * <li>ERROR_INVALID_ARGUMENT - if the source rectangle is not contained within the bounds of the source image</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES - if no handles are available to perform the operation</li> + * </ul> + */ +public void drawImage(Image image, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (srcWidth == 0 || srcHeight == 0 || destWidth == 0 || destHeight == 0) return; + if (srcX < 0 || srcY < 0 || srcWidth < 0 || srcHeight < 0 || destWidth < 0 || destHeight < 0) { + SWT.error (SWT.ERROR_INVALID_ARGUMENT); + } + if (image == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (image.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + drawImage(image, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, false); +} +void drawImage(Image srcImage, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, boolean simple) { + int[] width = new int[1]; + int[] height = new int[1]; + int[] depth = new int[1]; + int[] unused = new int[1]; + OS.XGetGeometry(data.display, srcImage.pixmap, unused, unused, unused, width, height, unused, depth); + int imgWidth = width[0]; + int imgHeight = height[0]; + if (simple) { + srcWidth = destWidth = imgWidth; + srcHeight = destHeight = imgHeight; + } else { + simple = srcX == 0 && srcY == 0 && + srcWidth == destWidth && destWidth == imgWidth && + srcHeight == destHeight && destHeight == imgHeight; + if (srcX + srcWidth > imgWidth || srcY + srcHeight > imgHeight) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + } + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + if (data.alpha != 0) { + srcImage.createSurface(); + Cairo.cairo_save(cairo); + Cairo.cairo_rectangle(cairo, destX , destY, destWidth, destHeight); + Cairo.cairo_clip(cairo); + Cairo.cairo_translate(cairo, destX - srcX, destY - srcY); + if (srcWidth != destWidth || srcHeight != destHeight) { + Cairo.cairo_scale(cairo, destWidth / (float)srcWidth, destHeight / (float)srcHeight); + } + int filter = Cairo.CAIRO_FILTER_GOOD; + switch (data.interpolation) { + case SWT.DEFAULT: filter = Cairo.CAIRO_FILTER_GOOD; break; + case SWT.NONE: filter = Cairo.CAIRO_FILTER_NEAREST; break; + case SWT.LOW: filter = Cairo.CAIRO_FILTER_FAST; break; + case SWT.HIGH: filter = Cairo.CAIRO_FILTER_BEST; break; + } + int /*long*/ pattern = Cairo.cairo_pattern_create_for_surface(srcImage.surface); + if (pattern == 0) SWT.error(SWT.ERROR_NO_HANDLES); + if (srcWidth != destWidth || srcHeight != destHeight) { + /* + * Bug in Cairo. When drawing the image streched with an interpolation + * alghorithm, the edges of the image are faded. This is not a bug, but + * it is not desired. To avoid the faded edges, it should be possible to + * use cairo_pattern_set_extend() to set the pattern extend to either + * CAIRO_EXTEND_REFLECT or CAIRO_EXTEND_PAD, but these are not implemented + * in some versions of cairo (1.2.x) and have bugs in others (in 1.4.2 it + * draws with black edges). The fix is to implement CAIRO_EXTEND_REFLECT + * by creating an image that is 3 times bigger than the original, drawing + * the original image in every quadrant (with an appropriate transform) and + * use this image as the pattern. + * + * NOTE: For some reaons, it is necessary to use CAIRO_EXTEND_PAD with + * the image that was created or the edges are still faded. + */ + if (Cairo.cairo_version () >= Cairo.CAIRO_VERSION_ENCODE(1, 4, 2)) { + int /*long*/ surface = Cairo.cairo_image_surface_create(Cairo.CAIRO_FORMAT_ARGB32, imgWidth * 3, imgHeight * 3); + int /*long*/ cr = Cairo.cairo_create(surface); + Cairo.cairo_set_source_surface(cr, srcImage.surface, imgWidth, imgHeight); + Cairo.cairo_paint(cr); + Cairo.cairo_scale(cr, -1, -1); + Cairo.cairo_set_source_surface(cr, srcImage.surface, -imgWidth, -imgHeight); + Cairo.cairo_paint(cr); + Cairo.cairo_set_source_surface(cr, srcImage.surface, -imgWidth * 3, -imgHeight); + Cairo.cairo_paint(cr); + Cairo.cairo_set_source_surface(cr, srcImage.surface, -imgWidth, -imgHeight * 3); + Cairo.cairo_paint(cr); + Cairo.cairo_set_source_surface(cr, srcImage.surface, -imgWidth * 3, -imgHeight * 3); + Cairo.cairo_paint(cr); + Cairo.cairo_scale(cr, 1, -1); + Cairo.cairo_set_source_surface(cr, srcImage.surface, -imgWidth, imgHeight); + Cairo.cairo_paint(cr); + Cairo.cairo_set_source_surface(cr, srcImage.surface, -imgWidth * 3, imgHeight); + Cairo.cairo_paint(cr); + Cairo.cairo_scale(cr, -1, -1); + Cairo.cairo_set_source_surface(cr, srcImage.surface, imgWidth, -imgHeight); + Cairo.cairo_paint(cr); + Cairo.cairo_set_source_surface(cr, srcImage.surface, imgWidth, -imgHeight * 3); + Cairo.cairo_paint(cr); + Cairo.cairo_destroy(cr); + int /*long*/ newPattern = Cairo.cairo_pattern_create_for_surface(surface); + Cairo.cairo_surface_destroy(surface); + if (newPattern == 0) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_pattern_destroy(pattern); + pattern = newPattern; + Cairo.cairo_pattern_set_extend(pattern, Cairo.CAIRO_EXTEND_PAD); + double[] matrix = new double[6]; + Cairo.cairo_matrix_init_translate(matrix, imgWidth, imgHeight); + Cairo.cairo_pattern_set_matrix(pattern, matrix); + } +// Cairo.cairo_pattern_set_extend(pattern, Cairo.CAIRO_EXTEND_REFLECT); + } + Cairo.cairo_pattern_set_filter(pattern, filter); + Cairo.cairo_set_source(cairo, pattern); + if (data.alpha != 0xFF) { + Cairo.cairo_paint_with_alpha(cairo, data.alpha / (float)0xFF); + } else { + Cairo.cairo_paint(cairo); + } + Cairo.cairo_restore(cairo); + Cairo.cairo_pattern_destroy(pattern); + } + return; + } + if (srcImage.alpha != -1 || srcImage.alphaData != null) { + drawImageAlpha(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, depth[0]); + } else if (srcImage.transparentPixel != -1 || srcImage.mask != 0) { + drawImageMask(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, depth[0]); + } else { + drawImage(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, depth[0]); + } +} +void drawImageAlpha(Image srcImage, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, boolean simple, int imgWidth, int imgHeight, int depth) { + /* Simple cases */ + if (srcImage.alpha == 0) return; + if (srcImage.alpha == 255) { + drawImage(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, depth); + return; + } + if (device.useXRender) { + drawImageXRender(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, srcImage.mask, OS.PictStandardA8); + return; + } + + /* Check the clipping */ + Rectangle rect = getClipping(); + rect = rect.intersection(new Rectangle(destX, destY, destWidth, destHeight)); + if (rect.isEmpty()) return; + + /* Optimization. Recalculate the src and dest rectangles so that + * only the clipping area is drawn. + */ + int sx1 = srcX + (((rect.x - destX) * srcWidth) / destWidth); + int sx2 = srcX + ((((rect.x + rect.width) - destX) * srcWidth) / destWidth); + int sy1 = srcY + (((rect.y - destY) * srcHeight) / destHeight); + int sy2 = srcY + ((((rect.y + rect.height) - destY) * srcHeight) / destHeight); + destX = rect.x; + destY = rect.y; + destWidth = rect.width; + destHeight = rect.height; + srcX = sx1; + srcY = sy1; + srcWidth = Math.max(1, sx2 - sx1); + srcHeight = Math.max(1, sy2 - sy1); + + int xDisplay = data.display; + int xDrawable = data.drawable; + int xDestImagePtr = 0, xSrcImagePtr = 0; + try { + /* Get the background pixels */ + xDestImagePtr = OS.XGetImage(xDisplay, xDrawable, destX, destY, destWidth, destHeight, OS.AllPlanes, OS.ZPixmap); + if (xDestImagePtr == 0) return; + XImage xDestImage = new XImage(); + OS.memmove(xDestImage, xDestImagePtr, XImage.sizeof); + byte[] destData = new byte[xDestImage.bytes_per_line * xDestImage.height]; + OS.memmove(destData, xDestImage.data, destData.length); + + /* Get the foreground pixels */ + xSrcImagePtr = OS.XGetImage(xDisplay, srcImage.pixmap, srcX, srcY, srcWidth, srcHeight, OS.AllPlanes, OS.ZPixmap); + if (xSrcImagePtr == 0) return; + XImage xSrcImage = new XImage(); + OS.memmove(xSrcImage, xSrcImagePtr, XImage.sizeof); + byte[] srcData = new byte[xSrcImage.bytes_per_line * xSrcImage.height]; + OS.memmove(srcData, xSrcImage.data, srcData.length); + + /* Compose the pixels */ + if (xSrcImage.depth <= 8) { + XColor[] xcolors = data.device.xcolors; + if (xcolors == null) SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + byte[] reds = new byte[xcolors.length]; + byte[] greens = new byte[xcolors.length]; + byte[] blues = new byte[xcolors.length]; + for (int i = 0; i < xcolors.length; i++) { + XColor color = xcolors[i]; + if (color == null) continue; + reds[i] = (byte)((color.red >> 8) & 0xFF); + greens[i] = (byte)((color.green >> 8) & 0xFF); + blues[i] = (byte)((color.blue >> 8) & 0xFF); + } + ImageData.blit(ImageData.BLIT_ALPHA, + srcData, xSrcImage.bits_per_pixel, xSrcImage.bytes_per_line, xSrcImage.byte_order, 0, 0, srcWidth, srcHeight, reds, greens, blues, + srcImage.alpha, srcImage.alphaData, imgWidth, srcX, srcY, + destData, xDestImage.bits_per_pixel, xDestImage.bytes_per_line, xDestImage.byte_order, 0, 0, destWidth, destHeight, reds, greens, blues, + false, false); + } else { + int srcRedMask = xSrcImage.red_mask; + int srcGreenMask = xSrcImage.green_mask; + int srcBlueMask = xSrcImage.blue_mask; + int destRedMask = xDestImage.red_mask; + int destGreenMask = xDestImage.green_mask; + int destBlueMask = xDestImage.blue_mask; + + /* + * Feature in X. XGetImage does not retrieve the RGB masks if the drawable + * is a Pixmap. The fix is to detect that the masks are not valid and use + * the default visual masks instead. + * + * NOTE: It is safe to use the default Visual masks, since we always + * create images with these masks. + */ + int visual = OS.XDefaultVisual(xDisplay, OS.XDefaultScreen(xDisplay)); + Visual xVisual = new Visual(); + OS.memmove(xVisual, visual, Visual.sizeof); + if (srcRedMask == 0 && srcGreenMask == 0 && srcBlueMask == 0) { + srcRedMask = xVisual.red_mask; + srcGreenMask = xVisual.green_mask; + srcBlueMask = xVisual.blue_mask; + } + if (destRedMask == 0 && destGreenMask == 0 && destBlueMask == 0) { + destRedMask = xVisual.red_mask; + destGreenMask = xVisual.green_mask; + destBlueMask = xVisual.blue_mask; + } + + ImageData.blit(ImageData.BLIT_ALPHA, + srcData, xSrcImage.bits_per_pixel, xSrcImage.bytes_per_line, xSrcImage.byte_order, 0, 0, srcWidth, srcHeight, srcRedMask, srcGreenMask, srcBlueMask, + srcImage.alpha, srcImage.alphaData, imgWidth, srcX, srcY, + destData, xDestImage.bits_per_pixel, xDestImage.bytes_per_line, xDestImage.byte_order, 0, 0, destWidth, destHeight, destRedMask, destGreenMask, destBlueMask, + false, false); + } + + /* Draw the composed pixels */ + OS.memmove(xDestImage.data, destData, destData.length); + OS.XPutImage(xDisplay, xDrawable, handle, xDestImagePtr, 0, 0, destX, destY, destWidth, destHeight); + } finally { + if (xSrcImagePtr != 0) OS.XDestroyImage(xSrcImagePtr); + if (xDestImagePtr != 0) OS.XDestroyImage(xDestImagePtr); + } +} +void drawImageMask(Image srcImage, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, boolean simple, int imgWidth, int imgHeight, int depth) { + int xDisplay = data.display; + int xDrawable = data.drawable; + /* Generate the mask if necessary. */ + if (srcImage.transparentPixel != -1) srcImage.createMask(); + + if (device.useXRender) { + drawImageXRender(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, srcImage.mask, OS.PictStandardA1); + } else { + int colorPixmap = 0, maskPixmap = 0; + int foreground = 0x00000000; + if (simple || (srcWidth == destWidth && srcHeight == destHeight)) { + colorPixmap = srcImage.pixmap; + maskPixmap = srcImage.mask; + } else { + /* Stretch the color and mask*/ + int xImagePtr = scalePixmap(xDisplay, srcImage.pixmap, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, false, false); + if (xImagePtr != 0) { + int xMaskPtr = scalePixmap(xDisplay, srcImage.mask, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, false, false); + if (xMaskPtr != 0) { + /* Create color scaled pixmaps */ + colorPixmap = OS.XCreatePixmap(xDisplay, xDrawable, destWidth, destHeight, depth); + int tempGC = OS.XCreateGC(xDisplay, colorPixmap, 0, null); + OS.XPutImage(xDisplay, colorPixmap, tempGC, xImagePtr, 0, 0, 0, 0, destWidth, destHeight); + OS.XFreeGC(xDisplay, tempGC); + + /* Create mask scaled pixmaps */ + maskPixmap = OS.XCreatePixmap(xDisplay, xDrawable, destWidth, destHeight, 1); + tempGC = OS.XCreateGC(xDisplay, maskPixmap, 0, null); + OS.XPutImage(xDisplay, maskPixmap, tempGC, xMaskPtr, 0, 0, 0, 0, destWidth, destHeight); + OS.XFreeGC(xDisplay, tempGC); + + OS.XDestroyImage(xMaskPtr); + } + OS.XDestroyImage(xImagePtr); + } + + /* Change the source rectangle */ + srcX = srcY = 0; + srcWidth = destWidth; + srcHeight = destHeight; + + foreground = ~foreground; + } + + /* Do the blts */ + if (colorPixmap != 0 && maskPixmap != 0) { + XGCValues values = new XGCValues(); + OS.XGetGCValues(xDisplay, handle, OS.GCForeground | OS. GCBackground | OS.GCFunction, values); + OS.XSetFunction(xDisplay, handle, OS.GXxor); + OS.XCopyArea(xDisplay, colorPixmap, xDrawable, handle, srcX, srcY, srcWidth, srcHeight, destX, destY); + OS.XSetForeground(xDisplay, handle, foreground); + OS.XSetBackground(xDisplay, handle, ~foreground); + OS.XSetFunction(xDisplay, handle, OS.GXand); + OS.XCopyPlane(xDisplay, maskPixmap, xDrawable, handle, srcX, srcY, srcWidth, srcHeight, destX, destY, 1); + OS.XSetFunction(xDisplay, handle, OS.GXxor); + OS.XCopyArea(xDisplay, colorPixmap, xDrawable, handle, srcX, srcY, srcWidth, srcHeight, destX, destY); + OS.XSetForeground(xDisplay, handle, values.foreground); + OS.XSetBackground(xDisplay, handle, values.background); + OS.XSetFunction(xDisplay, handle, values.function); + } + + /* Destroy scaled pixmaps */ + if (colorPixmap != 0 && srcImage.pixmap != colorPixmap) OS.XFreePixmap(xDisplay, colorPixmap); + if (maskPixmap != 0 && srcImage.mask != maskPixmap) OS.XFreePixmap(xDisplay, maskPixmap); + } + + /* Destroy the image mask if the there is a GC created on the image */ + if (srcImage.transparentPixel != -1 && srcImage.memGC != null) srcImage.destroyMask(); +} +void drawImageXRender(Image srcImage, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, boolean simple, int imgWidth, int imgHeight, int maskPixmap, int maskType) { + int drawable = data.drawable; + int xDisplay = data.display; + int maskPict = 0; + if (maskPixmap != 0) { + int attribCount = 0; + XRenderPictureAttributes attrib = null; + if (srcImage.alpha != -1) { + attribCount = 1; + attrib = new XRenderPictureAttributes(); + attrib.repeat = true; + } + maskPict = OS.XRenderCreatePicture(xDisplay, maskPixmap, OS.XRenderFindStandardFormat(xDisplay, maskType), attribCount, attrib); + if (maskPict == 0) SWT.error(SWT.ERROR_NO_HANDLES); + } + int format = OS.XRenderFindVisualFormat(xDisplay, OS.XDefaultVisual(xDisplay, OS.XDefaultScreen(xDisplay))); + int destPict = OS.XRenderCreatePicture(xDisplay, drawable, format, 0, null); + if (destPict == 0) SWT.error(SWT.ERROR_NO_HANDLES); + int srcPict = OS.XRenderCreatePicture(xDisplay, srcImage.pixmap, format, 0, null); + if (srcPict == 0) SWT.error(SWT.ERROR_NO_HANDLES); + if (srcWidth != destWidth || srcHeight != destHeight) { + int[] transform = new int[]{(int)(((float)srcWidth / destWidth) * 65536), 0, 0, 0, (int)(((float)srcHeight / destHeight) * 65536), 0, 0, 0, 65536}; + OS.XRenderSetPictureTransform(xDisplay, srcPict, transform); + if (maskPict != 0) OS.XRenderSetPictureTransform(xDisplay, maskPict, transform); + srcX *= destWidth / (float)srcWidth; + srcY *= destHeight / (float)srcHeight; + } + int clipping = data.clipRgn; + if (data.damageRgn != 0) { + if (clipping == 0) { + clipping = data.damageRgn; + } else { + clipping = OS.XCreateRegion (); + OS.XUnionRegion(clipping, data.clipRgn, clipping); + OS.XIntersectRegion(clipping, data.damageRgn, clipping); + } + } + if (clipping != 0) { + OS.XRenderSetPictureClipRegion(xDisplay, destPict, clipping); + if (clipping != data.clipRgn && clipping != data.damageRgn) { + OS.XDestroyRegion(clipping); + } + } + OS.XRenderComposite(xDisplay, maskPict != 0 ? OS.PictOpOver : OS.PictOpSrc, srcPict, maskPict, destPict, srcX, srcY, srcX, srcY, destX, destY, destWidth, destHeight); + OS.XRenderFreePicture(xDisplay, destPict); + OS.XRenderFreePicture(xDisplay, srcPict); + if (maskPict != 0) OS.XRenderFreePicture(xDisplay, maskPict); +} +void drawImage(Image srcImage, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, boolean simple, int imgWidth, int imgHeight, int depth) { + int xDisplay = data.display; + int xDrawable = data.drawable; + /* Simple case: no stretching */ + if ((srcWidth == destWidth) && (srcHeight == destHeight)) { + OS.XCopyArea(xDisplay, srcImage.pixmap, xDrawable, handle, srcX, srcY, srcWidth, srcHeight, destX, destY); + return; + } + if (device.useXRender) { + drawImageXRender(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, 0, -1); + return; + } + + /* Streching case */ + int xImagePtr = scalePixmap(xDisplay, srcImage.pixmap, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, false, false); + if (xImagePtr != 0) { + OS.XPutImage(xDisplay, xDrawable, handle, xImagePtr, 0, 0, destX, destY, destWidth, destHeight); + OS.XDestroyImage(xImagePtr); + } +} +static int scalePixmap(int display, int pixmap, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, boolean flipX, boolean flipY) { + int xSrcImagePtr = OS.XGetImage(display, pixmap, srcX, srcY, srcWidth, srcHeight, OS.AllPlanes, OS.ZPixmap); + if (xSrcImagePtr == 0) return 0; + XImage xSrcImage = new XImage(); + OS.memmove(xSrcImage, xSrcImagePtr, XImage.sizeof); + byte[] srcData = new byte[xSrcImage.bytes_per_line * xSrcImage.height]; + OS.memmove(srcData, xSrcImage.data, srcData.length); + OS.XDestroyImage(xSrcImagePtr); + int xImagePtr = 0; + int visual = OS.XDefaultVisual(display, OS.XDefaultScreen(display)); + switch (xSrcImage.bits_per_pixel) { + case 1: + case 4: + case 8: { + int format = xSrcImage.bits_per_pixel == 1 ? OS.XYBitmap : OS.ZPixmap; + xImagePtr = OS.XCreateImage(display, visual, xSrcImage.depth, format, 0, 0, destWidth, destHeight, xSrcImage.bitmap_pad, 0); + if (xImagePtr == 0) return 0; + XImage xImage = new XImage(); + OS.memmove(xImage, xImagePtr, XImage.sizeof); + int bufSize = xImage.bytes_per_line * xImage.height; + if (bufSize < 0) { + OS.XDestroyImage(xImagePtr); + return 0; + } + int bufPtr = OS.XtMalloc(bufSize); + xImage.data = bufPtr; + OS.memmove(xImagePtr, xImage, XImage.sizeof); + byte[] buf = new byte[bufSize]; + int srcOrder = xSrcImage.bits_per_pixel == 1 ? xSrcImage.bitmap_bit_order : xSrcImage.byte_order; + int destOrder = xImage.bits_per_pixel == 1 ? xImage.bitmap_bit_order : xImage.byte_order; + ImageData.blit(ImageData.BLIT_SRC, + srcData, xSrcImage.bits_per_pixel, xSrcImage.bytes_per_line, srcOrder, 0, 0, srcWidth, srcHeight, null, null, null, + ImageData.ALPHA_OPAQUE, null, 0, 0, 0, + buf, xImage.bits_per_pixel, xImage.bytes_per_line, destOrder, 0, 0, destWidth, destHeight, null, null, null, + flipX, flipY); + OS.memmove(bufPtr, buf, bufSize); + break; + } + case 16: + case 24: + case 32: { + xImagePtr = OS.XCreateImage(display, visual, xSrcImage.depth, OS.ZPixmap, 0, 0, destWidth, destHeight, xSrcImage.bitmap_pad, 0); + if (xImagePtr == 0) return 0; + XImage xImage = new XImage(); + OS.memmove(xImage, xImagePtr, XImage.sizeof); + int bufSize = xImage.bytes_per_line * xImage.height; + if (bufSize < 0) { + OS.XDestroyImage(xImagePtr); + return 0; + } + int bufPtr = OS.XtMalloc(bufSize); + xImage.data = bufPtr; + OS.memmove(xImagePtr, xImage, XImage.sizeof); + byte[] buf = new byte[bufSize]; + ImageData.blit(ImageData.BLIT_SRC, + srcData, xSrcImage.bits_per_pixel, xSrcImage.bytes_per_line, xSrcImage.byte_order, 0, 0, srcWidth, srcHeight, 0, 0, 0, + ImageData.ALPHA_OPAQUE, null, 0, 0, 0, + buf, xImage.bits_per_pixel, xImage.bytes_per_line, xImage.byte_order, 0, 0, destWidth, destHeight, 0, 0, 0, + flipX, flipY); + OS.memmove(bufPtr, buf, bufSize); + break; + } + } + return xImagePtr; +} +/** + * Draws a line, using the foreground color, between the points + * (<code>x1</code>, <code>y1</code>) and (<code>x2</code>, <code>y2</code>). + * + * @param x1 the first point's x coordinate + * @param y1 the first point's y coordinate + * @param x2 the second point's x coordinate + * @param y2 the second point's y coordinate + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawLine (int x1, int y1, int x2, int y2) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + Cairo.cairo_move_to(cairo, x1 + xOffset, y1 + yOffset); + Cairo.cairo_line_to(cairo, x2 + xOffset, y2 + yOffset); + Cairo.cairo_stroke(cairo); + return; + } + OS.XDrawLine (data.display, data.drawable, handle, x1, y1, x2, y2); +} +/** + * Draws the outline of an oval, using the foreground color, + * within the specified rectangular area. + * <p> + * The result is a circle or ellipse that fits within the + * rectangle specified by the <code>x</code>, <code>y</code>, + * <code>width</code>, and <code>height</code> arguments. + * </p><p> + * The oval covers an area that is <code>width + 1</code> + * pixels wide and <code>height + 1</code> pixels tall. + * </p> + * + * @param x the x coordinate of the upper left corner of the oval to be drawn + * @param y the y coordinate of the upper left corner of the oval to be drawn + * @param width the width of the oval to be drawn + * @param height the height of the oval to be drawn + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawOval(int x, int y, int width, int height) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + if (width == height) { + Cairo.cairo_arc_negative(cairo, x + xOffset + width / 2f, y + yOffset + height / 2f, width / 2f, 0, -2 * (float)Compatibility.PI); + } else { + Cairo.cairo_save(cairo); + Cairo.cairo_translate(cairo, x + xOffset + width / 2f, y + yOffset + height / 2f); + Cairo.cairo_scale(cairo, width / 2f, height / 2f); + Cairo.cairo_arc_negative(cairo, 0, 0, 1, 0, -2 * (float)Compatibility.PI); + Cairo.cairo_restore(cairo); + } + Cairo.cairo_stroke(cairo); + return; + } + OS.XDrawArc(data.display, data.drawable, handle, x, y, width, height, 0, 23040); +} +/** + * Draws the path described by the parameter. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * + * @param path the path to draw + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the parameter is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the parameter has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see Path + * + * @since 3.1 + */ +public void drawPath(Path path) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (path == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (path.handle == 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + initCairo(); + checkGC(DRAW); + int /*long*/ cairo = data.cairo; + Cairo.cairo_save(cairo); + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + Cairo.cairo_translate(cairo, xOffset, yOffset); + int /*long*/ copy = Cairo.cairo_copy_path(path.handle); + if (copy == 0) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_append_path(cairo, copy); + Cairo.cairo_path_destroy(copy); + Cairo.cairo_stroke(cairo); + Cairo.cairo_restore(cairo); +} +/** + * Draws a pixel, using the foreground color, at the specified + * point (<code>x</code>, <code>y</code>). + * <p> + * Note that the receiver's line attributes do not affect this + * operation. + * </p> + * + * @param x the point's x coordinate + * @param y the point's y coordinate + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.0 + */ +public void drawPoint (int x, int y) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + Cairo.cairo_rectangle(cairo, x, y, 1, 1); + Cairo.cairo_fill(cairo); + return; + } + OS.XDrawPoint(data.display, data.drawable, handle, x, y); +} +/** + * Draws the closed polygon which is defined by the specified array + * of integer coordinates, using the receiver's foreground color. The array + * contains alternating x and y values which are considered to represent + * points which are the vertices of the polygon. Lines are drawn between + * each consecutive pair, and between the first pair and last pair in the + * array. + * + * @param pointArray an array of alternating x and y values which are the vertices of the polygon + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT if pointArray is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawPolygon(int[] pointArray) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + checkGC(DRAW); + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + drawPolyline(cairo, pointArray, true); + Cairo.cairo_stroke(cairo); + return; + } + + // Motif does not have a native drawPolygon() call. Instead we ensure + // that the first and last points are the same and call drawPolyline(). + + int length = pointArray.length; + + // Need at least 3 points to define the polygon. If 2 or fewer points + // passed in, it is either a line or point so just call drawPolyline(). + // Check what happens when XOR is implemented. We may not be able to + // do this optimization. + + if (length < 4) { + drawPolyline(pointArray); + return; + } + + // If first and last points are the same, the polygon is already closed. + // Just call drawPolyline(). + // + // Check what happens when XOR is implemented. We may not be able to + // do this optimization. + + if (pointArray[0] == pointArray[length - 2] && (pointArray[1] == pointArray[length - 1])) { + drawPolyline(pointArray); + return; + } + + // Grow the list of points by one element and make sure the first and last + // points are the same. This will close the polygon and we can use the + // drawPolyline() call. + + int newPoints[] = new int[length + 2]; + for (int i = 0; i < length ; i++) + newPoints[i] = pointArray[i]; + newPoints[length] = pointArray[0]; + newPoints[length + 1] = pointArray[1]; + + drawPolyline(newPoints); +} +/** + * Draws the polyline which is defined by the specified array + * of integer coordinates, using the receiver's foreground color. The array + * contains alternating x and y values which are considered to represent + * points which are the corners of the polyline. Lines are drawn between + * each consecutive pair, but not between the first pair and last pair in + * the array. + * + * @param pointArray an array of alternating x and y values which are the corners of the polyline + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the point array is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawPolyline(int[] pointArray) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + checkGC(DRAW); + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + drawPolyline(cairo, pointArray, false); + Cairo.cairo_stroke(cairo); + return; + } + short[] xPoints = new short[pointArray.length]; + for (int i = 0; i<pointArray.length;i++) { + xPoints[i] = (short) pointArray[i]; + } + OS.XDrawLines(data.display,data.drawable,handle,xPoints,xPoints.length / 2, OS.CoordModeOrigin); +} +void drawPolyline(int /*long*/ cairo, int[] pointArray, boolean close) { + int count = pointArray.length / 2; + if (count == 0) return; + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + Cairo.cairo_move_to(cairo, pointArray[0] + xOffset, pointArray[1] + yOffset); + for (int i = 1, j=2; i < count; i++, j += 2) { + Cairo.cairo_line_to(cairo, pointArray[j] + xOffset, pointArray[j + 1] + yOffset); + } + if (close) Cairo.cairo_close_path(cairo); +} +/** + * Draws the outline of the rectangle specified by the arguments, + * using the receiver's foreground color. The left and right edges + * of the rectangle are at <code>x</code> and <code>x + width</code>. + * The top and bottom edges are at <code>y</code> and <code>y + height</code>. + * + * @param x the x coordinate of the rectangle to be drawn + * @param y the y coordinate of the rectangle to be drawn + * @param width the width of the rectangle to be drawn + * @param height the height of the rectangle to be drawn + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawRectangle (int x, int y, int width, int height) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + Cairo.cairo_rectangle(cairo, x + xOffset, y + yOffset, width, height); + Cairo.cairo_stroke(cairo); + return; + } + OS.XDrawRectangle (data.display, data.drawable, handle, x, y, width, height); +} +/** + * Draws the outline of the specified rectangle, using the receiver's + * foreground color. The left and right edges of the rectangle are at + * <code>rect.x</code> and <code>rect.x + rect.width</code>. The top + * and bottom edges are at <code>rect.y</code> and + * <code>rect.y + rect.height</code>. + * + * @param rect the rectangle to draw + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the rectangle is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawRectangle (Rectangle rect) { + if (rect == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + drawRectangle (rect.x, rect.y, rect.width, rect.height); +} +/** + * Draws the outline of the round-cornered rectangle specified by + * the arguments, using the receiver's foreground color. The left and + * right edges of the rectangle are at <code>x</code> and <code>x + width</code>. + * The top and bottom edges are at <code>y</code> and <code>y + height</code>. + * The <em>roundness</em> of the corners is specified by the + * <code>arcWidth</code> and <code>arcHeight</code> arguments, which + * are respectively the width and height of the ellipse used to draw + * the corners. + * + * @param x the x coordinate of the rectangle to be drawn + * @param y the y coordinate of the rectangle to be drawn + * @param width the width of the rectangle to be drawn + * @param height the height of the rectangle to be drawn + * @param arcWidth the width of the arc + * @param arcHeight the height of the arc + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawRoundRectangle (int x, int y, int width, int height, int arcWidth, int arcHeight) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + int nx = x; + int ny = y; + int nw = width; + int nh = height; + int naw = arcWidth; + int nah = arcHeight; + if (nw < 0) { + nw = 0 - nw; + nx = nx - nw; + } + if (nh < 0) { + nh = 0 - nh; + ny = ny - nh; + } + if (naw < 0) naw = 0 - naw; + if (nah < 0) nah = 0 - nah; + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + if (naw == 0 || nah == 0) { + Cairo.cairo_rectangle(cairo, x + xOffset, y + yOffset, width, height); + } else { + float naw2 = naw / 2f; + float nah2 = nah / 2f; + float fw = nw / naw2; + float fh = nh / nah2; + Cairo.cairo_save(cairo); + Cairo.cairo_translate(cairo, nx + xOffset, ny + yOffset); + Cairo.cairo_scale(cairo, naw2, nah2); + Cairo.cairo_move_to(cairo, fw - 1, 0); + Cairo.cairo_arc(cairo, fw - 1, 1, 1, Compatibility.PI + Compatibility.PI/2.0, Compatibility.PI*2.0); + Cairo.cairo_arc(cairo, fw - 1, fh - 1, 1, 0, Compatibility.PI/2.0); + Cairo.cairo_arc(cairo, 1, fh - 1, 1, Compatibility.PI/2, Compatibility.PI); + Cairo.cairo_arc(cairo, 1, 1, 1, Compatibility.PI, 270.0*Compatibility.PI/180.0); + Cairo.cairo_close_path(cairo); + Cairo.cairo_restore(cairo); + } + Cairo.cairo_stroke(cairo); + return; + } + int naw2 = naw / 2; + int nah2 = nah / 2; + int xDisplay = data.display; + int xDrawable = data.drawable; + if (nw > naw) { + if (nh > nah) { + OS.XDrawArc(xDisplay, xDrawable, handle, nx, ny, naw, nah, 5760, 5760); + OS.XDrawLine(xDisplay, xDrawable, handle, nx + naw2, ny, nx + nw - naw2, ny); + OS.XDrawArc(xDisplay, xDrawable, handle, nx + nw - naw, ny, naw, nah, 0, 5760); + OS.XDrawLine(xDisplay, xDrawable, handle, nx + nw, ny + nah2, nx + nw, ny + nh - nah2); + OS.XDrawArc(xDisplay, xDrawable, handle, nx + nw - naw, ny + nh - nah, naw, nah, 17280, 5760); + OS.XDrawLine(xDisplay,xDrawable,handle, nx + naw2, ny + nh, nx + nw - naw2, ny + nh); + OS.XDrawArc(xDisplay, xDrawable, handle, nx, ny + nh - nah, naw, nah, 11520, 5760); + OS.XDrawLine(xDisplay, xDrawable, handle, nx, ny + nah2, nx, ny + nh - nah2); + } else { + OS.XDrawArc(xDisplay, xDrawable, handle, nx, ny, naw, nh, 5760, 11520); + OS.XDrawLine(xDisplay, xDrawable, handle, nx + naw2, ny, nx + nw - naw2, ny); + OS.XDrawArc(xDisplay, xDrawable, handle, nx + nw - naw, ny, naw, nh, 17280, 11520); + OS.XDrawLine(xDisplay,xDrawable,handle, nx + naw2, ny + nh, nx + nw - naw2, ny + nh); + } + } else { + if (nh > nah) { + OS.XDrawArc(xDisplay, xDrawable, handle, nx, ny, nw, nah, 0, 11520); + OS.XDrawLine(xDisplay, xDrawable, handle, nx + nw, ny + nah2, nx + nw, ny + nh - nah2); + OS.XDrawArc(xDisplay, xDrawable, handle, nx, ny + nh - nah, nw, nah, 11520, 11520); + OS.XDrawLine(xDisplay,xDrawable,handle, nx, ny + nah2, nx, ny + nh - nah2); + } else { + OS.XDrawArc(xDisplay, xDrawable, handle, nx, ny, nw, nh, 0, 23040); + } + } +} +/** + * Draws the given string, using the receiver's current font and + * foreground color. No tab expansion or carriage return processing + * will be performed. The background of the rectangular area where + * the string is being drawn will be filled with the receiver's + * background color. + * + * @param string the string to be drawn + * @param x the x coordinate of the top left corner of the rectangular area where the string is to be drawn + * @param y the y coordinate of the top left corner of the rectangular area where the string is to be drawn + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the string is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawString (String string, int x, int y) { + drawString(string, x, y, false); +} +/** + * Draws the given string, using the receiver's current font and + * foreground color. No tab expansion or carriage return processing + * will be performed. If <code>isTransparent</code> is <code>true</code>, + * then the background of the rectangular area where the string is being + * drawn will not be modified, otherwise it will be filled with the + * receiver's background color. + * + * @param string the string to be drawn + * @param x the x coordinate of the top left corner of the rectangular area where the string is to be drawn + * @param y the y coordinate of the top left corner of the rectangular area where the string is to be drawn + * @param isTransparent if <code>true</code> the background will be transparent, otherwise it will be opaque + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the string is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawString (String string, int x, int y, boolean isTransparent) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (string == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (string.length() == 0) return; + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + //TODO - honor isTransparent + checkGC(FOREGROUND | FONT); + cairo_font_extents_t extents = new cairo_font_extents_t(); + Cairo.cairo_font_extents(cairo, extents); + double baseline = y + extents.ascent; + Cairo.cairo_move_to(cairo, x, baseline); + byte[] buffer = Converter.wcsToMbcs(null, string, true); + Cairo.cairo_show_text(cairo, buffer); + Cairo.cairo_new_path(cairo); + return; + } + setString(string); + checkGC(FOREGROUND | FONT | BACKGROUND_BG); + if (isTransparent) { + OS.XmStringDraw (data.display, data.drawable, data.font.handle, data.xmString, handle, x, y, 0x7FFFFFFF, OS.XmALIGNMENT_BEGINNING, 0, null); + } else { + OS.XmStringDrawImage (data.display, data.drawable, data.font.handle, data.xmString, handle, x, y, 0x7FFFFFFF, OS.XmALIGNMENT_BEGINNING, 0, null); + } +} +void createRenderTable() { + int fontList = data.font.handle; + /* Get the width of the tabs */ + byte[] buffer = {(byte)' ', 0}; + int xmString = OS.XmStringCreate(buffer, OS.XmFONTLIST_DEFAULT_TAG); + int tabWidth = OS.XmStringWidth(fontList, xmString) * 8; + OS.XmStringFree(xmString); + + /* Create the tab list */ + int [] tabs = new int[16]; + int tab = OS.XmTabCreate(tabWidth, (byte) OS.XmPIXELS, (byte) OS.XmRELATIVE, (byte) OS.XmALIGNMENT_BEGINNING, null); + for (int i = 0; i < tabs.length; i++) tabs[i] = tab; + int tabList = OS.XmTabListInsertTabs(0, tabs, tabs.length, 0); + + /* Create a font context to iterate over the elements in the font list */ + int[] fontBuffer = new int[1]; + if (!OS.XmFontListInitFontContext(fontBuffer, fontList)) { + SWT.error(SWT.ERROR_NO_HANDLES); + } + int context = fontBuffer[0], fontListEntry = 0; + int[] renditions = new int[4]; int renditionCount = 0; + + /* Create a rendition for each entry in the font list */ + while ((fontListEntry = OS.XmFontListNextEntry(context)) != 0) { + int fontPtr = OS.XmFontListEntryGetFont(fontListEntry, fontBuffer); + int fontType = (fontBuffer [0] == 0) ? OS.XmFONT_IS_FONT : OS.XmFONT_IS_FONTSET; + if (fontPtr == 0) SWT.error(SWT.ERROR_NO_HANDLES); + int [] argList = { + OS.XmNtabList, tabList, + OS.XmNfont, fontPtr, + OS.XmNfontType, fontType, + }; + int rendition = OS.XmRenditionCreate(data.device.shellHandle, OS.XmFONTLIST_DEFAULT_TAG, argList, argList.length / 2); + renditions[renditionCount++] = rendition; + if (renditionCount == renditions.length) { + int[] newArray = new int[renditions.length + 4]; + System.arraycopy(newArray, 0, renditions, 0, renditionCount); + renditions = newArray; + } + } + OS.XmFontListFreeFontContext(context); + OS.XmTabFree(tab); + OS.XmTabListFree(tabList); + + /* Create the render table from the renditions */ + data.renderTable = OS.XmRenderTableAddRenditions(0, renditions, renditionCount, OS.XmMERGE_REPLACE); + for (int i = 0; i < renditionCount; i++) OS.XmRenditionFree(renditions[i]); +} +/** + * Draws the given string, using the receiver's current font and + * foreground color. Tab expansion and carriage return processing + * are performed. The background of the rectangular area where + * the text is being drawn will be filled with the receiver's + * background color. + * + * @param string the string to be drawn + * @param x the x coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param y the y coordinate of the top left corner of the rectangular area where the text is to be drawn + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the string is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawText (String string, int x, int y) { + drawText(string, x, y, SWT.DRAW_DELIMITER | SWT.DRAW_TAB); +} +/** + * Draws the given string, using the receiver's current font and + * foreground color. Tab expansion and carriage return processing + * are performed. If <code>isTransparent</code> is <code>true</code>, + * then the background of the rectangular area where the text is being + * drawn will not be modified, otherwise it will be filled with the + * receiver's background color. + * + * @param string the string to be drawn + * @param x the x coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param y the y coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param isTransparent if <code>true</code> the background will be transparent, otherwise it will be opaque + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the string is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawText (String string, int x, int y, boolean isTransparent) { + int flags = SWT.DRAW_DELIMITER | SWT.DRAW_TAB; + if (isTransparent) flags |= SWT.DRAW_TRANSPARENT; + drawText(string, x, y, flags); +} +/** + * Draws the given string, using the receiver's current font and + * foreground color. Tab expansion, line delimiter and mnemonic + * processing are performed according to the specified flags. If + * <code>flags</code> includes <code>DRAW_TRANSPARENT</code>, + * then the background of the rectangular area where the text is being + * drawn will not be modified, otherwise it will be filled with the + * receiver's background color. + * <p> + * The parameter <code>flags</code> may be a combination of: + * <dl> + * <dt><b>DRAW_DELIMITER</b></dt> + * <dd>draw multiple lines</dd> + * <dt><b>DRAW_TAB</b></dt> + * <dd>expand tabs</dd> + * <dt><b>DRAW_MNEMONIC</b></dt> + * <dd>underline the mnemonic character</dd> + * <dt><b>DRAW_TRANSPARENT</b></dt> + * <dd>transparent background</dd> + * </dl> + * </p> + * + * @param string the string to be drawn + * @param x the x coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param y the y coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param flags the flags specifying how to process the text + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the string is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void drawText (String string, int x, int y, int flags) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (string == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (string.length() == 0) return; + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + //TODO - honor flags + checkGC(FOREGROUND | FONT); + cairo_font_extents_t extents = new cairo_font_extents_t(); + Cairo.cairo_font_extents(cairo, extents); + double baseline = y + extents.ascent; + Cairo.cairo_move_to(cairo, x, baseline); + byte[] buffer = Converter.wcsToMbcs(null, string, true); + Cairo.cairo_show_text(cairo, buffer); + Cairo.cairo_new_path(cairo); + return; + } + setText(string, flags); + checkGC(FOREGROUND | FONT | BACKGROUND_BG); + int xDisplay = data.display; + int xDrawable = data.drawable; + if (data.image != null) OS.XtRegisterDrawable (xDisplay, xDrawable, data.device.shellHandle); + int xmMnemonic = data.xmMnemonic; + if (xmMnemonic != 0) { + OS.XmStringDrawUnderline(xDisplay, xDrawable, data.renderTable, data.xmText, handle, x, y, 0x7FFFFFFF, OS.XmALIGNMENT_BEGINNING, 0, null, xmMnemonic); + } else { + if ((flags & SWT.DRAW_TRANSPARENT) != 0) { + OS.XmStringDraw(xDisplay, xDrawable, data.renderTable, data.xmText, handle, x, y, 0x7FFFFFFF, OS.XmALIGNMENT_BEGINNING, 0, null); + } else { + OS.XmStringDrawImage(xDisplay, xDrawable, data.renderTable, data.xmText, handle, x, y, 0x7FFFFFFF, OS.XmALIGNMENT_BEGINNING, 0, null); + } + } + if (data.image != null) OS.XtUnregisterDrawable (xDisplay, xDrawable); +} +/** + * Compares the argument to the receiver, and returns true + * if they represent the <em>same</em> object using a class + * specific comparison. + * + * @param object the object to compare with this object + * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise + * + * @see #hashCode + */ +public boolean equals (Object object) { + if (object == this) return true; + if (!(object instanceof GC)) return false; + return handle == ((GC)object).handle; +} +/** + * Fills the interior of a circular or elliptical arc within + * the specified rectangular area, with the receiver's background + * color. + * <p> + * The resulting arc begins at <code>startAngle</code> and extends + * for <code>arcAngle</code> degrees, using the current color. + * Angles are interpreted such that 0 degrees is at the 3 o'clock + * position. A positive value indicates a counter-clockwise rotation + * while a negative value indicates a clockwise rotation. + * </p><p> + * The center of the arc is the center of the rectangle whose origin + * is (<code>x</code>, <code>y</code>) and whose size is specified by the + * <code>width</code> and <code>height</code> arguments. + * </p><p> + * The resulting arc covers an area <code>width + 1</code> pixels wide + * by <code>height + 1</code> pixels tall. + * </p> + * + * @param x the x coordinate of the upper-left corner of the arc to be filled + * @param y the y coordinate of the upper-left corner of the arc to be filled + * @param width the width of the arc to be filled + * @param height the height of the arc to be filled + * @param startAngle the beginning angle + * @param arcAngle the angular extent of the arc, relative to the start angle + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #drawArc + */ +public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(FILL); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + if (width == 0 || height == 0 || arcAngle == 0) return; + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + if (width == height) { + if (arcAngle >= 0) { + Cairo.cairo_arc_negative(cairo, x + width / 2f, y + height / 2f, width / 2f, -startAngle * (float)Compatibility.PI / 180, -(startAngle + arcAngle) * (float)Compatibility.PI / 180); + } else { + Cairo.cairo_arc(cairo, x + width / 2f, y + height / 2f, width / 2f, -startAngle * (float)Compatibility.PI / 180, -(startAngle + arcAngle) * (float)Compatibility.PI / 180); + } + Cairo.cairo_line_to(cairo, x + width / 2f, y + height / 2f); + } else { + Cairo.cairo_save(cairo); + Cairo.cairo_translate(cairo, x + width / 2f, y + height / 2f); + Cairo.cairo_scale(cairo, width / 2f, height / 2f); + if (arcAngle >= 0) { + Cairo.cairo_arc_negative(cairo, 0, 0, 1, -startAngle * (float)Compatibility.PI / 180, -(startAngle + arcAngle) * (float)Compatibility.PI / 180); + } else { + Cairo.cairo_arc(cairo, 0, 0, 1, -startAngle * (float)Compatibility.PI / 180, -(startAngle + arcAngle) * (float)Compatibility.PI / 180); + } + Cairo.cairo_line_to(cairo, 0, 0); + Cairo.cairo_restore(cairo); + } + Cairo.cairo_fill(cairo); + return; + } + OS.XFillArc(data.display, data.drawable, handle, x, y, width, height, startAngle * 64, arcAngle * 64); +} + +/** + * Fills the interior of the specified rectangle with a gradient + * sweeping from left to right or top to bottom progressing + * from the receiver's foreground color to its background color. + * + * @param x the x coordinate of the rectangle to be filled + * @param y the y coordinate of the rectangle to be filled + * @param width the width of the rectangle to be filled, may be negative + * (inverts direction of gradient if horizontal) + * @param height the height of the rectangle to be filled, may be negative + * (inverts direction of gradient if vertical) + * @param vertical if true sweeps from top to bottom, else + * sweeps from left to right + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #drawRectangle(int, int, int, int) + */ +public void fillGradientRectangle(int x, int y, int width, int height, boolean vertical) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if ((width == 0) || (height == 0)) return; + + RGB backgroundRGB, foregroundRGB; + backgroundRGB = getBackground().getRGB(); + foregroundRGB = getForeground().getRGB(); + + RGB fromRGB, toRGB; + fromRGB = foregroundRGB; + toRGB = backgroundRGB; + boolean swapColors = false; + if (width < 0) { + x += width; width = -width; + if (! vertical) swapColors = true; + } + if (height < 0) { + y += height; height = -height; + if (vertical) swapColors = true; + } + if (swapColors) { + fromRGB = backgroundRGB; + toRGB = foregroundRGB; + } + if (fromRGB.equals(toRGB)) { + fillRectangle(x, y, width, height); + return; + } + /* X Window deals with a virtually limitless array of color formats + * but we only distinguish between paletted and direct modes + */ + int xDisplay = data.display; + int xScreenNum = OS.XDefaultScreen(xDisplay); + final int xScreen = OS.XDefaultScreenOfDisplay(xDisplay); + final int xVisual = OS.XDefaultVisual(xDisplay, xScreenNum); + Visual visual = new Visual(); + OS.memmove(visual, xVisual, Visual.sizeof); + final int depth = OS.XDefaultDepthOfScreen(xScreen); + final boolean directColor = (depth > 8); + + // This code is intentionally commented since elsewhere in SWT we + // assume that depth <= 8 means we are in a paletted mode though + // this is not always the case. + //final boolean directColor = (visual.c_class == OS.TrueColor) || (visual.c_class == OS.DirectColor); + + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + int /*long*/ pattern; + if (vertical) { + pattern = Cairo.cairo_pattern_create_linear (0.0, 0.0, 0.0, 1.0); + } else { + pattern = Cairo.cairo_pattern_create_linear (0.0, 0.0, 1.0, 0.0); + } + Cairo.cairo_pattern_add_color_stop_rgba (pattern, 0, fromRGB.red / 255f, fromRGB.green / 255f, fromRGB.blue / 255f, data.alpha / 255f); + Cairo.cairo_pattern_add_color_stop_rgba (pattern, 1, toRGB.red / 255f, toRGB.green / 255f, toRGB.blue / 255f, data.alpha / 255f); + Cairo.cairo_save(cairo); + Cairo.cairo_translate(cairo, x, y); + Cairo.cairo_scale(cairo, width, height); + Cairo.cairo_rectangle(cairo, 0, 0, 1, 1); + Cairo.cairo_set_source(cairo, pattern); + Cairo.cairo_fill(cairo); + Cairo.cairo_restore(cairo); + Cairo.cairo_pattern_destroy(pattern); + return; + } + final int redBits, greenBits, blueBits; + if (directColor) { + // RGB mapped display + redBits = getChannelWidth(visual.red_mask); + greenBits = getChannelWidth(visual.green_mask); + blueBits = getChannelWidth(visual.blue_mask); + } else { + // Index display + redBits = greenBits = blueBits = 0; + } + ImageData.fillGradientRectangle(this, data.device, + x, y, width, height, vertical, fromRGB, toRGB, + redBits, greenBits, blueBits); +} + +/** + * Computes the required channel width (depth) from a mask. + */ +static int getChannelWidth(int mask) { + int width = 0; + while (mask != 0) { + width += (mask & 1); + mask >>>= 1; + } + return width; +} + +/** + * Fills the interior of an oval, within the specified + * rectangular area, with the receiver's background + * color. + * + * @param x the x coordinate of the upper left corner of the oval to be filled + * @param y the y coordinate of the upper left corner of the oval to be filled + * @param width the width of the oval to be filled + * @param height the height of the oval to be filled + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #drawOval + */ +public void fillOval (int x, int y, int width, int height) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(FILL); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + if (width == height) { + Cairo.cairo_arc_negative(cairo, x + width / 2f, y + height / 2f, width / 2f, 0, 2 * (float)Compatibility.PI); + } else { + Cairo.cairo_save(cairo); + Cairo.cairo_translate(cairo, x + width / 2f, y + height / 2f); + Cairo.cairo_scale(cairo, width / 2f, height / 2f); + Cairo.cairo_arc_negative(cairo, 0, 0, 1, 0, 2 * (float)Compatibility.PI); + Cairo.cairo_restore(cairo); + } + Cairo.cairo_fill(cairo); + return; + } + OS.XFillArc (data.display, data.drawable, handle, x, y, width, height, 0, 23040); +} +/** + * Fills the path described by the parameter. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * + * @param path the path to fill + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the parameter is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the parameter has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see Path + * + * @since 3.1 + */ +public void fillPath (Path path) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (path == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (path.handle == 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + initCairo(); + checkGC(FILL); + int /*long*/ cairo = data.cairo; + int /*long*/ copy = Cairo.cairo_copy_path(path.handle); + if (copy == 0) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_append_path(cairo, copy); + Cairo.cairo_path_destroy(copy); + Cairo.cairo_fill(cairo); +} +/** + * Fills the interior of the closed polygon which is defined by the + * specified array of integer coordinates, using the receiver's + * background color. The array contains alternating x and y values + * which are considered to represent points which are the vertices of + * the polygon. Lines are drawn between each consecutive pair, and + * between the first pair and last pair in the array. + * + * @param pointArray an array of alternating x and y values which are the vertices of the polygon + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT if pointArray is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #drawPolygon + */ +public void fillPolygon(int[] pointArray) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + checkGC(FILL); + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + drawPolyline(cairo, pointArray, true); + Cairo.cairo_fill(cairo); + return; + } + short[] xPoints = new short[pointArray.length]; + for (int i = 0; i<pointArray.length;i++) { + xPoints[i] = (short) pointArray[i]; + } + OS.XFillPolygon(data.display, data.drawable, handle,xPoints, xPoints.length / 2, OS.Complex, OS.CoordModeOrigin); +} +/** + * Fills the interior of the rectangle specified by the arguments, + * using the receiver's background color. + * + * @param x the x coordinate of the rectangle to be filled + * @param y the y coordinate of the rectangle to be filled + * @param width the width of the rectangle to be filled + * @param height the height of the rectangle to be filled + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #drawRectangle(int, int, int, int) + */ +public void fillRectangle (int x, int y, int width, int height) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(FILL); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + Cairo.cairo_rectangle(cairo, x, y, width, height); + Cairo.cairo_fill(cairo); + return; + } + OS.XFillRectangle (data.display, data.drawable, handle, x, y, width, height); +} +/** + * Fills the interior of the specified rectangle, using the receiver's + * background color. + * + * @param rect the rectangle to be filled + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the rectangle is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #drawRectangle(int, int, int, int) + */ +public void fillRectangle (Rectangle rect) { + if (rect == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + fillRectangle(rect.x, rect.y, rect.width, rect.height); +} +/** + * Fills the interior of the round-cornered rectangle specified by + * the arguments, using the receiver's background color. + * + * @param x the x coordinate of the rectangle to be filled + * @param y the y coordinate of the rectangle to be filled + * @param width the width of the rectangle to be filled + * @param height the height of the rectangle to be filled + * @param arcWidth the width of the arc + * @param arcHeight the height of the arc + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #drawRoundRectangle + */ +public void fillRoundRectangle (int x, int y, int width, int height, int arcWidth, int arcHeight) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(FILL); + int nx = x; + int ny = y; + int nw = width; + int nh = height; + int naw = arcWidth; + int nah = arcHeight; + if (nw < 0) { + nw = 0 - nw; + nx = nx - nw; + } + if (nh < 0) { + nh = 0 - nh; + ny = ny -nh; + } + if (naw < 0) naw = 0 - naw; + if (nah < 0) nah = 0 - nah; + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + if (naw == 0 || nah == 0) { + Cairo.cairo_rectangle(cairo, x, y, width, height); + } else { + float naw2 = naw / 2f; + float nah2 = nah / 2f; + float fw = nw / naw2; + float fh = nh / nah2; + Cairo.cairo_save(cairo); + Cairo.cairo_translate(cairo, nx, ny); + Cairo.cairo_scale(cairo, naw2, nah2); + Cairo.cairo_move_to(cairo, fw - 1, 0); + Cairo.cairo_arc(cairo, fw - 1, 1, 1, Compatibility.PI + Compatibility.PI/2.0, Compatibility.PI*2.0); + Cairo.cairo_arc(cairo, fw - 1, fh - 1, 1, 0, Compatibility.PI/2.0); + Cairo.cairo_arc(cairo, 1, fh - 1, 1, Compatibility.PI/2, Compatibility.PI); + Cairo.cairo_arc(cairo, 1, 1, 1, Compatibility.PI, 270.0*Compatibility.PI/180.0); + Cairo.cairo_close_path(cairo); + Cairo.cairo_restore(cairo); + } + Cairo.cairo_fill(cairo); + return; + } + int naw2 = naw / 2; + int nah2 = nah / 2; + int xDisplay = data.display; + int xDrawable = data.drawable; + if (nw > naw) { + if (nh > nah) { + OS.XFillArc(xDisplay, xDrawable, handle, nx, ny, naw, nah, 5760, 5760); + OS.XFillRectangle(xDisplay, xDrawable, handle, nx + naw2, ny, nw - naw2 * 2, nah2); + OS.XFillArc(xDisplay, xDrawable, handle, nx + nw - naw, ny, naw, nah, 0, 5760); + OS.XFillRectangle(xDisplay, xDrawable, handle, nx, ny + nah2, nw, nh - nah2 * 2); + OS.XFillArc(xDisplay, xDrawable, handle, nx + nw - naw, ny + nh - nah, naw, nah, 17280, 5760); + OS.XFillRectangle(xDisplay, xDrawable, handle, nx + naw2, ny + nh - nah2, nw - naw2 * 2, nah2); + OS.XFillArc(xDisplay, xDrawable, handle, nx, ny + nh - nah, naw, nah, 11520, 5760); + } else { + OS.XFillArc(xDisplay, xDrawable, handle, nx, ny, naw, nh, 5760, 11520); + OS.XFillRectangle(xDisplay, xDrawable, handle, nx + naw2, ny, nw - naw2 * 2, nh); + OS.XFillArc(xDisplay, xDrawable, handle, nx + nw - naw, ny, naw, nh, 17280, 11520); + } + } else { + if (nh > nah) { + OS.XFillArc(xDisplay, xDrawable, handle, nx, ny, nw, nah, 0, 11520); + OS.XFillRectangle(xDisplay, xDrawable, handle, nx, ny + nah2, nw, nh - nah2 * 2); + OS.XFillArc(xDisplay, xDrawable, handle, nx, ny + nh - nah, nw, nah, 11520, 11520); + } else { + OS.XFillArc(xDisplay, xDrawable, handle, nx, ny, nw, nh, 0, 23040); + } + } +} +char fixMnemonic(char[] text) { + char mnemonic=0; + int i=0, j=0; + while (i < text.length) { + if ((text [j++] = text [i++]) == '&') { + if (i == text.length) {continue;} + if (text [i] == '&') {i++; continue;} + if (mnemonic == 0) mnemonic = text [i]; + j--; + } + } + while (j < text.length) text [j++] = 0; + return mnemonic; +} +/** + * Returns the <em>advance width</em> of the specified character in + * the font which is currently selected into the receiver. + * <p> + * The advance width is defined as the horizontal distance the cursor + * should move after printing the character in the selected font. + * </p> + * + * @param ch the character to measure + * @return the distance in the x direction to move past the character before painting the next + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getAdvanceWidth(char ch) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(FONT); + int fontList = data.font.handle; + byte[] charBuffer = Converter.wcsToMbcs(getCodePage (), new char[] { ch }, false); + int val = charBuffer[0] & 0xFF; + /* Create a font context to iterate over each element in the font list */ + int[] buffer = new int[1]; + if (!OS.XmFontListInitFontContext(buffer, fontList)) { + SWT.error(SWT.ERROR_NO_HANDLES); + } + int context = buffer[0]; + XFontStruct fontStruct = new XFontStruct(); + XCharStruct charStruct = new XCharStruct(); + int fontListEntry; + int[] fontStructPtr = new int[1]; + int[] fontNamePtr = new int[1]; + /* Go through each entry in the font list. */ + while ((fontListEntry = OS.XmFontListNextEntry(context)) != 0) { + int fontPtr = OS.XmFontListEntryGetFont(fontListEntry, buffer); + if (buffer[0] == 0) { + OS.memmove(fontStruct, fontPtr, XFontStruct.sizeof); + /* FontList contains a single font */ + if (fontStruct.min_byte1 == 0 && fontStruct.max_byte1 == 0) { + /* Single byte fontStruct */ + if (fontStruct.min_char_or_byte2 <= val && val <= fontStruct.max_char_or_byte2) { + /* The font contains the character */ + int charWidth = 0; + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width as the font's maximum width. + */ + charWidth = fontStruct.max_bounds_width; + } else { + OS.memmove(charStruct, perCharPtr + ((val - fontStruct.min_char_or_byte2) * XCharStruct.sizeof), XCharStruct.sizeof); + charWidth = charStruct.width; + } + if (charWidth != 0) { + OS.XmFontListFreeFontContext(context); + return charWidth; + } + } + } else { + /* Double byte fontStruct */ + int charsPerRow = fontStruct.max_char_or_byte2 - fontStruct.min_char_or_byte2 + 1; + int row = 0; + if (charBuffer.length > 1) row = charBuffer[1] - fontStruct.min_byte1; + int col = charBuffer[0] - fontStruct.min_char_or_byte2; + if (row <= fontStruct.max_byte1 && col <= fontStruct.max_char_or_byte2) { + /* The font contains the character */ + int charWidth = 0; + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width as the font's maximum width. + */ + charWidth = fontStruct.max_bounds_width; + } else { + int offset = row * charsPerRow + col; + OS.memmove(charStruct, perCharPtr + offset * XCharStruct.sizeof, XCharStruct.sizeof); + charWidth = charStruct.width; + } + if (charWidth != 0) { + OS.XmFontListFreeFontContext(context); + return charWidth; + } + } + } + } else { + /* FontList contains a fontSet */ + int nFonts = OS.XFontsOfFontSet(fontPtr, fontStructPtr, fontNamePtr); + int [] fontStructs = new int[nFonts]; + OS.memmove(fontStructs, fontStructPtr[0], nFonts * 4); + /* Go through each fontStruct in the font set */ + for (int i = 0; i < nFonts; i++) { + OS.memmove(fontStruct, fontStructs[i], XFontStruct.sizeof); + if (fontStruct.min_byte1 == 0 && fontStruct.max_byte1 == 0) { + /* Single byte fontStruct */ + if (fontStruct.min_char_or_byte2 <= val && val <= fontStruct.max_char_or_byte2) { + /* The font contains the character */ + int charWidth = 0; + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width as the font's maximum width. + */ + charWidth = fontStruct.max_bounds_width; + } else { + OS.memmove(charStruct, perCharPtr + ((val - fontStruct.min_char_or_byte2) * XCharStruct.sizeof), XCharStruct.sizeof); + charWidth = charStruct.width; + } + if (charWidth != 0) { + OS.XmFontListFreeFontContext(context); + return charWidth; + } + } + } else { + /* Double byte fontStruct */ + int charsPerRow = fontStruct.max_char_or_byte2 - fontStruct.min_char_or_byte2 + 1; + int row = 0; + if (charBuffer.length > 1) row = charBuffer[1] - fontStruct.min_byte1; + int col = charBuffer[0] - fontStruct.min_char_or_byte2; + if (row <= fontStruct.max_byte1 && col <= fontStruct.max_char_or_byte2) { + /* The font contains the character */ + int charWidth = 0; + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width as the font's maximum width. + */ + charWidth = fontStruct.max_bounds_width; + } else { + int offset = row * charsPerRow + col; + OS.memmove(charStruct, perCharPtr + offset * XCharStruct.sizeof, XCharStruct.sizeof); + charWidth = charStruct.width; + } + if (charWidth != 0) { + OS.XmFontListFreeFontContext(context); + return charWidth; + } + } + } + } + } + } + OS.XmFontListFreeFontContext(context); + return stringExtent(new String(new char[]{ch})).x; +} +/** + * Returns <code>true</code> if receiver is using the operating system's + * advanced graphics subsystem. Otherwise, <code>false</code> is returned + * to indicate that normal graphics are in use. + * <p> + * Advanced graphics may not be installed for the operating system. In this + * case, <code>false</code> is always returned. Some operating system have + * only one graphics subsystem. If this subsystem supports advanced graphics, + * then <code>true</code> is always returned. If any graphics operation such + * as alpha, antialias, patterns, interpolation, paths, clipping or transformation + * has caused the receiver to switch from regular to advanced graphics mode, + * <code>true</code> is returned. If the receiver has been explicitly switched + * to advanced mode and this mode is supported, <code>true</code> is returned. + * </p> + * + * @return the advanced value + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #setAdvanced + * + * @since 3.1 + */ +public boolean getAdvanced() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.cairo != 0; +} +/** + * Returns the receiver's alpha value. The alpha value + * is between 0 (transparent) and 255 (opaque). + * + * @return the alpha value + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public int getAlpha() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.alpha; +} +/** + * Returns the receiver's anti-aliasing setting value, which will be + * one of <code>SWT.DEFAULT</code>, <code>SWT.OFF</code> or + * <code>SWT.ON</code>. Note that this controls anti-aliasing for all + * <em>non-text drawing</em> operations. + * + * @return the anti-aliasing setting + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getTextAntialias + * + * @since 3.1 + */ +public int getAntialias() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.cairo == 0) return SWT.DEFAULT; + int antialias = Cairo.cairo_get_antialias(data.cairo); + switch (antialias) { + case Cairo.CAIRO_ANTIALIAS_DEFAULT: return SWT.DEFAULT; + case Cairo.CAIRO_ANTIALIAS_NONE: return SWT.OFF; + case Cairo.CAIRO_ANTIALIAS_GRAY: + case Cairo.CAIRO_ANTIALIAS_SUBPIXEL: return SWT.ON; + } + return SWT.DEFAULT; +} +/** + * Returns the background color. + * + * @return the receiver's background color + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Color getBackground() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + XColor color = data.background; + if ((data.state & BACKGROUND_RGB) == 0) { + OS.XQueryColor(data.display, data.colormap, color); + data.state |= BACKGROUND_RGB; + } + return Color.motif_new(data.device, color); +} +/** + * Returns the background pattern. The default value is + * <code>null</code>. + * + * @return the receiver's background pattern + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see Pattern + * + * @since 3.1 + */ +public Pattern getBackgroundPattern() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.backgroundPattern; +} +/** + * Returns the width of the specified character in the font + * selected into the receiver. + * <p> + * The width is defined as the space taken up by the actual + * character, not including the leading and tailing whitespace + * or overhang. + * </p> + * + * @param ch the character to measure + * @return the width of the character + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getCharWidth(char ch) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(FONT); + int fontList = data.font.handle; + byte[] charBuffer = Converter.wcsToMbcs(getCodePage (), new char[] { ch }, false); + int val = charBuffer[0] & 0xFF; + /* Create a font context to iterate over each element in the font list */ + int[] buffer = new int[1]; + if (!OS.XmFontListInitFontContext(buffer, fontList)) { + SWT.error(SWT.ERROR_NO_HANDLES); + } + int context = buffer[0]; + XFontStruct fontStruct = new XFontStruct(); + XCharStruct charStruct = new XCharStruct(); + int fontListEntry; + int[] fontStructPtr = new int[1]; + int[] fontNamePtr = new int[1]; + /* Go through each entry in the font list. */ + while ((fontListEntry = OS.XmFontListNextEntry(context)) != 0) { + int fontPtr = OS.XmFontListEntryGetFont(fontListEntry, buffer); + if (buffer[0] == 0) { + OS.memmove(fontStruct, fontPtr, XFontStruct.sizeof); + /* FontList contains a single font */ + if (fontStruct.min_byte1 == 0 && fontStruct.max_byte1 == 0) { + /* Single byte fontStruct */ + if (fontStruct.min_char_or_byte2 <= val && val <= fontStruct.max_char_or_byte2) { + /* The font contains the character */ + int charWidth = 0; + int lBearing = 0; + int rBearing = 0; + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width and left/right bearings as the font. + */ + charWidth = fontStruct.max_bounds_width; + lBearing = fontStruct.min_bounds_lbearing; + rBearing = fontStruct.max_bounds_rbearing; + } else { + OS.memmove(charStruct, perCharPtr + ((val - fontStruct.min_char_or_byte2) * XCharStruct.sizeof), XCharStruct.sizeof); + charWidth = charStruct.width; + lBearing = charStruct.lbearing; + rBearing = charStruct.rbearing; + } + if (charWidth != 0) { + OS.XmFontListFreeFontContext(context); + return rBearing - lBearing; + } + } + } else { + /* Double byte fontStruct */ + int charsPerRow = fontStruct.max_char_or_byte2 - fontStruct.min_char_or_byte2 + 1; + int row = 0; + if (charBuffer.length > 1) row = charBuffer[1] - fontStruct.min_byte1; + int col = charBuffer[0] - fontStruct.min_char_or_byte2; + if (row <= fontStruct.max_byte1 && col <= fontStruct.max_char_or_byte2) { + /* The font contains the character */ + int charWidth = 0; + int lBearing = 0; + int rBearing = 0; + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width and left/right bearings as the font. + */ + charWidth = fontStruct.max_bounds_width; + lBearing = fontStruct.min_bounds_lbearing; + rBearing = fontStruct.max_bounds_rbearing; + } else { + int offset = row * charsPerRow + col; + OS.memmove(charStruct, perCharPtr + offset * XCharStruct.sizeof, XCharStruct.sizeof); + charWidth = charStruct.width; + lBearing = charStruct.lbearing; + rBearing = charStruct.rbearing; + } + if (charWidth != 0) { + OS.XmFontListFreeFontContext(context); + return rBearing - lBearing; + } + } + } + } else { + /* FontList contains a fontSet */ + int nFonts = OS.XFontsOfFontSet(fontPtr, fontStructPtr, fontNamePtr); + int [] fontStructs = new int[nFonts]; + OS.memmove(fontStructs, fontStructPtr[0], nFonts * 4); + /* Go through each fontStruct in the font set */ + for (int i = 0; i < nFonts; i++) { + OS.memmove(fontStruct, fontStructs[i], XFontStruct.sizeof); + if (fontStruct.min_byte1 == 0 && fontStruct.max_byte1 == 0) { + /* Single byte fontStruct */ + if (fontStruct.min_char_or_byte2 <= val && val <= fontStruct.max_char_or_byte2) { + /* The font contains the character */ + int charWidth = 0; + int lBearing = 0; + int rBearing = 0; + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width and left/right bearings as the font. + */ + charWidth = fontStruct.max_bounds_width; + lBearing = fontStruct.min_bounds_lbearing; + rBearing = fontStruct.max_bounds_rbearing; + } else { + OS.memmove(charStruct, perCharPtr + ((val - fontStruct.min_char_or_byte2) * XCharStruct.sizeof), XCharStruct.sizeof); + charWidth = charStruct.width; + lBearing = charStruct.lbearing; + rBearing = charStruct.rbearing; + } + if (charWidth != 0) { + OS.XmFontListFreeFontContext(context); + return rBearing - lBearing; + } + } + } else { + /* Double byte fontStruct */ + int charsPerRow = fontStruct.max_char_or_byte2 - fontStruct.min_char_or_byte2 + 1; + int row = 0; + if (charBuffer.length > 1) row = charBuffer[1] - fontStruct.min_byte1; + int col = charBuffer[0] - fontStruct.min_char_or_byte2; + if (row <= fontStruct.max_byte1 && col <= fontStruct.max_char_or_byte2) { + /* The font contains the character */ + int charWidth = 0; + int lBearing = 0; + int rBearing = 0; + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width and left/right bearings as the font. + */ + charWidth = fontStruct.max_bounds_width; + lBearing = fontStruct.min_bounds_lbearing; + rBearing = fontStruct.max_bounds_rbearing; + } else { + int offset = row * charsPerRow + col; + OS.memmove(charStruct, perCharPtr + offset * XCharStruct.sizeof, XCharStruct.sizeof); + charWidth = charStruct.width; + lBearing = charStruct.lbearing; + rBearing = charStruct.rbearing; + } + if (charWidth != 0) { + OS.XmFontListFreeFontContext(context); + return rBearing - lBearing; + } + } + } + } + } + } + OS.XmFontListFreeFontContext(context); + return stringExtent(new String(new char[]{ch})).x; +} +/** + * Returns the bounding rectangle of the receiver's clipping + * region. If no clipping region is set, the return value + * will be a rectangle which covers the entire bounds of the + * object the receiver is drawing on. + * + * @return the bounding rectangle of the clipping region + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Rectangle getClipping() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + /* Calculate visible bounds in device space */ + int x = 0, y = 0, width = 0, height = 0; + int[] w = new int[1], h = new int[1], unused = new int[1]; + OS.XGetGeometry(data.display, data.drawable, unused, unused, unused, w, h, unused, unused); + width = w[0]; + height = h[0]; + /* Intersect visible bounds with clipping in device space and then convert then to user space */ + int cairo = data.cairo; + int clipRgn = data.clipRgn; + int damageRgn = data.damageRgn; + if (clipRgn != 0 || damageRgn != 0 || cairo != 0) { + int rgn = OS.XCreateRegion (); + XRectangle rect = new XRectangle(); + rect.width = (short)width; + rect.height = (short)height; + OS.XUnionRectWithRegion(rect, rgn, rgn); + if (damageRgn != 0) { + OS.XIntersectRegion (damageRgn, rgn, rgn); + } + /* Intersect visible bounds with clipping */ + if (clipRgn != 0) { + /* Convert clipping to device space if needed */ + if (data.clippingTransform != null) { + clipRgn = convertRgn(clipRgn, data.clippingTransform); + OS.XIntersectRegion(rgn, clipRgn, rgn); + OS.XDestroyRegion(clipRgn); + } else { + OS.XIntersectRegion(rgn, clipRgn, rgn); + } + } + /* Convert to user space */ + if (cairo != 0) { + double[] matrix = new double[6]; + Cairo.cairo_get_matrix(cairo, matrix); + Cairo.cairo_matrix_invert(matrix); + clipRgn = convertRgn(rgn, matrix); + OS.XDestroyRegion(rgn); + rgn = clipRgn; + } + OS.XClipBox(rgn, rect); + OS.XDestroyRegion(rgn); + x = rect.x; + y = rect.y; + width = rect.width; + height = rect.height; + } + return new Rectangle(x, y, width, height); +} +/** + * Sets the region managed by the argument to the current + * clipping region of the receiver. + * + * @param region the region to fill with the clipping region + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the region is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the region is disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void getClipping(Region region) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int clipping = region.handle; + OS.XSubtractRegion (clipping, clipping, clipping); + int /*long*/ cairo = data.cairo; + int clipRgn = data.clipRgn; + if (clipRgn == 0) { + int[] width = new int[1], height = new int[1], unused = new int[1]; + OS.XGetGeometry(data.display, data.drawable, unused, unused, unused, width, height, unused, unused); + XRectangle rect = new XRectangle(); + rect.x = 0; + rect.y = 0; + rect.width = (short)width[0]; + rect.height = (short)height[0]; + OS.XUnionRectWithRegion(rect, clipping, clipping); + } else { + /* Convert clipping to device space if needed */ + if (data.clippingTransform != null) { + int rgn = convertRgn(clipRgn, data.clippingTransform); + OS.XUnionRegion(clipping, rgn, clipping); + OS.XDestroyRegion(rgn); + } else { + OS.XUnionRegion(clipping, clipRgn, clipping); + } + } + if (data.damageRgn != 0) { + OS.XIntersectRegion(clipping, data.damageRgn, clipping); + } + /* Convert to user space */ + if (cairo != 0) { + double[] matrix = new double[6]; + Cairo.cairo_get_matrix(cairo, matrix); + Cairo.cairo_matrix_invert(matrix); + int rgn = convertRgn(clipping, matrix); + OS.XSubtractRegion(clipping, clipping, clipping); + OS.XUnionRegion(clipping, rgn, clipping); + OS.XDestroyRegion(rgn); + } +} +String getCodePage () { + return data.font.codePage; +} +/** + * Returns the receiver's fill rule, which will be one of + * <code>SWT.FILL_EVEN_ODD</code> or <code>SWT.FILL_WINDING</code>. + * + * @return the receiver's fill rule + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public int getFillRule() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + XGCValues values = new XGCValues(); + OS.XGetGCValues(data.display, handle, OS.GCFillRule, values); + return values.fill_rule == OS.WindingRule ? SWT.FILL_WINDING : SWT.FILL_EVEN_ODD; +} +/** + * Returns the font currently being used by the receiver + * to draw and measure text. + * + * @return the receiver's font + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Font getFont () { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return Font.motif_new(data.device, data.font.handle); +} +int getFontHeight () { + int fontList = data.font.handle; + /* Create a font context to iterate over each element in the font list */ + int [] buffer = new int [1]; + if (!OS.XmFontListInitFontContext (buffer, fontList)) { + SWT.error(SWT.ERROR_NO_HANDLES); + } + int context = buffer [0]; + + /* Values discovering during iteration */ + int height = 0; + XFontStruct fontStruct = new XFontStruct (); + int fontListEntry; + int [] fontStructPtr = new int [1]; + int [] fontNamePtr = new int [1]; + + /* Go through each entry in the font list. */ + while ((fontListEntry = OS.XmFontListNextEntry (context)) != 0) { + int fontPtr = OS.XmFontListEntryGetFont (fontListEntry, buffer); + if (buffer [0] == 0) { + /* FontList contains a single font */ + OS.memmove (fontStruct, fontPtr, XFontStruct.sizeof); + int fontHeight = fontStruct.ascent + fontStruct.descent; + height = Math.max(height, fontHeight); + } else { + /* FontList contains a fontSet */ + int nFonts = OS.XFontsOfFontSet (fontPtr, fontStructPtr, fontNamePtr); + int [] fontStructs = new int [nFonts]; + OS.memmove (fontStructs, fontStructPtr [0], nFonts * 4); + + /* Go through each fontStruct in the font set */ + for (int i=0; i<nFonts; i++) { + OS.memmove (fontStruct, fontStructs[i], XFontStruct.sizeof); + int fontHeight = fontStruct.ascent + fontStruct.descent; + height = Math.max(height, fontHeight); + } + } + } + + OS.XmFontListFreeFontContext (context); + return height; +} +/** + * Returns a FontMetrics which contains information + * about the font currently being used by the receiver + * to draw and measure text. + * + * @return font metrics for the receiver's font + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public FontMetrics getFontMetrics() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(FONT); + int xDisplay = data.display; + Font font = data.font; + int fontList = font.handle; + /* Create a font context to iterate over each element in the font list */ + int[] buffer = new int[1]; + if (!OS.XmFontListInitFontContext(buffer, fontList)) { + SWT.error(SWT.ERROR_NO_HANDLES); + } + int context = buffer[0]; + /* Values discovering during iteration */ + int ascent = 0; + int descent = 0; + int averageCharWidth = 0, numAverageCharWidth = 0; + int leading = 0; + int height = 0; + + XFontStruct fontStruct = new XFontStruct(); + int fontListEntry; + int[] fontStructPtr = new int[1]; + int[] fontNamePtr = new int[1]; + /* Go through each entry in the font list. */ + while ((fontListEntry = OS.XmFontListNextEntry(context)) != 0) { + int fontPtr = OS.XmFontListEntryGetFont(fontListEntry, buffer); + if (buffer[0] == 0) { + /* FontList contains a single font */ + OS.memmove(fontStruct, fontPtr, XFontStruct.sizeof); + ascent = Math.max(ascent, fontStruct.ascent); + descent = Math.max(descent, fontStruct.descent); + int fontHeight = fontStruct.ascent + fontStruct.descent; + height = Math.max(height, fontHeight); + /* Calculate average character width */ + int propPtr = fontStruct.properties; + for (int i = 0; i < fontStruct.n_properties; i++) { + /* Look through properties for XAFONT */ + int[] prop = new int[2]; + OS.memmove(prop, propPtr, 8); + if (prop[0] == OS.XA_FONT) { + /* Found it, prop[1] points to the string */ + int ptr = OS.XmGetAtomName(xDisplay, prop[1]); + int length = OS.strlen(ptr); + byte[] nameBuf = new byte[length]; + OS.memmove(nameBuf, ptr, length); + OS.XFree(ptr); + String xlfd = new String(Converter.mbcsToWcs(null, nameBuf)).toLowerCase(); + int avg = 0; + try { + avg = FontData.motif_new(xlfd).averageWidth / 10; + } catch (Exception e) { + // leave avg unchanged so that it will be computed below + } + if (avg == 0) { + /* + * Not all fonts have average character width encoded + * in the xlfd. This one doesn't, so do it the hard + * way by averaging all the character widths. + */ + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width as the font's maximum width. So no + * averaging is required. + */ + averageCharWidth = fontStruct.max_bounds_width; + } else { + int sum = 0, count = 0; + int cols = fontStruct.max_char_or_byte2 - fontStruct.min_char_or_byte2 + 1; + XCharStruct struct = new XCharStruct(); + for (int index = 0; index < cols; index++) { + OS.memmove(struct, perCharPtr + (index * XCharStruct.sizeof), XCharStruct.sizeof); + int w = struct.width; + if (w != 0) { + sum += w; + count++; + } + } + averageCharWidth += sum / count; + } + } else { + /* Average character width was in the xlfd */ + averageCharWidth += avg; + } + numAverageCharWidth++; + break; + } + propPtr += 8; + } + } else { + /* FontList contains a fontSet */ + int nFonts = OS.XFontsOfFontSet(fontPtr, fontStructPtr, fontNamePtr); + int [] fontStructs = new int[nFonts]; + OS.memmove(fontStructs, fontStructPtr[0], nFonts * 4); + /* Go through each fontStruct in the font set */ + for (int i = 0; i < nFonts; i++) { + OS.memmove(fontStruct, fontStructs[i], XFontStruct.sizeof); + ascent = Math.max(ascent, fontStruct.ascent); + descent = Math.max(descent, fontStruct.descent); + int fontHeight = fontStruct.ascent + fontStruct.descent; + height = Math.max(height, fontHeight); + /* Calculate average character width */ + int propPtr = fontStruct.properties; + for (int j = 0; j < fontStruct.n_properties; j++) { + /* Look through properties for XAFONT */ + int[] prop = new int[2]; + OS.memmove(prop, propPtr, 8); + if (prop[0] == OS.XA_FONT) { + /* Found it, prop[1] points to the string */ + int ptr = OS.XmGetAtomName(xDisplay, prop[1]); + int length = OS.strlen(ptr); + byte[] nameBuf = new byte[length]; + OS.memmove(nameBuf, ptr, length); + OS.XFree(ptr); + String xlfd = new String(Converter.mbcsToWcs(null, nameBuf)).toLowerCase(); + int avg = 0; + try { + avg = FontData.motif_new(xlfd).averageWidth / 10; + } catch (Exception e) { + /* + * Some font servers, for example, xfstt, do not pass + * reasonable font properties to the client, so we + * cannot construct a FontData for these. Use the font + * name instead. + */ + int[] fontName = new int[1]; + OS.memmove(fontName, fontNamePtr [0] + (i * 4), 4); + ptr = fontName[0]; + if (ptr != 0 ) { + length = OS.strlen(ptr); + nameBuf = new byte[length]; + OS.memmove(nameBuf, ptr, length); + xlfd = new String(Converter.mbcsToWcs(null, nameBuf)).toLowerCase(); + try { + avg = FontData.motif_new(xlfd).averageWidth / 10; + } catch (Exception ex) { + // leave avg unchanged (0) so that it will be computed below + } + } + } + if (avg == 0) { + /* + * Not all fonts have average character width encoded + * in the xlfd. This one doesn't, so do it the hard + * way by averaging all the character widths. + */ + int perCharPtr = fontStruct.per_char; + if (perCharPtr == 0) { + /* + * If perCharPtr is 0 then all glyphs in the font have + * the same width as the font's maximum width. So no + * averaging is required. + */ + averageCharWidth = fontStruct.max_bounds_width; + } else { + int sum = 0, count = 0; + int cols = fontStruct.max_char_or_byte2 - fontStruct.min_char_or_byte2 + 1; + XCharStruct struct = new XCharStruct(); + for (int index = 0; index < cols; index++) { + OS.memmove(struct, perCharPtr + (index * XCharStruct.sizeof), XCharStruct.sizeof); + int w = struct.width; + if (w != 0) { + sum += w; + count++; + } + } + averageCharWidth += sum / count; + } + } else { + /* Average character width was in the xlfd */ + averageCharWidth += avg; + } + numAverageCharWidth++; + break; + } + propPtr += 8; + } + } + } + } + OS.XmFontListFreeFontContext(context); + return FontMetrics.motif_new(ascent, descent, averageCharWidth / numAverageCharWidth, leading, height); +} +/** + * Returns the receiver's foreground color. + * + * @return the color used for drawing foreground things + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Color getForeground() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + XColor color = data.foreground; + if ((data.state & FOREGROUND_RGB) == 0) { + OS.XQueryColor(data.display, data.colormap, color); + data.state |= FOREGROUND_RGB; + } + return Color.motif_new(data.device, color); +} +/** + * Returns the foreground pattern. The default value is + * <code>null</code>. + * + * @return the receiver's foreground pattern + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see Pattern + * + * @since 3.1 + */ +public Pattern getForegroundPattern() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.foregroundPattern; +} +/** + * Returns the GCData. + * <p> + * <b>IMPORTANT:</b> This method is <em>not</em> part of the public + * API for <code>GC</code>. 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. + * </p> + * + * @return the receiver's GCData + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see GCData + * + * @since 3.2 + * @noreference This method is not intended to be referenced by clients. + */ +public GCData getGCData() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data; +} +/** + * Returns the receiver's interpolation setting, which will be one of + * <code>SWT.DEFAULT</code>, <code>SWT.NONE</code>, + * <code>SWT.LOW</code> or <code>SWT.HIGH</code>. + * + * @return the receiver's interpolation setting + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public int getInterpolation() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.interpolation; +} +/** + * Returns the receiver's line attributes. + * + * @return the line attributes used for drawing lines + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.3 + */ +public LineAttributes getLineAttributes() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + float[] dashes = null; + if (data.lineDashes != null) { + dashes = new float[data.lineDashes.length]; + System.arraycopy(data.lineDashes, 0, dashes, 0, dashes.length); + } + return new LineAttributes(data.lineWidth, data.lineCap, data.lineJoin, data.lineStyle, dashes, data.lineDashesOffset, data.lineMiterLimit); +} +/** + * Returns the receiver's line cap style, which will be one + * of the constants <code>SWT.CAP_FLAT</code>, <code>SWT.CAP_ROUND</code>, + * or <code>SWT.CAP_SQUARE</code>. + * + * @return the cap style used for drawing lines + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public int getLineCap() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.lineCap; +} +/** + * Returns the receiver's line dash style. The default value is + * <code>null</code>. + * + * @return the line dash style used for drawing lines + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public int[] getLineDash() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineDashes == null) return null; + int[] lineDashes = new int[data.lineDashes.length]; + for (int i = 0; i < lineDashes.length; i++) { + lineDashes[i] = (int)data.lineDashes[i]; + } + return lineDashes; +} +/** + * Returns the receiver's line join style, which will be one + * of the constants <code>SWT.JOIN_MITER</code>, <code>SWT.JOIN_ROUND</code>, + * or <code>SWT.JOIN_BEVEL</code>. + * + * @return the join style used for drawing lines + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public int getLineJoin() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.lineJoin; +} +/** + * Returns the receiver's line style, which will be one + * of the constants <code>SWT.LINE_SOLID</code>, <code>SWT.LINE_DASH</code>, + * <code>SWT.LINE_DOT</code>, <code>SWT.LINE_DASHDOT</code> or + * <code>SWT.LINE_DASHDOTDOT</code>. + * + * @return the style used for drawing lines + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getLineStyle() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.lineStyle; +} +/** + * Returns the width that will be used when drawing lines + * for all of the figure drawing operations (that is, + * <code>drawLine</code>, <code>drawRectangle</code>, + * <code>drawPolyline</code>, and so forth. + * + * @return the receiver's line width + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getLineWidth() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return (int)data.lineWidth; +} +/** + * Returns the receiver's style information. + * <p> + * Note that the value which is returned by this method <em>may + * not match</em> the value which was provided to the constructor + * when the receiver was created. This can occur when the underlying + * operating system does not support a particular combination of + * requested styles. + * </p> + * + * @return the style bits + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 2.1.2 + */ +public int getStyle () { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.style; +} +/** + * Returns the receiver's text drawing anti-aliasing setting value, + * which will be one of <code>SWT.DEFAULT</code>, <code>SWT.OFF</code> or + * <code>SWT.ON</code>. Note that this controls anti-aliasing + * <em>only</em> for text drawing operations. + * + * @return the anti-aliasing setting + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getAntialias + * + * @since 3.1 + */ +public int getTextAntialias() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.cairo == 0) return SWT.DEFAULT; + int /*long*/ options = Cairo.cairo_font_options_create(); + Cairo.cairo_get_font_options(data.cairo, options); + int antialias = Cairo.cairo_font_options_get_antialias(options); + Cairo.cairo_font_options_destroy(options); + switch (antialias) { + case Cairo.CAIRO_ANTIALIAS_DEFAULT: return SWT.DEFAULT; + case Cairo.CAIRO_ANTIALIAS_NONE: return SWT.OFF; + case Cairo.CAIRO_ANTIALIAS_GRAY: + case Cairo.CAIRO_ANTIALIAS_SUBPIXEL: return SWT.ON; + } + return SWT.DEFAULT; +} +/** + * Sets the parameter to the transform that is currently being + * used by the receiver. + * + * @param transform the destination to copy the transform into + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the parameter is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the parameter has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see Transform + * + * @since 3.1 + */ +public void getTransform(Transform transform) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (transform == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (transform.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + Cairo.cairo_get_matrix(cairo, transform.handle); + } else { + transform.setElements(1, 0, 0, 1, 0, 0); + } +} +/** + * Returns <code>true</code> if this GC is drawing in the mode + * where the resulting color in the destination is the + * <em>exclusive or</em> of the color values in the source + * and the destination, and <code>false</code> if it is + * drawing in the mode where the destination color is being + * replaced with the source color value. + * + * @return <code>true</code> true if the receiver is in XOR mode, and false otherwise + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public boolean getXORMode() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + XGCValues values = new XGCValues (); + OS.XGetGCValues (data.display, handle, OS.GCFunction, values); + return values.function == OS.GXxor; +} +/** + * Returns an integer hash code for the receiver. Any two + * objects that return <code>true</code> when passed to + * <code>equals</code> must return the same value for this + * method. + * + * @return the receiver's hash + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #equals + */ +public int hashCode () { + return handle; +} +void init(Drawable drawable, GCData data, int xGC) { + if (data.foreground != null) data.state &= ~(FOREGROUND | FOREGROUND_RGB); + if (data.background != null) data.state &= ~(BACKGROUND | BACKGROUND_BG | BACKGROUND_RGB); + if (data.font != null) data.state &= ~FONT; + Image image = data.image; + if (image != null) { + image.memGC = this; + /* + * The transparent pixel mask might change when drawing on + * the image. Destroy it so that it is regenerated when + * necessary. + */ + if (image.transparentPixel != -1) image.destroyMask(); + } + this.drawable = drawable; + this.data = data; + handle = xGC; +} +void initCairo() { + data.device.checkCairo(); + int /*long*/ cairo = data.cairo; + if (cairo != 0) return; + int xDisplay = data.display; + int xDrawable = data.drawable; + int xVisual = OS.XDefaultVisual(xDisplay, OS.XDefaultScreen(xDisplay)); + int[] width = new int[1], height = new int[1], unused = new int[1]; + OS.XGetGeometry(xDisplay, xDrawable, unused, unused, unused, width, height, unused, unused); + int /*long*/ surface = Cairo.cairo_xlib_surface_create(xDisplay, xDrawable, xVisual, width[0], height[0]); + if (surface == 0) SWT.error(SWT.ERROR_NO_HANDLES); + data.cairo = cairo = Cairo.cairo_create(surface); + Cairo.cairo_surface_destroy(surface); + if (cairo == 0) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_set_fill_rule(cairo, Cairo.CAIRO_FILL_RULE_EVEN_ODD); + data.state &= ~(BACKGROUND | FOREGROUND | FONT | LINE_WIDTH | LINE_CAP | LINE_JOIN | LINE_STYLE | DRAW_OFFSET); + setCairoClip(data.damageRgn, data.clipRgn); +} +/** + * Returns <code>true</code> if the receiver has a clipping + * region set into it, and <code>false</code> otherwise. + * If this method returns false, the receiver will draw on all + * available space in the destination. If it returns true, + * it will draw only in the area that is covered by the region + * that can be accessed with <code>getClipping(region)</code>. + * + * @return <code>true</code> if the GC has a clipping region, and <code>false</code> otherwise + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public boolean isClipped() { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.clipRgn != 0; +} +/** + * Returns <code>true</code> if the GC has been disposed, + * and <code>false</code> otherwise. + * <p> + * This method gets the dispose state for the GC. + * When a GC has been disposed, it is an error to + * invoke any other method using the GC. + * + * @return <code>true</code> when the GC is disposed and <code>false</code> otherwise + */ +public boolean isDisposed() { + return handle == 0; +} +boolean isIdentity(double[] matrix) { + if (matrix == null) return true; + return matrix[0] == 1 && matrix[1] == 0 && matrix[2] == 0 && matrix[3] == 1 && matrix[4] == 0 && matrix[5] == 0; +} +/** + * Sets the receiver to always use the operating system's advanced graphics + * subsystem for all graphics operations if the argument is <code>true</code>. + * If the argument is <code>false</code>, the advanced graphics subsystem is + * no longer used, advanced graphics state is cleared and the normal graphics + * subsystem is used from now on. + * <p> + * Normally, the advanced graphics subsystem is invoked automatically when + * any one of the alpha, antialias, patterns, interpolation, paths, clipping + * or transformation operations in the receiver is requested. When the receiver + * is switched into advanced mode, the advanced graphics subsystem performs both + * advanced and normal graphics operations. Because the two subsystems are + * different, their output may differ. Switching to advanced graphics before + * any graphics operations are performed ensures that the output is consistent. + * </p><p> + * Advanced graphics may not be installed for the operating system. In this + * case, this operation does nothing. Some operating system have only one + * graphics subsystem, so switching from normal to advanced graphics does + * nothing. However, switching from advanced to normal graphics will always + * clear the advanced graphics state, even for operating systems that have + * only one graphics subsystem. + * </p> + * + * @param advanced the new advanced graphics state + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #setAlpha + * @see #setAntialias + * @see #setBackgroundPattern + * @see #setClipping(Path) + * @see #setForegroundPattern + * @see #setLineAttributes + * @see #setInterpolation + * @see #setTextAntialias + * @see #setTransform + * @see #getAdvanced + * + * @since 3.1 + */ +public void setAdvanced(boolean advanced) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (advanced && data.cairo != 0) return; + if (advanced) { + try { + initCairo(); + } catch (SWTException e) {} + } else { + int /*long*/ cairo = data.cairo; + if (cairo != 0) Cairo.cairo_destroy(cairo); + data.cairo = 0; + data.interpolation = SWT.DEFAULT; + data.backgroundPattern = data.foregroundPattern = null; + data.state = 0; + setClipping(0); + } +} +/** + * Sets the receiver's alpha value which must be + * between 0 (transparent) and 255 (opaque). + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * @param alpha the alpha value + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see #getAdvanced + * @see #setAdvanced + * + * @since 3.1 + */ +public void setAlpha(int alpha) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.cairo == 0 && (alpha & 0xff) == 0xff) return; + initCairo(); + data.alpha = alpha & 0xff; + data.state &= ~(BACKGROUND | FOREGROUND | BACKGROUND_BG); +} +/** + * Sets the receiver's anti-aliasing value to the parameter, + * which must be one of <code>SWT.DEFAULT</code>, <code>SWT.OFF</code> + * or <code>SWT.ON</code>. Note that this controls anti-aliasing for all + * <em>non-text drawing</em> operations. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * + * @param antialias the anti-aliasing setting + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the parameter is not one of <code>SWT.DEFAULT</code>, + * <code>SWT.OFF</code> or <code>SWT.ON</code></li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see #getAdvanced + * @see #setAdvanced + * @see #setTextAntialias + * + * @since 3.1 + */ +public void setAntialias(int antialias) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.cairo == 0 && antialias == SWT.DEFAULT) return; + int mode = 0; + switch (antialias) { + case SWT.DEFAULT: mode = Cairo.CAIRO_ANTIALIAS_DEFAULT; break; + case SWT.OFF: mode = Cairo.CAIRO_ANTIALIAS_NONE; break; + case SWT.ON: mode = Cairo.CAIRO_ANTIALIAS_GRAY; + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + initCairo(); + int /*long*/ cairo = data.cairo; + Cairo.cairo_set_antialias(cairo, mode); +} +/** + * Invokes platform specific functionality to allocate a new graphics context. + * <p> + * <b>IMPORTANT:</b> This method is <em>not</em> part of the public + * API for <code>GC</code>. 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. + * </p> + * + * @param drawable the Drawable for the receiver. + * @param data the data for the receiver. + * + * @return a new <code>GC</code> + */ +public static GC motif_new(Drawable drawable, GCData data) { + GC gc = new GC(); + int xGC = drawable.internal_new_GC(data); + gc.device = data.device; + gc.init(drawable, data, xGC); + return gc; +} +/** + * Invokes platform specific functionality to wrap a graphics context. + * <p> + * <b>IMPORTANT:</b> This method is <em>not</em> part of the public + * API for <code>GC</code>. 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. + * </p> + * + * @param xGC the X Windows graphics context. + * @param data the data for the receiver. + * + * @return a new <code>GC</code> + */ +public static GC motif_new(int xGC, GCData data) { + GC gc = new GC(); + gc.device = data.device; + gc.init(null, data, xGC); + return gc; +} +/** + * Sets the background color. The background color is used + * for fill operations and as the background color when text + * is drawn. + * + * @param color the new background color for the receiver + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the color is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the color has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setBackground (Color color) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (color == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (color.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + data.background = color.handle; + data.backgroundPattern = null; + data.state &= ~(BACKGROUND | BACKGROUND_BG); + data.state |= BACKGROUND_RGB; +} +/** + * Sets the background pattern. The default value is <code>null</code>. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * + * @param pattern the new background pattern + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the parameter has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see Pattern + * @see #getAdvanced + * @see #setAdvanced + * + * @since 3.1 + */ +public void setBackgroundPattern(Pattern pattern) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pattern != null && pattern.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (data.cairo == 0 && pattern == null) return; + initCairo(); + if (data.backgroundPattern == pattern) return; + data.backgroundPattern = pattern; + data.state &= ~BACKGROUND; +} +static void setCairoFont(int /*long*/ cairo, Font font) { + //TODO - use X font instead of loading new one??? + FontData[] fds = font.getFontData(); + FontData fd = fds[0]; + int style = fd.getStyle(); + int slant = Cairo.CAIRO_FONT_SLANT_NORMAL; + if ((style & SWT.ITALIC) != 0) slant = Cairo.CAIRO_FONT_SLANT_ITALIC; + int weight = Cairo.CAIRO_FONT_WEIGHT_NORMAL; + if ((style & SWT.BOLD) != 0) weight = Cairo.CAIRO_FONT_WEIGHT_BOLD; + String name = fd.getName(); + int index = name.indexOf('-'); + if (index != -1) name = name.substring(index + 1); + byte[] buffer = Converter.wcsToMbcs(null, name, true); + Cairo.cairo_select_font_face(cairo, buffer, slant, weight); + Cairo.cairo_set_font_size(cairo, fd.getHeight()); +} +static void setCairoRegion(int /*long*/ cairo, int /*long*/ rgn) { + //TODO - get rectangles from region instead of clip box + XRectangle rect = new XRectangle(); + OS.XClipBox(rgn, rect); + Cairo.cairo_rectangle(cairo, rect.x, rect.y, rect.width, rect.height); +} +static void setCairoPatternColor(int /*long*/ pattern, int offset, Color c, int alpha) { + XColor color = c.handle; + double aa = (alpha & 0xFF) / (double)0xFF; + double red = ((color.red & 0xFFFF) / (double)0xFFFF); + double green = ((color.green & 0xFFFF) / (double)0xFFFF); + double blue = ((color.blue & 0xFFFF) / (double)0xFFFF); + Cairo.cairo_pattern_add_color_stop_rgba(pattern, offset, red, green, blue, aa); +} +void setCairoClip(int /*long*/ damageRgn, int /*long*/ clipRgn) { + int /*long*/ cairo = data.cairo; + Cairo.cairo_reset_clip(cairo); + if (damageRgn != 0) { + double[] matrix = new double[6]; + Cairo.cairo_get_matrix(cairo, matrix); + Cairo.cairo_identity_matrix(cairo); + setCairoRegion(cairo, damageRgn); + Cairo.cairo_clip(cairo); + Cairo.cairo_set_matrix(cairo, matrix); + } + if (clipRgn != 0) { + setCairoRegion(cairo, clipRgn); + Cairo.cairo_clip(cairo); + } +} +void setClipping(int clipRgn) { + int /*long*/ cairo = data.cairo; + if (clipRgn == 0) { + if (data.clipRgn != 0) { + OS.XDestroyRegion (data.clipRgn); + data.clipRgn = 0; + } + if (cairo != 0) { + data.clippingTransform = null; + setCairoClip(data.damageRgn, 0); + } else { + if (data.damageRgn == 0) { + OS.XSetClipMask (data.display, handle, OS.None); + } else { + OS.XSetRegion (data.display, handle, data.damageRgn); + } + } + } else { + if (data.clipRgn == 0) data.clipRgn = OS.XCreateRegion (); + OS.XSubtractRegion (data.clipRgn, data.clipRgn, data.clipRgn); + OS.XUnionRegion (clipRgn, data.clipRgn, data.clipRgn); + if (cairo != 0) { + if (data.clippingTransform == null) data.clippingTransform = new double[6]; + Cairo.cairo_get_matrix(cairo, data.clippingTransform); + setCairoClip(data.damageRgn, clipRgn); + } else { + int clipping = clipRgn; + if (data.damageRgn != 0) { + clipping = OS.XCreateRegion(); + OS.XUnionRegion(clipping, clipRgn, clipping); + OS.XIntersectRegion(clipping, data.damageRgn, clipping); + } + OS.XSetRegion (data.display, handle, clipping); + if (clipping != clipRgn) OS.XDestroyRegion(clipping); + } + } +} +/** + * Sets the area of the receiver which can be changed + * by drawing operations to the rectangular area specified + * by the arguments. + * + * @param x the x coordinate of the clipping rectangle + * @param y the y coordinate of the clipping rectangle + * @param width the width of the clipping rectangle + * @param height the height of the clipping rectangle + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setClipping (int x, int y, int width, int height) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + XRectangle rect = new XRectangle (); + rect.x = (short) x; + rect.y = (short) y; + rect.width = (short) Math.max (0, width); + rect.height = (short) Math.max (0, height); + int clipRgn = OS.XCreateRegion(); + OS.XUnionRectWithRegion(rect, clipRgn, clipRgn); + setClipping(clipRgn); + OS.XDestroyRegion(clipRgn); +} +/** + * Sets the area of the receiver which can be changed + * by drawing operations to the path specified + * by the argument. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * + * @param path the clipping path. + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the path has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see Path + * @see #getAdvanced + * @see #setAdvanced + * + * @since 3.1 + */ +public void setClipping(Path path) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (path != null && path.isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + setClipping(0); + if (path != null) { + initCairo(); + int /*long*/ cairo = data.cairo; + int /*long*/ copy = Cairo.cairo_copy_path(path.handle); + if (copy == 0) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_append_path(cairo, copy); + Cairo.cairo_path_destroy(copy); + Cairo.cairo_clip(cairo); + Cairo.cairo_new_path(cairo); + } +} +/** + * Sets the area of the receiver which can be changed + * by drawing operations to the rectangular area specified + * by the argument. Specifying <code>null</code> for the + * rectangle reverts the receiver's clipping area to its + * original value. + * + * @param rect the clipping rectangle or <code>null</code> + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setClipping (Rectangle rect) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (rect == null) { + setClipping(0); + } else { + setClipping (rect.x, rect.y, rect.width, rect.height); + } +} +/** + * Sets the area of the receiver which can be changed + * by drawing operations to the region specified + * by the argument. Specifying <code>null</code> for the + * region reverts the receiver's clipping area to its + * original value. + * + * @param region the clipping region or <code>null</code> + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the region has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setClipping (Region region) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region != null && region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + setClipping(region != null ? region.handle : 0); +} +/** + * Sets the receiver's fill rule to the parameter, which must be one of + * <code>SWT.FILL_EVEN_ODD</code> or <code>SWT.FILL_WINDING</code>. + * + * @param rule the new fill rule + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the rule is not one of <code>SWT.FILL_EVEN_ODD</code> + * or <code>SWT.FILL_WINDING</code></li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void setFillRule(int rule) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + int mode = OS.EvenOddRule, cairo_mode = Cairo.CAIRO_FILL_RULE_EVEN_ODD; + switch (rule) { + case SWT.FILL_WINDING: + mode = OS.WindingRule; cairo_mode = Cairo.CAIRO_FILL_RULE_WINDING; break; + case SWT.FILL_EVEN_ODD: + mode = OS.EvenOddRule; cairo_mode = Cairo.CAIRO_FILL_RULE_EVEN_ODD; break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + OS.XSetFillRule(data.display, handle, mode); + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + Cairo.cairo_set_fill_rule(cairo, cairo_mode); + } +} +/** + * Sets the font which will be used by the receiver + * to draw and measure text to the argument. If the + * argument is null, then a default font appropriate + * for the platform will be used instead. + * + * @param font the new font for the receiver, or null to indicate a default font + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the font has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setFont (Font font) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (font != null && font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + data.font = font != null ? font : data.device.systemFont; + data.state &= ~FONT; + if (data.renderTable != 0) OS.XmRenderTableFree(data.renderTable); + data.renderTable = 0; + data.stringWidth = data.stringHeight = data.textWidth = data.textHeight = -1; +} +/** + * Sets the foreground color. The foreground color is used + * for drawing operations including when text is drawn. + * + * @param color the new foreground color for the receiver + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the color is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the color has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setForeground (Color color) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (color == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (color.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + data.foreground = color.handle; + data.foregroundPattern = null; + data.state &= ~FOREGROUND; + data.state |= FOREGROUND_RGB; +} +/** + * Sets the foreground pattern. The default value is <code>null</code>. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * @param pattern the new foreground pattern + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the parameter has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see Pattern + * @see #getAdvanced + * @see #setAdvanced + * + * @since 3.1 + */ +public void setForegroundPattern(Pattern pattern) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pattern != null && pattern.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (data.cairo == 0 && pattern == null) return; + initCairo(); + if (data.foregroundPattern == pattern) return; + data.foregroundPattern = pattern; + data.state &= ~FOREGROUND; +} +/** + * Sets the receiver's interpolation setting to the parameter, which + * must be one of <code>SWT.DEFAULT</code>, <code>SWT.NONE</code>, + * <code>SWT.LOW</code> or <code>SWT.HIGH</code>. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * + * @param interpolation the new interpolation setting + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the rule is not one of <code>SWT.DEFAULT</code>, + * <code>SWT.NONE</code>, <code>SWT.LOW</code> or <code>SWT.HIGH</code> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see #getAdvanced + * @see #setAdvanced + * + * @since 3.1 + */ +public void setInterpolation(int interpolation) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.cairo == 0 && interpolation == SWT.DEFAULT) return; + switch (interpolation) { + case SWT.DEFAULT: + case SWT.NONE: + case SWT.LOW: + case SWT.HIGH: + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + initCairo(); + data.interpolation = interpolation; +} +/** + * Sets the receiver's line attributes. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * @param attributes the line attributes + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the attributes is null</li> + * <li>ERROR_INVALID_ARGUMENT - if any of the line attributes is not valid</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see LineAttributes + * @see #getAdvanced + * @see #setAdvanced + * + * @since 3.3 + */ +public void setLineAttributes(LineAttributes attributes) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (attributes == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int mask = 0; + float lineWidth = attributes.width; + if (lineWidth != data.lineWidth) { + mask |= LINE_WIDTH | DRAW_OFFSET; + } + int lineStyle = attributes.style; + if (lineStyle != data.lineStyle) { + mask |= LINE_STYLE; + switch (lineStyle) { + case SWT.LINE_SOLID: + case SWT.LINE_DASH: + case SWT.LINE_DOT: + case SWT.LINE_DASHDOT: + case SWT.LINE_DASHDOTDOT: + break; + case SWT.LINE_CUSTOM: + if (attributes.dash == null) lineStyle = SWT.LINE_SOLID; + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + } + int join = attributes.join; + if (join != data.lineJoin) { + mask |= LINE_JOIN; + switch (join) { + case SWT.CAP_ROUND: + case SWT.CAP_FLAT: + case SWT.CAP_SQUARE: + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + } + int cap = attributes.cap; + if (cap != data.lineCap) { + mask |= LINE_CAP; + switch (cap) { + case SWT.JOIN_MITER: + case SWT.JOIN_ROUND: + case SWT.JOIN_BEVEL: + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + } + float[] dashes = attributes.dash; + float[] lineDashes = data.lineDashes; + if (dashes != null && dashes.length > 0) { + boolean changed = lineDashes == null || lineDashes.length != dashes.length; + for (int i = 0; i < dashes.length; i++) { + float dash = dashes[i]; + if (dash <= 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (!changed && lineDashes[i] != dash) changed = true; + } + if (changed) { + float[] newDashes = new float[dashes.length]; + System.arraycopy(dashes, 0, newDashes, 0, dashes.length); + dashes = newDashes; + mask |= LINE_STYLE; + } else { + dashes = lineDashes; + } + } else { + if (lineDashes != null && lineDashes.length > 0) { + mask |= LINE_STYLE; + } else { + dashes = lineDashes; + } + } + float dashOffset = attributes.dashOffset; + if (dashOffset != data.lineDashesOffset) { + mask |= LINE_STYLE; + } + float miterLimit = attributes.miterLimit; + if (miterLimit != data.lineMiterLimit) { + mask |= LINE_MITERLIMIT; + } + initCairo(); + if (mask == 0) return; + data.lineWidth = lineWidth; + data.lineStyle = lineStyle; + data.lineCap = cap; + data.lineJoin = join; + data.lineDashes = dashes; + data.lineDashesOffset = dashOffset; + data.lineMiterLimit = miterLimit; + data.state &= ~mask; +} +/** + * Sets the receiver's line cap style to the argument, which must be one + * of the constants <code>SWT.CAP_FLAT</code>, <code>SWT.CAP_ROUND</code>, + * or <code>SWT.CAP_SQUARE</code>. + * + * @param cap the cap style to be used for drawing lines + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the style is not valid</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void setLineCap(int cap) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineCap == cap) return; + switch (cap) { + case SWT.CAP_ROUND: + case SWT.CAP_FLAT: + case SWT.CAP_SQUARE: + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + data.lineCap = cap; + data.state &= ~LINE_CAP; +} +/** + * Sets the receiver's line dash style to the argument. The default + * value is <code>null</code>. If the argument is not <code>null</code>, + * the receiver's line style is set to <code>SWT.LINE_CUSTOM</code>, otherwise + * it is set to <code>SWT.LINE_SOLID</code>. + * + * @param dashes the dash style to be used for drawing lines + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if any of the values in the array is less than or equal 0</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void setLineDash(int[] dashes) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + float[] lineDashes = data.lineDashes; + if (dashes != null && dashes.length > 0) { + boolean changed = data.lineStyle != SWT.LINE_CUSTOM || lineDashes == null || lineDashes.length != dashes.length; + for (int i = 0; i < dashes.length; i++) { + int dash = dashes[i]; + if (dash <= 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (!changed && lineDashes[i] != dash) changed = true; + } + if (!changed) return; + data.lineDashes = new float[dashes.length]; + for (int i = 0; i < dashes.length; i++) { + data.lineDashes[i] = dashes[i]; + } + data.lineStyle = SWT.LINE_CUSTOM; + } else { + if (data.lineStyle == SWT.LINE_SOLID && (lineDashes == null || lineDashes.length == 0)) return; + data.lineDashes = null; + data.lineStyle = SWT.LINE_SOLID; + } + data.state &= ~LINE_STYLE; +} +/** + * Sets the receiver's line join style to the argument, which must be one + * of the constants <code>SWT.JOIN_MITER</code>, <code>SWT.JOIN_ROUND</code>, + * or <code>SWT.JOIN_BEVEL</code>. + * + * @param join the join style to be used for drawing lines + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the style is not valid</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void setLineJoin(int join) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineJoin == join) return; + switch (join) { + case SWT.JOIN_MITER: + case SWT.JOIN_ROUND: + case SWT.JOIN_BEVEL: + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + data.lineJoin = join; + data.state &= ~LINE_JOIN; +} +/** + * Sets the receiver's line style to the argument, which must be one + * of the constants <code>SWT.LINE_SOLID</code>, <code>SWT.LINE_DASH</code>, + * <code>SWT.LINE_DOT</code>, <code>SWT.LINE_DASHDOT</code> or + * <code>SWT.LINE_DASHDOTDOT</code>. + * + * @param lineStyle the style to be used for drawing lines + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the style is not valid</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setLineStyle(int lineStyle) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineStyle == lineStyle) return; + switch (lineStyle) { + case SWT.LINE_SOLID: + case SWT.LINE_DASH: + case SWT.LINE_DOT: + case SWT.LINE_DASHDOT: + case SWT.LINE_DASHDOTDOT: + break; + case SWT.LINE_CUSTOM: + if (data.lineDashes == null) lineStyle = SWT.LINE_SOLID; + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + data.lineStyle = lineStyle; + data.state &= ~LINE_STYLE; +} +/** + * Sets the width that will be used when drawing lines + * for all of the figure drawing operations (that is, + * <code>drawLine</code>, <code>drawRectangle</code>, + * <code>drawPolyline</code>, and so forth. + * <p> + * Note that line width of zero is used as a hint to + * indicate that the fastest possible line drawing + * algorithms should be used. This means that the + * output may be different from line width one. + * </p> + * + * @param lineWidth the width of a line + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setLineWidth(int lineWidth) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineWidth == lineWidth) return; + data.lineWidth = lineWidth; + data.state &= ~(LINE_WIDTH | DRAW_OFFSET); +} +void setString(String string) { + if (string == data.string) return; + if (data.xmString != 0) OS.XmStringFree(data.xmString); + byte[] buffer = Converter.wcsToMbcs(getCodePage (), string, true); + data.xmString = OS.XmStringCreate(buffer, OS.XmFONTLIST_DEFAULT_TAG); + data.string = string; + data.stringWidth = data.stringHeight = -1; +} +void setText(String string, int flags) { + if (data.renderTable == 0) createRenderTable(); + if (string == data.text && (flags & ~SWT.DRAW_TRANSPARENT) == (data.drawFlags & ~SWT.DRAW_TRANSPARENT)) { + return; + } + if (data.xmText != 0) OS.XmStringFree(data.xmText); + if (data.xmMnemonic != 0) OS.XmStringFree(data.xmMnemonic); + char mnemonic = 0; + int tableLength = 0; + Device device = data.device; + int[] parseTable = new int[2]; + char[] text = new char[string.length()]; + string.getChars(0, text.length, text, 0); + if ((flags & SWT.DRAW_DELIMITER) != 0) parseTable[tableLength++] = device.crMapping; + if ((flags & SWT.DRAW_TAB) != 0) parseTable[tableLength++] = device.tabMapping; + if ((flags & SWT.DRAW_MNEMONIC) != 0) mnemonic = fixMnemonic(text); + String codePage = getCodePage(); + byte[] buffer = Converter.wcsToMbcs(codePage, text, true); + data.xmText = OS.XmStringParseText(buffer, 0, OS.XmFONTLIST_DEFAULT_TAG, OS.XmCHARSET_TEXT, parseTable, tableLength, 0); + if (mnemonic != 0) { + byte [] buffer1 = Converter.wcsToMbcs(codePage, new char[]{mnemonic}, true); + data.xmMnemonic = OS.XmStringCreate (buffer1, OS.XmFONTLIST_DEFAULT_TAG); + } else { + data.xmMnemonic = 0; + } + data.text = string; + data.textWidth = data.textHeight = -1; + data.drawFlags = flags; +} +/** + * Sets the receiver's text anti-aliasing value to the parameter, + * which must be one of <code>SWT.DEFAULT</code>, <code>SWT.OFF</code> + * or <code>SWT.ON</code>. Note that this controls anti-aliasing only + * for all <em>text drawing</em> operations. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * + * @param antialias the anti-aliasing setting + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the parameter is not one of <code>SWT.DEFAULT</code>, + * <code>SWT.OFF</code> or <code>SWT.ON</code></li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see #getAdvanced + * @see #setAdvanced + * @see #setAntialias + * + * @since 3.1 + */ +public void setTextAntialias(int antialias) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.cairo == 0 && antialias == SWT.DEFAULT) return; + int mode = 0; + switch (antialias) { + case SWT.DEFAULT: mode = Cairo.CAIRO_ANTIALIAS_DEFAULT; break; + case SWT.OFF: mode = Cairo.CAIRO_ANTIALIAS_NONE; break; + case SWT.ON: mode = Cairo.CAIRO_ANTIALIAS_GRAY; + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + initCairo(); + int /*long*/ options = Cairo.cairo_font_options_create(); + Cairo.cairo_font_options_set_antialias(options, mode); + Cairo.cairo_set_font_options(data.cairo, options); + Cairo.cairo_font_options_destroy(options); +} +/** + * Sets the transform that is currently being used by the receiver. If + * the argument is <code>null</code>, the current transform is set to + * the identity transform. + * <p> + * This operation requires the operating system's advanced + * graphics subsystem which may not be available on some + * platforms. + * </p> + * + * @param transform the transform to set + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the parameter has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_NO_GRAPHICS_LIBRARY - if advanced graphics are not available</li> + * </ul> + * + * @see Transform + * @see #getAdvanced + * @see #setAdvanced + * + * @since 3.1 + */ +public void setTransform(Transform transform) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (transform != null && transform.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (data.cairo == 0 && transform == null) return; + initCairo(); + int /*long*/ cairo = data.cairo; + if (transform != null) { + Cairo.cairo_set_matrix(cairo, transform.handle); + } else { + Cairo.cairo_identity_matrix(cairo); + } + data.state &= ~DRAW_OFFSET; +} +/** + * If the argument is <code>true</code>, puts the receiver + * in a drawing mode where the resulting color in the destination + * is the <em>exclusive or</em> of the color values in the source + * and the destination, and if the argument is <code>false</code>, + * puts the receiver in a drawing mode where the destination color + * is replaced with the source color value. + * <p> + * Note that this mode in fundamentally unsupportable on certain + * platforms, notably Carbon (Mac OS X). Clients that want their + * code to run on all platforms need to avoid this method. + * </p> + * + * @param xor if <code>true</code>, then <em>xor</em> mode is used, otherwise <em>source copy</em> mode is used + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @deprecated this functionality is not supported on some platforms + */ +public void setXORMode(boolean xor) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + OS.XSetFunction(data.display, handle, xor ? OS.GXxor : OS.GXcopy); +} +/** + * Returns the extent of the given string. No tab + * expansion or carriage return processing will be performed. + * <p> + * The <em>extent</em> of a string is the width and height of + * the rectangular area it would cover if drawn in a particular + * font (in this case, the current font in the receiver). + * </p> + * + * @param string the string to measure + * @return a point containing the extent of the string + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the string is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Point stringExtent(String string) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (string == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + checkGC(FONT); + byte[] buffer = Converter.wcsToMbcs(null, string, true); + cairo_font_extents_t font_extents = new cairo_font_extents_t(); + Cairo.cairo_font_extents(cairo, font_extents); + cairo_text_extents_t extents = new cairo_text_extents_t(); + Cairo.cairo_text_extents(cairo, buffer, extents); + return new Point((int)extents.width, (int)font_extents.height); + } + setString(string); + checkGC(FONT); + if (data.stringWidth != -1) return new Point(data.stringWidth, data.stringHeight); + int width, height; + if (string.length() == 0) { + width = 0; + height = getFontHeight(); + } else { + int fontList = data.font.handle; + int xmString = data.xmString; + width = OS.XmStringWidth(fontList, xmString); + height = OS.XmStringHeight(fontList, xmString); + } + return new Point(data.stringWidth = width, data.stringHeight = height); +} +/** + * Returns the extent of the given string. Tab expansion and + * carriage return processing are performed. + * <p> + * The <em>extent</em> of a string is the width and height of + * the rectangular area it would cover if drawn in a particular + * font (in this case, the current font in the receiver). + * </p> + * + * @param string the string to measure + * @return a point containing the extent of the string + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the string is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Point textExtent(String string) { + return textExtent(string, SWT.DRAW_DELIMITER | SWT.DRAW_TAB); +} +/** + * Returns the extent of the given string. Tab expansion, line + * delimiter and mnemonic processing are performed according to + * the specified flags, which can be a combination of: + * <dl> + * <dt><b>DRAW_DELIMITER</b></dt> + * <dd>draw multiple lines</dd> + * <dt><b>DRAW_TAB</b></dt> + * <dd>expand tabs</dd> + * <dt><b>DRAW_MNEMONIC</b></dt> + * <dd>underline the mnemonic character</dd> + * <dt><b>DRAW_TRANSPARENT</b></dt> + * <dd>transparent background</dd> + * </dl> + * <p> + * The <em>extent</em> of a string is the width and height of + * the rectangular area it would cover if drawn in a particular + * font (in this case, the current font in the receiver). + * </p> + * + * @param string the string to measure + * @param flags the flags specifying how to process the text + * @return a point containing the extent of the string + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the string is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Point textExtent(String string, int flags) { + if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (string == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int /*long*/ cairo = data.cairo; + if (cairo != 0) { + //TODO - honor flags + checkGC(FONT); + byte[] buffer = Converter.wcsToMbcs(null, string, true); + cairo_font_extents_t font_extents = new cairo_font_extents_t(); + Cairo.cairo_font_extents(cairo, font_extents); + cairo_text_extents_t extents = new cairo_text_extents_t(); + Cairo.cairo_text_extents(cairo, buffer, extents); + return new Point((int)extents.width, (int)font_extents.height); + } + setText(string, flags); + checkGC(FONT); + if (data.textWidth != -1) return new Point(data.textWidth, data.textHeight); + int width, height; + if (string.length() == 0) { + width = 0; + height = getFontHeight(); + } else { + int fontList = data.font.handle; + int xmText = data.xmText; + width = OS.XmStringWidth(fontList, xmText); + height = OS.XmStringHeight(fontList, xmText); + } + return new Point(data.textWidth = width, data.textHeight = height); +} +/** + * Returns a string containing a concise, human-readable + * description of the receiver. + * + * @return a string representation of the receiver + */ +public String toString () { + if (isDisposed()) return "GC {*DISPOSED*}"; + return "GC {" + handle + "}"; +} +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/GCData.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/GCData.java new file mode 100755 index 0000000000..8d6836cd9a --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/GCData.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +import org.eclipse.swt.*; +import org.eclipse.swt.internal.motif.*; + +/** + * Instances of this class are descriptions of GCs in terms + * of unallocated platform-specific data fields. + * <p> + * <b>IMPORTANT:</b> This class is <em>not</em> part of the public + * API for SWT. 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. + * </p> + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + * @noinstantiate This class is not intended to be instantiated by clients. + */ +public final class GCData { + public Device device; + public int style, state = -1; + public XColor foreground; + public XColor background; + public Pattern foregroundPattern; + public Pattern backgroundPattern; + public Font font; + public int clipRgn; + public int lineStyle = SWT.LINE_SOLID; + public float lineWidth; + public int lineCap = SWT.CAP_FLAT; + public int lineJoin = SWT.JOIN_MITER; + public float[] lineDashes; + public float lineDashesOffset; + public float lineMiterLimit = 10; + public int alpha = 0xFF; + public int interpolation = SWT.DEFAULT; + + public int renderTable; + public int damageRgn; + public int colormap; + public Image backgroundImage; + public Image image; + public int display; + public int drawable; + public int /*long*/ cairo; + public double cairoXoffset, cairoYoffset; + public double[] clippingTransform; + public String string; + public int stringWidth = -1; + public int stringHeight = -1; + public int xmString; + public String text; + public int textWidth = -1; + public int textHeight = -1; + public int xmText, xmMnemonic; + public int drawFlags; +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Image.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Image.java new file mode 100755 index 0000000000..6aa4d87995 --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Image.java @@ -0,0 +1,1429 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +import org.eclipse.swt.internal.cairo.*; +import org.eclipse.swt.internal.motif.*; +import org.eclipse.swt.*; +import java.io.*; + +/** + * Instances of this class are graphics which have been prepared + * for display on a specific device. That is, they are ready + * to paint using methods such as <code>GC.drawImage()</code> + * and display on widgets with, for example, <code>Button.setImage()</code>. + * <p> + * If loaded from a file format that supports it, an + * <code>Image</code> may have transparency, meaning that certain + * pixels are specified as being transparent when drawn. Examples + * of file formats that support transparency are GIF and PNG. + * </p><p> + * There are two primary ways to use <code>Images</code>. + * The first is to load a graphic file from disk and create an + * <code>Image</code> from it. This is done using an <code>Image</code> + * constructor, for example: + * <pre> + * Image i = new Image(device, "C:\\graphic.bmp"); + * </pre> + * A graphic file may contain a color table specifying which + * colors the image was intended to possess. In the above example, + * these colors will be mapped to the closest available color in + * SWT. It is possible to get more control over the mapping of + * colors as the image is being created, using code of the form: + * <pre> + * ImageData data = new ImageData("C:\\graphic.bmp"); + * RGB[] rgbs = data.getRGBs(); + * // At this point, rgbs contains specifications of all + * // the colors contained within this image. You may + * // allocate as many of these colors as you wish by + * // using the Color constructor Color(RGB), then + * // create the image: + * Image i = new Image(device, data); + * </pre> + * <p> + * Applications which require even greater control over the image + * loading process should use the support provided in class + * <code>ImageLoader</code>. + * </p><p> + * Application code must explicitly invoke the <code>Image.dispose()</code> + * method to release the operating system resources managed by each instance + * when those instances are no longer required. + * </p> + * + * @see Color + * @see ImageData + * @see ImageLoader + * @see <a href="http://www.eclipse.org/swt/snippets/#image">Image snippets</a> + * @see <a href="http://www.eclipse.org/swt/examples.php">SWT Examples: GraphicsExample, ImageAnalyzer</a> + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + */ +public final class Image extends Resource implements Drawable { + /** + * specifies whether the receiver is a bitmap or an icon + * (one of <code>SWT.BITMAP</code>, <code>SWT.ICON</code>) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int type; + + /** + * The handle to the OS pixmap resource. + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int pixmap; + + /** + * The handle to the OS mask resource. + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int mask; + + int /*long*/ surface; + + /** + * specifies the transparent pixel + */ + int transparentPixel = -1; + + /** + * The GC the image is currently selected in. + */ + GC memGC; + + /** + * The alpha data of the image. + */ + byte[] alphaData; + + /** + * The global alpha value to be used for every pixel. + */ + int alpha = -1; + + /** + * The width of the image. + */ + int width = -1; + + /** + * The height of the image. + */ + int height = -1; + + /** + * Specifies the default scanline padding. + */ + static final int DEFAULT_SCANLINE_PAD = 4; + +Image(Device device) { + super(device); +} +/** + * Constructs an empty instance of this class with the + * specified width and height. The result may be drawn upon + * by creating a GC and using any of its drawing operations, + * as shown in the following example: + * <pre> + * Image i = new Image(device, width, height); + * GC gc = new GC(i); + * gc.drawRectangle(0, 0, 50, 50); + * gc.dispose(); + * </pre> + * <p> + * Note: Some platforms may have a limitation on the size + * of image that can be created (size depends on width, height, + * and depth). For example, Windows 95, 98, and ME do not allow + * images larger than 16M. + * </p> + * + * @param device the device on which to create the image + * @param width the width of the new image + * @param height the height of the new image + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_INVALID_ARGUMENT - if either the width or height is negative or zero</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for image creation</li> + * </ul> + */ +public Image(Device device, int width, int height) { + super(device); + init(width, height); + init(); +} +/** + * Constructs a new instance of this class based on the + * provided image, with an appearance that varies depending + * on the value of the flag. The possible flag values are: + * <dl> + * <dt><b>{@link SWT#IMAGE_COPY}</b></dt> + * <dd>the result is an identical copy of srcImage</dd> + * <dt><b>{@link SWT#IMAGE_DISABLE}</b></dt> + * <dd>the result is a copy of srcImage which has a <em>disabled</em> look</dd> + * <dt><b>{@link SWT#IMAGE_GRAY}</b></dt> + * <dd>the result is a copy of srcImage which has a <em>gray scale</em> look</dd> + * </dl> + * + * @param device the device on which to create the image + * @param srcImage the image to use as the source + * @param flag the style, either <code>IMAGE_COPY</code>, <code>IMAGE_DISABLE</code> or <code>IMAGE_GRAY</code> + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if srcImage is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the flag is not one of <code>IMAGE_COPY</code>, <code>IMAGE_DISABLE</code> or <code>IMAGE_GRAY</code></li> + * <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_INVALID_IMAGE - if the image is not a bitmap or an icon, or is otherwise in an invalid state</li> + * <li>ERROR_UNSUPPORTED_DEPTH - if the depth of the image is not supported</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for image creation</li> + * </ul> + */ +public Image(Device device, Image srcImage, int flag) { + super(device); + device = this.device; + if (srcImage == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (srcImage.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + int xDisplay = device.xDisplay; + this.type = srcImage.type; + this.mask = 0; + int[] unused = new int[1]; + int[] w = new int[1]; + int[] h = new int[1]; + OS.XGetGeometry(xDisplay, srcImage.pixmap, unused, unused, unused, w, h, unused, unused); + int width = w[0]; + int height = h[0]; + int drawable = OS.XDefaultRootWindow(xDisplay); + /* Don't create the mask here if flag is SWT.IMAGE_GRAY. See below.*/ + if (flag != SWT.IMAGE_GRAY && ((srcImage.type == SWT.ICON && srcImage.mask != 0) || srcImage.transparentPixel != -1)) { + /* Generate the mask if necessary. */ + if (srcImage.transparentPixel != -1) srcImage.createMask(); + int mask = OS.XCreatePixmap(xDisplay, drawable, width, height, 1); + int gc = OS.XCreateGC(xDisplay, mask, 0, null); + OS.XCopyArea(xDisplay, srcImage.mask, mask, gc, 0, 0, width, height, 0, 0); + OS.XFreeGC(xDisplay, gc); + this.mask = mask; + /* Destroy the image mask if the there is a GC created on the image */ + if (srcImage.transparentPixel != -1 && srcImage.memGC != null) srcImage.destroyMask(); + } + switch (flag) { + case SWT.IMAGE_COPY: + int[] depth = new int[1]; + OS.XGetGeometry(xDisplay, srcImage.pixmap, unused, unused, unused, unused, unused, unused, depth); + int pixmap = OS.XCreatePixmap(xDisplay, drawable, width, height, depth[0]); + int gc = OS.XCreateGC(xDisplay, pixmap, 0, null); + OS.XCopyArea(xDisplay, srcImage.pixmap, pixmap, gc, 0, 0, width, height, 0, 0); + OS.XFreeGC(xDisplay, gc); + this.pixmap = pixmap; + transparentPixel = srcImage.transparentPixel; + alpha = srcImage.alpha; + if (srcImage.alphaData != null) { + alphaData = new byte[srcImage.alphaData.length]; + System.arraycopy(srcImage.alphaData, 0, alphaData, 0, alphaData.length); + } + createAlphaMask(width, height); + break; + case SWT.IMAGE_DISABLE: + /* Get src image data */ + XImage srcXImage = new XImage(); + int srcXImagePtr = OS.XGetImage(xDisplay, srcImage.pixmap, 0, 0, width, height, OS.AllPlanes, OS.ZPixmap); + OS.memmove(srcXImage, srcXImagePtr, XImage.sizeof); + byte[] srcData = new byte[srcXImage.bytes_per_line * srcXImage.height]; + OS.memmove(srcData, srcXImage.data, srcData.length); + /* Create destination image */ + int destPixmap = OS.XCreatePixmap(xDisplay, drawable, width, height, srcXImage.depth); + int visualPtr = OS.XDefaultVisual(xDisplay, OS.XDefaultScreen(xDisplay)); + int screenDepth = OS.XDefaultDepthOfScreen(OS.XDefaultScreenOfDisplay(xDisplay)); + int destXImagePtr = OS.XCreateImage(xDisplay, visualPtr, screenDepth, OS.ZPixmap, 0, 0, width, height, srcXImage.bitmap_pad, 0); + XImage destXImage = new XImage(); + OS.memmove(destXImage, destXImagePtr, XImage.sizeof); + int bufSize = destXImage.bytes_per_line * destXImage.height; + int bufPtr = OS.XtMalloc(bufSize); + destXImage.data = bufPtr; + OS.memmove(destXImagePtr, destXImage, XImage.sizeof); + byte[] destData = new byte[bufSize]; + /* Find the colors to map to */ + Color zeroColor = device.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW); + Color oneColor = device.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); + int zeroPixel = zeroColor.handle.pixel; + int onePixel = oneColor.handle.pixel; + switch (srcXImage.bits_per_pixel) { + case 1: + /* + * Nothing we can reasonably do here except copy + * the bitmap; we can't make it a higher color depth. + * Short-circuit the rest of the code and return. + */ + gc = OS.XCreateGC(xDisplay, drawable, 0, null); + pixmap = OS.XCreatePixmap(xDisplay, drawable, width, height, 1); + OS.XCopyArea(xDisplay, srcImage.pixmap, pixmap, gc, 0, 0, width, height, 0, 0); + OS.XDestroyImage(srcXImagePtr); + OS.XDestroyImage(destXImagePtr); + OS.XFreeGC(xDisplay, gc); + return; + case 4: + SWT.error(SWT.ERROR_NOT_IMPLEMENTED); + break; + case 8: + int index = 0; + int srcPixel, r, g, b; + XColor[] colors = new XColor[256]; + int colormap = OS.XDefaultColormap(xDisplay, OS.XDefaultScreen(xDisplay)); + for (int y = 0; y < srcXImage.height; y++) { + for (int x = 0; x < srcXImage.bytes_per_line; x++) { + srcPixel = srcData[index + x] & 0xFF; + /* Get the RGB values of srcPixel */ + if (colors[srcPixel] == null) { + XColor color = new XColor(); + color.pixel = srcPixel; + OS.XQueryColor(xDisplay, colormap, color); + colors[srcPixel] = color; + } + XColor xColor = colors[srcPixel]; + r = (xColor.red >> 8) & 0xFF; + g = (xColor.green >> 8) & 0xFF; + b = (xColor.blue >> 8) & 0xFF; + /* See if the rgb maps to 0 or 1 */ + if ((r * r + g * g + b * b) < 98304) { + /* Map down to 0 */ + destData[index + x] = (byte)zeroPixel; + } else { + /* Map up to 1 */ + destData[index + x] = (byte)onePixel; + } + } + index += srcXImage.bytes_per_line; + } + break; + case 16: + index = 0; + /* Get masks */ + Visual visual = new Visual(); + OS.memmove(visual, visualPtr, Visual.sizeof); + int redMask = visual.red_mask; + int greenMask = visual.green_mask; + int blueMask = visual.blue_mask; + /* Calculate mask shifts */ + int[] shift = new int[1]; + getOffsetForMask(16, redMask, srcXImage.byte_order, shift); + int rShift = 24 - shift[0]; + getOffsetForMask(16, greenMask, srcXImage.byte_order, shift); + int gShift = 24 - shift[0]; + getOffsetForMask(16, blueMask, srcXImage.byte_order, shift); + int bShift = 24 - shift[0]; + byte zeroLow = (byte)(zeroPixel & 0xFF); + byte zeroHigh = (byte)((zeroPixel >> 8) & 0xFF); + byte oneLow = (byte)(onePixel & 0xFF); + byte oneHigh = (byte)((onePixel >> 8) & 0xFF); + for (int y = 0; y < srcXImage.height; y++) { + int xIndex = 0; + for (int x = 0; x < srcXImage.bytes_per_line; x += 2) { + srcPixel = ((srcData[index + xIndex + 1] & 0xFF) << 8) | (srcData[index + xIndex] & 0xFF); + r = (srcPixel & redMask) << rShift >> 16; + g = (srcPixel & greenMask) << gShift >> 16; + b = (srcPixel & blueMask) << bShift >> 16; + /* See if the rgb maps to 0 or 1 */ + if ((r * r + g * g + b * b) < 98304) { + /* Map down to 0 */ + destData[index + xIndex] = zeroLow; + destData[index + xIndex + 1] = zeroHigh; + } else { + /* Map up to 1 */ + destData[index + xIndex] = oneLow; + destData[index + xIndex + 1] = oneHigh; + } + xIndex += srcXImage.bits_per_pixel / 8; + } + index += srcXImage.bytes_per_line; + } + break; + case 24: + case 32: + index = 0; + /* Get masks */ + visual = new Visual(); + OS.memmove(visual, visualPtr, Visual.sizeof); + redMask = visual.red_mask; + greenMask = visual.green_mask; + blueMask = visual.blue_mask; + /* Calculate mask shifts */ + shift = new int[1]; + getOffsetForMask(srcXImage.bits_per_pixel, redMask, srcXImage.byte_order, shift); + rShift = shift[0]; + getOffsetForMask(srcXImage.bits_per_pixel, greenMask, srcXImage.byte_order, shift); + gShift = shift[0]; + getOffsetForMask(srcXImage.bits_per_pixel, blueMask, srcXImage.byte_order, shift); + bShift = shift[0]; + byte zeroR = (byte)zeroColor.getRed(); + byte zeroG = (byte)zeroColor.getGreen(); + byte zeroB = (byte)zeroColor.getBlue(); + byte oneR = (byte)oneColor.getRed(); + byte oneG = (byte)oneColor.getGreen(); + byte oneB = (byte)oneColor.getBlue(); + for (int y = 0; y < srcXImage.height; y++) { + int xIndex = 0; + for (int x = 0; x < srcXImage.width; x++) { + r = srcData[index + xIndex + rShift] & 0xFF; + g = srcData[index + xIndex + gShift] & 0xFF; + b = srcData[index + xIndex + bShift] & 0xFF; + /* See if the rgb maps to 0 or 1 */ + if ((r * r + g * g + b * b) < 98304) { + /* Map down to 0 */ + destData[index + xIndex + rShift] = zeroR; + destData[index + xIndex + gShift] = zeroG; + destData[index + xIndex + bShift] = zeroB; + } else { + /* Map up to 1 */ + destData[index + xIndex + rShift] = oneR; + destData[index + xIndex + gShift] = oneG; + destData[index + xIndex + bShift] = oneB; + } + xIndex += destXImage.bits_per_pixel / 8; + } + index += srcXImage.bytes_per_line; + } + break; + default: + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + OS.memmove(destXImage.data, destData, destData.length); + gc = OS.XCreateGC(xDisplay, destPixmap, 0, null); + OS.XPutImage(xDisplay, destPixmap, gc, destXImagePtr, 0, 0, 0, 0, width, height); + OS.XDestroyImage(destXImagePtr); + OS.XDestroyImage(srcXImagePtr); + OS.XFreeGC(xDisplay, gc); + alpha = srcImage.alpha; + if (srcImage.alphaData != null) { + alphaData = new byte[srcImage.alphaData.length]; + System.arraycopy(srcImage.alphaData, 0, alphaData, 0, alphaData.length); + } + createAlphaMask(width, height); + this.pixmap = destPixmap; + break; + case SWT.IMAGE_GRAY: + ImageData data = srcImage.getImageData(); + PaletteData palette = data.palette; + ImageData newData = data; + if (!palette.isDirect) { + /* Convert the palette entries to gray. */ + RGB [] rgbs = palette.getRGBs(); + for (int i=0; i<rgbs.length; i++) { + if (data.transparentPixel != i) { + RGB color = rgbs [i]; + int red = color.red; + int green = color.green; + int blue = color.blue; + int intensity = (red+red+green+green+green+green+green+blue) >> 3; + color.red = color.green = color.blue = intensity; + } + } + newData.palette = new PaletteData(rgbs); + } else { + /* Create a 8 bit depth image data with a gray palette. */ + RGB[] rgbs = new RGB[256]; + for (int i=0; i<rgbs.length; i++) { + rgbs[i] = new RGB(i, i, i); + } + newData = new ImageData(width, height, 8, new PaletteData(rgbs)); + newData.alpha = data.alpha; + newData.alphaData = data.alphaData; + newData.maskData = data.maskData; + newData.maskPad = data.maskPad; + if (data.transparentPixel != -1) newData.transparentPixel = 254; + + /* Convert the pixels. */ + int[] scanline = new int[width]; + int redMask = palette.redMask; + int greenMask = palette.greenMask; + int blueMask = palette.blueMask; + int redShift = palette.redShift; + int greenShift = palette.greenShift; + int blueShift = palette.blueShift; + for (int y=0; y<height; y++) { + int offset = y * newData.bytesPerLine; + data.getPixels(0, y, width, scanline, 0); + for (int x=0; x<width; x++) { + int pixel = scanline[x]; + if (pixel != data.transparentPixel) { + int red = pixel & redMask; + red = (redShift < 0) ? red >>> -redShift : red << redShift; + int green = pixel & greenMask; + green = (greenShift < 0) ? green >>> -greenShift : green << greenShift; + int blue = pixel & blueMask; + blue = (blueShift < 0) ? blue >>> -blueShift : blue << blueShift; + int intensity = (red+red+green+green+green+green+green+blue) >> 3; + if (newData.transparentPixel == intensity) intensity = 255; + newData.data[offset] = (byte)intensity; + } else { + newData.data[offset] = (byte)254; + } + offset++; + } + } + } + init (newData); + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + init(); +} +/** + * Constructs an empty instance of this class with the + * width and height of the specified rectangle. The result + * may be drawn upon by creating a GC and using any of its + * drawing operations, as shown in the following example: + * <pre> + * Image i = new Image(device, boundsRectangle); + * GC gc = new GC(i); + * gc.drawRectangle(0, 0, 50, 50); + * gc.dispose(); + * </pre> + * <p> + * Note: Some platforms may have a limitation on the size + * of image that can be created (size depends on width, height, + * and depth). For example, Windows 95, 98, and ME do not allow + * images larger than 16M. + * </p> + * + * @param device the device on which to create the image + * @param bounds a rectangle specifying the image's width and height (must not be null) + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the bounds rectangle is null</li> + * <li>ERROR_INVALID_ARGUMENT - if either the rectangle's width or height is negative</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for image creation</li> + * </ul> + */ +public Image(Device device, Rectangle bounds) { + super(device); + if (bounds == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(bounds.width, bounds.height); + init(); +} +/** + * Constructs an instance of this class from the given + * <code>ImageData</code>. + * + * @param device the device on which to create the image + * @param data the image data to create the image from (must not be null) + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the image data is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_UNSUPPORTED_DEPTH - if the depth of the ImageData is not supported</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for image creation</li> + * </ul> + */ +public Image(Device device, ImageData image) { + super(device); + init(image); + init(); +} +/** + * Constructs an instance of this class, whose type is + * <code>SWT.ICON</code>, from the two given <code>ImageData</code> + * objects. The two images must be the same size. Pixel transparency + * in either image will be ignored. + * <p> + * The mask image should contain white wherever the icon is to be visible, + * and black wherever the icon is to be transparent. In addition, + * the source image should contain black wherever the icon is to be + * transparent. + * </p> + * + * @param device the device on which to create the icon + * @param source the color data for the icon + * @param mask the mask data for the icon + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if either the source or mask is null </li> + * <li>ERROR_INVALID_ARGUMENT - if source and mask are different sizes</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for image creation</li> + * </ul> + */ +public Image(Device device, ImageData source, ImageData mask) { + super(device); + if (source == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (mask == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (source.width != mask.width || source.height != mask.height) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + mask = ImageData.convertMask(mask); + ImageData image = new ImageData(source.width, source.height, source.depth, source.palette, source.scanlinePad, source.data); + image.maskPad = mask.scanlinePad; + image.maskData = mask.data; + init(image); + init(); +} +/** + * Constructs an instance of this class by loading its representation + * from the specified input stream. Throws an error if an error + * occurs while loading the image, or if the result is an image + * of an unsupported type. Application code is still responsible + * for closing the input stream. + * <p> + * This constructor is provided for convenience when loading a single + * image only. If the stream contains multiple images, only the first + * one will be loaded. To load multiple images, use + * <code>ImageLoader.load()</code>. + * </p><p> + * This constructor may be used to load a resource as follows: + * </p> + * <pre> + * static Image loadImage (Display display, Class clazz, String string) { + * InputStream stream = clazz.getResourceAsStream (string); + * if (stream == null) return null; + * Image image = null; + * try { + * image = new Image (display, stream); + * } catch (SWTException ex) { + * } finally { + * try { + * stream.close (); + * } catch (IOException ex) {} + * } + * return image; + * } + * </pre> + * + * @param device the device on which to create the image + * @param stream the input stream to load the image from + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the stream is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_IO - if an IO error occurs while reading from the stream</li> + * <li>ERROR_INVALID_IMAGE - if the image stream contains invalid data </li> + * <li>ERROR_UNSUPPORTED_DEPTH - if the image stream describes an image with an unsupported depth</li> + * <li>ERROR_UNSUPPORTED_FORMAT - if the image stream contains an unrecognized format</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for image creation</li> + * </ul> + */ +public Image(Device device, InputStream stream) { + super(device); + init(new ImageData(stream)); + init(); +} +/** + * Constructs an instance of this class by loading its representation + * from the file with the specified name. Throws an error if an error + * occurs while loading the image, or if the result is an image + * of an unsupported type. + * <p> + * This constructor is provided for convenience when loading + * a single image only. If the specified file contains + * multiple images, only the first one will be used. + * + * @param device the device on which to create the image + * @param filename the name of the file to load the image from + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * <li>ERROR_NULL_ARGUMENT - if the file name is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_IO - if an IO error occurs while reading from the file</li> + * <li>ERROR_INVALID_IMAGE - if the image file contains invalid data </li> + * <li>ERROR_UNSUPPORTED_DEPTH - if the image file describes an image with an unsupported depth</li> + * <li>ERROR_UNSUPPORTED_FORMAT - if the image file contains an unrecognized format</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for image creation</li> + * </ul> + */ +public Image(Device device, String filename) { + super(device); + init(new ImageData(filename)); + init(); +} +void createAlphaMask(int width, int height) { + if (device.useXRender && (alpha != -1 || alphaData != null)) { + int xDisplay = device.xDisplay; + int drawable = OS.XDefaultRootWindow(xDisplay); + mask = OS.XCreatePixmap(xDisplay, drawable, alpha != -1 ? 1 : width, alpha != -1 ? 1 : height, 8); + if (mask == 0) SWT.error(SWT.ERROR_NO_HANDLES); + int gc = OS.XCreateGC(xDisplay, mask, 0, null); + if (alpha != -1) { + OS.XSetForeground(xDisplay, gc, (alpha & 0xFF) << 8 | (alpha & 0xFF)); + OS.XFillRectangle(xDisplay, mask, gc, 0, 0, 1, 1); + } else { + int imagePtr = OS.XGetImage(xDisplay, mask, 0, 0, width, height, OS.AllPlanes, OS.ZPixmap); + XImage xImage = new XImage(); + OS.memmove(xImage, imagePtr, XImage.sizeof); + if (xImage.bytes_per_line == width) { + OS.memmove(xImage.data, alphaData, alphaData.length); + } else { + byte[] line = new byte[xImage.bytes_per_line]; + for (int y = 0; y < height; y++) { + System.arraycopy(alphaData, width * y, line, 0, width); + OS.memmove(xImage.data + (xImage.bytes_per_line * y), line, xImage.bytes_per_line); + } + } + OS.XPutImage(xDisplay, mask, gc, imagePtr, 0, 0, 0, 0, width, height); + OS.XDestroyImage(imagePtr); + } + OS.XFreeGC(xDisplay, gc); + } +} +/** + * Create the receiver's mask if necessary. + */ +void createMask() { + if (mask != 0) return; + int xDisplay = device.xDisplay; + int drawable = OS.XDefaultRootWindow(xDisplay); + int screenDepth = OS.XDefaultDepthOfScreen(OS.XDefaultScreenOfDisplay(xDisplay)); + int visual = OS.XDefaultVisual(xDisplay, OS.XDefaultScreen(xDisplay)); + ImageData maskImage = getImageData().getTransparencyMask(); + int maskPixmap = OS.XCreatePixmap(xDisplay, drawable, maskImage.width, maskImage.height, 1); + XColor[] xcolors = device.xcolors; + int gc = OS.XCreateGC(xDisplay, maskPixmap, 0, null); + Image.putImage(maskImage, 0, 0, maskImage.width, maskImage.height, 0, 0, maskImage.width, maskImage.height, xDisplay, visual, screenDepth, xcolors, null, true, maskPixmap, gc); + OS.XFreeGC(xDisplay, gc); + this.mask = maskPixmap; +} +void createSurface() { + if (surface != 0) return; + int [] unused = new int [1]; int [] width = new int [1]; int [] height = new int [1]; + OS.XGetGeometry (device.xDisplay, pixmap, unused, unused, unused, width, height, unused, unused); + int xDisplay = device.xDisplay; + int xDrawable = pixmap; + int xVisual = OS.XDefaultVisual(xDisplay, OS.XDefaultScreen(xDisplay)); + surface = Cairo.cairo_xlib_surface_create(xDisplay, xDrawable, xVisual, width[0], height[0]); +} +void destroy() { + if (memGC != null) memGC.dispose(); + int xDisplay = device.xDisplay; + if (pixmap != 0) OS.XFreePixmap (xDisplay, pixmap); + if (mask != 0) OS.XFreePixmap (xDisplay, mask); + if (surface != 0) Cairo.cairo_surface_destroy(surface); + surface = pixmap = mask = 0; + memGC = null; +} +/** + * Destroy the receiver's mask if it exists. + */ +void destroyMask() { + if (mask == 0) return; + OS.XFreePixmap (device.xDisplay, mask); + mask = 0; +} +/** + * Compares the argument to the receiver, and returns true + * if they represent the <em>same</em> object using a class + * specific comparison. + * + * @param object the object to compare with this object + * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise + * + * @see #hashCode + */ +public boolean equals (Object object) { + if (object == this) return true; + if (!(object instanceof Image)) return false; + Image image = (Image)object; + return device == image.device && pixmap == image.pixmap; +} +/** + * Returns the color to which to map the transparent pixel, or null if + * the receiver has no transparent pixel. + * <p> + * There are certain uses of Images that do not support transparency + * (for example, setting an image into a button or label). In these cases, + * it may be desired to simulate transparency by using the background + * color of the widget to paint the transparent pixels of the image. + * Use this method to check which color will be used in these cases + * in place of transparency. This value may be set with setBackground(). + * <p> + * + * @return the background color of the image, or null if there is no transparency in the image + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Color getBackground() { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (transparentPixel == -1) return null; + XColor xColor = new XColor(); + xColor.pixel = transparentPixel; + int xDisplay = device.xDisplay; + int colormap = OS.XDefaultColormap(xDisplay, OS.XDefaultScreen(xDisplay)); + OS.XQueryColor(xDisplay, colormap, xColor); + return Color.motif_new(device, xColor); +} +/** + * Returns the bounds of the receiver. The rectangle will always + * have x and y values of 0, and the width and height of the + * image. + * + * @return a rectangle specifying the image's bounds + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_INVALID_IMAGE - if the image is not a bitmap or an icon</li> + * </ul> + */ +public Rectangle getBounds () { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width != -1 && height != -1) { + return new Rectangle(0, 0, width, height); + } + int [] unused = new int [1]; int [] w = new int [1]; int [] h = new int [1]; + OS.XGetGeometry (device.xDisplay, pixmap, unused, unused, unused, w, h, unused, unused); + return new Rectangle(0, 0, width = w [0], height = h [0]); +} +/** + * Returns an <code>ImageData</code> based on the receiver + * Modifications made to this <code>ImageData</code> will not + * affect the Image. + * + * @return an <code>ImageData</code> containing the image's data and attributes + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * <li>ERROR_INVALID_IMAGE - if the image is not a bitmap or an icon</li> + * </ul> + * + * @see ImageData + */ +public ImageData getImageData() { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + Rectangle srcBounds = getBounds(); + int width = srcBounds.width; + int height = srcBounds.height; + int xDisplay = device.xDisplay; + int xSrcImagePtr = OS.XGetImage(xDisplay, pixmap, 0, 0, width, height, OS.AllPlanes, OS.ZPixmap); + if (xSrcImagePtr == 0) SWT.error(SWT.ERROR_NO_HANDLES); + XImage xSrcImage = new XImage(); + OS.memmove(xSrcImage, xSrcImagePtr, XImage.sizeof); + + /* Get the data and palette of the source image. */ + PaletteData palette = null; + int length = xSrcImage.bytes_per_line * xSrcImage.height; + byte[] srcData = new byte[length]; + OS.memmove(srcData, xSrcImage.data, length); + switch (xSrcImage.bits_per_pixel) { + case 1: + palette = new PaletteData(new RGB[] { + new RGB(0, 0, 0), + new RGB(255, 255, 255) + }); + break; + case 4: + /* + * We currently don't run on a 4-bit server, so 4-bit images + * should not exist. + */ + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + case 8: + /* Normalize the pixels in the source image data (by making the + * pixel values sequential starting at pixel 0). Reserve normalized + * pixel 0 so that it maps to real pixel 0. This assumes pixel 0 is + * always used in the image. + */ + byte[] normPixel = new byte[256]; + for (int index = 0; index < normPixel.length; index++) { + normPixel[index] = 0; + } + int numPixels = 1; + int index = 0; + for (int y = 0; y < xSrcImage.height; y++) { + for (int x = 0; x < xSrcImage.bytes_per_line; x++) { + int srcPixel = srcData[index + x] & 0xFF; + if (srcPixel != 0 && normPixel[srcPixel] == 0) { + normPixel[srcPixel] = (byte)numPixels++; + } + srcData[index + x] = normPixel[srcPixel]; + } + index += xSrcImage.bytes_per_line; + } + + /* Create a palette with only the RGB values used in the image. */ + int colormap = OS.XDefaultColormap(xDisplay, OS.XDefaultScreen(xDisplay)); + RGB[] rgbs = new RGB[numPixels]; + XColor color = new XColor(); + for (int srcPixel = 0; srcPixel < normPixel.length; srcPixel++) { + /* If the pixel value was used in the image, get its RGB values. */ + if (srcPixel == 0 || normPixel[srcPixel] != 0) { + color.pixel = srcPixel; + OS.XQueryColor(xDisplay, colormap, color); + int rgbIndex = normPixel[srcPixel] & 0xFF; + rgbs[rgbIndex] = new RGB((color.red >> 8) & 0xFF, (color.green >> 8) & 0xFF, (color.blue >> 8) & 0xFF); + } + } + palette = new PaletteData(rgbs); + break; + case 16: + /* Byte swap the data if necessary */ + if (xSrcImage.byte_order == OS.MSBFirst) { + for (int i = 0; i < srcData.length; i += 2) { + byte b = srcData[i]; + srcData[i] = srcData[i+1]; + srcData[i+1] = b; + } + } + break; + case 24: + break; + case 32: + /* Byte swap the data if necessary */ + if (xSrcImage.byte_order == OS.LSBFirst) { + for (int i = 0; i < srcData.length; i += 4) { + byte b = srcData[i]; + srcData[i] = srcData[i+3]; + srcData[i+3] = b; + b = srcData[i+1]; + srcData[i+1] = srcData[i+2]; + srcData[i+2] = b; + } + } + break; + default: + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + } + if (palette == null) { + /* + * For some reason, the XImage does not have the mask information. + * We must get it from the defualt visual. + */ + int visual = OS.XDefaultVisual(xDisplay, OS.XDefaultScreen(xDisplay)); + Visual v = new Visual(); + OS.memmove(v, visual, Visual.sizeof); + palette = new PaletteData(v.red_mask, v.green_mask, v.blue_mask); + } + ImageData data = new ImageData(width, height, xSrcImage.bits_per_pixel, palette, 4, srcData); + if (transparentPixel == -1 && type == SWT.ICON && mask != 0) { + /* Get the icon mask data */ + int xMaskPtr = OS.XGetImage(xDisplay, mask, 0, 0, width, height, OS.AllPlanes, OS.ZPixmap); + if (xMaskPtr == 0) SWT.error(SWT.ERROR_NO_HANDLES); + XImage xMask = new XImage(); + OS.memmove(xMask, xMaskPtr, XImage.sizeof); + byte[] maskData = new byte[xMask.bytes_per_line * xMask.height]; + OS.memmove(maskData, xMask.data, maskData.length); + OS.XDestroyImage(xMaskPtr); + int maskPad = xMask.bitmap_pad / 8; + /* Make mask scanline pad equals to 2 */ + data.maskPad = 2; + maskData = ImageData.convertPad(maskData, width, height, 1, maskPad, data.maskPad); + /* Bit swap the mask data if necessary */ + if (xMask.bitmap_bit_order == OS.LSBFirst) { + for (int i = 0; i < maskData.length; i++) { + byte b = maskData[i]; + maskData[i] = (byte)(((b & 0x01) << 7) | ((b & 0x02) << 5) | + ((b & 0x04) << 3) | ((b & 0x08) << 1) | ((b & 0x10) >> 1) | + ((b & 0x20) >> 3) | ((b & 0x40) >> 5) | ((b & 0x80) >> 7)); + } + } + data.maskData = maskData; + } + data.transparentPixel = transparentPixel; + data.alpha = alpha; + if (alpha == -1 && alphaData != null) { + data.alphaData = new byte[alphaData.length]; + System.arraycopy(alphaData, 0, data.alphaData, 0, alphaData.length); + } + OS.XDestroyImage(xSrcImagePtr); + return data; +} +/** + * Get the offset for the given mask. + * + * For 24 and 32-bit masks, the offset indicates which byte holds the + * data for the given mask (indexed from 0). + * For example, in 0x0000FF00, the byte offset is 1. + * + * For 16-bit masks, the offset indicates which bit holds the most significant + * data for the given mask (indexed from 1). + * For example, in 0x7E0, the bit offset is 11. + * + * The different semantics are necessary because 24- and 32-bit images + * have their color components aligned on byte boundaries, and 16-bit images + * do not. + */ +static boolean getOffsetForMask(int bitspp, int mask, int byteOrder, int[] poff) { + if (bitspp % 8 != 0) { + return false; + } + switch (mask) { + /* 24-bit and 32-bit masks */ + case 0x000000FF: + poff[0] = 0; + break; + case 0x0000FF00: + poff[0] = 1; + break; + case 0x00FF0000: + poff[0] = 2; + break; + case 0xFF000000: + poff[0] = 3; + break; + /* 16-bit masks */ + case 0x001F: + poff[0] = 5; + break; + case 0x03E0: + poff[0] = 10; + break; + case 0x07E0: + poff[0] = 11; + break; + case 0x7C00: + poff[0] = 15; + break; + case 0xF800: + poff[0] = 16; + break; + default: + return false; + } + if (bitspp == 16) { + return true; + } + if (poff[0] >= bitspp / 8) { + return false; + } + if (byteOrder == OS.MSBFirst) { + poff[0] = (bitspp/8 - 1) - poff[0]; + } + return true; +} +/** + * Returns an integer hash code for the receiver. Any two + * objects that return <code>true</code> when passed to + * <code>equals</code> must return the same value for this + * method. + * + * @return the receiver's hash + * + * @see #equals + */ +public int hashCode () { + return pixmap; +} +void init(int width, int height) { + if (width <= 0 || height <= 0) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + + /* Create the pixmap */ + this.type = SWT.BITMAP; + int xDisplay = device.xDisplay; + int screen = OS.XDefaultScreenOfDisplay(xDisplay); + int depth = OS.XDefaultDepthOfScreen(screen); + int screenNum = OS.XDefaultScreen(xDisplay); + int drawable = OS.XDefaultRootWindow(xDisplay); + int pixmap = OS.XCreatePixmap(xDisplay, drawable, width, height, depth); + if (pixmap == 0) SWT.error(SWT.ERROR_NO_HANDLES); + /* Fill the bitmap with white */ + int xGC = OS.XCreateGC(xDisplay, drawable, 0, null); + OS.XSetForeground(xDisplay, xGC, OS.XWhitePixel(xDisplay, screenNum)); + OS.XFillRectangle(xDisplay, pixmap, xGC, 0, 0, width, height); + OS.XFreeGC(xDisplay, xGC); + this.pixmap = pixmap; +} +void init(ImageData image) { + if (image == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int xDisplay = device.xDisplay; + int drawable = OS.XDefaultRootWindow(xDisplay); + int screenDepth = OS.XDefaultDepthOfScreen(OS.XDefaultScreenOfDisplay(xDisplay)); + int visual = OS.XDefaultVisual(xDisplay, OS.XDefaultScreen(xDisplay)); + int pixmap = OS.XCreatePixmap(xDisplay, drawable, image.width, image.height, screenDepth); + if (pixmap == 0) SWT.error(SWT.ERROR_NO_HANDLES); + int gc = OS.XCreateGC(xDisplay, pixmap, 0, null); + int[] transPixel = null; + if (image.transparentPixel != -1) transPixel = new int[]{image.transparentPixel}; + int error = putImage(image, 0, 0, image.width, image.height, 0, 0, image.width, image.height, xDisplay, visual, screenDepth, device.xcolors, transPixel, false, pixmap, gc); + OS.XFreeGC(xDisplay, gc); + if (error != 0) { + OS.XFreePixmap (xDisplay, pixmap); + SWT.error(error); + } + if (image.getTransparencyType() == SWT.TRANSPARENCY_MASK || image.transparentPixel != -1) { + if (image.transparentPixel != -1) transparentPixel = transPixel[0]; + ImageData maskImage = image.getTransparencyMask(); + int mask = OS.XCreatePixmap(xDisplay, drawable, image.width, image.height, 1); + gc = OS.XCreateGC(xDisplay, mask, 0, null); + error = putImage(maskImage, 0, 0, maskImage.width, maskImage.height, 0, 0, maskImage.width, maskImage.height, xDisplay, visual, screenDepth, device.xcolors, null, true, mask, gc); + OS.XFreeGC(xDisplay, gc); + if (error != 0) { + OS.XFreePixmap (xDisplay, pixmap); + OS.XFreePixmap (xDisplay, mask); + SWT.error(error); + } + this.mask = mask; + if (image.getTransparencyType() == SWT.TRANSPARENCY_MASK) { + this.type = SWT.ICON; + } else { + this.type = SWT.BITMAP; + } + } else { + this.type = SWT.BITMAP; + this.mask = 0; + this.alpha = image.alpha; + if (image.alpha == -1 && image.alphaData != null) { + this.alphaData = new byte[image.alphaData.length]; + System.arraycopy(image.alphaData, 0, this.alphaData, 0, alphaData.length); + } + createAlphaMask(image.width, image.height); + } + this.pixmap = pixmap; +} +/** + * Invokes platform specific functionality to allocate a new GC handle. + * <p> + * <b>IMPORTANT:</b> This method is <em>not</em> part of the public + * API for <code>Image</code>. 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. + * </p> + * + * @param data the platform specific GC data + * @return the platform specific GC handle + */ +public int internal_new_GC (GCData data) { + if (pixmap == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (type != SWT.BITMAP || memGC != null) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + int xDisplay = device.xDisplay; + int xGC = OS.XCreateGC (xDisplay, pixmap, 0, null); + if (xGC == 0) SWT.error (SWT.ERROR_NO_HANDLES); + if (data != null) { + int mask = SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT; + if ((data.style & mask) == 0) { + data.style |= SWT.LEFT_TO_RIGHT; + } + data.device = device; + data.display = xDisplay; + data.drawable = pixmap; + data.background = device.COLOR_WHITE.handle; + data.foreground = device.COLOR_BLACK.handle; + data.font = device.systemFont; + data.colormap = OS.XDefaultColormap (xDisplay, OS.XDefaultScreen (xDisplay)); + data.image = this; + } + return xGC; +} +/** + * Invokes platform specific functionality to dispose a GC handle. + * <p> + * <b>IMPORTANT:</b> This method is <em>not</em> part of the public + * API for <code>Image</code>. 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. + * </p> + * + * @param hDC the platform specific GC handle + * @param data the platform specific GC data + */ +public void internal_dispose_GC (int gc, GCData data) { + int xDisplay = 0; + if (data != null) xDisplay = data.display; + if (xDisplay == 0 && device != null) xDisplay = device.xDisplay; + if (xDisplay == 0) SWT.error (SWT.ERROR_NO_HANDLES); + OS.XFreeGC(xDisplay, gc); +} +/** + * Returns <code>true</code> if the image has been disposed, + * and <code>false</code> otherwise. + * <p> + * This method gets the dispose state for the image. + * When an image has been disposed, it is an error to + * invoke any other method using the image. + * + * @return <code>true</code> when the image is disposed and <code>false</code> otherwise + */ +public boolean isDisposed() { + return pixmap == 0; +} +public static Image motif_new(Device device, int type, int pixmap, int mask) { + Image image = new Image(device); + image.type = type; + image.pixmap = pixmap; + image.mask = mask; + return image; +} +/** + * Put a device-independent image of any depth into a drawable of any depth, + * stretching if necessary. + */ +static int putImage(ImageData image, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, int display, int visual, int screenDepth, XColor[] xcolors, int[] transparentPixel, boolean isMask, int drawable, int gc) { + PaletteData palette = image.palette; + if (!(((image.depth == 1 || image.depth == 2 || image.depth == 4 || image.depth == 8) && !palette.isDirect) || + ((image.depth == 8) || (image.depth == 16 || image.depth == 24 || image.depth == 32) && palette.isDirect))) + return SWT.ERROR_UNSUPPORTED_DEPTH; + + boolean flipX = destWidth < 0; + boolean flipY = destHeight < 0; + if (flipX) { + destWidth = -destWidth; + destX = destX - destWidth; + } + if (flipY) { + destHeight = -destHeight; + destY = destY - destHeight; + } + byte[] srcReds = null, srcGreens = null, srcBlues = null; + if (!palette.isDirect) { + RGB[] rgbs = palette.getRGBs(); + int length = rgbs.length; + srcReds = new byte[length]; + srcGreens = new byte[length]; + srcBlues = new byte[length]; + for (int i = 0; i < rgbs.length; i++) { + RGB rgb = rgbs[i]; + if (rgb == null) continue; + srcReds[i] = (byte)rgb.red; + srcGreens[i] = (byte)rgb.green; + srcBlues[i] = (byte)rgb.blue; + } + } + byte[] destReds = null, destGreens = null, destBlues = null; + int destRedMask = 0, destGreenMask = 0, destBlueMask = 0; + final boolean screenDirect; + if (screenDepth <= 8) { + if (xcolors == null) return SWT.ERROR_UNSUPPORTED_DEPTH; + destReds = new byte[xcolors.length]; + destGreens = new byte[xcolors.length]; + destBlues = new byte[xcolors.length]; + for (int i = 0; i < xcolors.length; i++) { + XColor color = xcolors[i]; + if (color == null) continue; + destReds[i] = (byte)((color.red >> 8) & 0xFF); + destGreens[i] = (byte)((color.green >> 8) & 0xFF); + destBlues[i] = (byte)((color.blue >> 8) & 0xFF); + } + screenDirect = false; + } else { + Visual xVisual = new Visual(); + OS.memmove(xVisual, visual, Visual.sizeof); + destRedMask = xVisual.red_mask; + destGreenMask = xVisual.green_mask; + destBlueMask = xVisual.blue_mask; + screenDirect = true; + } + if (transparentPixel != null) { + int transRed = 0, transGreen = 0, transBlue = 0; + if (palette.isDirect) { + RGB rgb = palette.getRGB(transparentPixel[0]); + transRed = rgb.red; + transGreen = rgb.green; + transBlue = rgb.blue; + } else { + RGB[] rgbs = palette.getRGBs(); + if (transparentPixel[0] < rgbs.length) { + RGB rgb = rgbs[transparentPixel[0]]; + transRed = rgb.red; + transGreen = rgb.green; + transBlue = rgb.blue; + } + } + transparentPixel[0] = ImageData.closestMatch(screenDepth, (byte)transRed, (byte)transGreen, (byte)transBlue, + destRedMask, destGreenMask, destBlueMask, destReds, destGreens, destBlues); + } + + /* Depth 1 */ + if (image.depth == 1) { + int xImagePtr = OS.XCreateImage(display, visual, 1, OS.XYBitmap, 0, 0, destWidth, destHeight, image.scanlinePad * 8, 0); + if (xImagePtr == 0) return SWT.ERROR_NO_HANDLES; + XImage xImage = new XImage(); + OS.memmove(xImage, xImagePtr, XImage.sizeof); + int bufSize = xImage.bytes_per_line * xImage.height; + int bufPtr = OS.XtMalloc(bufSize); + xImage.data = bufPtr; + OS.memmove(xImagePtr, xImage, XImage.sizeof); + byte[] buf = new byte[bufSize]; + ImageData.blit(ImageData.BLIT_SRC, + image.data, image.depth, image.bytesPerLine, image.getByteOrder(), srcX, srcY, srcWidth, srcHeight, null, null, null, + ImageData.ALPHA_OPAQUE, null, 0, srcX, srcY, + buf, xImage.bits_per_pixel, xImage.bytes_per_line, xImage.bitmap_bit_order, 0, 0, destWidth, destHeight, null, null, null, + flipX, flipY); + OS.memmove(xImage.data, buf, bufSize); + + int foreground = 1, background = 0; + if (!isMask) { + foreground = 0; + if (srcReds.length > 1) { + foreground = ImageData.closestMatch(screenDepth, srcReds[1], srcGreens[1], srcBlues[1], + destRedMask, destGreenMask, destBlueMask, destReds, destGreens, destBlues); + } + if (srcReds.length > 0) { + background = ImageData.closestMatch(screenDepth, srcReds[0], srcGreens[0], srcBlues[0], + destRedMask, destGreenMask, destBlueMask, destReds, destGreens, destBlues); + } + } + XGCValues values = new XGCValues(); + OS.XGetGCValues(display, gc, OS.GCForeground | OS.GCBackground, values); + OS.XSetForeground(display, gc, foreground); + OS.XSetBackground(display, gc, background); + OS.XPutImage(display, drawable, gc, xImagePtr, 0, 0, destX, destY, destWidth, destHeight); + OS.XSetForeground(display, gc, values.foreground); + OS.XSetBackground(display, gc, values.background); + OS.XDestroyImage(xImagePtr); + return 0; + } + + /* Depths other than 1 */ + int xImagePtr = OS.XCreateImage(display, visual, screenDepth, OS.ZPixmap, 0, 0, destWidth, destHeight, image.scanlinePad * 8, 0); + if (xImagePtr == 0) return SWT.ERROR_NO_HANDLES; + XImage xImage = new XImage(); + OS.memmove(xImage, xImagePtr, XImage.sizeof); + int bufSize = xImage.bytes_per_line * xImage.height; + int bufPtr = OS.XtMalloc(bufSize); + xImage.data = bufPtr; + OS.memmove(xImagePtr, xImage, XImage.sizeof); + byte[] buf = new byte[bufSize]; + if (palette.isDirect) { + if (screenDirect) { + ImageData.blit(ImageData.BLIT_SRC, + image.data, image.depth, image.bytesPerLine, image.getByteOrder(), srcX, srcY, srcWidth, srcHeight, palette.redMask, palette.greenMask, palette.blueMask, + ImageData.ALPHA_OPAQUE, null, 0, srcX, srcY, + buf, xImage.bits_per_pixel, xImage.bytes_per_line, xImage.byte_order, 0, 0, destWidth, destHeight, xImage.red_mask, xImage.green_mask, xImage.blue_mask, + flipX, flipY); + } else { + ImageData.blit(ImageData.BLIT_SRC, + image.data, image.depth, image.bytesPerLine, image.getByteOrder(), srcX, srcY, srcWidth, srcHeight, palette.redMask, palette.greenMask, palette.blueMask, + ImageData.ALPHA_OPAQUE, null, 0, srcX, srcY, + buf, xImage.bits_per_pixel, xImage.bytes_per_line, xImage.byte_order, 0, 0, destWidth, destHeight, destReds, destGreens, destBlues, + flipX, flipY); + } + } else { + if (screenDirect) { + ImageData.blit(ImageData.BLIT_SRC, + image.data, image.depth, image.bytesPerLine, image.getByteOrder(), srcX, srcY, srcWidth, srcHeight, srcReds, srcGreens, srcBlues, + ImageData.ALPHA_OPAQUE, null, 0, srcX, srcY, + buf, xImage.bits_per_pixel, xImage.bytes_per_line, xImage.byte_order, 0, 0, destWidth, destHeight, xImage.red_mask, xImage.green_mask, xImage.blue_mask, + flipX, flipY); + } else { + ImageData.blit(ImageData.BLIT_SRC, + image.data, image.depth, image.bytesPerLine, image.getByteOrder(), srcX, srcY, srcWidth, srcHeight, srcReds, srcGreens, srcBlues, + ImageData.ALPHA_OPAQUE, null, 0, srcX, srcY, + buf, xImage.bits_per_pixel, xImage.bytes_per_line, xImage.byte_order, 0, 0, destWidth, destHeight, destReds, destGreens, destBlues, + flipX, flipY); + } + } + OS.memmove(xImage.data, buf, bufSize); + OS.XPutImage(display, drawable, gc, xImagePtr, 0, 0, destX, destY, destWidth, destHeight); + OS.XDestroyImage(xImagePtr); + return 0; +} +/** + * Sets the color to which to map the transparent pixel. + * <p> + * There are certain uses of <code>Images</code> that do not support + * transparency (for example, setting an image into a button or label). + * In these cases, it may be desired to simulate transparency by using + * the background color of the widget to paint the transparent pixels + * of the image. This method specifies the color that will be used in + * these cases. For example: + * <pre> + * Button b = new Button(); + * image.setBackground(b.getBackground()); + * b.setImage(image); + * </pre> + * </p><p> + * The image may be modified by this operation (in effect, the + * transparent regions may be filled with the supplied color). Hence + * this operation is not reversible and it is not legal to call + * this function twice or with a null argument. + * </p><p> + * This method has no effect if the receiver does not have a transparent + * pixel value. + * </p> + * + * @param color the color to use when a transparent pixel is specified + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the color is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the color has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setBackground(Color color) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (color == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (color.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (transparentPixel == -1) return; + /* Generate the mask if necessary. */ + if (mask == 0) createMask(); + Rectangle bounds = getBounds(); + int[] unused = new int[1]; + int[] depth = new int[1]; + int xDisplay = device.xDisplay; + OS.XGetGeometry(xDisplay, pixmap, unused, unused, unused, unused, unused, unused, depth); + int drawable = OS.XDefaultRootWindow(xDisplay); + int tempPixmap = OS.XCreatePixmap(xDisplay, drawable, bounds.width, bounds.height, depth[0]); + int xGC = OS.XCreateGC(xDisplay, tempPixmap, 0, null); + OS.XSetForeground(xDisplay, xGC, color.handle.pixel); + OS.XFillRectangle(xDisplay, tempPixmap, xGC, 0, 0, bounds.width, bounds.height); + OS.XSetClipMask(xDisplay, xGC, mask); + OS.XCopyArea(xDisplay, pixmap, tempPixmap, xGC, 0, 0, bounds.width, bounds.height, 0, 0); + OS.XSetClipMask(xDisplay, xGC, OS.None); + OS.XCopyArea(xDisplay, tempPixmap, pixmap, xGC, 0, 0, bounds.width, bounds.height, 0, 0); + OS.XFreePixmap(xDisplay, tempPixmap); + OS.XFreeGC(xDisplay, xGC); + /* Destroy the receiver's mask if the there is a GC created on it */ + if (memGC != null) destroyMask(); +} +/** + * Returns a string containing a concise, human-readable + * description of the receiver. + * + * @return a string representation of the receiver + */ +public String toString () { + if (isDisposed()) return "Image {*DISPOSED*}"; + return "Image {" + pixmap + "}"; +} +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Region.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Region.java new file mode 100755 index 0000000000..8aaaefb757 --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/Region.java @@ -0,0 +1,561 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + + +import org.eclipse.swt.internal.motif.*; +import org.eclipse.swt.*; + +/** + * Instances of this class represent areas of an x-y coordinate + * system that are aggregates of the areas covered by a number + * of polygons. + * <p> + * Application code must explicitly invoke the <code>Region.dispose()</code> + * method to release the operating system resources managed by each instance + * when those instances are no longer required. + * </p> + * + * @see <a href="http://www.eclipse.org/swt/examples.php">SWT Example: GraphicsExample</a> + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + */ +public final class Region extends Resource { + /** + * the OS resource for the region + * (Warning: This field is platform dependent) + * <p> + * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT + * public API. 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 accessed from application code. + * </p> + */ + public int handle; + +/** + * Constructs a new empty region. + * + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for region creation</li> + * </ul> + */ +public Region () { + this(null); +} +/** + * Constructs a new empty region. + * <p> + * You must dispose the region when it is no longer required. + * </p> + * + * @param device the device on which to allocate the region + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * </ul> + * @exception SWTError <ul> + * <li>ERROR_NO_HANDLES if a handle could not be obtained for region creation</li> + * </ul> + * + * @see #dispose + * + * @since 3.0 + */ +public Region (Device device) { + super(device); + handle = OS.XCreateRegion (); + if (handle == 0) SWT.error(SWT.ERROR_NO_HANDLES); + init(); +} +Region (Device device, int handle) { + super(device); + this.handle = handle; +} +/** + * Adds the given polygon to the collection of polygons + * the receiver maintains to describe its area. + * + * @param pointArray points that describe the polygon to merge with the receiver + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.0 +* + */ +public void add (int[] pointArray) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + short[] points = new short[pointArray.length]; + for (int i = 0; i < pointArray.length; i++) { + points[i] = (short)pointArray[i]; + } + int polyRgn = OS.XPolygonRegion(points, points.length / 2, OS.EvenOddRule); + OS.XUnionRegion(handle, polyRgn, handle); + OS.XDestroyRegion(polyRgn); +} +/** + * Adds the given rectangle to the collection of polygons + * the receiver maintains to describe its area. + * + * @param rect the rectangle to merge with the receiver + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the rectangle's width or height is negative</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void add (Rectangle rect) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (rect == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + add (rect.x, rect.y, rect.width, rect.height); +} +/** + * Adds the given rectangle to the collection of polygons + * the receiver maintains to describe its area. + * + * @param x the x coordinate of the rectangle + * @param y the y coordinate of the rectangle + * @param width the width coordinate of the rectangle + * @param height the height coordinate of the rectangle + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the rectangle's width or height is negative</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void add (int x, int y, int width, int height) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width < 0 || height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + XRectangle xRect = new XRectangle(); + xRect.x = (short)x; + xRect.y = (short)y; + xRect.width = (short)width; + xRect.height = (short)height; + OS.XUnionRectWithRegion(xRect, handle, handle); +} +/** + * Adds all of the polygons which make up the area covered + * by the argument to the collection of polygons the receiver + * maintains to describe its area. + * + * @param region the region to merge + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void add (Region region) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + OS.XUnionRegion(handle, region.handle, handle); +} +/** + * Returns <code>true</code> if the point specified by the + * arguments is inside the area specified by the receiver, + * and <code>false</code> otherwise. + * + * @param x the x coordinate of the point to test for containment + * @param y the y coordinate of the point to test for containment + * @return <code>true</code> if the region contains the point and <code>false</code> otherwise + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public boolean contains (int x, int y) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return OS.XPointInRegion(handle, x, y); +} +/** + * Returns <code>true</code> if the given point is inside the + * area specified by the receiver, and <code>false</code> + * otherwise. + * + * @param pt the point to test for containment + * @return <code>true</code> if the region contains the point and <code>false</code> otherwise + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public boolean contains (Point pt) { + if (pt == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + return contains(pt.x, pt.y); +} +void destroy() { + OS.XDestroyRegion(handle); + handle = 0; +} +/** + * Compares the argument to the receiver, and returns true + * if they represent the <em>same</em> object using a class + * specific comparison. + * + * @param object the object to compare with this object + * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise + * + * @see #hashCode + */ +public boolean equals (Object object) { + if (this == object) return true; + if (!(object instanceof Region)) return false; + Region region = (Region)object; + return handle == region.handle; +} +/** + * Returns a rectangle which represents the rectangular + * union of the collection of polygons the receiver + * maintains to describe its area. + * + * @return a bounding rectangle for the region + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see Rectangle#union + */ +public Rectangle getBounds() { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + XRectangle rect = new XRectangle(); + OS.XClipBox(handle, rect); + return new Rectangle(rect.x, rect.y, rect.width, rect.height); +} +/** + * Returns an integer hash code for the receiver. Any two + * objects that return <code>true</code> when passed to + * <code>equals</code> must return the same value for this + * method. + * + * @return the receiver's hash + * + * @see #equals + */ +public int hashCode () { + return handle; +} +/** + * Intersects the given rectangle to the collection of polygons + * the receiver maintains to describe its area. + * + * @param rect the rectangle to intersect with the receiver + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the rectangle's width or height is negative</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.0 + */ +public void intersect (Rectangle rect) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (rect == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + intersect(rect.x, rect.y, rect.width, rect.height); +} +/** + * Intersects the given rectangle to the collection of polygons + * the receiver maintains to describe its area. + * + * @param x the x coordinate of the rectangle + * @param y the y coordinate of the rectangle + * @param width the width coordinate of the rectangle + * @param height the height coordinate of the rectangle + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the rectangle's width or height is negative</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void intersect (int x, int y, int width, int height) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width < 0 || height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + int rectRgn = OS.XCreateRegion(); + XRectangle xRect = new XRectangle(); + xRect.x = (short)x; + xRect.y = (short)y; + xRect.width = (short)width; + xRect.height = (short)height; + OS.XUnionRectWithRegion(xRect, rectRgn, rectRgn); + OS.XIntersectRegion(handle, rectRgn, handle); + OS.XDestroyRegion(rectRgn); +} +/** + * Intersects all of the polygons which make up the area covered + * by the argument to the collection of polygons the receiver + * maintains to describe its area. + * + * @param region the region to intersect + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.0 + */ +public void intersect (Region region) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + OS.XIntersectRegion(handle, region.handle, handle); +} +/** + * Returns <code>true</code> if the rectangle described by the + * arguments intersects with any of the polygons the receiver + * maintains to describe its area, and <code>false</code> otherwise. + * + * @param x the x coordinate of the origin of the rectangle + * @param y the y coordinate of the origin of the rectangle + * @param width the width of the rectangle + * @param height the height of the rectangle + * @return <code>true</code> if the rectangle intersects with the receiver, and <code>false</code> otherwise + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see Rectangle#intersects(Rectangle) + */ +public boolean intersects (int x, int y, int width, int height) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return OS.XRectInRegion (handle, x, y, width, height) != OS.RectangleOut; +} +/** + * Returns <code>true</code> if the given rectangle intersects + * with any of the polygons the receiver maintains to describe + * its area and <code>false</code> otherwise. + * + * @param rect the rectangle to test for intersection + * @return <code>true</code> if the rectangle intersects with the receiver, and <code>false</code> otherwise + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see Rectangle#intersects(Rectangle) + */ +public boolean intersects (Rectangle rect) { + if (rect == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + return intersects(rect.x, rect.y, rect.width, rect.height); +} +/** + * Returns <code>true</code> if the region has been disposed, + * and <code>false</code> otherwise. + * <p> + * This method gets the dispose state for the region. + * When a region has been disposed, it is an error to + * invoke any other method using the region. + * + * @return <code>true</code> when the region is disposed, and <code>false</code> otherwise + */ +public boolean isDisposed() { + return handle == 0; +} +/** + * Returns <code>true</code> if the receiver does not cover any + * area in the (x, y) coordinate plane, and <code>false</code> if + * the receiver does cover some area in the plane. + * + * @return <code>true</code> if the receiver is empty, and <code>false</code> otherwise + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public boolean isEmpty () { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return OS.XEmptyRegion(handle); +} +public static Region motif_new(Device device, int handle) { + return new Region(device, handle); +} +/** + * Subtracts the given polygon from the collection of polygons + * the receiver maintains to describe its area. + * + * @param pointArray points that describe the polygon to merge with the receiver + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.0 + */ +public void subtract (int[] pointArray) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + short[] points = new short[pointArray.length]; + for (int i = 0; i < pointArray.length; i++) { + points[i] = (short)pointArray[i]; + } + int polyRgn = OS.XPolygonRegion(points, points.length / 2, OS.EvenOddRule); + OS.XSubtractRegion(handle, polyRgn, handle); + OS.XDestroyRegion(polyRgn); +} +/** + * Subtracts the given rectangle from the collection of polygons + * the receiver maintains to describe its area. + * + * @param rect the rectangle to subtract from the receiver + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the rectangle's width or height is negative</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.0 + */ +public void subtract (Rectangle rect) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (rect == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + subtract (rect.x, rect.y, rect.width, rect.height); +} +/** + * Subtracts the given rectangle from the collection of polygons + * the receiver maintains to describe its area. + * + * @param x the x coordinate of the rectangle + * @param y the y coordinate of the rectangle + * @param width the width coordinate of the rectangle + * @param height the height coordinate of the rectangle + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the rectangle's width or height is negative</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void subtract (int x, int y, int width, int height) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width < 0 || height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + int rectRgn = OS.XCreateRegion(); + XRectangle xRect = new XRectangle(); + xRect.x = (short)x; + xRect.y = (short)y; + xRect.width = (short)width; + xRect.height = (short)height; + OS.XUnionRectWithRegion(xRect, rectRgn, rectRgn); + OS.XSubtractRegion(handle, rectRgn, handle); + OS.XDestroyRegion(rectRgn); +} +/** + * Subtracts all of the polygons which make up the area covered + * by the argument from the collection of polygons the receiver + * maintains to describe its area. + * + * @param region the region to subtract + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.0 + */ +public void subtract (Region region) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + OS.XSubtractRegion(handle, region.handle, handle); +} +/** + * Translate all of the polygons the receiver maintains to describe + * its area by the specified point. + * + * @param x the x coordinate of the point to translate + * @param y the y coordinate of the point to translate + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void translate (int x, int y) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + OS.XOffsetRegion (handle, x, y); +} +/** + * Translate all of the polygons the receiver maintains to describe + * its area by the specified point. + * + * @param pt the point to translate + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the argument is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.1 + */ +public void translate (Point pt) { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pt == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + translate (pt.x, pt.y); +} +/** + * Returns a string containing a concise, human-readable + * description of the receiver. + * + * @return a string representation of the receiver + */ +public String toString () { + if (isDisposed()) return "Region {*DISPOSED*}"; + return "Region {" + handle + "}"; +} +} diff --git a/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/TextLayout.java b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/TextLayout.java new file mode 100644 index 0000000000..a03a44526c --- /dev/null +++ b/bundles/org.eclipse.swt/Eclipse SWT/motif/org/eclipse/swt/graphics/TextLayout.java @@ -0,0 +1,1935 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.swt.graphics; + +import org.eclipse.swt.internal.*; +import org.eclipse.swt.internal.motif.*; +import org.eclipse.swt.*; + +/** + * <code>TextLayout</code> is a graphic object that represents + * styled text. + * <p> + * Instances of this class provide support for drawing, cursor + * navigation, hit testing, text wrapping, alignment, tab expansion + * line breaking, etc. These are aspects required for rendering internationalized text. + * </p><p> + * Application code must explicitly invoke the <code>TextLayout#dispose()</code> + * method to release the operating system resources managed by each instance + * when those instances are no longer required. + * </p> + * + * @see <a href="http://www.eclipse.org/swt/snippets/#textlayout">TextLayout, TextStyle snippets</a> + * @see <a href="http://www.eclipse.org/swt/examples.php">SWT Example: CustomControlExample, StyledText tab</a> + * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> + * + * @since 3.0 + */ +public final class TextLayout extends Resource { + Font font; + String text; + int lineSpacing; + int ascent, descent; + int alignment; + int wrapWidth; + int orientation; + int indent; + boolean justify; + int[] tabs; + int[] segments; + StyleItem[] styles; + + StyleItem[][] runs; + int[] lineOffset, lineY, lineWidth; + int defaultAscent, defaultDescent; + + static final RGB LINK_FOREGROUND = new RGB (0, 51, 153); + + static class StyleItem { + TextStyle style; + int start, length, width, height, baseline; + boolean lineBreak, softBreak, tab; + + public String toString () { + return "StyleItem {" + start + ", " + style + "}"; + } + } + +/** + * Constructs a new instance of this class on the given device. + * <p> + * You must dispose the text layout when it is no longer required. + * </p> + * + * @param device the device on which to allocate the text layout + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li> + * </ul> + * + * @see #dispose() + */ +public TextLayout (Device device) { + super(device); + wrapWidth = ascent = descent = -1; + lineSpacing = 0; + orientation = SWT.LEFT_TO_RIGHT; + XFontStruct fontStruct = getFontHeigth(this.device.getSystemFont()); + defaultAscent = fontStruct.ascent; + defaultDescent = fontStruct.descent; + styles = new StyleItem[2]; + styles[0] = new StyleItem(); + styles[1] = new StyleItem(); + text = ""; //$NON-NLS-1$ + init(); +} + +void checkLayout () { + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); +} + +int stringWidth (StyleItem run, char[] ch) { + if (ch.length == 0) return 0; + Font font = getItemFont(run); + int fontList = font.handle; + byte[] buffer = Converter.wcsToMbcs(font.codePage, ch, true); + int xmString = OS.XmStringCreateLocalized(buffer); + int width = OS.XmStringWidth(fontList, xmString); + OS.XmStringFree(xmString); + return width; +} + +void computeRuns () { + if (runs != null) return; + StyleItem[] allRuns = itemize(); + for (int i=0; i<allRuns.length-1; i++) { + StyleItem run = allRuns[i]; + place(run); + } + int lineWidth = 0, lineStart = 0, lineCount = 1; + for (int i=0; i<allRuns.length - 1; i++) { + StyleItem run = allRuns[i]; + if (run.length == 1) { + char ch = text.charAt(run.start); + switch (ch) { + case '\t': { + run.tab = true; + run.baseline = 0; + if (tabs == null) break; + int tabsLength = tabs.length, j; + for (j = 0; j < tabsLength; j++) { + if (tabs[j] > lineWidth) { + run.width = tabs[j] - lineWidth; + break; + } + } + if (j == tabsLength) { + int tabX = tabs[tabsLength-1]; + int lastTabWidth = tabsLength > 1 ? tabs[tabsLength-1] - tabs[tabsLength-2] : tabs[0]; + if (lastTabWidth > 0) { + while (tabX <= lineWidth) tabX += lastTabWidth; + run.width = tabX - lineWidth; + } + } + break; + } + case '\n': + run.lineBreak = true; + run.baseline = run.width = 0; + break; + case '\r': + run.lineBreak = true; + run.baseline = run.width = 0; + StyleItem next = allRuns[i + 1]; + if (next.length != 0 && text.charAt(next.start) == '\n') { + run.length += 1; + i++; + } + break; + } + } + if (wrapWidth != -1 && lineWidth + run.width > wrapWidth && !run.tab) { + int start = 0; + char[] chars = new char[run.length]; + text.getChars(run.start, run.start + run.length, chars, 0); + if (!(run.style != null && run.style.metrics != null)) { + int width = 0, maxWidth = wrapWidth - lineWidth; + char[] buffer = new char[1]; + buffer[0] = chars[start]; + int charWidth = stringWidth(run, buffer); + while (width + charWidth < maxWidth) { + width += charWidth; + start++; + buffer[0] = chars[start]; + charWidth = stringWidth(run, buffer); + } + } + int firstStart = start; + int firstIndice = i; + while (i >= lineStart) { + chars = new char[run.length]; + text.getChars(run.start, run.start + run.length, chars, 0); + while(start >= 0) { + if (Compatibility.isSpaceChar(chars[start]) || Compatibility.isWhitespace(chars[start])) break; + start--; + } + if (start >= 0 || i == lineStart) break; + run = allRuns[--i]; + start = run.length - 1; + } + if (start == 0 && i != lineStart) { + run = allRuns[--i]; + } else if (start <= 0 && i == lineStart) { + i = firstIndice; + run = allRuns[i]; + start = Math.max(1, firstStart); + } + chars = new char[run.length]; + text.getChars(run.start, run.start + run.length, chars, 0); + while (start < run.length) { + if (!Compatibility.isWhitespace(chars[start])) break; + start++; + } + if (0 < start && start < run.length) { + StyleItem newRun = new StyleItem(); + newRun.start = run.start + start; + newRun.length = run.length - start; + newRun.style = run.style; + run.length = start; + place (run); + place (newRun); + StyleItem[] newAllRuns = new StyleItem[allRuns.length + 1]; + System.arraycopy(allRuns, 0, newAllRuns, 0, i + 1); + System.arraycopy(allRuns, i + 1, newAllRuns, i + 2, allRuns.length - i - 1); + allRuns = newAllRuns; + allRuns[i + 1] = newRun; + } + if (i != allRuns.length - 2) { + run.softBreak = run.lineBreak = true; + } + } + lineWidth += run.width; + if (run.lineBreak) { + lineStart = i + 1; + lineWidth = 0; + lineCount++; + } + } + lineWidth = 0; + runs = new StyleItem[lineCount][]; + lineOffset = new int[lineCount + 1]; + lineY = new int[lineCount + 1]; + this.lineWidth = new int[lineCount]; + int lineRunCount = 0, line = 0; + int ascent = Math.max(defaultAscent, this.ascent); + int descent = Math.max(defaultDescent, this.descent); + StyleItem[] lineRuns = new StyleItem[allRuns.length]; + XFontStruct fontStruct; + for (int i=0; i<allRuns.length; i++) { + StyleItem run = allRuns[i]; + lineRuns[lineRunCount++] = run; + lineWidth += run.width; + if (run.style != null ) { + int runAscent = defaultAscent; + int runDescent = defaultDescent; + if (run.style.metrics != null) { + GlyphMetrics metrics = run.style.metrics; + runAscent = metrics.ascent; + runDescent = metrics.descent; + } else if (run.style.font != null) { + fontStruct = getFontHeigth(run.style.font); + runAscent = fontStruct.ascent; + runDescent = fontStruct.descent; + } + ascent = Math.max(ascent, runAscent + run.style.rise); + descent = Math.max(descent, runDescent - run.style.rise); + if (run.style.rise != 0) { + run.baseline += run.style.rise; + } + } + if (run.lineBreak || i == allRuns.length - 1) { + runs[line] = new StyleItem[lineRunCount]; + System.arraycopy(lineRuns, 0, runs[line], 0, lineRunCount); + StyleItem lastRun = runs[line][lineRunCount - 1]; + this.lineWidth[line] = lineWidth; + line++; + lineY[line] = lineY[line - 1] + ascent + descent + lineSpacing; + lineOffset[line] = lastRun.start + lastRun.length; + lineRunCount = lineWidth = 0; + ascent = Math.max(defaultAscent, this.ascent); + descent = Math.max(defaultDescent, this.descent); + } + } +} + +void destroy() { + freeRuns(); + font = null; + text = null; + tabs = null; + styles = null; + lineOffset = null; + lineY = null; + lineWidth = null; +} + +/** + * Draws the receiver's text using the specified GC at the specified + * point. + * + * @param gc the GC to draw + * @param x the x coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param y the y coordinate of the top left corner of the rectangular area where the text is to be drawn + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the gc is null</li> + * </ul> + */ +public void draw (GC gc, int x, int y) { + draw(gc, x, y, -1, -1, null, null); +} + +/** + * Draws the receiver's text using the specified GC at the specified + * point. + * + * @param gc the GC to draw + * @param x the x coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param y the y coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param selectionStart the offset where the selections starts, or -1 indicating no selection + * @param selectionEnd the offset where the selections ends, or -1 indicating no selection + * @param selectionForeground selection foreground, or NULL to use the system default color + * @param selectionBackground selection background, or NULL to use the system default color + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the gc is null</li> + * </ul> + */ +public void draw(GC gc, int x, int y, int selectionStart, int selectionEnd, Color selectionForeground, Color selectionBackground) { + draw(gc, x, y, selectionStart, selectionEnd, selectionForeground, selectionBackground, 0); +} + +/** + * Draws the receiver's text using the specified GC at the specified + * point. + * <p> + * The parameter <code>flags</code> can include one of <code>SWT.DELIMITER_SELECTION</code> + * or <code>SWT.FULL_SELECTION</code> to specify the selection behavior on all lines except + * for the last line, and can also include <code>SWT.LAST_LINE_SELECTION</code> to extend + * the specified selection behavior to the last line. + * </p> + * @param gc the GC to draw + * @param x the x coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param y the y coordinate of the top left corner of the rectangular area where the text is to be drawn + * @param selectionStart the offset where the selections starts, or -1 indicating no selection + * @param selectionEnd the offset where the selections ends, or -1 indicating no selection + * @param selectionForeground selection foreground, or NULL to use the system default color + * @param selectionBackground selection background, or NULL to use the system default color + * @param flags drawing options + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the gc is null</li> + * </ul> + * + * @since 3.3 + */ +public void draw(GC gc, int x, int y, int selectionStart, int selectionEnd, Color selectionForeground, Color selectionBackground, int flags) { + checkLayout(); + computeRuns(); + if (gc == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (gc.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (selectionForeground != null && selectionForeground.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (selectionBackground != null && selectionBackground.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + gc.checkGC(GC.FOREGROUND); + int length = text.length(); + if (length == 0 && flags == 0) return; + boolean hasSelection = selectionStart <= selectionEnd && selectionStart != -1 && selectionEnd != -1; + if (hasSelection || (flags & SWT.LAST_LINE_SELECTION) != 0) { + selectionStart = Math.min(Math.max(0, selectionStart), length - 1); + selectionEnd = Math.min(Math.max(0, selectionEnd), length - 1); + if (selectionForeground == null) selectionForeground = device.getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT); + if (selectionBackground == null) selectionBackground = device.getSystemColor(SWT.COLOR_LIST_SELECTION); + } + final Color foreground = gc.getForeground(); + final Color background = gc.getBackground(); + final Font gcFont = gc.getFont(); + Color linkColor = null; + Rectangle clip = gc.getClipping(); + for (int line=0; line<runs.length; line++) { + int drawX = x + getLineIndent(line); + int drawY = y + lineY[line]; + StyleItem[] lineRuns = runs[line]; + int lineHeight = lineY[line+1] - lineY[line]; + if (flags != 0 && (hasSelection || (flags & SWT.LAST_LINE_SELECTION) != 0)) { + boolean extent = false; + if (line == runs.length - 1 && (flags & SWT.LAST_LINE_SELECTION) != 0) { + extent = true; + } else { + StyleItem run = lineRuns[lineRuns.length - 1]; + if (run.lineBreak && !run.softBreak) { + if (selectionStart <= run.start && run.start <= selectionEnd) extent = true; + } else { + int endOffset = run.start + run.length - 1; + if (selectionStart <= endOffset && endOffset < selectionEnd && (flags & SWT.FULL_SELECTION) != 0) { + extent = true; + } + } + } + if (extent) { + gc.setBackground(selectionBackground); + int width = (flags & SWT.FULL_SELECTION) != 0 ? 0x7fffffff : lineHeight / 3; + gc.fillRectangle(drawX + lineWidth[line], drawY, width, lineHeight); + } + } + if (drawX > clip.x + clip.width) continue; + if (drawX + lineWidth[line] < clip.x) continue; + int baseline = Math.max(0, this.ascent); + for (int i = 0; i < lineRuns.length; i++) { + baseline = Math.max(baseline, lineRuns[i].baseline); + } + for (int i = 0; i < lineRuns.length; i++) { + StyleItem run = lineRuns[i]; + if (run.length == 0) continue; + if (drawX > clip.x + clip.width) break; + if (drawX + run.width >= clip.x) { + if (!run.lineBreak || run.softBreak) { + String string = text.substring(run.start, run.start + run.length); + int drawRunY = drawY + (baseline - run.baseline); + int end = run.start + run.length - 1; + gc.setFont(getItemFont(run)); + boolean fullSelection = hasSelection && selectionStart <= run.start && selectionEnd >= end; + TextStyle style = run.style; + if (fullSelection) { + gc.setBackground(selectionBackground); + gc.fillRectangle(drawX, drawY, run.width, lineHeight); + if (!run.tab && !(style != null && style.metrics != null)) { + gc.setForeground(selectionForeground); + gc.drawString(string, drawX, drawRunY, true); + drawLines(gc, run, drawX, drawRunY, run.width); + } + } else { + if (style != null && style.background != null) { + Color bg = style.background; + gc.setBackground(bg); + gc.fillRectangle(drawX, drawRunY, run.width, run.height); + } + if (!run.tab) { + Color fg = foreground; + if (style != null) { + if (style.foreground != null) { + fg = style.foreground; + } else { + if (style.underline && style.underlineStyle == SWT.UNDERLINE_LINK) { + if (linkColor == null) { + linkColor = new Color(device, LINK_FOREGROUND); + } + fg = linkColor; + } + } + } + if (!(style != null && style.metrics != null)) { + gc.setForeground(fg); + gc.drawString(string, drawX, drawRunY, true); + drawLines(gc, run, drawX, drawRunY, run.width); + } + boolean partialSelection = hasSelection && !(selectionStart > end || run.start > selectionEnd); + if (partialSelection) { + int selStart = Math.max(selectionStart, run.start); + int selEnd = Math.min(selectionEnd, end); + string = text.substring(run.start, selStart); + int selX = drawX + gc.stringExtent(string).x; + string = text.substring(selStart, selEnd + 1); + int selWidth = gc.stringExtent(string).x; + gc.setBackground(selectionBackground); + gc.fillRectangle(selX, drawY, selWidth, lineHeight); + if (fg != selectionForeground && !(style != null && style.metrics != null)) { + gc.setForeground(selectionForeground); + gc.drawString(string, selX, drawRunY, true); + drawLines(gc, run, selX, drawRunY, selWidth); + } + } + } + } + drawBorder(gc, lineRuns, i, drawX, drawY, lineHeight, foreground); + } + } + drawX += run.width; + } + } + gc.setForeground(foreground); + gc.setBackground(background); + gc.setFont(gcFont); + if (linkColor != null) linkColor.dispose(); +} + +void drawBorder(GC gc, StyleItem[] line, int index, int x, int y, int lineHeight, Color color) { + StyleItem run = line[index]; + TextStyle style = run.style; + if (style == null) return; + if (style.borderStyle != SWT.NONE && (index + 1 >= line.length || !style.isAdherentBorder(line[index + 1].style))) { + int width = run.width; + for (int i = index; i > 0 && style.isAdherentBorder(line[i - 1].style); i--) { + x -= line[i - 1].width; + width += line[i - 1].width; + } + if (style.borderColor != null) { + color = style.borderColor; + } else { + if (style.foreground != null) { + color = style.foreground; + } + } + gc.setForeground(color); + int lineStyle = gc.getLineStyle(); + int[] dashes = null; + if (lineStyle == SWT.LINE_CUSTOM) { + dashes = gc.getLineDash(); + } + switch (style.borderStyle) { + case SWT.BORDER_SOLID: + gc.setLineStyle(SWT.LINE_SOLID); + break; + case SWT.BORDER_DASH: + gc.setLineStyle(SWT.LINE_DASH); + break; + case SWT.BORDER_DOT: + gc.setLineStyle(SWT.LINE_DOT); + break; + } + gc.drawRectangle(x, y, width - 1, lineHeight - 1); + gc.setLineStyle(lineStyle); + if (dashes != null) { + gc.setLineDash(dashes); + } + } +} + +void drawLines(GC gc, StyleItem run, int x, int y, int width) { + TextStyle style = run.style; + if (style == null) return; + if (style.underline) { + int underlineY = y + run.baseline + 1 - style.rise; + if (style.underlineColor != null) { + gc.setForeground(style.underlineColor); + } + switch (style.underlineStyle) { + case SWT.UNDERLINE_SQUIGGLE: + case SWT.UNDERLINE_ERROR: + int squigglyThickness = 1; + int squigglyHeight = 2 * squigglyThickness; + int squigglyY = Math.min(underlineY, y + run.height - squigglyHeight - 1); + int[] points = computePolyline(x, squigglyY, x + width, squigglyY + squigglyHeight); + gc.drawPolyline(points); + break; + case SWT.UNDERLINE_DOUBLE: + gc.drawLine (x, underlineY + 2, x + width, underlineY + 2); + //FALLTHROU + case SWT.UNDERLINE_LINK: + case SWT.UNDERLINE_SINGLE: + gc.drawLine (x, underlineY, x + width, underlineY); + } + } + if (style.strikeout) { + int strikeoutY = y + run.height - run.height/2 - 1; + if (style.strikeoutColor != null) { + gc.setForeground(style.strikeoutColor); + } + gc.drawLine (x, strikeoutY, x + width, strikeoutY); + } +} + +int[] computePolyline(int left, int top, int right, int bottom) { + int height = bottom - top; // can be any number + int width = 2 * height; // must be even + int peaks = (right - left) / width; + if (peaks == 0 && right - left > 2) { + peaks = 1; + } + int length = ((2 * peaks) + 1) * 2; + if (length < 0) return new int[0]; + + int[] coordinates = new int[length]; + for (int i = 0; i < peaks; i++) { + int index = 4 * i; + coordinates[index] = left + (width * i); + coordinates[index+1] = bottom; + coordinates[index+2] = coordinates[index] + width / 2; + coordinates[index+3] = top; + } + coordinates[length-2] = Math.min(Math.max(0, right - 1), left + (width * peaks)); + coordinates[length-1] = bottom; + return coordinates; +} + +void freeRuns() { + runs = null; +} + +/** + * Returns the receiver's horizontal text alignment, which will be one + * of <code>SWT.LEFT</code>, <code>SWT.CENTER</code> or + * <code>SWT.RIGHT</code>. + * + * @return the alignment used to positioned text horizontally + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getAlignment () { + checkLayout(); + return alignment; +} + +/** + * Returns the ascent of the receiver. + * + * @return the ascent + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getDescent() + * @see #setDescent(int) + * @see #setAscent(int) + * @see #getLineMetrics(int) + */ +public int getAscent () { + checkLayout(); + return ascent; +} + +/** + * Returns the bounds of the receiver. The width returned is either the + * width of the longest line or the width set using {@link TextLayout#setWidth(int)}. + * To obtain the text bounds of a line use {@link TextLayout#getLineBounds(int)}. + * + * @return the bounds of the receiver + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #setWidth(int) + * @see #getLineBounds(int) + */ +public Rectangle getBounds () { + checkLayout(); + computeRuns(); + int width = 0; + if (wrapWidth != -1) { + width = wrapWidth; + } else { + for (int line=0; line<runs.length; line++) { + width = Math.max(width, lineWidth[line] + getLineIndent(line)); + } + } + return new Rectangle (0, 0, width, lineY[lineY.length - 1]); +} + +/** + * Returns the bounds for the specified range of characters. The + * bounds is the smallest rectangle that encompasses all characters + * in the range. The start and end offsets are inclusive and will be + * clamped if out of range. + * + * @param start the start offset + * @param end the end offset + * @return the bounds of the character range + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Rectangle getBounds (int start, int end) { + checkLayout(); + computeRuns(); + int length = text.length(); + if (length == 0) return new Rectangle(0, 0, 0, 0); + if (start > end) return new Rectangle(0, 0, 0, 0); + start = Math.min(Math.max(0, start), length - 1); + end = Math.min(Math.max(0, end), length - 1); + int startLine = getLineIndex(start); + int endLine = getLineIndex(end); + + Rectangle rect = new Rectangle(0, 0, 0, 0); + rect.y = lineY[startLine]; + rect.height = lineY[endLine + 1] - rect.y - lineSpacing; + if (startLine == endLine) { + rect.x = getLocation(start, false).x; + rect.width = getLocation(end, true).x - rect.x; + } else { + while (startLine <= endLine) { + rect.width = Math.max(rect.width, lineWidth[startLine++]); + } + } + return rect; +} + +/** + * Returns the descent of the receiver. + * + * @return the descent + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getAscent() + * @see #setAscent(int) + * @see #setDescent(int) + * @see #getLineMetrics(int) + */ +public int getDescent () { + checkLayout(); + return descent; +} + +/** + * Returns the default font currently being used by the receiver + * to draw and measure text. + * + * @return the receiver's font + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Font getFont () { + checkLayout(); + return font; +} + +XFontStruct getFontHeigth(Font font) { + int fontList = font.handle; + int [] buffer = new int [1]; + if (!OS.XmFontListInitFontContext (buffer, fontList)) { + SWT.error(SWT.ERROR_NO_HANDLES); + } + int context = buffer [0]; + int ascent = 0, descent = 0; + XFontStruct fontStruct = new XFontStruct (); + int fontListEntry; + int [] fontStructPtr = new int [1]; + int [] fontNamePtr = new int [1]; + while ((fontListEntry = OS.XmFontListNextEntry (context)) != 0) { + int fontPtr = OS.XmFontListEntryGetFont (fontListEntry, buffer); + if (buffer [0] == 0) { + OS.memmove (fontStruct, fontPtr, XFontStruct.sizeof); + ascent = Math.max(ascent, fontStruct.ascent); + descent = Math.max(descent, fontStruct.descent); + } else { + int nFonts = OS.XFontsOfFontSet (fontPtr, fontStructPtr, fontNamePtr); + int [] fontStructs = new int [nFonts]; + OS.memmove (fontStructs, fontStructPtr [0], nFonts * 4); + for (int i=0; i<nFonts; i++) { + OS.memmove (fontStruct, fontStructs[i], XFontStruct.sizeof); + ascent = Math.max(ascent, fontStruct.ascent); + descent = Math.max(descent, fontStruct.descent); + } + } + } + OS.XmFontListFreeFontContext (context); + fontStruct.ascent = ascent; + fontStruct.descent = descent; + return fontStruct; +} + +/** +* Returns the receiver's indent. +* +* @return the receiver's indent +* +* @exception SWTException <ul> +* <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> +* </ul> +* +* @since 3.2 +*/ +public int getIndent () { + checkLayout(); + return indent; +} + +/** +* Returns the receiver's justification. +* +* @return the receiver's justification +* +* @exception SWTException <ul> +* <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> +* </ul> +* +* @since 3.2 +*/ +public boolean getJustify () { + checkLayout(); + return justify; +} + +/** + * Returns the embedding level for the specified character offset. The + * embedding level is usually used to determine the directionality of a + * character in bidirectional text. + * + * @param offset the character offset + * @return the embedding level + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the character offset is out of range</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + */ +public int getLevel (int offset) { + checkLayout(); + int length = text.length(); + if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); + return 0; +} + +/** + * Returns the line offsets. Each value in the array is the + * offset for the first character in a line except for the last + * value, which contains the length of the text. + * + * @return the line offsets + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int[] getLineOffsets () { + checkLayout(); + computeRuns(); + int[] offsets = new int[lineOffset.length]; + System.arraycopy(lineOffset, 0, offsets, 0, offsets.length); + return offsets; +} + +/** + * Returns the bounds of the line for the specified line index. + * + * @param lineIndex the line index + * @return the line bounds + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the line index is out of range</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public Rectangle getLineBounds(int lineIndex) { + checkLayout(); + computeRuns(); + if (!(0 <= lineIndex && lineIndex < runs.length)) SWT.error(SWT.ERROR_INVALID_RANGE); + int x = getLineIndent(lineIndex); + int y = lineY[lineIndex]; + int width = lineWidth[lineIndex]; + int height = lineY[lineIndex + 1] - y - lineSpacing; + return new Rectangle (x, y, width, height); +} + +/** + * Returns the receiver's line count. This includes lines caused + * by wrapping. + * + * @return the line count + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getLineCount () { + checkLayout(); + computeRuns(); + return runs.length; +} + +int getLineIndent (int lineIndex) { + int lineIndent = 0; + if (lineIndex == 0) { + lineIndent = indent; + } else { + StyleItem[] previousLine = runs[lineIndex - 1]; + StyleItem previousRun = previousLine[previousLine.length - 1]; + if (previousRun.lineBreak && !previousRun.softBreak) { + lineIndent = indent; + } + } + if (wrapWidth != -1) { + boolean partialLine = true; +// if (justify) { +// StyleItem[] lineRun = runs[lineIndex]; +// if (lineRun[lineRun.length - 1].softBreak) { +// partialLine = false; +// } +// } + if (partialLine) { + int lineWidth = this.lineWidth[lineIndex] + lineIndent; + switch (alignment) { + case SWT.CENTER: lineIndent += (wrapWidth - lineWidth) / 2; break; + case SWT.RIGHT: lineIndent += wrapWidth - lineWidth; break; + } + } + } + return lineIndent; +} + +/** + * Returns the index of the line that contains the specified + * character offset. + * + * @param offset the character offset + * @return the line index + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the character offset is out of range</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getLineIndex (int offset) { + checkLayout(); + computeRuns(); + int length = text.length(); + if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); + for (int line=0; line<runs.length; line++) { + if (lineOffset[line + 1] > offset) { + return line; + } + } + return runs.length - 1; +} + +/** + * Returns the font metrics for the specified line index. + * + * @param lineIndex the line index + * @return the font metrics + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the line index is out of range</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public FontMetrics getLineMetrics (int lineIndex) { + checkLayout(); + computeRuns(); + if (!(0 <= lineIndex && lineIndex < runs.length)) SWT.error(SWT.ERROR_INVALID_RANGE); + int ascent = Math.max(defaultAscent, this.ascent); + int descent = Math.max(defaultDescent, this.descent); + if (text.length() != 0) { + GC gc = new GC(device); + StyleItem[] lineRuns = runs[lineIndex]; + for (int i = 0; i < lineRuns.length; i++) { + StyleItem run = lineRuns[i]; + if (run.style != null) { + int runAscent = 0; + int runDescent = 0; + if (run.style.metrics != null) { + GlyphMetrics glyphMetrics = run.style.metrics; + runAscent = glyphMetrics.ascent; + runDescent = glyphMetrics.descent; + } else if (run.style.font != null) { + gc.setFont(run.style.font); + FontMetrics metrics = gc.getFontMetrics(); + runAscent = metrics.getAscent(); + runDescent = metrics.getDescent(); + } + ascent = Math.max(ascent, runAscent + run.style.rise); + descent = Math.max(descent, runDescent - run.style.rise); + } + } + gc.dispose(); + } + return FontMetrics.motif_new(ascent, descent, 0, 0, ascent + descent); +} + +/** + * Returns the location for the specified character offset. The + * <code>trailing</code> argument indicates whether the offset + * corresponds to the leading or trailing edge of the cluster. + * + * @param offset the character offset + * @param trailing the trailing flag + * @return the location of the character offset + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getOffset(Point, int[]) + * @see #getOffset(int, int, int[]) + */ +public Point getLocation (int offset, boolean trailing) { + checkLayout(); + computeRuns(); + int length = text.length(); + if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); + int line; + for (line=0; line<runs.length; line++) { + if (lineOffset[line + 1] > offset) break; + } + line = Math.min(line, runs.length - 1); + StyleItem[] lineRuns = runs[line]; + Point result = null; + if (offset == length) { + result = new Point(lineWidth[line], lineY[line]); + } else { + int width = 0; + for (int i=0; i<lineRuns.length; i++) { + StyleItem run = lineRuns[i]; + int end = run.start + run.length; + if (run.start <= offset && offset < end) { + if (run.tab) { + if (trailing || offset == length) width += run.width; + } else { + if (trailing) offset++; + if (run.style != null && run.style.metrics != null) { + GlyphMetrics metrics = run.style.metrics; + width += metrics.width * (offset - run.start); + } else { + char[] chars = new char[offset - run.start]; + text.getChars(run.start, offset, chars, 0); + width += stringWidth(run, chars); + } + } + result = new Point(width, lineY[line]); + break; + } + width += run.width; + } + } + if (result == null) result = new Point(0, 0); + result.x += getLineIndent(line); + return result; +} + +Font getItemFont(StyleItem item) { + if (item.style != null && item.style.font != null) { + return item.style.font; + } + if (this.font != null) { + return this.font; + } + return device.systemFont; +} + +/** + * Returns the next offset for the specified offset and movement + * type. The movement is one of <code>SWT.MOVEMENT_CHAR</code>, + * <code>SWT.MOVEMENT_CLUSTER</code>, <code>SWT.MOVEMENT_WORD</code>, + * <code>SWT.MOVEMENT_WORD_END</code> or <code>SWT.MOVEMENT_WORD_START</code>. + * + * @param offset the start offset + * @param movement the movement type + * @return the next offset + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the offset is out of range</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getPreviousOffset(int, int) + */ +public int getNextOffset (int offset, int movement) { + checkLayout(); + computeRuns(); + int length = text.length(); + if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); + if (offset == length) return length; + if ((movement & (SWT.MOVEMENT_CHAR | SWT.MOVEMENT_CLUSTER)) != 0) return offset + 1; + int lineEnd = 0; + for (int i=1; i<lineOffset.length; i++) { + if (lineOffset[i] > offset) { + lineEnd = Math.max(lineOffset[i - 1], lineOffset[i] - 1); + if (i == runs.length) lineEnd++; + break; + } + } + boolean previousSpaceChar = !Compatibility.isLetterOrDigit(text.charAt(offset)); + offset++; + while (offset < lineEnd) { + boolean spaceChar = !Compatibility.isLetterOrDigit(text.charAt(offset)); + if (movement == SWT.MOVEMENT_WORD || movement == SWT.MOVEMENT_WORD_END) { + if (spaceChar && !previousSpaceChar) break; + } + if (movement == SWT.MOVEMENT_WORD_START) { + if (!spaceChar && previousSpaceChar) break; + } + previousSpaceChar = spaceChar; + offset++; + } + return offset; +} + +/** + * Returns the character offset for the specified point. + * For a typical character, the trailing argument will be filled in to + * indicate whether the point is closer to the leading edge (0) or + * the trailing edge (1). When the point is over a cluster composed + * of multiple characters, the trailing argument will be filled with the + * position of the character in the cluster that is closest to + * the point. + * + * @param point the point + * @param trailing the trailing buffer + * @return the character offset + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the trailing length is less than <code>1</code></li> + * <li>ERROR_NULL_ARGUMENT - if the point is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getLocation(int, boolean) + */ +public int getOffset (Point point, int[] trailing) { + checkLayout(); + if (point == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + return getOffset (point.x, point.y, trailing); +} + +/** + * Returns the character offset for the specified point. + * For a typical character, the trailing argument will be filled in to + * indicate whether the point is closer to the leading edge (0) or + * the trailing edge (1). When the point is over a cluster composed + * of multiple characters, the trailing argument will be filled with the + * position of the character in the cluster that is closest to + * the point. + * + * @param x the x coordinate of the point + * @param y the y coordinate of the point + * @param trailing the trailing buffer + * @return the character offset + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the trailing length is less than <code>1</code></li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getLocation(int, boolean) + */ +public int getOffset (int x, int y, int[] trailing) { + checkLayout(); + computeRuns(); + if (trailing != null && trailing.length < 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + int line; + int lineCount = runs.length; + for (line=0; line<lineCount; line++) { + if (lineY[line + 1] > y) break; + } + line = Math.min(line, runs.length - 1); + x -= getLineIndent(line); + if (x >= lineWidth[line]) x = lineWidth[line] - 1; + if (x < 0) x = 0; + StyleItem[] lineRuns = runs[line]; + int width = 0; + for (int i = 0; i < lineRuns.length; i++) { + StyleItem run = lineRuns[i]; + if (run.lineBreak && !run.softBreak) return run.start; + if (width + run.width > x) { + if (run.style != null && run.style.metrics != null) { + int xRun = x - width; + GlyphMetrics metrics = run.style.metrics; + if (metrics.width > 0) { + if (trailing != null) { + trailing[0] = (xRun % metrics.width < metrics.width / 2) ? 0 : 1; + } + return run.start + xRun / metrics.width; + } + } + if (run.tab) { + if (trailing != null) { + trailing[0] = x < (width + run.width / 2) ? 0 : 1; + } + return run.start; + } + int offset = 0; + char[] buffer = new char[1]; + char[] chars = new char[run.length]; + text.getChars(run.start, run.start + run.length, chars, 0); + for (offset = 0; offset < chars.length; offset++) { + buffer[0] = chars[offset]; + int charWidth = stringWidth(run, buffer); + if (width + charWidth > x) { + if (trailing != null) { + trailing[0] = x < (width + charWidth / 2) ? 0 : 1; + } + break; + } + width += charWidth; + } + return run.start + offset; + } + width += run.width; + } + if (trailing != null) trailing[0] = 0; + return lineOffset[line + 1]; +} + +/** + * Returns the orientation of the receiver. + * + * @return the orientation style + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getOrientation () { + checkLayout(); + return orientation; +} + +/** + * Returns the previous offset for the specified offset and movement + * type. The movement is one of <code>SWT.MOVEMENT_CHAR</code>, + * <code>SWT.MOVEMENT_CLUSTER</code> or <code>SWT.MOVEMENT_WORD</code>, + * <code>SWT.MOVEMENT_WORD_END</code> or <code>SWT.MOVEMENT_WORD_START</code>. + * + * @param offset the start offset + * @param movement the movement type + * @return the previous offset + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the offset is out of range</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getNextOffset(int, int) + */ +public int getPreviousOffset (int offset, int movement) { + checkLayout(); + computeRuns(); + int length = text.length(); + if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); + if (offset == 0) return 0; + if ((movement & (SWT.MOVEMENT_CHAR | SWT.MOVEMENT_CLUSTER)) != 0) return offset - 1; + int lineStart = 0; + for (int i=0; i<lineOffset.length-1; i++) { + int lineEnd = lineOffset[i+1]; + if (i == runs.length - 1) lineEnd++; + if (lineEnd > offset) { + lineStart = lineOffset[i]; + break; + } + } + offset--; + boolean previousSpaceChar = !Compatibility.isLetterOrDigit(text.charAt(offset)); + while (lineStart < offset) { + boolean spaceChar = !Compatibility.isLetterOrDigit(text.charAt(offset - 1)); + if (movement == SWT.MOVEMENT_WORD_END) { + if (!spaceChar && previousSpaceChar) break; + } + if (movement == SWT.MOVEMENT_WORD || movement == SWT.MOVEMENT_WORD_START) { + if (spaceChar && !previousSpaceChar) break; + } + offset--; + previousSpaceChar = spaceChar; + } + return offset; +} + +/** + * Gets the ranges of text that are associated with a <code>TextStyle</code>. + * + * @return the ranges, an array of offsets representing the start and end of each + * text style. + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getStyles() + * + * @since 3.2 + */ +public int[] getRanges () { + checkLayout(); + int[] result = new int[styles.length * 2]; + int count = 0; + for (int i=0; i<styles.length - 1; i++) { + if (styles[i].style != null) { + result[count++] = styles[i].start; + result[count++] = styles[i + 1].start - 1; + } + } + if (count != result.length) { + int[] newResult = new int[count]; + System.arraycopy(result, 0, newResult, 0, count); + result = newResult; + } + return result; +} + +/** + * Returns the text segments offsets of the receiver. + * + * @return the text segments offsets + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int[] getSegments() { + checkLayout(); + return segments; +} + +/** + * Returns the line spacing of the receiver. + * + * @return the line spacing + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getSpacing () { + checkLayout(); + return lineSpacing; +} + +/** + * Gets the style of the receiver at the specified character offset. + * + * @param offset the text offset + * @return the style or <code>null</code> if not set + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the character offset is out of range</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public TextStyle getStyle (int offset) { + checkLayout(); + int length = text.length(); + if (!(0 <= offset && offset < length)) SWT.error(SWT.ERROR_INVALID_RANGE); + for (int i=1; i<styles.length; i++) { + StyleItem item = styles[i]; + if (item.start > offset) { + return styles[i - 1].style; + } + } + return null; +} + +/** + * Gets all styles of the receiver. + * + * @return the styles + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #getRanges() + * + * @since 3.2 + */ +public TextStyle[] getStyles () { + checkLayout(); + TextStyle[] result = new TextStyle[styles.length]; + int count = 0; + for (int i=0; i<styles.length; i++) { + if (styles[i].style != null) { + result[count++] = styles[i].style; + } + } + if (count != result.length) { + TextStyle[] newResult = new TextStyle[count]; + System.arraycopy(result, 0, newResult, 0, count); + result = newResult; + } + return result; +} + +/** + * Returns the tab list of the receiver. + * + * @return the tab list + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int[] getTabs () { + checkLayout(); + return tabs; +} + +/** + * Gets the receiver's text, which will be an empty + * string if it has never been set. + * + * @return the receiver's text + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public String getText () { + checkLayout(); + return text; +} + +/** + * Returns the width of the receiver. + * + * @return the width + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public int getWidth () { + checkLayout(); + return wrapWidth; +} + +/** + * Returns <code>true</code> if the text layout has been disposed, + * and <code>false</code> otherwise. + * <p> + * This method gets the dispose state for the text layout. + * When a text layout has been disposed, it is an error to + * invoke any other method using the text layout. + * </p> + * + * @return <code>true</code> when the text layout is disposed and <code>false</code> otherwise + */ +public boolean isDisposed () { + return device == null; +} + +/* + * Itemize the receiver text, create run for + */ +StyleItem[] itemize () { + int length = text.length(); + if (length == 0) { + return new StyleItem[]{new StyleItem(), new StyleItem()}; + } + int runCount = 0, start = 0; + StyleItem[] runs = new StyleItem[length]; + char[] chars = text.toCharArray(); + for (int i = 0; i<length; i++) { + char ch = chars[i]; + if (ch == '\t' || ch == '\r' || ch == '\n') { + if (i != start) { + StyleItem item = new StyleItem(); + item.start = start; + runs[runCount++] = item; + } + StyleItem item = new StyleItem(); + item.start = i; + runs[runCount++] = item; + start = i + 1; + } + } + char lastChar = chars[length - 1]; + if (!(lastChar == '\t' || lastChar == '\r' || lastChar == '\n')) { + StyleItem item = new StyleItem(); + item.start = start; + runs[runCount++] = item; + } + if (runCount != length) { + StyleItem[] newRuns = new StyleItem[runCount]; + System.arraycopy(runs, 0, newRuns, 0, runCount); + runs = newRuns; + } + runs = merge(runs, runCount); + return runs; +} + +/* + * Merge styles ranges and script items + */ +StyleItem[] merge (StyleItem[] items, int itemCount) { + int length = text.length(); + int count = 0, start = 0, end = length, itemIndex = 0, styleIndex = 0; + StyleItem[] runs = new StyleItem[itemCount + styles.length]; + while (start < end) { + StyleItem item = new StyleItem(); + item.start = start; + item.style = styles[styleIndex].style; + runs[count++] = item; + int itemLimit = itemIndex + 1 < items.length ? items[itemIndex + 1].start : length; + int styleLimit = styleIndex + 1 < styles.length ? styles[styleIndex + 1].start : length; + if (styleLimit <= itemLimit) { + styleIndex++; + start = styleLimit; + } + if (itemLimit <= styleLimit) { + itemIndex++; + start = itemLimit; + } + item.length = start - item.start; + } + StyleItem item = new StyleItem(); + item.start = end; + runs[count++] = item; + if (runs.length != count) { + StyleItem[] result = new StyleItem[count]; + System.arraycopy(runs, 0, result, 0, count); + return result; + } + return runs; +} + +void place (StyleItem run) { + if (run.length == 0) return; + if (run.style != null && run.style.metrics != null) { + GlyphMetrics glyphMetrics = run.style.metrics; + run.width = glyphMetrics.width * run.length; + run.baseline = glyphMetrics.ascent; + run.height = glyphMetrics.ascent + glyphMetrics.descent; + } else { + char[] chars = new char[run.length]; + text.getChars(run.start, run.start + run.length, chars, 0); + Font font = getItemFont(run); + int fontList = font.handle; + byte[] buffer = Converter.wcsToMbcs(font.codePage, chars, true); + short[] width = new short[1], height = new short[1]; + int xmString = OS.XmStringCreateLocalized(buffer); + OS.XmStringExtent(fontList, xmString, width, height); + run.width = width[0] & 0xFFFF; + run.height = height[0] & 0xFFFF; + run.baseline = OS.XmStringBaseline(fontList, xmString); + OS.XmStringFree(xmString); + } +} + +/** + * Sets the text alignment for the receiver. The alignment controls + * how a line of text is positioned horizontally. The argument should + * be one of <code>SWT.LEFT</code>, <code>SWT.RIGHT</code> or <code>SWT.CENTER</code>. + * <p> + * The default alignment is <code>SWT.LEFT</code>. Note that the receiver's + * width must be set in order to use <code>SWT.RIGHT</code> or <code>SWT.CENTER</code> + * alignment. + * </p> + * + * @param alignment the new alignment + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #setWidth(int) + */ +public void setAlignment (int alignment) { + checkLayout(); + int mask = SWT.LEFT | SWT.CENTER | SWT.RIGHT; + alignment &= mask; + if (alignment == 0) return; + if ((alignment & SWT.LEFT) != 0) alignment = SWT.LEFT; + if ((alignment & SWT.RIGHT) != 0) alignment = SWT.RIGHT; + freeRuns(); + this.alignment = alignment; +} + +/** + * Sets the ascent of the receiver. The ascent is distance in pixels + * from the baseline to the top of the line and it is applied to all + * lines. The default value is <code>-1</code> which means that the + * ascent is calculated from the line fonts. + * + * @param ascent the new ascent + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the ascent is less than <code>-1</code></li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #setDescent(int) + * @see #getLineMetrics(int) + */ +public void setAscent (int ascent) { + checkLayout(); + if (ascent < -1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (this.ascent == ascent) return; + freeRuns(); + this.ascent = ascent; +} + +/** + * Sets the descent of the receiver. The descent is distance in pixels + * from the baseline to the bottom of the line and it is applied to all + * lines. The default value is <code>-1</code> which means that the + * descent is calculated from the line fonts. + * + * @param descent the new descent + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the descent is less than <code>-1</code></li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #setAscent(int) + * @see #getLineMetrics(int) + */ +public void setDescent (int descent) { + checkLayout(); + if (descent < -1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (this.descent == descent) return; + freeRuns(); + this.descent = descent; +} + +/** + * Sets the default font which will be used by the receiver + * to draw and measure text. If the + * argument is null, then a default font appropriate + * for the platform will be used instead. Note that a text + * style can override the default font. + * + * @param font the new font for the receiver, or null to indicate a default font + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the font has been disposed</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setFont (Font font) { + checkLayout (); + if (font != null && font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + Font oldFont = this.font; + if (oldFont == font) return; + this.font = font; + if (oldFont != null && oldFont.equals(font)) return; + freeRuns(); + XFontStruct fontStruct = getFontHeigth(font != null ? font : device.systemFont); + defaultAscent = fontStruct.ascent; + defaultDescent = fontStruct.descent; +} + +/** + * Sets the indent of the receiver. This indent it applied of the first line of + * each paragraph. + * + * @param indent new indent + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.2 + */ +public void setIndent (int indent) { + checkLayout(); + if (indent < 0) return; + if (this.indent == indent) return; + freeRuns(); + this.indent = indent; +} + +/** + * Sets the justification of the receiver. Note that the receiver's + * width must be set in order to use justification. + * + * @param justify new justify + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @since 3.2 + */ +public void setJustify (boolean justify) { + checkLayout(); + if (this.justify == justify) return; + freeRuns(); + this.justify = justify; +} + +/** + * Sets the orientation of the receiver, which must be one + * of <code>SWT.LEFT_TO_RIGHT</code> or <code>SWT.RIGHT_TO_LEFT</code>. + * + * @param orientation new orientation style + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setOrientation (int orientation) { + checkLayout(); + int mask = SWT.RIGHT_TO_LEFT | SWT.LEFT_TO_RIGHT; + orientation &= mask; + if (orientation == 0) return; + if ((orientation & SWT.LEFT_TO_RIGHT) != 0) orientation = SWT.LEFT_TO_RIGHT; + this.orientation = orientation; +} + +/** + * Sets the line spacing of the receiver. The line spacing + * is the space left between lines. + * + * @param spacing the new line spacing + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the spacing is negative</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setSpacing (int spacing) { + checkLayout(); + if (spacing < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (this.lineSpacing == spacing) return; + freeRuns(); + this.lineSpacing = spacing; +} + +/** + * Sets the offsets of the receiver's text segments. Text segments are used to + * override the default behaviour of the bidirectional algorithm. + * Bidirectional reordering can happen within a text segment but not + * between two adjacent segments. + * <p> + * Each text segment is determined by two consecutive offsets in the + * <code>segments</code> arrays. The first element of the array should + * always be zero and the last one should always be equals to length of + * the text. + * </p> + * + * @param segments the text segments offset + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setSegments(int[] segments) { + checkLayout(); + if (this.segments == null && segments == null) return; + if (this.segments != null && segments !=null) { + if (this.segments.length == segments.length) { + int i; + for (i = 0; i <segments.length; i++) { + if (this.segments[i] != segments[i]) break; + } + if (i == segments.length) return; + } + } + freeRuns(); + this.segments = segments; +} + +/** + * Sets the style of the receiver for the specified range. Styles previously + * set for that range will be overwritten. The start and end offsets are + * inclusive and will be clamped if out of range. + * + * @param style the style + * @param start the start offset + * @param end the end offset + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setStyle (TextStyle style, int start, int end) { + checkLayout(); + int length = text.length(); + if (length == 0) return; + if (start > end) return; + start = Math.min(Math.max(0, start), length - 1); + end = Math.min(Math.max(0, end), length - 1); + int low = -1; + int high = styles.length; + while (high - low > 1) { + int index = (high + low) / 2; + if (styles[index + 1].start > start) { + high = index; + } else { + low = index; + } + } + if (0 <= high && high < styles.length) { + StyleItem item = styles[high]; + if (item.start == start && styles[high + 1].start - 1 == end) { + if (style == null) { + if (item.style == null) return; + } else { + if (style.equals(item.style)) return; + } + } + } + freeRuns(); + int modifyStart = high; + int modifyEnd = modifyStart; + while (modifyEnd < styles.length) { + if (styles[modifyEnd + 1].start > end) break; + modifyEnd++; + } + if (modifyStart == modifyEnd) { + int styleStart = styles[modifyStart].start; + int styleEnd = styles[modifyEnd + 1].start - 1; + if (styleStart == start && styleEnd == end) { + styles[modifyStart].style = style; + return; + } + if (styleStart != start && styleEnd != end) { + StyleItem[] newStyles = new StyleItem[styles.length + 2]; + System.arraycopy(styles, 0, newStyles, 0, modifyStart + 1); + StyleItem item = new StyleItem(); + item.start = start; + item.style = style; + newStyles[modifyStart + 1] = item; + item = new StyleItem(); + item.start = end + 1; + item.style = styles[modifyStart].style; + newStyles[modifyStart + 2] = item; + System.arraycopy(styles, modifyEnd + 1, newStyles, modifyEnd + 3, styles.length - modifyEnd - 1); + styles = newStyles; + return; + } + } + if (start == styles[modifyStart].start) modifyStart--; + if (end == styles[modifyEnd + 1].start - 1) modifyEnd++; + int newLength = styles.length + 1 - (modifyEnd - modifyStart - 1); + StyleItem[] newStyles = new StyleItem[newLength]; + System.arraycopy(styles, 0, newStyles, 0, modifyStart + 1); + StyleItem item = new StyleItem(); + item.start = start; + item.style = style; + newStyles[modifyStart + 1] = item; + styles[modifyEnd].start = end + 1; + System.arraycopy(styles, modifyEnd, newStyles, modifyStart + 2, styles.length - modifyEnd); + styles = newStyles; +} + +/** + * Sets the receiver's tab list. Each value in the tab list specifies + * the space in pixels from the origin of the text layout to the respective + * tab stop. The last tab stop width is repeated continuously. + * + * @param tabs the new tab list + * + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setTabs (int[] tabs) { + checkLayout(); + if (this.tabs == null && tabs == null) return; + if (this.tabs != null && tabs !=null) { + if (this.tabs.length == tabs.length) { + int i; + for (i = 0; i <tabs.length; i++) { + if (this.tabs[i] != tabs[i]) break; + } + if (i == tabs.length) return; + } + } + freeRuns(); + this.tabs = tabs; +} + +/** + * Sets the receiver's text. + *<p> + * Note: Setting the text also clears all the styles. This method + * returns without doing anything if the new text is the same as + * the current text. + * </p> + * + * @param text the new text + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_NULL_ARGUMENT - if the text is null</li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + */ +public void setText (String text) { + checkLayout(); + if (text == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (text.equals(this.text)) return; + freeRuns(); + this.text = text; + styles = new StyleItem[2]; + styles[0] = new StyleItem(); + styles[1] = new StyleItem(); + styles[1].start = text.length(); +} + +/** + * Sets the line width of the receiver, which determines how + * text should be wrapped and aligned. The default value is + * <code>-1</code> which means wrapping is disabled. + * + * @param width the new width + * + * @exception IllegalArgumentException <ul> + * <li>ERROR_INVALID_ARGUMENT - if the width is <code>0</code> or less than <code>-1</code></li> + * </ul> + * @exception SWTException <ul> + * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> + * </ul> + * + * @see #setAlignment(int) + */ +public void setWidth (int width) { + checkLayout(); + if (width < -1 || width == 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (this.wrapWidth == width) return; + freeRuns(); + this.wrapWidth = width; +} + +/** + * Returns a string containing a concise, human-readable + * description of the receiver. + * + * @return a string representation of the receiver + */ +public String toString () { + if (isDisposed()) return "TextLayout {*DISPOSED*}"; + return "TextLayout {}"; +} +} |